// check the current protocol
function checkProto(){
	var current_proto = document.location.protocol;
	var proto = current_proto == "https:" ?  "https:" : "http:";
	return proto;
}
// globals
var protocol = checkProto();
var map,geocoder, home_latlng, home_address, home_icon, bounds_global, store_address_global, store_suburb_global, store_town_city_global, directions, polyline;
var marker = [];
var reasons = [];
var n=1;
var previous_address = "";
var anim_speed = 300;
var side_bar_html = "";
var legend_visible;
// filter arrays
var current_filter_params = new Array();
var previous_filter_params = new Array();
// account type array
var voda_store = new Array();
	voda_store[0] = "vodafoneretail";
	voda_store[1] = "firstmobile";
	voda_store[2] = "dswireless";
	voda_store[3] = "digitalmobile"; 
	       
var show_filters_clicked = false;
var show_animate = false;

// precache image icons
var home_marker_image = new Image();
home_marker_image.src = "/help/store-locations/img/home-marker.png";

var home_marker_shadow = new Image();
home_marker_shadow.src = "/help/store-locations/img/home-marker-shadow.png";

var voda_retail_image = new Image();
voda_retail_image.src = "/help/store-locations/img/vodafone-retail.png";     

var voda_retail_hover = new Image();
voda_retail_hover.src = "/help/store-locations/img/vodafone-retail-hover.png";  

var voda_retail_visited = new Image();
voda_retail_visited.src = "/help/store-locations/img/vodafone-retail-visited.png";  

var multi_retail_image = new Image();
multi_retail_image.src = "/help/store-locations/img/multi-retail.png";

var multi_retail_hover = new Image();
multi_retail_hover.src = "/help/store-locations/img/multi-retail-hover.png";  

var multi_retail_visited = new Image();
multi_retail_visited.src = "/help/store-locations/img/multi-retail-visited.png";  

var shop_marker_shadow = new Image();
shop_marker_shadow.src ="/help/store-locations/img/store-shadow.png"

// incrementer
function count(){
	n++;
	return n;
}

// remove custom error
function removeCustomError(){		
	$j("#custom_error").html("");
	$j("#custom_error").removeClass("inputErrMsg");
	if(legend_visible){
		$j("#legend").removeClass("hidden").addClass("show");
	}
	
}	
// write custom error
function writeCustomError(str){		
	$j("#custom_error").html(str);
	$j("#custom_error").addClass("inputErrMsg");
	$j("#custom_error").css({"margin":"0px"});
	if($j("#legend").hasClass("show")){
		$j("#legend").removeClass("show").addClass("hidden");
	}
}		

// get results from database (cross domain call)
function searchJsonLocations(data){	
	var radius = "";
	var services = "";
  // dev / prod ternary (point to stores.vfdev.co.nz in non prod env)
  var xhr_url = document.location.host == "www.vodafone.co.nz" ? "stores.vodafone.co.nz" : "stores.vfdev.co.nz";   
	
	$j('#storeLookup input:checkbox:checked').each(function(){
		var service = this.id;
		services += service+"=on&";	
	});
	// strip the last & off get string
	services = services.substring(0, services.length-1);	
	
	// do our cross domain json call          
	$j.ajax({
		dataType: 'jsonp',
		jsonp: 'storesJSONCallback',     
		url: protocol+'//'+xhr_url+'/includes/lookup-json.php?lat=' + data.lat() + '&lng=' + data.lng() + '&radius=' + radius + '&' + services
	});
}

