/* ########################################################################### *
/* ***** DOCUMENT INFO  ****************************************************** *
/* ########################################################################### *
 * ##### NAME:  global.js
 * ##### VERSION: v2.1
 * ##### UPDATED: 7 July 2009 (Damian Keeghan, Deloitte's Online Practice)
/* ########################################################################### *

/* ########################################################################### *
/* ***** INDEX *************************************************************** *
/* ########################################################################### *
/* ##### GLOBAL FUNCTIONS
/* ##### GLOBAL VARIABLES
/* ##### INITIALISATION
/* ##### FLASH INTERFACE
/* ##### FUNCTIONAL
/* ########################################################################### */

/* ########################################################################### *
/* ##### GLOBAL FUNCTIONS
/* ########################################################################### */

var loadOverlay_Initial;
var loadOverlay_RightColumn;
var loadOverlay_MiddleColumn;
var closeOverlay;
var closeFlashVar;
var closeOverlayContents;

/* ########################################################################### *
/* ##### GLOBAL VARIABLES
/* ########################################################################### */

var overlayColour;
var currentHref;
var currentThumbnail;
var closeInterval;

//global animation speed
var _speed = 250;
var _emailTimeout = 3000;

/* ########################################################################### *
/* ##### INITIALISATION
/* ########################################################################### */

$(document).ready(function(){
	init_global_functional();
});

$(window).unload(function(){
	destroyCookies();						  
});

/* ########################################################################### *
/* ##### FLASH INTERFACE
/* ########################################################################### */

function fl_loadContent(href, name, colour, layout){
	overlayColour = colour;
	var className = colour+" "+layout;
	loadOverlay_Initial(href, className, name, colour);
}

function fl_loadContentInIFrame(href, name, colour, layout){
	overlayColour = colour;
	var className = colour+" "+layout;
	loadOverlayIframe_Initial(href, className, name, colour);
}

function fl_loadContentInExternal(href){
	window.location.href = href;
}

function fl_loadContentInNewExternal(href){
	if(jQuery.browser.safari){
		window.location.href = href;
	} else {
		window.open( href );
	}
}

function fl_loadFragmentFromExternal(fragment){
	getFlashMovieFromId("CountryRoad").fl_updateFragment(fragment);
}

function fl_updateLeftMenu(id){
	if(jQuery.browser.msie){
		getFlashMovieFromId("CountryRoad_SubMenu_IE").fl_updateFlashLeftMenu(id);
	} else {
		getFlashMovieFromId("CountryRoad_SubMenu").fl_updateFlashLeftMenu(id);
	}
}

function fl_updateLeftCareersMenu(id){
	if(jQuery.browser.msie){
		getFlashMovieFromId("CountryRoad_Careers_Menu_IE").fl_updateFlashLeftCareersMenu(id);
	} else {
		getFlashMovieFromId("CountryRoad_Careers_Menu").fl_updateFlashLeftCareersMenu(id);
	}
}

function fl_updateMiddleCareersMenu(id){
	if(jQuery.browser.msie){
		getFlashMovieFromId("CountryRoad_Careers_SubMenu_IE").fl_updateFlashMiddleCareersMenu(id);
	} else {
		getFlashMovieFromId("CountryRoad_Careers_SubMenu").fl_updateFlashMiddleCareersMenu(id);
	}
}

function fl_loadRightContent(href){
	loadOverlay_RightColumn(href);
}

function fl_loadMiddleContent(href){
	loadOverlay_MiddleColumn(href);
}

function fl_closeOverlayButton(){
	if($("#popup").length > 0){
		window.close();
	} else {
		closeOverlay(true);	
	}
}

function fl_closeOverlay(){
	closeOverlay(false);
}

function fl_resizeMenuHeight(height){
	if($("#overlay").hasClass("threeColLayout1")){
		if(jQuery.browser.msie){
			$("#CountryRoad_Careers_SubMenu_IE").height(height);
		} else {
			if(jQuery.browser.safari){
				$("#CountryRoad_Careers_SubMenu_IE").attr("height", height);
			}
			$("#CountryRoad_Careers_SubMenu").height(height);
		}
	} else {
		if(jQuery.browser.msie){
			$("#CountryRoad_SubMenu_IE").height(height);
		} else {
			if(jQuery.browser.safari){
				$("#CountryRoad_SubMenu_IE").attr("height", height);
			}
			$("#CountryRoad_SubMenu").height(height);
		}
	}
}

function fl_resizeMenuHeightFromId(height, id){
	var formattedId = "#"+id
	$(formattedId).height(height);
}

function fl_clickButtonOnPage(id, name){
	var formattedId = "#"+id;
	
	//remove_scrollpane();
	
	if($(formattedId).css("text-decoration")!="underline"){
	
		if($(formattedId).hasClass('ecl_buttonUpdated')==false){
			var href = $(formattedId).attr("href");
			var onclickText = href.substr(href.indexOf(':')+1);
			//onclickText = "remove_scrollpane(); "+onclickText;
	
			if(jQuery.browser.safari){			
				document.getElementById(id).onclick = eval(onclickText);
			} else {
				$(formattedId).attr('onclick', onclickText);
			}
			$(formattedId).addClass('ecl_buttonUpdated');
	
			if (jQuery.browser.msie){
				$(formattedId).each(function(){
					this.click();
				});
			} else {
				$(formattedId).trigger("onclick");
			}
		} else {
			if (jQuery.browser.msie){
				$(formattedId).each(function(){
					this.click();
				});
			} else {
				$(formattedId).trigger("onclick");
			}
		}
		
		//page tracker
		var currentPage = window.location.toString();
		var lastIndex = currentPage.lastIndexOf("/");
		var pageUrl = currentPage.substring(lastIndex);
		pageTracker._trackPageview(pageUrl+"/"+name);
	}
}

