var centreId = "";

function findPos(obj, order) {
	
	obj = $(obj).get(order);
	
	var curleft = curtop = 0;
	
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;

		if(obj.offsetHeight) {
		   curHeight = obj.offsetHeight; 
		} else {
		   //curHeight = 0;
		} // end if/else
		
		if(obj.offsetWidth) {
		   curWidth = obj.offsetWidth;
		} else {
		   //curWidth = 0;
		} // end if/else
		
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop	
		}// end while
		
		return [curleft,curtop,curWidth,curHeight];	
		
	} else {
		
	  return false;
	  
	}

}

function stateSelected(state) {
	
	if (document.centreSearchForm.centre) {
	
		var centreSelect = document.centreSearchForm.centre;
		
		if (state != null && state.length > 0){
			while (centreSelect.length > 0) centreSelect[0]= null;
			centreSelect[centreSelect.length] = new Option('Select a Westfield','');
			for (var i=0; i < centres.length; i++) {
				if (centres[i].indexOf(state) == 0) {
					var thisCentre = centres[i].substring(state.length+1);
					centreSelect[centreSelect.length] = new Option(thisCentre.substring(thisCentre.indexOf('|')+1), thisCentre.substring(0,thisCentre.indexOf('|')));			}
			}
		} else {
			while (centreSelect.length > 0) centreSelect[0]= null;
			centreSelect[centreSelect.length] = new Option('Select a Westfield','');
			for (var i=0; i < centres.length; i++) {
				
				var thisValue = centres[i].substring(centres[i].indexOf("|")+1);
				var thisValue = thisValue.substring(thisValue.indexOf("|")+1);
				var thisCentreId = thisValue.substring(0,thisValue.indexOf('|'));
				var thisCentre = thisValue.substring(thisValue.indexOf("|")+1);
				if (thisCentreId != null && thisCentreId.length > 0) {
					centreSelect[centreSelect.length] = new Option(thisCentre, thisCentreId);			
				}
			}
		}
	
	}
}

function stateSelectedProduct(state) {
	
	if (document.findProductForm.find_product_centre) {
		
		var centreSelect = document.findProductForm.find_product_centre;
		
		if (state != null && state.length > 0){
			while (centreSelect.length > 0) centreSelect[0]= null;
			centreSelect[centreSelect.length] = new Option('Select a Westfield','');
			for (var i=0; i < centres.length; i++) {
				if (centres[i].indexOf(state) == 0) {
					var thisCentre = centres[i].substring(state.length+1);
					centreSelect[centreSelect.length] = new Option(thisCentre.substring(thisCentre.indexOf('|')+1), thisCentre.substring(0,thisCentre.indexOf('|')));			}
			}
		} else {
			while (centreSelect.length > 0) centreSelect[0]= null;
			centreSelect[centreSelect.length] = new Option('Select a Westfield','');
			for (var i=0; i < centres.length; i++) {
				
				var thisValue = centres[i].substring(centres[i].indexOf("|")+1);
				var thisValue = thisValue.substring(thisValue.indexOf("|")+1);
				var thisCentreId = thisValue.substring(0,thisValue.indexOf('|'));
				var thisCentre = thisValue.substring(thisValue.indexOf("|")+1);
				if (thisCentreId != null && thisCentreId.length > 0) {
					centreSelect[centreSelect.length] = new Option(thisCentre, thisCentreId);			
				}
			}
		}
	
	}
}

/* COOKIES */

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function updateCookies(value) {
	var fontValue = readCookie("westfield_tab");
	if (fontValue != null) {
		//Delete and Create New One
		createCookie("westfield_tab","",-1);
		createCookie("westfield_tab",value,7);
	} else {
		//Create New One
		createCookie("westfield_tab",value,7);
	}
}

function storeTab() {
	 
	 $('ul.find-tabs li').removeClass('find-a-centre-selected');
	 $('ul.find-tabs li').removeClass('find-a-product-selected');
	 
	 var tabId = $($('ul.find-tabs li').get(1)).attr('class');
	 $($('ul.find-tabs li').get(1)).addClass(tabId + '-selected');
	 $('.form-container').hide();
 	 $('#'+tabId).show();
	 
}

