/*
==============================================================
(C) 2012 Luxottica Retail Australia Pty Ltd
==============================================================
*/

/* See more locations Function Starts Here*/
	var loadingicon = '<span class="loading-img" style="position:relative; top:300px;"><img src="/wcsstore/OPSMStorefrontAssetStore/images/loading.gif"></span>',
		pageHeight = $(document).height();

$(document).ready(function () {

	//------------------------------------------------------------
	// FIND IN STORE AND INACTIVE BUTTON CLICK RIGHT ARROW DISPLAY
	//------------------------------------------------------------	
	$('.find-in-store-new .search-by .left button').click(function(){		
        var itemSelected = $(this).attr('data-item');                            
        $(this).parent().children().not(this).removeClass('arrow_box');                           
        $(this).addClass('arrow_box');        
        if(itemSelected == 'postcode') {
            $('.find-in-store-new .search-by .right .postcode-form').removeClass('hide');
            $('.find-in-store-new .search-by .right .town-suburb-form').addClass('hide');
        }else {
            $('.find-in-store-new .search-by .right .postcode-form').addClass('hide');
            $('.find-in-store-new .search-by .right .town-suburb-form').removeClass('hide');
            $('.find-in-store-new .search-by .right .town-suburb-form').removeClass('non-visible');
        }
    });
	
	  if( $('#townSuburb').length && $('#townSuburb').val() != '') {    	
	    	$('.find-in-store-new .search-by .left button').eq(1).trigger('click');        
	    }else {    	
	    	$('.find-in-store-new .search-by .left button').first().trigger('click');
	    }
   
	//-------------------------------------------------------------
    
	//------------------------------------------------------
	// Email Friend overlay -------------------
	//------------------------------------------------------
	$(".email").click(function (e) {
			e.preventDefault();
			var greyoutHeight = $(document).height(),
			wHeight = $(window).height()/2;
			var offset;
			if (self.pageYOffset) {
				offset = self.pageYOffset;
		    } else if (document.documentElement && document.documentElement.scrollTop) {
				offset = document.documentElement.scrollTop;
		    } else if (document.body) {// all other Explorers
		    	offset = document.body.scrollTop;
		    }
			$('.form-error-message.visible').removeClass('visible');
			$('#modal-greyout').css('height',greyoutHeight+70+'px');
			$('#modal-greyout, #share-direction-modal').removeClass('hide');
			var mHeight = $('#share-direction-modal .modal-container').height();
			$('#share-direction-modal').css("top",offset + mHeight/2 +'px');
			$('#mapInstrn').val( $('.resultsContent').html());
			//var personalmsg  = $("#personal-msg-textarea").text();
			//$("#your-message").val(personalmsg);
			callAnalyticsForError("Sharing", "Email", "GetDirectionsModal", "", "", "Email_GetDirections");
	});

	//------------------------------------------------------
	//------------------------------------------------------
	// EMAIL FRIEND POST...
//		$("#share-directions-form .submit").die('click').click(('click',function (e) {
//			e.preventDefault();
//			var sform = $(this).closest('form');
//			var isFormDataValid = true;
//			if($.browser.msie){
//				sform.find("input[required='']").each(function(){
//					if ($(this).attr('placeholder') == $(this).val()){
//						e.preventDefault();
//						isFormDataValid = false;
//					}
//				});
//			}
//			if(isFormDataValid){
//				$('#share-directions-form').h5Validate();
//
//				var data = $("#share-directions-form").serialize();
//
//				if($('#share-directions-form').h5Validate('allValid')) {
//					$.post("SendEmail", data, function () {
//						$("#share-directions-form, .share-Favourites").addClass("hide");
//						$("#send-directions-success").removeClass("hide");
//					},
//					"json" );
//					callAnalyticsForError("Sharing", "EmailConfirmation", "GetDirectionsModal", "", "ShareSocial", "");
//				}else{
//					callAnalyticsForError("Sharing", "Email", "GetDirectionsModal", "ValidationError", "", "Email_GetDirections");
//				}
//			}else{
//				callAnalyticsForError("Sharing", "Email", "GetDirectionsModal", "ValidationError", "", "Email_GetDirections");
//			}
//
//		});
		$('#share-direction-modal .close').click(function (e) {
			e.preventDefault();
			$("#share-direction-modal :input:not(:hidden, :submit)").val('');
			$("#share-directions-form input, #share-directions-form textarea").removeClass('error');
			$("#share-directions-form .form-error-message").removeAttr('style');
			$("#share-directions-form, .share-Favourites").removeClass("hide");
			$('#modal-greyout, #share-direction-modal').addClass('hide');
			$("#send-directions-success").addClass("hide");
		});


	/* initializes the store results pagination - START */

		var visible = 0,lis = '', max = 0;
		if($("#search-store-modal").length == 0) {
			initializeStoreList();
		}
	/* initializes the store results pagination - END */

	var nameOfPage = "";
	if(isAnalyticsEnabled){
		var nameOfPage = utag_data.pageName;
	}
	
	$('#more').click('click', function (e) { //.live('click', function (e) {
		callAnalyticsForClick('prop2', '', '', '', '', '', '', '', '', '', 'o', 'General|SeeMoreStores', nameOfPage);
		e.preventDefault();
		showUpToIndex();
	});

	/* Search term value adjust Starts Here */
	$(".search-term").each(function () {
		var getValue = $(this).val();
		$(this).focus(function () {
			$(this).val('');
		});
	});

	/* Blur text function Starts Here */
	$(this).blur(function () {
	//	$(this).val(getValue);
	});
	/* Blur text function Ends Here */

    
    $('#postCode, #zipCode').keyup(function () { 
	    this.value = this.value.replace(/[^a-zA-Z0-9.]/g,'');
	});
    /*----------------------------------------------------------------*/
	

	/* Overlay function for Book Eye Test Starts Here */
	$('.show-overlay-storeloc').click(function (e) {
		e.preventDefault();
		var storeLocId = $(this).attr("rel");
		$.ajax({
			url:"BookEyeTestOverlayView?storeLocId="+storeLocId+"&storeId="+ $('#storeId').val()+"&langId="+$('#langId').val(),
			success:function (result) {
				$(".overlay-panel").html(result);
			},
			error: function (xhr, ajaxOptions, thrownError) {
				$(".overlay-panel").html('Error');
			}
		});
		var id = '#'+$(this).data('overlay'),
			pageHeight = $(document).height();
		var offset;
		if (self.pageYOffset) {
			offset = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			offset = document.documentElement.scrollTop;
		} else if (document.body) {// all other Explorers
			offset = document.body.scrollTop;
		}


		$('#modal-greyout, '+id).removeClass('hide');
		$('#modal-greyout').css('height', pageHeight);
		$(id).css("top", offset+100+'px');
		$(id+' .close').data('overlay', id);
	});
	/* Overlay function for Book Eye Test Ends Here */

	/* Overlay function for Opening hours Starts Here */
	$('.show-overlay-storeloc-opening, .show-overlay-storeloc-opening1').click(function (e) {
		e.preventDefault();
		
		callAnalyticsForClick('prop2', '', '', '', '', '', '', '', '', '', 'o', 'General|OpeningHours', nameOfPage);
		
		var storeLocId = $(this).attr("rel");
		var fromPage = $(this).attr("id");
		var id = '#'+$(this).data('overlay'),
			pageHeight = $(document).height(),
			wHeight = $(window).height();
		var offset;
		if (self.pageYOffset) {
			offset = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			offset = document.documentElement.scrollTop;
		} else if (document.body) {// all other Explorers
			offset = document.body.scrollTop;
		}
		
		if($("#secondOverlayFlag").val() == 'true') {
			loadModelGreyOut2(this);
		}
		$(id).html(loadingicon).removeClass('hide');

		$.ajax({
			url:"BookEyeTestOverlayView?storeLocId="+storeLocId+"&storeId="+ $('#storeId').val()+"&langId="+$('#langId').val()+"&address="+$('#searchAddress').val()+"&fromPage="+fromPage,
			success:function (result) {
				$(".overlay-panel").html(result).css('top',offset + 10 +'px');
			},
			error: function (xhr, ajaxOptions, thrownError) {
				$(".overlay-panel").html('Error');
			}
		});
		var offset;
		if (self.pageYOffset) {
			offset = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			offset = document.documentElement.scrollTop;
		} else if (document.body) {// all other Explorers
			offset = document.body.scrollTop;
		}

		$('#modal-greyout').removeClass('hide');
		if($(id).parent().is('#quick-view-modal')) {
			$(id).css('top','130px');
		}else{
			$(id).css('top',offset + 100 +'px');
		}
		$('#modal-greyout').css('height', pageHeight +70+'px');
		$(id+' .close').data('overlay', id);
		callAnalytics("Common", "StoreLocator", "OpeningTimesModal", "");
	});
	/* Overlay function for Opening hours Ends Here */

	/* Overlay function for Eye test services Starts Here */
	$('.show-overlay-storeloc-eyetestservices,.show-overlay-storeloc-eyetestservices1').click(function (e) {
		e.preventDefault();
		
		callAnalyticsForClick('prop2', '', '', '', '', '', '', '', '', '', 'o', 'General|EyeTestServices', nameOfPage);
		
		var storeLocId = $(this).attr("rel");
		var fromPage = $(this).attr("id");
		var id = '#'+$(this).data('overlay'),
		pageHeight = $(document).height(),
		wHeight = $(window).height();
		var offset;
		if (self.pageYOffset) {
			offset = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			offset = document.documentElement.scrollTop;
		} else if (document.body) {// all other Explorers
			offset = document.body.scrollTop;
		}

		if($("#secondOverlayFlag").val() == 'true') {
			loadModelGreyOut2(this);
		}
		$(id).html(loadingicon).removeClass('hide');

		$.ajax({
			url:"BookEyeTestOverlayView?storeLocId="+storeLocId+"&storeId="+ $('#storeId').val()+"&langId="+$('#langId').val()+"&address="+$('#searchAddress').val()+"&fromPage="+fromPage,
			success:function (result) {
				$(".overlay-panel").html(result).css('top',offset + 10 +'px');
			},
			error: function (xhr, ajaxOptions, thrownError) {
				$(".overlay-panel").html('Error');
			}
		});
		var offset;
		if (self.pageYOffset) {
			offset = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			offset = document.documentElement.scrollTop;
		} else if (document.body) {// all other Explorers
			offset = document.body.scrollTop;
		}

		$('#modal-greyout').removeClass('hide');
		if($(id).parent().is('#quick-view-modal')) {
			$(id).css('top','130px');
		}else{
			$(id).css('top',offset + 100 +'px');
		}
		$('#modal-greyout').css('height', pageHeight +70+'px');
		$(id+' .close').data('overlay', id);
		callAnalytics("Common", "StoreLocator", "EyeTestServicesModal", "");
	});
	/* Overlay function for Eye test services Ends Here */

	/* Added for showing add stores to account overlay after sign in. */
	if(typeof(storeLocIdAfterSignIn) !== 'undefined' && storeLocIdAfterSignIn != null && storeLocIdAfterSignIn != '') {
		//The below commented code is causing an extra greyout which blocks user from adding the store.
		//loadModelGreyOut2(this);
		showAddToStoreOverlay(storeLocIdAfterSignIn);
	}
	/* Overlay function for Add to my stores Starts Here */
	$('.locations .add-my-stores').click(function (e) {
		e.preventDefault();
		//callAnalyticsForClick('prop2', '', '', '', '', '', '', '', '', '', 'o', 'General|AddToMyStores', nameOfPage);
		var storeLocId = $(this).closest("[data-store-id]").data("store-id");
		if($("#secondOverlayFlag").val() == 'true') {
			loadModelGreyOut2(this);
		}
		showAddToStoreOverlay(storeLocId);
	});
	/* Overlay function for Add to my stores Ends Here */

	/* Add to my stores submit section Starts Here */
	$(".addToListsubmit").unbind('click').click(function (e) {
		e.preventDefault();
		
		var param ={};
		var options = $(".locations").data("my-stores");
		var storeLocId = $(this).attr("rel");
		param.storeLocId = storeLocId;
		param.storeID = options.storeID,
		param.langID = options.langID,
		param.notFirstStore = options.notFirstStore,
		param.addedStores = options.addedStores,
		param.maxStores = options.maxStores,
		param.redirectBackUrl = escape(options.redirectBackURL);
		param.searchAddress = $('.location-search input[type="text"]').val();
		param.storeNickName =$("#storeNickName_"+storeLocId).val();
		param.nickName=$("#storeNickName_"+storeLocId).val();
		var noOfFavStores = $("#noOfFavStores").val();
		
		/*if(noOfFavStores>3){
			$('.store-add-err').show();
			$('html, body').animate({
				scrollTop: $('.store-add-err').offset().top - 110
			}, 800);
			return;
		}*/ /** OOC-1849 **/
		param.redirectPage=$("#redirectPage").val();
		param.data = $("#AddStoreToMyList").serialize();
		var addUrl = "PreferredStoreUpdateCmd";
		
		$.ajax({
			type: "GET",
			url: addUrl,
			data: param,
			success: function (result) {
				//Action on success
				var noOfStores = parseInt(noOfFavStores)+1;
				$("#noOfFavStores").val(noOfStores);
				//var aft = $("a[rel="+param.storeLocId+"]").parents(".links");
				//$("<p class='confirm'>Added to your stores</p>").insertAfter(aft);
				$("a[rel="+param.storeLocId+"]").parent().find(".addMyStoreMessage").html("Added to your stores!");
				//$("a[rel="+param.storeLocId+"]").parents(".store-location:first-child").find(".icon-store").addClass("store-preferred favourite")
				//$("a[rel="+param.storeLocId+"]").parent().parent().parent().find(".select-store--item--marker > .number").addClass("favourite-store-item")
				//$("a[rel="+param.storeLocId+"]").parents(".links").remove();
				$("a[rel="+param.storeLocId+"]").remove();
				//$("#overlay_panel_services").html(result);
				//callAnalytics("Common", "StoreLocator", "AddStore_ThankYouModal", "");
			},
			error: function (data) {
				//Action on failure
				//$("#overlay_panel_services").html('Error');
				$("a[rel="+param.storeLocId+"]").parent().find(".addMyStoreMessage").html("An error has occurred.");
			}
		});
		let map;

		
		initMap();
	});
	
	/* Add to my stores submit section Ends Here */

	/* preferred store set section Starts Here */
	$('#prefCheck').unbind('click').click(function (e) {
		if (!$(this).is(':checked')) {
			$('#isPreferredStore').val('false');
		}
		else {
			$('#isPreferredStore').val('true');
		}
	});
	/* preferred store set section Ends Here */

	$('.close').click(function (e) {
		e.preventDefault();
		var id = $(this).data('overlay');
		$('#modal-greyout, '+id).addClass('hide');

	});

	
//	$(".tealium-get-directions").click(function (e) {
//		callAnalyticsForClick('prop2', '', '', '', '', '', '', '', '', '', 'o', 'General|GetDirectionsPage', nameOfPage);
//	});
//	
//	$(".tealium-book-eyetest").click(function (e) {
//		callAnalyticsForClick('prop2,eVar8,events', '', '', 'FindStore', '', '', '', '', '', '', 'o', 'BookEyeTest', nameOfPage);
//	});
//	
//	$(".tealium-select-store").click(function (e) {
//		callAnalyticsForClick('prop2,eVar8,events', 'event8,event9', '', 'FindStore', '', '', '', '', '', '', 'o', 'BookEyeTest', nameOfPage);
//	});
//	
//	$(".tealium-add-store-signin").click(function (e) {
//		callAnalyticsForClick('prop2', '', '', '', '', '', '', '', '', '', 'o', 'SignIn', nameOfPage);
//	});
//	
//	$(".tealium-add-store-register").click(function (e) {
//		callAnalyticsForClick('prop2', '', '', '', '', '', '', '', '', '', 'o', 'Register', nameOfPage);
//	});
//	
//	$(".tealium-add-store-signinorregister").click(function (e) {
//		callAnalyticsForClick('prop2', '', '', '', '', '', '', '', '', '', 'o', 'SignInOrRegister', nameOfPage);
//	});
//	
//	$(".tealium-eyetests-change-location").click(function (e) {
//		callAnalyticsForClick('prop2', '', '', '', '', '', '', '', '', '', 'o', 'ChangeLocation', nameOfPage);
//	});
//	
//	$(".tealium-eyetests-select-one").click(function (e) {
//		callAnalyticsForClick('prop2', '', '', '', '', '', '', '', '', '', 'o', 'SelectAnEyeTest', nameOfPage);
//	});
//	
//	$(".tealium-eyetests-expand-eyetest").click(function (e) {
//		var eyeTest = $(this).attr('rel');
//		callAnalyticsForClick('prop2', '', '', '', '', '', '', '', '', '', 'o', 'Accordian|'+eyeTest, nameOfPage);
//	});
	/*$(".tealium-catalog-facet").click(function (e) {
		callAnalyticsForClick('prop2', '', '', '', '', '', '', '', '', '', 'o', 'FacetSearch',nameOfPage);
	});*/
	//------------------------------------------------------
	// Find in store search results overlay ------------------------------
	//------------------------------------------------------
	$(".find-in-store-search-btn").click(function (e) {
			e.preventDefault();

			var searchLink = $(this);
			findInStoreSearch(searchLink);

	});
	//Added for Enter key press.
	$('#searchAddress').keypress(function (event) {
		if(event.which == '13') {
			var searchLink = $(this).parent().find('.find-in-store-search-btn');
			findInStoreSearch(searchLink);
		}
	});

	/* Below code is intended for flexible map to be shown on scroll. Begins Here*/

	$(window).scroll(function () {
		var mapTopPosition;
		if($('#mapTopPosition').length > 0) {
			mapTopPosition = parseInt($('#mapTopPosition').val());
		}else{
			var mheight = $('#find-in-store-modal').css('top');
			mapTopPosition = parseInt(mheight) + 300; 
		}
		var offset = $(window).scrollTop(),
		laside = $('.displayLocations .leftAside').height(),
		raside = $('.displayLocations .rightAside').height(),
		maxHt = mapTopPosition + (laside - raside),
		dif = laside - raside;
		if($('.displayLocations .rightAside').length) {
			if (offset < mapTopPosition || dif < 0) {
				$('.displayLocations .rightAside').removeClass('fixed-map').css('top','0px');
			}
			else if (offset > mapTopPosition && offset < maxHt) {
				$('.displayLocations .rightAside').addClass('fixed-map').css('top','0px');
			}else{
				$('.displayLocations .rightAside').removeClass('fixed-map').css('top',laside - raside);
			}
		}
	});

	/* Above code is intended for flexible map to be shown on scroll. Ends Here*/
	
	/* Overlay function for Add to my stores Starts Here - Restored from previous live site */
	$('.show-overlay-storeloc-addstore, .show-overlay-storeloc-addstore1').click(function (e) {
		e.preventDefault();
		callAnalyticsForClick('prop2', '', '', '', '', '', '', '', '', '', 'o', 'General|AddToMyStores', nameOfPage);
		var storeLocId = $(this).attr("rel");
		if($("#secondOverlayFlag").val() == 'true') {
		loadModelGreyOut2(this);
		}
		showAddToStoreOverlay(storeLocId);
	});

	if($(window).width() > 992 && $("body").hasClass('pg-book-eye-test') && $(".select-store--list").length == 0) {
		initMapBaetBeforeResults();
	} else if ($("body").hasClass('pg-book-eye-test') && $(".select-store--list").length == 0){
		$(".select-store--maps").addClass('d-none');
	}		
});