function fl_setCurrentThumbnailImage(thumbnail){
	currentThumbnail = thumbnail;
}

function fl_downloadPdf(documentLink){
	pageTracker._trackPageview(SWFAddress.getPath()+"/download");
	window.open(documentLink);
}

//Country Road stores
function fl_filterStores(id){
	showStores(id);	
}

function getFlashMovieFromId(movieName) {
	if($.browser.msie){
		return window[movieName];
	} else {
		return document[movieName];
	}
}

function fl_getLocation(){
	if($.cookie("cr_currency_cookie")!=null){
		return $.cookie("cr_currency_cookie");
	} else {
		if(google.loader.ClientLocation.address.country_code=="AU"){
			return "AUD";
		} else if(google.loader.ClientLocation.address.country_code=="NZ"){
			return "NZD";
		} else if(google.loader.ClientLocation.address.country_code=="ZA"){
			return "ZAR";
		} else {
			return "AUD";	
		};
	}
}

/* ########################################################################### *
/* ##### FLASH LOGIN
/* ########################################################################### */

function fl_sendLoginToFlashFromIFrame(firstName, lastName, type, email){
	parent.fl_sendLoginToFlash(firstName, lastName, type, email);
}

function fl_sendLoginToFlash(firstName, lastName, type, email){
	getFlashMovieFromId("CountryRoad").fl_displayWelcomeMessage(firstName, lastName, type);
	
	//set cookies
	var fullname = firstName+" "+lastName;
	setPrepopulationCookies(fullname, email);
}

function fl_sendLogoutToFlashFromIFrame(){
	parent.fl_sendLogoutToFlash();
}

function fl_sendLogoutToFlash(){
	getFlashMovieFromId("CountryRoad").fl_hideWelcomeMessage();
	destroyCookies();
}

function fl_getCookieDataFromFlash(name, email){
	setPrepopulationCookies(name, email);
}

function fl_destroyCookies(){
	destroyCookies();
}

/* ########################################################################### *
/* ##### FUNCTIONAL
/* ########################################################################### */

function init_global_functional(){
	// Required for homepage load
	init_closeButtons();
	init_placeholderLinks();
	init_overlayActions();
	init_footerLinks();
	// Required for overlay window content
	init_loginForm();
	init_stores();
	init_comms_radio();
	init_subscribeToggle();
	//init_scrollPaneForm();
	ecl_clearHint();
	ecl_ieTweaks();
	init_leftcol_helptext();
	init_rightcol_helptext();
	init_module_control();
	init_terms();
	if($("#scrollto").length>0){
		update_scrollpane_thenScrollTo("#scrollto");
	} else {
		init_scrollpane();
	}
	init_faqs_scrollpane();
	ecl_externalLinks();
	init_contactUsCookies();
}

function afterContentLoad() {
	// Required for overlay window content
	init_loginForm();
	init_stores();
	init_leftcol_helptext();
	init_rightcol_helptext();
	init_module_control();
	init_comms_radio();
	init_subscribeToggle();
	//init_scrollPaneForm();
	ecl_clearHint();
	ecl_ieTweaks();
	ecl_emailToAFriend();
	update_scrollpane();
	init_terms();
	init_faqs_scrollpane();
	init_titleHeightFix();
	ecl_externalLinks();
	init_contactUsCookies();
}

function init_titleHeightFix(){
	$(".grey .flashTitle").each(function(){
		if($(this).find("object").length == 0){
			$(this).addClass("noHeight");	
		}
	});
}

function init_closeButtons(){
	$(".closeLink").parent().addClass("ecl_closeButton");
	$(".ecl_closeButton").html("<div class='close_black'><div id='closeButton_black'></div></div><div class='close_white'><div id='closeButton_white'></div></div>");
	
	addCloseButtonToOverlay('white');
	addCloseButtonToOverlay('black');
}

function addCloseButtonToOverlay(colour){
	var flashvars = {};
	flashvars.skin = ecl_global_skin;
	flashvars.colour = colour;
	var params = {};
	params.menu = "false";
	params.wmode = "transparent";
	params.allowscriptaccess = "always";
	params.base = ecl_global_baseUrl;
	var attributes = {};
	attributes.id = "CountryRoadButton_Close_"+colour;
	attributes.name = "CountryRoadButton_Close_"+colour;
	attributes.styleclass = "flashTitles";
	swfobject.embedSWF(ecl_global_baseUrl+"close_btn.swf", "closeButton_"+colour, "200", "20", "9.0.0", ecl_global_baseUrl+"expressInstall.swf", flashvars, params, attributes);
}