// json calback   
function storesJSONCallback(data){		         
	var side_bar = document.getElementById("side_bar");
	side_bar_html = "";
	side_bar.innerHTML = '';
	map.clearOverlays();  
	
	if (data.no_results == "true"){			
		$j("#side_bar").css("display","none").css("left", "-200px");
		$j("#map").css("left","0px").css("width","760px");
		$j("#toggle_side_bar").css({backgroundImage: "URL(/help/store-locations/img/toggle-on.jpg)"}).css("display","none");   		
		show_animate = false;				
		$j("#indicator").removeClass("show").addClass("hidden");
		writeCustomError("Sorry, no results found");
		// check for map container resize 
		map.checkResize();
		// center the map
		map.setCenter(new GLatLng(-40.7, 172.2), 5);		
		return;
	}
	else{		
		var bounds = new GLatLngBounds();
		var lat;
		var lng;
		var count = 0;
		// create the home marker
		var home_marker = new GMarker(home_latlng, home_icon);
		map.addOverlay(home_marker);
		GEvent.addListener(home_marker, "click", function(){
			home_marker.openInfoWindowHtml("<strong>Your Location<\/strong><br \/>"+home_address);
		});	 	
		
		// iterate through the JSON
		$j.each(data.markers, function(marker){       
			name = data.markers[count].name;
		 
      var customer_facing_address = data.markers[count].customer_facing_address,
        mapping_address = data.markers[count].mapping_address,
        suburb = data.markers[count].suburb,
        town_city = data.markers[count].town_city,
        phone = data.markers[count].phone,
        fax = data.markers[count].fax,
        account = data.markers[count].account,
        distance = parseFloat(data.markers[count].distance);
		 
			Mo_O = data.markers[count].Monday_Open;
			Mo_C = data.markers[count].Monday_Closed;
			Tu_O = data.markers[count].Tuesday_Open;
			Tu_C = data.markers[count].Tuesday_Closed;
			We_O = data.markers[count].Wednesday_Open;
			We_C = data.markers[count].Wednesday_Closed;
			Th_O = data.markers[count].Thursday_Open;
			Th_C = data.markers[count].Thursday_Closed;
			Fr_O = data.markers[count].Friday_Open;
			Fr_C = data.markers[count].Friday_Closed;
			Sa_O = data.markers[count].Saturday_Open;
			Sa_C = data.markers[count].Saturday_Closed;
			Su_O = data.markers[count].Sunday_Open;
			Su_C = data.markers[count].Sunday_Closed;               
		 
			lat = parseFloat(data.markers[count].lat);
			lng = parseFloat(data.markers[count].lng);
			var point = new GLatLng(lat, lng);
					
			// generate HTML for the info window
			var info_window_html = infoWindowHtml(name, customer_facing_address, mapping_address, account, suburb, town_city, phone, fax, Mo_O, Mo_C, Tu_O, Tu_C, We_O, We_C, Th_O, Th_C, Fr_O, Fr_C, Sa_O, Sa_C, Su_O, Su_C, lat, lng);	
					
			// write the side_bars			
			side_bar_html = sideBarHtml(marker, name, customer_facing_address, phone, distance, count);		
			document.getElementById("side_bar").innerHTML = side_bar_html;		
			// place the markers       
			ZMarker(point, name, account, mapping_address, suburb, town_city, info_window_html, 1, 0, count, null);
			
			bounds.extend(point);
			count++;       
		});   
		
		// extend bounds and update global var
		bounds.extend(home_latlng);
		bounds_global = bounds;
		
		// display the side_bar 
		if(show_animate == false){
			animateSideBar();
		}// or hide the mask and indicator
		else{
			hideMask();
		}
	}
}

// unblock the ui, hide ajax indicator, display legend and center the map
function hideMask(){
	setTimeout(function(){		
	if($j("#indicator, #mask").hasClass("show")){    	
		$j("#indicator, #mask").removeClass("show").addClass("hidden");
	}
	if($j("#legend").hasClass("hidden")){	
		$j("#legend").removeClass("hidden").addClass("show"); 
		legend_visible = true;
	}}, anim_speed);	
	// check for map container resize 
	map.checkResize();
	// center the map
	map.setCenter(bounds_global.getCenter(), map.getBoundsZoomLevel(bounds_global));
}

// animate the side_bar
function animateSideBar(){ 
	if(show_animate == true){     
		$j("#side_bar").css("overflow", "hidden");    
		$j("#toggle_side_bar").css({backgroundImage: "URL(/help/store-locations/img/toggle-on.jpg)"});   
		$j("#side_bar").animate({
			left: -200
		}, anim_speed);         
		$j("#map").animate({
			left: 0,
			width: 760
		}, anim_speed);
		$j("#toggle_side_bar").animate({
			width: 27       
		}, anim_speed, "linear", hideMask);
		show_animate = false;
	}
	else{
		$j("#toggle_side_bar").css("display", "block");
		$j("#side_bar").css("overflow", "auto").css("display", "block");  
		$j("#toggle_side_bar").css({backgroundImage: "URL(/help/store-locations/img/toggle-off.jpg)"});   
		$j("#side_bar").animate({
			left: 0
		}, anim_speed);   
		$j("#map").animate({
			left: 200,
			width: 560
		}, anim_speed);
		$j("#toggle_side_bar").animate({
			width: 227			
		}, anim_speed, "linear", hideMask);
		show_animate = true;
	}	
}