// Function that initializes the map showing 
function initMapBaetBeforeResults() {
	var mapLat, mapLng, mapZoom;
	if(window.countryCode == "AU") {
		mapLat = "-28.000"; 
		mapLng = "135.000";
		mapZoom = "5";
	} else {
		mapLat = "-41.400"; 
		mapLng = "173.000";
		mapZoom = "6";
	}
	//map = new google.maps.Map(document.getElementById("map"), mapOptionsDefault);
	$(".select-store--maps").html('<img class="d-lg-block d-none" src="http://maps.googleapis.com/maps/api/staticmap?center='+mapLat+','+mapLng+'&zoom='+mapZoom+'&size=1300x910&key='+opsm.core.getGoogleMapsApiKey()+'">');
}

/* Added function for showing add stores to account overlay or error message. */
function showAddToStoreOverlay(storeLocId) {
	var options = $(".locations").data("my-stores");
	var storeID = options.storeID,
		langID = options.langID,
		notFirstStore = options.notFirstStore,
		addedStores = options.addedStores,
		maxStores = options.maxStores,
		redirectBackURL = escape(options.redirectBackURL)
	;
	if (addedStores < maxStores) {
		var id = '#overlay_panel_services',
			pageHeight = $(document).height(),
			wHeight = $(window).height()
		;
		var offset;
		if (self.pageYOffset) {
			offset = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			offset = document.documentElement.scrollTop;
		} else if (document.body) {// all other Explorers
			offset = document.body.scrollTop;
		}
		$(id).html(loadingicon).removeClass('hide');
		$.ajax({
			url : "AddToMyStoresOverlayView?storeLocId=" + storeLocId + "&storeId="+ storeID + "&langId=" + langID + "&notFirstStore=" + notFirstStore + "&searchAddress=" + escape($('.location-search input[type="text"]').val()) + "&redirectBackUrl=" + redirectBackURL,
			success : function (result) {
				$(".overlay-panel").html(result).css('top', offset + wHeight / 2 - 100 + 'px');
			},
			error: function (xhr, ajaxOptions, thrownError) {
				$(".overlay-panel").html('Error');
			}
		});
		var offset;
		if (self.pageYOffset) {
			offset = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			offset = document.documentElement.scrollTop;
		} else if (document.body) {// all other Explorers
			offset = document.body.scrollTop;
		}
		var mHeight = $('#error-modal .modal-container').height();
		$('#modal-greyout').removeClass('hide');
		if ($(id).parent().is('#quick-view-modal')) {
			$(id).css('top', '130px');
		}else{
			$(id).css('top', offset + 100 + 'px');
		}
		$('#modal-greyout').css('height', pageHeight + 70 + 'px');
		$(id + ' .close').data('overlay', id);
		if (isGuestUser == 'false') {
			callAnalytics("Common", "StoreLocator", "AddStore_DefineNickNameModal", "");
		} else {
			callAnalytics("Common", "StoreLocator", "AddStore_SignInPromptModal", "");
		}
	} else {
		 var greyoutHeight = $(document).height(),
			wHeight = $(window).height() / 2;
		var offset;
		if (self.pageYOffset) {
			offset = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			offset = document.documentElement.scrollTop;
		} else if (document.body) {// all other Explorers
			offset = document.body.scrollTop;
		}
		var mHeight = $('#error-modal .modal-container').height();
		$('#modal-greyout, #error-modal').removeClass('hide');
		if ($(id).parent().is('#quick-view-modal')) {
			$(id).css('top', '130px');
		} else {
			$(id).css('top', offset + 100 + 'px');
		}
		$('#modal-greyout').css('height', greyoutHeight + 70 + 'px');
		$('#error-modal').css('top', offset + wHeight - mHeight + 'px');
		callAnalyticsForError("Common", "StoreLocator", "ErrorModal", "MoreThan4PrefStore", "", "");
	}
}