function centreTab() {

	$('ul.find-tabs li').removeClass('find-a-store-selected');
	$('ul.find-tabs li').removeClass('find-a-product-selected');
	
	var tabId = $($('ul.find-tabs li').get(0)).attr('class');
	$($('ul.find-tabs li').get(0)).addClass(tabId + '-selected');
	$('#'+tabId).show();

}

function productTab() {

	$('ul.find-tabs li').removeClass('find-a-store-selected');
	$('ul.find-tabs li').removeClass('find-a-centre-selected');
	
	var tabId = $($('ul.find-tabs li').get(2)).attr('class');
	tabId = tabId.replace(' last','');
	
	$($('ul.find-tabs li').get(2)).addClass(tabId + '-selected');
	$('#'+tabId).show();

}


function selectTab(tabName) {
	
	/* put value from cookies as priority */
	var prevTab = readCookie("westfield_tab");
	
	if (prevTab != null) {
		
		if (prevTab == "centre") {
			centreTab();			
		} else if (prevTab == "store") {
			storeTab();
		} else if (prevTab == "product") {
			if (centreId == "uscentres") {
				productTab();
			} else {
				if (tabName == "product") {
					productTab();
				} else if (tabName == "store") {
					storeTab();
				} else {
					centreTab();
				}
			}
		}
		
	} else if (tabName == "product") {
		productTab();
	} else if (tabName == "store") {
		storeTab();
	} else {
		/* default */
		centreTab();
	}
	
}

var currentOverlay = "";