function init_placeholderLinks(){
	// Find all links with an overlay attribute
	$("a[rel='overlay']").click(function(){
		var toLoad = $(this).attr("href");
		var linkClass = $(this).attr("class");
		loadOverlay_Initial(toLoad, linkClass);
		return false;
	});	
	
	$("a[rel='overlayiframe']").click(function(){
		var toLoad = $(this).attr("href");
		var linkClass = $(this).attr("class");
		loadOverlayIframe_Initial(toLoad, linkClass);
		return false;
	});
}

function init_overlayActions(){
	//load content into overlay (first time)
	loadOverlay_Initial = function(href, className, name, colour) {
		currentHref = href;
		
		$("#overlay").addClass(className);
		$("#overlay div:first").load(href+' #overlayInner',null,function(){
			//located inline inside homepage due to variables required to be written in using reddot
			displayCloseButton(colour);
			fadeInContent();
		}); 
	}
	
	//load content into overlay with an iframe (first time)
	loadOverlayIframe_Initial = function(href, className, name, colour) {
		currentHref = href;
		
		$("#overlay").addClass(className);
		if (className.indexOf("oneColLayout1") != -1) {
			$("#overlay div:first").html("<div id='overlayInner' class='clearfix'><div id='rightColumn'><div id='rightColumnInner'><iframe src='' width='731' height='462' scrolling='no' frameborder='0' class='noBorder'></iframe></div></div></div>");
		}
		$("#overlayInner iframe").attr("src",href);
		
		init_closeButtons();
		fadeInContent();
	}
	
	//load content into right column (on update)
	loadOverlay_RightColumn = function(href) {
		$("#overlay #rightColumn").fadeOut(_speed, function(){
			$("#overlay #rightColumn").load(href+' #rightColumnInner',null,function(){
				$("#overlay #rightColumn").fadeIn(_speed, function(){
					afterContentLoad();
				});
			});
		});
	}
	
	//load content into right column (on update)
	loadOverlay_MiddleColumn = function(href) {
		loadOverlay_RightColumn(href);
		
		$("#overlay #middleColumn").fadeOut(_speed, function(){
			$("#overlay #middleColumn").load(href+' #middleColumnInner',null,function(){
				$("#overlay #middleColumn").fadeIn(_speed);
			});
		});
	}
	
	//close overlay
	closeOverlay = function(closeFlash){
		closeFlashVar = closeFlash;
		
		if(jQuery.browser.mozilla){
			if(stringIsLessThan(jQuery.browser.version, "1.9")){
				closeInterval = setInterval("closeOverlayContents()", 250);
			} else {
				closeOverlayContents();
			}
		} else if(jQuery.browser.safari){
			closeInterval = setInterval("closeOverlayContents()", 250);
		} else {
			closeOverlayContents();
		}
	}
	
	closeOverlayContents = function(){
		var closeFlash = closeFlashVar
		
		clearInterval(closeInterval);
		currentHref = "";
		
		$("#overlay").hide();
		$('.overlayFooter').show();
		//remove styling
		$("#overlay").removeClass();
		//remove content from the overlay
		$("#overlay div:first").empty();	
		
		if(closeFlash){
			getFlashMovieFromId("CountryRoad").fl_closeFlashOverlay();
		}
	}
}

function stringIsLessThan(version, checkAgainst){
	var current = version.split(".");
	var check = checkAgainst.split(".");
	
	if(Number(current[0])<=Number(check[0])){
		if(Number(current[1])<=Number(check[1])){
			return true;
		} else {
			return false;	
		}
	} else {
		return false;	
	}
}

function fadeInContent() {  
	$("#overlay").fadeIn(_speed,afterContentLoad);  
}

function displayCloseButton(colour){
	//replace html close link with flash button
}

function init_footerLinks(){
	// Close link functionality
	$(".closeLink").click(function(){
		closeOverlay(true);
		return false;
	});
	
	// Email link functionality
	$(".emailLink").click(function(){
		$('.overlayFooter').fadeOut(_speed);
		loadOverlay_RightColumn($(this).attr('href'));
		return false;
	});	
	
	// Print link functionality
	$(".printLink").click(function(){
		window.print();
		return false;
	});	
}

/* ########################################################################### *
/* ##### EXTERNAL LINKS
/* ########################################################################### */
function ecl_externalLinks(){
	$("a").each(function(){
		if($(this).attr("rel")=="external"){
			$(this).click(function(){
				window.open($(this).attr("href"));
				return false;
			});
		}
		
		if($(this).attr("rel")=="parent"){
			$(this).click(function(){
				var href = $(this).attr("href");				   
				var fragment = href.substr(href.indexOf("#")+1);
				fragment = (fragment=="") ? "/" : fragment;				 
								 
				parent.fl_loadFragmentFromExternal(fragment);
				return false;
			});
		}
		
		if($(this).hasClass('ecl_careerPathways')){
			$(this).click(function(){
				window.open($(this).attr("href"), "", "width=622, height=485, resizable=no, scrollbars=no");
				return false;
			});
		}
	});
}

/* ########################################################################### *
/* ##### CLEAR FIELD HINT
/* ########################################################################### */
function ecl_clearHint(){
	$(".clearHint").focus(function(){
		$(this).attr("value","");
	});
}

/* ########################################################################### *
/* ##### IE TWEAKS
/* ########################################################################### */

