





/* HomewidgetController */


/* FtumessagingController */


/* public_LightboxController */
Object.extend(Element,{
		setHeight: function(element,h){
			elm = $(element);
			elm.style.height = h + 'px';
		},
		setWidth: function(element,w){
			elm = $(element);
			elm.style.width = w + 'px';
		},
		setInnerHTML: function(element,c){
			elm = $(element);
			elm.innerHTML = c;
		},
		setTop: function(element,t){
			elm = $(element);
			elm.style.top = t;
		},
		setLeft: function(element,l){
			elm = $(element);
			elm.style.left = l;
		},
		setVisible: function(element,o){
			elm = $(element);
			elm.style.visibility = o;
		},
		getOffsetHeight: function(element){
			elm = $(element);
			return elm.offsetHeight;
		},
		getOffsetWidth: function(element){
			elm = $(element);
			return elm.offsetWidth;
		}
});


var Overlay = Class.create();

Overlay.prototype = {
	initialize: function() {	
		this.options = Object.extend({
			opacity:	0.8,
			duration:	0.2
		},arguments[1] || {});
		var objBody = document.getElementsByTagName("body").item(0);
		
		var objOverlay = document.createElement("div");
		objOverlay.setAttribute('id','overlay');
		objOverlay.style.display = 'none';
		objBody.appendChild(objOverlay);
	},
	
	start: function(topOffset,setWidth) {	

		hideSelectBoxes();
		hideFlash();
		var arrayPageSize = getPageSize();
		if(setWidth != false){
			if(arrayPageSize[0] < arrayPageSize[2]){
				Element.setWidth('overlay', arrayPageSize[2]);
			}else{
				Element.setWidth('overlay', arrayPageSize[0]);
			}
		}
		
		Element.setHeight('overlay', arrayPageSize[1]);
		
		new Effect.Appear('overlay', { duration: this.options.duration, from: 0.0, to: this.options.opacity });
		
		var arrScrollPos = getPageScroll();
		var iOffHeight = Element.getHeight('divbox');
		var iOffWidth = Element.getWidth('divbox');
		var sLeft = parseInt(arrScrollPos[0]) + parseInt(arrayPageSize[2]/2) - parseInt(iOffWidth/2) + "px";
		if(sLeft < 0){
			sLeft=0;
		}
		if(topOffset != undefined){
			var sTop = parseInt(topOffset) - parseInt(iOffHeight/1.3);
			sTop = sTop + "px";		
		}else{
			var sTop = parseInt(arrayPageSize[1]/2) - parseInt(iOffHeight) + "px";
		}		
		Element.setTop('divbox',sTop);			
		Element.setLeft('divbox',sLeft);
		Element.show('divbox');
	
		 
	},
	
	addElm: function(e){
		var objBody = document.getElementsByTagName("body").item(0);
		objBody.appendChild(e);
			
	},	
	end: function() {
		Element.hide('divbox');
		new Effect.Fade('overlay', { duration: this.options.duration});
		showSelectBoxes();
		showFlash();
 	}

}

function arpltend(){
	document.getElementById('page').style.position = 'static';
	arpOverlay.end();
}

 

function getPageScroll(){

	var xScroll, yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}

	arrayPageScroll = new Array(xScroll,yScroll);
	return arrayPageScroll;
}

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else {
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;

	if (self.innerHeight) {
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) {
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	if(xScroll < windowWidth){			
		pageWidth = windowWidth;		
	} else {
		pageWidth = xScroll;
	}
	
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight,screen.width,screen.height);
	return arrayPageSize;
}

function showSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}
}

function hideSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		if(selects[i].id != 'mrMs'){
			selects[i].style.visibility = "hidden";
		}
	}
}

function showFlash(){
	var flashObjects = document.getElementsByTagName("object");
	for (i = 0; i < flashObjects.length; i++) {
		flashObjects[i].style.visibility = "visible";
	}

	var flashEmbeds = document.getElementsByTagName("embed");
	for (i = 0; i < flashEmbeds.length; i++) {
		flashEmbeds[i].style.visibility = "visible";
	}
}

function hideFlash(){
	var flashObjects = document.getElementsByTagName("object");
	for (i = 0; i < flashObjects.length; i++) {
		flashObjects[i].style.visibility = "hidden";
	}

	var flashEmbeds = document.getElementsByTagName("embed");
	for (i = 0; i < flashEmbeds.length; i++) {
		flashEmbeds[i].style.visibility = "hidden";
	}

}

function cenergyend(){
	cpoint.end();
}

function cpointemailend(){
	clogin.end();
}


