/**************************************************
 * Aeroplan sign-in and shop now functions.
 */

/* global default settings for the modal popup */
var apNyroModalSettings = {
	modal: true,
	bgColor:'#ffffff',
	closeButton:''
}

/*
   Attempts to sign in customer with an Ajax call.  Successful signin will
   update page with welcome message, otherwise modal signin popup will appear
   with error message displayed. 
   
   var modal - boolean to indicate if signing in from a modal window
   var shopnow - wheither to call shop now method in case in authentication was successfull
   var productCode - product code is required for shop now method. This parameter is only required if shopnow=true
   var redirectUrl - the link to redirect to 
*/
function apSignIn(modal, shopnow, productCode, redirectUrl) {
	var idPrefix = modal ? "popup_" : "";
	var pin1 = document.getElementById(idPrefix + "pin1").value;
	var pin2 = document.getElementById(idPrefix + "pin2").value;
	var pin3 = document.getElementById(idPrefix + "pin3").value;
	var aeroplanNumber = pin1 + pin2 + pin3;
	var lastName = document.getElementById(idPrefix + "pin").value;
	processRememberNumber(pin1, pin2, pin3, isRememberChecked(modal));
	apCustomerAjaxController.signIn({j_username: aeroplanNumber, j_password: lastName}, {
		callback:
			function (signInResultBean) {
				document.getElementById("login").innerHTML = "<p>" + signInResultBean.welcomeMessage + "</p>";
				document.getElementById("logout").style.display = "inline";
				if (modal && !shopnow) {
					$.nyroModalRemove();
				}
				if (shopnow) {				
					apShopNow(productCode, redirectUrl);
				}
			},
		errorHandler:
			function (error) {
				document.getElementById("ap_popup_signin_error").innerHTML = getSignInErrorMessage(error);
				document.getElementById("ap_popup_signin_error").style.display = "block";
				initRememberNumber(true);
				initRememberNumber(false);
				if (!modal) {
					document.getElementById("ap_popup_signin_button").onclick=function() { return apSignIn(true, false, '', null);};
					$('#ap_popup_signin_link').nyroModalManual(apNyroModalSettings);
				}
				document.getElementById("ap_popup_signin_button").focus();
			}
	});
}

function isRememberChecked(modal) {
	var idPrefix = modal ? "popup_" : "";
	return document.getElementById(idPrefix + "remember").checked;
}

/*
	Attempts to sign in customer using the custid and custname credentials passed in the URL link.
*/
function autoSignIn() {
	var doLogin = true;
	if (custname.length != 0) {
		document.getElementById("pin").value = custname;
	} else {
		doLogin = false;
	}
	if (custid.length == 9) {
		var pin1 = custid.substring(0,3);
		var pin2 = custid.substring(3,6);
		var pin3 = custid.substring(6);
		document.getElementById("pin1").value = pin1;
		document.getElementById("pin2").value = pin2;
		document.getElementById("pin3").value = pin3;
	} else {
		doLogin = false; 
	}
	
	if (doLogin) {
		document.getElementById("apSignin").click();
	} else {
		if (custname.length == 0) {
			document.getElementById("remember").checked = false;
		}	
	}
}

/*
	Logs out the current AE member.
*/
function autoLogout() {
	// if custid is the same as the current member id then logout is not required
	if (custid == memberid) {
		return;
	}
	
	// check if custid has valid length
	if (custid.length != 9)  {
		return;
	}

	// check if div element is visible (i.e. when member is already authenticated)
	if (document.getElementById("logout").style.display == "inline") {
		var signoutUrl = document.getElementById("apSignout").href;
		if (custid.length == 9) {
			// add the custid to be passed
			signoutUrl = signoutUrl + "?custid=" + custid;
			
			if (custname.length != 0) {
				// add the custname to be passed
				signoutUrl = signoutUrl + "&custname=" + custname;
			}
		}
		//alert(signoutUrl);	
		window.location.href = signoutUrl;
	}
}

