/* --------- Plugins --------------------------------------------------------- */

	/* Plugin for search fields */
	
	(function ($) {
	
	$.fn.hint = function (blurClass) {
	  if (!blurClass) { 
	    blurClass = 'blur';
	  }
	    
	  return this.each(function () {
	    // get jQuery version of 'this'
	    var $input = $(this),
	    
	    // capture the rest of the variable to allow for reuse
	      title = $input.attr('title'),
	      $form = $(this.form),
	      $win = $(window);
	
	    function remove() {
	      if ($input.val() === title && $input.hasClass(blurClass)) {
	        $input.val('').removeClass(blurClass);
	      }
	    }
	
	    // only apply logic if the element has the attribute
	    if (title) { 
	      // on blur, set value to title attr if text is blank
	      $input.blur(function () {
	        if (this.value === '') {
	          $input.val(title).addClass(blurClass);
	        }
	      }).focus(remove).blur(); // now change all inputs to title
	      
	      // clear the pre-defined text when form is submitted
	      $form.submit(remove);
	      $win.unload(remove); // handles Firefox's autocomplete
	    }
	  });
	};
	})(jQuery);
	
	
	/**
	 * jQuery Initial input value replacer
	 * 
	 * Sets input value attribute to a starting value  
	 * @author Marco "DWJ" Solazzi - hello@dwightjack.com
	 * @license  Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
	 * @copyright Copyright (c) 2008 Marco Solazzi
	 */
	(function (jQuery) {
		/**
		 * Setting input initialization
		 *  
		 * @param {String|Object|Bool} text Initial value of the field. Can be either a string, a jQuery reference (example: $("#element")), or boolean false (default) to search for related label
		 * @param {Object} [opts] An object containing options: 
		 * 							color (initial text color, default : "#666"), 
		 * 							e (event which triggers initial text clearing, default: "focus"), 
		 * 							force (execute this script even if input value is not empty, default: false)
		 * 							keep (if value of field is empty on blur, re-apply initial text, default: true)  
		 */
		jQuery.fn.inputLabel = function(text,opts) {
			o = jQuery.extend({ color: "#666", e:"focus", force : false, keep : true}, opts || {});
			var clearInput = function (e) {
				var target = jQuery(e.target);
				var value = jQuery.trim(target.val());
				if (e.type == e.data.obj.e && value == e.data.obj.innerText) {
					jQuery(target).css("color", "").val("");
					if (!e.data.obj.keep) {
						jQuery(target).unbind(e.data.obj.e+" blur",clearInput);
					}
				} else if (e.type == "blur" && value == "" && e.data.obj.keep) {
					jQuery(this).css("color", e.data.obj.color).val(e.data.obj.innerText);
				}
			};
			return this.each(function () {
						o.innerText = (text || false);
						if (!o.innerText) {
							var id = jQuery(this).attr("id");
							o.innerText = jQuery(this).parents("form").find("label[for=" + id + "]").hide().text();
						}
						else 
							if (typeof o.innerText != "string") {
								o.innerText = jQuery(o.innerText).text();
							}
				o.innerText = jQuery.trim(o.innerText);
				if (o.force || jQuery(this).val() == "") {
					jQuery(this).css("color", o.color).val(o.innerText);
				}
					jQuery(this).bind(o.e+" blur",{obj:o},clearInput);
				
			});
		};
	})(jQuery);
	
	

/* --------- Front End Scripts --------------------------------------------------------- */

