﻿function registerSearchFilter(sFilterId, sFilterKey, sPathToRoot, sUpdateUrl, sNumLocationsId) {
	if (sFilterId && sFilterKey) {
		var oFilter = jQuery('#' + sFilterId);

		oFilter.click(function () {
			//expandSearchUpdateText(jQuery('#search_status div.text'), 'Applying filters...');
			var bChecked = jQuery(this).attr('checked');
			updateSearch('Applying filters...', 'Filters applied', sPathToRoot, sUpdateUrl, sNumLocationsId, 0, false, true, checkIsOnVehicles(), sFilterKey, !bChecked);
		});
	}
}
function switchTabs(oOffTab, oOnTab) {
	jQuery.each(oOffTab.removeClass('on').find('img'), function() {
		jQuery(this).attr('src', jQuery(this).attr('src').replace(/(\_on)?\.gif$/i, '.gif'));
	});

	jQuery.each(oOnTab.addClass('on').find('img'), function() {
		jQuery(this).attr('src', jQuery(this).attr('src').replace(/(\_on)?\.gif$/i, '_on.gif'));
	});

	//Content
	var sOnClass = (oOnTab.hasClass('vehicle')) ? 'vehicle' : 'personal';
	jQuery.each(jQuery('#search_header .advanced .filters .filter'), function () {
		jQuery(this).css({ display: ((jQuery(this).hasClass(sOnClass)) ? 'block' : 'none') })
	});
}
function initResults(iNumSitesFound, iNumSitesDisplayed, iCurrPageIndex, iTotalPages, sNumLocationsId, sPathToRoot, sUpdateUrl, iNumTotalUnits, iNumVehicleUnits, bDisplayVehicles) {
	var oContainer = jQuery('#search_results');

	revealFilters();

	//Tabs
	var oPersonalUnitsTab = jQuery('#search_header .advanced .tabs ul li.personal');
	var oVehicleUnitsTab = jQuery('#search_header .advanced .tabs ul li.vehicle');

	var sUpdateText = 'Retrieving ' + ((bDisplayVehicles) ? 'vehicle units' : 'units');
	var bDisplayVehicles = bDisplayVehicles.toString().bool();
	if (bDisplayVehicles) {
		switchTabs(oPersonalUnitsTab, oVehicleUnitsTab);
	}
	else {
		switchTabs(oVehicleUnitsTab, oPersonalUnitsTab);
	}
	
	//alert(bDisplayVehicles);

	jQuery.each(jQuery('#search_header .advanced .tabs ul li'), function () {
		if (!jQuery(this).unbind('click').hasClass('on')) {
			jQuery(this).click(function () {
				//expandSearchUpdateText(jQuery('#search_status div.text'), sUpdateText);
				updateSearch(sUpdateText, 'Update Complete', sPathToRoot, sUpdateUrl, sNumLocationsId, 0, false, true, !bDisplayVehicles);
			});
		}
	});

	var iNumTotalUnitsFinal = parseInt(iNumTotalUnits);
	var iNumVehicleUnitsFinal = parseInt(iNumVehicleUnits);

	//Expanding clicks
	jQuery.each(oContainer.find('.items .item'), function () {
		var oItemContainer = jQuery(this);

		var oOpenLink = oItemContainer.find('.location p.details a');
		var oExpanding = oItemContainer.find('.location div.expanding');
		//var sOpenLinkText = 'Click here to see all units and details';
		var sOpenLinkText = 'Click here to see all units and details';
		if (!oItemContainer.find('.units').length)
			sOpenLinkText = 'Click here to see all details';
		var sCloseLinkText = 'Hide Details';
		try {
			if (gbViewAllUnits) {
				sOpenLinkText = gbViewAllUnits;
			}
			if (gbHideDetails) {
				sCloseLinkText = gbHideDetails;
			}
		}
		catch (ex) {
		}

		var iHeight = oExpanding.height();
		var iItemHeight = oItemContainer.height();
		var iHideItemHeight = 180;
		try
		{
			iHideItemHeight = (gHideItemOverride != null && gHideItemOverride > 0) ? gHideItemOverride : iHideItemHeight;
		}
		catch (exItemHeight)
		{
			iHideItemHeight = 180;
		}
		//alert(iHeight);
		//oExpanding.css({ overflow: 'hidden', height: '1px' });

		//Open
		oOpenLink.text(sOpenLinkText).click(function () {
			//Determine status
			var sStatus = jQuery(this).html();
			if (sStatus && sStatus == sCloseLinkText) {
				//Close
				jQuery(this).css('visibility', 'hidden').html(sOpenLinkText);
				//				oExpanding.stop().animate({ height: '1px' }, { duration: 800, complete: function () {
				//					oOpenLink.css('visibility', 'visible');
				//					oExpanding.css('display', 'none');
				//				}
				//				});
				oExpanding.css('display', 'none');
				oItemContainer.find('.hide').css({ visibility: 'hidden' });
				oItemContainer.stop().animate({ height: iHideItemHeight + 'px' }, { duration: 800, complete: function () {
					oOpenLink.css('visibility', 'visible');
				}
				});
			}
			else {
				//Open
				jQuery(this).css('visibility', 'hidden').html(sCloseLinkText);
				//				oExpanding.stop().css('display', 'block').animate({ height: iHeight + 'px' }, { duration: 800, complete: function () {
				//					oOpenLink.css('visibility', 'visible');
				//				}
				//				});
				oItemContainer.stop().animate({ height: iItemHeight + 'px' }, { duration: 800, complete: function () {
					oOpenLink.css('visibility', 'visible');
					oExpanding.css('display', 'block');
					oItemContainer.find('.hide').css({ visibility: 'visible' });
				}
				});
			}
		});

		oExpanding.css('display', 'none');
		oItemContainer.css({ height: iHideItemHeight + 'px', overflow: 'hidden' });


		//Show links
		//jQuery(this).find('p.details').css('display', 'block');
	});
	//Pagination
	buildPaginationForSearch(iNumSitesFound, iNumSitesDisplayed, iCurrPageIndex, iTotalPages, sNumLocationsId, sPathToRoot, sUpdateUrl, iNumTotalUnitsFinal, iNumVehicleUnitsFinal, bDisplayVehicles);
}


