/* Store Locator */

var map = null
var gdir = null;
var geocoder = null;
var gmarkers = [];
var reasons=[];
var mypoly = null;
var myaddr = null;
var map2 = null;
var distance = null;
var end = null;
var marker = [];
var searchterm = null;
var address = null;
var city = null;
var province = null;
var postal = null;
var phone = null;

jQuery(document).ready(function()
{
	// Set Dropdown Values
	jQuery("#returns > .ddTitle > span").text(jQuery("#returns input:checked").next().text());
	jQuery("#radius > .ddTitle > span").text(jQuery("#radius input:checked").next().text());
	
	// Initialize Geocoder
	geocoder = new GClientGeocoder();
	
	// Initialize Result Tabs
	jQuery('#resultpanel').tabs({ fxFade: true, fxSpeed: 'fast', fxAutoHeight: true });

	// Initialize Store Search if prev-search results
	if (location.hash == '#activeSearch' && jQuery("#address").val() != '')
		locateStores(loadHistory);		
});

function initializeGmaps()
{
	if (GBrowserIsCompatible())
	{   
		// Show the Map
		jQuery("#map").show();
		
		// Create the Map
		map = new GMap2(document.getElementById("map"));
		map2 = new GMap2(document.getElementById("map2"));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(myaddr, 12);

		// Create GDirections Object
		gdir = new GDirections(map2, document.getElementById("directions2"));
		GEvent.addListener(gdir, "load", onGDirectionsLoad);

		// Error Code Array
		reasons[G_GEO_SUCCESS]            = "We've found your directions";
		reasons[G_GEO_MISSING_ADDRESS]    = "The address you entered was either missing or had no value.";
		reasons[G_GEO_UNKNOWN_ADDRESS]    = "Sorry, we don't recognize that address!";
		reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Sorry, we don't recognize that address!";
		reasons[G_GEO_BAD_KEY]            = "Sorry, We're experiencing some technical difficulties now! [5]";
		reasons[G_GEO_TOO_MANY_QUERIES]   = "Sorry, We're experiencing some technical difficulties now! [6]";
		reasons[G_GEO_SERVER_ERROR]       = "There was an error with your request, please try again.";
		reasons[G_GEO_BAD_REQUEST]        = "There was an error with your request, please try again.";
		reasons[G_GEO_MISSING_QUERY]      = "There was an error with your request, please try again.";
		reasons[G_GEO_UNKNOWN_DIRECTIONS] = "Sorry, we can't find directions between the two locations.";
		
		// GEvent Event Listener (Error Catching)
		GEvent.addListener(gdir, "error", function() { alert("Error: " + (reasons[gdir.getStatus().code] ? reasons[gdir.getStatus().code] : "Code " + gdir.getStatus().code)); });
	}
}

//  Geocode the address and add it to the map
function locateStores(page)
{
	address = jQuery('#address').val();
	if (address.length < 1)
		alert('Please enter a search location');
	else if (address.length < 3)
		alert('Your search term must be longer than 3 characters');
	else
	{
		if (geocoder)
		{		
			geocoder.getLatLng(
			address += ', Canada',	// Tag "Canada" to the end of the address
			function(point)
			{
				if (!point)
					alert(address + ' not found');
				else
				{	

					searchterm = address;									// Save the search address to a global
					myaddr = point;											// Save the point to a global
					initializeGmaps();										// Initialize Map
					jQuery("#resultpanel").show();							// Show Result Tabs
					loadStores(page);										// Load Stores via jSON
					map.addOverlay(createMarker(myaddr, '', 'central'));	// Add central marker to the map
					location.hash = 'activeSearch';								// Set location hash to identify re-search on return
				}
			});
		}
	}
}
function loadStores(page)
{
	var stores = '';
	var services = '';
	jQuery("#stores li:not('.all')").each(function(){ if (jQuery(this).find('input').attr('checked') == true)stores += jQuery(this).find('label').text() + ','; });
	jQuery("#services li:not('.all')").each(function(){ if (jQuery(this).find('input').attr('checked') == true)	services += jQuery(this).find('label').text() + ','; });

	// Save To Session
	jQuery.post(ajax + 'sessions.php', { 'session':'storelocator', 'address':jQuery("#address").val(), 'stores':stores, 'services':services, 'returns':jQuery("#returns span").text(), 'radius':jQuery("#radius span").text(), 'page': (page > 1 ? page : 1) });

	// Load Stores via jSON & AJAX
	jQuery.ajax({
		type:'POST',
		url: ajax + 'storelocator.php',
		data: "locateStores=" + String(myaddr) + "&store=" + stores.substring(0, stores.length - 1) + "&service=" + services.substring(0, services.length - 1) + "&page=" + (page > 1 ? page : 1) + "&max=" + jQuery("#returns span").text().substring(8, jQuery("#returns span").text().length) + "&radius=" + jQuery("#radius span").text().substring(7, jQuery("#radius span").text().length - 2),
		processData: true,
		dataType: 'json',
		beforeSend: function(){	jQuery('#storelist').html('<img src="' + images + 'loading.gif" border="0" id="loading" />');},
		success: function(data){ responseJson(data, ajax + 'storelocator.php', 'POST', images + 'loading.gif');}
	});
}