// Enable functionality if the user's browser is IE
function ecl_ieTweaks(){
	// If browser is IE6
	if ((jQuery.browser.msie)&&(parseInt(jQuery.browser.version)==6)){
		ecl_input_padding();
		ecl_lists();
		ecl_internalLinkFix();
	}
}

// Adds a class to checkbox and radio buttons if IE
function ecl_input_padding(){
	$('input[type=checkbox],input[type=radio]').addClass('nopad');
}

// Adds .first and .last classes to simulate :first :last pseudo classes on list items.
function ecl_lists(){
	$('ul li:first-child').addClass("first");
	$('ul li:last-child').addClass("last");
}

//solves the issue of reloading the page when using HTML links (only effects IE6)
function ecl_internalLinkFix(){
	$('#overlay a').each(function(){
		var href = $(this).attr('href');
		
		if($(this).attr('rel')==""||$(this).attr('rel')==null){
			if(href.indexOf("#")!=-1){
				$(this).click(function(){
					loadFragment(href);
					return false;
				});
			}
		}
	});
}

function loadFragment(href){
	var fragment = href.substr(href.indexOf("#")+1);
	fragment = (fragment=="") ? "/" : fragment;
	
	SWFAddress.setValue(fragment);	
}

/* ########################################################################### *
/* ##### SCROLLPANE
/* ########################################################################### */

function init_scrollpane(){
	$(".ecl_js_scrollpane").each(function(){
		//$(this).css("overflow", "hidden");
		$(this).jScrollPane({scrollbarWidth:11});
	});
}

function update_scrollpane(){
	$(".ecl_js_scrollpane").each(function(){
		$(this).jScrollPane({scrollbarWidth:11});
	});	
}

var myDest;

function update_scrollpane_thenScrollTo(destination){
	$(destination).attr("id", "scrollToMenu");
	myDest = destination;
	
	$(".ecl_js_scrollpane").jScrollPane({scrollbarWidth:11,animateTo:true});
	
	setTimeout("scrollToDestination()", 50);
}

function scrollToDestination(){
	$(".ecl_js_scrollpane")[0].scrollTo("#scrollToMenu", true);
	$(myDest).removeAttr("id");
}

/* ########################################################################### *
/* ##### FAQs SCROLLPANE
/* ########################################################################### */

function init_faqs_scrollpane(){
	if ($("#ecl_crcard_faq").length > 0){
		$(".scrollpane").jScrollPane({scrollbarWidth:11,animateTo:true});
		$(".scroll-to-element").each(function(){
			$(this).click(function(){
				var targetElementSelectorString = $(this).attr('rel');
				$(".scrollpane")[0].scrollTo(targetElementSelectorString);
				return false;
			});
		});
	}
}

/* ########################################################################### *
/* ##### FORM FIELD HELPTEXT
/* ########################################################################### */


function init_leftcol_helptext(){
	$("#leftColumn .ctrlHolder p.helpText").each(function(){
		$(this).css("opacity", "0");
		$(this).hide();
		
		$(this).parents(".ctrlHolder").find("input, select").focus(function(){
			$(this).parents(".ctrlHolder").find("p.helpText").slideDown("normal", function(){
				$(this).parents(".ctrlHolder").find("p.helpText").animate({opacity: 1}, "fast");
			});
		});
		
		$(this).parents(".ctrlHolder").find("input, select").blur(function(){
			$(this).parents(".ctrlHolder").find("p.helpText").animate({opacity: 0}, 0, null, function(){
				$(this).parents(".ctrlHolder").find("p.helpText").slideUp();
			});
		});		
	});
}

function init_rightcol_helptext(){
	$("#rightColumn .ctrlHolder p.helpText").each(function(){
		$(this).css("opacity", "0");
		
		$(this).parents(".ctrlHolder").find("input, select").focus(function(){
			$(this).parents(".ctrlHolder").find("p.helpText").animate({opacity: 1}, "fast");
		});
		
		$(this).parents(".ctrlHolder").find("input, select").blur(function(){
			$(this).parents(".ctrlHolder").find("p.helpText").animate({opacity: 0}, "fast");
		});		
	});
}

/* ########################################################################### *
/* ##### FORM MODULE SHOW/HIDE BUTTON
/* ########################################################################### */