function killOverlay(){
	myOverlay.end();
}
function validateRegForm(){
	
	var email = document.lbRegForm.email.value.strip();
	var firstName = document.lbRegForm.userFName.value.strip();
	var lastName = document.lbRegForm.userLName.value.strip();
	var zipCode = document.lbRegForm.zipCodeWork.value.strip();
	var mrMs = document.lbRegForm.mrMs.value.strip();
	var uSource = document.lbRegForm.uSource.value.strip();
	var unsubscribeUser = document.lbRegForm.uSource.value.strip();

	if(email == ""){
		showError('Please enter an e-mail address');
		return false;	
	}else{
		validEmail = validate_email(email);
		if(!validEmail){
			showError('Please enter a valid e-mail address');
			return false;
		}
	}
	//fields can be empty
	if (firstName != "" && !isValidName(firstName)){
		showError('Please fill in a valid first name.');
		return false;
	}
	if (lastName != "" && !isValidName(lastName)){
		showError('Please fill in a valid last name.');
		return false;
	}
	if (zipCode != "" && !isValidZipCode(zipCode)){
		showError('Please fill in a valid zip code.');
		return false;
	}

	submitlbRegForm(email,firstName,lastName,zipCode,mrMs,uSource,unsubscribeUser);

}
function isValidZipCode(value) {
	var re = /^\d{5}([\-]\d{4})?$/;
	return (re.test(value));
}
function isValidName(value){
	var re = /^[\-\'\. a-zA-Z]*$/;
	return (re.test(value));
}
function submitlbRegForm(email,firstName,lastName,zipCode,mrMs,uSource,unsubscribeUser){
	$('rlbInputBtn').hide();
	$('rlbLoadImg').show();
	$('rlbError').innerHTML='';
	var url = '/login/registeruser';
	var myAjax = new Ajax.Request( url, {method: 'post',
		parameters: {email:email,firstName:firstName,lastName:lastName,zipCode:zipCode,mrMs:mrMs,uSource:uSource,unsubscribeUser:unsubscribeUser},
		onLoading: $('rlbSuccess').innerHTML='Submitting information...',
		onSuccess: updateRLB,
		'timeout':2000,'onTimeout':function(req){ alert('Timed Out!'); }} );	
}
function showError(msg){
	$('rlbError').innerHTML = msg;
}
function updateRLB(transport){

	var responseObj = transport.responseText.evalJSON();
	$('rlbSuccess').innerHTML='';
	
	if(responseObj.errorMsg != ''){
		showError(responseObj.errorMsg);
		$('rlbInputBtn').show();
		$('rlbLoadImg').hide();
	}else if(responseObj.successMsg != ''){
		$('rlbSuccess').innerHTML=responseObj.successMsg;
		
		if(navigator.userAgent.indexOf("MSIE") != -1){//delay required for IE
			var t=window.setTimeout(window.location.reload,1);
		}else{
			window.location.reload();
		}
	}else{
		showError('An unkown error has occured.');
	}
}


function focusInput(inputElement, defaultText) {
 if ($(inputElement).value == defaultText && $(inputElement).getStyle("color") == 'gray') {
 $(inputElement).value = "";
 $(inputElement).setStyle({color: "black"});
 }
}

function blurInput(inputElement, defaultText) {
 if ($(inputElement).value == '') {
 $(inputElement).value = defaultText;
 $(inputElement).setStyle({color: "gray"});
 }
} 

function invitetag(){
	var eventInfo = new Object();
	eventInfo.prop3 = 'VIP';
	eventInfo.var3 = 'VIP';
	eventInfo.prop4 = 'VIP_Tell a Friend';
	eventInfo.var4 = 'VIP_Tell a Friend';
	if(typeof genericObjectTracker == 'function')
		genericObjectTracker(eventInfo);
}

function checkGuest_popup()
{
	 var savestring="";
	 var trimmedFName = document.formGuestUser_popup.gfirstname.value.strip();
	 var trimmedLName = document.formGuestUser_popup.glastname.value.strip();
	 var trimmedEMail = document.formGuestUser_popup.gemail.value.strip();

	 if (document.formGuestUser_popup.gfirstname.value == "" || document.formGuestUser_popup.glastname.value=="" || document.formGuestUser_popup.gemail.value == "" || trimmedFName == "" || trimmedLName == "" || trimmedEMail == "")
	 {
	 	return;
	 }
	 else
	 {
		document.formGuestUser_popup.submit();
	 }
}

 function addguest_popup() {
  
  	var obj = document.getElementById('formUser');
 	var trimmedFName = document.formGuestUser_popup.gfirstname.value.strip();
	var trimmedLName = document.formGuestUser_popup.glastname.value.strip();
	var trimmedEMail = document.formGuestUser_popup.gemail.value.strip();
	if(trimmedFName == '' || trimmedLName == '' || trimmedEMail == '' || trimmedFName == 'First Name' || trimmedLName == 'Last Name' || trimmedEMail == 'Email Address'){
		$('error_mess_popup').innerHTML = 'Please enter all details.';
		return;
	}
	if(!validate_email(trimmedEMail)){
		$('error_mess_popup').innerHTML = 'Please enter a valid email address.';
		return;
	}
 	var getstr = "?gfirstname=" + trimmedFName + "&glastname=" + trimmedLName + "&gemail=" +trimmedEMail;
 	var updateDiv = $('popupboxtext_flag');
 	var url = '/shoppingeventwidget/saveguestpopup';
 	var myAjax = new Ajax.Request( url,
			{method:'post',
				parameters:getstr,	
				onLoad:showloadingmidpopup(updateDiv), onSuccess:showconfirmpopup});
 
	
} 

function showconfirmpopup(originalRequest){
	var updateDiv = $('saveguest_popup');
	updateDiv.innerHTML = originalRequest.responseText;
	$('invitepopup').style.display = "block";
	Effect.Appear(updateDiv, { duration: 0.35 });

}

 function showloadingmidpopup(up){
 	up.innerHTML = '<div class="loading" style="text-align:center;padding-top:100px;padding-bottom:100px;"><img src="https://imga.corporateperks.com/emp_image/overwhelmingoffer/ajax_loader.gif" alt="loading" title="loading"></div>';

}

   function logclick(id){
	var params = 'clicktype=' + id;
	var actionName = 'logclick';
	var myAjax = new Ajax.Request('/shoppingevent/' + actionName, {parameters:params,	method:'post'});
}

function optin(){
	if($('optoutcb').checked){
		optinAll();
	}else{
		optoutAll();
	}
}

function optinAll(){
	var merchid= 5933;
	var myAjaxRemind = new Ajax.Request('/activereminderswidget/submitreminder/'+ new Date().getTime(),{method:'get',parameters:{reminderID:merchid,uSource:'NOTI'},onComplete:function(){}});
	var Subscribed_4 = 4;
	var Subscribed_5 = 5;  
	var params = 'usource=EOOL1&MailFormat=HTML&Subscribed_5=' + Subscribed_5 + '&Subscribed_4=' + Subscribed_4;
	refreshOptinSettings('updateemailfromlb',params);
}
function optoutAll(){
	var merchid = 5933;
	var myAjaxRemind = new Ajax.Request('/topemailwidget/deleteremindernonssl/'+ new Date().getTime(),{method:'get',parameters:{reminderID:merchid,method:'DeleteNewCatList_SingleReminder_Secured',uSource:'NOTI'},onComplete:function(){}});
	var params = 'usource=EOOL1';
	refreshOptinSettings('unsubscribeemailnonssl',params);
}

function refreshOptinSettings(action,params){
	if (action == undefined){
		action = 'index';
	}
	if (params == undefined){
		params = '';
	}
	
	var url = '/emailsettingswidget/' + action;

	var myAjax = new Ajax.Request( url,
		{method:'post',
			parameters:params
		});
}

function showLSPopup(offerId){
    if(typeof(getDetails) == 'function' && offerId != 0){
        getDetails(offerId,1);
    }
}

/* FeedbackwidgetController */
var vote = 1;

function submitFeedback(topic, isTrusted){
    //clear the validtion msg

    $('email_validation_msg'+topic).innerHTML='';
    $('comment_validation_msg'+topic).innerHTML='';

    if(document.getElementById("send_To_CS").checked){
        send_to_cs = 1;
    }else{
        send_to_cs = 0;
    }

    var str_Text = $('str_Text'+topic).value;

    if(isTrusted==1 && topic!=4 && topic!=79 && topic!=80){
        if (/[^\s]+/.test(str_Text)){  // reject if all whitespace
            saveComment(topic, '');
        }else{
            $('comment_validation_msg' + topic).update('Please enter comments');
        }
    }else if(isTrusted==1 && (topic==4 ||topic!=79 || topic!=80)){
    //validation for odp page feedback
        if(str_Text =='' || str_Text==' '){
            $('comment_validation_msg'+topic).innerHTML="Please enter comments";
        }else{	
            saveComment(topic,"");
        }
    }else{
    //email validation
        var str_email= $('fk_email'+topic).value;
        if((validate_email(str_email) || (topic == 92 && str_email == '')) && !str_Text =='' && !str_Text==' '){   // if valid email (or on OO.com and email not entered) and comment not empty,
            saveComment(topic,str_email);
        }else{
            if(!(topic == 92 && str_email == '') && !validate_email(str_email)){  // check for valid email on all non-OO.com orgs & on OO.com only if email entered
                $('email_validation_msg'+topic).innerHTML='Email is invalid';
            }

            if(str_Text =='' || str_Text==' '){
                $('comment_validation_msg'+topic).innerHTML="Please enter comments";
            }
        }
    }
}

function saveComment(topic, email){
    var $temp =$('submitFeedback_mid'+topic).innerHTML;

    var str_Text = $('str_Text'+topic).value;
    if(str_Text.length > 2000){
        str_Text = str_Text.substring(0, 1999);
    }

    if(email!= ""){
        str_Text=email+ ": " + str_Text;
    }else{
        str_Text=email + str_Text;
    }

    var str_URL = document.getElementById('str_URL').value;
    var ajaxpos = -1;
    ajaxpos=str_URL.indexOf("/feedbackwidget/default?");
    if (ajaxpos >=0){
        str_URL = '/home/index/usource/HIMG';
    }

    if(str_Text != '' && str_Text != ' '){
        str_Text = str_Text.replace(/\?/g, "qMark");
        str_Text = str_Text.replace(/##/g, "\##");
        str_Text = str_Text.replace(/\%/g, "percent");
        str_Text = str_Text.replace(/\</g, " lt ");
        str_Text = str_Text.replace(/\>/g, " gt ");
        str_Text = str_Text.replace(/\'/g, " ");
    }

    var url = '/feedbackwidget/index';
    var myAjax = new Ajax.Request( url, {method: 'post',
                parameters:{topic:topic,comments:str_Text,str_URL:str_URL, email:email,send_to_cs:send_to_cs,vote:vote},
                onLoading:showLoad(topic),
                onComplete:function (transport) {
                                                var newData = transport.responseText;
                                                //alert(newData);
                                                //alert($('submitFeedback_mid'+topic));
                                                $('submitFeedback_mid'+topic).innerHTML ='<br><br><br>'+ newData ;
                                                },
                onSuccess:closeBox(topic),
                'timeout':2000,
                'onTimeout':function(req){ alert('Timed Out!'); }} );
    var text_field = false;
}

function replacement (str_Text) {
    str_Text = str_Text.replace(/\?/g, "qMark");
    str_Text = str_Text.replace(/##/g, "\##");
    str_Text = str_Text.replace(/\%/g, "percent");
    str_Text = str_Text.replace(/\</g, " lt ");
    str_Text = str_Text.replace(/\>/g, " gt ");
    str_Text = str_Text.replace(/\'/g, " ");
    return str_Text;
}

function showLoad(topic){
    $('feedbackForm' + topic).hide();
    $('submitFeedback_mid'+topic).innerHTML = '<P><STRONG>Sending Feedback...</P></STRONG>';
    $('submitFeedback_bot').setStyle({
        marginTop: '0px'
    });
}

function closeBox(topic){
    divObj = $('submitFeedback'+topic);
    setTimeout(function(){divObj.style.display='none';},1500,null,divObj);
}

function voteLike(div1,div2){
    if(vote == 0){
        $(div1).src="http://imga.nxjimg.com/secured/image/f08/home/thumbs_up.gif";
        vote = 1;
        $(div2).src="http://imgb.nxjimg.com/secured/image/f08/home/thumbs_downbw.gif";  
    }	  
}

function voteDislike(div1,div2){
    if(vote == 1){
        $(div1).src="http://imgb.nxjimg.com/secured/image/f08/home/thumbs_upbw.gif";
        vote = 0;
        $(div2).src="http://imga.nxjimg.com/secured/image/f08/home/thumbs_down.gif";
    } 
}
 
function tooLong(strTest,maxLength,remainingCharsName){
    if(strTest.value.length > maxLength){
        strTest.value = strTest.value.substr(0,maxLength);
    }
    $(remainingCharsName).innerHTML=maxLength-strTest.value.length;
}

function getPreviousVote(){
    vote = $('previous_vote').value;
    if(vote == "notset"){
        vote = 1;
    }

    if(vote == 0){
        $('vote_like').src="http://imgb.nxjimg.com/secured/image/f08/home/thumbs_upbw.gif";
        $("vote_dislike").src="http://imga.nxjimg.com/secured/image/f08/home/thumbs_down.gif";
    }
}

function voteLike(){
    if(vote == 0){
        $('vote_like').src="http://imga.nxjimg.com/secured/image/f08/home/thumbs_up.gif";
        vote = 1;
        $("vote_dislike").src="http://imgb.nxjimg.com/secured/image/f08/home/thumbs_downbw.gif";  
    }	  
}

function voteDislike(){
    if(vote == 1){
        $('vote_like').src="http://imgb.nxjimg.com/secured/image/f08/home/thumbs_upbw.gif";
        vote = 0;
        $("vote_dislike").src="http://imga.nxjimg.com/secured/image/f08/home/thumbs_down.gif";
    } 
}

function submitFeedback_instoreevent( topic, offerId, feedback_site_id ){
    //alert(feedback_site_id);
    str_URL = offerId;
    send_to_cs = 0;	
    str_Text = $('str_Text'+topic).value;
    if(str_Text != '' && str_Text != ' '){	
        str_Text = replacement (str_Text);
    }

    var url = '/feedbackwidget/instoreeventfeedback';
    var myAjax = new Ajax.Request( url, {method: 'post',
                        parameters:{topic:topic,comments:str_Text,str_URL:str_URL,send_to_cs:send_to_cs, vote:vote, feedback_site_id:feedback_site_id },
                        onLoading:showLoadOfInstoreEvent(topic),
                        onComplete:function (transport) {
                        //alert(newData);
                                        var newData = transport.responseText;
                                        $('submitFeedback_mid'+topic).style.display="none";
                                        //$('submitFeedback_result'+topic).innerHTML = "" + newData;
                                        $('submitFeedback_result'+topic).style.display="block";
                                        $('feedback_link_a').innerHTML ="Change Vote";
                                        },
			onSuccess:closeBoxOfInstoreEvent(topic),
			'timeout':2000,
                        'onTimeout':function(req){ alert('Timed Out!'); }} );
}

function closeBoxOfInstoreEvent(topic){
    divObj = $('submitFeedback'+topic);
    setTimeout(function(){divObj.style.display='none'; $('submitFeedback_mid'+topic).style.display="block";
    $('submitFeedback_result'+topic).style.display="none";},3000,null,divObj);
    if(vote == 1){
        $("vote_msg").innerHTML = "You voted thumbs up. Do you want to change?";
    }else{
        $("vote_msg").innerHTML = "You voted thumbs down. Do you want to change?";
    }
    $("voting_msg").innerHTML = "Change the vote?";
}

function showLoadOfInstoreEvent(topic){
    $('submitFeedback_result'+topic).innerHTML = '<P><STRONG>Sending Feedback...</P></STRONG>';
    $('submitFeedback_mid'+topic).style.display="none";
    $('submitFeedback_result'+topic).style.display="block";
}

function tooLong(strTest,maxLength,remainingCharsName){
    if(strTest.value.length > maxLength){
        strTest.value = strTest.value.substr(0,maxLength);
    }
    document.getElementById(remainingCharsName).innerHTML=maxLength-strTest.value.length;
    //alert(maxLength-strTest.value.length);
}

function showHide_instore_feedback( divID ){
    if( $(divID).style.display == "none" ){
        getPreviousVote();
        $(divID).style.display ="block";
    }else{
        $(divID).style.display ="none";
    }
}

function toggle_feedbackwidgetpopup(id){
    $('feedback_ajaxloading'+id).style.display = "none";
    $('submitFeedback'+id).style.display = "block";
}

function showfeedbackwidget_ajax(id,copy,vote){
    if(id!=3 && $('submitFeedback'+id)){
        $('submitFeedback'+id).style.display = "block";
    }else{
        $('feedback_ajaxloading'+id).style.display = "inline";
        var url = '/feedbackwidget/default';
        var myAjax = new Ajax.Request( url, {method:'get',
                                        parameters:{feedbackDBID:id,feedbackCopy:copy,vote:vote},
                                        timeout:6000,
                                        onComplete:function(movieSubmit2){
                                                        var response = movieSubmit2.responseText || "no response text";;
                                                        if(id==39){
                                                            document.getElementById('votepopup1nh').innerHTML = response;
                                                        }else if (id==60){
                                                            document.getElementById('feedbackposition').innerHTML = response;
                                                        }else if (id==61){
                                                            document.getElementById('feedbackposition61').innerHTML = response;
                                                        }else if (id==3){
                                                            document.getElementById('feedbackfooter').innerHTML = response;
                                                        }
                                                        toggle_feedbackwidgetpopup(id);
                                                    },
                                        'onTimeout':function(req){ alert('Timed Out!'); }} );
    }
}

/* Public_FooterController */
function Set_Cookie( name, value, expires, path, domain, secure )
{
    var today = new Date();
    today.setTime( today.getTime() );

    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }

    var expires_date = new Date( today.getTime() + (expires) );
    document.cookie = name + "=" +escape( value ) +
                      (( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
                      (( path ) ? ";path=" + path : "" ) +
                      (( domain ) ? ";domain=" + domain : "" ) +
                      (( secure ) ? ";secure" : "" );
}
function on(e){
    e.src = e.src.replace(/_off./,'_on.');
}
function off(e){
    e.src = e.src.replace(/_on./,'_off.');
}
function on_id(id) {
    e = document.getElementById(id);
    e.src = e.src.replace(/_off./,'_on.');
}
function off_id(id) {
    e = document.getElementById(id);
    e.src = e.src.replace(/_on./,'_off.');
}
function setBookmark (url,str){
    if(str=='')str=url;
    if(document.all)window.external.AddFavorite(url,str);
    else alert('To add '+str+' to your bookmarks, press CTRL and D.');
}
function showHide(elementID){
    var divElement = $(elementID);
    if(divElement.style.display == "none"){
        divElement.style.display="block";
    }else{
        divElement.style.display="none";
    }
}
function imageLoader(){
    leftButtonImage = new Image();
    rightButtonImage = new Image();
    leftButtonImage.src = 'http://imga.nxjimg.com/emp_image/button_left_on.gif';
    rightButtonImage.src = 'http://imga.nxjimg.com/emp_image/button_right_on.gif';
}
function showHideDelay(divID){
    if($(divID).style.display=='none'){
        var divObj = $(divID);
        setTimeout(function(){divObj.style.display='block';},100,null,divObj);
    }else{
        $(divID).style.display='none';
    }
}
function showHideZIndexSwap(eId){
    var divElement = $(eId);
    var footerElement = $('footer');
    if(divElement.style.display == "none"){
        footerElement.style.zIndex = "3";
        divElement.style.display="block";
    }else{
        footerElement.style.zIndex = "0";
        divElement.style.display="none";
    }
}

/* CartController */
var starAdvDoLightStars = true;

function leaderboardTrophy(){
	if ($('trophy'))
		setTimeout("$('trophy').src = 'https://imgb.corporateperks.com/emp_image/UserRank/trophyani_2.gif'",800);
		setTimeout("$('trophy').src = 'https://imgb.corporateperks.com/emp_image/UserRank/trophyani_1.gif'",1200);
		setTimeout("$('trophy').src = 'https://imgb.corporateperks.com/emp_image/UserRank/trophyani_3.gif'",1600);
		setTimeout("$('trophy').src = 'https://imgb.corporateperks.com/emp_image/UserRank/trophyani_1.gif'",2000);
		setTimeout("$('trophy').src = 'https://imgb.corporateperks.com/emp_image/UserRank/trophyani_4.gif'",2400);
		setTimeout("$('trophy').src = 'https://imgb.corporateperks.com/emp_image/UserRank/trophyani_1.gif'",2800);
		
}

function starAdvLightStar(which)
{
	var maxBumpHeight = 10;
	var marginTops = [];
	marginTops[0] = 0;
	marginTops[1] = -0.31;
	marginTops[2] = -0.59;
	marginTops[3] = -0.81;
	marginTops[4] = -0.95;
	marginTops[5] = -1;
	marginTops[6] = -0.95;
	marginTops[7] = -0.81;
	marginTops[8] = -0.59;
	marginTops[9] = -0.31;
	marginTops[10] = 0;
	
	$('starAdvReadoutStar'+which).style.visibility = "visible";
	
	for (var i = 1; i < marginTops.length; i++)
		setTimeout("$('starAdvReadoutStar"+which+"').style.marginTop = '"+(marginTops[i]*maxBumpHeight)+"px';",i*40);
}

var counterDigits = [];
var oldCounterDigits;

function resetCounterTo(num,whichCounter) {
	if (whichCounter == 'ptsTickerDigit')
	{
		var i = 0;
		var localCounterDigits = [];
		if (num != null)
		{
			if (num == 0)
				localCounterDigits[0] = 0;
			else
			{
				while(num > 0) {
					var digit = num % 10;
					localCounterDigits[i] = digit;
					i = i + 1;
					num = num / 10;
					num = Math.floor(num);
				}
			}
		}
		
		var numDigits = 7;
		for (var i = 1; i <= numDigits; i++)
		{
			if ((numDigits-i) < localCounterDigits.length)
			{
				if (i == 1 || i == 4)
					changeBackgroundPosition('ptsTickerDigit'+i,(-23.4*(localCounterDigits[numDigits-i]+1)),'-118');
				else
					changeBackgroundPosition('ptsTickerDigit'+i,(-23.4*(localCounterDigits[numDigits-i]+1)),'-0');
			}
			else
				changeBackgroundPosition('ptsTickerDigit'+i,'0','0');
		}
	}
}

function spinCounter(num,whichCounter) {
	if ($(whichCounter+'1') == null)
		return;	// assume if first digit absent, then counter doesn't exist
		
	var i = 0;
	var localCounterDigits = [];
	if (num == 0)
		localCounterDigits[0] = 0;
	else
	{
		while(num > 0) {
			var digit = num % 10;
			localCounterDigits[i] = digit;
			i = i + 1;
			num = num / 10;
			num = Math.floor(num);
		}
	}

	if (whichCounter == 'cartCounterDigit')
	{
		var numDigits = 6;
		for(i = 0; i < localCounterDigits.length ; ++i) {
			if (i > 0 && i % 3 == 0)
				setDigitAtPositionWithComma(numDigits, localCounterDigits[i], 0, whichCounter);
			else 
				setDigitAtPosition(numDigits, localCounterDigits[i], 0, whichCounter);
			numDigits = numDigits - 1;
		}
		
		for(numDigits ; numDigits >= 1 ; --numDigits) {
			if($(whichCounter+numDigits).style.backgroundPosition != '0px 0px' && $(whichCounter+numDigits).style.backgroundPosition != '') {
				resetDigitAtPosition(numDigits, whichCounter);
			}
		}
	}
	if (whichCounter == 'ptsTickerDigit')
	{
/*
		oldCounterDigits = [];
		for (i = 0; i < counterDigits.length; i++)
			oldCounterDigits[i] = counterDigits[i];
			
		counterDigits = [];
		for (i = 0; i < localCounterDigits.length; i++)
			counterDigits[i] = localCounterDigits[i];
			
		var numDigits = 7;
		setDigitAtPosition(numDigits, counterDigits[0], (oldCounterDigits.length >= 1)? oldCounterDigits[0] : null, 'ptsTickerDigit');
*/
		var numDigits = 7;
		var step = 125;
		for (var nextDigitToStop = numDigits, i = 0, f = 0; nextDigitToStop >= 1; i = (i+1)%11, f++)
		{
			var decNextDigitToStopAfterThisTurn = false;
			
			for (var g = nextDigitToStop; g >= 1; g--)
			{
				setTimeout("changeBackgroundPosition('ptsTickerDigit"+g+"',"+(-23.4*i)+",'-39')", f*step + (1/4)*step);
				setTimeout("changeBackgroundPosition('ptsTickerDigit"+g+"',"+(-23.4*i)+",'-78')", f*step + (3/4)*step);
				
				if ((numDigits-g) < localCounterDigits.length)
					var destIndex = localCounterDigits[numDigits-g]+1;
				else
					var destIndex = 0;
					
				if (g == nextDigitToStop && ((i+1)%11) == destIndex)
				{
					if (destIndex == 0)
						nextDigitToStop--;
					else
						decNextDigitToStopAfterThisTurn = true;
					
					if (g == 1 || g == 4)
						setTimeout("changeBackgroundPosition('ptsTickerDigit"+g+"',"+(-23.4*((i+1)%11))+","+((destIndex==0)?'-0':'-118')+")", f*step + step);
					else
						setTimeout("changeBackgroundPosition('ptsTickerDigit"+g+"',"+(-23.4*((i+1)%11))+",'-0')", f*step + step);
				}
			}
			
			if (decNextDigitToStopAfterThisTurn)
				nextDigitToStop--;
		}
		
		setTimeout("starAdvLightStars()", f*step);
	}
	if (whichCounter == 'ooTickerDigit')
	{
		var numDigits = 7;
		var step = 125;
		for (var nextDigitToStop = numDigits, i = 0, f = 0; nextDigitToStop >= 1; i = (i+1)%11, f++)
		{
			var decNextDigitToStopAfterThisTurn = false;
			
			for (var g = nextDigitToStop; g >= 1; g--)
			{
				setTimeout("changeBackgroundPosition('ooTickerDigit"+g+"',"+(-31*i)+",'-52')", f*step + (1/4)*step);
				setTimeout("changeBackgroundPosition('ooTickerDigit"+g+"',"+(-31*i)+",'-104')", f*step + (3/4)*step);
				
				if ((numDigits-g) < localCounterDigits.length)
					var destIndex = localCounterDigits[numDigits-g]+1;
				else
					var destIndex = 0;
					
				if (g == nextDigitToStop && ((i+1)%11) == destIndex)
				{
					if (destIndex == 0)
						nextDigitToStop--;
					else
						decNextDigitToStopAfterThisTurn = true;
					
					if (g == 1 || g == 4)
						setTimeout("changeBackgroundPosition('ooTickerDigit"+g+"',"+(-31*((i+1)%11))+","+((destIndex==0)?'-0':'-156')+")", f*step + step);
					else
						setTimeout("changeBackgroundPosition('ooTickerDigit"+g+"',"+(-31*((i+1)%11))+",'-0')", f*step + step);
				}
			}
			
			if (decNextDigitToStopAfterThisTurn)
				nextDigitToStop--;
		}
	}
}

function resetCounter(whichCounter) {
	var step = 125;
	var increment = 1;
	var spacing = 0.25;
	if (whichCounter == 'cartCounterDigit')
	{
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit1','0','-52'); }, 1*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit1','0','-104'); }, (1+increment)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit1','0','0'); }, (1+2*increment)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit2','0','-52'); }, (1+spacing)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit2','0','-104'); }, ((1+spacing)+increment)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit2','0','0'); }, ((1+spacing)+2*increment)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit3','0','-52'); }, (1+2*spacing)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit3','0','-104'); }, ((1+2*spacing)+increment)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit3','0','0'); }, ((1+2*spacing)+2*increment)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit4','0','-52'); }, (1+3*spacing)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit4','0','-104'); }, ((1+3*spacing)+increment)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit4','0','0'); }, ((1+3*spacing)+2*increment)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit5','0','-52'); }, (1+4*spacing)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit5','0','-104'); }, ((1+4*spacing)+increment)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit5','0','0'); }, ((1+4*spacing)+2*increment)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit6','0','-52'); }, (1+5*spacing)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit6','0','-104'); }, ((1+5*spacing)+increment)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit6','0','0'); }, ((1+5*spacing)+2*increment)*step);
	}
	else
	{
		var numDigits = 7;
		starAdvDoLightStars = false;
		resetDigitAtPosition(numDigits, 'ptsTickerDigit');
		starAdvDoLightStars = true;
		
		counterDigits = [];
		oldCounterDigits = [];
	}
}