/*
   Make shopNow Ajax call. If user was not authenticated, error occur. In this case apSignInForShopNow() method is called
   attempting to authenticate a user. If the user is finally authenticated, modal confirmation box appears. 
   After confirmation user is redirected to an affiliate site.
   
   var productCode - string containing advertiser(product) code.
   var redirectUrl - if the redirectUrl is provided this Url will be used instead of the url
   					associated with the advertiser for redirecting 
*/
function apShopNow(productCode, redirectUrl) {
	apShopNowAjaxController.shopNow(productCode, redirectUrl, {
		callback:
			function (affiliateRedirectBean) {
				if (affiliateRedirectBean.imageProperties.length > 0) {
					document.getElementById("double_dip").innerHTML = '<a href="" id="shop_now_banner_href" target="_blank"><img id="shop_now_banner" src="' + baseUrl + '/template-resources/images/ap/"></img></a>'; 
					initShopNowBanner(affiliateRedirectBean.imageProperties);
					if (document.getElementById("nyroModalCloseButton") != null) {
						document.getElementById("shopnow_signedin_content").removeChild(document.getElementById("nyroModalCloseButton"));
					}
				}
				// check for an anchor element called advertiser_logo_<productCode> 
				try {
					// assign the advertiser logo to the shopnow logo on the transfer screen 
					document.getElementById("ap_shopnow_advertiser_logo").innerHTML=document.getElementById("advertiser_logo_" + productCode).innerHTML;
				} catch(err) {
					// if offer is not configured as a featured item then the advertiser_logo_<productCode> element may not exist.
					try {
						// check for an anchor element called offer_advertiser_logo_<productCode> (special offers page only)   
						document.getElementById("ap_shopnow_advertiser_logo").innerHTML=document.getElementById("offer_advertiser_logo_" + productCode).innerHTML;
					} catch (err) {
						document.getElementById("ap_shopnow_advertiser_logo").innerHTML="";
					}
				}

				document.getElementById("ap_shopnow_advertiser_logo").style.display = "block";
				document.getElementById("ap_shopnow_customer_first_name_message").innerHTML = affiliateRedirectBean.customerFirstName + ",";

				var shopNowPopupUrl = baseUrl + '/ap-redirect-to-retailer.ep?redirectUrl=' + escape(affiliateRedirectBean.redirectUrl) 
							+ '&'+ findAffiliateCodeId(affiliateRedirectBean.affiliation) + '=' + escape(affiliateRedirectBean.guid) 
							+ '&affiliation=' + escape(affiliateRedirectBean.affiliation);
				document.getElementById("ap_shopnow_click_to_popup_message").href = shopNowPopupUrl;

				sa_onclick(affiliateRedirectBean.storeUrl);
				
				$('#ap_shopnow_signedin_link').nyroModalManual(apNyroModalSettings);
				var affiliateUrl = baseUrl + '/ap-redirect-to-retailer.ep?redirectUrl=' + escape(affiliateRedirectBean.redirectUrl) 
						+ '&'+ findAffiliateCodeId(affiliateRedirectBean.affiliation) + '=' + escape(affiliateRedirectBean.guid) 
						+ '&affiliation=' + escape(affiliateRedirectBean.affiliation) 
						+ '&productCode=' + escape(affiliateRedirectBean.productCode) 
						+ '&productName=' + escape(affiliateRedirectBean.productName)
						+ '&categoryName=' + escape(affiliateRedirectBean.categoryName) 							 
						+ '\'';
				var timeoutId = setTimeout('window.open(' + '\'' + affiliateUrl + ')', 2000);
				document.getElementById("ap_shopnow_timeout_id").value = timeoutId;
				document.getElementById("ap_shopnow_affiliate_url").value = affiliateUrl;
			},
		errorHandler:
			function (error) {
				if (error.validationErrors['j_username']) {
					errorMessage = error.validationErrors['j_username'];
					initRememberNumber(true);
					initRememberNumber(false);
					document.getElementById("ap_popup_signin_button").onclick = function() {
						return apSignIn(true, true, productCode, redirectUrl);
					};
					$('#ap_popup_signin_link').nyroModalManual(apNyroModalSettings);
				}  else if (error.validationErrors['apShopNow.error.urlCreationFailed']) {
					errorMessage = error.validationErrors['apShopNow.error.urlCreationFailed'];
					document.getElementById("ap_shopnow_error_message").innerHTML = errorMessage;
					$('#ap_shopnow_error_link').nyroModalManual(apNyroModalSettings);
				}
				
			}
	});
}

