





/* LocaldealswidgetController */
var makeNS = function(path){
    for(var i=0, pos=window, path=path.split('.'), pl=path.length; i<pl; i++) {
        pos = pos[path[i]] = pos[path[i]] || {};
    }
    return pos;
};

(function(self) {
    var ie6 = /MSIE 6/.test(navigator.userAgent);
    var ie7 = /MSIE 7/.test(navigator.userAgent);
    
    var makeMap = function(div, name, lat, long) {
        var pos = new google.maps.LatLng(lat, long),
            map = new google.maps.Map(div, {
                zoom: 15,
                center: pos,
                zoomControl : true,
                disableDefaultUI: true,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }),
            marker = new google.maps.Marker({
                position: pos,
                map: map,
                title: name,
                icon: 'http://imga.nxjimg.com/emp_image/localdeals/smallA.png',
                animation: google.maps.Animation.DROP
            });
    }
    
    var shortenDescription = function(e) {
        var description = e.select('.description')[0];
        description.removeClassName('descriptionScroll');
        if(description.measure('height') > 190) {
            description.addClassName('descriptionScroll');
        }
    };
    
    var showOverlay = function() {
        document.body.appendChild($('processingWait'));
        $('processingWait').show();
    };
    
    self.initQuickview = function(parentSelector, linkSelector) {
        // open quickview
        var restorePopup;
        $$(parentSelector).each(function(e) {
            var details = e.select('.popupDetails'),
                detail = details.length ? details[0] : false,
                id = e.getAttribute('data-id'),
                links = linkSelector ? e.select(linkSelector) : $A([e]);
                links.invoke('observe', 'click', function(event) {
                event.stop();
                if(restorePopup) {
                    restorePopup();
                }
                if(detail) {
                    $('bigPopupContent').appendChild(detail);
                    $('bigPopup').show();
                    if(ie6) {
                        $('bigPopup').setStyle({
                            'top': document.viewport.getScrollOffsets().top + 100 + 'px'
                        });
                    } else if(detail.select('.gMapInner > img').length) {
                        var target = detail.select('.gMapInner')[0],
                            name = target.getAttribute('data-name'),
                            lat = target.getAttribute('data-lat'),
                            lng = target.getAttribute('data-lng');
                        setTimeout(makeMap.curry(target, name, lat, lng, 500));
                    }
                    shortenDescription(detail);
                    restorePopup = function() {
                        e.appendChild(detail);
                    };
                }
                if(id) {
                    new Ajax.Request(params.quickviewUrl, {
                        method: 'get',
                        parameters: { 
                            id: id,
                            logRequired: 1
                        }
                    });
                }
            });
            // change quickview to update with selection
            detail.select('.selectDenom input').invoke('observe', 'click', function(event) {
            	detail.select('.jsValue').invoke('update', this.getAttribute('data-value'));
            	detail.select('.jsPrice').invoke('update', this.getAttribute('data-price'));
                detail.select('.jsPriceNoDollar').invoke('update', this.getAttribute('data-price').substr(1));
                detail.select('.jsPriceBeforeDiscount').invoke('update', this.getAttribute('data-priceBeforeDiscount'));
                detail.select('.jsPts').invoke('update', this.getAttribute('data-pts'));
                detail.select('.jsTerms').invoke('update', this.getAttribute('data-terms'));
                
                detail.select('.save, .jsPriceNoDollar, .jsPts, .termsconditions').invoke(
                		'highlight', { startcolor: '#DAE9FC', endcolor: '#ffffff' });
            });
        });
        
        // close quickview
        $$('#bigPopup .close, #bigPopup .cover').invoke('observe', 'click', function(event) {
            if(restorePopup) {
                restorePopup();
            }
            restorePopup = false;
            $('bigPopup').hide();
            event.stop();
        });
        
        // fix restaurant name overflowing
        $$('.listRow .description .name').each(function(e) {
            e.removeClassName('shortened');
            var words = e.innerHTML.split(/[\s]+/);
            if(e.measure('height') > 21) {
                e.addClassName('long');
                while(e.measure('height') > 21) {
                    words.pop();
                    e.update(words.join(' ') + '...');
                }
            }
        });
        self.addToCart = function(url){
            new Ajax.Request(url, function(){
                //we will do something here
            });
        }
    };
    
    self.initIndex = function(params) {
        $$('.quantity select').invoke('observe', 'change', function(event) {
            $('loading').show();
            event.findElement('form').request({
                onComplete: function() {
                    setTimeout(function() {
                        var sels = $$('.tbody .quantity select'),
                            pts = $$('.tbody .yearnings span'),
                            costs = $$('.tbody .subtotal div'),
                            totalPrice = 0,
                            totalPoints = 0,
                            po1nts, price;
                        for(var i=0; i<sels.length; i++) {
                            price = sels[i].getAttribute('data-price') * (sels[i].selectedIndex + 1);
                            costs[i].update('$' + price.toFixed(2));
                            totalPrice += price;
                            
                            po1nts = Math.ceil(price * params.po1ntsRank);
                            pts[i].update(po1nts);
                            totalPoints += po1nts;
                        }
                        $('totalprice').update('$' + totalPrice.toFixed(2));
                        $('totalpointsspan').update(totalPoints);
                        $('loading').hide();
                    }, 500);
                }
            });
        });
    };
    
    self.initCheckout = function(params) {
        var checkoutProcessing = false;
        
        $('buyNew').observe('click', function(event) {
            if(!checkoutProcessing) {
                var valid = nxjdy.cc.validateForm();
                if(valid!==true) {
                    $('cardError').update(valid);
                } else {
                    showOverlay();
                    processForm($('optionNew'), $('cardError'));
                }
            }
        });
        
        $('buyLinked').observe('click', function(event) {
            if(!checkoutProcessing && !$('cardToken')) {
                showOverlay();
                processForm($('optionLinked'), $('linkedError'));
            }
        });
        
        function processForm(form, error) {
            checkoutProcessing = true;
            form.request({
                parameters: {
                    ajax: 1,
                    logRequired: 1
                },
                onComplete: function(xhr) {
                    try {
                        var obj = JSON.parse(xhr.responseText) || {};
                        if(obj.cartId) {
                            window.location = params.completeURL + '/cart/' + obj.cartId;
                        } else if(obj.invalid) {
                            window.location = params.checkoutURL + '/failed/' + obj.invalid;
                        } else {
                            error.update(obj.error || 'There was an issue processing your purchase, please try again in a short while');
                            $('processingWait').hide();
                            checkoutProcessing = false;
                        }
                    } catch(err) {
                        error.update('There was an issue processing your purchase, please try again in a short while');
                        $('processingWait').hide();
                        checkoutProcessing = false;
                    }
                },
                onError: function() {
                    error.update('There was an issue processing your purchase, please try again in a short while');
                    $('processingWait').hide();
                    checkoutProcessing = false;
                }
            });
        }
    };
}) (makeNS('nxjdy.cart'));



/* preferencepersonalizerwidgetController */


/* Mastercard_PersonalizedwidgetController */

var eCancelReload=false;
var eIsDeleting=false;
var rIsDeleting=false;

var isScrolling = false;
var isSwapping = false;
var isLoading = true;

var destdivCopy="";

var lpIndex = 0;

var eTotal = -1;
var rTotal = -1;

var eStartId = 1;
var rStartId = 1;

var erFirstInView = 1;
var rrFirstInView= 1;

var erLastInView = 4;
var rrLastInView= 4;

var er = new Array();
er[0] = '';

var rr = new Array();
rr[0] = '';


var  eMerchantIds = new Array();
eMerchantIds[0] = '';
eMerchantIds[1] = '';
eMerchantIds[2] = '';
eMerchantIds[3] = '';
 	 
var  rMerchantIds = new Array();
rMerchantIds[0] = '';
rMerchantIds[1] = '';
rMerchantIds[2] = '';
rMerchantIds[3] = '';

var keepSB = false;
var SBClickOpen = false; 		

function swapOfferSingle(elementId, position,matchType,pageNum, OfferID,merchid,curMid1,curMid2,curMid3) {
	if (matchType == 'related')
	{ rMerchantIds[0] = curMid1;
	  rMerchantIds[1] = curMid2;
	  rMerchantIds[2] = curMid3;
	}
	else{
	  eMerchantIds[0] = curMid1;
	  eMerchantIds[1] = curMid2;
	  eMerchantIds[2] = curMid3;
	}

	$(elementId+'mask').style.display='block';
	$(elementId+'yellowbox').style.display='block';


	if (matchType == 'exact'){
		eIsDeleting=true;
	}else if(matchType == 'related'){
		rIsDeleting=true;
	}
	if(pageNum != 'home'){
		add4More(matchType);
	}
	setTimeout("swapOfferSingle2('"+elementId+"','"+position+"','"+matchType+"','"+pageNum+"','"+OfferID+"','"+merchid+"')",3000);

}

function openClose(div){
	if($(div).style.visibility == 'visible'){
		$(div).style.visibility = 'hidden';
	}else{
		$(div).style.visibility = 'visible';
	}
}

function swapOfferSingle2(elementId, position,matchType,pageNum, OfferID,merchid) {
	
	 if ($(elementId+'mask') && $(elementId+'mask').style.display=='block') {
		 
		var origMatchType = matchType;
		
		for (i=1; i<rr.length; i=i+1) {
			if (rr[i] == elementId) {
				position = i;
				matchType='related';
			} 
		}
		for (i=1; i<er.length; i=i+1) {
			if (er[i] == elementId) {
				position = i;
				matchType='exact';
			} 
		}
		
		if ($(elementId+'yellowbox')) {
		 	$(elementId+'yellowbox').style.display='none';
		}
		$(elementId).style.background='#fff';
		 
		setTimeout("finishDelete('"+elementId+"','"+position+"','"+matchType+"','"+origMatchType+"','"+pageNum+"','"+OfferID+"','"+merchid+"')",10);
	 }
}

function showLoading(containerId,matchType) {
	if (matchType=='similar') {
	    $(containerId).innerHTML =$('loadingCardS').innerHTML;
	} else if (matchType=='exact') {
		$(containerId).innerHTML =$('loadingCardE').innerHTML;
	} else {
		$(containerId).innerHTML =$('loadingCardR').innerHTML;
	}

}

function undoDelete(elementId) {	   		 
		$(elementId+'mask').style.display='none';
		$(elementId+'yellowbox').style.display='none';
}

function insertCard(destdiv, srcdiv, elementId, recursionLevel) {

		//if not inserting at the end of the holder
		if (destdiv != 'ERHolder') {

		//if nothing in this div just insert the srcdiv here
		if ($(destdiv).innerHTML.length<100) {	

		//if something is in this div already, then put the contents of this div in the srcdiv's left container and then insert the srcdiv here
		} else {
			$(srcdiv.replace("container", "left")).innerHTML=destdivCopy;
		}
		
	}
	insertCard2(destdiv,srcdiv,elementId);
}

function insertCard2(destdiv, srcdiv, elementId) {
	$(elementId).style.top=0;
	$(srcdiv.replace("container", "")).className='ERCard';
	
	//if inserting at the end of the holder
	if (destdiv=='ERHolder') {
		$('ERHolder').innerHTML = $('ERHolder').innerHTML + $(srcdiv).innerHTML;	
	} else {
 		$(destdiv).innerHTML = $(srcdiv).innerHTML;	
	}

	$(srcdiv).innerHTML=$('cardSpacerContainer').innerHTML;
	Effect.Shrink(srcdiv, { duration: 0.6 });

	setTimeout("insertCard3('"+srcdiv+"')",650);
	
	updateArrows('exact');
	updateNumbers('exact');
	
	isSwapping = false;
}

function insertCard3(srcdiv) {
		$(srcdiv).style.display='none';		
}

function insertSpacer(destdiv, srcdiv, elementId, recursionLevel) {
	destdivCopy = $(destdiv).innerHTML;
	$(destdiv).innerHTML = $(destdiv).innerHTML+"<div id=\""+destdiv+"spacer\" style=\"width:136px;float:left;display:none;\">&nbsp;</div>";
	Effect.Grow(destdiv+"spacer");
}
function RemindswapOfferSingle(elementId, position,matchType,OfferID, MerchID,desc,pageNum) {
	
	//Calculate desired action
	var srcPos=0;
	var srcIndex=0;
	var srcdiv = elementId+'container';	
	
	if (matchType=='related') {
		var prefix = 'RR';
		var i = 1;
		for (i=1; i<rr.length; i=i+1) {
			if (rr[i]==elementId) {
				srcIndex = i; 	
			}
		}		
		srcPos = srcIndex-rrFirstInView+1;
	}

	var destPos=srcPos;
	var destIndex=erFirstInView+destPos-1;
	if (($(er[destIndex]+'mask') && $(er[destIndex]+'mask').style.display=='block')||($(er[destIndex-1]+'mask') && $(er[destIndex-1]+'mask').style.display=='block')||($(er[destIndex+1]+'mask') && $(er[destIndex+1]+'mask').style.display=='block')) {
		eCardDeleting = true;
	} else {
		eCardDeleting = false;
	}
	
	//If another card is not moving up and the card above this is not being deleted, move this card up
	if (!isSwapping && !eCardDeleting) {

		isSwapping = true;

		//if there are no more exact matches above the card, put the card to the right of the last exact card
		if (destIndex > eTotal) {
			destIndex = eTotal+1;
			destdiv = 'ERHolder';
			//if there are 0 exact matches, put the card in the main ERHolder div
			if (eTotal == 0){
				destdiv = 'ERHolder';
			}
		}
		else {
			var destdiv = er[destIndex]+'left';
		}

		//Update arrays
		var erNew = new Array();
		var i = 1;
		var newLength = er.length+1;
		//if new array length is 1, make it 2
		if (newLength==1) {
			newLength=2;
		}		
		for (i=1; i<newLength; i=i+1) {
			if (i < destIndex) {
				erNew[i]=er[i];
			} else if (i == destIndex) {
				erNew[i]=elementId;
			} else if (i > destIndex) {
				erNew[i]=er[i-1];
			}
		}
		er = erNew;
		eTotal=eTotal+1;
			
		if (matchType=='related') {
			var rrNew = new Array();
			for (i=1; i<rr.length-1; i=i+1) {
				if (i < srcIndex) {
					rrNew[i]=rr[i];
				} else if (i >= srcIndex) {
					rrNew[i]=rr[i+1];
				}
			}
			rr = rrNew;
			rTotal=rTotal-1;
		}	
		
		$(elementId+'_CardYes').innerHTML='<img src="http://imgb.nxjimg.com/secured/image/PrefGame/Preferences09/exact_tl2_on.gif" alt="Like it">';

		add4More(matchType);	
		
		//Update database
		setTimeout("addReminder('"+elementId+"','"+MerchID+"','"+OfferID+"','"+desc+"')",100);
	
		if (destIndex < eTotal) {
			insertSpacer(destdiv,srcdiv,elementId, 1);
		}	
		
		//Update html
		setTimeout("moveCards('"+destdiv+"','"+srcdiv+"','"+elementId+"')",1000);
			
			
		//Animate
		setTimeout("slideUp('"+elementId+"','"+matchType+"')",500);

		updateAllNumbers();
	
	}
		
}

 function RemindswapOfferSingleHome(elementId, position,matchType,OfferID, MerchID,curMid1,curMid2,curMid3) {
	if (matchType == 'related')
	{ rMerchantIds[0] = curMid1;
	  rMerchantIds[1] = curMid2;
	  rMerchantIds[2] = curMid3;
	}
	else{
	  eMerchantIds[0] = curMid1;
	  eMerchantIds[1] = curMid2;
	  eMerchantIds[2] = curMid3;
	}

	if (eIsDeleting==false) {
		eCancelReload=true;
	}

	//Calculate desired action
	var srcPos=position;
	var srcIndex=0;
	var srcdiv = elementId+'container';

	var srcIndex=position;

	destPos = 0;
	var destdiv = 'ERCard_'+position+'container';

	if ( $('ERCard_'+1+'container').innerHTML.length < 4000  ) {
		destPos = 1;
	} else if ( $('ERCard_'+2+'container').innerHTML.length < 4000 ) {
		destPos = 2;
	} else if ( $('ERCard_'+3+'container').innerHTML.length < 4000 ) {
		destPos = 3;
	} else {
		destPos = srcPos;
	}


	eMerchantIds[destPos] = rMerchantIds[srcPos];

	//rMerchantIds[srcPos] = '';

	//Update database
	addReminder(elementId,MerchID,OfferID,'home',position);

	//Animate
	delta = srcPos+3-destPos; 
	var xDist = -469; //(-152*srcPos) - 13;


	var dur = (0.3*delta) + 0.4;

	new Effect.Move(elementId, { x: xDist, y: 0, mode: 'relative', duration: dur});

	//Update html
	setTimeout("finishMove('"+destdiv+"','"+srcdiv+"','"+matchType+"','"+elementId+"','"+srcIndex+"',"+position+")",(1000*dur));

}

function add4More(matchType,sortOrd) {
	
	//Add 4 more cards
	var startId = 0;
	if (matchType=='exact'){
		startId=eStartId;
		loadOfferList('ERHolder','exact',startId,sortOrd,'rightNoMove');
	}else if (matchType=='related'){
		startId=rStartId;	
		loadOfferList('RRHolder','related',startId,sortOrd,'rightNoMove');
	}
	
}

function moveCards(destdiv,srcdiv,elementId) {
	insertCard(destdiv,srcdiv,elementId, 1);		
}