function resetDigitAtPosition(pos, whichCounter) {
	var step = 125;
	var increment = 1;
	var spacing = 0.25;
	if (whichCounter == 'cartCounterDigit')
	{
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit' + pos,'0','-52'); }, (1+(pos-1)*spacing)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit' + pos,'0','-104'); }, ((1+(pos-1)*spacing)+increment)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit' + pos,'0','0'); }, ((1+(pos-1)*spacing)+2*increment)*step);
	}
	else
	{
		changeBackgroundPosition('ptsTickerDigit'+pos,'0','0');
		
		if (--pos >= 1)
			resetDigitAtPosition(pos, 'ptsTickerDigit');
		else
			starAdvLightStars();
	}
}

function setDigitAtPosition(pos, num, oldNum, whichCounter) {
	var step = 125;
	if (whichCounter == 'cartCounterDigit')
	{
		var increment = 1;
		var spacing = 0.25;
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit' + pos,'0','-52'); }, (1+(pos-1)*spacing)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit' + pos,'0','-104'); }, ((1+(pos-1)*spacing) + increment)*step);
		for(var i = 0; i <= num; ++i) {
			var f1 = function(y) { return function() { changeBackgroundPosition('cartCounterDigit' + pos,-31*(y+1),'-52'); } }(i);
			var f2 = function(y) { return function() { changeBackgroundPosition('cartCounterDigit' + pos,-31*(y+1),'0'); } }(i);
			setTimeout(f1, ((1+(pos-1)*spacing)+(2*i+2)*increment)*step);
			setTimeout(f2, ((1+(pos-1)*spacing)+(2*i+3)*increment)*step);
		}
		if(num == 0) {
			setTimeout(function() {changeBackgroundPosition('cartCounterDigit' + pos,-31,'-52'); }, ((1+(pos-1)*spacing)+2*increment)*step);
			setTimeout(function() {changeBackgroundPosition('cartCounterDigit' + pos,-31,'0'); }, ((1+(pos-1)*spacing)+3*increment)*step);
		}
	}
	else
	{
		for (var i = (oldNum == null)? 0 : oldNum+1, f = 0; i != (num+1); i = (i+1)%11, f++)
		{
			var f1 = function(y) { return function() { changeBackgroundPosition('ptsTickerDigit' + pos,-23.4*y,'-39'); } }(i);
			var f2 = function(y) { return function() { changeBackgroundPosition('ptsTickerDigit' + pos,-23.4*y,'-78'); } }(i);
			var f3 = function(y) { return function() { changeBackgroundPosition('ptsTickerDigit' + pos,-23.4*((y+1)%11),'0'); } }(i);
			setTimeout(f1, f*step + (1/4)*step);
			setTimeout(f2, f*step + (3/4)*step);
			setTimeout(f3, f*step + step);
		}
		
		var newPos = pos-1;
		if (newPos >= 1)
		{
			if ((7-newPos) < counterDigits.length)
			{
				var oldDigit = ((7-newPos) < oldCounterDigits.length)? oldCounterDigits[7-newPos] : null;
				if (newPos == 4 || newPos == 1)
					setTimeout("setDigitAtPositionWithComma("+newPos+","+counterDigits[7-newPos]+","+oldDigit+",'ptsTickerDigit')", f*step+step);
				else
					setTimeout("setDigitAtPosition("+newPos+","+counterDigits[7-newPos]+","+oldDigit+",'ptsTickerDigit')", f*step+step);
			}
			else
				setTimeout("resetDigitAtPosition("+newPos+", 'ptsTickerDigit')", f*step+step);
		}
		else
			starAdvLightStars();
	}
}