/* --------------------- GET DIRECTIONS START ----------------------- */

// Form

var storeInfo = {};

$("#GetDirectionSubmit").bind('click',function (e) {

	e.preventDefault();
	callAnalyticsForClick('prop2', '', '', '', '', '', '', '', '', '', 'o', 'General|GetDirection', utag_data.pageName);
	var nz = $('.getDirectionPage');
	var st = $('#street').val() == $('#street').attr('placeholder') ? '' : $('#street').val()+'';
	var twn = $('#town').val() == $('#town').attr('placeholder') ? '' : $('#town').val()+'';
	var pst = $('#postcode').val() == $('#postcode').attr('placeholder') ? '' : $('#postcode').val()+'';
	var state = $('.state select').val() == 'Select' ? '' : $('.state select').val()+'';

	var query = "";
	// State wont be available for NZ
	if(trim(state)!= 'undefined'){
		query = st+' '+twn+' '+state+' '+pst+' ';
	}else{
		query = st+' '+twn+' '+pst+' ';
	}
	
	if(trim(query).length == 0) {
		//$('.form-error-message').removeClass('visible');
		if($('.addressPH').length >0){
			$('.addressPH').html(trim(query));
		}
		$('.form-error-message.no-location-match').removeClass('hide').addClass('visible');
		
		callAnalyticsForError("Common", "StoreLocator", "GetDirections", "ValidationError", "", "");
	} else {
		initMap();
		calcRoute(query, false);
	}

});