/*
 * Initializes the shop now popup banner. Banners are being rotated.
 */
function initShopNowBanner(imageProperties) {
	var imgDoubleDip = document.getElementById("shop_now_banner");
	var imageFolderUrl = imgDoubleDip.getAttribute('src').substring(0, imgDoubleDip.getAttribute('src').lastIndexOf('/') + 1);
	var imgIndex = getShopNowBannerIndex(imageProperties.length);
	imgDoubleDip.setAttribute('src', imageFolderUrl + imageProperties[imgIndex].imageName);
	var aDoubleDip = document.getElementById("shop_now_banner_href");
	aDoubleDip.setAttribute('href', imageProperties[imgIndex].imageUrl);
	//imgDoubleDip.setAttribute('onclick', 'window.open(\'' + imageProperties[imgIndex].imageUrl + '\');');
}

/*
   Returns a printable error message for signIn given an error object.

   var error - error object with error messages
*/
function getSignInErrorMessage(error) {
	var errorMessage = "";
	if (error.validationErrors['j_username']) {
		errorMessage = error.validationErrors['j_username'];
	}
	else if (error.validationErrors['j_password']) {
		errorMessage = error.validationErrors['j_password'];
	}
	return errorMessage;
}

/*
   Fill pin number textboxes and check associated remember number checkbox if
   all three parts of pin number exist in cookie, otherwise do nothing.

   var modal - boolean to indicate if initializing for the modal signin window
*/
function initRememberNumber(modal) {
	var idPrefix = modal ? "popup_" : "";
	var cookie_pin1 = readCookie("aeroplan_memberno_1");
	var cookie_pin2 = readCookie("aeroplan_memberno_2");
	var cookie_pin3 = readCookie("aeroplan_memberno_3");
	document.getElementById(idPrefix + "pin1").value = (cookie_pin1 == null) ? "" : cookie_pin1;
	document.getElementById(idPrefix + "pin2").value = (cookie_pin2 == null) ? "" : cookie_pin2;
	document.getElementById(idPrefix + "pin3").value = (cookie_pin3 == null) ? "" : cookie_pin3;
	if ((cookie_pin1 != null) && (cookie_pin2 != null) && (cookie_pin3 != null)) {
		document.getElementById(idPrefix + "remember").checked = true;
	}
}

/*
   Process remember number.  Set all three parts of pin number into cookie if
   remember number checkbox is checked, otherwise clear all three parts of pin
   number from cookie.

   var pin1 - first part of pin number
   var pin2 - second part of pin number
   var pin3 - third part of pin number
   var rememberChecked - remember number checkbox is checked
*/
function processRememberNumber(pin1, pin2, pin3, rememberChecked) {
	if (rememberChecked) {
		var today = new Date();
		// expire date is set at 10 years to conform to aeroplan.com's cookie expiry date
		var expireDate = new Date(today.getTime() + 3600000 * 24 * 3650);
		setCookie("aeroplan_memberno_1", pin1, expireDate, "/");
		setCookie("aeroplan_memberno_2", pin2, expireDate, "/");
		setCookie("aeroplan_memberno_3", pin3, expireDate, "/");
	}
	else {
		cleanCookie("aeroplan_memberno_1", "/");
		cleanCookie("aeroplan_memberno_2", "/");
		cleanCookie("aeroplan_memberno_3", "/");
	}
}

/*
	Sets the query string parameter name to the affiliate specific ID.

	var affiliateCode - affiliate name
*/
function findAffiliateCodeId(affiliateCode) {
	var affiliateId = "u1";
	
	if (affiliateCode == "Linkshare") {
		affiliateId = "u1"
	} else if (affiliateCode == "Commission Junction") {
		affiliateId = "SID"
	} else if (affiliateCode == "Google Affiliate Network") {
		affiliateId = "mid"
	} else if (affiliateCode == "Intact Earnings") {
		affiliateId = "SID"
	} else if (affiliateCode == "eBay") {
		affiliateId = "customid"
	}
	
	return affiliateId;
}