function slideUp(elementId,matchType) {
		var yDist = -242;

		new Effect.Move(elementId, { x: 0, y: yDist, mode: 'relative', duration: 0.8 });

}

 function finishMove(destdiv,srcdiv,matchType,elementId,srcIndex,position) {

		eCancelReload = false; 
		destinationCard=destdiv.replace("container","");
		sourceCard=srcdiv.replace("container","");


		if (matchType=='related')
		{ destination = 'R_'+position;
		  source = 'S_'+position;
		  if ($(destination)){
			$(destination).innerHTML=$(source).innerHTML.replace(/RR/g,"ER").replace(/'related'/g,"'exact'");
			}
		  $(destinationCard).style.color=''; 
		  $(destinationCard).style.left ='0';
		  $(srcdiv).innerHTML =$('loadingCardR').innerHTML;
		}else
		{	destination = 'S_'+position;
			source = 'R_'+position;
			if ($(destination)){
			$(destination).innerHTML=$(source).innerHTML.replace(/ER/g,"RR");
			}
			$(destinationCard).style.color=''; 
		  	$(destinationCard).style.left ='';
			$(srcdiv).innerHTML =$('loadingCardS').innerHTML;
		}
				
		//function only used on home page
		setTimeout("add1More('"+matchType+"','"+sourceCard+"','"+srcIndex+"',false,"+position+",true,'move','home')",10);

 }

 function add1More(matchType,destdiv,index, fadeIn, pos, filterOffers,action,page) {
		
		if (matchType=='exact'){
			eStartId = eStartId+1;
			var startId = eStartId;
		}
		else {
			rStartId = rStartId+1;
			var startId = rStartId;
		}

		
		if (matchType=='exact'){
			er[index]='ERCard_'+pos;
		}
		else {
			rr[index]='RRCard_'+pos;
		}
		
		merchantList="0";
		if (matchType =='exact') {
			if (eMerchantIds[0]!= '') {
				merchantList=merchantList+","+eMerchantIds[0];
			}
			if (eMerchantIds[1]!= '') {
				merchantList=merchantList+","+eMerchantIds[1];
			}
			if (eMerchantIds[2]!= '') {
				merchantList=merchantList+","+eMerchantIds[2];
			}
		} else {
			if (rMerchantIds[0]!= '') {
				merchantList=merchantList+","+rMerchantIds[0];
			}
			if (rMerchantIds[1]!= '') {
				merchantList=merchantList+","+rMerchantIds[1];
			}
			if (rMerchantIds[2]!= '') {
				merchantList=merchantList+","+rMerchantIds[2];
			}
			
		}
		
		if (filterOffers && merchantList.length > 1) { 
			var url = '/personalizedwidget/get1more/matchtype/'+matchType+'/sort/'+1+'/elementId/'+destdiv+'/position/'+pos+'/merchantIdList/'+merchantList+'/page/'+page;
		}else { 
			var url = '/personalizedwidget/get1more/matchtype/'+matchType+'/sort/'+1+'/elementId/'+destdiv+'/position/'+pos+'/page/'+page;
		}

		if (action=='move')
			var myAjaxCG = new Ajax.Request(url,{method:'get', asynchronous: false,onSuccess:showSOContent});
		else
			var myAjaxCG = new Ajax.Request(url,{method:'get', asynchronous: false,onSuccess:showSOContentDelete});

}


function addReminder(elementId, merchid, offerid,page,positionid) {

	if(page != 'home'){
		updateRemindersNum('totReminders', 'add');
	}


var url = '/activereminderswidget/submitprefreminder';
	if(page =="home"){
		var myAjax = new Ajax.Request(url,{method:'get',asynchronous: false,
							parameters:{merchantID:merchid,offerID:offerid,uSource:'NPRF'},
							onComplete: addRemindSuccess(elementId,positionid)}); 					

	}else{ 
		var myAjax = new Ajax.Request(url,{method:'get',asynchronous: false,
							parameters:{merchantID:merchid,offerID:offerid,uSource:'NPRF'},
							onComplete:nothing});		
	}

}

function addRemindSuccess(elementId){

	 var corpic =  elementId+'_CardYes';

	 $(corpic).style.display = 'none';
	 var output = "<img src='http://imgb.nxjimg.com/secured/image/PrefGame/Preferences09/exact_tl2_on.gif'>";
	 $(corpic).innerHTML =output ;
	 $(corpic).style.display = 'block';
	 
}

function loadOfferList(elementId,matchType,pageNum,sortOrd,direction){	
 	  var startId = 1;
	  var total = 0;
	  if (direction=='left') {
	  	  if (matchType=='exact'){
			startId=eStartId-8;
		  }else if (matchType=='related'){
			startId=rStartId-8;	
		  } 
	  }   
	  else {
	  	  if (matchType=='exact'){
			startId=eStartId;
			eStartId=eStartId+4;
			total=eTotal;
		  }else if (matchType=='related'){
			startId=rStartId;
			rStartId=rStartId+4;	
			total=rTotal;
		   }
	  }

	  if ( total == -1 || startId <= total ) {
 
		  var pageNum=pageNum;
		  var paramsCG = 'elementId='+ elementId+'&matchtype='+matchType+'&pageNum='+ startId+'&sort='+sortOrd+'&type=offer&isV8SingleCard=true';
		  if(elementId == 'ERHolder'){ 
			  if (direction=='left')
			  	var myAjaxCG = new Ajax.Request('/personalizedwidget/personalizedview',{method:'post',parameters:paramsCG,onComplete:showOLContentLeft});
			  else if (direction=='right')
				  var myAjaxCG = new Ajax.Request('/personalizedwidget/personalizedview',{method:'post',parameters:paramsCG,onComplete:showOLContentRight});
			  else if (direction=='rightNoMove')
				  var myAjaxCG = new Ajax.Request('/personalizedwidget/personalizedview',{method:'post',parameters:paramsCG,onComplete:showOLContentRightNoMove});
			  else
				  var myAjaxCG = new Ajax.Request('/personalizedwidget/personalizedview',{method:'post',parameters:paramsCG,onComplete:showOLContentNone});
		  }else{
			  if (direction=='left')
			  	var myAjaxCG = new Ajax.Request('/personalizedwidget/shopgenieview',{method:'post',parameters:paramsCG,onComplete:showOLContentLeft});
			  else if (direction=='right')
				  var myAjaxCG = new Ajax.Request('/personalizedwidget/shopgenieview',{method:'post',parameters:paramsCG,onComplete:showOLContentRight});
			  else if (direction=='rightNoMove')
				  var myAjaxCG = new Ajax.Request('/personalizedwidget/shopgenieview',{method:'post',parameters:paramsCG,onComplete:showOLContentRightNoMove});
			  else
				  var myAjaxCG = new Ajax.Request('/personalizedwidget/shopgenieview',{method:'post',parameters:paramsCG,onComplete:showOLContentNone});
		  }
			
	  }else{
	  	waitforDelete(matchType);
	  }

}

function loadSingle(elementId,position,matchType,pageNum,OfferID)
{
 	if ($(elementId+'mask').style.display=='block') { 
 
	  var sortOrd=1;
	  var pageNum=pageNum;
	  var position=position;
	  var matchType=matchType;
	  var OfferID=OfferID;
	 
	} else {
	   setTimeout("undoDelete('"+elementId+"')",10);
	   setTimeout("undoDelete('"+elementId+"')",300);
	   setTimeout("undoDelete('"+elementId+"')",600);
	}
}

function finishDelete(elementId,position,matchType,origMatchType,pageNum,OfferID,merchid){

 	if ($(elementId+'mask') && $(elementId+'mask').style.display=='block') { 
 		
		$(elementId).innerHTML = "<div id=\""+elementId+"spacerDel\" style=\"width:136px;float:left;\">&nbsp;</div>";
		$(elementId).style.width='auto';
	    	Effect.Shrink(elementId+"spacerDel", { duration: 0.6 });

		var index=position;	
		
 		//update containing array
		if (matchType=='related') {
			var rrNew = new Array();
			for (i=1; i<rr.length-1; i=i+1) {
				if (i < index) {
					rrNew[i]=rr[i];
				} else if (i >= index) {
					rrNew[i]=rr[i+1];
				}
			}
			rr = rrNew;
			rTotal=rTotal-1;
		} else if (matchType=='exact') {
			if(pageNum != 'home'){
		 		updateRemindersNum('totReminders', 'remove');
		 	}
			var erNew = new Array();
			for (i=1; i<er.length-1; i=i+1) {
				if (i < index) {
					erNew[i]=er[i];
				} else if (i >= index) {
					erNew[i]=er[i+1];
				}
			}
			er = erNew;
			eTotal=eTotal-1;
		}
		if(pageNum =='home'){
			setTimeout("add1More('"+matchType+"','"+elementId+"','"+position+"',false,'"+position+"',true,null,'"+pageNum+"')",250);
		}else{
			var numDislike = parseInt($('numDislikedOffers').innerHTML);
			numDislike++;
			$('numDislikedOffers').update(numDislike);
		}
		
		var url = '/personalizedwidget/setdislike/merchantid/'+merchid+'/offerid/'+OfferID+'/matchtype/'+matchType;
		var myAjax = new Ajax.Request(url,{method:'get'});
		if (matchType == 'exact'){
			eIsDeleting=false;
		}else if(matchType == 'related'){
			rIsDeleting=false;
		}
		
	} else {
	   setTimeout("undoDelete('"+elementId+"')",10);
	   setTimeout("undoDelete('"+elementId+"')",300);
	   setTimeout("undoDelete('"+elementId+"')",600);
	}
}


function nothing (originalRequest){}

function failure (originalRequest) {
	isLoading=false;
	$('ERHolder').innerHTML=$('noReminderContainer').innerHTML;
}

function showOLContentLeft (originalRequest) {
	showOLContent (originalRequest, 'left'); 
}

function showOLContentRight (originalRequest) {
	showOLContent (originalRequest, 'right'); 
}

function showOLContentRightNoMove (originalRequest) {
	showOLContent (originalRequest, 'rightNoMove'); 
}
	
function showOLContentNone (originalRequest) {
	showOLContent (originalRequest, ''); 
}

function moveSlider(matchType, direction) {
	var divName='';
	var firstNum=-1;
	var TotalNum=-1;
	
	if (matchType=='related') {
		divName='RRHolder';
		TotalNum=rTotal;
	} else if (matchType=='exact') {				
		divName='ERHolder';
		TotalNum=eTotal;
	}
		
	if (direction=='right') {		
	    new Effect.Move(divName, { x: -540, y: 0, mode: 'relative' , duration: 1.0 });
    } else if (direction=='left') {
	    new Effect.Move(divName, { x: 540, y: 0, mode: 'relative' , duration: 1.0});
    } 	
	
	if (direction=='right') {		
		if (matchType == 'exact') {
			 //update last card in view
			erLastInView=erLastInView+4;
			erFirstInView=erFirstInView+4;
			firstNum=erFirstInView;
		}else if (matchType == 'related') {
			 //update last card in view
			rrLastInView=rrLastInView+4;
			rrFirstInView=rrFirstInView+4;
			firstNum=rrFirstInView;
		}
    } else if (direction=='left') {
		//update cards in view
		if (matchType == 'exact') { 
			erLastInView=erLastInView-4;
			erFirstInView=erFirstInView-4;
			firstNum=erFirstInView;
		}else if (matchType == 'related') {
			rrLastInView=rrLastInView-4;
			rrFirstInView=rrFirstInView-4;
			firstNum=rrFirstInView;
		}
    }
	
	var lastNum = firstNum+3;
	
	updateArrows(matchType);
	updateTotals(matchType);
	
	isScrolling = true;
	setTimeout("endScroll()",910);

	setTimeout("ensureCorrectPosition('"+matchType+"')",1410);
	
	if (firstNum > 20) {
		setTimeout("ensureCorrectPosition('"+matchType+"')",4010);
	}
	
	if (firstNum > 40) {
		setTimeout("ensureCorrectPosition('"+matchType+"')",8010);
	}

}

function endScroll () {
	isScrolling = false;
}

function ensureCorrectPosition (matchType) {
	if (isScrolling == false){
		if (matchType=='related') {
			divName='RRHolder';
			correctLeft = (rrFirstInView-1)*135*-1;
			$(divName).style.left = correctLeft+'px';
		} else if (matchType=='exact') {				
			divName='ERHolder';
			correctLeft = (erFirstInView-1)*135*-1;
			$(divName).style.left = correctLeft+'px';
		}

		updateNumbers(matchType);
	}
}

function showOLContent (originalRequest, direction) {
    	var arr = originalRequest.responseText.split("****");
	var divName = trim(arr[0]);
	var prefix = divName.replace("Holder", "" );
	var newData = arr[1];
	var firstNum =parseInt(arr[2]);
 	var lastNum  = parseInt(arr[3]);
	var TotalNum = parseInt(arr[4]);
	var NextPage = parseInt(arr[5])+1;
	var PrevPage = parseInt(arr[5])-1;
	var matchType = trim(arr[6]);
	var sort_ord =  1;
	var div_str =  divName;

	if (prefix == 'ER') {
		if (eTotal==-1)
			eTotal=TotalNum;
	}else if (prefix == 'RR') {
		if (rTotal==-1)
			rTotal=TotalNum;
	}
	
	if (firstNum > 1) {
		$(divName).innerHTML = $(divName).innerHTML + newData;
	} else {
		if (newData.length > 100) { 
			$(divName).innerHTML = newData;
		} else {
			if (prefix=='ER'){
				$(prefix+'Holder').innerHTML=$('noReminderContainer'+prefix).innerHTML;
			} else if (er.length>1) { 
				$(prefix+'Holder').innerHTML=$('noReminderContainer'+prefix).innerHTML;
			} else {
				$(prefix+'Holder').innerHTML='';
			}
		}
	}
	
	var numNewCards =  lastNum-firstNum+1;
	
	if (direction=='right' || direction=='rightNoMove' || direction=='') {
		if (prefix == 'ER') {
			//add 4 more cards
			 if (numNewCards>0)
		     er[er.length] = 'ERCard_'+firstNum;
			 if (numNewCards>1)
			 er[er.length] = 'ERCard_'+(firstNum+1);
			 if (numNewCards>2)
			 er[er.length] = 'ERCard_'+(firstNum+2);
			 if (numNewCards>3)
			 er[er.length] = 'ERCard_'+(firstNum+3);
		}else if (prefix == 'RR') {			
			//add 4 more cards
			 if (numNewCards>0)
		     rr[rr.length] = 'RRCard_'+firstNum;
			 if (numNewCards>1)
			 rr[rr.length] = 'RRCard_'+(firstNum+1);
			 if (numNewCards>2)
			 rr[rr.length] = 'RRCard_'+(firstNum+2);
			 if (numNewCards>3)
			 rr[rr.length] = 'RRCard_'+(firstNum+3);
		}
	}


	if (direction=='right') {		
		 updateNumbers(matchType);
	} else if (direction=='left') {

	} else if (direction=='rightNoMove') {
		if (prefix == 'ER') {
			 firstNum=erFirstInView;
			 lastNum=erLastInView;
		}else if (prefix == 'RR') {
			 firstNum=rrFirstInView;
			 lastNum=rrLastInView;
		}
		updateArrows(matchType);
		if(eIsDeleting || rIsDeleting){
			ID=window.setTimeout("waitforDelete('"+matchType+"');",10);
		}else{
			updateNumbers(matchType);
		}
	} else {	
		updateArrows(matchType);	
		updateNumbers(matchType);
	}

}

function waitforDelete(matchType){

	
	if(eIsDeleting){
		ID=window.setTimeout("waitforDelete('"+matchType+"');",10);
	}else if(rIsDeleting){
		ID=window.setTimeout("waitforDelete('"+matchType+"');",10);
	}else{
		updateNumbers(matchType);
	}
}

function updateArrows(matchType) {

	if (matchType=='related') {
		var divName='RRHolder';
		var TotalNum=rTotal;
	} else if (matchType=='exact') {				
		var divName='ERHolder';
		var TotalNum=eTotal;
	}

	
	if (matchType == 'exact') {
		var firstNum=erFirstInView;
		var lastNum=erLastInView;
	}else if (matchType == 'related') {
		var firstNum=rrFirstInView;
		var lastNum=rrLastInView;
	}

	 var sort_ord = 0;
	 
	 var NextPage = 0;
	 var PrevPage = 0;

	 if (TotalNum > lastNum)
	 {   
	 	  $(divName+'_Rscroll').style.display = 'none';
		  
		  var output = "<img  src='http://imga.nxjimg.com/secured/image/PrefGame/Preferences09/Scroll_R_off.gif' height='195' width='29' border='0' style='cursor:pointer;'";
			  output =output + " onclick='swapOfferList(\""+ divName + "\",\"" + matchType +"\","+ NextPage + ","+ sort_ord+",\"right\")'  onmouseover='on(this)' onmouseout='off(this)'/>";

		 	  $(divName+'_Rscroll').innerHTML = output ;
		
			  $(divName+'_Rscroll').style.display = 'block';
 
		 } 
		 else
		 {
		 		$(divName+'_Rscroll').style.display = 'none';

			  var output = "<img  src='http://imgb.nxjimg.com/secured/image/PrefGame/Preferences09/Pref_RightScroll_inactive.gif' height='195' width='29' border='0'/>";
		 	  $(divName+'_Rscroll').innerHTML = output ;
		   $(divName+'_Rscroll').style.display = 'block';
		  
	 }   
	 if (firstNum > 1)
	 {   
	 	  $(divName+'_Lscroll').style.display = 'none';
 
 	       var output = "<img  src='http://imgb.nxjimg.com/secured/image/PrefGame/Preferences09/Scroll_L_off.gif' height='195' width='29' border='0' style='cursor:pointer;'";
			  output =output + " onclick='swapOfferList(\""+ divName + "\",\"" + matchType +"\","+ PrevPage + ","+ sort_ord +",\"left\")'  onmouseover='on(this)' onmouseout='off(this)'/>";
		  
	 	  $(divName+'_Lscroll').innerHTML =output ;
		  $(divName+'_Lscroll').style.display = 'block';
 
	 } 
	 else
	 {
	  
			   $(divName+'_Lscroll').style.display = 'none';
	 	  var output = "<img  src='http://imga.nxjimg.com/secured/image/PrefGame/Preferences09/Pref_LeftScroll_inactive.gif' height='195' width='29' border='0'/>";
		 	  $(divName+'_Lscroll').innerHTML = output ;
		   $(divName+'_Lscroll').style.display = 'block';
 
	 } 

}

function updateAllNumbers(matchType) {
	updateNumbers('related');
	updateNumbers('exact');
}

function showSOContent (originalRequest) {

	var arr = originalRequest.responseText.split("****");
	var divName = trim(arr[0])+'container';
	var newData = arr[1];
	var firstNum =parseInt(arr[2]);
 	var lastNum  = parseInt(arr[3]);
	var TotalNum = parseInt(arr[4]);
	var NextPage = parseInt(arr[5])+1;
	var PrevPage = parseInt(arr[5])-1;
	var matchType = trim(arr[6]);
	
	
	$(divName).style.display = 'none';

    	$(divName).innerHTML = newData;
	Effect.Appear(divName);

	  var CounterdivName =  divName.split("_")[0]+"_ExCountEnd" ;
	$(CounterdivName).style.display = 'none';
    $(CounterdivName).innerHTML = firstNum +' to ' +  lastNum  +'&nbsp;of&nbsp;' + TotalNum;
	Effect.Appear(CounterdivName);

}
	
	
	