// create HTML for store info window
function infoWindowHtml(store_name, customer_facing_address, mapping_address, account, suburb, town_city, phone, fax, Mo_O, Mo_C, Tu_O, Tu_C, We_O, We_C, Th_O, Th_C, Fr_O, Fr_C, Sa_O, Sa_C, Su_O, Su_C, lat, lng){
	var info_window_html = "";	
//	account = account.replace(/&\%/g,"");	
  // replace ampersands and percents
  account_img = account.replace(/&|%/g,"");	
  
  //if(account.indexOf())
  
  if(account.indexOf("unbranded") == -1){
    info_window_html += '<img height="37" width="100" src="\/help/store-locations\/img\/' + account_img + '.gif" alt="' + account + '"\/><br \/>'; 
  }
	info_window_html += '<strong>' + store_name + '<\/strong><br \/>' + customer_facing_address + ', '+suburb+'<br\/>';  
	
	if(phone != undefined){info_window_html += 'Ph: ' + phone + "<br/>";}
  if(fax != undefined){info_window_html += 'Fax: ' + fax + "<br/>";}   
  info_window_html += '<ul>';
	if(Mo_O != undefined){info_window_html += '<li>Monday: '+Mo_O+' - '+Mo_C+'<\/li>';}
	if(Tu_O != undefined){info_window_html += '<li>Tuesday: '+Tu_O+' - '+Tu_C+'<\/li>';}
	if(We_O != undefined){info_window_html += '<li>Wednesday: '+We_O+' - '+We_C+'<\/li>';}
	if(Th_O != undefined){info_window_html += '<li>Thursday: '+Th_O+' - '+Th_C+'<\/li>';}
	if(Fr_O != undefined){info_window_html += '<li>Friday: '+Fr_O+' - '+Fr_C+'<\/li>';}
	if(Sa_O != undefined){info_window_html += '<li>Saturday: '+Sa_O+' - '+Sa_C+'<\/li>';}
	if(Su_O != undefined){info_window_html += '<li>Sunday: '+Su_O+' - '+Su_C+'<\/li>';}
	info_window_html += '<\/ul>'; 
	// only if a street number is entered do we display directions link
	var street_number_in_address = /[0-9]{1,}/i.test(home_address);
	if(street_number_in_address){info_window_html += '<br \/><a href="#directions" class="getDirections">Get Directions<\/a>';}	
	return info_window_html;	
}

// create HTML for side bar
function sideBarHtml(marker, name, customer_facing_address, phone, distance, j){
	//var side_bar_html = "";
	side_bar_html += "<div class='side_bar_entry'";
	side_bar_html += "onclick='GEvent.trigger(marker["+j+"],\"click\")' ";
	side_bar_html += "onmouseover='GEvent.trigger(marker["+j+"],\"mouseover\")' ";
	side_bar_html += "onmouseout='GEvent.trigger(marker["+j+"],\"mouseout\")' ";
	side_bar_html += ">";
	side_bar_html += "<strong>"+name+"<\/strong><br \/>";
	side_bar_html += customer_facing_address+"<br \/>";
	side_bar_html += "<\/div>";	
	return side_bar_html;	
}

/*
 DIRECTIONS 
*/
// fired after infowindow is opened
function onInfoWindowOpen(){
	$j(".getDirections").click(function(){    
		// clear existing directions
		if(directions != null){directions.clear();}   
		// load directions - fn "onGDirectionsLoad" is fired after directions are loaded
		directions.load("from: "+home_address+", New Zealand to: "+mapping_address_global+", "+store_suburb_global+", "+store_town_city_global+", New Zealand", {
			getSteps: true,
			preserveViewport: true,
			getPolyline: true
			}, G_TRAVEL_MODE_DRIVING);						
		return false;
	});           
}

// fired after directions load - show polyline and direction instructions
function onGDirectionsLoad(){
  // remove existing polyline if present
  if(polyline != null){map.removeOverlay(polyline);} 
  polyline = directions.getPolyline();
  map.addOverlay(polyline); 
  $j("#directions_area").removeClass("hidden").addClass("show");
  directionsHTML(map,"map", directions, document.getElementById("directions"));
}