function setDigitAtPositionWithComma(pos, num, oldNum, whichCounter) {
	var step = 125;
	if (whichCounter == 'cartCounterDigit')
	{
		var increment = 1;
		var spacing = 0.25;
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit' + pos,'0','-52'); }, 1*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit' + pos,'0','-104'); }, (1+increment)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit' + pos,-31*(num+1),'-52'); }, (1+2*increment)*step);
		setTimeout(function() {changeBackgroundPosition('cartCounterDigit' + pos,-31*(num+1),'-104'); }, (1+3*increment)*step);
	}
	else
	{
		for (var i = (oldNum == null)? 0 : oldNum+1, f = 0; i != (num+1); i = (i+1)%11, f++)
		{
			var f1 = function(y) { return function() { changeBackgroundPosition('ptsTickerDigit' + pos,-23.4*y,'-39'); } }(i);
			var f2 = function(y) { return function() { changeBackgroundPosition('ptsTickerDigit' + pos,-23.4*y,'-78'); } }(i);
			
			if ((i+1)%11 == (num+1))	// last iteration of loop
				var f3 = function(y) { return function() { changeBackgroundPosition('ptsTickerDigit' + pos,-23.4*((y+1)%11),'-118'); } }(i);
			else
				var f3 = function(y) { return function() { changeBackgroundPosition('ptsTickerDigit' + pos,-23.4*((y+1)%11),'0'); } }(i);
				
			setTimeout(f1, f*step + (1/4)*step);
			setTimeout(f2, f*step + (3/4)*step);
			setTimeout(f3, f*step + step);
		}

		var newPos = pos-1;
		if (newPos >= 1)
		{
			var oldDigit = ((7-newPos) < oldCounterDigits.length)? oldCounterDigits[7-newPos] : null;
			if ((7-newPos) < counterDigits.length)
				setTimeout("setDigitAtPosition("+newPos+","+counterDigits[7-newPos]+","+oldDigit+",'ptsTickerDigit')", f*step+step);
			else
				setTimeout("resetDigitAtPosition("+newPos+",'ptsTickerDigit')", f*step+step);
		}
		else
			starAdvLightStars();
	}
}