$(document).ready(function() {
	
	/* Input text hints  */
	$('input[title!=""]').hint();
	
	
	/* Login form password label */
	
	$('input#login-form-password').blur(function() {
		if (!$('input#login-form-password').val()) {
			$(this).addClass('password-hint');
		}
	 });	
	
	$('input#login-form-password').focus(function() {
		if ($(this).hasClass('password-hint')) $(this).removeClass('password-hint');
	});
	
	$('input#login-form-password').blur();	
	
	
	/* IE inputs tweaks */
	$("div.form-default div.inputs input.text").focus(function(){
		$(this).parents("div.input-container").css("background-position","0 -41px");
	});
	$("div.form-default div.inputs input.text").blur(function(){
		$(this).parents("div.input-container").css("background-position","100% 0");
	});
	$("div.rewards-header input.text").focus(function(){
		$(this).parents("div.rewards-search").css("background-position","0 -41px");
		$(this).css("color","#898989");
	});
	$("div.rewards-header input.text").blur(function(){
		$(this).parents("div.rewards-search").css("background-position","0 0");
		$(this).css("color","#e1e1e1");
	});
	$("div.form-default textarea").focus(function(){
		$(this).parents("div.textarea-container").css("background-position","0 -160px");
	});
	$("div.form-default textarea").blur(function(){
		$(this).parents("div.textarea-container").css("background-position","0 0");
	});
	
	/* IE Inputs Rollover */
	$("div.button").mouseover(function(){
		$(this).css("background-position","0 -40px");
		$(this).children("input").css("background-position","100% -40px").css("color","#5cd0fc");
	});
	$("div.button").mouseout(function(){
		$(this).css("background-position","0 0");
		$(this).children("input").css("background-position","100% 0").css("color","#fff");
	});
	
	
	/* Enter Magic Code input focus */
	$(".widget-enter-magic-code input").focus();
	$(".widget-enter-magic-code .enter-magic-code-enabled").click(function(){
		if (isEmpty($(this).siblings("span").children("input").val())){
			return false;
		}
		else {
			$(this).hide();
			$(this).siblings(".enter-magic-code-disabled").show();
			document.magicCodeForm.submit();
			return true;
		}
	});
	
	/* Carousels */
	
		/* Home - Signed in */
		jQuery('#promotions #mycarousel').jcarousel({
			scroll: 1,
			auto: 10,
			start: 1
		});
		
		$(".jcarousel-skin-promotions").mouseover(function(){
			$(this).find(".promotion-text").show();
			$(".jcarousel-prev-horizontal").css("top","119px");
			$(".jcarousel-next-horizontal").css("top","119px");
		});
		$(".jcarousel-skin-promotions").mouseout(function(){
			$(this).find(".promotion-text").hide();
			$(".jcarousel-prev-horizontal").css("top","11900px");
			$(".jcarousel-next-horizontal").css("top","11900px");
		});
		
		$(".jcarousel-skin-promotions li.promotion").mouseover(function(){
			$(this).css("cursor","pointer");
		});
		
		$("#promotions li.promotion").click(function(){
			var url = $(this).find("h2 a").attr("href");
			if ($(this).hasClass("new-window")){
				window.open (url,"mywindow");
				return false;
			}
			else {
				window.location = url;
			}
		});
		
		
		/* Home - Not signed in */	
		function itemLastIn(carousel, li, index, state)
		{
			clearCarousel(carousel, li, index, state);
			if(index > 2){
				$(li).addClass('reward-right');
				if(index > 3){
					$(li).prev("li").addClass('reward-right');
				}
			}
			/*
			$("ul#mycarousel li.item").each(function(){
				if ($(this).hasClass("reward-right")){
					$(this).find("h3 a").prepend("<span class='testspan' style='color:red;'>Class: reward-right.</span> ");
				}
			});
			*/
		}
		function clearCarousel(carousel, li, index, state)
		{
		    $(li).siblings(".reward-right").removeClass('reward-right');
		    //$(".testspan").remove();
		}
		
		jQuery('.module-rewards-showcase #mycarousel').jcarousel({
			scroll: 4,
			itemLastInCallback: itemLastIn
			
		});
		
		
		
		
	/* My Account */
	$(".my-account-section a.change").click(function(){
		$(this).siblings(".change-details").show();
		$(this).siblings(".content").hide();
		$(this).hide();
		return false;
	});
	$(".my-account-section a.cancel").click(function(){
		$(this).parents(".change-details").hide();
		$(this).parents(".change-details").siblings(".content").show();
		$(this).parents(".change-details").siblings("a.change").show();
		return false;
	});	
	$(".review-your-order .my-account-section a.change").click(function(){
		$(this).parents("ul.my-account-sections").siblings("div.button").hide().siblings("a.cancel").hide();
		$("#buttonRedeem").hide();
		$("#buttonRedeem input").hide();
		$("#buttonRedeemTemp").show();
		$(this).siblings(".address-input").children("input.radio").attr("checked","checked");
		return false;
	});
	$(".review-your-order .my-account-section a.cancel").click(function(){
		$(this).parents("ul.my-account-sections").siblings("div.button").show().siblings("a.cancel").show();
		$("#buttonRedeem").show();
		$("#buttonRedeem input").show();
		$("#buttonRedeemTemp").hide();
		return false;
	});
	
	
	/* Competitions Popup */
	
	$("a.popup").click(function(){
		var link = $(this).attr("href");
		window.open(link,"termsandconditions","scrollbars=1,width=350,height=450");
		return false;
	});	
	
	
	/* Footer CSS Tweaks */
	$("#footer tr:first td:last").addClass("last");
	$("#footer tr:first td:first a").addClass("first");
	
	
	/* Rewards Left hand Side Nav */
	$(".rewards-nav h3 a").click(function(){
		$(this).parents("li").toggleClass("active");
		return false;
	});
	
	$("li.list-all-films a.list-all-films").toggle(
			function(){
				$("div.rewards-nav ").css("padding-bottom","100px");
				$("div.list-all-films div.title").html("<h4>"+dmrMsgRewardsBrowseByFilm+"</h4>");
				$("li.reward").css("z-index","1");
				$("div.list-all-films").css("z-index","999999");
				$("div.list-all-films").show();
				return false;
			},
			function(){
				$("div.list-all-films h4").remove();
				$("div.list-all-films").hide();
				$("div.rewards-nav ").css("padding-bottom","0");
			return false;
	});
	
	$("div.list-all-films").mouseover(function(){
		$("li.reward").css("z-index","1");
		return false;
	});
	
	$("div.list-all-films div.close").click(function(){
		$("li.list-all-films a.list-all-films").click();
		return false;
	});
	
	/* Rewards Top Navigation */
	$(".rewards-nav-browse li.rewards-nav-browse").mouseover(function(){
		$("div.rewards-subnav-browse").hide();
		$(".module-rewards").css("z-index","1");
		$(this).css("z-index","99999");
		$(this).children("div.rewards-subnav-browse").show();
		$(this).children("h3").children("a").addClass("active");
		return false;
	});
	
	$(".rewards-nav-browse li.rewards-nav-browse div.close").click(function(){
		$("div.rewards-subnav-browse").hide();
		$(this).children("h3").children("a").removeClass("active");
		return false;
	});
	
	$(".rewards-nav-browse li.rewards-nav-browse").mouseout(function(){
		$(this).children("div.rewards-subnav-browse").hide();
		$(this).children("h3").children("a").removeClass("active");
		return false;
	});
	
	
	/* Rewards lists */	
	$("div.rewards-recommended").each(function(){
		$(this).find("li.reward:gt(1)").addClass("reward-right");
	});
	
	var liIndex = 1;
	var liRow = 1;
	$(".browse-rewards li.reward").each(function(){
		if (liIndex % (4*liRow-1) == 0) {
			$(this).addClass("reward-right");
		}
		else if (liIndex % 4 == 0) {
			$(this).addClass("reward-right").addClass("last");
		}
		else {
			$(this).removeClass("reward-right");
		}
		liIndex++;
		if (liIndex % 4 == 0){liRow++;};
	});
	
	/* Rewards popup */		
	$("li.reward").mouseover(function(){
		$(".rewards-popup").hide();
		$("li.reward").css("z-index","1");
		$(this).css("z-index","8888");
		var popup = $(this).children(".rewards-popup");
		var popup_title = $(this).find(".reward-title a").html();
		var popup_points = $(this).find("p.points").html();
		//var popup_link = $(this).find(".reward-title a").attr("href");
		
		$(this).find("div.title a").html(popup_title);
		$(this).children(".rewards-popup").children("div.points").html(popup_points);
		
		popup.show();
		return false;
	});
	
	$("li.reward div.close").click(function(){
		$(".rewards-popup").hide();
		return false;
	});
	
	$("li.reward").mouseout(function(){
		$(".rewards-popup").hide();
		return false;
	});
	
	
	/* FAQ */
	$("ul.faq li dl dt").toggle(
		function(){			
			$("ul.faq li dl dt.active").click();			
			$(this).addClass("active");
			$(this).next().append("<a href=\"#\" class=\"close\" onclick='$(this).parents(\"dd\").prev(\"dt\").click();$(this).remove();return false;'>"+dmrMsgRewardsClose+"</a>");
			$(this).next("dd").show();
			return false;
		},
		function(){
			$(this).removeClass("active");
			$(this).next("dd").hide();
			$(this).next("dd").children("a.close").remove();
			return false;
		}
	);	
	
	/* Link behaviours */
	$('a.new-window').click(function(){
        window.open(this.href);
        return false;
    });
	
	$('div.footer-content table a').click(function(){
        window.open(this.href);
        return false;
    });
	
	$('a.go-back').click(function(){
		history.back();
        return false;
    });
	
	$('.wish-list a').click(function(){
		wurl = this.href;
		findStr="reward=";
		addActionIndex=wurl.indexOf("add-to-wishlist");
		if(!isEmpty(addActionIndex) && addActionIndex > 0){	
			index = wurl.indexOf(findStr);
			rewardPK = wurl.substring(index+findStr.length);
			MyWishlist.add(rewardPK, wishlistCb);
			$(this).parents(".wish-list").html(dmrMsgWishlistAdd);
			return false;
		}
    });
	
	/* My Points */
	$(".table1 td.view-all a").toggle(	
		function () {
			$(this).parents(".table1").find("tr.all-points").show();
			$(this).html(getMyPointsMessage($(this).parents(".table1"), false));
			return false;
		},
		function () {
			$(this).parents(".table1").find("tr.all-points").hide();
			$(this).html(getMyPointsMessage($(this).parents(".table1"), true));
			return false;
		}
	);
	
	function getMyPointsMessage(obj, all){
		var objId = obj.attr('id');
		var outMsg;
		if(objId == 'table1Rewards'){
			if(all){
				outMsg = dmrMsgMyPointsViewRedeemedRewardsAll;
			}else{
				outMsg = dmrMsgMyPointsViewRedeemedRewardsLatest;
			}
		}else if(objId == 'table1Codes'){
			if(all){
				outMsg = dmrMsgMyPointsViewCodesAll;
			}else{
				outMsg = dmrMsgMyPointsViewCodesLatest;
			}
		}else if(objId == 'table1Offers'){
			if(all){
				outMsg = dmrMsgMyPointsViewOffersAll;
			}else{
				outMsg = dmrMsgMyPointsViewOffersLatest;
			}
		}
		
		return outMsg;
	}
	
	/* Print */
	$(".print").click(function(){
		window.print();
		return false;
	});
	
	/* Flash */
	if ($("#flashcontent")){$("#flashcontent p").show();};
	if ($("#flashContent1")){$("#flashContent1 p").show();};
	if ($("#flashContent2")){$("#flashContent2 p").show();};
	if ($("#flashContent3")){$("#flashContent3 p").show();};
	
	
	/* Message Centre */
	
	$(".section-message-centre th.select-all a").toggle(
		function(){
			$(this).text(dmrMsgMessageCentreUnselectAll);
			$(this).parents("table").find("input:checkbox").attr("checked","checked");
			return false;
		},
		function(){
			$(this).text(dmrMsgMessageCentreSelectAll);
			$(this).parents("table").find("input:checkbox").removeAttr("checked");
			return false;
		}
	);	
	
	//$(".section-message-centre span.hidden:empty").parent().siblings("div.controls").remove();
	//$(".section-message-centre span.hidden:empty").remove();
	//$(".section-message-centre span.hidden").before("<span class='ellipsis'> ...</span>");
	//$(".section-message-centre div.controls").text(dmrMsgMessageCentreExpand);
	
	$(".text-content").each(function(){
		var altura = $(this).height();
		if (altura >= 35){
			$(this).parents("td.message").append("<div class='controls'></div>");
		}
	});
	$(".section-message-centre div.controls").text(dmrMsgMessageCentreExpand);
	
	$(".section-message-centre div.controls").hover(
		function(){
			$(this).css("color","#5cd0fc");
		}, 
		function(){
			$(this).css("color","#16a5ce");
		}
	);
	$(".section-message-centre div.controls").toggle(
		function() {
			//$(this).parent().find(".hidden").show();
			//$(this).parent().find(".ellipsis").hide();
			$(this).parent().children(".text").children(".text-content").css("max-height","10000px");
			$(this).text(dmrMsgMessageCentreMinimize);
			return false;
		},
		function(){
			//$(this).parent().find(".hidden").hide();
			//$(this).parent().find(".ellipsis").show();
			$(this).parent().children(".text").children(".text-content").css("max-height","35px");
			$(this).text(dmrMsgMessageCentreExpand);
			return false;
		}
	);
	
	/* Contact Us */
	if (! jQuery.support.cssFloat) { // only applied to IE
		var selectWidth = $(".section-contact-us .rounded-box select").width();
		$("div.section-contact-us div.rounded-box").width(selectWidth + 15);
	}

	$("#topSigninButton").click(checkSession);
	$("#mainSigninButton").click(checkSession2);
	
	function checkSession(){
		$("#topSigninButton").hide();
		$("#login-form-button-disabled").show();
		Register.checkSession(unsecureCookieCsCb);
	}
	function unsecureCookieCsCb(){
		Register.unsecureCookie(csCb);
	}
	function csCb(){
		document.topSigninForm.submit();
	}
	function checkSession2(){
		$(this).hide();
		$(this).siblings(".submit-sign-in-disabled").show();
		$(this).parent().siblings(".waiting").show();
		Register.checkSession(unsecureCookieCsCb2);
	}
	function unsecureCookieCsCb2(){
		Register.unsecureCookie(csCb2);
	}
	function csCb2(){
		document.mainSigninForm.submit();
	}
});