// error handling for directions
function handleErrors(){
	if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS){
		writeCustomError("No corresponding geographic location could be found for the specified address. This may be due to the fact that the address is relatively new, or it may be incorrect. Error code: " + directions.getStatus().code);
	}
	else if (directions.getStatus().code == G_GEO_SERVER_ERROR){
		writeCustomError("A geocoding request could not be successfully processed. The exact reason for the failure is not known. Error code: " + directions.getStatus().code);
	}
	else if (directions.getStatus().code == G_GEO_MISSING_QUERY){
		writeCustomError("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input. Error code: " + directions.getStatus().code);
	}	 
	else if (directions.getStatus().code == G_GEO_BAD_KEY){
		writeCustomError("The given key is either invalid or does not match the domain for which it was given. Error code: " + directions.getStatus().code);
	}
	else if (directions.getStatus().code == G_GEO_BAD_REQUEST){
		writeCustomError("A directions request could not be successfully parsed. Error code: " + directions.getStatus().code);
	}
	else{
		writeCustomError("Sorry, no results found");
	}
}

// ============ custom directions panel ===============
function directionsHTML(map, mapname, dirn, div) {
    var directions_html = "";
    // waypoint banner
    function waypoint(i, address) {
    	var state;
    	if(i == 0){state = "FROM"}
    	else{state = "TO"}
    	directions_html += "<div class=\"to_from\"><strong>"+state+":&nbsp;"+address+"<\/strong><\/div>";
    }
    // route distance
    function routeDistance(dist) {
        directions_html += "<div class=\"distance\">Approximate distance: "+dist+"<\/div>";
    }
    // step detail
    function detail(point, num, description, dist) {
    	directions_html += "<div class=\"step\"><strong>"+num+"<\/strong>&nbsp;&nbsp;&nbsp;"+description+"&nbsp;&nbsp;&nbsp;"+dist+"<\/div>";
    }
    // iterate through the GRoutes and GSteps
    for (var i=0; i<dirn.getNumRoutes(); i++) {
        var route = dirn.getRoute(i);
        var geocode = route.getStartGeocode();
        var point = route.getStep(0).getLatLng();
        // waypoint at the start of each GRoute
        waypoint(i, geocode.address);
        routeDistance(route.getDistance().html+" (about "+route.getDuration().html+")");

        for (var j=0; j<route.getNumSteps(); j++) {
            var step = route.getStep(j);
            // detail lines for each step
            detail(step.getLatLng(), j+1, step.getDescriptionHtml(), step.getDistance().html);
        }
    }
    // the final destination waypoint
    var geocode = route.getEndGeocode();
    var point = route.getEndLatLng();
    waypoint(point, geocode.address);                     
    // write to target div
    div.innerHTML = directions_html;

}
// ============ end of directionsHTML function ===========
// A special createZMarker function
// 'infowindowclose' listener is attached to marker
// It deletes the marker and creates a copy with lower z-index
// Feel free to use but please include:
// Originally created by Esa 2007
function ZMarker(point, name, account, mapping_address, suburb, town_city, info_window_html, n, imInd, i, visited) {
	
	function sendBack(marker,b) {
		return GOverlay.getZIndex(marker.getPoint().lat())-n*10000;
	}	
	var shop_icon = new GIcon();
	  for(x=0;x<voda_store.length;x++) {
			if (account == voda_store[x]) {
				shop_icon.image = voda_retail_image.src;
				shop_icon_hover = voda_retail_hover.src;
				shop_icon_visited = voda_retail_visited.src;
				break;				
			} else {
				shop_icon.image = multi_retail_image.src;
				shop_icon_hover = multi_retail_hover.src;
				shop_icon_visited = multi_retail_visited.src;				
			}
    }
  
	shop_icon.iconSize = new GSize(24, 24);
	shop_icon.shadow = shop_marker_shadow.src;
	shop_icon.shadowSize = new GSize(28, 28);
	shop_icon.iconAnchor = new GPoint(12, 12);
	shop_icon.infoWindowAnchor = new GPoint(22, 4);
    
	var markerImage = [
		shop_icon.image,
		shop_icon_hover,
		shop_icon_visited
	];			
		
	marker[i] = new GMarker(point,{title:name, icon:shop_icon, zIndexProcess:sendBack});
			
	map.addOverlay(marker[i]);	
	marker[i].setImage(markerImage[imInd]);	
	marker[i].visited = visited;

	GEvent.addListener(marker[i], "click", function() {
		marker[i].openInfoWindowHtml(info_window_html);
		marker[i].visited = true;		
		// set globals for directions
		mapping_address_global = mapping_address;
    store_suburb_global = suburb;
    store_town_city_global = town_city;		
		GEvent.trigger(marker[i],"mouseout");
	});
	
	GEvent.addListener(marker[i],'mouseover',function(){
		marker[i].setImage(markerImage[1]);
		document.getElementById("side_bar").getElementsByTagName("div")[i].style.background ="#efefef";
	});
	
	GEvent.addListener(marker[i],'mouseout',function(){
		if(marker[i].visited){
			marker[i].setImage(markerImage[2]);
			document.getElementById("side_bar").getElementsByTagName("div")[i].style.color ="gray";
		}
		else{
			marker[i].setImage(markerImage[0]);
			document.getElementById("side_bar").getElementsByTagName("div")[i].style.color ="black";
		}
		document.getElementById("side_bar").getElementsByTagName("div")[i].style.background ="#dadada";
	});

	GEvent.addListener(marker[i], "infowindowclose", function() {
		map.removeOverlay(marker[i]);
		ZMarker(point, name, account, mapping_address, suburb, town_city, info_window_html, count(), 2 ,i,marker[i].visited);		
	})
}