function init_module_control(){
	// Hide sections that should be closed on load
	$(".closed").hide();
	$(".closed").find(".ctrlHolder, .buttonHolder").css("position","static");
	
	$(".modulesContainer .ecl_btn_moduleControlSingle").each(function(){											  
		$(this).click(function(){
			if ($(this).parents("div:first").find(".moduleContent").hasClass("closed")){
				
				if ($(".modulesContainer .open").length > 0){
					$(".modulesContainer .open").each(function(){
						// Set position static so that form fields animate in IE
						$(this).find(".ctrlHolder, .buttonHolder").css("position","static");
						$(this).animate({opacity: 0}, "slow", null, function(){
							$(this).slideUp("normal", function(){
								$(".modulesContainer .closed").slideDown("normal", function(){
									$(this).animate({opacity: 1}, "slow", null, function(){
										// Reset position relative so that helptext appears properly
										$(this).find(".ctrlHolder, .buttonHolder").css("position","relative");
										$(this).removeClass('closed').addClass('open');
									});
								});
								$(this).addClass('closed').removeClass('open');
							});
						});
					});
				}
				else {
					$(this).parents("div:first").find(".moduleContent").slideDown("normal", function(){
						$(this).animate({opacity: 1}, "slow", null, function(){
							// Reset position relative so that helptext appears properly
							$(this).find(".ctrlHolder, .buttonHolder").css("position","relative");
							$(this).removeClass('closed').addClass('open');
						});
					});
				}
			}
			else {
				// Set position static so that form fields animate in IE
				$(this).parents("div:first").find(".moduleContent .ctrlHolder, .moduleContent .buttonHolder").css("position","static");
				$(this).parents("div:first").find(".moduleContent").animate({opacity: 0}, "slow", null, function(){
					$(this).slideUp("normal", function(){
						$(this).addClass('closed').removeClass('open');
					});
				});	
			}
			$(this).blur();
			return false;
		});
	});
	
	$(".ecl_btn_moduleControl").each(function(){											  
		$(this).click(function(){
			if ($(this).parents("div:first").find(".moduleContent").hasClass("closed")){
				$(this).parents("div:first").find(".moduleContent .ctrlHolder, .moduleContent .buttonHolder").css("position","static");
				$(this).parents("div:first").find(".moduleContent").slideDown("normal", function(){
					$(this).animate({opacity: 1}, "slow", null, function(){
						// Reset position relative so that helptext appears properly
						$(this).find(".ctrlHolder, .buttonHolder").css("position","relative");
						$(this).removeClass('closed').addClass('open');
						update_scrollpane();	
					});
				});
			}
			else {
				// Set position static so that form fields animate in IE
				$(this).parents("div:first").find(".moduleContent .ctrlHolder, .moduleContent .buttonHolder").css("position","static");
				$(this).parents("div:first").find(".moduleContent").animate({opacity: 0}, "slow", null, function(){
					$(this).slideUp("normal", function(){
						$(this).addClass('closed').removeClass('open');
						update_scrollpane();
					});
				});	
			}
			$(this).blur();
			return false;
		});
	});
	
	$(".moduleCancel").each(function(){
		$(this).click(function(){
			// Set position static so that form fields animate in IE
			$(this).parents("div[class*='moduleContent']:first").find(".ctrlHolder, .buttonHolder").css("position","static");
			$(this).parents("div[class*='moduleContent']:first").animate({opacity: 0}, "slow", null, function(){
				$(this).slideUp("normal", function(){
					$(this).addClass('closed').removeClass('open');
					update_scrollpane();
				});	
			});
			$(this).blur();
			return false;
		});
	});
}

/* ########################################################################### *
/* ##### SHOW/HIDE TERMS AND CONDITIONS
/* ########################################################################### */

function init_terms(){
	// Hide the terms container
	$("#termsContainer").each(function(){
		$("#termsContainer .scrollpane").jScrollPane({scrollbarWidth:11});
		$(this).hide();
	});
	
	// Toggle the terms container on click of the link
	$("#privacyLink").click(function(){
		$("#termsContainer").toggle();
		update_scrollpane();
		$(this).blur();
		return false;
	});
}

/* ########################################################################### *
/* ##### ACCORDION LOGIN BOXES
/* ########################################################################### */

function init_loginForm(){
	/*
	This code is still buggy - have removed it for the moment. The error we are trying to fix is not an FED issue.
	
	if($("#LoginModule1_LoginContainer, #LoginModule1_PasswordContainer").length>0){
		$("#LoginModule1_Button1").click(function(e){		
			var usernameVal = $("#LoginModule1_LoginNameField").val();
			var passwordVal = $("#LoginModule1_PasswordField").val();
			var emailAddressRegExp = /([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/g;
			var isError = false;			

			$("#LoginModule1_LoginContainer, #LoginModule1_PasswordContainer").removeClass("error");			

			$(".crForm").find(".ctrlHolder, .buttonHolder").css("position","static");
			$("#LoginModule1_CustomValidator1, #LoginModule1_RequiredFieldValidator1, #LoginModule1_RequiredFieldValidator2").html("");
			$(".crForm").find(".ctrlHolder, .buttonHolder").css("position","");

			if(usernameVal.length==0 && passwordVal.length==0){
				$("#LoginModule1_LoginContainer, #LoginModule1_PasswordContainer").addClass("error");
				updateLoginStatus("Card Number/Email address is required<br/>Password is required");
				isError = true;
			} else if(usernameVal.length==0){
				$("#LoginModule1_LoginContainer").addClass("error");
				updateLoginStatus("Card Number/Email address is required");
				isError = true;
			} else if(passwordVal.length==0){
				if(IsNumeric(usernameVal) || emailAddressRegExp.test(usernameVal)){
					$("#LoginModule1_PasswordContainer").addClass("error");
					updateLoginStatus("Password is required");
				} else {
					$("#LoginModule1_LoginContainer, #LoginModule1_PasswordContainer").addClass("error");
					updateLoginStatus("Please enter a valid CR Card number or email address<br/>Password is required");		
				}
				isError = true;
			}

			if(isError){
				e.preventDefault();
			}
		});
	}*/
}

function IsNumeric(sText){
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

   for (i = 0; i < sText.length && IsNumber == true; i++) { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) {
         IsNumber = false;
      }
   }
   return IsNumber;
}