//below is vladimir's territory :)

function wishlistCb(r){
// nothing here
}

function getDwrValues(formId){
	var json = $('#'+formId).serializeArray();
	reply={};
	var i=0;
	for (i=0;i<json.length;i++){
		//alert(json[i].name+" = "+json[i].value);
		if(!isEmpty(json[i].value)){
			if(json[i].value == 'false' && json[i].name.startsWith('_')){
				//do nothing
			}else{
				if(!isEmpty(reply[json[i].name])){
					reply[json[i].name] += ','+json[i].value;
				}else{
					reply[json[i].name] = json[i].value;
				}
			}
		}
	}
	return reply;
}

String.prototype.startsWith = function(str){
	return (this.match("^"+str)==str);
}

function replaceAll( str, searchTerm, replaceWith, ignoreCase )	{
	var regex = "/"+searchTerm+"/g";
	if( ignoreCase ) regex += "i";
	return str.replace( eval(regex), replaceWith );
}

function isEmpty(data){
	if (data == undefined) { return true; }
	else if(typeof data == '' || data === null) { return true; }
	else if(typeof data == 'string' && (data === '0' || data.replace(/^\s+|\s+$/g, '') === '')) { return true; }
	else if(typeof data == 'number' && data === 0) { return true; }
	else if(typeof data == 'boolean' && data === false) { return true; }
	else if(typeof data == 'object'){
		if(data instanceof Array && data.length == 0) { return true; }
		else{
			var n = 0;
			for(var i in data){
				if(!data.hasOwnProperty(i)) { continue; }
				n++;
			}
			if(n == 0) { return true; }
		}
	}
	return false;
}