function changeBackgroundPosition(id, posX, posY) {
	if($(id)) {
		$(id).style.backgroundPosition = posX + 'px ' + posY + 'px';
	}
}

/* public_HeaderController */
/* star advantage dropdown */
var dontHideBadgeOffers = false;

function setDontHideBadgeOffers(value)
{
	dontHideBadgeOffers = value;
}

function getDontHideBadgeOffers()
{
	return dontHideBadgeOffers;
}

function showBadgeOffers()
{
	setDontHideBadgeOffers(true);
	setTimeout('_showBadgeOffers()',10);
	
	$('starAdvArrow').src = 'http://imga.nxjimg.com/emp_image/UserRank/header/header_arrow_up.gif';
	$('starAdvantageReadoutContainer').stopObserving('click', showBadgeOffers);
	$('starAdvantageReadoutContainer').observe('click', hideBadgeOffers);
}

function _showBadgeOffers()
{
	setDontHideBadgeOffers(false);
	
	$('ptsTickerNormalBG').style.visibility = 'hidden';
	$('ptsTickerBadgeBG').style.visibility = 'visible';
		
	$('ptsBadgeOffers').innerHTML = '<center><img alt="Loading Offers" src="http://imga.nxjimg.com/emp_image/invitefriend/loading.gif" title="Loading Offers"></center>';
	
	var howManyPerPage = 4;
	new Ajax.Request('/header/getstaradvantage/',
					 {method:'get',
					 onSuccess:loadStarAdvantage});
	}

	