var responseJson = function(data, url, method, busy){
	var html = new String();
	var totalPage = Math.floor(parseFloat(data.ttl) / 10) + Math.ceil(Math.floor(parseFloat(data.ttl) % 10) / 10);
	var current = data.crr;
	var markerWindows = [];
	var currentNow = new String();
	
	// Remove Old Markers
	if (typeof marker[1] == 'object')
		for (j = 0; j < 10; j++)
			map.removeOverlay(marker[j]);
			
	// List Stores
	var j = 0;
	var dist = null;
	var lat = null;
	var lon = null;
	var resultset = null;
	var storeTemp = null;
	jQuery.each(data.items, function(i,item){
		// Initialize result list icons for grand opening and brands
		
		item.brand = (item.storeType == 'Prescription Centre') ? item.brand + ' *' : item.brand;
		item.brand = (item.storeType == 'Full Promotion') ? item.brand + ' **' : item.brand;
		item.brand = (item.storeType == 'none') ? item.brand : item.brand;
		//if(item.storeType.length){
		//	window.storeTemp = item.storeType;
		//}
		
		//
		//document.write('<!-- storeType'+storeType+'-->\n');
		
		var grandopening = (item.grandopening == 'true') ? '<img src="' + images + 'storelocator/iconGrandOpening.gif" />' : '';
		//item.brand = (item.brand == "Guardian" || item.brand == "I.D.A.") ? item.brand + ' *' : item.brand;

		// Create HTML for geomark info window & store list
		markerWindows[j] = '<div class="infoWindow"><div class="storeName">' + item.brand + '</div><div class="storeAddress">' + item.address + '<br />' + item.city + ', ' + item.province + ' ' + item.postal + '<br />' + item.phone + '</div><ul><li><a href="' + storelocator + 'store' + item.id + '">Store Hours & Information</a></li><li><a onClick="getDirections(' + item.latitude + ', ' + item.longitude + ', ' + item.distance + ', \'' + item.address + '\', \'' + item.city + '\', \'' + item.province + '\', \'' + item.postal + '\', \'' + item.phone + '\')">Show Directions</a></li></ul></div>';
		html += '<div class="pagi-elements"><table class="tbStore" cellspacing="0"><tr><td valign="top" class="tdIcon"><img src="' + images + 'storelocator/geomarker' + (j + 1) + '.gif"  alt="' + j + '"/></td><td valign="top" class="kms">' + Number(item.distance).toFixed(2) + ' km</td><td valign="top"><div class="title" alt="' + j + '">' + item.brand + grandopening + '</div>' + item.address + ', ' + item.city + ', ' + item.province + '<div class="option"><a href="' + storelocator + 'store' + item.id + '">Store Information</a> | <a class="getDirections" onClick="getDirections(' + item.latitude + ', ' + item.longitude + ', ' + item.distance + ', \'' + item.address + '\', \'' + item.city + '\', \'' + item.province + '\', \'' + item.postal + '\', \'' + item.phone + '\');">Show Directions</a></div></td></tr></table></div>';			

		// Create the geomarker and its infowindow & add it to the map
		marker[j]= createMarker(new GLatLng(item.latitude,item.longitude), markerWindows[j], j);
		map.addOverlay(marker[j]);
		
		// Save Globals
		dist = item.distance;
		lat = item.latitude;
		lon = item.longitude;
		j++;
	});
	
	//temporarily output value
	//if(window.storeTemp.length){
	//	alert(window.storeTemp);
	//}
	
	if (j > 0)
	{
		// Load directions into the hidden map and scrape zoom level and center
		gdir.load("from: " + String(myaddr).substring(1, String(myaddr).length - 1) + " to: "+ lat + ',' + lon, { getPolyline:true } );
		
		// Format "Of # results" in Result Title
		var resultset = '<div id="resultset">Displaying ' +  ((Number(current) * 10) -9) + '-' + (Number(current) * 10 > data.ttl ? searchmax = data.ttl : searchmax = Number(current) * 10) + ' of ' + data.ttl + ' for <b><em>' + searchterm.substring(0, searchterm.length - 8) + '</em></b></div>';
		jQuery("#pagination").html('<div id="pagi-wrapper">'+Pagination(5,totalPage,current)+'</div>').css('border-top', '1px solid #CCC');
	}
	else
	{
		resultset = '<div id="resultset">No Search Results Returned for <b><em>' + searchterm.substring(0, searchterm.length - 8) + '</em></b><br /><br /><b>Try Broadening Your Search</b></div>';
		jQuery("#pagination").html('');
	}
	
	// Plug Result Title & Store List into Container
	jQuery("#storelist").html(resultset + html);
	
	// Event Handling For Store Title Click & Hover
	jQuery("#storelist .title, #storelist img").click(function(){ marker[jQuery(this).attr('alt')].openInfoWindowHtml(markerWindows[jQuery(this).attr('alt')]); });
	jQuery("#storelist .title").hover(function(){jQuery(this).css('text-decoration','underline')},function(){jQuery(this).css('text-decoration','none')});
	
	// Trigger Search Results Tab
	jQuery("#resultpanel").triggerTab(1);

	// Activate Pagination Buttons
	jQuery(".pagi li a").click(function(){ loadStores(jQuery(this).attr("name").substr(4)); });
}