if($('.getDirectionContainer').length||$('.directionResultsBot').length){
	// Direction map vars
	var dirMap;
	var directionsDisplay;
	var directionsService = new google.maps.DirectionsService();

	// Direction marker vars
	var markerA;
	var markerB;
	
}

// Clear direction markers on refresh
function clearMarkers() {
	markerA.setMap(null);
	markerB.setMap(null);
}

function initMap() {

	directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true});

	var mapOptions = {
		zoom: 8,
		//center: new google.maps.LatLng(startLongLat[0], startLongLat[1]),
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};

	// Not implemented??
	//if(mapImage) {
	/* unhide the map area before before displaying the map , else it wont be centered */
	$('.displayLocations').removeClass('hide');
	
	
	dirMap = new google.maps.Map(document.getElementById("rightAsideMap"), mapOptions);

	directionsDisplay.setMap(dirMap);
	directionsDisplay.setPanel(document.getElementById("directionsPanel"));
	//}
}

// Set direction (A&B) markers
function setMarker(pinUrl, LatLng) {

	var pinEv = "new google.maps.MarkerImage(pinUrl,\
			new google.maps.Size(40, 50),\
			new google.maps.Point(0, 0),\
			new google.maps.Point(20, 45));";

	var shadow = new google.maps.MarkerImage($('#assetsDirectory').val()+'images/storelocator/map_pin_shadow.png',
		new google.maps.Size(40, 50),
		new google.maps.Point(0,0),
		new google.maps.Point(20, 45));

	var shape = {
		coord: [1, 1, 1, 40, 40, 50, 40, 1],
		type: 'poly'
	};

	return new google.maps.Marker({
		map:dirMap,
		position:LatLng,
		shadow:shadow,
		icon:eval(pinEv),
		shape:shape
	});
}