function trim(s) {
	return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
}
	

	var numRemSet = -100;
	var numMatches = -100;
	var numShopG = -100;
	var numRem = -100;
	
function starRating(e){

	var num = e.substring(e.length-1);
	var id = e.split("_",1);

	var i = 0;

	for (i = 1; i <= 5; i++)
	{

		$(id + "_" + i).src = 'http://imgb.nxjimg.com/emp_image/starrank/star_off.gif';
		if(i == 1){
			$(id + "_" + i).alt = "Boring";
			$(id + "_" + i).title = "Boring";
		}
		if(i == 2){
			$(id + "_" + i).alt = "Nothing Special";
			$(id + "_" + i).title = "Nothing Special";
		}
		if(i == 3){
			$(id + "_" + i).alt = "Not Bad";
			$(id + "_" + i).title = "Not Bad";
		}
		if(i == 4){
			$(id + "_" + i).alt = "Good Stuff";
			$(id + "_" + i).title = "Good Stuff";

		}
		if(i == 5){
			$(id + "_" + i).alt = "I'm Shopping";
			$(id + "_" + i).title = "I'm Shopping";
		}
	}

	for (i = 1; i <= 5; i++)
	{
		var OfferId = id + "_" + i;
		if(i<= num){
			$(id + "_" + i).src = 'http://imgb.nxjimg.com/emp_image/starrank/star_on.gif';
		}

	}

}

function starRetain(id,rank){
	var i = 0;
	for (i = 1; i <= 5; i++)
	{
		if(i<= rank){
			$(id + "_" + i).src = 'http://imga.nxjimg.com/Secured/image/CategoryHeader/star_on.gif';
		}
		else{
			$(id + "_" + i).src = 'http://imgb.nxjimg.com/Secured/image/CategoryHeader/star_off.gif';
		}
	}
}

function toggleSB(){
	name = 'SBdropdown';
	if ( SBClickOpen ) {
		$(name).style.display='none';
		SBClickOpen=false;
	} else {
		setTimeout("$('"+name+"').style.display='block';SBClickOpen=true;",10);
	}
}	

function SB1off(){
	if (!keepSB) {	
		$('SBdropdown').style.display='none';
		SBClickOpen = false;
	}
}

function setkeepSBTrue() {
	keepSB=true;
	setTimeout("keepSB=false;",500);
}
/////////////Start Mayor Tile////////////////////////
function prevTile(bgimg, img2, msg, url, id) {
	$('prevTileBtn').style.display = 'none';
	$('nextTileBtn').style.display = 'block';
	switchTileContent(bgimg, img2, msg, url, id);
}

function nextTile(bgimg, img2, msg, url, id) {
	$('prevTileBtn').style.display = 'block';
	$('nextTileBtn').style.display = 'none';
	switchTileContent(bgimg, img2, msg, url, id);
}

function switchTileContent(bgimg, img2, msg, url, id) {
	$('logoImage').src = bgimg;
	$('mayorBlueMsg').innerHTML = msg;
	$('mayorBlueMsg').href = url;
	$('mayorRedMsg').href = url;
	$('logoImageLink').href = url;
	$('merchantImageLink').href = url;
	$('merchantImage').src = img2;
}
/////////////End Mayor Tile//////////////////////////

/////////////Start Alternate Mayor Tile//////////////////////////
function alternateMayorTile(hideTile, showTile) {
  
	$(showTile).style.display = 'block';
	$(hideTile).style.display = 'none';
	
}
/////////////End Alternate Mayor Tile//////////////////////////

/* Mastercard_FeedbackwidgetController */
var vote = 1;

function submitFeedback(topic, isTrusted) {

	//clear the validtion msg
	
	$('email_validation_msg'+topic).innerHTML='';
	$('comment_validation_msg'+topic).innerHTML='';

	//following block of code commented out since we are not using checkbox on feedbackwidget anymore
	
	/*if(document.getElementById("send_To_CS").checked){
	    send_to_cs = 1;
	} else {
	    send_to_cs = 0;
	}
	*/
	send_to_cs = 0;
	var str_Text = $('str_Text'+topic).value;

	if(topic == 72)
	{
		saveComment(topic,"");
		return;
	}
    if(isTrusted==1)
    {

		saveComment(topic,"");

    }else{
     //email validation
		var str_email= $('fk_email'+topic).value;
		if(validate_email(str_email) && !str_Text =='' && !str_Text==' ')
		{
			saveComment(topic,str_email);
		}
		else
		{
			if(!validate_email(str_email))
			{
			    $('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;
	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;
						$('submitFeedback_msg'+topic).innerHTML ='';
						if(topic == 72 && newData.match(/Thanks for your input/)){
						  newData = '&nbsp;&nbsp;Thank you.';
						  $('str_Text'+topic).value = 'Enter another merchant name';
						}

						$('submitFeedback_mid'+topic).innerHTML = "<STRONG>"+"<br><br><br>"+newData+"</STRONG>";
					},
		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) {
	$('submitFeedback_msg'+topic).innerHTML = 'Sending Feedback...';
}

function closeBox(topic){
	divObj = $('submitFeedback'+topic);
	if(topic != 72 )
	  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 Feedback";
						},
			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 = 'Sending Feedback...';
	$('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 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){
													$('votepopup1nh').innerHTML = response;
												}else if (id==60){
													$('feedbackposition').innerHTML = response;
												}else if (id==61){
													$('feedbackposition61').innerHTML = response;
												}else if (id==3){
													$('feedbackfooter').innerHTML = response;
												}
												
												toggle_feedbackwidgetpopup(id);
											},'onTimeout':function(req){ alert('Timed Out!'); }} );
										    
     
     return;
     }
}
function toggle_feedbackwidgetpopup(id){
	$('feedback_ajaxloading'+id).style.display = "none";
	$('submitFeedback'+id).style.display = "block";
}

/* FtumessagingController */


/* mastercard_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://imgb.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);
    }
}

/* Mastercard_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';
	}
}

/* AlertwidgetController */
	function closeAlert(id){
		var divName = $(id);
		Effect.BlindUp(divName, { duration: 0.6 });
		var params = '';

          var myAjaxVote = new Ajax.Request('/alertwidget/hidealert',{method:'get',parameters:params});
		  setTimeout("showAlertMsg('home_alert_link')", 600);
	}
	function scrollToDiv(divName){
		new Effect.ScrollTo(divName);
	}
	function showAlertMsg(divName){
		if(divName == 'home_alert'){
			$('home_alert_link').style.display='none';
			Effect.BlindDown(divName, { duration: 0.6 });
			var params = '';

           var myAjaxVote = new Ajax.Request('/alertwidget/showalert',{method:'get',parameters:params});
		}
		else{
			$(divName).style.display='block';
		}
	}
	

/* Mastercard_HeaderController */
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);
}



/* pts ticker badge */
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').onclick =  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
    starAdvLightStars(); 
}
	

	
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').onclick = showBadgeOffers;
	}

		
}




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) == 'undefined' || $(divID) == null)
    return;
  if($(divID).style.display=='block'){
    $(divID).style.display='none';
  }
}

function bodyClick(){
	maincatnavoff();
  hide('accountdropdown');
  //hide('helpdropdown');
  hide('pointdropdown');
  if($('filterList') != 'undefined' && $('filterList') != null){
    hide('filterList');
  }
  if ($('ph_inactive_entries'))
  	hide('ph_inactive_entries');
  //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');
    }
    hide('org_dropdown');
    hide('category_dropdown');
}

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 keepmainnav = false;
var mlHoverOpen = false;
var mlClickOpen = false;

    var isOpeningMainNav = false;
    var openingMainNav = false;
var clickedMainNav = false;

//hideAllSubcats();

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){
		$(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).style.display=='block' || $(name).style.display=='' ) {
		$(name).style.display='none';
		if (name=='maincatdropdown') {
			mlClickOpen = false;
		}
	}
}

function dropdownMouseOverSubCat(e,num){
	blueAllSubcats();
	e.style.background='#ffffff';
	mlClickOpen=true;
	if($('subcatbox'+num)){
		toggleDivCat2('subcatbox'+num);
	}
	highlightMainRow(num);
}

function maincatnavoff(){
   	if (!keepmainnav) {
		hideAllSubcats();
		hidediv('maincatdropdown');
		mlHoverOpen = false;
		//$('BarDownArrow').src='http://imga.nxjimg.com/secured/image/09/nav/17_down_off.gif';
	}
}



function highlightMainRow (index) {
	$('maindropdownrow'+index).style.background='#feffff';
	$('maindropdownarrow'+index).addClassName("dropdown_arrow_icon_over");
}

function unhighlightMainRow (index) {
	$('maindropdownrow'+index).style.background='#eff6ff';
	$('maindropdownarrow'+index).removeClassName("dropdown_arrow_icon_over");
}

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 changeBarDownArrow() {
	if (mlHoverOpen || mlClickOpen) {
		$('BarDownArrow').src='http://imgb.nxjimg.com/secured/image/09/nav/dk_gray_17_down.gif';
	} else {
		$('BarDownArrow').src='http://imga.nxjimg.com/secured/image/09/nav/17_down_off.gif';
		//off($('BarDownArrow'));
	}

}

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 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(){}

/* Nav bar menu */
var expandMoreDropDown = function(){
    if($('headerMoreDropDownColumn').getStyle('width') == '171px'){
        new Effect.Morph('headerMoreDropDownColumn', {
            style: 'width:350px',
            duration: 0.1
        });
    }
    if(typeof(shrinkTimeout) != 'undefined') {
        window.clearTimeout(shrinkTimeout);
    }
}

var shrinkMoreDropDown = function(){
    if($('headerMoreDropDownColumn').getStyle('width') == '350px'){
    shrinkTimeout = window.setTimeout(function(){
        new Effect.Morph('headerMoreDropDownColumn', {
            style: 'width:171px',
            duration: 0.2
        });
    }, 1.0);
    }
}
var showMoreDropDown = function(){
    $('headerNavMoreDropDown').show();
}

var hideMoreDropDown = function(){
    $('headerNavMoreDropDown').hide();
}

var navBarImageChange = function(id, src){
    $(id).src  = src;
}



/* Mastercard_OverwhelmingofferController */
/* Bonus WOWPoints popup code */
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 highlightOn(id,loc){
    if($(id) !== undefined && $(id) !== null){
        $(id).style.backgroundPosition = "0 "+loc+"px";
    }
}

function highlightOff(id){
    if($(id) !== undefined && $(id) !== null){
        $(id).style.backgroundPosition = "0 0px";
    }
}
function closeBonusPopUpWithDelay(){
    if(!openPopup){
        $('bonusPopUp').style.display = 'none';
        openPopup = 1;
    }
}

function openBonusPopUpWithDelay(){
    if(openPopup){
        $('bonusPopUp').style.display = 'block';
        openPopup = 0;
    }
}
/* Start countdown code */

/**
 * Timer class for OO clock
 */
var OoTimer = Class.create({
	/**
	 * This is a constructor for the OO Timer class.
	 * @param {int} millisToLaunch The time (in milliseconds) left for OO to go live
	 */
	initialize: function(millisToLaunch) {
		this.millisToLaunch = millisToLaunch;
		this.handle = null;
		var generateId = function() {
			return OoTimer.id++;
		};
		var id = generateId();
		this.event = {
			start: "nxj:oo:clock:start:" + id,
			tick: "nxj:oo:clock:tick:" + id,
			drift: "nxj:oo:clock:drift:" + id,
			finish: "nxj:oo:clock:finish:" + id,
			stop: "nxj:oo:clock:stop:" + id
		};
		var self = this;
		document.observe(this.event.finish, function(event) {self.stop();});
	},
	/**
	 * Start the timer.
	 * Event fired - this.getEvents().start
	 */
	start: function() {
		if(this.handle === null) {
			var millisToLaunch = this.millisToLaunch;
			var amount = Math.floor(millisToLaunch/1000);
			var event = this.event;
			var hours = 0;
			var minutes = 0;
			var seconds = 0;
			var startTime = new Date().getTime();
			var drift = 0;
			var self = this;
			var tick = function() {
				hours = Math.floor(amount/3600);
				amount = amount%3600;
				if(hours < 10) {
					if(hours < 0) {
						hours = 0;
					}
					hours = '0' + hours;
				}
				
				minutes = Math.floor(amount/60);
				amount = amount%60;
				if(minutes < 10) {
					if(minutes < 0) {
						minutes = 0;
					}
					minutes = '0' + minutes;
				}
				
				seconds = Math.floor(amount);
				if(seconds < 10) {
					if(seconds < 0) {
						seconds = 0;
					}
					seconds = '0' + seconds;
				}

				millisToLaunch = millisToLaunch - 1000;
				amount = Math.floor(millisToLaunch/1000);
				drift = (new Date().getTime() - startTime) - (self.millisToLaunch - millisToLaunch);
				
				/* Fire event:drift */
				if(Math.abs(drift) > 500) {
					document.fire(event.drift, {amount: drift});
				} else {
				
					/* Fire event:tick */
					document.fire(event.tick, {secs: seconds, mins: minutes, hours: hours, days: 0});
					
					/* Fire event:finish when clock reaches zero */
					if(amount < 0) {
						document.fire(event.finish, {secs: seconds, mins: minutes, hours: hours, days: 0});
					} else {
						self.handle = setTimeout(tick, 1000 - drift);
					}
				}
			};
			this.handle = setTimeout(tick, 1000);
			document.fire(this.event.start);
		}
	},
	/**
	 * Restart the timer.
	 * Event fired - this.getEvents().start and this.getEvents().stop
	 */
	restart: function(millisToLaunch) {
		this.stop();
		if(millisToLaunch) {
			this.millisToLaunch = millisToLaunch;
		}
		this.start();
	},
	/**
	 * Stop the timer.
	 * Event fired - this.getEvents().stop
	 */
	stop: function() {
		if(this.handle !== null) {
			clearTimeout(this.handle);
			this.handle = null;
			document.fire(this.event.stop);
		}
	},
	/**
	 * Get all the supported events.
	 * @return {Object} The object {K1: V1, K2: V2} where K is the (short) event reference key and V is the acutal string event identifier
	 */
	getEvents: function() {
		return this.event;
	}
});
OoTimer.id = 0;

/**
 * Encapsulates and updates OO Clock DOM elements
 */
var OoClock = Class.create({
	/**
	 * This is a constructor for the OO Clock class.
	 * @param {Prototype.Element} secsElem The prototype HTMLElement representing seconds
	 * @param {Prototype.Element} minsElem The prototype HTMLElement representing minutes
	 * @param {Prototype.Element} hoursElem The prototype HTMLElement representing hours
	 * @param {Prototype.Element} daysElem The prototype HTMLElement representing days
	 * @param {string} updateEvent The string event identifier to observe for updating the DOM elements
	 */
	initialize: function(secsElem, minsElem, hoursElem, daysElem, updateEvent){
		this.secsElem = secsElem;
		this.minsElem = minsElem;
		this.hoursElem = hoursElem;
		this.daysElem = daysElem;
		var self = this;
		document.observe(updateEvent, function(event){self.update(event);});
	},
	/**
	 * Event handler to update all the DOM elements.
	 * @param {Prototype.Event} event The event fired to which the clock listens to update itself
	 */
	update: function(event) {
		var fields = event.memo;
		OoClock.updateField(this.secsElem, fields.secs);
		OoClock.updateField(this.minsElem, fields.mins);
		OoClock.updateField(this.hoursElem, fields.hours);
		OoClock.updateField(this.daysElem, fields.days);
	}
});
/**
 * Static helper to update the fields
 * @param {Prototype.Element} elem The prototype HTMLElement to be updated
 * @param {string} value The value to which the prototype HTMLElement is to be updated
 */
OoClock.updateField = function(elem, value) {
	if(elem) {
		elem.update(value);
	}
};

/**
 * Main OO clock.
 */
var MainClock = {
	/**
	 * Start the clock.
	 * @param {int} millisToLaunch The time (in milliseconds) left for OO to go live
	 * @param {int} userRank The userrank for the user
	 * @param {Function} triggerFunction (optional) The callback function which should be called when OO goes live
	 */
	start: function(millisToLaunch, userRank, triggerFunction) {
		var triggerFunc = triggerFunction == undefined ? triggerSwitch : triggerFunction;
		this.userRank = userRank;
		this.triggerFunc = triggerFunc;
		var self = this;
		
		if(this.commonClock) {
			this.commonClock.restart(millisToLaunch);
		} else {
			this.commonClock = new OoTimer(millisToLaunch);
			new OoClock($('left_seconds_allusers'), $('left_minutes_allusers'), $('left_hours_allusers'), $('left_days_allusers'), this.commonClock.getEvents().tick);
			document.observe(this.commonClock.getEvents().drift, function(event) {
				self.stop();
				self.refresh(currentOoId);
			});
			this.commonClock.start();
		}

		if(this.userClock) {
			this.userClock.restart(millisToLaunch + (userRank * -1000));
		} else {
			this.userClock = new OoTimer(millisToLaunch + (userRank * -1000));
			new OoClock($('left_seconds'), $('left_minutes'), $('left_hours'), $('left_days'), this.userClock.getEvents().tick);
			
			/* OO about to start warning - red flashing */
			var timerContainer = $('oo-current0-r-inner-time');
			if(timerContainer) {
				document.observe(this.userClock.getEvents().tick, function(event) {
					var fields = event.memo;
					if (fields.hours == 0 && fields.mins < 2) {
						if (fields.secs % 2 == 0) {
							timerContainer.setStyle({color: ''});
						} else {
							timerContainer.setStyle({color: '#FF0000'});
						}
					}
				});
			}
			
			/* OO is going live */
			document.observe(this.userClock.getEvents().finish, function(event) {
				showHide('oo_midState');
				showHide('oo-current-wrapper');
				triggerFunc('active');
			});
			this.userClock.start();
		}
	},
	/**
	 * Stop the clock.
	 */
	stop: function() {
		if(this.commonClock) {
			this.commonClock.stop();
		}
		if(this.userClock) {
			this.userClock.stop();
		}
	},
	/**
	 * Restart the clock with a fresh time.
	 */
	refresh: function(ooId) {
		var url = '/overwhelmingoffer/gettimetostart/';
		var params = 'ooId='+ooId;
		var self = this;
		var myAjax = new Ajax.Request(url, {
			method: 'post',
			parameters: params,
			onSuccess: function(e) {
				var response = e.responseText.evalJSON();
				if('millisToLive' in response) {
					var millisToLive = parseInt(response['millisToLive']);
					if(!isNaN(millisToLive)) {
						self.start(millisToLive, self.userRank, self.triggerFunction);
					}
				} else {
					/* Error - skip this */
				}
			}});
	}
};