function buildPaginationForSearch(iNumSitesFound, iNumSitesDisplayed, iCurrPageIndex, iTotalPages, sNumLocationsId, sPathToRoot, sUpdateUrl, iNumTotalUnits, iNumVehicleUnits, bDisplayVehicles) {
	jQuery('#' + sNumLocationsId).text(iNumSitesFound);
	var oSearchText = jQuery('#search_status div.text');
	iTotalPages = parseInt(iTotalPages);
	iCurrPageIndex = parseInt(iCurrPageIndex);
	iNumSitesDisplayed = parseInt(iNumSitesDisplayed);
	iNumSitesFound = parseInt(iNumSitesFound);

	//Summary
	var oSummary = jQuery('#search_navigation .results');

	//Build Nav Link Container
	var oNav = jQuery(document.createElement("ul"));
	oNav.addClass('search_pagination');
	var oHeaderPageContainer = jQuery('#search_navigation .search_pagination');
	var oFooterPageContainer = jQuery('#search_results .footer .search_pagination');

	//Tabs
	jQuery('span.search_num_found').text(iNumTotalUnits);
	jQuery('span.search_num_vehicle_found').text(iNumVehicleUnits);

	if (iNumSitesFound > 0) {
		jQuery('#search_results .no_results_found').css({ display: 'none' });
		
		if (iTotalPages > 1 && iNumSitesDisplayed < iNumSitesFound) {

			var sCompleteText = 'Update complete';

			//View All
			var oViewAll = jQuery(document.createElement('li')).text('View All');
			oViewAll.click(function () {
				//expandSearchUpdateText(oSearchText, 'Retrieving all matches...');
				updateSearch('Retrieving all matches...', sCompleteText, sPathToRoot, sUpdateUrl, sNumLocationsId, 0, true, true, bDisplayVehicles);
			});
			oNav.append(oViewAll);


			var oLast = jQuery(document.createElement('li')).text('Last');
			var oNext = jQuery(document.createElement('li')).text('Next');
			if (iCurrPageIndex + 1 < iTotalPages) {
				//Last

				oLast.click(function () {
					//expandSearchUpdateText(oSearchText, 'Advancing to last page...');
					updateSearch('Advancing to last page...', sCompleteText, sPathToRoot, sUpdateUrl, sNumLocationsId, iTotalPages - 1, false, true, bDisplayVehicles);
				});


				//Next Page

				oNext.click(function () {
					//expandSearchUpdateText(oSearchText, 'Advancing to next page...');
					updateSearch('Advancing to next page...', sCompleteText, sPathToRoot, sUpdateUrl, sNumLocationsId, iCurrPageIndex + 1, false, true, bDisplayVehicles);
				});

			}
			oNav.append(oLast);
			oNav.append(oNext);



			//First Page
			var oPrevious = jQuery(document.createElement('li')).text('Prev');
			var oFirst = jQuery(document.createElement('li')).text('First');
			if (iCurrPageIndex > 0) {
				//Previous

				oPrevious.click(function () {
					//expandSearchUpdateText(oSearchText, 'Refreshing previous page...');
					updateSearch('Refreshing previous page...', sCompleteText, sPathToRoot, sUpdateUrl, sNumLocationsId, iCurrPageIndex - 1, false, true, bDisplayVehicles);
				});

				//First
				oFirst.click(function () {
					//expandSearchUpdateText(oSearchText, 'Refreshing first page...');
					updateSearch('Refreshing first page...', sCompleteText, sPathToRoot, sUpdateUrl, sNumLocationsId, 0, false, true, bDisplayVehicles);
				});

			}
			oNav.append(oPrevious);
			oNav.append(oFirst);
		}
		else {
		}

		//Summary
		var iTotalPageToIndex = (iTotalPages - 1);
		var iNumSitesPerPage = iNumSitesFound;
		var iStartSite = 1;

		if (iTotalPageToIndex > 0) {
			iNumSitesPerPage = Math.ceil(iNumSitesFound / (iTotalPages));
			iStartSite = Math.floor(iNumSitesPerPage * iCurrPageIndex) + 1;
		}
		else {

		}
		var iEndSite = (iStartSite + (iNumSitesDisplayed - 1));

		//alert(iStartSite + ' ' + iNumSitesDisplayed + ' ' + iEndSite);
		//alert(iNumSitesPerPage);

		
		if (iNumSitesDisplayed <= 1) {
			oSummary.text('Location ' + iStartSite + ' of ' + iNumSitesFound);
		}
		else {
			oSummary.text('Locations ' + iStartSite + ' - ' + iEndSite + ' of ' + iNumSitesFound);
		}
	}
	else {
		//No sites found
		jQuery('#search_results .no_results_found').css({ display: 'block' });

		oSummary.text('No locations found.');
	}
	oFooterPageContainer.replaceWith(oNav);
	oHeaderPageContainer.replaceWith(oNav.clone(true));
}

