var gmarkers = [];
var b = 0;
var htmls = [];
var tabsx = []
var omg_url = '/';

var this_id = 0;

function omg_map()
{
	this.map = null;
	this.initload = true;
	this.min_zoom = 11;
	this.max_zoom = 16;
	this.default_zoom = 13;
	
	this.radius = new Array;
	this.radius[9] = 5;
	this.radius[10] = 4;
	this.radius[11] = 3;
	this.radius[12] = 2.5;
	this.radius[13] = 2;
	this.radius[14] = 1.5;
	this.radius[15] = 1;
	this.radius[16] = 0.8;
	this.radius[17] = 0.6;
	this.radius[18] = 0.4;
	this.radius[19] = 0.3;
	this.radius[20] = 0.3;
	this.mapUrl = 'http://www.ohmygas.com/';

	
	
	
	this.initmap = function(){
		if (GBrowserIsCompatible()) {
			
		      this.loadMap(); 
		      
		  	}
		  }
	
	this.loadMap = function(){
		
	 	this.map = new GMap2(document.getElementById("map"));
	 	this.map.addControl(new GSmallZoomControl());
	 	this.map.setCenter(new GLatLng(lat,lon),this.default_zoom);
		var pos = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(01,01));
		pos.apply(document.getElementById("on_map_search_box"));
		this.map.getContainer().appendChild(document.getElementById("on_map_search_box"));
		this.getStationsInRange();
		
		// ==== Create a KML Overlay ====
		if(kml_location){
			var kml_url = "http://www.ohmygas.com/kml-location?lo=" + kml_location;
			var kml = new GGeoXml(kml_url);
			this.map.addOverlay(kml);
		}
		
		GEvent.addListener(this.map, "moveend", function(){
			
			//alert('move');
			//omgmap.getStationsInRange();
			
		});
		GEvent.addListener(this.map, "dragend", function(){
			omgmap.getStationsInRange();
		});
		GEvent.addListener(this.map, "zoomend", function(){
			omgmap.getStationsInRange();
		});
	

		
	}	
	

	this.createTabbedMarker = function(point,htmls,labels,id, sptop, spleft) {
		
		
		var myicon = new GIcon(G_DEFAULT_ICON);
	   	myicon.iconSize = new GSize(20, 24);
	   	myicon.transparent = "http://www.google.com/intl/en_ALL/mapfiles/markerTransparent.png";
	   	myicon.iconAnchor = new GPoint(5, 34);
	   	myicon.infoWindowAnchor = new GPoint(5, 2);

	  	myicon.sprite = {image:omg_url + "images/sprite_small_logos.gif",width:30, height:30, top:sptop, bottom:5, left:spleft, right:0};
	   var marker = new GMarker(point, {icon:myicon,title:labels});  
	   

	    //  ======  The new marker "mouseover" and "mouseout" listeners  ======
	    GEvent.addListener(marker,"mouseover", function() {
	      //showTooltip(marker);
	    });        
	    GEvent.addListener(marker,"mouseout", function() {
	  		//tooltip.style.visibility="hidden"
	    });
		
	    GEvent.addListener(marker, "click", function() {

	  	  buildStationInfo(id);

	    	  //myPano.setLocationAndPOV(latlng);
	        
	      // adjust the width so that the info window is large enough for this many tabs
//	      if (htmls.length > 2) {
//	        htmls[0] = '<div style="width:'+htmls.length*88+'px">' + htmls[0] + '<\/div>';
//	      }
//	      //alert(marker);
//	      var tabs = [];
//	      for (var i=0; i<htmls.length; i++) {
//	        tabs.push(new GInfoWindowTab(labels[i],htmls[i]));
//	      }
//
//	      
//	      marker.openInfoWindowTabsHtml(tabs);
//	      //alert(id);
//	     
	  	marker.openInfoWindowHtml(htmls);
	    });
	  	
	    tabsx[id] = htmls;
	    gmarkers[id] = marker;

	    return marker;
		
	}	
	

	this.getStationsInRange = function() {
		
	    var bounds = this.map.getBounds();
		var sw = bounds.getSouthWest();
		var ne = bounds.getNorthEast();
		var pcenter = this.map.getCenter();
		var zoom = this.map.getZoom();
		var params = '?c=' + pcenter.toUrlValue() + '&r=' + this.radius[zoom];
		
		var url = omg_url + "index.php/xml-data" + params;

	      //GDownloadUrl(url, this.processIt);		
		  $.getJSON(url, function(json){
			  jsonData = eval(json);
			  omgmap.processIt(jsonData);
	
		    });
		  

	       // Note: replace this publisher ID with your own.
	       var publisherID = 'pub-4965272222015239';

	       var adsManagerOptions = {
	         maxAdsOnMap : 2,
	         style: 'adunit',
	         // The channel field is optional - replace this field with a channel number 
	         // of your own for Google AdSense tracking
	         channel: '1988043629',
	         position: new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(03,02))
	       };

	       adsManager = new GAdsManager(this.map, publisherID, adsManagerOptions);
	       adsManager.enable();
	        
		

	}
	
	this.processIt =  function(jsonData){
		
		
		 // ===== Start with an empty GLatLngBounds object =====     
	    bounds = new GLatLngBounds();
		var tablesort = '';
			tablesort += '<table id="myTable" style="width: 662px;" ><thead class="fixedHeader">';
			tablesort += '<tr>';
			tablesort += '<th style="width:20px;"></th>';
			tablesort += '<th style="width:200px;">Gas Station</th>'; 
			tablesort += '<th style="width:80px;"></th>'; 
			tablesort += '<th style="background: #ce071a; width:50px;">Reg</th>'; 
			tablesort += '<th style="background: #007cff; width:50px;">Med</th>'; 
			tablesort += '<th style="background: #f46111; width:50px;">Pre</th>';
			tablesort += '<th style="background: #299608; width:50px;">Diesel</th>';
			tablesort += '<th style="width:132px;">Last update</th>';      
			tablesort += '</tr>';
			tablesort += '</thead>';
			tablesort += '<tbody id="tabbody" >';
			

	    // === Define the function thats going to process the JSON file ===
	      //process_it = function(doc) {
	        // === Parse the JSON document === 
	        //var jsonData = doc; //eval('(' + doc + ')');
	        //alert(jsonData.station[0].id);
	        // === Plot the markers ===
	       
	        for (var i=0; i<jsonData.station.length; i++) {
	        	
		         xypx = calSprite(jsonData.station[i].sprite);
		         sptop	 = xypx[0]
		         spleft  = xypx[1]
		         var st_id = jsonData.station[i].id;
	 			 var point = new GLatLng(jsonData.station[i].lat,jsonData.station[i].lon);
	 			 var html = '';
	 			 html += '<div style="color: #333333; height:15px; width:200px; padding-right:20px;"><span class="fc_dark_blue ucwords bold">' + jsonData.station[i].brand + '<br></span>';
	 			 html += '<span class="ucwords">' + jsonData.station[i].address + '<br>' + jsonData.station[i].city  + ', ' + jsonData.station[i].state + ' ' + jsonData.station[i].zipcode + '</div>';
	 			 //html += '<span class="ucwords">' + jsonData.station[i].address + ', ' + jsonData.station[i].city  + '</div>';
	 			 //html += '<div style="height: 35px; ">$' + price_format(jsonData.station[i].pt3) + '</div>';
	             var marker = omgmap.createTabbedMarker(point, html,ucfirst(jsonData.station[i].brand) + "  $" +price_format(jsonData.station[i].pt3),st_id,sptop, spleft);
	             omgmap.map.addOverlay(marker);
	             // ==== Each time a point is found, extent the bounds ato include it =====
	 			bounds.extend(point);
	            
	            tablesort += '<tr style="background: #e7e9ea;">';
	            tablesort += '<td class="inner_img" onclick="zoomIn(' + st_id + ');">';
	            tablesort += '<div style="background-image: url(' + omg_url + 'images/sprite_small_logos.gif); background-repeat:no-repeat; background-position: -' + spleft + 'px -' + sptop + 'px; width: 25px;  height: 25px; margin:0px; padding:0px;"></div></td>';
	            tablesort += '<td class="inner_gst" ><a href="javascript:zoomIn(' + st_id + ');">' + jsonData.station[i].brand + '</a>&nbsp&nbsp&nbsp&nbsp<a href="javascript:zoomIn(' + st_id + ');">zoom in </a><br>' + jsonData.station[i].address + ', ' + jsonData.station[i].city + '</td>';
	            tablesort += '<td class="inner_dt" ><a href="javascript:showPopBox2(\'pop_gas_update2\',\'ts_outer\',' + st_id + ');">Update </a></td>';
	            tablesort += '<td class="inner_price">$' + price_format(jsonData.station[i].pt3) + '</td>';
	            tablesort += '<td class="inner_price">$' + price_format(jsonData.station[i].pt4) + '</td>';
	            tablesort += '<td class="inner_price">$' + price_format(jsonData.station[i].pt5) + '</td>';
	            tablesort += '<td class="inner_price">$' + price_format(jsonData.station[i].pt1) + '</td>';
	            tablesort += '<td class="inner_date">' + calculateDate(jsonData.station[i].last_update) + '</td>';
	            tablesort += '</tr>';
	
	        }
	     
			// ===== determine the zoom level from the bounds =====
			//omgmap.map.setZoom(omgmap.map.getBoundsZoomLevel(bounds));	
			// ===== determine the centre from the bounds ======
			//omgmap.map.setCenter(bounds.getCenter());
	
	        if(i<1){
	        	tablesort += '<tr><td colspan="5">No gas station were found in this area, please try to drag on map or zoom out to other locations</td></tr>';
	        }	

	        tablesort += '</tbody>';
	        tablesort += '<tfoot>';
			tablesort += '<tr>';
			tablesort += '<td style="width:20px;"></td>';
			tablesort += '<td style="width:200px;">Total found: ' + i +'</td>'; 
			tablesort += '<td style="width:80px;">Avg Price:</td>'; 
			tablesort += '<td style="width:50px; text-align:right;">$3.55</td>'; 
			tablesort += '<td style="width:50px; text-align:right;">$3.55</td>'; 
			tablesort += '<td style="width:50px; text-align:right;">$3.55</td>';
			tablesort += '<td style="width:50px; text-align:right;">$3.55</td>';
			tablesort += '<td style="width:132px; text-align:right;"></td>';  
			tablesort += '</tr>';
			tablesort += '</tfoot>';
			tablesort += '</table>';
	        	
	        
	        $("#ts_innera").empty().append(tablesort);
	        
	        if(i>1){
	        	$("#myTable").tablesorter( {sortList: [[3,0],[7,0]]} ); 
	        } 
	        
	    }	
	     
			
	
}