function loadStarAdvantage(ajax_request){
	$('ptsBadgeOffers').innerHTML = ajax_request.responseText;
	if($('hpbRed_0')) {	
		var bonusCount = parseInt($('bonusCountHeader').value);
		for (var i = 0; i < bonusCount; i++){
			var timeleft = parseInt($('timeLeftHeader_' + i).value);
			var timetotal = parseInt($('timeTotalHeader_' + i).value);
            if (timetotal != 0) {
                new Effect.Morph('hpbRed_' + i, {style:'width:' + timeleft*(233/timetotal) + 'px', duration:1});
            }
		}
	}
	if($('hpbBlue')) {
		var lastYear = parseInt($('lastYearHeader').value);
		var userRankLastYear = parseInt($('userRankLastYearHeader').value);
		var userRankThisYear = parseInt($('userRankThisYearHeader').value);
		var qualPtsEarnedThisYear = parseInt($('qualPointsEarnedThisYearHeader').value);

		if (userRankThisYear == 5 || userRankLastYear == 5) {
			new Effect.Morph('hpbBlue', {style:'width:233px', duration:1});
		} else if (lastYear == 1) {
			var nextLevel = userRankLastYear + 1;
			new Effect.Morph('hpbBlue', {style:'width:' + qualPtsEarnedThisYear*(233/(nextLevel*1000)) + 'px', duration:1});
		} else {
			qualPtsEarnedThisYear = qualPtsEarnedThisYear - (userRankThisYear*1000);
			new Effect.Morph('hpbBlue', {style:'width:' + qualPtsEarnedThisYear*.233 + 'px', duration:1});
		}
	}
    //this function is defined in cart/javascript.phtml - relights stars to refresh

}

function hideBadgeOffers()
{
	if (getDontHideBadgeOffers())
		return;
		
	if ($('ptsTickerBadgeBG'))
		$('ptsTickerBadgeBG').style.visibility = 'hidden';
	if ($('ptsTickerNormalBG'))
		$('ptsTickerNormalBG').style.visibility = 'visible';
	if($('starAdvArrow') != undefined && $('starAdvArrow') != null){
		$('starAdvArrow').src = 'http://imga.nxjimg.com/emp_image/UserRank/header/header_arrow_down.gif';
		$('starAdvantageReadoutContainer').stopObserving('click', hideBadgeOffers);
		$('starAdvantageReadoutContainer').observe('click', showBadgeOffers);
	}
		
}


/* pts ticker */

function flashCounter(message, param, param2)
{
	if (message == 'winner')
		var bgImageAddress = 'http://imga.nxjimg.com/emp_image/header/pts_ticker_winner.gif';
	else
		return;	/* for now, only 'winner' supported */
	
	for (var f = 1; f <= 7; f++)
		$('ptsTickerDigit'+f).style.backgroundImage = "url('"+bgImageAddress+"')";
		
	var normalFlashDuration = 150;
	var lastFlashDuration = 2000;
	var delayBeforeCountUp = 3000;
	
	for (var i = 0; i < 40; i += 2)
	{
		setTimeout('flashCounterWinnerB()', i*normalFlashDuration);
		setTimeout('flashCounterWinnerA()', (i+1)*normalFlashDuration);
	}
	
	var resetDigitBackgrounds = "";
	for (f = 1; f <= 7; f++) {
        resetDigitBackgrounds += "$('ptsTickerDigit"+f+"').style.backgroundImage = \"url('http://imga.nxjimg.com/emp_image/header/pts_ticker_digits_2b.gif')\";";
    }
    setTimeout(resetDigitBackgrounds, (i-1)*normalFlashDuration+lastFlashDuration);
   
    setTimeout("resetCounterTo("+param+",'ptsTickerDigit');", (i-1)*normalFlashDuration+lastFlashDuration);
    if(!(param && param2 && param == param2)) {
        for (f = 0; f < 15; f += 2)
        {
            setTimeout("resetCounterTo(null,'ptsTickerDigit');", (i-1)*normalFlashDuration+lastFlashDuration*2 + f*normalFlashDuration);
            setTimeout("resetCounterTo("+param+",'ptsTickerDigit');", (i-1)*normalFlashDuration+lastFlashDuration*2 + (f+1)*normalFlashDuration);
        }
        setTimeout("spinCounter("+param2+",'ptsTickerDigit');", (i-1)*normalFlashDuration+lastFlashDuration+(f-1)*normalFlashDuration+delayBeforeCountUp);
    }
}

function flashCounterWinnerA()
{
	changeBackgroundPosition('ptsTickerDigit1', -47, 0);
	changeBackgroundPosition('ptsTickerDigit2', -70, 0);
	changeBackgroundPosition('ptsTickerDigit3', -94, 0);
	changeBackgroundPosition('ptsTickerDigit4', -117, 0);
	changeBackgroundPosition('ptsTickerDigit5', -140, 0);
	changeBackgroundPosition('ptsTickerDigit6', -164, 0);
	changeBackgroundPosition('ptsTickerDigit7', -187, 0);
}

function flashCounterWinnerB()
{
	changeBackgroundPosition('ptsTickerDigit1', -47, -39.5);
	changeBackgroundPosition('ptsTickerDigit2', -70, -39.5);
	changeBackgroundPosition('ptsTickerDigit3', -94, -39.5);
	changeBackgroundPosition('ptsTickerDigit4', -117, -39.5);
	changeBackgroundPosition('ptsTickerDigit5', -140, -39.5);
	changeBackgroundPosition('ptsTickerDigit6', -164, -39.5);
	changeBackgroundPosition('ptsTickerDigit7', -187, -39.5);
}


function getPosY(e) {
                var posy = 0;
                if (!e) var e = window.event;

                if (e.clientY) {
                                posy = e.clientY
                } else if (e.pageY) {
                                posy = e.pageY;
                }


                if(document.body.scrollTop && document.body.scrollTop > 0) {
                                posy = posy + document.body.scrollTop;
                }
                else if (document.documentElement.scrollTop && document.documentElement.scrollTop > 0) {
                                posy = posy + document.documentElement.scrollTop;
                }
                else if (e.pageYOffset && e.pageYOffset > 0) {
                                posy = posy + e.pageYOffset;
                }

                return posy;
}

function getPosX(e) {
                var posx = 0;
                if (!e) var e = window.event;
                if (e.clientX) {
                                posx = e.clientX
                } else if (e.pageX) {
                                posx = e.pageX;
                }

                if(document.body.scrollLeft && document.body.scrollLeft > 0) {
                                posx = posx + document.body.scrollLeft;
                }
                else if (document.documentElement.scrollLeft && document.documentElement.scrollLeft > 0) {
                                posx = posx + document.documentElement.scrollLeft;
                }
                else if (e.pageXOffset && e.pageXOffset > 0) {
                                posx = posx + e.pageXOffset;
                }

                return posx;
}