function updateLoginStatus(message){
	$(".crForm").find(".ctrlHolder, .buttonHolder").css("position","static");
	$("#LoginModule1_CustomValidator1").html(message+"<br/>").show();
	$(".crForm").find(".ctrlHolder, .buttonHolder").css("position","");
}

/* ########################################################################### *
/* ##### STORES FUNCTIONALITY
/* ########################################################################### */

var unfilteredRowSelector = ".activeList > li:not(.filtered)";
var INITIAL_ZOOM = 15;
var FIND_LOCATION_ERROR = '<strong>Sorry, no stores were found.</strong><br/><br/><strong>Suggestions:</strong><ul><li>Make sure all suburb and city names are spelled correctly.</li><li><a href="'+ecl_contactUs_Url+'">Contact us</a> for more information about store locations.</li></ul>';
var SEARCH_BOX_DEFAULT_TXT = 'Enter your postcode, suburb or city';
var geocoder;
var map;
var mapCounter;
var currentStoreId;
var sortExecuted;

function init_stores(){
	if($(".storesHeader").length>0){
		mapCounter=0;
		sortExecuted="false";
		geocoder = new GClientGeocoder();
		
		$(".storesNav a").click(function(){
			var navId = $(this).parent().attr("id");
			if(navId != ""){
				showStores(navId);
			}
			return false;
		});
				
		$(".storeMap").each(function(){
			// assign an id to each map		
			$(this).attr("id","map" + mapCounter);
			mapCounter++;
		});	
		
		$(".storesContainer").each(function(){
			$(this).find(".openHours table").removeAttr("border");
			$(this).find(".openHours table").removeAttr("cellpadding");	
			$(this).find(".openHours table").removeAttr("cellspacing");	
		});
		
		$("#closeStoresForm").submit(function(){
			var closeStores = $("#closeStoresForm #closeStores").attr("value");		
			showLocation(closeStores);
			return false;
		});
	
		init_showHideButtons();
		init_printStoreButtons();
		
		$(".sectionsFilter input[type='checkbox']").click(ecl_filteringCheckbox_Click);
		ecl_filteringCheckbox_Click();
	}
}

function init_showHideButtons() {	
	$(".showStoreMap").click(function(){
		var setupScrollTo = false;
		
		if ($(this).html()=="Show map"){
			setupScrollTo = true;
			
			$(this).html("Hide map");	
			
			var latitude = $(this).parent().parent().find(".latitude").text();				 
			var longitude = $(this).parent().parent().find(".longitude").text();			
			var mapId = $(this).parent().next().attr("id"); 
														
			initializeMap(mapId,latitude,longitude);
		}
		else {
			$(this).html("Show map");
		}
		
		var currentButton = $(this);
		
		$(this).parent().next().slideToggle("normal",function(){
			if(setupScrollTo){
				update_scrollpane_thenScrollTo($(this).parent().find(".storeHeader"));
			} else {
				update_scrollpane();
			}
		});
		$(this).blur();
		return false;
	});
}

function init_printStoreButtons() {
	$(".printSingleLink").click(function(){
		// Remove all printSingleList classes from results
		$(".storesList").removeClass("printSingleList");
		// Remove all printSingleItem classes from results
		$(".storesList li").removeClass("printSingleItem");
		// Apply printSingleList class to active list
		$(this).parents(".storesList").addClass("printSingleList");
		// Apply printSingleItem class to active item
		$(this).parents("li:first").addClass("printSingleItem");
		// Open map if it is not showing already
		var buttonTitle = $(this).parents("li:first").find(".showStoreMap").html();
		if (buttonTitle == "Show map"){
			$(this).parents("li:first").find(".showStoreMap").trigger("click");
		}
		// Set timeout to wait for IE to display the map
		timeoutID = setTimeout("window.print()", 1000);
		return false;
	});	
}

function Store(store,lat,lng, name) {
    this.store = store;
    this.lat = lat;
    this.lng = lng;
    this.point = new GLatLng(lat, lng);
    this.name = name;
}

function showStores(storeId) {
	if ($(".storesImage").length > 0) {
		$(".storesImage").hide();
	}
	
	if($(".storesHeader").hasClass("displayed")==false){
		$(".storesHeader").show();
		$(".storesHeader").addClass("displayed");
	}
	
	resetStores();

	href = $("#storelistUrl").text();
	currentStoreId = "#"+storeId;
	
	$("#overlay #rightColumn #allStores").removeClass("hidden");
	$("#overlay #rightColumn #allStores").fadeOut(_speed, function(){
		$("#overlay #rightColumn #allStores").load(href+' #'+storeId,null,function(){
			$("#overlay #rightColumn #allStores").fadeIn(_speed, function(){				
				init_stores();			

				// Show the filters and store based on ID
				$("#allStores div"+currentStoreId).show();
				$("#allStores div"+currentStoreId+" ol").addClass("activeList");
				
				ecl_filteringCheckbox_Click();
				
				update_scrollpane();
			});
		});
	});	
}