/*
 * Gets shop now banner's index. Banners indexes are being rotated on each call.
 */
function getShopNowBannerIndex(count) {
	var cookieName = "doubleDipIndex";
	var index = readCookie(cookieName);
	if (index == null) {
		var randomnumber = Math.floor(Math.random()*count);
		setCookie(cookieName, randomnumber);
		return randomnumber;
	}
	index++;
	index %= count;
	setCookie(cookieName, index);
	return index;	
}
				
// Copied from "http://www.aeroplan.com/static/js/autotab.js" to handle auto-tabbing when entering aeroplan number
// Detection of Browser should be replaced by Detection of
// Objects as per Coding Standards

var isNN = (navigator.appName.indexOf("Netscape")!=-1);

function autoTab(input,len, e) {

    var keyCode = (isNN) ? e.which : e.keyCode;
    var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];

    if (input.value.length >= len && !containsElement(filter,keyCode)) {
        input.value = input.value.slice(0, len);
        var index = getIndex(input) + 1;
        index = index % input.form.length;
        
        while ((index < input.form.length) && (input.form[index].type == "hidden")) {
            index = index + 1;
        }

        
        if (index >= 0 && input.form[index] != null && input.form[index].type != "hidden" && !input.form[index].disabled)
        {
          input.form[index].focus();
        }
    }

    function containsElement(arr, ele) {
        var found = false, index = 0;
        while(!found && index < arr.length)
            if(arr[index] == ele)
                found = true;
            else
                index++;
        return found;
    }

    function getIndex(input) {
        var index = -1, i = 0, found = false;
        while (i < input.form.length && index == -1)
            if (input.form[i] == input)index = i;
            else i++;
        return index;
    }

    return true;
}

function saveSorting(type) {
	setCookie('allOffersSortBy', type);
}

function initSorting() {
	var type = readCookie('allOffersSortBy');
	if (type == null) {
		type = 'date';
		saveSorting(type);
	}
	if (type == 'date') {
		var sortByDate = document.getElementById('sortByDateLink').innerHTML;
		document.getElementById('sortByDate').removeChild(document.getElementById('sortByDateLink'));
		document.getElementById('sortByDate').innerHTML = sortByDate;
		var byRetailerHref = document.getElementById('sortByRetailerLink');
		if (byRetailerHref == null) {
			document.getElementById('sortByRetailer').innerHTML = '<a href="$action?$sortBy=retailer" onclick="saveSorting("retailer")" id="sortByRetalerLink">#springMessage("offergrid.alphabetically.by.retailer")</a>';
		}
	} else if (type == 'retailer') {
		var sortByRetailer = document.getElementById('sortByRetailerLink').innerHTML;
		document.getElementById('sortByRetailer').removeChild(document.getElementById('sortByRetailerLink'));
		document.getElementById('sortByRetailer').innerHTML = sortByRetailer;
		var byRetailerHref = document.getElementById('sortByDateLink');
		if (byRetailerHref == null) {
			document.getElementById('sortByDate').innerHtml = '<a href="$action?$sortBy=date" onclick="saveSorting("date")" id="sortByDateLink">#springMessage("offergrid.end.date")</a>';
		}
	}
}

// Cookie management javascript functions, received from Aeroplan (April 23, 2008)

/* --------------------------------------------------------------- */
/* Tools for cookie management */
/* --------------------------------------------------------------- */

/* 20080521 - added variable path to cleanCookie function */
function cleanCookie(name, path) {
	date = new Date();
	date.setFullYear(date.getFullYear()-1);
	setCookie(name,null,date,path);
}

/* --------------------------------------------------------------- */

function setCookie(name, value) {
	var argv = setCookie.arguments;
	var argc = setCookie.arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	
	document.cookie = name + "=" + escape(value) +
	((expires == null) ? "" : ("; expires="+expires.toGMTString())) +
	((path == null) ? "" : ("; path="+path)) +
	((domain == null) ? "" : ("; domain="+domain)) +
	((secure == true) ? "; secure" : "");
}