/**
 * @Deprecated
 * Method to start clock.
 * Use MainClock.start instead
 */
function startClock(millisToLaunch, userRank, triggerFunction) {
	MainClock.start(millisToLaunch, userRank, triggerFunction);
}

/* End countdown code */

/* Start reservation process code */

var Captcha = {
	init: function(server, ooId, token) {
		this.token = token;
		this.src = new Template(server + '?ooid='+ ooId + '&token=#{token}');
		this.reloadSrc = new Template(server + '?ooid=' + ooId + '&token=#{token}&rand=#{rand}');
		this.reloadCount = 0;
	},
	setToken: function(token) {
		this.token = token;
	},
	load: function() {
		var self = this;
		if($('imgCaptcha')) {
			setTimeout(function() {$('imgCaptcha').src = self.src.evaluate({token: self.token});}, 10);
		}
	},
	reload: function() {
		this.reloadCount = this.reloadCount % 4 + 1;
		var self = this;
		if($('imgCaptcha')) {
			setTimeout(function() {$('imgCaptcha').src = self.reloadSrc.evaluate({token: self.token, rand: self.reloadCount});}, 10);
		}
	}
};

/* obsolete, replaced by loadCahcedPages */
function loadPartial( part,ooId,cachTime,forceActiveState ) {
    var d = new Date();
    var url = '/overwhelmingoffer/offer/ooId/'+ooId;
    var param = 'partial='+part+'&ooId='+ooId+'&cacheTime='+cachTime+'&forceActiveState='+forceActiveState+'&rand='+d.getMilliseconds();
    var result = new Ajax.Request(url, {method: 'post', parameters: param,
        onComplete: function( e ) {
            var rContent = e.responseText;
            if ( rContent != false && rContent != '' && rContent != 'invalid' ) {
                if ( part=='active' ) {
                    part_currentOffer = rContent;
                    part_currentOfferLoaded = true;
                } else if ( part=='active_fee' ) {
                    part_resFee = rContent;
                    part_resFeeLoaded = true;
                }
            }
        }
    } );
}

function loadCachedPages( ooId ) {
    var url = '/overwhelmingoffer/offer/ooId/'+ooId+'/cacheTime/15/exhaustive/1/forceActiveState/1';
    var result = new Ajax.Request(url, {method: 'get',
        onComplete: function( e ) {
           assignCachedPages( e );
        }
    } );
}
function assignCachedPages( response ) {
	var rContent = eval( "(" + response.responseText + ")" );
	Captcha.setToken(rContent['token']);
	if ( rContent['active_coming_soon'] != undefined && rContent['active_coming_soon'] != '' ) {
		part_currentOfferComingSoon = rContent['active_coming_soon'];
		part_currentOfferComingSoonLoaded = true;
	}
	if ( rContent['active'] != undefined && rContent['active'] != '' ) {
		part_currentOffer = rContent['active'];
		part_currentOfferLoaded = true;
	}
	if ( rContent['active_fee'] != undefined && rContent['active_fee'] != '' ) {
		part_resFee = rContent['active_fee'];
		part_resFeeLoaded = true;
	}
    if ( rContent['active_failed'] != undefined && rContent['active_failed'] != '' ) {
		part_resFailed = rContent['active_failed'];
		part_resFailedLoaded = true;
	}
	if( rContent['success_points_interstitial'] != undefined && rContent['success_points_interstitial'] != '' ) {
		part_resSuccessPoints = rContent['success_points_interstitial'];
		part_resSuccessPointsLoaded = true;
	}
}
function rejectReservation( id ) {
    var url = '/overwhelmingoffer/reject';
    var pars = 'ooId=' + id;
    var myAjax = new Ajax.Request( url, {
        method: 'post',
        parameters: pars,
        onComplete: function (e) {
           window.location = '/overwhelmingoffer/rejected';
        }
    } );
}

function placeReservation( id ) {
    var url = '/overwhelmingoffer/reservation';
    var captcha = document.getElementById('captcha').value;
    $('captchaError').style.display='none';
    $('captchaSuccess').style.display='none';
    $('captchaCopyError1').style.display='none';
    $('captchaCopyError2').style.display='none';
    $('captchaProccessing').style.display='block';
    var myAjax = new Ajax.Request( url, {
        method: 'post',
        parameters: {
            ooId:id,
            captcha:captcha,
            token:Captcha.token
        },
        onComplete: function (e) {
            var result = e.responseText.replace(/^\s+|\s+$/g,"");
            if( result == 'true' || result == '1' ) {
                $('captchaError').style.display='none';
                $('captchaCopyError1').style.display='none';
                $('captchaCopyError2').style.display='none';
                $('captchaProccessing').style.display='none';
                $('captchaSuccess').style.display='block';
                $('captcha').style.backgroundColor="#9FFFB3";
                showDialog();
                setTimeout(function(){checkReservation(id);}, 1000 * (30 + (Math.random()*15)));
            } else {
                $('captchaSuccess').style.display='none';
                $('captchaProccessing').style.display='none';
                $('captchaError').innerHTML = result;
                $('captchaError').style.display='block';
                $('captchaCopyError1').style.display='none';
                $('captchaCopyError2').style.display='none';
                $('captcha').style.backgroundColor="#FFAFB4";
            }
        }
    } );
}

function placeMayorReservation( id ) {
    var url = '/overwhelmingoffer/mayorreservation';
    $('captchaNoteForMayor').style.display='none';
    $('captchaProccessing').style.display='block';
    var myAjax = new Ajax.Request( url, {
        method: 'post',
        parameters: {
            ooId:id
        },
        onComplete: function (e) {
            var result = e.responseText.replace(/^\s+|\s+$/g,"");
            if( result == 'true' || result == '1' ) {
                $('captchaProccessing').style.display='none';
                $('captchaSuccess').style.display='block';
                showDialog();
                setTimeout(function(){checkReservation(id);}, 1000 * (30 + (Math.random()*15)));
            } else {
                $('captchaSuccess').style.display='none';
                $('captchaProccessing').style.display='none';
                $('captchaError').innerHTML = result;
                $('captchaError').style.display='block';
            }
        }
    } );
}

var attempts = 0;
function checkReservation( id ) {
    if (attempts >= 2) {
        showFailedPage(id);
    }
    var url = '/overwhelmingoffer/verify';
    var pars = 'ooId=' + id;

    var myAjax = new Ajax.Request( url, {
        method: 'post',
        parameters: pars,
        onComplete: function (e) {
            var result = e.responseText.replace(/^\s+|\s+$/g,"");
            if (result == '1') {
                showSuccessPage(id);
            } else if (result == '0')  {
                showFailedPage(id);
            } else {
                attempts++;
                setTimeout(function(){checkReservation(id);}, 1000 * (30 + (Math.random()*15)));
            }
        },
        timeout: 60000,
        onTimeout: function (e){
            setTimeout(function(){checkReservation(id);},1000 * (30 + (Math.random()*15)));
        }
    });
}

var pointAttempts = 0;
function checkPoints(id) {
	var url = '/overwhelmingoffer/verifyinstapoints';
    var pars = 'ooId=' + id;

	var myAjax = new Ajax.Request( url, {
        method: 'post',
        parameters: pars,
        onComplete: function (e) {
            var result = e.responseText.replace(/^\s+|\s+$/g,"");
            if (result == 'true') {
                window.location = '/overwhelmingoffer/success/ooId/'+id;
            } else if (result == 'false' && pointAttempts > 0)  {
                showTimeOutPage(id);
            } else {
                pointAttempts++;
                setTimeout(function(){checkPoints(id);}, 25337);
            }
        },
        timeout: 60000,
        onTimeout: function (e){
            showTimeOutPage(id);
        }
    });
}

function showSuccessPage(id) {
	if(typeof is_atoo != 'undefined' && is_atoo) {
		window.location = '/overwhelmingoffer/atsuccess/ooId/'+id;
	} else if ((part_resFeeLoaded && !part_resSuccessPointsLoaded) || !$('ooContentOutput')) {
		/* Not a WOWPoints OO or a Mega OO */
    	window.location = '/overwhelmingoffer/success/ooId/'+id;
    } else {
		if ( $('dialog_container') ) $('dialog_container').style.display = "none";
        if ( $('userfeedback_wrapper') ) $('userfeedback_wrapper').style.display = "none";
        if ( $('mNavContainer') ) $('mNavContainer').style.display = 'none';
    	$('ooContentOutput').innerHTML = part_resSuccessPoints;
        setTimeout(function(){checkPoints(id);}, 25337);
    }
}

function showFailedPage(id) {
    window.location = '/overwhelmingoffer/failed/ooid/' + id;
}

function showTimeOutPage(id) {
	if($('success_points_interstitial_text')) {
		$('success_points_interstitial_text').addClassName('oo-red');
		$('success_points_interstitial_text').innerHTML = 'Sorry! Taking too long to prepare your Instant WOWPoints.<br/>Please check back in 15 minutes. <a href="/overwhelmingoffer/index/uSource/OOSUC">Go to the OO Page</a>';
	}
	if($('success_points_interstitial_loading')) {
		$('success_points_interstitial_loading').style.display = 'none';
	}
}

function requestUserFailedData( id ) {
	var url = '/overwhelmingoffer/faileduser';
    var pars = 'ooId=' + id;

    var myAjax = new Ajax.Request( url, {
        method: 'post',
        parameters: pars,
        onComplete: function (e) {
            var rContent = eval( "(" + e.responseText + ")" );
            if ( rContent['content'] != undefined && rContent['content'] != '' && $('missedByContainer') ) {
            	$('missedByContainer').style.display = 'none';
                $('missedByContainer').innerHTML = rContent['content'];
                Effect.Appear('missedByContainer');
            }

        },
        timeout: 120000,
        onTimeout: function (e){
            setTimeout(function(){requestUserFailedData(id);},1000 * (5 + (Math.random()*4)));
        }
    });
}

function showDialog(prefix) {
	if(prefix == undefined) {
		prefix = '';
	}
    var dialog = document.getElementById(prefix + 'dialog_container');
    if ( $('page') ) {
        $('page').appendChild(dialog);
    }
    dialog.style.height = getFullPageHeightWithScroll()+"px";
    dialog.style.width = getFullPageWidthWithScroll()+"px";

    if(_isFireFox)
    {
        dialog.style.width = "100%";
    }

    document.getElementById(prefix + 'dialog_popup').style.top = (getScrollY()+300)+"px";
    document.getElementById(prefix + 'dialog_container').style.display = "block";

    window.onresize = function()
    {
        dialog.style.width = getFullPageWidthWithScroll()+"px";

        if(_isFireFox)
        {
            dialog.style.width = "100%";
        }
    }
}

/* End reservation process code */

function showHide(id) {
    if ($(id) == null) return;
    if($(id) != null) {
        if ($(id).style.display == 'none') {
            $(id).style.display = 'block';
        } else {
            $(id).style.display = 'none';
        }
    }
}

function showHideWithSlide(id) {
    if ($(id) == null) return;
    if($(id) != null) {
        if ($(id).style.display == 'none') {
        	Effect.SlideDown(id);
        } else {
            Effect.SlideUp(id);
        }
    }
}

function showHideTop(id) {
    if ($(id).style.display == 'none') {
        var adjustedTop = getTopOffset();
        $(id).style.top = adjustedTop+'px';
        $(id).style.display = 'block';
    } else {
        $(id).style.display = 'none';
    }
}

function submitOO_Dream()
{
    var value = $('oo_dream_str_Text').value;

    if(value.length > 2000)
    {
        value = value.substring(0, 1999);
    }

    value = value.replace(/^\s+|\s+$/g,"");

    if(value != '')
    {
        $('submitDreamFeedbackLink').innerHTML = 'Submitting...';

        value = value.replace(/\?/g, "qMark");
        value = value.replace(/#/g, "\#");
        value = value.replace(/\%/g, "percent");
        value = value.replace(/\</g, " lt ");
        value = value.replace(/\>/g, " gt ");
        value = value.replace(/\'/g, " ");

        var url = '/overwhelmingoffer/dream/';
        var pars = 'url=yahoodeals.nextjump.com&comment=' + value + '&topic=48';
        var myAjax = new Ajax.Request( url
            , {method: 'post', parameters: pars, onComplete: oo_showDreamResponse } );
    }
}

function oo_showDreamResponse( e )
{
    var result = e.responseText.replace(/^\s+|\s+$/g,"");

    if(result == 1)
    {
        $('submitDreamFeedbackLink').innerHTML = 'Thanks for your input!';
    }

    setTimeout("showHide('oo_submitDream')",1000);
}

function addRem(obj,merchid,prefix){
    if ( prefix == 'oow_alert' || prefix == 'poo_reminder_oo' ) {
        var params = 'remindId='+merchid+'&type=overwhelming&uSource=OOSP&rnd='+new Date().getTime();
    } else {
        obj.style.textDecoration = 'none';
        obj.innerHTML = 'Adding reminder...';
        obj.onlick = void(0);
        var params = 'remindId='+merchid+'&type=merchant&uSource=OOSP&rnd='+new Date().getTime();
    }
    var myAjaxRemind = new Ajax.Request('/overwhelmingoffer/reminder/',{
        method:'post',
        parameters:params,
        onComplete:function() {
            if ( $(prefix+'-on') && $(prefix+'-off') ) {
                $(prefix+'-on').style.display = 'none';
                $(prefix+'-off').style.display = 'block';
            }
            if ( prefix == 'oow_alert' ) {
                setTimeout("showHide('oow_alert');",2000);
                if ( $('poo_reminder_oo-on') && $('poo_reminder_oo-off') ) {
                    $('poo_reminder_oo-on').style.display = 'none';
                    $('poo_reminder_oo-off').style.display = 'block';
                }
            }
        }
    });
}

var _isFireFox = navigator.userAgent.match(/gecko/i);
var _isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
function getFullPageWidthWithScroll(){
    if (window.innerHeight && window.scrollMaxY) {
        xWithScroll = window.innerWidth + window.scrollMaxX;
    } else if (document.body.scrollHeight > document.body.offsetHeight){
        xWithScroll = document.body.scrollWidth;
    } else {
        xWithScroll = document.body.offsetWidth;
    }
    return xWithScroll;
}

function getFullPageHeightWithScroll(){
    if (window.innerHeight && window.scrollMaxY) {// Firefox
        yWithScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        yWithScroll = document.body.scrollHeight;
    } else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
        yWithScroll = document.body.offsetHeight;
    }
    return yWithScroll;
}

function getScrollY() {
    var scrOfY = 0;
    if( typeof( window.pageYOffset ) == 'number' ) {
      //Netscape compliant
      scrOfY = window.pageYOffset;
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
      //DOM compliant
      scrOfY = document.body.scrollTop;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
      //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    }
    return scrOfY;
}

function getTopOffset(){
    var scrOfY = 0;
    if( typeof( window.pageYOffset ) == 'number' ) {
        //Netscape compliant
        scrOfY = window.pageYOffset;
    } else if( document.body && document.body.scrollTop ) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
    } else if( document.documentElement && document.documentElement.scrollTop ) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
    }
    return scrOfY;
}

var prevOoId = 0; 
function showHideStats( ooId ) {
    if ( $('oostats-positioner') ) {
        if ( $('oostats-positioner').style.display == 'none' ) {
            getStats( ooId );
            var adjustedTop = getTopOffset();
            $('oostats-positioner').style.top = adjustedTop+'px';
            $('oostats-positioner').style.display = 'block';
        } else {
            $('oostats-positioner').style.display = 'none';
        }
    }
}
function getStats( ooId ) {
    if ( ooId != prevOoId ) {
        $('oostats-wrapper-ajax').innerHTML = '<img src="http://imgb.nxjimg.com/secured/image/f08/home/rightside/loading.gif" alt="loading" title="loading" style="vertical-align:middle;padding-left:36px" /> Loading...';
        var url = "/oostats/stats/";
        var rand = Math.floor(Math.random()*1000);
        new Ajax.Request(url, {
            method: 'get',
            parameters: {
                ajax: 'true',
                ooId: ooId,
                unique: rand
            },
            onComplete: function( e ){
                var arr = e.responseText.split("<!--****-->");
                prevOoId = ooId;
                var sliderContent = arr[1];
                $('oostats-wrapper-ajax').innerHTML = sliderContent;
            }
        });
    }
}
function dismissStats(ooId) {
    if(!readCookie('oo-stat-disp-'+ooId)) {
        createCookie('oo-stat-disp-'+ooId,'true',0.2); //expires after 5 hrs approx.
    }
    showHideStats(ooId);
}

function showHideSneakPeek( ) {
    sneakPeek(false);
}

var currentOoId;

function sneakPeek(signUp, prefix) {
    showHide( 'poo_sneakpeek_container' );
    if ( $('poo_sneakpeek_content') ) {
        if ( currentOoId != undefined ) { var ooId = currentOoId; }
        else { var ooId = ''; }
        $('poo_sneakpeek_content').innerHTML = '<img src="http://imgb.nxjimg.com/secured/image/f08/home/rightside/loading.gif" alt="loading" title="loading" style="vertical-align:middle;padding-left:36px" /> Loading...';
        var url = "/oosneakpeek/index";
        if (signUp) {
            url = url + '/signUp/optin';
            if($(prefix + 'off') && $(prefix + 'on')) {
                $(prefix + 'off').style.display = 'none';
                $(prefix + 'on').style.display = 'block';
            }
        }
        var rand = Math.floor(Math.random()*1000);
        new Ajax.Request(url, {
            method: 'post',
            parameters: {
                ooid: ooId ,
                unique: rand
            },
            onComplete: function( e ){
                var sneakPeekContent = e.responseText;
                $('poo_sneakpeek_content').innerHTML = sneakPeekContent;
            }
        });
    }
}