$(document).ready(function() {
						   
	/* Initial Custom Tab */
	$('.form-container').hide();
	/* var tabId = $($('ul.find-tabs li').get(0)).attr('class');
	$($('ul.find-tabs li').get(0)).addClass(tabId + '-selected');
	$('#'+tabId).show(); */
	
	/* absolute the position */
	$("ul.find-tabs").css({display: "block"});
	$("legend").css({display: "none"});
	$("fieldset").css({border: "0"});
	
	$('form[@name="centreSearchForm"] .input-text').focus(function() {
		$(this).attr("value","");
	});
	
	$('form[@name="storeSearchForm"] .input-text').focus(function() {
		$(this).attr("value","");
	});
	
	/* search and change all the input into a tag type button */
	
	$('form[@name="findProductForm"] input.input-submit').each(function() {
		$(this).after('<span class="button-submit" id="button-submit-find-product"><a href="#">submit</a></span>');
		$(this).remove();
	});
	
	$('input.input-submit').each(function() {
		$(this).prev().after('<span class="button-submit"><a href="#">submit</a></span>');
		$(this).remove();
	});
	
	$('input.newsletter-profile-input-submit').each(function() {
		$(this).after('<span class="button-submit-query" id="button-newsletter-profile-submit"><a href="#">'+$(this).attr('value')+'</a></span>');
		$(this).remove();
	});
	
	/* search and change all the input into a tag type button */
	$('input.contact-us-input-submit').each(function() {
		$(this).after('<span class="button-submit-query" id="button-contact-us-submit"><a href="#">'+$(this).attr('value')+'</a></span>');
		$(this).remove();
	});
	
	$('input.your-details-input-submit').each(function() {
		$(this).after('<span class="button-submit-query" id="button-your-details-submit"><a href="#">'+$(this).attr('value')+'</a></span>');
		$(this).remove();
	});
	
	$('input.input-search').each(function() {
		$(this).after('<span class="button-submit" id="button-search"><a href="#">submit</a></span>');
		$(this).remove();
	});
	
	$('input.newsletter-login-submit, input.input-submit-ourstores').each(function() {
		$(this).after('<span class="button-submit" id="button-newsletter-login"><a href="#">submit</a></span>');
		$(this).remove();
		
	});
	
	$('input.newsletter-input-subscribe').each(function() {
		$(this).after('<span class="button-submit-query" id="button-newsletter-subscribe"><a href="#">'+$(this).attr('value')+'</a></span>');
		$(this).remove();
	});
	
	/* attached onchange function on state */
	$('form[@name=centreSearchForm] select.state').change(function() {
		//stateSelected(this[this.selectedIndex].value);
		stateSelected($(this).val());
	});
	
	$('form[@name=findProductForm] select.select-state-b').change(function() {
		//stateSelected(this[this.selectedIndex].value);
		stateSelectedProduct($(this).val());
	});
	
	/*$('form[@name=centreSearchForm] span.button-submit a').click(function() {
		$(this).parents("form")[0].submit();
		return false;
	});
	
	$('form[@name=storeSearchForm] span.button-submit a').click(function() {
		$(this).parents("form")[0].submit();
		return false;
	});*/
	
	/*$('form[@name=search-our-stores] span.button-submit a').click(function() {
		$(this).parents("form")[0].submit();
		return false;
	});*/
	
	$('ul.find-tabs li').click(function() {
		
		var className = $(this).attr('class');
		
		if (className.search('selected') == -1) {
		
			className = className.replace(className+'-selected','');
			className = className.replace(' last','');
			
			if ((className != 'find-a-gift') && (className != 'find-a-product-link')) {
				
				if (className == 'find-a-centre') {
					updateCookies("centre");
				} else if (className == 'find-a-store') {
					updateCookies("store");
				} else if (className == 'find-a-product') {
					updateCookies("product");
				}
				
				$('ul.find-tabs li').removeClass('find-a-store-selected');
				$('ul.find-tabs li').removeClass('find-a-product-selected');
				$('ul.find-tabs li').removeClass('find-a-centre-selected');
				$(this).addClass(className+'-selected');
				$('.form-container').hide();
				$('#'+className).fadeIn();
				
			} else {
				location.href=$(this).find('a').attr('href');
			}
		
		}
		
		return false;
	
	});
	
	/* Site Map */
	
	$('dl.site-map ul li a.minus').toggle(function() {
		
		$($(this).parent().find('ul').get(0)).hide();
		$(this).removeClass('minus');
		$(this).addClass('plus');
		return false;					
	}, function() {
		
		$($(this).parent().find('ul').get(0)).show();
		$(this).removeClass('plus');
		$(this).addClass('minus');
		return false;
	});
	
	/* our store search function replace form */
	$("form[@name=categorySearchForm] #keywords").attr("name","keywords");

	$("form[@name=alphaSearchForm] #initial").attr("name","initial");

	
	$("ul.category-structure li dl a").click(function() { 
		value = $(this).text();
		$("form[@name=categorySearchForm] #keywords").attr("value",value);
		$(this).parents("form")[0].submit();
	});
	
	/* make all form submit from javascript a tag */
	$(".button-submit").click(function () {
		$(this).parents("form")[0].submit();
	});
	
	/* enable all button */
	$(".button-submit").css({display: "block"});
	$("ul.pagination li a").css({display: "block"});					   
	$("ul.category-structure li dl a").css({display: "block"});		
	
/*	$(".edit-template").hover(function() {
		
		
		
		var url = $(this).attr('href');
		var order = 0;
		var arrCurrentPos = findPos($(this).parent().parent().parent(),order);
		currentOverlay = "currentOverlay" + order +"-highlight";
		
		if (($('#currentOverlay '))) {

			$("body").prepend("<div id='" + currentOverlay + "' class='highlight-temp'><h2>Click to edit this content</h2></div>");
			$("#"+currentOverlay).css("top",arrCurrentPos[1]);
			$("#"+currentOverlay).css("left",arrCurrentPos[0]);
			$("#"+currentOverlay).css("width",arrCurrentPos[2]);
			$("#"+currentOverlay).css("height",arrCurrentPos[3]);
			
			$('#'+currentOverlay).hover(function() {
			
			}, function() {
				$(this).remove();
			});
			
			$('#'+currentOverlay).click(function() {
				window.open(url);
			});
		
		}
	}, function() {
		
		
	});*/
	
	

});