function getMouseXY(e) {
  if (IE) { // grab the x-y pos.s if browser is IE
    tempX = event.clientX + document.body.scrollLeft
    tempY = event.clientY + document.body.scrollTop
  } else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX
    tempY = e.pageY
  }  
  // catch possible negative values in NS4
  if (tempX < 0){tempX = 0}
  if (tempY < 0){tempY = 0}  
  // show the position values in the form named Show
  // in the text fields named MouseX and MouseY
  document.Show.MouseX.value = tempX
  document.Show.MouseY.value = tempY
  return true
}


function togglelogin(event)
{
	
	
	if(getPosY(event)>1200)
		$("loginpopup").style.top = "950px";
	else
	{
		if(getPosY(event)>400)
			$("loginpopup").style.top = "" + (0 + getPosY(event) -220) + "px";
		else
			$("loginpopup").style.top = "0px";
	}

	

	if($("SIBack"))
	{
		if($("SIBack").style.display =='block')
		{
			document.body.style.background='#fff';
			$("loginpopup").style.display='none';
			$("SIBack").style.display ='none';
		}
		else
		{
			document.body.style.background='#e8e8e8';
			$("outer-container").style.background='#fff';
			$("loginpopup").style.display='block';
			
			$("SIBack").style.display ='block';
		}
		
	}
}

function toggleloginnewdeal(event)
{
	
	
	if(getPosY(event)>1200)
		$("loginpopup").style.top = "950px";
	else
	{
		if(getPosY(event)>400)
			$("loginpopup").style.top = "" + (0 + getPosY(event) -320) + "px";
		else
			$("loginpopup").style.top = "0px";
	}

	

	if($("SIBack"))
	{
		if($("SIBack").style.display =='block')
		{
			document.body.style.background='#fff';
			$("loginpopup").style.display='none';
			$("SIBack").style.display ='none';
		}
		else
		{
			document.body.style.background='#e8e8e8';
			$("outer-container").style.background='#fff';
			$("loginpopup").style.display='block';
			
			$("SIBack").style.display ='block';
		}
		
	}
}

function validateJoin1() {
  if (validate_email($("joinEmail1").value)) {
    return true;
  } else {
    $('error-message11').style.display='block';
  $('error-space1').style.display='none';
    $('error-message11').update("The email address you provided doesn't appear to be valid.");
    return false;
  }
}

function validatePassword1() {
if ($("loginPasswordStar1").value.length > 0) {
    return true;
  } else {
  	$('error-message11').style.display='block';
  	$('error-space1').style.display='none';
    $('error-message11').update("Please enter a password.");
    return false;
  }
}

function submitJoin1() {
  if (validateJoin1()) {
    document.join1.submit();
  }
}

function submitLogin1() {
	
	if (validateEmail1() && validatePassword1()) {

  	document.login1.submit();

  	return true;
	}
//	else return false;
}
function validateEmail1() {
  if (validate_email($("loginEmail1").value)) {
    return true;
  } else {
  $('error-message11').style.display='block';
  $('error-space1').style.display='none';
    $('error-message11').update("A valid email address is required.");
    return false;
  }
}

function hide(divID){
  if($(divID) && !($(divID).style === undefined) && $(divID).style.display=='block'){				
    $(divID).style.display='none';		
  }
}

function bodyClick(){
    maincatnavoff();
    function hide(divID){
        // There are issues with other code redifining the hide function...
        // Imagine that... a namespace collision.  So i'm locking down the defintion
        // of hide within the scope of the body click.
        if($(divID) && !($(divID).style === undefined) && $(divID).style.display=='block'){				
            $(divID).style.display='none';		
        }
    }
    if($('mlcontainer1') != undefined && $('mlcontainer1') != null){
        hide('mlcontainer1');
    }
    hide('accountdropdown');
    hide('helpdropdown');
    hide('filter_dropdown');
    hide('org_dropdown');
    hide('category_dropdown');

    if($('pointdropdown') != undefined && $('pointdropdown') != null){
    hide('pointdropdown');
    }
    if($('filterList') != undefined && $('filterList') != null){		
    hide('filterList');	
    }
    //hide the drop down from lto page
    if( typeof isLTO === undefined) {

    }
    else{
    hide('CBdropdown');	
    }

    //hide the drop down category list of best selling product widget
    if (typeof showingHGOG=="undefined") { 
    } else { 
    if (showingHGOG) { 
     setTimeout("guidehideDivCat();",20);
    }
    }


    if($('reminderSortFilterList') != 'undefined' && $('reminderSortFilterList') != null) {
        hide('reminderSortFilterList');
    }
    
    if ($('usDropdownTxnAllTimes')) {
        $('usDropdownTxnAllTimes').hide();
        $('usDropdownTxnAllTypes').hide();
    }
}

function getPosX(e) {	
  var posx = 0;	
  if (!e) var e = window.event;	
  if (e.clientX) {		
    posx = e.clientX;
  } else if (e.pageX) {		
    posx = e.pageX;	
  }	
  if(document.body.scrollLeft && document.body.scrollLeft > 0) {		
    posx = posx + document.body.scrollLeft;	
  }else if (document.documentElement.scrollLeft && document.documentElement.scrollLeft > 0) {		
    posx = posx + document.documentElement.scrollLeft;	
  }else if (e.pageXOffset && e.pageXOffset > 0) {		
    posx = posx + e.pageXOffset;	
  }	
  return posx;
}