function expandSearchUpdateText(oSrchObj, sTextToSpawn) {
	oSrchObj.css({ display: 'block' }).text(sTextToSpawn).stop().animate({ 'margin-left': '0px', duration: 1100 });
}

/* Map Functionality */
function gmap_initialize(dCoordLat, dCoordLon, fSearchRadius, arrStores, sUpdateUrl, sPathToRoot, sNumLocationsId, sLblLocationId, bAdjustableMap) {
	fSearchRadius = (!fSearchRadius) ? 50 : fSearchRadius;
	var fSearchKm = (fSearchRadius * 1609.344);
	var myOptions = { zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP, center: new google.maps.LatLng(dCoordLat, dCoordLon), minZoom: 4 };
	map = new google.maps.Map(document.getElementById("google_map_canvas"), myOptions);

	map.fitBounds(new google.maps.Circle({ radius: fSearchKm * .9, /*fillColor: '#000', 'map': map, fillOpacity: .8,*/ center: new google.maps.LatLng(dCoordLat, dCoordLon) }).getBounds());
	

	var lastEvent = new Date();
	var bFirstIdle = true;

	var oSearchText = jQuery('#search_status div.text');

	var mgr = new MarkerManager(map);
	google.maps.event.addListener(mgr, 'loaded', function () {
		var iCount = 0;
		var markers4 = [];
		var markers6 = [];
		var markers8 = [];
		for (var iStoreIndex in arrStores) {
			if (arrStores.hasOwnProperty(iStoreIndex)) {
				var currStore = arrStores[iStoreIndex]["store"];

				if (iCount < 40)
					markers4.push(createMarker(currStore["posn"], currStore["title"], currStore["content"]));
				if (iCount < 200)
					markers6.push(createMarker(currStore["posn"], currStore["title"], currStore["content"]));
				if (iCount < 2000)
					markers8.push(createMarker(currStore["posn"], currStore["title"], currStore["content"]));

				iCount++;
			}
		}
		mgr.addMarkers(markers4, 2);
		mgr.addMarkers(markers6, 5);
		mgr.addMarkers(markers8, 7);
		mgr.refresh();

		if (bAdjustableMap) {
			var listener = google.maps.event.addListener(map, 'bounds_changed', function () {
				if (bFirstIdle)
					bFirstIdle = false;
				else {
					//Listener activated
					hideFilters(true);
					expandSearchUpdateText(oSearchText, 'New search parameters detected...');

					lastEvent = new Date();
					setTimeout(function () { fireIfLastEvent() }, 2000);
				}
			});
		}
	});

	function createMarker(posn, title, con) {
		var infowindow = new google.maps.InfoWindow({
			content: con
			//pixelOffset: new google.maps.Size(0, 34),
			//,maxWidth: 160
		});

		var markerOptions = {
			position: posn,
			title: title,
			icon: sPathToRoot + 'ui/image/locations/smartstop_marker.png'
		};

		var marker = new google.maps.Marker(markerOptions);

//		google.maps.event.addListener(marker, 'click', function () {
//			infowindow.open(map, marker);
//		});
		return marker;
	}

	/* Map tweaks */
	function fireIfLastEvent() {
		if (lastEvent.getTime() + 1990 <= new Date().getTime()) {
			//alert(bHasDisVehicle);
			updateSearch('Submitting coordinates...', 'Update Complete', sPathToRoot, sUpdateUrl, sNumLocationsId, 0, false, false, checkIsOnVehicles(), null, sLblLocationId);
		}
	}
	/* End Map Tweaks */
}
function addStore(coords, content, title) {
	nStore = new Array();
	nStore["store"] = new Array();
	nStore["store"]["content"] = content;
	nStore["store"]["title"] = title;
	nStore["store"]["posn"] = new google.maps.LatLng(coords[0], coords[1]);
	return nStore;
}
function updateSearch(sUpdateText, sCompleteText, sPathToRoot, sUpdateUrl, sNumLocationsId, iPageIndex, bAllPages, bDoNotRefresh, bDisplayVehicles, sFilterKey, bRemoveFilterKey, sLblLocationId) {
	var oSearchText = jQuery('#search_status div.text');
	oSearchText.text(sUpdateText);

	//Trigger Loading
	hideFilters();
	jQuery('#search_loading').css({ opacity: 0, display: 'block', height: jQuery('#search_body').height() + 'px' }).stop().animate(
			{ opacity: .7 }, { duration: 800, complete: function () { oSearchText.text('Checking unit availability...'); } });

	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var center = map.getCenter();
	var sRequest = '<Request NorthEastLatitude="' + northEast.lat() +
					'" NorthEastLongitude="' + northEast.lng() +
					'" SouthWestLatitude="' + southWest.lat() +
					'" SouthWestLongitude="' + southWest.lng() +
					'" CenterOfMapLatitude="' + center.lat() +
					'" CenterOfMapLongitude="' + center.lng() +
					'" PathToRootOfWebSite="' + sPathToRoot;
	if (sFilterKey && sFilterKey.length > 0) {
		if (!bRemoveFilterKey)
			sRequest += '" AddFilterKey="' + sFilterKey;
		else
			sRequest += '" RemoveFilterKey="' + sFilterKey;
	}
	// include whether this is a state page
	sRequest += (jQuery('#lblStateAbbrev').length > 0) ? '" StateAbbrev="' + jQuery('#lblStateAbbrev').val() : '';
	sRequest += 
					((!bDoNotRefresh) ? '" ForceRefresh="true' : '') +
					((bAllPages) ? '" DisplayAll="true' : '') +
					((bDisplayVehicles) ? '" DisplayVehicles="true' : '') +
					'" PageIndex="' + ((iPageIndex) ? iPageIndex : 0) +
					'" />';
	//Bounds changed. update map
	//alert(sRequest);
	//Update Service
	jQuery.ajax({
		type: "POST",
		url: sUpdateUrl,
		data: { request: sRequest },
		dataType: "xml",
		error: function (jqXHR, textStatus, errorThrown) {
			//alert('ajax returned error');
		},
		success: function (xml) {
			//Check for handled error
			var oRespXml = jQuery(xml).find('Response');
			if (oRespXml.attr('Success').bool()) {

				var oResultsHtml = jQuery(xml).find('Results');
				if (sLblLocationId)
					jQuery('#' + sLblLocationId).text('');
				var oDisplayHtml = oResultsHtml.find('DisplayHtml');
				if (!bDoNotRefresh)
					oSearchText.text('Loading results...')
				if (oDisplayHtml != null) {
					//alert(sRequest);
					//alert('here');
					jQuery('#search_results .search_results_body').html(jQuery('<div />').html(oDisplayHtml.text()).text());
					//jQuery('#search_results').html('<pre>' + jQuery('<div />').text(oDisplayHtml.text()).html() + '</pre>');

					initResults(oResultsHtml.attr('NumSitesFound'), oResultsHtml.attr('NumSitesDisplayed'), oResultsHtml.attr('CurrentPageIndex'), oResultsHtml.attr('TotalPages'), sNumLocationsId, sPathToRoot, sUpdateUrl,
					oResultsHtml.attr('NumTotalUnitsFound'), oResultsHtml.attr('NumVehicleUnitsFound'), oResultsHtml.attr('DisplayingVehicles'));
				}
			}
			else {
				alert(oRespXml.find('Message').text());
			}

			jQuery('#search_loading').stop().animate(
					{ opacity: 0 }, { duration: 800, complete: function () {
						jQuery(this).css({ display: 'none' });
						oSearchText.text(sCompleteText).stop().animate(
							{ 'margin-left': '-300px' }, { duration: 1600 });
					}
					});
		}
	});
}
/* End Map */
//(iNumSitesFound, iNumSitesDisplayed, iCurrPageIndex, iTotalPages, sNumLocationsId) {
function checkIsOnVehicles() {
	return jQuery('#search_header .advanced .tabs ul li.vehicle').hasClass('on')
}
function hideFilters(bAlways) {
	if (bAlways)
		jQuery('#search_header .advanced .tab_overlay').css({ display: 'block' }).stop().animate({ opacity: .7 }, { duration: 700 }); ;
}
function revealFilters() {
	jQuery('#search_header .advanced .tab_overlay').css({ opacity: .7 }).stop().animate({ opacity: 0 }, { duration: 700, complete: function () { jQuery(this).css({ display: 'none' }); } });
}
function selectUnitViaXml(sPostUrl, xml) {
	hideFilters(true);
	jQuery('#search_loading').css({ opacity: 0, display: 'block', height: jQuery('#search_body').height() + 'px' }).stop().animate(
			{ opacity: .7 }, { duration: 800, complete: function () {  } });
	//expandSearchUpdateText(
	jQuery.ajax({
		type: "POST",
		url: sPostUrl,
		data: { request: '<Request><RequestXml><![CDATA[' + xml + ']]></RequestXml></Request>' },
		dataType: "xml",
		error: function (jqXHR, textStatus, errorThrown) {
			alert('ajax returned error');
		},
		success: function (xml) {
			processHandlerReturnXml(xml, function () {
				//Success
				//alert('success');
				shoppingcartRedirect();
			},
			function () {
				//Fail
				alert('An unexpected error occurred that prevented us from selecting the unit for you. Please try calling the store or try selecting a different unit from the list.');
				revealFilters();
				jQuery('#search_loading').stop().animate(
					{ opacity: 0 }, { duration: 800, complete: function () {
						jQuery(this).css({ display: 'none' });
						
					}
					});
			});
		}
	});
}