// Find directions
function calcRoute(query, print) {

	var startLocation;
	var endLocation;
	var startLatLng ;

	if(!print) {

		startLocation = getGeoCoords(query);
		startLatLng = new google.maps.LatLng(startLocation[0],startLocation[1]);
		endLocation = new google.maps.LatLng($('#destinationLatitude').val(), $('#destinationLongitude').val());

		/* For share directions **/
		$('#srcLatitude').val(startLocation[0]);
		$('#srcLongitude').val(startLocation[1]);

	} else {

		startLocation = [query.startLat, query.startLon];
		startLatLng = new google.maps.LatLng(startLocation[0],startLocation[1]);
		endLocation = new google.maps.LatLng(query.endLat, query.endLon);

		query = query.address;

	}
	
	var destinationAdd = $('#add1').html()+' '+ $('#add2').html()+' '+$('#add3').html()+' '+$('#add4').html();
	
	/* Append src latlong to print href . Image url wil be build post 'loadGoogleMap' call */
	var printLink = $('#StoreDirectionsPrintURL').val()+"&srcLatitude="+startLocation[0]+"&srcLongitude="+startLocation[1]+"&startAddress="+query;
	$('a.print').attr("href", printLink );

	var request = {
		origin:startLatLng,
		destination:endLocation,
		travelMode:google.maps.TravelMode.DRIVING,
		unitSystem: google.maps.UnitSystem.METRIC
	};

	directionsService.route(request, function (result, status) {
		if (status == google.maps.DirectionsStatus.OK) {

			$('.form-error-message.no-location-match').removeClass('visible').addClass('hide');
			
			directionsDisplay.setDirections(result);

			if(markerB && markerA) clearMarkers();
			
			markerB = setMarker($('#assetsDirectory').val()+'images/storelocator/map_pin_b.png', endLocation);
			markerA = setMarker($('#assetsDirectory').val()+'images/storelocator/map_pin_a.png', startLatLng);

			var mapImageUrl = buildMapImageUrl(result.routes[0] , '' ,'roadmap', 880 , 680, 5 );
			var mapImageUrl1 = 'http://maps.google.com/maps?saddr='+query+'&daddr='+destinationAdd;
			
			// Set the attribute for map image url , do it only for get direction page to pass to share email page
			if($('#mapImageUrl').length > 0 ) {
				$('#mapImageUrl').val(mapImageUrl);
				$('#mapslink').val(mapImageUrl1);
			}

			//for print page
			if($('#mapImg').length > 0 ) {
				$('#mapImg').attr ('src' , mapImageUrl);
			}

			//setting total dist in print page
			if($('#totalDistance').length > 0 ) {
				$('#totalDistance').html(result.routes[0].legs[0].distance.text);

			}

			// if(mapInstructions) {
			$('.resultsContent').html('');

			var resultsContent = '';

			$.each(result.routes[0].legs[0].steps, function (index, step) {
				var instr = step.instructions;
				var distText = step.distance.text;
				var dirIcon = directionIcon(instr);
				var c = index+1;
				if(c != result.routes[0].legs[0].steps.length) {
					resultsContent += '<li class="directionResults"><div class="directionContainer clearfix"><span class="indicator '+dirIcon+'"></span><span class="desc"><strong class="number">' + c +'. ' + '</strong>'+instr+'</span><span class="distance">'+distText+'</span></div></li>';
				} else {
					resultsContent += '<li class="directionResults"><div class="directionContainer clearfix"><span class="indicator '+dirIcon+'"></span><span class="desc"><strong class="number">' + c +'. ' + '</strong>'+instr+'</span><span class="distance">'+distText+'</span></div></li>'
					+'<li class="directionResults"><div class="directionContainer clearfix"><span class="indicator last"></span><span class="desc"><strong class="number">'+'</strong>'+destinationAdd+'</span><span class="distance">'+'</span></div></li>';
				}

			});

			$('.resultsContent').append(resultsContent);

			if(($('#custom-scrollbar').length > 0) && !print) {
				$('#custom-scrollbar').tinyscrollbar();
			}

			setAddress(startLocation, print);
			callAnalytics("Common", "StoreLocator", "GetDirectionsResults", "");
		} else {
			$('.displayLocations').addClass('hide');
			$('.form-error-message').removeClass('visible');
			$('.toshow').removeClass('hide').addClass('visible');
			
			//set the error message
			if($('.addressPH').length >0){
				$('.addressPH').html(trim(query));
			}
			$('.form-error-message.no-location-match').removeClass('hide').addClass('visible');
			callAnalyticsForError("Common", "StoreLocator", "GetDirectionsResults", "NoMatchingStoresError", "", "");
		}
	});
}

/* --------------------- GET DIRECTIONS END ----------------------- */

/*
	Build static map api
	path=color:0x0000ff|weight:5|40.702147,-74.015794|40.711614,-74.012318
	Sample url : http://maps.googleapis.com/maps/api/staticmap?zoom=15&maptype=roadmap&size=480x480&sensor=false&
	path=color:0x0000ff|weight:5|40.702147,-74.015794|40.711614,-74.012318&
	markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318
	&key=AIzaSyDFGMq64h3YY-I0XJc-D69zrgBylq4IuJQ
*/

function buildMapImageUrl(route, zoom, maptype, width, height, lineWeight ) {

	/* get first and last points for markers and all co-ordintes for routes*/
	var staticMapurl = "http://maps.googleapis.com/maps/api/staticmap?sensor=false&zoom="
						+zoom+"&maptype="+maptype+"&size="+width+"x"+height+
						"&path=color:0x0000ff|weight:"+lineWeight ;

	staticMapurl = staticMapurl +"|enc:"+route.overview_polyline.points ;

	/* Build start and end markers */
	/* 11/27/2013 - OPTWO-3264 - Host name hard-coded to 'www.opsm.com.au' as google map expects TLD for marker icon URL - Start */
	/*var markerAURL = encodeURI($('#envSchemeToUse').val() +$('#envHostName').val() + $('#assetsDirectory').val() + 'images/storelocator/map_pin_a.png');
	var markerBURL = encodeURI($('#envSchemeToUse').val() +$('#envHostName').val() + $('#assetsDirectory').val() + 'images/storelocator/map_pin_b.png');*/

	var markerAURL = encodeURI($('#envSchemeToUse').val() + 'www.opsm.com.au' + $('#assetsDirectory').val() + 'images/storelocator/map_pin_a.png');
	var markerBURL = encodeURI($('#envSchemeToUse').val() + 'www.opsm.com.au' + $('#assetsDirectory').val() + 'images/storelocator/map_pin_b.png');
	/* 11/27/2013 - OPTWO-3264 - End */
	
	var mapMarkers = "&markers=icon:"+markerBURL+"|shadow:true|"+route.legs[0].start_location.lat() + "," + route.legs[0].start_location.lng();
	 	mapMarkers +=	"&markers=icon:"+markerAURL+"|shadow:true|"+ route.legs[0].end_location.lat() + "," + route.legs[0].end_location.lng();
	
	staticMapurl = staticMapurl  + mapMarkers ;

	return staticMapurl;

}
function getGeoCoords(query) {

	var geocoder = new google.maps.Geocoder();
	var storeId= $('#storeId').val();
	var searchCountryCode= $('#searchCountryCode').val();
	var startGeoLocation = new Array(2);

	$.ajax({
		url:"GetGeocodeCmd?address="+jQuery.trim(query)+"&storeId="+storeId+"&fromPage=getDirections"+"&searchCountryCode="+searchCountryCode ,
		type : 'POST',
		async : false,
		timeout:30,
		dataType: 'json',
		success:function (result) {
			startGeoLocation[0]=result.latitude;
			startGeoLocation[1]=result.longitude;
		},
		error: function (xhr, ajaxOptions, thrownError) {
			if(ajaxOptions==="timeout") {
				//console.log('timeout');
			}
		}
	});
	return startGeoLocation;
}

function setAddress(query, print) {
	var lat = parseFloat(query[0]);
	var lng = parseFloat(query[1]);
	var latlng = new google.maps.LatLng(lat, lng);

	geocoder = new google.maps.Geocoder();
	geocoder.geocode({'latLng': latlng}, function (results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			if(results[1]){	
				result = results[1].formatted_address;
				var html = '<li class="directionResults"><div class="directionContainer clearfix"><span class="indicator start-address first"></span><span class="desc">'+result+'</span></li>';
				$('.resultsContent').prepend(html);
				if(!print) {
					$('#custom-scrollbar').tinyscrollbar_update();
				}
			}
		}
	});
}