/* Validation for US National */
	
$(document).ready(function() {
	
	if (document.getElementById("findProductForm")) {	
		
		var validator = $("#findProductForm").validate({
				rules: {
					find_product_centre: "required"
				},
				messages: {
					find_product_centre: "Please select a centre"
				}
			});	
		
		$('#button-submit-find-product').click(function() {
			if (validator.form()) {
				location.href = "http://" + $('#find_product_centre').attr("value") + ".nearbynow.com";
			}
		});
	
	}
});

/* opening hours */
$(document).ready(function() {
	var COOKIE_NAME = "centres_visited";
	var COOKIE_NAME_STATE = "last_visited_state";

	/* default selected state */
	if ( $.cookie(COOKIE_NAME_STATE) == null )
	{
		$('.opening-hours-nsw-centres .opening-hours-centre-list-container').show();
		$('ul.opening-hours-state-list-text li').eq(1).addClass('selected');
   }
	else
	{
		$('.opening-hours-'+$.cookie(COOKIE_NAME_STATE)+'-centres .opening-hours-centre-list-container').show();
		$('ul.opening-hours-state-list-text li')
			.find('a.'+$.cookie(COOKIE_NAME_STATE))
			.parent()
			.addClass('selected');
		$('.opening-hours-right-container img').attr("src","../images/maps/map_"+$.cookie(COOKIE_NAME_STATE)+".gif");
	}
	
	/* show and hide state and centres upon clicking on state nav */
	$('ul.opening-hours-state-list-text li').click(function() {
		var className = ($(this).find('a').attr('class'));
		
		$('ul.opening-hours-state-list-text li').removeClass('selected');
		$(this).addClass('selected');
		$('.opening-hours-centre-list-container').hide();
		$('.opening-hours-'+className+'-centres .opening-hours-centre-list-container').fadeIn(1000);
		$('.opening-hours-right-container img').attr("src","../images/maps/map_"+className+".gif");
		
		createCookie('last_visited_state',className,'');
	});
	
	/* show and hide state and centres upon clicking on map */
	$('map area').click(function() {
		this.blur();

		var className = ($(this)).attr('class');

		$('ul.opening-hours-state-list-text li').removeClass('selected');
		$('ul.opening-hours-state-list-text li')
			.find('a.'+className)
			.parent()
			.addClass('selected');
		$('.opening-hours-centre-list-container').hide();
		$('.opening-hours-'+className+'-centres .opening-hours-centre-list-container').fadeIn(1000);
		$('.opening-hours-right-container img').attr("src","../images/maps/map_"+className+".gif");

		createCookie('last_visited_state',className,'');
	});
	
	/* get last 3 visited centres from cookie */
	if ( $.cookie(COOKIE_NAME) != null )
	{
		var index = 0;
		var visited_centres = "";
		var cookie_value = $.cookie(COOKIE_NAME).split(",");

		$('.opening-hours-visited-text').show();

		$.each(cookie_value, function() {
			var centre_hour_href = window.location.href;		
			var centre_id = cookie_value[index];
			centre_id = centre_id.replace(/\s*/g, "").toLowerCase();
			
			if ( centre_hour_href.match(/teamsite/) )
			{
				var REGEX = /^(.+)\/.+\/(WORKAREA)\/[a-z]+\/.*$/;
				centre_hour_href = centre_hour_href.replace(REGEX, "$1/"+centre_id+"/$2/"+centre_id+"/shoppinghours/");
			}
			else
			{
				var REGEX = /^(.+)\/[a-z]+\/.*$/;
				centre_hour_href = centre_hour_href.replace(REGEX, "$1/"+centre_id+"/shoppinghours/");
			}

			$('span.opening-hours-visited-centres-list').each(function() {
				if ( index == cookie_value.length-1 )
				{
					var string = "<a href=\""+centre_hour_href+"\" onclick=\"setArrayCookie('centres_visited', '"+cookie_value[index]+"');\">"+cookie_value[index]+"</a>";
				}
				else
				{
					var string = "<a href=\""+centre_hour_href+"\" onclick=\"setArrayCookie('centres_visited', '"+cookie_value[index]+"');\">"+cookie_value[index]+"</a>, ";
				}

				visited_centres = visited_centres.concat(string);
				$(this).html(visited_centres);
			});
			index++;
		});
	}
});