// animate the search filters
function animateFilters() {
	$j("#side_bar").css("overflow", "hidden");
	
	if(show_filters_clicked != true){
		$j("#toggle_filters").text("Hide filters");   
		$j("#filters").animate({
			height: 110
		}, anim_speed);    
		$j("#filters").children().css("display","block");
		show_filters_clicked = true;
	}
	else {
		$j("#toggle_filters").text("Show filters");
		$j("#filters").animate({
			height: 0
		}, anim_speed); 
		$j("#filters").children().css("display","none");
		show_filters_clicked = false;
	}	
	
	setTimeout(function(){
		$j("#side_bar").css("overflow", "auto"); 
	},anim_speed);
}

// build filter array - we block the geo-code if filters are same as last submit
function setFilterArray(array_name){
	var count = 0;
	$j("#filters input:checkbox").each(function(){
		var state = $j(this).attr("checked");
		array_name[count] = state;
		count++;
	});	
}

// array compare 
Array.prototype.compare = function(testArr) {
	if(this.length != testArr.length) return false;
	for(var i = 0; i < testArr.length; i++){
		if(this[i].compare){ 
			if(!this[i].compare(testArr[i])) return false;
		}
		if(this[i] !== testArr[i]) return false;
  }
  return true;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

function place(lat,lng, suggested_address) {
	if(suggested_address != null){
		$j("#addressInput").val(suggested_address);
		previous_address = suggested_address;
		}
	
	var latlng = new GLatLng(lat,lng);
	home_latlng = latlng;  
	$j("#suggestions_wrapper").removeClass("show").addClass("hidden"); 
	document.getElementById("suggestions").innerHTML = "";
	
	
	searchJsonLocations(latlng);
}
			
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// search for stores
function searchStores(){
	if($j("#directions_area").hasClass("show")){
		$j("#directions_area").removeClass("show").addClass("hidden");
	}
	home_address = $j("#addressInput").val();    		
		
	if(home_address != ""){		
		if($j("#overlay").hasClass("show")){
			$j("#overlay").removeClass("show").addClass("hidden");
		}
		
		setFilterArray(current_filter_params);
			
		if(previous_filter_params.length == 0){
			setFilterArray(previous_filter_params);
			}
		else{
			var filter_match = previous_filter_params.compare(current_filter_params);		
		}
		
		// if home address is the same and filters have changed since last submit		
		if(home_address != previous_address || filter_match != true){			
			// copy current filters to previous filters array
			previous_filter_params = current_filter_params.slice();
			previous_address = home_address;			
			
			var geocode_home_address = home_address+", New Zealand";
			
			//alert(geocode_home_address);
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////					
				geocoder.getLocations(geocode_home_address, function (result){
					map.clearOverlays(); 
					var suggestionsHtml = "";
					if (result.Status.code == G_GEO_SUCCESS) {
						// if there was more than one result
						if (result.Placemark.length > 1) { 
							// Loop through the results
							suggestionsHtml += "<ul class=\"link_list4Col\">";
							for (var i=0; i<result.Placemark.length; i++) {
								var p = result.Placemark[i].Point.coordinates;
								var r = result.Placemark[i].address;
								
								// heinous links!								
								suggestionsHtml += "<li>";
								suggestionsHtml += "<a class='btnPetrol' id='suggestions_"+[i]+"' href='#' onclick='javascript:place(" +p[1]+","+p[0]+",\""+result.Placemark[i].address+"\")'>"+ result.Placemark[i].address+"<\/a>";
								suggestionsHtml += "<\/li>";						
							}
							suggestionsHtml += "<\/ul>";
							document.getElementById("suggestions").innerHTML = suggestionsHtml;
							$j("#suggestions_wrapper").removeClass("hidden").addClass("show");
						}
						// if there was a single result
						else {
							document.getElementById("suggestions").innerHTML = "";
							var p = result.Placemark[0].Point.coordinates;
							place(p[1],p[0], null);
						}
					}
					// error status
					else {
						var reason="Code "+result.Status.code;
						if (reasons[result.Status.code]) {
							reason = reasons[result.Status.code]
						} 
						$j("#indicator").removeClass("show").addClass("hidden");
						writeCustomError("Could not find&nbsp;"+geocode_home_address+"&nbsp;"+reason);							
					}
				});
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////				
			// block the ui and display ajax indicator       	
			$j("#indicator, #mask").removeClass("hidden").addClass("show");
		}
		else{
			writeCustomError(previous_address+"&nbsp;has already been searched for. Please enter another address or change your search filters");							
			return false;   	
		}
	}
	// stop form submission
	else{
		// validate the form field (use 1st index[0] to get the HTMLobject) - referenced from /js/form-validator.js
		VFNZform_validator.validate().checkError($j("#addressInput")[0]);
		return false;   
	}	
	
	return false;   
	//
}
// init map, controls, events
function initialise(){
	// create the map instance         
	if (GBrowserIsCompatible()){
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(-40.7, 172.2), 5);  
		map.enableScrollWheelZoom();		
		geocoder = new GClientGeocoder();      
		// create custom home marker icon
		home_icon = new GIcon();
		home_icon.image = home_marker_image.src;
		home_icon.shadow = home_marker_shadow.src;
		home_icon.iconSize = new GSize(32, 32);
		home_icon.shadowSize = new GSize(59, 32);
		home_icon.iconAnchor = new GPoint(25, 20);
		home_icon.infoWindowAnchor = new GPoint(31, 8);     
		// create new directions object
		directions = new GDirections();  
		// globally registered events
		GEvent.addListener(directions, "load", onGDirectionsLoad);
		GEvent.addListener(directions, "error", handleErrors);
		GEvent.addListener(map, "infowindowopen", onInfoWindowOpen);
	}   	
}