function directionIcon(instr) {

	var iconClass ;
	if(instr.search(/u-turn/i)>=0) {
		iconClass = 'uturn';
	}
	else if(instr.search(/slight/i)>=0) {
		if(instr.search(/right/i)>=0) iconClass = 'slightright';
		else if(instr.search(/left/i)>=0) iconClass = 'slightleft';
	}
	else if(instr.search(/sharp/i)>=0) {
		if(instr.search(/right/i)>=0) iconClass = 'sharpright';
		else if(instr.search(/left/i)>=0) iconClass = 'slightleft';
	}
	else if(instr.search(/exit/i)>=0) {
		if(instr.search(/right/i)>=0) iconClass = 'exitright';
		else if(instr.search(/left/i)>=0) iconClass = 'exitleft';
	}
	else if(instr.search(/keep/i)>=0) {
		if(instr.search(/right/i)>=0) iconClass = 'keepright';
		else if(instr.search(/left/i)>=0) iconClass = 'keepleft';
	}

	else if(instr.search(/right/i)>=0) { iconClass = 'right';

	}
	else if(instr.search(/left/i)>=0) {
		iconClass = 'left';
	}
	else if(instr.search(/ramp/i)>=0 || instr.search(/merge/i)>=0) {
		iconClass = 'rampmerge';
	}
	else if(instr.search(/roundabout/i)>=0) {
		if(instr.search(/roundabout/i)< instr.search(/continue/i)) {
			iconClass = 'roundabout';
		}
		else {iconClass = 'roundabout';}
		iconClass = 'continue';
	}
	else if(instr.search(/continue/i)==0) {
		iconClass = 'continue';
	}

	return iconClass;

}

/* Load store info into data object start */


function getStoreInfo() {
	
	storeInfo['global'] = {
		dirMsg:$("#directnsMsg").val(),
		hoursMsg:$("#openHoursMsg").val(),
		eyeMsg:$("#eyeServicesMsg").val()
	};

	$.each($('.store-location'), function (c, ele) {

		var i = c+1;

		var store = {};

		var uid = $("#uniqueId_"+i).val();

		var LatLng = new google.maps.LatLng($("#latitude_"+i).val(), $("#longitude_"+i).val());

		store['latlng'] = LatLng;
		store['rendered'] = '';

		var addToStoreLink = '';
		var isAddToStoreDisabled = $("#isAddToStoreDisabled_"+i).val();
			if( isAddToStoreDisabled == 'false' )
			addToStoreLink = "<a href='#' rel='"+uid+"' class='show-overlay-storeloc-addstore1 mapOverlayClass' data-overlay='overlay_panel_services'>"+$("#addStrsMsg").val()+"</a>";

		var addyVal = {
			name:"#description",
			add1:"#addressLine1",
			add2:"#addressLine2",
			city:"#city",
			state:"#state",
			pcode:"#postalCode",
			tphon:"#telephone",
		};

		$.each(addyVal, function (key, val) {
			var seperator = '<br/>';
			var wrap = '';
			
			
			switch(key) {
				case 'state':
					seperator = ', ';
				break;
				case 'name':
					wrap = 'strong';
				break;
			}
			if(val = hasVal(val+'_'+i)) {
				//$(val+'_'+i).val();
				store[key] = val;//$(val+'_'+i).val();
				store['rendered'] += wrapStr(val, wrap)+seperator;
			}
		});
		var dirUrl = $("#storeDirectionsUrl_"+i).val();
		store['rendered'] += '<br/><a rel="'+uid+'" data-overlay="overlay_panel_services" class="show-overlay-storeloc-opening1 mapOverlayClass" id="show-overlay-storeloc-opening1" href="#">'+storeInfo.global.hoursMsg+'</a><br/>\
								<a rel="'+uid+'" data-overlay="overlay_panel_services" class="show-overlay-storeloc-eyetestservices1 mapOverlayClass" href="#">'+storeInfo.global.eyeMsg+'</a><br/>\
								<a href="'+dirUrl+'">'+storeInfo.global.dirMsg+'</a><br/>'+addToStoreLink;

		storeInfo[uid] = store;
	});
}

function wrapStr(val, tag) {
	return tag == '' ? val : '<'+tag+'>'+val+'</'+tag+'>';
}

function hasVal(cls) {
	return ($(cls).val() != null && $(cls).val() && $(cls).val() != 'null' ) ? $(cls).val() : false;
}


/* Load store info into data object end */

/* Load Map with markers pointing different store location. Starts Here */
// UPDATED BY PABLO 15.01.13

var infoBox;

function loadMapWithMarkers() {
	opsm.locationSearch.fillMapCanvasDelayed();
	
	/*
	var size = $("#totalStores").val(),
		addedStoresSize = $("#totalAddedStores").val(),
		latitude = $("#latitude_1").val(),
		longitude = $("#longitude_1").val(),
		preferredStoreId = $("#preferredStoreId").val(),
		userFavStoreCount = $("#userFavStoreCount").val(),
		maxAllowedFavs = $("#maxAllowedFavs").val(),
		userType = $("#userType").val();

	if(size > 0) {

		getStoreInfo();

		var center = new google.maps.LatLng(latitude, longitude);

		var mapOptions = {
			zoom: 8,
			center: center,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};

		//var map = new google.maps.Map(document.getElementsByClassName("locations-map")[0], mapOptions);
		var map = opsm.locationSearch.init();

		var bounds = new google.maps.LatLngBounds();

		var pinEv = "new google.maps.MarkerImage(pinUrl,\
				new google.maps.Size(40, 50),\
				new google.maps.Point(0, 0),\
				new google.maps.Point(20, 45));";

		var shadow = new google.maps.MarkerImage($('#assetsDirectory').val()+'images/storelocator/map_pin_shadow.png',
				new google.maps.Size(40, 50),
				new google.maps.Point(0,0),
				new google.maps.Point(20, 45));

		var shape = {
				coord: [1, 1, 1, 40, 40, 50, 40, 1],
				type: 'poly'
		};

		$.each($('.store-location'), function (c) {
			var i = c+1;

			var stLocId = $("#uniqueId_"+i).val();

			var pinUrl = $('#assetsDirectory').val()+'images/storelocator/map_pin_' + (preferredStoreId == stLocId ? 'fav':i) + '.png';

			var marker = new google.maps.Marker({
				map:map,
				position:storeInfo[stLocId].latlng,
				shadow:shadow,	
				icon:eval(pinEv),
				shape:shape,
				title:$("#description_"+i).val(),
				zIndex:size-i
			});


		    google.maps.event.addListener(marker, "click", function(e) {
		    	removeInfoBox();
		    	infoBox = new InfoBox({latlng: marker.getPosition(), map: map, uid:stLocId});
		    });
		    if(i <= 4) {
				bounds.extend(marker.position);
			}

		});

		map.fitBounds(bounds);

*/
		/*google.maps.event.addListener(map, "click", function (e) {
			removeInfoBox();
		});*/
/*
	}
	*/
}
/* Load Map with markers pointing different store location. Ends Here */