/* set visited centre to cookie */
function setArrayCookie(cookie_name, new_value)
{
	var cookie_value = new Array();

	if(!Array.indexOf){
	  Array.prototype.indexOf = function(obj){
	   for(var i=0; i<this.length; i++){
		if(this[i]==obj){
		 return i;
		}
	   }
	   return -1;
	  }
	}

	if ( $.cookie(cookie_name) != null )
	{
		cookie_value = $.cookie(cookie_name).split(',');

		if ( cookie_value.indexOf(new_value,0) != -1 )
		{
			cookie_value.splice(cookie_value.indexOf(new_value,0),1);
		}
		else
		{
			var cookie_value_length = cookie_value.length;
			if ( cookie_value_length >= 3 )
			{
				cookie_value.pop();
			}
		}

		cookie_value = new_value.concat(","+cookie_value);
	}
	else
	{
		cookie_value = new_value;
	}

	document.cookie = cookie_name+"="+cookie_value+""+"; path=/";
}

// EDM - UPDATE YOUR DETAILS - Add/remove centre subscription(s)
var uyd_index = 0;
function create_centre_list(centre_id_list, centre_name_list)
{
	var centre_list  = "";
	uyd_index = $('.centre-subscriptions').size();
	
	// Build centre list
	centre_id_list   = centre_id_list.split(/,/);
	centre_name_list = centre_name_list.split(/,/);
	for (i = 0; i < centre_name_list.length; i++) {
		centre_list = centre_list+"<option value='"+centre_id_list[i].toUpperCase()+"'>"+centre_name_list[i]+"</option>\n";
	}

	uyd_index++;
	$('.uyd-new-subscriptions').append([
		'<div class="centre-subscriptions" id="centre-subscriptions-'+uyd_index+'">',
			'<div class="uyd-inner-subscriptions">',
				'<div class="uyd-centre-list-container">',
					'<div class="uyd-centre-list">',
						'<select class="subscribe-'+uyd_index+'" name="subscribe" onchange="get_segments('+uyd_index+')">',
							'<option value="">-- Select a centre --</option>',
							centre_list,
						'</select>',
					'</div>',
					'<div class="uyd-funky-spinner"><img src="/common/images/background/funky-spinner.gif" /></div>',
					'<div class="uyd-remove-subscription"><a class="delete-centre-subscription-'+uyd_index+'" href="#" onclick="destroy_subscription('+uyd_index+');">Remove</a></div>',
				'</div>',
				'<ul class="uyd-subscribed-segment" id="segment-list-'+uyd_index+'">',
				'</ul>',
			'</div>',
		'</div>'
	].join(''));
}

function select_deselect_all(index) {
	if ( $('#unsubscribe-all-'+index).attr("checked") ) {
		$('.subscribe-'+index).attr("checked","");
	}
}

function deselect(index) {
	if ( $('#unsubscribe-all-'+index).attr("checked") ) {
		$('#unsubscribe-all-'+index).attr("checked","");
	}
}

function destroy_subscription(index) {
	uyd_index--;
	$('#centre-subscriptions-'+index+'').remove();
}

function get_segments(index) {
	var location = window.location;
	var regex    = /([^\/]+?)((\?|#).*)?$/;
	var match    = regex.exec(location);
	location     = match[1]+"/segment.html";
	var subscribe  = $('.subscribe-'+index+'').val();
	var dataString = 'subscribe='+ subscribe;
	$('.uyd-funky-spinner img').css('display','inline')
	$.ajax({  
		type:    "POST",
		url:     location,
		data:    dataString,
		success: function(segments) {
			$('.uyd-funky-spinner img').css('display','none')
			$('ul#segment-list-'+index+' li').remove();
			$('ul#segment-list-'+index+'').append(segments);
		}  
	});  	
}