// A function to create the marker and set up the event window
function createMarker(point, html, i)
{	

	var baseIcon = new GIcon();
	baseIcon.iconSize=new GSize(32,32);
	baseIcon.shadowSize=new GSize(59,32);
	baseIcon.iconAnchor=new GPoint(16,32);
	baseIcon.infoWindowAnchor=new GPoint(16,0);
	var thisicon = new GIcon(baseIcon, images + 'storelocator/geomarker' + (i == 'central' ? '' : i + 1) + ".png", null, images + 'storelocator/geoshadow.png');
	var marker = new GMarker(point, {icon: thisicon});

	if (i != 'central')
		GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(html); }); // Geomarker event listener: Launches info window
	return marker;
}


function onGDirectionsLoad(){
	
	// Clear existing polylines (If they exist)
	if (mypoly != null)
		map.removeOverlay(mypoly);

	// Distance is null when store directions are requested
	if (distance != null)
	{			
		// Wait a millisecond - Then load the directions list and the map path
		setTimeout(directions, 1);
		setTimeout(handle, 1);
		
		// Reset distance to null
		distance = null;
	}
	// This triggers when a new page is requested (pagination)
	else
	{
		// Readjust the zoom to correlate with the hidden map's zoom
		setTimeout(function(){map.setCenter(myaddr, map2.getZoom() - 1); }, 1);
	}
} 	
// Request Directions
function getDirections(lat, lon, dist, addr, ci, prov, pos, ph)
{
	map.closeInfoWindow(); // Close Info Window
	
	// Save Globals
	end = lat + ',' + lon;
	distance = dist;
	address = addr;
	city = ci;
	province = prov;
	postal = pos;
	phone = ph;
	
	// Load Directions
	gdir.load("from: " + String(myaddr).substring(1, String(myaddr).length - 1) + " to: "+ lat + ',' + lon, { getPolyline:true } );
}

// Scrape Directions
function directions()
{
	// Intialize Time Estimate & Turn By Turn Directions
	var turnbyturn = [];
	var estimate = jQuery("#directions2 div[jseval='this.innerHTML = $Route.summaryHtml']").text().replace('(',' - ').replace(')', '');
	
	// Scrape Turn By Turn Directions
	jQuery("#directions2 td:has('a')").each(function(){ turnbyturn.push('TBT:' + jQuery(this).next().text() + ' (' + String(jQuery(this).next().next().text()).replace(/\r|\n|\r\n|\t/g, '') + ')'); });
	jQuery("#directions, #directions2").html('');	// Clear Both Direction Containers
	
	// Display Time Estimate & Search Title
	jQuery("#directions").append('<table cellspacing="0"><tr><td style="padding-right: 5px;">From:</td><td><b><em>' + searchterm.substring(0, searchterm.length - 8) + '</em></b></td></tr><tr><td>To:</td><td><b><em>' + address + ', ' + city + ', ' + province + '<em/></b></td></tr></table><br /><em>Distance: ' + estimate + '</em><br /><br /><table cellspacing="0">');	
	// Display Turn By Turn directions
	for (var i in turnbyturn)
		if (turnbyturn[i].substring(0, 4) == 'TBT:' && turnbyturn[i] != 'TBT: ()')
			jQuery("#directions").append('<tr><td class="step">' + (Number(i)+1) + '.</td><td>' + turnbyturn[i].substring(4) + '</td></tr>');
	jQuery("#directions").append('</table><br /><br /><a class="back">Back To Search Results</a>');
	
	// Enable & Trigger Directions Tab
	jQuery("#resultpanel").enableTab(2).triggerTab(2);
	
	// Event Handler [Return To Search Results (From Directions)]
	jQuery("a.back").click(function(){ jQuery("#resultpanel").triggerTab(1); });
	
}