/* yummy cookie stuff */
function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return false;
}
function eraseCookie(name) {
    createCookie(name,"",-1);
}
function checkLightboxDisplay(name,days) {
    found = readCookie(name);
    if ( !found && $(name) ) {
        showHideTop(name);
        createCookie(name,"true",days);
        return true;
    } else {
        return false;
    }
}
function dismissElement(name,days) {
    createCookie(name,"true",days);
    if ( $(name) ) {
        $(name).style.display = "none";
    }
}
function checkElementDisplay(name) {
    found = readCookie(name);
    if ( !found && $(name) ) {
        $(name).style.display = "block";
    }
}


function checkSSWpointerDisplay(name){
    found = readCookie(name);
    var elem = document.getElementById('sswpointer');
    if ( !found && $(elem) ) {
        $(elem).style.display = "block";
       new Effect.Shake('sswpointer');
   }

}


function dismissSSWpointer(name,days) {
    createCookie(name,"true",days);
    var elem = document.getElementById('sswpointer');
    if ( $(elem) ) {
        $(elem).style.display = "none";
    }
}
/* facebook stuff */
function fbs_click() {
    u= location.href;
    t=document.title.substring(document.title.indexOf('-')+1);
    window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),
                'sharer',
                'toolbar=0,status=0,width=626,height=436'
                );
    return false;
}
function logFBShareClick(uBody) {
    var myAjax = new Ajax.Request('/facebookapp/fbshare/uBody/' + uBody + '/logRequired/1/',{method:'post'});
}
function logFBConnectClick(uBody) {
    var myAjax = new Ajax.Request('/facebookapp/fbconnect/uBody/' + uBody + '/logRequired/1/',{method:'post'});
}


function chooseOO1(offerId,cnt,num){
    var len = cnt
    var bb = document.getElementById(num+'_Checkbox').checked;

    for (i = 1; i < cnt; i++){
        document.getElementById(i+'_Checkbox').checked = false;
        document.getElementById(i+'_td').bgColor  = "#fff";
    }
    if(bb == true){
        document.getElementById(num+'_Checkbox').checked = true;
        document.getElementById(num+'_td').bgColor  = "#d8ffd7";
    }

    /*Save*/
    var myAjax = new Ajax.Request('/oospendsave/saveprefoo/',{method:'post',parameters: {offerId:offerId}});
}

function chooseOO(offerId,cnt,num){
    for (i = 1; i < cnt; i++){
        document.getElementById(i+'_td').innerHTML = '<img src="http://imga.nxjimg.com/emp_image/overwhelmingoffer/check_no.gif" width="35" height="35"></img>';
        document.getElementById(i+'_td').bgColor  = "#ffffff";
    }
    document.getElementById(num+'_td').innerHTML = '<img src="http://imgb.nxjimg.com/emp_image/overwhelmingoffer/check_yes.gif" width="35" height="35"></img>';
    document.getElementById(num+'_td').bgColor  = "#FFECD2";

    var myAjax = new Ajax.Request('/oospendsave/saveprefoo/',{method:'post',parameters: {offerId:offerId}});
}

function chooseOObanner(oomerchant,oodesc)
{
document.getElementById('chosenoo-info').innerHTML = 'You have selected ' + oomerchant +': '+oodesc;
document.getElementById('beforeoochoose').style.display  = "none";
document.getElementById('afteroochoose').style.display  = "block";
document.getElementById('pickOOImage').style.visibility  = "visible";

}

function scrollUpTo(divid) {
    new Effect.ScrollTo(divid);
    new Effect.Pulsate('chooseOObanner', {duration:2.0});
}

function   insertUser_frmFailed(){
    document.getElementById('insertUser').style.display  = "none";
    document.getElementById('insertUserLoading').style.display  = "block";
    var myAjax = new Ajax.Request('/oospendsave/insertnewuser/',{method:'post',onComplete:reDirect});
}

function reDirect(){
    window.location = '/overwhelmingoffer/index/uSource/SSW';
}

/* Disable copy and paste the captcha */
//not allow Right Click
function whichButton(event)
{
     if (event.button==2)//For right click
     {
      //alert("Right Click Not Allowed!");
       $('captchaCopyError1').style.display='block';
       $('captchaCopyError2').style.display='none';
       $('captchaError').style.display='none';
       return false;
     }
}

//dont allow Ctrl Key
function noCTRL(e)
{
 var code = (document.all) ? event.keyCode:e.which;
 var msg = "Sorry, this functionality is disabled.";
 if (parseInt(code)==17) // This is the Key code for CTRL key
     {
      //alert(msg);
       $('captchaCopyError1').style.display='none';
       $('captchaCopyError2').style.display='block';
       $('captchaError').style.display='none';
       return false;
     }
}

function toStmt() {
    window.location = '/oostatement/index';
}

/* Recommended for you */
function refreshRecommendations(uSource) {
	if($('oo-top-offers-mask')) {
		$('oo-top-offers-mask').style.display = 'block';
	}
	if($('oo-top-offers-mask-ie')) {
		$('oo-top-offers-mask-ie').style.display = 'block';
	}
	if($('oo-top-offers')) {
		var url = "/overwhelmingoffer/recommendations";
        var rand = Math.floor(Math.random()*1000);
        new Ajax.Request(url, {
            method: 'post',
            parameters: {
            	uSource: uSource,
                rand: rand
            },
            onComplete: function( e ){
                var recommendations = e.responseText;
                if($('oo-top-offers-mask')) {
					$('oo-top-offers-mask').style.display = 'none';
				}
				if($('oo-top-offers-mask-ie')) {
					$('oo-top-offers-mask-ie').style.display = 'none';
				}
                $('oo-top-offers').innerHTML = recommendations;
            }
        });
	}
}

/*Function to handle calendar entry - ubhatia*/
/*Reminder to self: Hard-fixed for google calendar right now, build on top of this, not around this*/

function getGoogleCalendarToken()
{
	$('google_auth_link').innerHTML = "Taking you to Google authentication page...";
	var ajaxAuthRequest = new Ajax.Request('/overwhelmingoffer/ical',
							{method:'post',
							onComplete:
									function (e) {
						            var result = e.responseText;
						            window.location = result;
						        }
							});
}
function getTopOffset(){
    var scrOfY = 0;
    if( typeof( window.pageYOffset ) == 'number' ) {
        //Netscape compliant
        scrOfY = window.pageYOffset;
    } else if( document.body && document.body.scrollTop ) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
    } else if( document.documentElement && document.documentElement.scrollTop ) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
    }
    return scrOfY;
}
function showCalWidget()
{
	showHideCalendarWidget();
}
function saveCalendar(calendarService)
{
	if(calendarService == 'Apple' || calendarService == 'Google' || calendarService == 'Outlook' || calendarService == 'Yahoo')
	{
		var url =  '/overwhelmingoffer/ical';
		if(calendarService == 'Outlook')
		{
			url =  '/overwhelmingoffer/geticsfile/usource/OOOCA?calendarService=Outlook';
			window.location = url;

		}
		else if(calendarService == 'Apple')
		{
			url =  '/overwhelmingoffer/geticsfile/usource/OOACA?calendarService=Apple';
			window.location = url;
		}
		else if(calendarService == 'Yahoo')
		{
			url =  '/overwhelmingoffer/ical/usource/OOYCA';
		}
		else if(calendarService == 'Google')
		{
			$('message').innerHTML = "<div class='big orange'>Taking you to Google Authentication page...</div>";
			$('message').style.display = 'none';
			Effect.Appear('message');
		}
		var param = 'calendarService='+calendarService;
		var ajaxAuthRequest = new Ajax.Request(url,
							{
							method:'post',
							parameters: param,
							onComplete:
									function (e) {
						            var result = e.responseText;
						            if(calendarService == 'Google')
						            {
						            	window.location.href = trim(result);
						            }
						            else if(calendarService == 'Yahoo')
						            {
						            	window.open(trim(result));

						            }
						        }
							});

		if(readCookie('oo_cal_messagetrue'))
		{
			eraseCookie('oo_cal_messagetrue');
		}
		if(readCookie('oo_cal_messagefalse'))
		{
			eraseCookie('oo_cal_messagefalse');
		}
	}
	else
	{
		$('message').innerHTML = "<div class='big orange'>Please choose a calendar first...</div>";
		$('message').style.display = 'none';
		Effect.Appear('message');
	}
}
function showFinalMessage(message,cookiePostFix)
{
		if(!readCookie('oo_cal_message'+cookiePostFix))
		{
			createCookie('oo_cal_message'+cookiePostFix,'true',1);
			$('calProcessMessage').style.display = 'block';
			$('calProcessMessage').innerHTML = message;
			showHideCalendarWidget();
		}
}
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}
function tag_and_redirect(type, url){
	if(type.indexOf("Share") > -1) {
		/* Do nothing */
	}
	if (url!=''){
		if (type != 'Share_Facebook')
			window.open(url);
		else
			window.open(url,'popup','width=626,height=436,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no');
	}
}


/* Trigger */

Effect.Counter = Class.create();
Object.extend(Object.extend(Effect.Counter.prototype, Effect.Base.prototype), {
	initialize: function(element, to, increment) {
		var options = arguments[2] || {};
		this.element = $(element);
		this.startNumber = parseInt(this.element.innerHTML);
		this.startNumber = isNaN(this.startNumber) ? 0 : this.startNumber;
		this.endNumber = to;
		this.delta = this.endNumber - this.startNumber;
		this.increment = increment;
		this.start(options);
	},
	update: function(position) {
		var newCount = parseInt(this.startNumber + this.delta * position);
		newCount = Math.min(newCount, this.endNumber);
		if((newCount - this.startNumber) % this.increment == 0 || newCount == this.endNumber) {
			/*if(newCount < 34) {
				this.element.style.color = '#333333';
			} else if(newCount < 68) {
				this.element.style.color = '#333333';
			} else {
				this.element.style.color = '#FFFFFF';
			}*/
			Element.update(this.element, newCount + '%');
		}
	}
});

var timeHandle = null;
var triggerPollHandle = null;
var streamPollHandle = null;
var queuePollHandle = null;
var queue = new Array();
var queueCounter = 0;
var alreadyDisplayed = new Object();
var imgCounter = 0;
var queueLength = 0;
var graceReloadsStream = 10;
var graceReloadsTriggerData = 10;

Event.observe(document, 'mousemove', function(event) {
    if (graceReloadsTriggerData <= 0) {
        graceReloadsTriggerData = 10;
		pollTriggerEngine(activeOfferId, 1);
        startPollingTriggerEngine(activeOfferId, defaultPingTime);
    } else if (graceReloadsTriggerData < 10) {
        graceReloadsTriggerData++;
    }

	if (graceReloadsStream <= 0) {
        // user is active on the page again. boot up reloads
        graceReloadsStream = 10;
		pollStream(activeOfferId, 1);
        startPollingStream(activeOfferId, checkInStreamPingTime);
    } else if (graceReloadsStream < 10) {
        // user is seeing reloads on the page and active, continue to reload
        graceReloadsStream++;
    }
});

function pollStream(ooId, noDecrement) {
	var d = new Date();
	var param = 'ooId='+ooId+'&rand='+d.getMilliseconds();
   	var url = '/overwhelmingoffer/getcheckinstream';
	var result = new Ajax.Request(url, {method: 'get', parameters: param,
        onComplete: function( e ) {
            var response = e.responseText;
            if ( response != false && response != '' && response != 'invalid' ) {
				var rContent = eval( "(" + response + ")" );
				if(rContent['checkInStream']) {
					var checkInStream = eval( "(" + rContent['checkInStream'] + ")" );
					moveDataToQueue(checkInStream);
				}
			}
		}
	});
	if(noDecrement != 1) {
		--graceReloadsStream;
		if(graceReloadsStream <= 0)
			stopPollingStream();
	}
}


function moveDataToQueue(checkIns) {
	queueLength = 0;
	for(var i=0 ; i < 20 ; ++i) {
		if(checkIns[i]) {
			if(i == 0 && queue[i] != null) {
				if(queue[i]['name'] != checkIns[i]['name'])
					queueCounter = 0;
			}
			queue[i] = checkIns[i];
			++queueLength;
		}
		else {
			queue[i] = null;
		}
	}
}