function getPosY(e) {
  var posy = 0;	
  if (!e) var e = window.event;	
  if (e.clientY) {		
    posy = e.clientY;
  } else if (e.pageY) {		
    posy = e.pageY;	
  }	
  if(document.body.scrollTop && document.body.scrollTop > 0) {		
    posy = posy + document.body.scrollTop;	
  }else if (document.documentElement.scrollTop && document.documentElement.scrollTop > 0) {
    posy = posy + document.documentElement.scrollTop;	
  }else if (e.pageYOffset && e.pageYOffset > 0) {		
    posy = posy + e.pageYOffset;	
  }	
  return posy;
}


	var rev_keepmainnav = false;

    var keepmainnav = false;
	var mlHoverOpen = false;
	var mlClickOpen = false; 
   
    var isOpeningMainNav = false;
    var openingMainNav = false;
	var clickedMainNav = false;

	//hideAllSubcats();
	//hideAllSubSubcats();
	

	function toggleDiv(name){
		if ( $(name).style.display=='block' ) {
			$(name).style.display='none';
		} else {
			setTimeout("$('"+name+"').style.display='block';",50);
		}
	}
	
    function toggleDivCat(name){
		if ( $(name).style.display=='block' ) {
			hideAllSubcats();
			$(name).style.display='none';
		} else {
			hideAllSubcats();
			setTimeout("$('"+name+"').style.display='block';",1);
		}
	}
	
	function toggleDivCat2(name){
			hideAllSubcats();
			$(name).style.display='block';
	}
	
	function toggleSubSubDivCat(name){
			hideAllSubSubcats();
			$(name).style.display='block';
	}
	
	function toggleML(){
		name = 'maincatdropdown';
		if ( mlClickOpen || mlHoverOpen ) { 
			hideAllSubcats();
			$(name).style.display='none';
			clickedMainNav=false;	
			//alert('makefalse2');
			mlClickOpen=false;
			mlHoverOpen=false;
		} else {
			hideAllSubcats();
			setTimeout("$('"+name+"').style.display='block';mlClickOpen=true;",30);
			clickedMainNav=true;	
		}
	}
	
   function showDivCat(name){
		$(name).style.display='block';
	}	
	
    function hidediv(name){
		if ( $(name) && !($(name).style === undefined) && ($(name).style.display=='block' || $(name).style.display=='' )) {
			$(name).style.display='none';
			if (name=='maincatdropdown') {
				mlClickOpen = false;
			}
		} 

	}
	

	
    function maincatnavoff(){	
   		if (!keepmainnav) {	
			if(window.hideAllSubcats)
				{hideAllSubcats();}
			hidediv('maincatdropdown');
			mlHoverOpen = false;
            if($('BarDownArrow'))
			{$('BarDownArrow').className = 'BarDownArrow_off';
			//$('BarDownArrow').src='http://imga.nxjimg.com/secured/image/09/nav/17_down_off.gif';
			}
		}		
    }
    
    function changeBarDownArrow() {
		if (mlHoverOpen || mlClickOpen) {
        $('BarDownArrow').className = 'BarDownArrow_on';
        
			//$('BarDownArrow').src='http://imgb.nxjimg.com/secured/image/09/nav/dk_gray_17_down.gif';
		} 
        else {
        $('BarDownArrow').className = 'BarDownArrow_off';
        
			//$('BarDownArrow').src='http://imga.nxjimg.com/secured/image/09/nav/17_down_off.gif';
			//off($('BarDownArrow'));
		}
		
	}
	

	
    function highlightMainRow (index) {
        if($('maindropdownrow'+index) !== undefined && $('maindropdownrow'+index) !== null){
            $('maindropdownrow'+index).style.background='#feffff';
        }
    }
	
    function unhighlightMainRow (index) {
        if($('maindropdownrow'+index) !== undefined && $('maindropdownrow'+index) !== null){
            $('maindropdownrow'+index).style.background='#eff6ff';
        }
    }
	
	function unhighlightSubSubRow (index) {
		$('alldropdownrow'+index).style.background='#eff6ff';
		//off($('alldropdownarrow'+index));
	}
	
	function hoverOpenMainNav(){
		openingMainNav=true;
		setTimeout("tryOpenMainNav()",500);
	}
	
	function tryOpenMainNav(){
		if (openingMainNav) {
			$('maincatdropdown').style.display='block';
		}
	}
	
	function hoverOpenArrow() {
		isOpeningMainNav = true;
		setTimeout("hoverOpenArrow2();",800);
	}
	
	function hoverOpenArrow2() {
		if (isOpeningMainNav) {
			mlHoverOpen=true;
			showDivCat('maincatdropdown');
			clickedMainNav=true;
		}
	}
	
	function tryCloseMainNav(){
		if (!mlClickOpen && mlHoverOpen) {
			hideAllSubcats();
			$('maincatdropdown').style.display='none';
			mlHoverOpen = false;
		}	
	}
	
	
	
	function setKeepMainNavTrue() {
		keepmainnav=true;
		setTimeout("keepmainnav=false;",500);
	}
	
	function onMouseOutMainNavRow1 (index) {
		setTimeout("onMouseOutMainNavRow2("+index+")",500);
	}

	function onMouseOutMainNavRow2 (index) {
		if($('maindropdownrow'+index).style.backgroundColor=='#feffff'  ) { 
		}
		else {
			$('maindropdownrow'+index).style.background='#eff6ff';
		}
	}
	
	function moveMainList(num) {
		hideAllSubcats();
		if (num==1){
			other=2;
			oldsource1='DST';
			newsource1='DSB';
			oldsource2='DT';
			newsource2='DB';
		}
		else {
			other = 1;
			oldsource1='DSB';
			newsource1='DST';
			oldsource2='DB';
			newsource2='DT';
		}
		
		if ( $('mlcontainer'+num).innerHTML=='' ) {
			$('mlcontainer'+num).innerHTML=$('mlcontainer'+other).innerHTML.replace(new RegExp(oldsource1,"g"),newsource1).replace(new RegExp(oldsource2,"g"),newsource2);
			$('mlcontainer'+other).innerHTML='';
		}		
	}
	
	function whiteBG(e) {
		setTimeout("$('"+e+"').style.background='#ffffff'",10);
	}


function openDiv(div){
	if($(div).style.display == 'block'){
		$(div).style.display = 'none';
	}else{
		$(div).style.display = 'block';
	}

}


function rev_maincatnavoff(){	
	if (!rev_keepmainnav) {	
		//rev_hideAllSubcats();
		rev_hidediv('revcatdropdown');
		rev_mlHoverOpen = false;			
		$('rev_BarDownArrow').src='http://imga.nxjimg.com/secured/image/09/nav/17_down_off.gif';
	}
}		
		
function clearSearchField() {
	if ($('searchInput').value == 'Search Offers & Merchants') {
	$('searchInput').value = '';
	}
	$('searchInput').style.color = 'black';
}

function replaceEmptySearch() {
	if($('searchInput').value == '') {
		$('searchInput').value = 'Search Offers & Merchants';
		$('searchInput').style.color = 'gray';
	}
}

function searchSubmit() {
	if($('searchInput').value =='Search Offers & Merchants') {
		$('searchInput').value = '';
	}
	$('search_form').submit();
}

var googleMapsLoaded = false;
function loadGoogleMaps(){
    if(!googleMapsLoaded){
        googleMapsLoaded = true;
        Event.observe(window, 'load', function(){
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = "//maps.google.com/maps/api/js?sensor=false&callback=empty";
            document.body.appendChild(script);
        });
    }
}
function empty(){}


/* ObsessionsController */

var usource = 'HPSG';
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}

function toggleGender(g, listStyle){
    hideToggle = 0;
    if($('popularGenderOn') && !g){
        if($('popularGenderOn').innerHTML == 'Men'){
            g = 'F';
            $('popularGenderOn').innerHTML = 'Women';
            $('popularGenderOff').innerHTML = 'Men';
        }else{
            g = 'M';
            $('popularGenderOn').innerHTML = 'Men';
            $('popularGenderOff').innerHTML = 'Women';
        }
        hideToggle = 1;
    }
    if(listStyle){
        listStyle = "/listStyle/" + listStyle;
    }else{
        listStyle = "";
    }

    var myAjax = new Ajax.Request('/obsessions/mostshoppedwidget/gender/'+ g + listStyle + '/hideToggle/'+ hideToggle,
                {	method:'post'
                    ,onSuccess:function(e){
                        $('mostPurchasedCon').innerHTML = e.responseText;
                    }
                });
}

function showZipPopup(){
	$('added_popup').setStyle('display:block');
}
/* 5 star Popup box*/
var openPopup = 0;
var timeoutid = 0;
function closeBonusPopUp(id){
	openPopup = 0;
	clearTimeout(timeoutid);
	if(id){
		timeoutid = setTimeout(closeBonusPopUpWithDelay, 300);
	}else{
		timeoutid = setTimeout(closeBonusPopUpWithDelay, 1);
	}
}

function openBonusPopUpWithDelay(){
	if(openPopup){
		$('bonusPopUp').style.display = 'block';
		openPopup = 0;
	}
}

function closeBonusPopUpWithDelay(time){
	if($('bonusPopUp')){
		$('bonusPopUp').style.display = 'none';		
	}
}
function toggleDisplay(displayId){
    if($(displayId).style.display == 'block'){
        $(displayId).style.display = 'none';
    }else if( $(displayId).style.display == 'none'){
        $(displayId).style.display = 'block';
    }
}
var openWowPopup = 0;
var wowtimeoutid = 0;

function closewowPopUp(id){
    openWowPopup = 0;
    clearTimeout(wowtimeoutid);
    if(id){
        wowtimeoutid = setTimeout(closewowPopUpWithDelay, 200);
    }else{
        wowtimeoutid = setTimeout(closewowPopUpWithDelay, 1);
    }
}

function openwowPopUp(id){
    clearTimeout(wowtimeoutid);
    openWowPopup = 1;
    wowtimeoutid = setTimeout(openwowPopUpWithDelay, 300);
}
function closewowPopUpWithDelay(){
    if(!openWowPopup){
        $('wowPopUp').style.display = 'none';
        openWowPopup = 1;
    }
}

function openwowPopUpWithDelay(){
    if(openWowPopup){
        $('wowPopUp').style.display = 'block';
        openWowPopup = 0;
    }
}
function showVipBanner(divId){
    Effect.SlideDown(divId);
    $('vipLinkSoho').hide();
}
function hideVipBanner(divId){
    Effect.SlideUp(divId);
    setTimeout("$('vipLinkSoho').show()", 500);
}