var nameToId = {
		"member.email": "email",
		"attr[email]": "email",
		"confirmEmail": "confirmEmail",
		"member.guardianEmail": "guardianEmail",
		"member.authInfo.password": "password",
		"confirmPassword": "confirmPassword",
		"member.firstName": "firstName",
		"member.lastName": "lastName",
		"member.gender": "gender",
		"attr[firstName]": "firstName",
		"attr[lastName]": "lastName",
		"member.address.country": "country",
		"dobYear": "dobYear", 
		"agreedToTcAndCs": "agreedToTcAndCs",
		"newPassword": "newPassword", 
		"oldPassword": "oldPassword",
		"member.address.address1": "homeAddress1",
		"member.address.address2": "homeAddress2",
		"member.address.address3": "homeAddress3",
		"member.address.city": "homeCity",
		"member.address.county": "homeCounty",
		"member.address.postcode": "homePostcode",
		"member.phone": "homePhone",
		"recipientFirstName": "deliveryFirstName",
		"recipientLastName": "deliveryLastName",
		"deliveryAddress.address1": "deliveryAddress1",
		"deliveryAddress.address2": "deliveryAddress2",
		"deliveryAddress.address3": "deliveryAddress3",
		"deliveryAddress.city": "deliveryCity",
		"deliveryAddress.county": "deliveryCounty",
		"deliveryAddress.postcode": "deliveryPostcode",
		"deliveryAddress.country": "deliveryCountry",
		"member.mobile": "deliveryPhone",
		"notifications": "notifications",
		"member.guardianConsent": "guardianConsent",
		// for refer friend we may have 10 attributes
		"attr[name1]": "name1",
		"attr[email1]": "email1",
		"attr[name2]": "name2",
		"attr[email2]": "email2",
		"attr[name3]": "name3",
		"attr[email3]": "email3",
		"attr[name4]": "name4",
		"attr[email4]": "email4",
		"attr[name5]": "name5",
		"attr[email5]": "email5",
		"attr[name6]": "name6",
		"attr[email6]": "email6",
		"attr[name7]": "name7",
		"attr[email7]": "email7",
		"attr[name8]": "name8",
		"attr[email8]": "email8",
		"attr[name9]": "name9",
		"attr[email9]": "email9",
		"attr[name10]": "name10",
		"attr[email10]": "email10"
	};

