/*********************************************
* Created By Benjamin Talavera
*
*   3/3/2011
*
*   Makes use of Google Maps Javascript API V3.2 and MaxMind.com's Javascript Geolocation API to produce a sorted list of UGP Stores
*
*   Sort Order:  Same State, Travel time between store and current locations
*
*   global variable, stores, is a sorted JSON object of all the stores and they're attributes
*
*/

mmjsCountryCode = geoip_country_code();
mmjsCountryName = geoip_country_name();
mmjsCity = geoip_city();
mmjsRegion = geoip_region();
mmjsRegionName = geoip_region_name();
mmjsLat = geoip_latitude();
mmjsLong = geoip_longitude();
mmjsPostalCode = geoip_postal_code();
mmjsIPAddress = "<?php echo $_SERVER['REMOTE_ADDR']; ?>";

var directionsService = new google.maps.DirectionsService();
var stores = null;

var sort_by = function(field, reverse, primer)
{
	reverse = (reverse) ? -1 : 1;

	return function(a,b)
			{
				a = a[field];
				b = b[field];

				if (typeof(primer) != 'undefined')
				{
					a = primer(a);
					b = primer(b);
				}

				if (a<b) return reverse * -1;
				if (a>b) return reverse * 1;
				return 0;
			}
}

  
function calcRoute(start, end, id) 
{
	var request = {
				    origin:start, 
				    destination:end,
				    travelMode: google.maps.DirectionsTravelMode.DRIVING
				  };
					
	directionsService.route(request, function(result, status) 
									{
									    if (status == google.maps.DirectionsStatus.OK) 
										{
											for(i=0;i<result.routes[0].legs.length;i++)
											{
												stores[id].duration += result.routes[0].legs[i].duration.value;
												stores[id].distance += result.routes[0].legs[i].distance.value;
											}
											
											calculateStores(id+1);
									    }
									});
}

function calculateStores(i)
{
	if (i<stores.length)
	{
		stores[i].duration = 0;
		stores[i].distance = 0;
		
		calcRoute(stores[i].city + ', ' + stores[i].state + ' ' + stores[i].zip, mmjsLat + ", " + mmjsLong, i);
	}
	else
	{
		stores.sort(sort_by('duration', false, parseInt));
		stateFilter();
			$(document).trigger('actuallyReady');
	}
}

function showStores()
{
	var str="";
	
	for(j=0; j<stores.length; j++)
	{
		str += stores[j].id + " " + stores[j].city + " " + stores[j].state + " " + stores[j].zip + " " + stores[j].duration + " " + stores[j].distance + "<BR>";
	}
	
	$("#content").prepend(str);
}

function getStores()
{
  return stores;
}

function contains(a, arr)
{
  var val=false;
  
  for(k=0; k<arr.length; k++)
  {
    if (arr[k]==a)
    {
      val=true;
    }
  }
  
  return val;
}

function getCarts()
{
  str = "[";
  
  var tempJSON = [];
  var tempIDs = [];
  
  for(j=0; j<stores.length; j++)
  {
    for(i=0; i<stores[j].cart_ids.length; i++)
    {
      //alert(tempIDs);
      //alert(stores[j].cart_ids[i].site_id);
      
      if (!(contains(stores[j].cart_ids[i].site_id, tempIDs)))
      {
        tempJSON.push($.JSON.encode(stores[j].cart_ids[i]));
        tempIDs.push(stores[j].cart_ids[i].site_id);
      }
    }
  }
  
  for(j=0; j<tempJSON.length; j++)
  {
    if (j!=0)
		{
			str += " ,";
		}
		str += tempJSON[j];
  }
  
  str += "]";
  
  return $.JSON.decode(str);
}

function stateFilter()
{
	var instate=[];
	var outstate=[];
	
	//alert($.JSON.encode(stores));
	
	for(j=0; j<stores.length; j++)
	{
		if (stores[j].state==mmjsRegion)
		{
			instate.push($.JSON.encode(stores[j]));
		}
		else
		{
			outstate.push($.JSON.encode(stores[j]));
		}
	}
	
	var str="[";
	
	for(j=0; j<instate.length; j++)
	{
		if (j!=0)
		{
			str += " ,";
		}
		str += instate[j];
	}
	
	for(j=0; j<outstate.length; j++)
	{
		str += " ," + outstate[j];
	}
	
	str += "]";

	stores=$.JSON.decode(str);
}

function initGeo(init_stores)
{
  $(document).bind('actuallyReady', function(e){actuallyReady(e);});
  stores = init_stores;
  calculateStores(0);
}