/* Functions for custom infobox starts */

function removeInfoBox() {
	if(infoBox) infoBox.setMap(null);
}

function InfoBox(opts) {

	google.maps.OverlayView.call(this);

	this.latlng_ = opts.latlng;
	this.map_ = opts.map;

	this.uid = opts.uid;

	this.offsetVertical_ = -270;
	this.offsetHorizontal_ = -120;

	var me = this;

	this.boundsChangedListener_ = google.maps.event.addListener(
		this.map_, 
		"bounds_changed", 
		function () {
			return me.panMap.apply(me);
	});

	this.setMap(this.map_);
}

/* InfoBox extends GOverlay class from the Google Maps API
 */
if($('.getDirectionContainer').length||$('.getDirectionContainer').length){
	InfoBox.prototype = new google.maps.OverlayView();
}
/* Creates the DIV representing this InfoBox
 */
InfoBox.prototype.remove = function () {
	if (this.div_) {
		this.div_.parentNode.removeChild(this.div_);
		this.div_ = null;
	}
};

/* Redraw the Bar based on the current projection and zoom level
 */
InfoBox.prototype.draw = function () {
	// Creates the element if it doesn't exist already.
	this.createElement();
	if (!this.div_) return;

	// Calculate the DIV coordinates of two opposite corners of our bounds to
	// get the size and position of our Bar
	var pixPosition = this.getProjection().fromLatLngToDivPixel(this.latlng_);
	if (!pixPosition) return;

	// Now position our DIV based on the DIV coordinates of our bounds
	//this.div_.style.width = this.width_ + "px";
	this.div_.style.left = (pixPosition.x + this.offsetHorizontal_) + "px";
	//this.div_.style.height = this.height_ + "px";
	this.div_.style.top = (pixPosition.y + this.offsetVertical_) + "px";
	this.div_.style.display = 'block';

};

InfoBox.prototype.createElement = function () {

	var panes = this.getPanes();

	var div = this.div_;

	if (!div) {

		// This does not handle changing panes. You can set the map to be null and
		// then reset the map to move the div.
		div = this.div_ = document.createElement("div");
		div.style.border = "0px none";
		div.style.position = "absolute";
		div.style.background = "url('"+$('#assetsDirectory').val()+"images/storelocator/bg_infobox.png') no-repeat";
		div.style.width = '200px';
		div.style.height = '200px';
		div.style.padding ='20px';
		div.style.display = 'none';
		div.id = 'infobox';

		// Set content
		div.innerHTML = storeInfo[this.uid].rendered;

		panes.floatPane.appendChild(div);

		this.panMap();

	} else if (div.parentNode != panes.floatPane) {
		// The panes have changed. Move the div.
		div.parentNode.removeChild(div);
		panes.floatPane.appendChild(div);
	} else {
		// The panes have not changed, so no need to create or move the div.
	}
}

/* Pan the map to fit the InfoBox.
*/
InfoBox.prototype.panMap = function() {
	// if we go beyond map, pan map
	var map = this.map_;
	var bounds = map.getBounds();
	if (!bounds) return;

	// The position of the infowindow
	var position = this.latlng_;

	// The dimension of the infowindow
	var iwWidth = 180;//this.width_;
	var iwHeight = this.height_;

	// The offset position of the infowindow
	var iwOffsetX = -90;//this.offsetHorizontal_;
	var iwOffsetY = this.offsetVertical_;

	// Padding on the infowindow
	var padX = 40;
	var padY = 40;


	// The degrees per pixel
	var mapDiv = map.getDiv();
	var mapWidth = mapDiv.offsetWidth;
	var mapHeight = mapDiv.offsetHeight;
	var boundsSpan = bounds.toSpan();
	var longSpan = boundsSpan.lng();
	var latSpan = boundsSpan.lat();
	var degPixelX = longSpan / mapWidth;
	var degPixelY = latSpan / mapHeight;

	// The bounds of the map
	var mapWestLng = bounds.getSouthWest().lng();
	var mapEastLng = bounds.getNorthEast().lng();
	var mapNorthLat = bounds.getNorthEast().lat();
	var mapSouthLat = bounds.getSouthWest().lat();

	// The bounds of the infowindow
	var iwWestLng = position.lng() + (iwOffsetX - padX) * degPixelX;
	var iwEastLng = position.lng() + (iwOffsetX + iwWidth + padX) * degPixelX;
	var iwNorthLat = position.lat() - (iwOffsetY - padY) * degPixelY;
	var iwSouthLat = position.lat() - (iwOffsetY + iwHeight + padY) * degPixelY;

	// calculate center shift
	var shiftLng =
	(iwWestLng < mapWestLng ? mapWestLng - iwWestLng : 0) +
	(iwEastLng > mapEastLng ? mapEastLng - iwEastLng : 0);
	var shiftLat =
	(iwNorthLat > mapNorthLat ? mapNorthLat - iwNorthLat : 0) +
	(iwSouthLat < mapSouthLat ? mapSouthLat - iwSouthLat : 0);

	// The center of the map
	var center = map.getCenter();

	// The new map center
	var centerX = center.lng() - shiftLng;
	var centerY = center.lat() - shiftLat;

	// center the map to the new shifted center
	map.setCenter(new google.maps.LatLng(centerY, centerX));

	// Remove the listener after panning is complete.
	google.maps.event.removeListener(this.boundsChangedListener_);
	this.boundsChangedListener_ = null;
};

/* Functions for custom infobox ends */

/* Load Map in User Account with marker pointing the store location. Starts Here */
function loadMapWithMarkersForUserStores() {

	var size = $("#totalStores").val();
	for(var i=1; i <= size; i++) {
		latitude = $("#latitude_"+i).val();
		longitude = $("#longitude_"+i).val();

		var mapOptions = {
			center: new google.maps.LatLng(latitude, longitude),
			zoom: 12,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};

		var map = new google.maps.Map(document.getElementById("map_canvas_"+i), mapOptions);
		var infowindow = new google.maps.InfoWindow();

		var image = $('#assetsDirectory').val()+ 'images/storelocator/map_pin_'+i+'.png';
		if($('#isPreferredStore_'+i).val() == 'true') {
			image = $('#assetsDirectory').val()+ 'images/storelocator/map_pin_fav.png';
		}
		var marker = new google.maps.Marker({
			position: new google.maps.LatLng(latitude , longitude),
			map: map,
			icon: image,
			zoom: 8
		});
	}
}
/* Load Map in User Account with marker pointing the store location. Ends Here */