/* --------------------------------------------------------------- */

function getCookieVal(offset) {
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1) endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

/* --------------------------------------------------------------- */

function readCookie(name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	
	var i=0;
	while (i<clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg) return getCookieVal(j);
		i = document.cookie.indexOf(" ",i) + 1;
		if (i==0) break;
	}
	return null;
}

/* --------------------------------------------------------------- */

/*
	Expands and collapses content in static pages.
*/

function expandCollapse() {
	for (var i=0; i<expandCollapse.arguments.length; i++) {
	var element = document.getElementById (expandCollapse.arguments[i]);
	element.style.display = (element.style.display == "none") ? "block" : "none";
	}
}


/* --------------------------------------------------------------- */
/* custom aeroplan jquery javascript                               */
/* --------------------------------------------------------------- */
/*

Author: Darius Ratkevicius / ratkevicius@gmail.com / aphex.lt / +370 674 11099
Version: 4
Ordered by: UAB "EMTN," iregistruota adresu H. Manto 84-228, Klaipeda, Lietuva (imones kodas: 300067087)
Version date: 2007 05 17

*/

var search_value_en = "Search by retailer name or product keyword";
var search_value_fr = "Recherchez par nom de detaillant ou par mot-clé de produit";

var MenuDelayFinnished=false;
var MenuDelayObject;
var MenuDelayTime=300; //change this value, to alter left menu apearance delay
var MenuSelected;
var MenuShowFunction=function() {	
	
	MenuDelayFinnished=true;
	
	$(MenuSelected).addClass("sm_selected");
	$("div.nav_second_holder",MenuSelected).show(); // show sub,	highlight 1 level		
	
	if($('ul',MenuSelected).offset().top-$(document).scrollTop()+$('ul',MenuSelected).height()>$(window).height())
	{ // up or down?
		$('div.nav_second',MenuSelected).addClass('nav_second_up'); 	
	} 
}