// DOM ready
$j(document).ready(function(){      	
	initialise();
	// reset filter checkboxes
	$j('#storeLookup input:checkbox:checked').each(function(){
		//this.checked = false;
		$j(this).removeAttr("checked");
	});
	// show/hide search filters   
	$j("#toggle_filters").click(function(){                     
		animateFilters();
		return false;
	});             
	//toggle side_bar
	$j("#toggle_side_bar").click(function(){
		animateSideBar();
		return false;
	});
	// clear custom error on field click
	// $j(input).click(function(){  
  $j('#addressInput').parents('.modBody').find('input').click(function(){  
		// remove validation error (use 1st index[0] to get the HTMLobject)	- referenced from /js/form-validator.js
		// VFNZform_validator.validate().removeError($j("#addressInput")[0]);
    vfnz.formValidator.reset();
		// remove custom error
		removeCustomError();
	});   
	// submit address search
	// hit enter
	$j('#addressInput').keydown(function(e){
    if(e.keyCode == 13){
    	searchStores();
    	return false;
    }		
  });
	// click submit
	$j("#addressSearch").click(function(){
		searchStores();
		return false;
	});	
	
  // filter deep link e.g append #homephonewireless to URL
  if(document.location.hash.toLowerCase() !== ""){
    
    // split location.hash on the '#'
    var hash = document.location.hash.toLowerCase().split("#");     
    // if / else - temporary deep link for earthquake response
    if(hash[1] === 'christchurch'){
      $j("#addressInput").val('Christchurch');  
      $j("#addressSearch").click();  
    } else {       
      $j("#filters input").each(function(){      
        // used to match location.hash format (lowercase, no underscores)
        var el_id = $j(this).attr("id").toLowerCase().replace(/_/g, "");      
        
        // if location.hash contains el_id, animate filters, check the checkbox and focus address field
        if(el_id.indexOf(hash[1]) !== -1){           
          animateFilters();                 
          $j(this).attr('checked', true);
          $j("#addressInput").focus();		
        }      
      });
    }  
  }
  
});

// unload to prevent memory leaks
$j(window).unload(function(){
	GUnload();
});