function handle()
{
	var points = [];
	var poly = gdir.getPolyline();

	for (var i = 0; i < poly.getVertexCount(); i++)
		points[i] = poly.getVertex(i);

	map.setCenter(map2.getCenter(), map2.getZoom() - 1);

	mypoly = new GPolyline(points, "#3977E7", 3, 1);
	map.addOverlay(mypoly);
}

// jQuery Event Handlers
jQuery(function(){
	// Initialize Store Search
	jQuery('#searchBar #address').keypress(function(event){ if (event.which == 13) { locateStores(1); } });
	jQuery('#searchBar .submit').click(function(){ locateStores(1); });
	
	// Dropdown Handlers
	jQuery(".dropdown .ddTitle").click(function(){ resize(jQuery(this).parent()); });
	jQuery(".dropdown").mouseleave(function(){ if (jQuery(this).innerHeight() > 22) resize(jQuery(this)); });

	// Set Hover Colors for Dropdown List Elements
	jQuery(".ddList ul li").hover(function(){jQuery(this).css('background','#D4E1F4');}, function(){jQuery(this).css('background','none');});
	
	// Check / Uncheck `All` Checkbox
	jQuery("#stores .ddList ul li:not('.all') input").click(function(){
		var checkTrue = null;
		var checkFalse = null;
		jQuery(this).parent().parent().parent().find("li:not('.all') input").each(function(){
			if (jQuery(this).attr('checked') == true)
				checkTrue = 1;
			else
				checkFalse = 1;
		});
		
		if (checkTrue == 1 && checkFalse == null)
			jQuery(this).parent().parent().parent().find("li.all input").attr('checked', 'true');
		else
			jQuery(this).parent().parent().parent().find("li.all input").removeAttr('checked');
	});
	jQuery("#services .ddList ul li:not('.all') input").click(function(){
		var checkTrue = null;
		var checkFalse = null;
		jQuery(this).parent().parent().parent().find("li:not('.all') input").each(function(){
			if (jQuery(this).attr('checked') == true)
				checkTrue = 1;
			else
				checkFalse = 1;
		});
		
		if (checkFalse == 1 && checkTrue == null)
			jQuery(this).parent().parent().parent().find("li.all input").attr('checked', 'true');
		else
			jQuery(this).parent().parent().parent().find("li.all input").removeAttr('checked');
	});
	
	// Set `All` Click Functionality
	jQuery("#stores .ddList ul li.all input").click(function(){
		if (jQuery(this).attr('checked') == true)
			jQuery(this).parent().parent().parent().find('input').attr('checked', 'true');
		else
			jQuery(this).parent().parent().parent().find('input').removeAttr('checked');
	});
	jQuery("#services .ddList ul li.all input").click(function(){
		if (jQuery(this).attr('checked') == true)
		{
			jQuery(this).parent().parent().parent().find('li:not(.all) input').removeAttr('checked');
			jQuery(this).attr('checked');
		}
	});
	
	// Modify Title Text for Radio Selections
	jQuery(".ddList ul li input:radio").click(function(){
		jQuery(this).parent().parent().parent().parent().find('span').text(jQuery(this).next().text());
		resize(jQuery(this).parent().parent().parent().parent());
	});
});

// Expand / Close Dropdowns
function resize(element)
{
	if (jQuery(element).find('img').attr('src') == images + 'storelocator/icon_dropdown_maximize.gif')
	{
		jQuery(".dropdown").each(function(){
			if (jQuery(this).find('img').attr('src') == images + 'storelocator/icon_dropdown_minimize.gif')
				resize(jQuery(this));
		});
		jQuery(element).find('img').attr('src', images + 'storelocator/icon_dropdown_maximizing.gif');
		jQuery(element).animate( { height: jQuery(element).find('img').attr('alt') }, jQuery(element).find('img').attr('alt'), function(){
			jQuery(element).find('img').attr('src',images + 'storelocator/icon_dropdown_minimize.gif');
		}).find('.ddList').show();
	}
	else if (jQuery(element).find('img').attr('src') == images + 'storelocator/icon_dropdown_minimize.gif')
	{
		jQuery(element).find('img').attr('src', images + 'storelocator/icon_dropdown_minimizing.gif');
		jQuery(element).find('img').attr('alt', jQuery(element).innerHeight());
		jQuery(element).animate( { height: 22 }, jQuery(element).find('img').attr('alt'), function(){
			jQuery(element).find('.ddList').css('display','none');
			jQuery(element).find('img').attr('src',images + 'storelocator/icon_dropdown_maximize.gif');
		});
	}
}