$(document).ready(function(){
	
	
	/* 
		left menu toggle functionality
	*/
	$('#left_sidebar').bind('mouseleave',function(){  // if mouse leaves sidebar area, reset time check to false;
		MenuDelayFinnished=false;
	});
	
	$("li.sm").bind('mouseenter',function(){		
		MenuSelected=this;		
		
		if(MenuDelayFinnished) MenuShowFunction();
		else MenuDelayObject=setTimeout("MenuShowFunction();",MenuDelayTime);
		
    }).bind('mouseleave',(function(){
    	clearTimeout(MenuDelayObject);
		$(this).removeClass("sm_selected");	 //restore original look at level 1
		$("div.nav_second_holder",this).hide(); // hide sub
		$('div.nav_second',MenuSelected).removeClass('nav_second_up'); 
    }));
	/*/*/
	
	
	
	/*	
		right menu toggle functionality 	
	*/
	
	$('#right_sidebar').bind('mouseleave',function(){  // if mouse leaves sidebar area, reset time check to false;
		MenuDelayFinnished=false;
	});

	$("#logo_list>li").bind('mouseenter',function(){
		MenuSelected=this;
		
		if(MenuDelayFinnished) {
			$(this).addClass("selected"); //highlight 1 level			
			$("div.nav_second_holder_r",this).show(); // show sub
			if($("div.txt",MenuSelected).offset().top-$(document).scrollTop()+$("div.txt",MenuSelected).height()>$(window).height())
			{ // up or down?
				$('div.nav_second_r',MenuSelected).addClass('nav_second_r_up'); 	
			}	
		} else MenuDelayObject=setTimeout("$(MenuSelected).addClass('selected');$('div.nav_second_holder_r',MenuSelected).show(); MenuDelayFinnished=true;",MenuDelayTime);
    }).bind('mouseleave', function(){
    	clearTimeout(MenuDelayObject);
		$(MenuSelected).removeClass("selected");	 //restore original look at level 1
		$("div.nav_second_holder_r",MenuSelected).hide(); // hide sub
	
    });
	
	/*/*/
	
	
	
	/* 
		Modal windows
	*/
	$.fn.nyroModal.settings.css.content.overflow='visible'; //firefox overflow fix
	/* 
		Shop now modal window.
		Window template is selected from "shop now" url.
		Templates placed at the end of html in section <!-- modal windows -->
		Spcify template id in href attribute.
		
		<a href="#shop_now_template1" class="shop_now">shop_now</a>
		
	$('.shop_now').nyroModal({ 				
			bgColor:'#ffffff',								
			closeButton:''																								
	});
	*/
							
	
	/*  
		dropdown menu 
	*/
	$("#nav").bind('mouseenter',function(){
		$('#dropdown').show(); // show dropdown			
    }).bind('mouseleave',function(){
		$('#dropdown').hide(); // show dropdown	
	})
	
	
	/* 
		dropdown menu -> 2 level
	*/
	$("li.sm2").bind('mouseenter',function(){			
		$(this).addClass("sm2_selected"); //highlight 		
		$("div.nav_second_holder",this).show(); // show sub			
    }).bind('mouseleave',function(){			
		$("div.nav_second_holder",this).hide(); // hide sub
		$(this).removeClass("sm2_selected"); //highlight 
	})
	
	
	
	
	
	
	/* How does it work image hover */
	
	$('#title a').mouseover(function(){
		$('#title img').show()
	}).mouseout(function(){
		$('#title img').hide()
	});
	
	/* How does it work image hover (fr) */
	
	$('#title_fr a').mouseover(function(){
		$('#title_fr img').show()
	}).mouseout(function(){
		$('#title_fr img_').hide()
	});

	/* cluetips
	
		Adds cluetips to every <a with class cluetip. Put text to title attribute. Prefix text with |
		<a class="cluetip right" title="|asdfasfsasd fasd fasdf asdf asdf asdf asdf" ><img src="img/sing_1.gif" alt="" width="30" height="30" /></a>
	
	*/
	
	$('a.cluetip').cluetip({ positionBy:'fixed',splitTitle:'|', showTitle:true, dropShadow:false, leftOffset:-233, topOffset:-4, width:190});
	
	/* Default search text value */
	
//	$("#search-input").defaultvalue(search_value_en);
//	$("#search-input-fr").defaultvalue(search_value_fr);
	
	/* How does it work image hover */
	
	$('#title a').mouseover(function(){
		$('#title img').show()
	}).mouseout(function(){
		$('#title img').hide()
	});
	
	
	/* How does it work image hover (fr) */
	
	$('#title_fr a').mouseover(function(){
		$('#title_fr img').show()
	}).mouseout(function(){
		$('#title_fr img').hide()
	});
	
	
	
	
	
	/** 
	
	Shop block hover functions in grid and list files
	
	*/
	
	$('div.shop_block').bind('mouseenter',function(){
		$(this).addClass('shop_block_hover');
		
		if($(this).hasClass('r_border')) $(this).removeClass('r_border').addClass('r_border_');
		if($(this).hasClass('t_border')) $(this).removeClass('t_border').addClass('t_border_');
	}).bind('mouseleave',function(){	
		$(this).removeClass('shop_block_hover');
		
		if($(this).hasClass('r_border_')) $(this).removeClass('r_border_').addClass('r_border');
		if($(this).hasClass('t_border_')) $(this).removeClass('t_border_').addClass('t_border');
	});
	
	
	$('div.shop_row').bind('mouseenter',function(){
		$(this).addClass('shop_row_hover');		
	}).bind('mouseleave',function(){	
		$(this).removeClass('shop_row_hover');		
	});
});



/* custom aeroplan jquery javascript by Aphex end ------------------------- */


function check_value(id) {
      var element = document.getElementById(id);
      var value = element.value;
      if (value == search_value_en || value == search_value_fr) {
            element.value = ""; 
    }
}

/*
	dropdown_out() kills all menu
*/
function dropdown_out() {
	if(typeof(selected)!='undefined') {		
		$("div.nav_second_holder",selected).hide(); // hide sub
		$(selected).removeClass("sm2_selected"); //highlight 
	}
	$('#dropdown').hide(); // hide dropdown		
}
/* custom aeroplan jquery javascript end ------------------------- */