function resetStores() {
	// Hide all open filters and store containers
	$("div.storesContainer").hide();
	// Reset all the filters to be checked
	$(".sectionsFilter input[type='checkbox']").removeAttr("checked");
	// Reset search box	
	$(".storesSearch input[type='text']").val(SEARCH_BOX_DEFAULT_TXT);	
	
	/* legacy code
	
	// Remove the filtered class from all stores
	$(".activeList li").removeClass('filtered');
	$(".activeList .sections li").removeClass('matchedCategory');
	// Remove the printSingleList class from all stores
	$(".storesList").removeClass("printSingleList");
	// Remove the printSingleItem class from all stores
	$(".storesList li").removeClass("printSingleItem");
	// Remove the no results message if shown
	$(".noResultsToShow").remove();
	// Show all stores
	$(".activeList, .activeList li").show();
	// Remove the activeList class
	$(".activeList").removeClass("activeList");
	
	*/
}

function ecl_filteringCheckbox_Click() {
	var checkedBoxes = $(".sectionsFilter input:checked");
	var notcheckedBoxes = $(".sectionsFilter input:not(:checked)");
	
	if(checkedBoxes.length==0){
		// Show all rows with unchecked categories
		for (var i = 0; i < notcheckedBoxes.length; i++)
		{
			var category = $(notcheckedBoxes[i]).next("label").text();
			var filterString = ":contains(" + category + ")";
			$(".activeList .sections").filter(filterString).each(function(){
				$(this).parent().removeClass('filtered');
				$(this).parent().show();
			});
		}
	} else {
		// Hide all rows with unhecked categories
		for (var i = 0; i < notcheckedBoxes.length; i++)
		{
			var category = $(notcheckedBoxes[i]).next("label").text();
			var filterString = ":contains(" + category + ")";
			$("ol.activeList .sections").filter(filterString).each(function(){
				//remove AND matching class
				$(this).find("li"+filterString).removeClass("matchedCategory");
				// adding filtered class.
				$(this).parent().addClass('filtered');
				$(this).parent().hide();					 
			});
		}
		// Show all rows with checked categories
		for (var i = 0; i < checkedBoxes.length; i++)
		{
			var category = $(checkedBoxes[i]).next("label").text();
			var filterString = ":contains(" + category + ")";
			$(".activeList .sections").filter(filterString).each(function(){
				//check for multiple matches
				$(this).find("li"+filterString).addClass("matchedCategory");
				var matchedCategories = $(this).find("li.matchedCategory").length;
				
				//alert(matchedCategories+", "+checkedBoxes.length);
				
				if(matchedCategories==checkedBoxes.length){
					//remove filtered class
					$(this).parent().removeClass('filtered');
					$(this).parent().show();
				} else {
					$(this).parent().addClass('filtered');
					$(this).parent().hide();	
				}
			});
		}
	}
	// Cater for no results by hiding results div and displaying the no results paragraph.
	if ($(unfilteredRowSelector).length > 0)
	{
		$('ol.activeList').show();
		$('.noResultsToShow').remove();
	}
	else
	{
		$('ol.activeList').hide();
		if ($(".noResultsToShow").length < 1) {
			$("ol.activeList").after('<div class="noResultsToShow errors"><p>Sorry, there are no results matching your current filter settings.</p></div>');
		}
	}
	
	update_scrollpane();
}

function initializeMap(mapId,lat,lng) {
	map = new GMap2(document.getElementById(mapId), {size: new GSize(400,180)});

	map.removeMapType(G_HYBRID_MAP);
	map.addMapType(G_SATELLITE_MAP);
	map.addMapType(G_PHYSICAL_MAP);
	map.addControl(new GMapTypeControl());

	map.addControl(new GSmallMapControl());

	storePoint = new GLatLng(lat, lng);
	map.setCenter(storePoint, INITIAL_ZOOM);

	// add a marker for the store
	marker = new GMarker(storePoint);
	map.addOverlay(marker);    
}

function findClosetsStores(response) {
	var stores;
	var storeCounter=0;

	sortExecuted="true";

	if (!response || response.Status.code != 200) {  		     
		$("div"+currentStoreId+" .storesList").hide();
		// Remove the no results message if shown
		$(".noResultsToShow").remove();
		$("div"+currentStoreId+" .storesList").after('<div class="noResultsToShow"><p>' + FIND_LOCATION_ERROR + '</p></div>');
	} else { 
		stores = new Array();
						       
		$('.noResultsToShow').remove();
	
		// get location of the address the user has entered
    	place = response.Placemark[0];
		startPoint = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);    
		
		// get a list of all stores
		$("div"+currentStoreId+" .storesList .storeLocation").each(function() {
			var latitude = $(this).find(".latitude").text();
			var longitude = $(this).find(".longitude").text();			
			var store = $(this).parent().get(0);
											
			stores[storeCounter] = new Store(store,latitude,longitude,"");			
			storeCounter++;
		});	

		if(stores.length  == 0){
			$(".noResultsToShow").remove();
			$("div"+currentStoreId+" .storesList").after('<div class="noResultsToShow"><p>' + FIND_LOCATION_ERROR + '</p></div>');
		}
		else {
			stores.sort(function(store1,store2){return startPoint.distanceFrom(store1.point,  null)- startPoint.distanceFrom(store2.point,  null)})
	
			// print a re-ordered list of stores based on distance from the address specified by users
			$("div"+currentStoreId+" .storesList").empty();			
			for(var i=0; i<stores.length;i++) {	                                   
	            $("div"+currentStoreId+" .storesList").append(stores[i].store);
			}
			init_showHideButtons();
			init_printStoreButtons();
		}
	}
}