/* Load Map in Store Landing Page with marker pointing the store location. Starts Here */
function loadMapWithMarkersForStorePage() {

	var latitude = $("#latitude").val(),
	longitude = $("#longitude").val();

	var mapOptions = {
		center: new google.maps.LatLng(latitude, longitude),
		zoom: 12,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};

	var map = new google.maps.Map(document.getElementById("map_canvas_store_page"), mapOptions);
	var infowindow = new google.maps.InfoWindow();

	var image = $('#assetsDirectory').val()+ 'images/pin.png';
	var marker = new google.maps.Marker({
		position: new google.maps.LatLng(latitude , longitude),
		map: map,
		icon: image,
		zoom: 12
	});
}
/* Load Map in Store Landing Page with marker pointing the store location. Ends Here */

/* Controls the store list pagination */
/* See more locations Function */

function initializeStoreList() {

	visible = 0;
	lis = $('.store-location');
	max = lis.length;

	showUpToIndex();
}

function showUpToIndex() {

	visible = visible + 4; //+ 6; //OPS-971

	if (visible > max) {
		visible = max;
	}

	$(lis).hide();

	$(lis).slice(0, visible).show();

	$('.storesShown').html(visible);
	$('.totStores').html(max);

	if(visible == max) {
		$('#more').addClass('hide');
	}
}

/* for find in store search */
function findInStoreSearch(searchLink) {

	var offset = self.pageYOffset,
	greyoutHeight = $(document).height(),
	catentryId = searchLink.attr("relCatId"),
	partNumber = searchLink.attr("relModelName") ;

	var address = $('#searchAddress').val();

	if (address == '' | address =='Enter location') {
		$('.form-error-message').addClass('hide');
		$('#searchAddress + .form-error-nullmsg').removeClass('hide');
	}else{

		var searchCountryCode = $('#searchCountryCode').val();
		var fullPageView = $('#fullPageView').val();

		//encode uri
		address = escape(address);
		searchCountryCode = escape(searchCountryCode);
		$('#searchAddress + .form-error-message').addClass('hide');

		var storeInvUrl = "FindInStoreResultsView?address="+address+"&searchCountryCode="+searchCountryCode+
							"&catentryId="+catentryId+"&partNumber="+partNumber+
							"&storeId="+$('#storeId').val()+"&langId="+$('#langId').val();

		if(fullPageView == 'true') {

			storeInvUrl = storeInvUrl + "&viewMode=fullPageView";
			window.location.href = storeInvUrl ;
		}else{
			$('#find-in-store-modal').load(storeInvUrl);
			callAnalytics("Common", "FindInStore", "FindInStoreResultsModal", "");
		}
	}
}

//Scripts for Tealium Tagging.
function callAnalytics(ch, subSec, pName, errType){
	if(isAnalyticsEnabled){
		var loggedInStatus = "NotLoggedIn";
		if(isGuestUser != 'true'){
			loggedInStatus = "LoggedIn";
		}
		
		utag.view({
			country : countryCode,
            currency : currencyCode,
			pageName : "OPSM_"+countryCode+":"+ch+":"+subSec+":"+pName, 
			channel : ch, 
			subSection : subSec,
			errorType : errType,
			productsList : "",
			authenticated:loggedInStatus
		});
	}
}
function callAnalyticsForError(ch, subSec, pName, errType, pageEvent, shareDetail){
	if(isAnalyticsEnabled){
		var loggedInStatus = "NotLoggedIn";
		if(isGuestUser != 'true'){
			loggedInStatus = "LoggedIn";
		}
		utag.view({
			country : countryCode,
            currency : currencyCode,
			pageName : "OPSM_"+countryCode+":"+ch+":"+subSec+":"+pName, 
			channel : ch, 
			subSection : subSec,
			errorType : errType,
			pageEvents : pageEvent,
			shareDetails : shareDetail,
			productsList : "",
			authenticated:loggedInStatus
		});
	}
}

function callAnalyticsForClick(trackVars, trackEvents, prodList, bookTestSrc, socialShare, printPageType, sortProductsType, faqPageName, videoTtl, selectedStore, linkType, linkText, pName){
	if(isAnalyticsEnabled){
//		utag.track("link", { 
//			linkTrackVars:trackVars, 
//			linkTrackEvents:trackEvents, 
//			productsList:prodList,
//			bookTestSource:bookTestSrc,
//			shareDetails:socialShare,
//			printType:printPageType,
//			sortType:sortProductsType,
//			faqName:faqPageName,
//			videoTitle:videoTtl,
//			StoreDetails:selectedStore,
//			link_type:linkType,
//			link_text:linkText,
//			linkPageName:pName
//		});
	}
}

function loadModelGreyOut2(selObject){
	
	if($('#find-in-store-modal').length > 0  ){
		$('#modal-greyout-2').css('height',pageHeight).removeClass('hide');
	}
}

//constraints user from entering characters for postcode field
function checkNumeral(eventParam) {
  var numeralEvent = eventParam || window.event;
  var checkKey = numeralEvent.keyCode || numeralEvent.which;
  if(numeralEvent.keyCode != '8' && numeralEvent.keyCode != '13'&& numeralEvent.keyCode != '37' && numeralEvent.keyCode != '39'){
	  checkKey = String.fromCharCode(checkKey);
	  var format = /[0-9]|\./;
	  if( !format.test(checkKey) ) {
		  numeralEvent.returnValue = false;
	    if(numeralEvent.preventDefault) numeralEvent.preventDefault();
	  }
  }
}

function validateFindStore(){
	var address = $.trim($('#find-store-address').val()); // 11/27/2013 - OPTWO-3310
	
	if (address == '' | address =='Address, suburb or postcode') {
		$('span.form-error-message').show();
		$('span.form-error-message').removeClass("hide");
		return false;
	}else{
		$('span.form-error-message').hide();
		return true;
	}
}


function validateFindStoreZip(){
	var address = $.trim($('#zipCode').val()); 
		if (address.length == 0) {
		$('div#invalidPostCode').removeClass("hide");
		return false;
	}else{
		$('div#invalidPostCode').addClass("hide");
		if($(window).width() <= 992) {
			var currAction = $("#frmByPostCode").attr('action');
			$("#frmByPostCode").attr('action', currAction+'#showStoreList');
		}
		return true;
	}
}

function validateFindStoreTownSuburb(){
	var townSuburb = $.trim($('#townSuburb').val());

		if (townSuburb.length ==0 ) {
			$('div#invalidTown').removeClass("invisible");
			return false;
		}
		else{
			$('div#invalidTown').addClass("invisible");
			return true;
		}
}


function validateFindStoreTown(){
	var address = $.trim($('#state').val()); 
	var townSuburb = $.trim($('#townSuburb').val());
    var addressError=false;
    var townSuburbError=false;
	if (townSuburb.length ==0 ) {
		$('div#invalidTown').removeClass("invisible");
		townSuburbError=true;
	}
	else{
		$('div#invalidTown').addClass("invisible");
		townSuburbError=false;
	}
	if(address.length == 0){
		$('div#stateErrorMsg').removeClass("invisible");
		addressError=true;
	}
	else{
		$('div#stateErrorMsg').addClass("invisible");
		addressError=false;
	}
	if(addressError || townSuburbError ){
		return false;
	}else{
		return true;
	}
	
}