function setMsgFreeze(prefix, postfix, msg){
	freeze(prefix);
	setMsg(prefix, postfix, msg);
}

function printMessageDwr(messageDwr){
	setMsg(convertVar(messageDwr.field), messageDwr.status, messageDwr.message);
}

function setWaitMsg(prefix){
	setMsg(prefix, "wait", " ");
}

function setMsg(prefix, postfix, msg){
	postfix = postfix.toLowerCase();		//in css its all lowercase
	clearMsg(prefix);
	$("#"+prefix+"Container").append("<div class=\"form-message form-message-"+postfix+"\" id=\""+prefix+postfix+"\"><span class=\"icon\"></span><span class=\"text\">"+msg+"</span></div>");
}

function clearMsg(prefix){
	$("#"+prefix+"wait").remove();
	$("#"+prefix+"error").remove(); 
	$("#"+prefix+"success").remove(); 
}

function freeze(prefix){
	$("#"+prefix).attr("disabled", "disabled");
	$("#"+prefix+"Container").addClass("disabled");
}

function unfreeze(prefix){
	unblock(prefix);
	$("#"+prefix+"Container").removeClass("disabled");
}

function unblock(prefix){
	$("#"+prefix+"").removeAttr("disabled");
}

function convertVar(varToConvert){
	converted = nameToId[varToConvert];
	
	if(isEmpty(converted)){
		return varToConvert;
	}else{
		return converted;
	}
}

function setAllMsgs(postfix){
	for (var key in nameToId) {
		setMsg(nameToId[key], postfix, "");
	}
}

function clearAllMsgs(){
	for (var key in nameToId) {
		clearMsg(nameToId[key]);
	}
}

function printMessages(respObj){
	if(!isEmpty(respObj.messages)){
		for (var i = 0; i < respObj.messages.length; i++){
			printMessageDwr(respObj.messages[i]);
		}
	}
}

function onCountryChange(country, addr){
	if(!isEmpty(cities[country])){
		$("#"+addr+"CityContainer label").html(cities[country]);
		$("#"+addr+"CountyContainer label").html(counties[country]);
	}
}