function showLocation(address) {
	
	//determine where current region is located by getting the name attributed of the current store's div
	var location = $("div"+currentStoreId).attr("name");

	// append location to the address the user is searching for	
	address = address + " " + location;
	
	// show the list of stores in case they have  been hidden due to a previous search result that didn't have any results
	$("div"+currentStoreId+" .storesList").show();
	
    geocoder.getLocations(address, findClosetsStores);
}

/* ########################################################################### *
/* ##### MODIFYING PARENT OVERLAY COLOR FROM AN IFRAME
/* ########################################################################### */

/*function init_changeColor() {
	$(".changeColor").click(function(){
		var targetColor = $(this).parents("#overlay").attr("class");
		var isBlack = targetColor.indexOf('black');
		var isWhite = targetColor.indexOf('white');
		var isGrey = targetColor.indexOf('grey');
		if (isBlack >= 0) {
			parent.changeColor("black");
		}
		if (isWhite >= 0) {
			parent.changeColor("white");
		}
		if (isGrey >= 0) {
			parent.changeColor("grey");
		}
		return false;								 
	});	
}*/

function iframeChangeColor(color) {
	parent.changeColor(color);
}

function changeColor(color) {
	$("#overlay").removeClass("black white grey").addClass(color);
}

/* ########################################################################### *
/* ##### SCROLLPANE FORM TABBING FIX FOR IE
/* ########################################################################### */

function init_scrollPaneForm() {
	if ($.browser.msie) {
		if($("#Profile1_SaveButton") != null)
		{
			$("#Profile1_SaveButton").focus(function(){
				$(".scrollpane")[0].scrollTo('#'+$(this).attr("id"));
			});
		}
	}
}

/* ########################################################################### *
/* ##### EMAIL RADIO BUTTON FUNCTIONALITY
/* ########################################################################### */

// id's changed to align with server control id's used by .NET code.

function init_comms_radio() {
	if($("#Profile1_radio4") != null)
	{
		$("#Profile1_radio4").click(function(){
			if ($("#Profile1_radio4:checked")){
				$("#Profile1_radio2").attr("checked","checked");
			}
		});
	}
}

function init_subscribeToggle(){
	if($("input.userType_radio").length>0){
		$("input.userType_radio").each(function(){
			$(this).click(function(){
				var formattedId = "#"+$(this).parents(".module").find("#Select a").attr("id");			

				if($(formattedId).hasClass('ecl_buttonUpdated')==false){
					var href = $(formattedId).attr("href");
					var onclickText = href.substr(href.indexOf(':')+1);

					if(jQuery.browser.safari){			
						document.getElementById(id).onclick = eval(onclickText);
					} else {
						$(formattedId).attr('onclick', onclickText);
					}
					$(formattedId).addClass('ecl_buttonUpdated');
			
					if (jQuery.browser.msie){
						$(formattedId).each(function(){
							this.click();
						});
					} else {
						$(formattedId).trigger("onclick");
					}
				} else {
					if (jQuery.browser.msie){
						$(formattedId).each(function(){
							this.click();
						});
					} else {
						$(formattedId).trigger("onclick");
					}
				}
			});
		});
	}
}

/* ########################################################################### *
/* ##### COOKIES
/* ########################################################################### */

function destroyCookies(){
	if (window == top){
		$.cookie("cr_prepopulation_name_cookie", null, { path: '/' });	
		$.cookie("cr_prepopulation_email_cookie", null, { path: '/' });
		$.cookie("cr_prepopulation_toname_cookie", null, { path: '/' });	
		$.cookie("cr_prepopulation_toemail_cookie", null, { path: '/' });
	}
}

function setPrepopulationCookies(name, email){
	$.cookie("cr_prepopulation_name_cookie", name, { path: '/', expires: 999 });	
	$.cookie("cr_prepopulation_email_cookie", email, { path: '/', expires: 999 });
}

function fl_setCurrencyCookie(currency){
	$.cookie("cr_currency_cookie", currency, { path: '/', expires: 999 });
}

function init_contactUsCookies(){
	if($("#name").length>0 && $("#email").length>0){
		var name = $.cookie("cr_prepopulation_name_cookie");
		var email = $.cookie("cr_prepopulation_email_cookie");
		
		if(name!=null){
			$("#name").val(name);
		}
		
		if(email!=null){
			$("#email").val(email);
		}
	}
}

/* ########################################################################### *
/* ##### SCROLLPANE HACKS
/* ########################################################################### */

function remove_scrollpane(){
	if($(".jScrollPaneContainer").length>0){
		if(ifIE6()){
			$(".jScrollPaneTrack").each(function(){
				var container = $(this).parent();
				//$(container).find(".scrollpane .flashTitle").html("");
				var scrollpaneContent = $(container).find(".scrollpane").html();
				$(this).remove();
				
				$(container).replaceWith(scrollpaneContent);
			});
		}
	};
}

function ifIE6(){
	if (jQuery.browser.msie) {
		if(parseInt(jQuery.browser.version) == 6) {
			return true;
		}
	}
	
	return false;
}