function pollQueue() {
	if(queue[queueCounter % queueLength]) {
		var item = queue[queueCounter % queueLength];
		if(alreadyDisplayed[item['name']] != 1) {
			if(item['profilepic'].match(/^\/emp_image\//)) {
				if(imgCounter % 2 == 0)
					item['profilepic'] = 'http://imga.nxjimg.com' + item['profilepic'];
				else
					item['profilepic'] = 'http://imgb.nxjimg.com' + item['profilepic'];
			}
			var template = '<div class="item" style="display:none;">								<div class="too-stream-profile-pic">									<img height="30" width="30" src="' +  item['profilepic'] +'" />								</div>								<div style="width:148px;white-space:nowrap;overflow:hidden;float:left;display:inline;"><span class="too-stream-name">';

			var loc = '';
			if(item['city'] != '' && item['city'] != 'unknown') {
				loc = loc + ' - ' + item['city'];
				if(item['state'] != '' && item['state'] != 'unknown')
					loc = loc + ', ' + item['state'];
			}
			//assuming the name font is 7px wide/char and the location is 5px wide/char
			var string = item['name'] + loc;
			if(item['name'].length * 7 > 148)
				template = template + item['name'].substr(0,22) + '...';
			else if(item['name'].length * 7 + loc.length * 5 + 6 > 148)
				template = template +  item['name'] + '</span><span style="color:#aaa;font-size:9px;">' + loc.substr(0,24-item['name'].length) + '...</span></div>';
			else
				template = template + item['name'] + '</span><span style="color:#aaa;font-size:9px;">' + loc + '</span></div>';

			template = template + '<br/><abbr class="too-stream-timestamp">' + item['checkintime'] + '</abbr></div>';


			if($('beFirst'))
				$('beFirst').remove();

			if ($('too-checkin-stream')) {
				$('too-checkin-stream').insert({'top':template});
				var children = $('too-checkin-stream').childElements();
				var maxlength = 4;
				if(isDisplayOOList == 1) {
					maxlength = 6;
				} 
				if(typeof(onHomePage) != 'undefined' && onHomePage == 1) {
					maxlength = 10;
				}
				if(children.length == 1*maxlength + 1) {
					//var lastChildsChildren = children[4].childElements();
					//var lastChildsName = lastChildsChildren[1].innerHTML;
					//delete alreadyDisplayed[lastChildsName];
					Effect.SlideUp(children[maxlength], {duration: 0.5});
					Effect.SlideDown(children[0], {duration: 1});
					children[maxlength].remove();
					alreadyDisplayed[item['name']] = 1;
				} else {
					Effect.SlideDown(children[0], {duration: 1});
					alreadyDisplayed[item['name']] = 1;
				}
			} else {
				stopPollingQueue();
			}
		}
		++queueCounter;
	}
}

function startUpdatingTimes(interval) {
	if ( timeHandle != null ) clearInterval(timeHandle);
	timeHandle = setInterval(function(){updateTimes();}, interval);
}

function stopUpdatingTimes() {
	if ( timeHandle != null ) clearInterval(timeHandle);
}

function startPollingStream(ooId, interval) {
	if ( streamPollHandle != null ) clearInterval(streamPollHandle);
	streamPollHandle = setInterval(function(){pollStream(ooId);}, interval);
}

function stopPollingStream() {
	if ( streamPollHandle != null ) clearInterval(streamPollHandle);
}

function startPollingQueue(interval) {
	if ( queuePollHandle != null ) clearInterval(queuePollHandle);
	queuePollHandle = setInterval(function(){pollQueue();}, interval);
}

function stopPollingQueue() {
	if ( queuePollHandle != null ) clearInterval(queuePollHandle);
}

function updateAndPulsateCounter(value) {
	return function() {
		if($('too-checkin-stats-count-number')) {
			Effect.Pulsate($('too-checkin-stats-count-number'),{pulses:1, duration:1.2});
			$('too-checkin-stats-count-number').innerHTML = value;
		}
	}
}



function formatNumber(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function pollTriggerEngine(ooId, noDecrement, pingInterval) {
	var d = new Date();
	var param = 'ooId='+ooId+'&rand='+d.getMilliseconds();
	if(isDisplayOOList == 1) {
		var url = '/overwhelmingoffer/getuntriggereddata';
	} else {
		var url = '/overwhelmingoffer/gettriggerdetails';
	}
	if(fieldList != null)
		param += '&fieldList='+fieldList;
	var result = new Ajax.Request(url, {method: 'get', parameters: param,
        onComplete: function( e ) {
            var response = e.responseText;
            if ( response != false && response != '' && response != 'invalid' ) {

            	renderSocElems($('too-trigger-container'));

				var rContent = eval( "(" + response + ")" );
				if(rContent['token']){
					Captcha.setToken(rContent['token']);
				}

				if(rContent['checkInCount'] != undefined && $('too-checkin-stats-count-number')) {
					var count = parseInt(rContent['checkInCount']);
					if(!isNaN(count)) {
						var currentCount = $('too-checkin-stats-count-number').innerHTML.replace(/\,/g,''); //take commas out!
						if(count > currentCount) {
							var numSteps = Math.floor(pingInterval/5000);
							var step = Math.floor((count - currentCount)/numSteps);
							var steps = [];
							var foos = [];
							for(var k=1 ; k < numSteps; ++k) {
								steps[k-1] = step * k + currentCount * 1; //just being paranoid here -- making sure that concatentation doesn't take place
								steps[k-1] = formatNumber(steps[k-1]);
								foos[k-1] = updateAndPulsateCounter(steps[k-1]);
								setTimeout(foos[k-1], (k-1)*5000);
							}
							var foo = updateAndPulsateCounter(rContent['checkInCountNF']);
							setTimeout(foo, pingInterval-5000);
						} else {
							updateAndPulsateCounter(rContent['checkInCountNF'])();
						}
						if(count == 1 && $('too-checkin-stats-count-text')) {
							$('too-checkin-stats-count-text').innerHTML = 'Check-in Today';
						} else {
							$('too-checkin-stats-count-text').innerHTML = 'Check-ins Today';
						}

						if(isDisplayOOList == 1) {
							updateListLockStatus(count);
						}
					}
				}
				if(rContent['checkInCountPercent'] != undefined) {
					var countPercent = parseFloat(rContent['checkInCountPercent']).toFixed(2);
					if(!isNaN(countPercent)) {
						/* Start the isOoTriggered check */
						if(countPercent > 0.9 && $('too-trigger-ci') && $('too-trigger-ci').innerHTML == 1) {
							fieldList = null;
						}
						updateCheckInBar(countPercent);
					}
				}
				if(rContent['isOoTriggered'] != undefined && rContent['isOoTriggered']) {
					if(rContent['isCheckedIn'] != undefined && !rContent['isCheckedIn'] && $('too-trigger-outer-container')) {

						/* Triggered but not checked in */
						$('too-trigger-outer-container').innerHTML = rContent['active'];

						/* Switch to a light poll */
						fieldList = 'checkInCount';

					} else if($('too-trigger-outer-container') && $('too-trigger-outer-container-next') && rContent['millisToLive'] != undefined) {

						//$('too-trigger-outer-container-next').innerHTML = rContent['active'];
						triggerSwitch('active_coming_soon');
						$('too-bonus-unlock-curtain').style.display = 'block';
						var millisToLaunch = parseInt(rContent['millisToLive']);
	                    if (millisToLaunch > 0 && $('oo-current0-r-inner-time')) {
							var userRank = rContent['advRank'] == undefined ? 0 : parseInt(rContent['advRank']);
							MainClock.start(millisToLaunch, userRank);
						}
						parseAndEvalJs($('too-trigger-outer-container-next'));

						/* Transition */
						if($('too-stack-1-container') && $('too-checkin-container')) {
						    if($('too-checkin-right-btm-arrow')) {
						        $('too-checkin-right-btm-arrow').setAttribute('class', 'too-frame-btm-right-2');
						    }

						    var flyHeightBonus = parseInt($('too-checkin-container').offsetHeight);
						    if(isNaN(flyHeightBonus)) {
						        flyHeightBonus = 356;
						    }
						    flyHeightBonus += 5;
						    var flyHeightCheckin = parseInt($('too-stack-1-container').offsetHeight);
						    if(isNaN(flyHeightCheckin)) {
						        flyHeightCheckin= 72;
						    }
						    flyHeightCheckin += 5;

						    new Effect.Parallel([
						            new Effect.Move('too-stack-1-container', {x:0, y:-flyHeightBonus, mode: 'relative', sync: true}),
						            new Effect.Move('too-checkin-container', {x:0, y:flyHeightCheckin, mode: 'relative', sync: true})
							], {duration: 1.5, afterFinish: function() {
					                    $('too-checkin-body-full').style.display = 'none';
						                $('too-checkin-body-empty').style.display = 'block';
						                new Effect.Parallel([
						                		new Effect.Morph('too-frame-mid-full-grey-id', {style: 'height:'+(flyHeightBonus-25)+'px;', sync: true}),
						                    	new Effect.Morph('too-checkin-body-empty', {style: 'padding-top:270px;', sync: true}),
						                    	new Effect.Morph('too-checkin-body-empty-mid', {style: 'height:'+(flyHeightCheckin-25)+'px;', sync: true}),
						                    	new Effect.Morph('too-trigger-outer-container-next', {style: 'height:477px;', sync: true}),
						                    	new Effect.Fade('too-trigger-outer-container', {sync: true}),
                        						new Effect.Appear('too-trigger-outer-container-next', {sync: true})
						                ], {duration: 2.5, afterFinish: function() {

						                			$('too-trigger-outer-container-next').style.height = 'auto';
													$('too-trigger-outer-container-next').style.position = 'relative';
													$('too-trigger-outer-container-next').style.overflow = 'visible';
													setTimeout(function(){
				                                        new Effect.Fade('too-bonus-unlock-curtain', {duration: 2.0});
				                                    }, 5333);
				                                    setTimeout(function(){
				                                        renderSocElems($('too-trigger-outer-container-next'));
				                                    }, 2000);
				                                	$('too-trigger-outer-container').innerHTML = '';
													adjustLoadingPartialHeight();
						                		}
					                    	}
			                    		);
						        	}
					            }
						    );
						}
					}
				}
            }
        }
    } );
	if(noDecrement != 1) {
		--graceReloadsTriggerData;
		if(graceReloadsTriggerData <= 0)
			stopPollingTriggerEngine();
	}
}

function startPollingTriggerEngine(ooId, interval) {
	if ( triggerPollHandle != null ) clearInterval(triggerPollHandle);
	triggerPollHandle = setInterval(function(){pollTriggerEngine(ooId, 1, interval);}, interval);
}

function stopPollingTriggerEngine() {
	if ( triggerPollHandle != null ) clearInterval(triggerPollHandle);
}

function checkIn(redirectTo) {

	/* Stop the polling engine */
	/*stopPollingTriggerEngine();*/

	var d = new Date();
    var url = '/overwhelmingoffer/checkin';
    var param = 'rand='+d.getMilliseconds();
    var result = new Ajax.Request(url, {method: 'post', parameters: param,
        onComplete: function( e ) {

        	/* Start the polling engine */
        	//startPollingTriggerEngine(ooId);

            var response = e.responseText;
			if ( response != false && response != '' && response != 'invalid' ) {
				if($('too-checkin-speech-bubble-checking-in')) {
					$('too-checkin-speech-bubble-checking-in').style.display = 'none';
				}
				if($('too-checkin-speech-bubble-checked-in')) {
					$('too-checkin-speech-bubble-checked-in').style.display = 'block';
				}
				setTimeout(function(){
					if(redirectTo) {
						window.location = redirectTo;
					} else if(typeof(onHomePage) != 'undefined' && onHomePage == 1) {
						window.location = '/overwhelmingoffer/home';
					} else {
						window.location = '/overwhelmingoffer/index';
					}
				}, 333);
            }
        }
    } );
}

function checkedIn() {
	if($('too-checkin-unlocked')) {
		Effect.Appear('too-checkin-unlocked');
	}
	if($('too-checkin-body-desc-content')) {
		$('too-checkin-body-desc-content').style.maxHeight = '96px';
	}
}

function updateCheckInBar(countPercent) {
	if($('too-checkin-stats-full-bar')) {
		var barWidth = parseInt($('too-checkin-stats-empty-bar').offsetWidth);
		if(!isNaN(barWidth)) {
			var originalWidth = parseInt($('too-checkin-stats-full-bar').style.width);
			var newWidth = parseInt(barWidth * countPercent);
			if(originalWidth != newWidth && !$('too-checkin-stats-bar-percent')) {
				new Effect.Morph('too-checkin-stats-full-bar', {style:'width:' + newWidth + 'px', duration:0.8});
			}
		}
	}
	if($('too-checkin-stats-bar-percent')) {
		var originalPercent = parseInt($('too-checkin-stats-bar-percent').innerHTML);
		originalPercent = isNaN(originalPercent) ? 0 : originalPercent;
		var newPercent = parseInt(Math.round(countPercent * 100));
		newPercent = isNaN(newPercent) ? 0 : newPercent;
		if(originalPercent != newPercent) {
			if($('too-checkin-stats-full-bar')) {
				new Effect.Parallel(
					[new Effect.Counter('too-checkin-stats-bar-percent', newPercent, 1),
					new Effect.Morph('too-checkin-stats-full-bar', {style:'width:' + newWidth + 'px'})],
					{duration:1}
					);
			} else {
				new Effect.Counter('too-checkin-stats-bar-percent', newPercent, 1);
			}

			/* Unlock the lock */
			if(newPercent == 100 && $('too-stack-1-header-lock-img-wrapper') && $('too-stack-1-header-lock-img')) {
				showHide('too-stack-1-header-lock-text');
				showHide('too-stack-1-header-lock-text-unlocked');
				$('too-stack-1-header-lock-img-wrapper').style.width = '41px';
				$('too-stack-1-header-lock-img').style.marginLeft = '-27px';
				Effect.Pulsate($('too-stack-1-header-lock-img'),{pulses:1, duration:0.8});
			}
		}
	}
}

function updateListLockStatus(checkinCount) {
	if($('too-list')) {
		var elems = $('too-list').select('.too_listing_row');
		var isHighlighted = false;
        var checkinThreshold = 0;
        var ooId = 0;
		elems.each(function(e) {
				checkinThreshold = parseInt(e.readAttribute('ct'));
				ooId = parseInt(e.id.replace('too_listing_row_', ''));
				if(!isNaN(ooId)) {
                    var catElem = $('too_listing_cat_' + ooId);
                    if(!isNaN(checkinThreshold)) {
                        if(checkinCount >= checkinThreshold) {
                            var stateWrapper = $('too_listing_quantity_wrapper_' + ooId);
                            var lockedElem = $('too_listing_qw_locked_' + ooId);
                            var unlockedElem = $('too_listing_qw_unlocked_' + ooId);
                            if(stateWrapper && lockedElem && unlockedElem) {
                                stateWrapper.addClassName('too_listing_qw_available');
                                unlockedElem.toggle();
                                lockedElem.remove();
                            }
                            if(!isHighlighted) {
                                catElem.addClassName('too_listing_unlock_highlight');
                                isHighlighted = true;
                            } else {
                                catElem.removeClassName('too_listing_unlock_highlight');
                            }
                        } else {
                            catElem.removeClassName('too_listing_unlock_highlight');
                        }
                    }
                }
			});
	} else {
		updateListStatus(checkinCount);
	}
}

function updateListStatus(checkinCount) {
	if ($('nooListings')) {
		var elems = $('nooListings').select('.nooListingRow');
		var checkinThreshold = 0;
        var ooId = 0;
        var isHighlighted = false;
        var prevElem = false;
		elems.each(function(e) {


			if (!prevElem) {
				prevElem = e;
			}
    		checkinThreshold = parseInt(e.readAttribute('ct'));
    		ooId = parseInt(e.id.replace('nooListingRow_', ''));
    		if(!isNaN(ooId)) {
    			if(!isNaN(checkinThreshold)) {
    				if(checkinCount >= checkinThreshold) {
    					if ( !isHighlighted ) {
    						if (prevElem.hasClassName('nooStatusLocked')) {
    							prevElem.removeClassName('nooStatusLocked');

        						if (!prevElem.hasClassName('nooStatusNext')) {
        							prevElem.addClassName('nooStatusNext');
        							isHighlighted = true;
        						}
    						}
    					}

    					e.removeClassName('nooStatusLocked');
    					e.removeClassName('nooStatusNext');

    					if (!e.hasClassName('nooStatusAvailable') && !e.hasClassName('nooStatusSoldOut')) {
    						e.addClassName('nooStatusAvailable');
    					}
    				}
    				prevElem = e;
    			}
    		}
		});
		if (prevElem && !isHighlighted) {
			if (prevElem.hasClassName('nooStatusLocked')) {
				prevElem.removeClassName('nooStatusLocked');

				if (!prevElem.hasClassName('nooStatusNext')) {
					prevElem.addClassName('nooStatusNext');
					isHighlighted = true;
				}
			}
		}
	}
}

function iAmTriggered(ooId) {
	var d = new Date();
	var url = '/overwhelmingoffer/iamtriggered';
	var param = 'ooId='+ooId+'&rand='+d.getMilliseconds();
	var result = new Ajax.Request(url, {
		method: 'post',
		parameters: param,
		onComplete: function( e ) {
		}
	});
	if($('mobile-only')) {
		setTimeout(function() {
			window.location.reload();
		}, Math.random() * 10000);
	}
}

function amIAlive() {
	var aliveHandle = setInterval(function(){
		var d = new Date();
		var url = '/overwhelmingoffer/amialive';
	    var param = 'rand='+d.getMilliseconds();
	    var result = new Ajax.Request(url, {method: 'post', parameters: param,
	        onComplete: function( e ) {
	            var response = e.responseText;
	            if ( response != false && response != '' && response != 'invalid' ) {
	            	var rContent = eval( "(" + response + ")" );
					if(!(rContent['amIAlive'] != undefined && rContent['amIAlive'])) {
						if(aliveHandle) {
							clearInterval(aliveHandle);
						}
						if($('sexpired_dialog_container')) {
							//$('sexipred_dialog_container').style.display = "block";
							showDialog('sexpired_');
						}
					}
	            }
	        }
	    });
    ;}, 720000);

}

var originalBodyBg = null;

function bonusOoUnlocked(isUnlocked) {
	/* originalBodyBg - inited in index */
	if(originalBodyBg == null) {
		originalBodyBg = getOriginalBodyBackground();
	}
	if(isUnlocked) {
		//document.body.style.background = 'url("http://imga.nxjimg.com/emp_image/overwhelmingoffer/trigger/bonus_oo_bg_1.jpg") no-repeat scroll center 0 transparent';
		document.body.style.backgroundColor = 'transparent';
		document.body.style.backgroundImage = 'url("http://imga.nxjimg.com/emp_image/overwhelmingoffer/trigger/bonus_oo_bg_1.jpg")';
		document.body.style.backgroundPosition = 'center 0';
		document.body.style.backgroundRepeat = 'no-repeat';
	} else {
		//document.body.style.background = originalBodyBg;
		restoreOriginalBodyBackground();
	}
}

function parseAndEvalJs(elem) {
	if(elem) {
		var scriptNodes = elem.getElementsBySelector('script');
		for(var i=0; i < scriptNodes.length; i++) {
			eval(scriptNodes[i].innerHTML);
		}
	}
}

function getOriginalBodyBackground() {
	return {'color': document.body.style.backgroundColor,
			'image': document.body.style.backgroundImage,
			'position': document.body.style.backgroundPosition,
			'repeat': document.body.style.backgroundRepeat};
}

function restoreOriginalBodyBackground() {
	document.body.style.backgroundColor = originalBodyBg['color'];
	document.body.style.backgroundImage = originalBodyBg['image'];
	document.body.style.backgroundPosition = originalBodyBg['psoition'];
	document.body.style.backgroundRepeat = originalBodyBg['repeat'];
}

function renderSocElems(elem) {
	renderFbLikeButton(elem);
	renderTwitterButton(elem);
}

function renderFbLikeButton(elem) {
	if(elem) {

		/* FB */
		FB.XFBML.parse(elem);

	}
}

function renderTwitterButton(elem) {
	if(elem) {
		elem.select('a.twitter-share-button').each(function(s)
		{
			var tweet_button = new twttr.TweetButton(s);
			tweet_button.render();
		});
	}
}

function addOoAlertReminder(elemPrefix){
	var params = 'remindId='+5933+'&act=save&type=Reminder&uSource=OOTOS&rnd='+new Date().getTime();
    new Ajax.Request('/overwhelmingoffer/reminder/',{
        method:'post',
        parameters:params,
        onComplete:function() {
        	var text = $(elemPrefix + '-text');
        	var img = $(elemPrefix + '-img');
			if(img) {
				img.removeAttribute('onmouseover');
				img.removeAttribute('onmouseout');
				on(img);
			}
			if(text) {
				text.innerHTML = 'Signed up for Alert';
			}
        }
    });
}

/* Adjust the height of the loading partial */
function adjustLoadingPartialHeight() {
	var container;
	if($('too-trigger-container')) {
		container = $('too-trigger-container');
	} else if($('atoo-container')) {
		container = $('atoo-container');
	}
	if(container && $('oo_midState') && $('oo_midState_inner')) {
		$('oo_midState').style.height = (container.offsetHeight - 120) + 'px';
		$('oo_midState_inner').style.marginTop = ((container.offsetHeight - 120) * 0.4) + 'px';
	}
}

/* END - Trigger OO */

/* START: All new header JS and multi OO tab management */

function changeTab(ooId) {
    if ( ooId != currentOoId )  {
        if ( clockHandle != null ) clearInterval(clockHandle);
        if ( clockHandleD != null ) clearInterval(clockHandleD);
        if ( triggerPollHandle != null ) clearInterval(triggerPollHandle);
        updateTabs( ooId );
        if ( $('oo_midState') ) showHide('oo_midState');
        if ( $('oo-current-wrapper') ) showHide('oo-current-wrapper');
        var d = new Date();
        var url = '/overwhelmingoffer/offer/ooId/'+ooId+'/fresh/'+d.getMilliseconds();
        var param = 'partial=active&ooId='+ooId+'&cacheTime=0&forceActiveState=0&exhaustive=1';
        var result = new Ajax.Request(url, {method: 'post', parameters: param,
            onComplete: function( e ) {
                var rContent = eval( "(" + e.responseText + ")" );
                if ( rContent['active'] != undefined && rContent['active'] != '' ) {
                    currentOoId = ooId;
                    $('ooCurrentOutput').innerHTML = rContent['active'];
                    if ( $('ooSpilloverOutput') && rContent['spillover'] != undefined && rContent['spillover'] != '' ) {
                        $('ooSpilloverOutput').innerHTML = rContent['spillover'];
                    }
                    part_currentOfferLoaded = false;
                    part_resFeeLoaded = false;
                    if ( $('oo-current0-r-inner-time') && rContent['millistolive'] != undefined ) {
                        var millisToLaunch = parseInt(rContent['millistolive']);
                        if ( millisToLaunch > 0 ) {
                            var userRank = rContent['advRank'] == undefined ? 0 : parseInt(rContent['advRank']);
                            MainClock.start(millisToLaunch, userRank);
                        }
                    }

                    /* Nifty way to find out if it's a Trigger OO */
					if ($('too-trigger-outer-container')) {
						parseAndEvalJs($('too-trigger-outer-container'));
                    	if ($('too-trigger-container')) {
							renderSocElems($('too-trigger-container'));
						}
                    } else {
                    	bonusOoUnlocked(false);
                    }

					/* Call for forced partials only if not the oolist page */
					if (typeof isDisplayOOList == 'undefined' || isDisplayOOList == 0) {
						loadCachedPages( currentOoId );
					}

					/* Is AT OO */
					if($('atoo-container')) {
						is_atoo = true;
					} else {
						is_atoo = false;
					}
                }
            }
        } );
    }
}

function updateTabs( ooId ) {
	var isFound = false;
    for ( i=0; i <= activeOOIds.length; i++ ) {
    	if(i == activeOOIds.length) {
    		if(adOoId && $('mnavItem_'+adOoId)) {
    			var activeOOid = adOoId;
    		} else if($('mnavItem_'+ooId)) {
    			var activeOOid = ooId;
    		} else {
    			break;
    		}
    	} else {
    		var activeOOid = activeOOIds[i];
    	}

        if ( $('mnavItem_'+activeOOid) ) {
            if ( activeOOid == ooId ) {
            	isFound = true;
                if ( !$('mnavItem_'+activeOOid).hasClassName('mnavItemSelected') )
                    $('mnavItem_'+activeOOid).addClassName('mnavItemSelected');
            } else {
                if ( $('mnavItem_'+activeOOid).hasClassName('mnavItemSelected') )
                    $('mnavItem_'+activeOOid).removeClassName('mnavItemSelected');
            }
        }
    }
}

function isOoTabVisible( ooId ) {
    var count = 1;
    for ( i=0; i < activeOOIds.length; i++ ) {
        var activeOOid = activeOOIds[i];
        if ( activeOOid == ooId ) {
            return ( count <= 5 );
        }
        count++;
    }
}

function slideToOO( ooId ) {
    var count = 0;
    var position = 0;
    for ( i=0; i < activeOOIds.length; i++ ) {
        var activeOOid = activeOOIds[i];
        if ( activeOOid == ooId ) {
            position = count;
            break;
        }
        count++;
    }
    var pos_from_end = activeOOIds.length - (position + 1);

    if ( pos_from_end < 5 ) {
        var pages = activeOOIds.length - 5;
    } else {
        var pages = position;
    }

    if ( pages > 0 ) {
        mnav_slider.slide( true,pages );
    }
}

function nxjSlider( prefix,windowCount ) {
    this.window_width = 0;
    this.window_count = windowCount;
    this.slider_count = 0;
    this.page_count = 0;
    this.curr_page = 1;
    this.leftlink_content = '';
    this.rightlink_content = '';
    this.leftlink_content_d = '';
    this.rightlink_content_d = '';
    this.leftlink_content_dd = '';
    this.rightlink_content_dd = '';
    this.slider = false;
    this.prefix = prefix;
    if ( $(this.prefix+'-slider') ) {
        this.slider = $(this.prefix+'-slider');
        this.sliderwindow = $(this.prefix+'-window');
        setTimeout(this.prefix+"_slider.init();",5);
    }
    this.init = function() {

        var notWhitespace = /\S/;
        for (var x = 0; x < this.slider.childNodes.length; x++) {
            var childNode = this.slider.childNodes[x];
            if ( (childNode.nodeType == 3) && (!notWhitespace.test(childNode.nodeValue)) ) {
              this.slider.removeChild(this.slider.childNodes[x]);
              x--;
            }
        }
        this.window_width = parseInt( this.sliderwindow.offsetWidth );
        this.slider_count = parseInt( this.slider.childNodes.length );

        this.page_count = Math.ceil( this.slider_count/this.window_count );

        this.slider.style.width = (this.page_count*this.window_width)+'px';
        this.slider.style.marginLeft = '0px';
        this.curr_page = 1;
        this.leftlink_content = $(this.prefix+'-leftarrow').innerHTML;
        this.rightlink_content = $(this.prefix+'-rightarrow').innerHTML;
        this.leftlink_content_d = $(this.prefix+'-leftarrow-disabled').innerHTML;
        this.rightlink_content_d = $(this.prefix+'-rightarrow-disabled').innerHTML;
        this.leftlink_content_dd = $(this.prefix+'-leftarrow-dead').innerHTML;
        this.rightlink_content_dd = $(this.prefix+'-rightarrow-dead').innerHTML;
        this.checkArrows();
    }
    this.checkArrows = function() {
        if ( this.curr_page <= 1 ) $(this.prefix+'-leftarrow').innerHTML = this.leftlink_content_dd;
        else $(this.prefix+'-leftarrow').innerHTML = this.leftlink_content;
        if ( this.curr_page >= this.page_count ) $(this.prefix+'-rightarrow').innerHTML = this.rightlink_content_dd;
        else $(this.prefix+'-rightarrow').innerHTML = this.rightlink_content;
    }
    this.slide = function( right,pages ) {
        var multiplier = 1;
        if ( pages != null ) multiplier = pages;
        var slide_amount = multiplier * this.window_width/this.window_count;

        if ( right ) {
            if ( this.curr_page > this.page_count ) return false;
            slide_amount = 0 - slide_amount;
            this.curr_page += multiplier;
        } else {
            if ( this.curr_page <= 1 ) return false;
            this.curr_page -= multiplier;
        }
        this.disableLinks();
        new Effect.Move(this.slider, { x: slide_amount, y: 0, mode: 'relative' });

        setTimeout(this.prefix+"_slider.checkArrows();",1000);
    }
    this.disableLinks = function() {
        $(this.prefix+'-leftarrow').innerHTML = this.leftlink_content_d;
        $(this.prefix+'-rightarrow').innerHTML = this.rightlink_content_d;
    }
    this.enableLinks = function() {
        $(this.prefix+'-leftarrow').innerHTML = this.leftlink_content;
        $(this.prefix+'-rightarrow').innerHTML = this.rightlink_content;
    }
    this.highlight = function( obj ) {
        if ( obj.style.backgroundColor == '' ) obj.style.backgroundColor = '#F8FDFF';
        else obj.style.backgroundColor = '';
    }
}

/* END: All new header JS and multi OO tab management */

/* OO tour */
var oot_is_pre_check_in = true;
var oot_acceptAnimRequests = true;
var oot_tourStarted = false;
var oot_currentPane = 0;
var oot_skipToPane = 0;

var oot_panes = new Array();
oot_panes[0] = 'too-checkin-body-container';


var oot_pane_loaded = new Array();
oot_pane_loaded[0] = true;


function oot_skipToNextPane(oot_nextpane){
    oot_skipToPane=oot_nextpane;
    oot2.oot2_skipToPane = oot_nextpane;
    oot_showNextPane();
}
function oot_showNextPane()
{
	if (oot_is_pre_check_in)
	{
		if (!oot_acceptAnimRequests || !oot_tourStarted)
			return;

		oot_acceptAnimRequests = false;

        if(oot_skipToPane > 0){
            var transitionToPane = oot_skipToPane;
            oot_skipToPane = 0;
         }else{
            var transitionToPane = (oot_currentPane+1);
         }

		function oot_showNextPaneHelper()
		{
			new Effect.Move(oot_panes[oot_currentPane], {x:-690, y:0, mode:'absolute', duration:1.0});
			new Effect.Move(oot_panes[transitionToPane], {x:0, y:0, mode:'absolute', duration:1.0});
			setTimeout('oot_currentPane='+transitionToPane+';oot_acceptAnimRequests=true;', 1000);
		}

		if (oot_pane_loaded[transitionToPane]){
			oot_showNextPaneHelper();
		}else{
			new Ajax.Request('/overwhelmingoffertourwidget/index',
								{method: 'post',
								parameters: {whichPane: transitionToPane},
								onSuccess: function (response)
									{
										$(oot_panes[transitionToPane]).innerHTML = response.responseText;
										oot_pane_loaded[transitionToPane] = true;
										oot_showNextPaneHelper();
									}
								});
        }
	}else{
		oot2.showNextPane();
    }
}

function oot_skipToPrevPane(oot_prevpane){
        oot_skipToPane=oot_prevpane;
        oot2.oot2_skipToPane = oot_prevpane;
        oot_showPrevPane();

}


function oot_showPrevPane()
{
	if (oot_is_pre_check_in){
		if (!oot_acceptAnimRequests || !oot_tourStarted)
			return;

		oot_acceptAnimRequests = false;
        if(oot_skipToPane > 0){
            var transitionToPane = oot_skipToPane;
            oot_skipToPane = 0;
         }else{
            var transitionToPane = (oot_currentPane==0)? oot_panes.length-1 : oot_currentPane-1;
         }



		function oot_showPrevPaneHelper(){
			new Effect.Move(oot_panes[oot_currentPane], {x:690, y:0, mode:'absolute', duration:1.0});
			new Effect.Move(oot_panes[transitionToPane], {x:0, y:0, mode:'absolute', duration:1.0});
			setTimeout('oot_currentPane='+transitionToPane+';oot_acceptAnimRequests=true;', 1000);
		}

		if (oot_pane_loaded[transitionToPane]){
			oot_showPrevPaneHelper();
		}else{
			new Ajax.Request('/overwhelmingoffertourwidget/index',
								{method: 'post',
								parameters: {whichPane: transitionToPane},
								onSuccess: function (response)
									{
										$(oot_panes[transitionToPane]).innerHTML = response.responseText;
										oot_pane_loaded[transitionToPane] = true;
										oot_showPrevPaneHelper();
									}
								});
        }
	}else{
		oot2.showPrevPane();
    }
}
function oot_startTour(){
    //Get # of panes to set dynamically from db.
    if (!oot_tourStarted){
        new Ajax.Request('/overwhelmingoffertourwidget/panescount',
                        {method: 'post',
                        parameters: {},
                        onSuccess: function (response){
                            $('oot-pane-container').innerHTML='';
                                oot_currentPane = 0;
                                oot_tourStarted = true;
                                var panescount = parseInt(response.responseText);
                                for (var i = 1; i <= panescount; i++){
                                    oot_panes[i] = 'oot-pane-'+i;
                                    oot_pane_loaded[i] = false;
                                    $('oot-pane-container').innerHTML+='<div class="oot-pane" id="oot-pane-'+i+'"></div>';
                            }
                             if (oot_currentPane == oot_panes.length-1){
                                oot_endTour();
                            }else{
                                oot_showNextPane();
                            }
                        }
                        });
                        
    }
    if (oot_currentPane == oot_panes.length-1){
        oot_endTour();
    }else{
        oot_showNextPane();
    }

}

function oot_endTour()
{
	if (oot_is_pre_check_in)
	{
		if (!oot_acceptAnimRequests || !oot_tourStarted)
			return;

		oot_acceptAnimRequests = false;

		$(oot_panes[0]).style.left = '690px';
		new Effect.Move(oot_panes[oot_currentPane], {x:-690, y:0, mode:'absolute', duration:1.0});
		new Effect.Move(oot_panes[0], {x:0, y:0, mode:'absolute', duration:1.0});
		setTimeout('oot_cleanup();', 1050);	// 50ms bump here so Effect.Move() & oot_cleanup() don't access oot_panes[oot_currentPane] simultaneously
	}
	else
		oot2.endTour();
}

function oot_cleanup()
{
	if (!oot_tourStarted)
		return;

	for (var i = 1; i <= oot_panes.length-1; i++){
		$(oot_panes[i]).style.left = '690px';
    }
	oot_currentPane = 0;
	oot_acceptAnimRequests = true;
	oot_tourStarted = false;
}

/* OO tour on OO list, single OO pages */
var oot2 =
{
	tour_started: false,
	current_pane: 1,
    paneslistcount:2,
    oot2_skipToPane:0,
	pane_loaded: new Array(),	// none of the 5 displayable panes are initially loaded

	resetPanes: function(){
		$('oot-pane-1').style.left = '0px';
		for (var i = 2; i <= 5; i++){
			$('oot-pane-'+i).style.left = '690px';
            $('oot-pane-'+i).style.display = 'none';
        }
		this.current_pane = 1;
        this.oot2_skipToPane=0;
	},

    startTour: function(){
        if (!this.tour_started){
            //if the panes are not created, get panes count
            if(!this.pane_loaded[1]){
            new Ajax.Request('/overwhelmingoffertourwidget/panescount',{
                        method: 'post',
                        parameters: {},
                        onSuccess: function (response){
                        //create the containers
                           oot2.paneslistcount = parseInt(response.responseText);
                           $('oot2-content').innerHTML = '<div class="oot-pane" id="oot-pane-1" style="left:0px;"></div>';
                            for (var i = 2; i <= oot2.paneslistcount; i++){
                                $('oot2-content').innerHTML += '<div class="oot-pane" id="oot-pane-'+i+'"></div>';
                            }
                             new Ajax.Request('/overwhelmingoffertourwidget/index',
                                    {method: 'post',
                                    parameters: {whichPane: 1},
                                    onSuccess: function(response)
                                        {
                                            $('oot-pane-1').innerHTML = response.responseText;
                                            oot2.pane_loaded[1] = true;
                                            startTourHelper();
                                        }
                                });
                        }
                    });

            }else{
            new Ajax.Request('/overwhelmingoffertourwidget/index',
                            {method: 'post',

                            parameters: {whichPane: 1},
                            onSuccess: function(response){
                                    $('oot-pane-1').innerHTML = response.responseText;
                                    oot2.pane_loaded[1] = true;
                                    startTourHelper();
                                }
                            });
            }
            oot_is_pre_check_in = false;
            if ($('oo-header-more-menu')){
                $('oo-header-more-menu').style.display = 'none';
            }
            if (this.tour_started){
                return;
            }else{
                this.tour_started = true;
            }
            function startTourHelper(){
                oot2.resetPanes();
                new Effect.Appear('oot-pane-1', { duration: 0.2 });
                new Effect.SlideDown('oot2-content-container');
                if ($('too-list-fm')){
                    new Effect.Move('too-list-fm', {y:225});
                }else{
                    setTimeout("new Effect.ScrollTo('oot2-content-container', {offset:-20});", 100);
                }
            }
        }else{
            oot2.showNextPane();
        }
	},

	endTour: function()
	{
		new Effect.SlideUp('oot2-content-container');
		if ($('too-list-fm'))
			new Effect.Move('too-list-fm', {y:-225});
		this.tour_started = false;
	},

	showNextPane: function()
	{
		var next_pane = this.current_pane+1;

		function showNextPaneHelper()
		{
			new Effect.Move('oot-pane-'+oot2.current_pane, {x:-690, y:0, mode:'absolute', duration:1.0});
			new Effect.Move('oot-pane-'+(++oot2.current_pane), {x:0, y:0, mode:'absolute', duration:1.0});
		}

		if (this.pane_loaded[next_pane])
			showNextPaneHelper();
		else
		{
			new Ajax.Request('/overwhelmingoffertourwidget/index',
								{method: 'post',
								parameters: {whichPane: next_pane},
								onSuccess: function(response)
									{
										$('oot-pane-'+next_pane).innerHTML = response.responseText;
										oot2.pane_loaded[next_pane] = true;
										showNextPaneHelper();
									}
							});
		}
	},

	showPrevPane: function()
	{
		var prev_pane = this.current_pane-1;

		function showPrevPaneHelper()
		{
			new Effect.Move('oot-pane-'+oot2.current_pane, {x:690, y:0, mode:'absolute', duration:1.0});
			new Effect.Move('oot-pane-'+(--oot2.current_pane), {x:0, y:0, mode:'absolute', duration:1.0});
		}

		if (this.pane_loaded[prev_pane])
			showPrevPaneHelper();
		else
		{
			new Ajax.Request('/overwhelmingoffertourwidget/index',
								{method: 'post',
								parameters: {whichPane: prev_pane},
								onSuccess: function(response)
									{
										$('oot-pane-'+prev_pane).innerHTML = response.responseText;
										oot2.pane_loaded[prev_pane] = true;
										showPrevPaneHelper();
									}
							});
		}
	}
}

function move(i) {
	return function() {
		var element = $('recent'+i).remove();
		element.style.display = 'none';
		$('items').appendChild(element);
	}
}

function shift() {
	var toShow = (i + showing) % count;
	Effect.SlideDown('recent'+toShow, {duration: 1});
	Effect.SlideUp('recent'+i, {duration: 1});
	var foo = function(i) {
		move(i);
	}
	setTimeout('foo()',1000);
	i = (i + 1) % count;
	setTimeout('shift()', delay);
}

/* OO email-a-friend widget */
var tef_savedHTML = new Array();
tef_savedHTML['editorDiv'] = '';
tef_savedHTML['emailsend_head'] = '';

function tef_saveHTML()
{
	tef_savedHTML['editorDiv'] = $('editorDiv').innerHTML;
	tef_savedHTML['emailsend_head'] = $('emailsend_head').innerHTML;
}

function tef_loadHTML()
{
	$('editorDiv').innerHTML = tef_savedHTML['editorDiv'];
	$('emailsend_head').innerHTML = tef_savedHTML['emailsend_head'];
	tef_savedHTML['editorDiv'] = '';
	tef_savedHTML['emailsend_head'] = '';
}

function toggle_editorform()
{
	if($('editor_submitform').style.display == 'none')
	{
		$('editor_submitform').style.display = 'block';
		Effect.ScrollTo('too-checkin-soc-container', {duration:1.0, offset:-80});
	}
	else
	{
		$('editor_submitform').style.display = 'none';
		$('offeremail_container').style.display = 'none';

		if (tef_savedHTML['editorDiv'] != '')
			tef_loadHTML();
	}
}

function ismaxlength(obj)
{
	var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : "";
	if (obj.getAttribute && obj.value.length>mlength)
		obj.value=obj.value.substring(0,mlength);
}

function showListLoad(divObj)
{
	$(divObj).innerHTML = '<div class="loading"><img src="http://imgb.nxjimg.com/secured/image/f08/home/rightside/loading.gif" alt="loading" title="loading"></div>';
}


function timeSince(unixTs) {
	var periods = [[60 * 60 * 24 * 365 , 'year'],[60 * 60 * 24 * 30 , 'month'],[60 * 60 * 24 * 7, 'week'],[60 * 60 * 24 , 'day'],[60 * 60 , 'hour'],[60 , 'minute'],[1 , 'second']];
	var today = Math.round(new Date().getTime() / 1000);
	var since = today - unixTs;
	for (var i = 0, j = periods.length; i < j; i++)
	{
		var count = '';
		var seconds = periods[i][0];
		var name = periods[i][1];
		if ((count = Math.floor(since / seconds)) != 0)
				break;
	}

	var output = (count == 1) ? '1 ' + name : count + ' ' + name + 's';
	output = output + ' ago';
	return output;
}

function updateTimes() {
	var times = document.getElementsByTagName('abbr');
	for(var i=0; i < times.length; ++i) {
		var time = times[i];
		time.innerHTML = timeSince(time.getAttribute('title'));
	}
}

function colorBonusOO(id, ooType) {
	var offerimg = 'offerimg-'+ id;
	var descr = 'descr-'+ id;
	var quantity = 'quantity-' + id;
	if(!document.getElementById(offerimg).style.background.match(/rollover\.gif/)) {
		document.getElementById(offerimg).style.background = 'url("http://imga.nxjimg.com/emp_image/overwhelmingoffer/trigger/oolist/rollover.gif") repeat-x scroll 0 0 transparent';
		document.getElementById(descr).style.background = 'url("http://imga.nxjimg.com/emp_image/overwhelmingoffer/trigger/oolist/rollover.gif") repeat-x scroll 0 0 transparent';
		document.getElementById(quantity).style.background = 'url("http://imga.nxjimg.com/emp_image/overwhelmingoffer/trigger/oolist/rollover.gif") repeat-x scroll 0 0 transparent';
	}
}

function uncolorBonusOO(id, ooType) {
	var offerimg = 'offerimg-'+ id;
	var descr = 'descr-'+ id;
	var quantity = 'quantity-' + id;
	if(document.getElementById(offerimg).style.background.match(/rollover\.gif/)) {
		document.getElementById(offerimg).style.background = '';
		document.getElementById(descr).style.background = '';
		document.getElementById(quantity).style.background = '';
		if(ooType) {
			if(ooType == 'exclusive') {
				document.getElementById(offerimg).style.backgroundColor = '#FFFCDE';
				document.getElementById(descr).style.backgroundColor = '#FFFCDE';
				document.getElementById(quantity).style.backgroundColor = '#FFFCDE';
			} else if(ooType == 'mega') {
				document.getElementById(offerimg).style.background = "url('http://imga.nxjimg.com/emp_image/overwhelmingoffer/trigger/oolist/23_stripe.gif') repeat-x";
				document.getElementById(descr).style.background = "url('http://imga.nxjimg.com/emp_image/overwhelmingoffer/trigger/oolist/23_stripe.gif') repeat-x";
				document.getElementById(quantity).style.background = "url('http://imga.nxjimg.com/emp_image/overwhelmingoffer/trigger/oolist/23_stripe.gif') repeat-x";
			}
		}
	}
}

function colorSpillover(id) {
	var spill = 'spillover-'+ id;
	if(document.getElementById(spill).style.background.match(/green_bg2\.gif/)) {
		document.getElementById(spill).style.background = '';
	}
}

function uncolorSpillover(id) {
	var spill = 'spillover-'+ id;
	if(!document.getElementById(spill).style.background.match(/green_bg2\.gif/)) {
		document.getElementById(spill).style.background = 'url("http://imgb.nxjimg.com/emp_image/overwhelmingoffer/trigger/green_bg2.gif") no-repeat scroll -20px 3px #EDFFE9';
	}
}

/* link a card */

function seccodeField(){
	var len = document.forms.cardRegistrationForm.length;
	for (var i = 0; i < len; i++){
		if (document.forms.cardRegistrationForm[i].checked){
			if(document.forms.cardRegistrationForm[i].id == "amexRadio"){
				document.getElementById("seccode").style.display = 'block';
				var k = 1;
			}else if (k != 1)  {
				document.getElementById("seccode").style.display = 'none';
			}
			if(document.forms.cardRegistrationForm[i].id == "paypalRadio") {
				//document.getElementById("paypalForm").style.display = 'block';
				document.getElementById("cardForm").style.display = 'none';
				var j = 1;
			} else if (j != 1) {
				//document.getElementById("paypalForm").style.display = 'none';
				document.getElementById("cardForm").style.display = 'block';
			}
		}
	}
}

function OpenAns(ans){
	var checkOpen = document.getElementById(ans).style.display;
	if(checkOpen == "none")
		document.getElementById(ans).style.display = "block";
	else
		document.getElementById(ans).style.display = "none";
}

function hideme(){
	document.getElementById("im").style.display = "none";
}

function IsNumeric(sText)
{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
   for (i = 0; i < sText.length && IsNumber == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsNumber = false;
         }
      }
   return IsNumber;
}

function numbersonly(myfield, e, dec)
{
var key;
var keychar;
if (window.event)
   key = window.event.keyCode;
else if (e)
   key = e.which;
else
   return true;
keychar = String.fromCharCode(key);

if(e==null){
    keychar=myfield.value;
    if(keychar && keychar.length > 1)
        return IsNumeric(keychar);
}

// control keys
if ((key==null) || (key==0) || (key==8) ||
    (key==9) || (key==13) || (key==27) )
   return true;

// numbers
else if ((("0123456789").indexOf(keychar) > -1))
   return true;

// decimal point jump
else if (dec && (keychar == "."))
   {
   myfield.form.elements[dec].focus();
   return false;
   }
else
   return false;
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function regCard(ooId){
	var cardholderName = document.forms.cardRegistrationForm.cardholderName.value;
	var cardNumber = document.forms.cardRegistrationForm.cardNumber.value;
	var cardExpiryYear = document.forms.cardRegistrationForm.cardExpiryYear.value;
	var cardExpiryMonth = document.forms.cardRegistrationForm.cardExpiryMonth.value;
	var billingZip = document.forms.cardRegistrationForm.billingZip.value;
	var cardType = getCheckedValue(document.forms.cardRegistrationForm.cardType);
	var cardSecurityCode = document.forms.cardRegistrationForm.cardSecurityCode.value;
	var good = true;
	if(cardholderName==""){
		document.getElementById("messagePanel").innerHTML = "The cardholder's name is required";
		document.getElementById("messagePanel").style.display = 'block';
		good = false; return;
	}
	if(cardNumber==""){
		document.getElementById("messagePanel").innerHTML = "The credit card number is required";
		document.getElementById("messagePanel").style.display = 'block';
		good = false; return;
	}else if(cardNumber!=""){
		if(!numbersonly(cardNumber,null)){
			document.getElementById("messagePanel").innerHTML = "The credit card number should be numeric";
			document.getElementById("messagePanel").style.display = 'block';
			good = false; return;
		}
	}
	if(cardExpiryYear==""){
		document.getElementById("messagePanel").innerHTML = "The card expiration year is required";
		document.getElementById("messagePanel").style.display = 'block';
		good = false; return;
	}
	if(cardExpiryMonth==""){
		document.getElementById("messagePanel").innerHTML = "The card expiration month is required";
		document.getElementById("messagePanel").style.display = 'block';
		good = false; return;
	}
	if(billingZip==""){
		document.getElementById("messagePanel").innerHTML = "The Zipcode is required";
		document.getElementById("messagePanel").style.display = 'block';
		good = false;
	}else if(billingZip!=""){
		if(!numbersonly(billingZip,null)){
			document.getElementById("messagePanel").innerHTML = "The Zipcode should be numeric";
			document.getElementById("messagePanel").style.display = 'block';
			good = false; return;
		}
	}
	if(cardType ==1 && cardSecurityCode==""){
		document.getElementById("messagePanel").innerHTML = "The card security code is required";
		document.getElementById("messagePanel").style.display = 'block';
		good = false; return;
	}

	if(good == true) {
		document.getElementById("messagePanel").innerHTML = "";
		document.getElementById("messagePanel").style.display = 'none';
		processPwp(ooId, 0, cardholderName, cardNumber, cardExpiryYear, cardExpiryMonth, billingZip, cardType, cardSecurityCode);
	}
}

function processPwp(ooId, isCardLinked, cardholderName, cardNumber, cardExpiryYear, cardExpiryMonth, billingZip, cardType, cardSecurityCode) {
	var datetime = new Date();
	var url = '/overwhelmingoffer/chargecardandpwp/ooId/'+ooId;
	if(!isCardLinked) {
		var params = {isCardLinked:isCardLinked,ooId:ooId,cardholderName:cardholderName,cardNumber:cardNumber,cardExpiryYear:cardExpiryYear,cardExpiryMonth:cardExpiryMonth,billingZip:billingZip,cardType:cardType,cardSecurityCode:cardSecurityCode,rand:datetime.getMilliseconds()};
	} else {
		var params = {isCardLinked:isCardLinked,ooId:ooId,rand:datetime.getMilliseconds()};
	}
	if($('atoo-is-second')) {
		params['second'] = '1';
	}
	var result = new Ajax.Request(url, {method: 'post', parameters: params,
		onLoading: function() {
			$('charge_card_content').innerHTML = '<div id="charge_card_interstitial_text">Processing your OO Purchase...</div><div id="charge_card_interstitial_loading"><img src="http://imga.nxjimg.com/emp_image/overwhelmingoffer/loading_green.gif" style="width:64px;height:64px;" /></div>';
	   	},
		onComplete: function(e) {
			var rContent = e.responseText;
			if ( rContent != false && rContent != '' && rContent != 'invalid' ) {
				$('inter_container').innerHTML = rContent;
			}
		}
	});
}


/* /link a card */



/* bonus_failed.phtml */
var checkin_oo_carousel =
{
	currentIndex: 0,
	numCheckinOOs: 0,
	
	getNumCheckinOOs: function()
	{
		this.numCheckinOOs = parseInt($('num_checkin_oos').innerHTML);
	},
	
	prev: function()
	{
		this.getNumCheckinOOs();
		
		if (this.currentIndex-2 >= 0 && this.currentIndex-2 < this.numCheckinOOs)
		{
			$('checkin_oo_'+this.currentIndex).style.display = 'none';
			this.currentIndex -= 2;
			$('checkin_oo_'+this.currentIndex).style.display = '';
			
			// hide/show next/prev links as appropriate
			this.showNextLink();
			if (this.currentIndex-2 >= 0)
				this.showPrevLink();
			else
				this.hidePrevLink();
		}
	},
	
	next: function()
	{
		this.getNumCheckinOOs();
		
		if (this.currentIndex+2 >= 0 && this.currentIndex+2 < this.numCheckinOOs)
		{
			$('checkin_oo_'+this.currentIndex).style.display = 'none';
			this.currentIndex += 2;
			$('checkin_oo_'+this.currentIndex).style.display = '';
			
			// hide/show next/prev links as appropriate
			this.showPrevLink();
			if (this.currentIndex+2 < this.numCheckinOOs)
				this.showNextLink();
			else
				this.hideNextLink();
		}
	},
	
	showPrevLink: function()
	{
		$('checkin_oo_nav_prev_active').style.display = '';
		$('checkin_oo_nav_prev_inactive').style.display = 'none';
	},
	
	hidePrevLink: function()
	{
		$('checkin_oo_nav_prev_active').style.display = 'none';
		$('checkin_oo_nav_prev_inactive').style.display = '';
	},
	
	showNextLink: function()
	{
		$('checkin_oo_nav_next_active').style.display = '';
		$('checkin_oo_nav_next_inactive').style.display = 'none';
	},
	
	hideNextLink: function()
	{
		$('checkin_oo_nav_next_active').style.display = 'none';
		$('checkin_oo_nav_next_inactive').style.display = '';
	}
};

    /*catlist bonus popup*/
    var openPopupList = 0;
    var timeoutidList = 0;
    function closeBonusPopUpList(id){
        openPopupList = 0;
        clearTimeout(timeoutidList);
        if(id){
            timeoutidList = setTimeout(closeBonusPopUpWithDelayList, 300);
        }else{
            timeoutidList = setTimeout(closeBonusPopUpWithDelayList, 1);
        }
    }
    
    function closeBonusPopUpWithDelayList(){
        if(!openPopupList){
            $('bonusPopUpList').style.display = 'none';
            openPopupList = 1;
        }
    }
	function processReminderRequest(mid,oid){
		var myAjax = new Ajax.Request('/oo/reminder/',{method:'post',onSuccess:showAddRemindSuccess});

	}

	function showAddRemindSuccess(originalRequest) {
		var returnVal= originalRequest.responseText;

		$('signup-text').style.display='none';
		$('signup-confirm').style.display='';
	}

	function trim(s) {
    	return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
	}
	
    function toggleOOLearnMore(id) {
        var divName = $(id);
        if(divName.style.display == 'none') {
            Effect.BlindDown(divName, { duration: 0.6 });
        } else {
            Effect.BlindUp(divName, { duration: 0.6 });
        }
    }
	

/* animation used in oo success */
var oosuccess = oosuccess || {};
(function(self) {
    self.count = function(start, end, duration, endAnimation) {
        var fps = 25,
            fpms = fps/1000,
            frames = duration * fpms,
            delta = (end - start)/frames,
            current = start,
            inter = setInterval(function() {
                frames--;
                if(frames < 0) {
                    clearInterval(inter);
                    setTicker(end);
                    if(endAnimation && typeof endAnimation == 'function') {
                        endAnimation();
                    }
                } else {
                    current+=delta;
                    setTicker(Math.round(current, 10));
                }
            }, 1000/fps);
        setTicker(start);
    };
    
    self.flash = function(count, duration) {
        var time = duration/count/2,
            i = 0;
            inter = setInterval(function() {
                i++;
                if(i > 2 * count) {
                    clearInterval(inter);
                } else {
                    self.setTickerActive(i%2 == 0);
                }
            }, time);
    };
    
    self.setTickerActive = function(active) {
        $('oo-points-win-amount').setStyle({
            backgroundColor: active ? '#F47321' : '#333'
        }); 
    };
    
    self.onload = function() {
        // provide click events
        $$('#editAdd').invoke('observe', 'click', function(event) {
            $('editing').className = 'editingAdd';
        });
        
        $$('#editCard').invoke('observe', 'click', function(event) {
            $('editing').className = 'editingCard';
        });
        
        $$('.editCancel').invoke('observe', 'click', function(event) {
            $('editing').className = '';
            $('regCC').hide();
        });
        
        $$('.linkAnotherCard').invoke('observe', 'click', function(event) {
            $('regCC').show();
        });
        
        $$('#ooWhyPopup a, .spendTakenBack').invoke('observe', 'click', function(event) {
            $('ooWhyPopup').toggle();
        });
        
        $$('#celebrateAgain').invoke('observe', 'click', function(event) {
            new Effect.Fade('celebrate');
            self.celebrate();
            setTimeout(function() {
                new Effect.Appear('celebrate');
            }, 3000);
        });
        
        $$('body').invoke('observe', 'click', function(event) {
            if(!event.findElement('.spendTakenBack, #ooWhyPopup')) {
                $('ooWhyPopup').hide();
            }
        });
        
        $$('body').invoke('observe', 'click', function(event) {
            var el = event.findElement('a.nxjGui');
            if(el) {
                el.blur();
                event.preventDefault();
            }
        });
        
        // update selects to look nice
        $$('select.nxjselect').each(nxjwidgets.styleSelect);
        
        $$('body').invoke('observe', 'click', function(event) {
            var el = event.findElement('.nxjSelectMain'),
                opened = el && !el.hasClassName('nxjSelectOpened');
            $$('.nxjSelectMain').invoke('removeClassName', 'nxjSelectOpened');
            if(opened) {
                el.addClassName('nxjSelectOpened');
            }
        });
    };
    
    self.celebrate = function() {
        function hide() {
            $('oo-success-gold-coins-left').hide(); 
            $('oo-success-gold-coins-right').hide();
        }
        function show() {
            $('oo-success-gold-coins-left').show();
            $('oo-success-gold-coins-right').show();
        }
        show();
        self.count(0, self.balance, 1500);
        //flashCounter('winner', userPoints, userPoints);
        setTimeout(hide, 1000);
        setTimeout(show, 2000);
    };
    
    function setTicker(value) {
        if (value<0 || value>99999) return; 
        for (var d=0; d<6; d++) {
            if (value > 0) {
                $('oo-points-digit-' + d).className = 'oo_points_digit oopd_' + (value % 10);
                value = Math.floor(value/10);
            } else {
                $('oo-points-digit-' + d).className = 'oo_points_digit oopd_x';
            }
        }
    }
}) (oosuccess);

/* nxj widgets - select */
var nxjwidgets = nxjwidgets || {};
(function(self) {
    self.nxjwidgets = self.styleSelect = function(e) {
        var options = e.select('option'),
            main = new Element('div', { 'class': 'nxjSelectMain' }),
            value = new Element('a', { 'class': 'nxjSelectValue nxjGui', 'href': '#' }),
            dropdown = new Element('div', { 'class': 'nxjSelectDrop' });
        
        for(var i=0; i<options.length; i++) {
            var val = options[i].value,
                text = options[i].getAttribute('data-html') || options[i].innerHTML,
                el = new Element('a', {
                    'class': 'nxjSelectOption nxjGui',
                    'data-value': val,
                    'data-text': text,
                    'href': '#'
                }).update(text);
            if(options[i].disabled) {
                el.addClassName('nxjSelectDisabled');
            }
            if(options[i].selected) {
                value.update(text);
            }
            dropdown.insert(el);
        }
        
        main.insert(value);
        main.insert(dropdown);
        
        dropdown.observe('click', function(event) {
            var option = event.findElement('.nxjSelectOption');
            if(option) {
                var newValue = option.getAttribute('data-value'),
                    newText = option.getAttribute('data-text'),
                    disabled = option.hasClassName('nxjSelectDisabled');
                if(!disabled) {
                    e.value = newValue;
                    value.update(newText);
                    main.removeClassName('nxjSelectOpened');
                }
                event.stop();
            }
        });
        
        e.hide();
        e.insert({ after: main });
    };
}) (nxjwidgets);
function overlayScreen() {
    var f = function() {
        $(document.body).appendChild($('tooCheckinOverlay'));
        $('tooCheckinOverlay').show();
        if(/MSIE 6/.exec(navigator.userAgent)) {
            ie6fixedposition();
        }
    }
    if(document.loaded) {
        f();
    } else {
        document.observe('dom:loaded', f);
    }
}
function ie6fixedposition() {
    // emulate {position: fixed, left: 0, top: 0, height: 100%, width: 100%} on ie6
    var $divs = $$('.fixed'),
        dv = document.viewport,
        fix = function() {
            var pos = document.viewport.getScrollOffsets(),
                p = {
                    left: (pos.left) + 'px',
                    top: (pos.top - 100) + 'px',
                    width: (dv.getWidth()) + 'px',
                    height: (dv.getHeight() + 200) + 'px'
                };
            $divs.invoke('setStyle', p);
        };
    Event.observe(window, 'scroll', fix);
    Event.observe(window, 'resize', fix);
    fix();
}

function addCommas(nStr){
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

/** Function for most popular home page widget**/
function toggleGender(g){
    $('mostPurchasedCon').setStyle('opacity:0.3');
    var myAjax = new Ajax.Request('/obsessions/mostshoppedwidget/gender/'+ g,
                {	method:'post'
                    ,onSuccess:function(e){
                        $('mostPurchasedCon').innerHTML = e.responseText;
                        $('mostPurchasedCon').setStyle('opacity:1.0');
                    }
                });
}