price_format = function(price){
	
	if(price=='0.000'){
		price = '9-N/A';
	}
	
	return price;
	
}

function calculateDate(d){
	var today = new Date()
	var update = Date.parse(d);
	var dd = Math.ceil(today - update);
	var one_hour=1000*60*60;
	tm = Math.ceil(dd/one_hour);
	var rt = '';
	if(tm < 24){
    	if(tm==0){tm=1}
		rt = tm + ' h ago';
	}else {
		rt = Math.ceil(tm/24) + ' d ago';
	}
	return rt;
}

function showPopBox(id1, id2) {
	
	var eles = document.getElementsByTagName("div");
	
	for (var i=0; i<eles.length; i++) {
		if (eles[i].className=='pop_box') eles[i].style.display='none';
	} 

	popbox_bk = document.getElementById(id2);
	
	x = parseInt(popbox_bk.offsetLeft) + parseInt(popbox_bk.offsetWidth) + 3;
	y = parseInt(popbox_bk.offsetTop);
		
	
	ele = document.getElementById(id1);
	ele.style.left = x - 185 + 'px';
	ele.style.top  = y + 20 + 'px';
	
	ele.style.display = '';
}

function showPopBox2(id1, id2,station_id) {
	
	this_id = station_id;
	
	var eles = document.getElementsByTagName("div");
	
	for (var i=0; i<eles.length; i++) {
		if (eles[i].className=='pop_box') eles[i].style.display='none';
	} 

	popbox_bk = document.getElementById(id2);
	
	x = parseInt(popbox_bk.offsetLeft) + parseInt(popbox_bk.offsetWidth) + 3;
	y = parseInt(popbox_bk.offsetTop);
		
	
	ele = document.getElementById(id1);
	ele.style.left = x - 385 + 'px';
	ele.style.top  = y + 25 + 'px';
	
	ele.style.display = '';
}


