<?php
class Google_model extends CI_Model{
	
 	function google_model(){
  		//parent::CI_model();
			
 	}

	/**
	++++++++++++++++++++++++++++++++++++++++++++
	//GOOGLE API 
	//Functions
			$this->load->library('ga_api');

		 Set new profile id if not the default id within your config document
		$this->ga = $this->ga_api->login()->init(array('profile_id' => $this->session->userdata('GA_profile')));
		
		 Query Google metrics and dimensions
		 Documentation: http://code.google.com/apis/analytics/docs/gdata/dimsmets/dimsmets.html)

		 Also please note, if you using default values you still need to init()
		$data = $this->ga_api->login()
			->dimension('keyword')
			->metric('organicSearches')
			->limit(30)
			->get_object();
   
   
		 Please note you can also query against your account and find all the profiles associated with it by
		 grab all profiles within your account
		$data['accounts'] = $this->ga_api->login()->get_accounts();
	++++++++++++++++++++++++++++++++++++++++++++	
	*/
	//30 Day Overview Summary
	public function load_overview()
	{

		$this->load->library('ga_api');

		// Set new profile id if not the default id within your config document
		$this->ga = $this->ga_api->login()->init(array('profile_id' => $this->session->userdata('GA_profile')));
		
		// Query Google metrics and dimensions
		// Documentation: http://code.google.com/apis/analytics/docs/gdata/dimsmets/dimsmets.html)
		
		
		// Also please note, if you using default values you still need to init()
		$data = $this->ga_api->login()
			->dimension('visitCount, visitLength, pageDepth')
			->metric('visitors, percentNewVisits, newVisits,  avgTimeOnSite, entranceBounceRate, uniquePageviews, avgPageLoadTime, pageviewsPerVisit')
			->limit(30)
			->get_object();
		
		//LOAD CIRCLE STATS
		echo '	
				<div class="circleStats">
                    
					<div class="span2" onTablet="span4" onDesktop="span2">
                    	<div class="circleStatsItem red">
							<i class="fa-icon-group"></i>
							
                        	<input type="text" value="'.$data['summary']->metrics->visitors.'" class="orangeCircle" />
                    	</div>
						<div class="box-small-title">Visitors this month</div>
					</div>
					<div class="span2" onTablet="span4" onDesktop="span2">
                    	<div class="circleStatsItem blue">
                        	<i class="fa-icon-user"></i>
                        	<input type="text" value="'.$data['summary']->metrics->newVisits.'" class="blueCircle" />
                    	</div>
						<div class="box-small-title">New Visitors</div>
					</div>
					<div class="span2" onTablet="span4" onDesktop="span2">
						<div class="circleStatsItem yellow">
                        	<i class="fa-icon-thumbs-down"></i>
							
							<span class="percent">%</span>
                        	<input type="text" value="'.round($data['summary']->metrics->entranceBounceRate,2).'" class="yellowCircle" />
                    	</div>
						<div class="box-small-title">Bounce Rate</div>
					</div>
					<div class="noMargin span2" onTablet="span4" onDesktop="span2">
						<div class="circleStatsItem pink">
                        	<i class="fa-icon-user-md"></i>
							<span class="percent">%</span>
                        	<input type="text" value="'.round($data['summary']->metrics->percentNewVisits,2).'" class="pinkCircle" />
                    	</div>
						<div class="box-small-title">% New Visits</div>
					</div>
					<div class="span2" onTablet="span4" onDesktop="span2">
                    	<div class="circleStatsItem green">
                        	<i class="fa-icon-dashboard"></i>

							<span class="percent">s</span>
                        	<input type="text" value="'.round($data['summary']->metrics->avgPageLoadTime,2).'" class="greenCircle" />
                    	</div>
						<div class="box-small-title">Average Page Load Time</div>
					</div>
					<div class="span2" onTablet="span4" onDesktop="span2">
						<div class="circleStatsItem lightorange">
                        	<i class="fa-icon-bar-chart"></i>
	
							
                        	<input type="text" value="'.round($data['summary']->metrics->pageviewsPerVisit,2).'" class="lightOrangeCircle" />
                    	</div>
						<div class="box-small-title">Pageviews/Visit</div>
					</div>

                </div>
			
			
			<script type="text/javascript">
			$(document).ready(function(){
	
					var divElement = $("div"); //log all div elements
					
					$(".greenCircle").knob({
						"min":0,
						"max":15,
						"readOnly": true,
						"width": 120,
						"height": 120,
						"fgColor": "#b9e672",
						"dynamicDraw": true,
						"thickness": 0.2,
						"tickColorizeValues": true,
						"skin":"tron"
					})
				
					$(".orangeCircle").knob({
						"min":0,
						"max":7000,
						"readOnly": true,
						"width": 120,
						"height": 120,
						"fgColor": "#FA5833",
						"dynamicDraw": true,
						"thickness": 0.1,
						"tickColorizeValues": true,
						"skin":"tron"
					})
				
					$(".lightOrangeCircle").knob({
						"min":0,
						"max":10,
						"readOnly": true,
						"width": 120,
						"height": 120,
						"fgColor": "#f4a70c",
						"dynamicDraw": true,
						"thickness": 0.2,
						"tickColorizeValues": true,
						"skin":"tron"
					})
				
					$(".blueCircle").knob({
						"min":0,
						"max":1500,
						"readOnly": true,
						"width": 120,
						"height": 120,
						"fgColor": "#2FABE9",
						"dynamicDraw": true,
						"thickness": 0.2,
						"tickColorizeValues": true,
						"skin":"tron"
					})
				
					$(".yellowCircle").knob({
						"min":0,
						"max":100,
						"readOnly": true,
						"width": 120,
						"height": 120,
						"fgColor": "#e7e572",
						"dynamicDraw": true,
						"thickness": 0.2,
						"tickColorizeValues": true,
						"skin":"tron"
					})
				
					$(".pinkCircle").knob({
						"min":0,
						"max":100,
						"readOnly": true,
						"width": 120,
						"height": 120,
						"fgColor": "#e42b75",
						"dynamicDraw": true,
						"thickness": 0.2,
						"tickColorizeValues": true,
						"skin":"tron"
					})
					
					
				});                

			
			</script>';
			//Home Stats
			echo '<hr>
			
			<div class="row-fluid">
			
			<div class="box span12 noMargin" onTablet="span12" onDesktop="span12">
					<div class="box-header">
						<h2><i class="icon-list"></i><span class="break"></span>Monthly Traffic Overview</h2>
						<div class="box-icon">
							<a href="#" class="btn-minimize"><i class="icon-chevron-up"></i></a>
							<a href="#" class="btn-close"><i class="icon-remove"></i></a>
						</div>
					</div>
					<div class="box-content">
					<div class="sparkLineStats">
	                        <ul class="unstyled thumbnails">
	                            <li>
									Visits: 
									<span class="number">'.$data['summary']->metrics->visitors.'</span>
								</li>
	                            <li>
	                                
	                                New Visitors: 
	                                <span class="number">'.$data['summary']->metrics->newVisits.'</span>
	                            </li>
	                            <li>
	                                Pageviews: 
	                                <span class="number">'.$data['summary']->metrics->uniquePageviews.'</span>
	                            </li>
	                            <li>
	                                Pages / Visit: 
	                                <span class="number">'.round($data['summary']->metrics->pageviewsPerVisit,2).'</span>
	                            </li>
	                            <li>
	                                Avg. Visit Duration: 
	                                <span class="number">'.round($data['summary']->metrics->avgTimeOnSite,2).' s</span>
	                            </li>
	                            <li>
	                                Bounce Rate: <span class="number">'.round($data['summary']->metrics->entranceBounceRate,2).' %</span>
	                            </li>
	                            <li>
	                                % New Visits: 
	                                <span class="number">'.round($data['summary']->metrics->percentNewVisits,2).' %</span>
	                            </li>
	                            <li>
	                                Average page load time (s): 
	                                <span class="number">'.round($data['summary']->metrics->avgPageLoadTime,2).' s</span>
	                            </li>

	                        </ul>
	
	                    </div><!-- End .sparkStats -->
						</div>
				</div><!--/span-->
				</div>';		
			
			

	}
	
public function traffic_graph_og(){
		
		$this->load->library('ga_api');

		$data = $this->ga_api->login()
			->dimension('date')
			->metric('visitors, visits')
			->when('1 month ago', 'yesterday')
			->get_array();
   
   		$x = 30;
		$c = 30;

		$tooltip = "id='tooltip'";
		//LOAD MAIN TRAFFIC GRAPH
		echo '<div class="box span8" onTablet="span12" onDesktop="span8">
						<div class="box-header">
							<h2><i class="icon-signal"></i><span class="break"></span>Site Statistics</h2>
							<div class="box-icon">
								<a href="#" class="btn-setting"><i class="icon-wrench"></i></a>
								<a href="#" class="btn-minimize"><i class="icon-chevron-up"></i></a>
								<a href="#" class="btn-close"><i class="icon-remove"></i></a>
							</div>
						</div>
						<div class="box-content">
							<div id="stats-chart"  class="center" style="height:300px" ></div>
						</div>
			</div>
			<script type="text/javascript">
			/* ---------- Chart with points ---------- */
			$(document).ready(function(){
				
			
				var pageviews = [';
					
				foreach($data as $key => $value){
				   if($key != 'summary'){	
						$comma = ',';
								 
						if($c == 0){
							$comma = '';
						 }
							   
						 $final = $value['visits'];
						
						 echo '['.$c.', ' .$final. ']'.$comma;
						 $c = $c - 1;
				   }
				}
				  
		   
				
						
				echo '];
				
				var visitors = [';
				
				foreach($data as $key => $value){
				   if($key != 'summary'){	
						$comma = ',';
								 
						if($x == 0){
							$comma = '';
						 }
							   
						 $final = $value['visitors'];
						
						 echo '['.$x.', ' .$final. ']'.$comma;
						 $x = $x - 1;
				   }
				}
						
				echo '];
				
				var plot = $.plot($("#stats-chart"),
					   [ { data: pageviews, label: "pageviews"}, { data: visitors, label: "visitors" } ], {
						   series: {
							   lines: { show: true,
										lineWidth: 3,
										fill: true, fillColor: { colors: [ { opacity: 0.08 }, { opacity: 0.01 } ] }
									 },
							   points: { show: true },
							   shadowSize: 2
						   },
						   grid: { hoverable: true, 
								   clickable: true, 
								   tickColor: "#eee",
								   borderWidth: 0,
								 },
						   colors: ["#FA5833", "#2FABE9"],
							xaxis: {ticks:11, tickDecimals: 0},
							yaxis: {ticks:11, tickDecimals: 0},
						 });
				
				function showTooltip(x, y, contents) {
					$("<div '.$tooltip.'>" + contents + "</div>").css( {
						position: "absolute",
						display: "none",
						top: y + 5,
						left: x + 5,
						border: "1px solid #fdd",
						padding: "2px",
						"background-color": "#dfeffc",
						opacity: 0.80
					}).appendTo("body").fadeIn(200);
				}
		
				var previousPoint = null;
				$("#stats-chart").bind("plothover", function (event, pos, item) {
					$("#x").text(pos.x.toFixed(2));
					$("#y").text(pos.y.toFixed(2));
		
						if (item) {
							if (previousPoint != item.dataIndex) {
								previousPoint = item.dataIndex;
		
								$("#tooltip").remove();
								var x = item.datapoint[0].toFixed(2),
									y = item.datapoint[1].toFixed(2);
		
								showTooltip(item.pageX, item.pageY,
											item.series.label + " of " + x + " = " + y);
							}
						}
						else {
							$("#tooltip").remove();
							previousPoint = null;
						}
				});
				
		
		
				$("#sincos").bind("plotclick", function (event, pos, item) {
					if (item) {
						$("#clickdata").text("You clicked point " + item.dataIndex + " in " + item.series.label + ".");
						plot.highlight(item.series, item.datapoint);
					}
				});
			});
			
			</script>
			
			';
				
				
		
	}
	
	public function traffic_graph(){
			
			
		$this->load->library('ga_api');

		$visits = $this->ga_api->login()
			->dimension('date')
			->metric('visitors, visits')
			->when('1 month ago', 'yesterday')
			->sort_by('date')
			->get_array();
   
   		$x = 30;
		$c = 30;
		
		//var_dump($visits);
		
		if(count($visits)) {
				
			
				foreach($visits as $day=>$visit) { 
					//strip the summary
					if($day == 'summary'){
					
					}else{
						$flot_datas_visits[] = '[ gd('.date('Y',strtotime($day)).','.date('n',strtotime($day)).','.date('j',strtotime($day)).'),'.$visit['visitors'].']';
						$flot_datas_views[] = '[ gd('.date('Y',strtotime($day)).','.date('n',strtotime($day)).','.date('j',strtotime($day)).'),'.$visit['visits'].']';
					}
					
					//$flot_datas_views[] = '['.$day.','.$views[$day].']';
				}
				$flot_data_visits = '['.implode(',',$flot_datas_visits).']';
				$flot_data_views = '['.implode(',',$flot_datas_views).']';
			
		}

		$tooltip = "id='tooltip'";
		//LOAD MAIN TRAFFIC GRAPH
		echo '<div class="box span8" onTablet="span12" onDesktop="span8">
						<div class="box-header">
							<h2><i class="icon-signal"></i><span class="break"></span>Site Statistics</h2>
							<div class="box-icon">
								<a href="#" class="btn-setting"><i class="icon-wrench"></i></a>
								<a href="#" class="btn-minimize"><i class="icon-chevron-up"></i></a>
								<a href="#" class="btn-close"><i class="icon-remove"></i></a>
							</div>
						</div>
						<div class="box-content">
							<div id="stats-chart"  class="center" style="height:300px" ></div>
						</div>
			</div>
			<script type="text/javascript">
			/* ---------- Chart with points ---------- */
			$(document).ready(function(){
				
				
				var plot = $.plot($("#stats-chart"),
					   [ { data: '.$flot_data_views.', label: "pageviews"}, { data:  '.$flot_data_visits.', label: "visitors" } ], {
						  
						   series: {
							   lines: { show: true,
										lineWidth: 3,
										fill: true, fillColor: { colors: [ { opacity: 0.08 }, { opacity: 0.01 } ] }
									 },
							   points: { show: true },
							   shadowSize: 2
						   },
						   grid: { hoverable: true, 
								   clickable: true, 
								   tickColor: "#eee",
								   borderWidth: 0,
								 },
						   colors: ["#FA5833", "#2FABE9"],
							xaxis: { mode: "time",minTickSize: [1, "day"]
							},
							yaxis: {ticks:11, tickDecimals: 0},
						 });
								
				function gd(year, month, day) {
					return new Date(year, month - 1, day).getTime();
				}
				
				function showTooltip(x, y, contents) {
					$("<div '.$tooltip.'>" + contents + "</div>").css( {
						position: "absolute",
						display: "none",
						top: y + 5,
						left: x + 5,
						border: "1px solid #fdd",
						padding: "2px",
						"background-color": "#dfeffc",
						opacity: 0.80
					}).appendTo("body").fadeIn(200);
				}
		
				var previousPoint = null;
				$("#stats-chart").bind("plothover", function (event, pos, item) {
					$("#x").text(pos.x.toFixed(2));
					$("#y").text(pos.y.toFixed(2));
		
						if (item) {
							if (previousPoint != item.dataIndex) {
								previousPoint = item.dataIndex;
		
								$("#tooltip").remove();
								var x = item.datapoint[0].toFixed(2),
									y = item.datapoint[1].toFixed(2);
		
								showTooltip(item.pageX, item.pageY,
											item.series.label + " of " + x + " = " + y);
							}
						}
						else {
							$("#tooltip").remove();
							previousPoint = null;
						}
				});
				
		
		
				$("#sincos").bind("plotclick", function (event, pos, item) {
					if (item) {
						$("#clickdata").text("You clicked point " + item.dataIndex + " in " + item.series.label + ".");
						plot.highlight(item.series, item.datapoint);
					}
				});
			});
			
			</script>
			
			';
				
			
			
	}	
	
	
	public function traffic_graph3_OG(){
		
		$this->load->library('ga_api');

		// Set new profile id if not the default id within your config document
		$this->ga = $this->ga_api->login()->init(array('profile_id' => $this->session->userdata('GA_profile')));
		$data = $this->ga_api->login()
			->dimension('visitCount, pageDepth')
			->metric('visitors, pageviews')
			->limit(30)
			->when('1 month ago', 'yesterday')
			->get_array();
   
   		$x = 0;
		$c = 0;
		
		$data2 = $this->ga_api->login()
			->dimension('date')
			->metric('visitors, visits')
			->when('1 month ago', 'yesterday')
			->get_array();
		
		
		$tooltip = "id='tooltip'";
		//LOAD MAIN TRAFFIC GRAPH
		echo '<div class="box span8" onTablet="span12" onDesktop="span8">
						<div class="box-header">
							<h2><i class="icon-signal"></i><span class="break"></span>Site Statistics</h2>
							<div class="box-icon">
								<a href="#" class="btn-setting"><i class="icon-wrench"></i></a>
								<a href="#" class="btn-minimize"><i class="icon-chevron-up"></i></a>
								<a href="#" class="btn-close"><i class="icon-remove"></i></a>
							</div>
						</div>
						<div class="box-content">
							<div id="stats-chart"  class="center" style="height:300px" ></div>
						</div>
			</div>
			<script type="text/javascript">
			/* ---------- Chart with points ---------- */
			$(document).ready(function(){
				
			
				var pageviews = [';
				
				foreach($data as $key => $value){
   		   			
				   if($key != 'summary'){
						foreach($value as $key2 => $value2){
				   			 $comma = ',';
							 
							 if($c == 29){
								 $comma = '';
							 }
							 
							 $final = $value2['pageviews'];
							 if($value2['pageviews'] > 100){
								 $final = $value2['pageviews'] = '99';
							 }
							 echo '['.$c.', ' .$final. ']'.$comma;
							$c ++;
						}
				   }
		   
				}
						
				echo '];
				
				var visitors = [';
				
				foreach($data2 as $keyv => $valuev){
				   if($keyv != 'summary'){	
						$comma = ',';
								 
						if($c == 29){
							$comma = '';
						 }
							   
						 $finalv = $valuev['visitors'];
						
						 echo '['.$c.', ' .$finalv. ']'.$comma;
						 $c ++;
				   }
				}
						
				echo '];
				
				var plot = $.plot($("#stats-chart"),
					   [ { data: pageviews, label: "pageviews"}, { data: visitors, label: "visitors" } ], {
						   series: {
							   lines: { show: true,
										lineWidth: 3,
										fill: true, fillColor: { colors: [ { opacity: 0.08 }, { opacity: 0.01 } ] }
									 },
							   points: { show: true },
							   shadowSize: 2
						   },
						   grid: { hoverable: true, 
								   clickable: true, 
								   tickColor: "#eee",
								   borderWidth: 0,
								 },
						   colors: ["#FA5833", "#2FABE9"],
							xaxis: {ticks:11, tickDecimals: 0},
							yaxis: {ticks:11, tickDecimals: 0},
						 });
				
				function showTooltip(x, y, contents) {
					$("<div '.$tooltip.'>" + contents + "</div>").css( {
						position: "absolute",
						display: "none",
						top: y + 5,
						left: x + 5,
						border: "1px solid #fdd",
						padding: "2px",
						"background-color": "#dfeffc",
						opacity: 0.80
					}).appendTo("body").fadeIn(200);
				}
		
				var previousPoint = null;
				$("#stats-chart").bind("plothover", function (event, pos, item) {
					$("#x").text(pos.x.toFixed(2));
					$("#y").text(pos.y.toFixed(2));
		
						if (item) {
							if (previousPoint != item.dataIndex) {
								previousPoint = item.dataIndex;
		
								$("#tooltip").remove();
								var x = item.datapoint[0].toFixed(2),
									y = item.datapoint[1].toFixed(2);
		
								showTooltip(item.pageX, item.pageY,
											item.series.label + " of " + x + " = " + y);
							}
						}
						else {
							$("#tooltip").remove();
							previousPoint = null;
						}
				});
				
		
		
				$("#sincos").bind("plotclick", function (event, pos, item) {
					if (item) {
						$("#clickdata").text("You clicked point " + item.dataIndex + " in " + item.series.label + ".");
						plot.highlight(item.series, item.datapoint);
					}
				});
			});
			
			</script>
			
			';
				
				
		
	}
	//30 Organic Searches per day
	public function organic_searches()
	{

		$this->load->library('ga_api');

		// Set new profile id if not the default id within your config document
		$this->ga = $this->ga_api->login()->init(array('profile_id' => $this->session->userdata('GA_profile')));
		
		$data = $this->ga_api->login()
			->dimension('keyword')
			->metric('organicSearches')
			->limit(30)
			->get_object();
   
		$array =  (array) $data;
		$x = 0;
		foreach($array as $row){
			
			if(isset($row->organicSearches)){
				echo $x .' ' . $row->organicSearches .'<br />';
			}

			$x ++;
		}
		echo 'Total Organic Searches: '.$array['summary']->metrics->organicSearches;

	}
	
	
	//30 day Organic Keywords
	public function organic_keywords()
	{

		$this->load->library('ga_api');

		// Set new profile id if not the default id within your config document
		$this->ga = $this->ga_api->login()->init(array('profile_id' => $this->session->userdata('GA_profile')));
		
		// Also please note, if you using default values you still need to init()
		$data = $this->ga_api->login()
			->dimension('keyword')
			->metric('organicSearches')
			->limit(10)
			->sort_by('organicSearches')
			->when('1 month ago', 'yesterday')
			->get_array();
   
   		echo '<div class="box span4 noMargin" onTablet="span12" onDesktop="span4">
					<div class="box-header">
						<h2><i class="icon-list"></i><span class="break"></span>Search Terms</h2>
						<div class="box-icon">
							<a href="#" class="btn-minimize"><i class="icon-chevron-up"></i></a>
							<a href="#" class="btn-close"><i class="icon-remove"></i></a>
						</div>
					</div>
					<div class="box-content">
					     <ul class="dashboard-list">';
		   				
						foreach($data as $key => $value){
						   
						   if($key != 'summary'){
							   
							 echo '<li>
										<a href="#">
										<i class="fa-icon-bookmark-empty blue"></i>                               
										<span class="blue">'.$value['organicSearches'].'</span>'
										.$key.'                                     
										</a>
								   </li>';
							 
						   }
						   
						}
		
			echo '</ul>
			   </div>
			</div><!--/span-->';

	}



}
?>