function calSprite(v){
	var xypx = [];
	if(v !=''){
	 var sg = new String(v); 
     var sa = sg.split("|");
     var xypx = [];
     xypx[0] = (30 * sa[0]) + (Math.ceil(sa[0]/2) + 2);
     xypx[1] = (30 * sa[1]) + (Math.ceil(sa[1]/2) + 5) ;
	}else {
		 xypx[0] = 0;
         xypx[1] = 0;
	}	
   return xypx;  
}	


function submitReview(id){

	//alert('review');
	closePopBox();
}	

function zoomIn(id) {
    gmarkers[id].openInfoWindowTabsHtml(tabsx[id]);
    buildStationInfo(id);
}
function updateGasPrice(id){
	
	
}
function updatePrice2(){
	
	var gp = [];
	var p = '';
	var stid = this_id;
	for(var gt=1;gt<5; gt++){
		
		var f_id = 'gpt_' + gt;
		
		gp[gt] = $("#" + f_id).val();
		
	}
	if(this_id > 0){
		$.ajax({
			   type: "POST",
			   url: omg_url + "station/updatePrice?",
			   data: 'id=' + stid + '&gp1=' + gp[1] + '&gp2=' + gp[2] + '&gp3=' + gp[3] + '&gp4=' + gp[4],
			   success: function(msg){
			 	$('#gp_input_table').hide();
			 	$('#gp_update_thank').show();
				buildStationInfo(stid);
				$('#pop_gas_update2').wait(3000,function(){ 
				closePopBox();
				$('#gp_update_thank').hide();
				$('#gp_input_table').show();
				});
			   }
			 });
	}	
	
}

function buildStationInfo(id) { 
	
	$.ajax({
		   type: "POST",
		   url: omg_url + 'station/getStation?',
		   data: 'id=' + id,
		   success: function(msg){
		document.getElementById("right_ct").innerHTML = msg;
		}
	 });
//	$.get(omg_url + 'get-station/' + id, function(data) {
//		document.getElementById("right_ct").innerHTML = data;
//	});	    	
} 

$(document).ready(function(){ 
	
	  omgmap = new omg_map();
	  omgmap.initmap();
});
