// CHANGE LOG
// 4/21/09 - Rename showPopup to amexShowPopup

// Show the popup

// Use semaphore to prevent render popup to be called simultaneously
// See showPopup and renderPopup functions
var renderPopupSemaphore = false;
var switchCatSemaphore = false;

// Added for Phase 3 Ticket # 230
var showAll = false;

function amexShowPopup(url) {

    if ($("popup") == undefined)
    {
       return false;
    }
    
    if(renderPopupSemaphore == false)
    {
        renderPopupSemaphore = true;
        setTimeout('renderPopupSemaphore = false;',10000); // timeout to avoid deadlocking
        var popup = $("popup");
        if (popup != undefined)
        {
            if (popup.style.visibility == "visible")
            {
                switchPopup(url);
            }
            else
            {
                addHash(url, 'popup');
                dwr.engine._nextBatchId=0;
                URIIncludeService.include(url, renderPopup);
            }
        }
    }
    return false;
}

function switchPopup(url) {

    if ($("popup") == undefined)
    {
       return false;
    }
        
    addHash(url, 'popup');
    dwr.engine._nextBatchId=0;
    URIIncludeService.include(url, replacePopup);
    return false;
}

function switchBanner(url) {

    if ($("banner") == undefined)
    {
        return true;
    }
    dwr.engine._nextBatchId=1;
    URIIncludeService.include(url, renderBanner);
    return false;
}

function refreshRecentlyViewed(url) {
	dwr.engine._nextBatchId=2;
    URIIncludeService.include(url, renderRecentlyViewed);
    return false;
}

function getFormElementsAsQueryString(formId)
{
    var form = $(formId);
    var qs = "";
    for (i = 0; i < form.elements.length; i ++)
    {
        qs += form.elements[i].name + '=' + encodeURIComponent(form.elements[i].value);
        
        if (i != (form.elements.length -1))
        {
            qs += "&";
        }
    }
    return qs;
}

var replacePopup = function (content)
{
    $("popupContent").innerHTML = content;
}

var renderBanner = function (content)
{
    $("banner").innerHTML = content;
    displayRandomBanner();
}

function displayRandomBanner()
{
    // display a random banner
    if ($("categoryBanners") != undefined)
    {
        bannerCount = 0;
        
        for (i = 0; i < $("categoryBanners").childNodes.length; i++)
        {
            if ($("categoryBanners").childNodes[i].className == 'categoryBanner')
            {
                bannerCount ++;
            }
        }
        
        if (bannerCount > 0)
        {
        	displayBannerNum = randRange(1, bannerCount);
        	bannerId = 'banner-' + displayBannerNum;
        	$(bannerId).style.display='block';
    	}
	}
}

var renderRecentlyViewed = function (content)
{
    $("recentlyViewed").innerHTML = content;
}

function getYOffSet()
{
    var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body
    var dsoctop=document.all? iebody.scrollTop : pageYOffset
    return dsoctop;
}

var renderPopup = function (content)
{
    if (content != undefined) {
        var popup = $("popup");
        
        // change the position based on where the location/search bar is
        if ($('offers') != undefined)
        {
            var pos = findPos($("offers"));
           
            // add scroll offset
            var dsoctop = getYOffSet();
            
            if (dsoctop > 150)
            {  
                dsoctop = dsoctop - 100;
            }
            else
            {
                dsoctop = 0;
            }
            
            $('popupContent').style.top = (pos.top + dsoctop + 30) + "px";
            
            // shift to left for ie
            if ((/MSIE/.test(navigator.userAgent) && !window.opera))
            {
                $('popupContent').style.left = (pos.left) + "px";
            }

        }
        
        // Fade the background and show the popup
        popup.style.visibility = "visible";
        // Commented to fix Phase 3 Defect # 409
        //popup.style.height = document.body.offsetHeight + "px";
        popup.style.width = document.body.offsetWidth + "px";
        var popupContent = $("popupContent");
        // Commented to fix Phase 3 Defect # 409
        //$('darken').style.height = "100%";
        $('darken').style.height = document.body.offsetHeight + "px";
        // First, fade in the dark background
        // Now, fade in the content
        var darken = $("darken");
        if (darken.style.display != "none") {
            // fade out and in the content, no darkening
            new Effect.Fade(popupContent, {
                duration : 0.250,
                afterFinish : function() {
                    popupContent.innerHTML = content.innerHTML;
                    new Effect.Appear(popupContent, { duration : 0.250 });
                }
            });
        } else {
            // New popup, darken the BG
            new Effect.Appear(darken, {
                from: 0.0,
                to: 0.30,
                duration: 0.250,
                afterFinish : function() {
                    popupContent.innerHTML = content;
                    new Effect.Appear(popupContent, {duration: 0.250 });
                }
            });
        }
    
    // unblock semaphore
    renderPopupSemaphore = false; 
    }
    return false;
}

window.onscroll = onScroll;
var currentOffset = getYOffSet();
function onScroll()
{
    if ($('darken').style.display != "none")
    {
        // reposition offers layer if scrolling down
        if (currentOffset > getYOffSet())
        {
            var pos = findPos($("offers"));
            var dsoctop = getYOffSet();
            
            if (dsoctop > 150)
            {  
                dsoctop = dsoctop - 100;
            }
            else
            {
                dsoctop = 0;
            }
            
            $('popupContent').style.top = (pos.top + dsoctop + 30) + "px"; 
        }
        
        // Now re-render the darken area
        var darkenHeight = $('popupContent').clientHeight - 700;
        if (darkenHeight > 0)
        {
            darkenHeight = darkenHeight + 1100;
            if (darkenHeight < 1000) darkenHeight = 1100;
    
            $('darken').style.height = darkenHeight;
            new Effect.Appear($('darken'), {
                    from: 0.0,
                    to: 0.30,
                    duration: 0});
        }
    }
    
    currentOffset = getYOffSet();
}

function closePopup(newContent) {
    var popup = $("popup");
    if (popup.style.visibility == "visible")
    {
        var popupContent = $("popupContent");
        if (newContent == undefined) {
            new Effect.Fade(popupContent, {
                duration : 0.250,
                afterFinish : function() {
                    popupContent.innerHTML = "";
                    new Effect.Fade($("darken"), {
                        duration : 0.250,
                        afterFinish : function() {
                            $("popup").style.visibility = "hidden"; if ($('query') != null) $('query').value='';
                        }
                    });
                }
            });
            // Just hide and un-fade the background
        } else {
            new Effect.Appear($("darken"), {
                from: 0.0,
                to: 0.30,
                duration: 0.250,
                afterFinish : function() {
                    new Effect.Appear(popupContent, {duration: 0.250 });
                }
            });
            popupContent.innerHTML = newContent;
            // Change the popup, don't unfade the background
        }
    }
    return false;
}

function switchGrid(url)
{
        var p_element = $('offerGrid');
        if (p_element == undefined)
        {
            return true;
        }
        
        // Added for Phase 3 Ticket # 230
        if ($("showAll") == undefined )
        {
        	showAll = false;
        } 
        else 
        {
        	showAll = true;
        }
        if(showAll){
        	url = url+'&showAll=true'
        }
        addHash(url, 'grid');
        new Effect.Fade('scrollerArea', {
                    to:0.05, duration: 0.250,
                    afterFinish: function() {
        				  dwr.engine._nextBatchId=3;
                          URIIncludeService.include(url, renderScrollerArea);
                    }
                });

}

var renderScrollerArea = function(content)
{
    
    var p_element = $('offerGrid');
    p_element.innerHTML = content;
    appearGrid();
    switchCatSemaphore = false;
}

function fadeGrid()
{ 
    var p_element = $('offerGrid');
    new Effect.Fade('offerGrid');
}

function appearGrid()
{
    new Effect.Appear('scrollerArea', {
                duration: 0.250});
}

function getCategoryPathFromQueryString(queryString)
{
    queryString = queryString.substring(queryString.indexOf('categoryPath=') + 13);
    if (queryString.indexOf('&') >=0 )
    {
        queryString = queryString.substring(0,queryString.indexOf('&'));
    }
    return queryString;
}


// Body onload utility (supports multiple onload functions)
var gSafeOnload = new Array();
function SafeAddOnload(f)
{
	if (IEmac && IE4)  // IE 4.5 blows out on testing window.onload
	{
		window.onload = SafeOnload;
		gSafeOnload[gSafeOnload.length] = f;
	}
	else if  (window.onload)
	{
		if (window.onload != SafeOnload)
		{
			gSafeOnload[0] = window.onload;
			window.onload = SafeOnload;
		}		
		gSafeOnload[gSafeOnload.length] = f;
	}
	else
		window.onload = f;
}
function SafeOnload()
{
	for (var i=0;i<gSafeOnload.length;i++)
		gSafeOnload[i]();
}

function randRange(lowVal,highVal) {
     return Math.floor(Math.random()*(highVal-lowVal+1))+lowVal;
}

function addRecentlyViewedOffer(offerId, merchantName)
{

    if ($('recentlyViewed') != undefined)
    {
        var cookieVal = getCookie("rvo");
        
        if (cookieVal != null && cookieVal != '')
        {
            // add new cookie at the top
            newCookieVal = offerId + ":::" + merchantName;
           
            // add existing cookies
            var offers;
            if (cookieVal.indexOf("||") == -1)
            {
                offers = new Array(1);
                offers[0] = cookieVal;
            }
            else
            {
                offers = cookieVal.split("||");
            }
            offers = cookieVal.split("||");
            
            var maxOffers = 20;
            var offerCount = 0;
            for (i = 0 ; ((i < offers.length) && (offerCount < (maxOffers - 1))); i++)
            {
            
                offer = offers[i];
                if (offer.indexOf(offerId) == -1)
                {
                    offerData = offer.split(":::");
                    newCookieVal = newCookieVal + "||" + offerData[0] + ":::" + offerData[1];
                    offerCount ++;
                }
        
            }
            
            this.setCookie("rvo", newCookieVal, 0, "/", false);
        }
        else
        {
            // first time, craete the cookie
            cookieVal = offerId + ":::" + merchantName;
            this.setCookie("rvo", cookieVal, 0, "/", false);
        }
        
        refreshRVOList();
    }
}

function removeRecentlyViewedOffer(offerId)
{
    if ($('recentlyViewed') != undefined)
    {
        var cookieVal = getCookie("rvo");
        
        if (cookieVal != null)
        {
            newCookieVal = "";       
            // add existing cookies except the one to remove
            var offers;
            if (cookieVal.indexOf("||") == -1)
            {
                offers = new Array(1);
                offers[0] = cookieVal;
            }
            else
            {
                offers = cookieVal.split("||");
            }
            
            for (i = 0 ; i < offers.length; i++)
            {
            
                offer = offers[i];
                if (offer.indexOf(offerId) == -1)
                {
                    offerData = offer.split(":::");
                    if (newCookieVal != '')
                    {
                        newCookieVal = newCookieVal + "||";
                    }
                    newCookieVal = newCookieVal + offerData[0] + ":::" + offerData[1];
                   
                }
            }
            
            this.setCookie("rvo", newCookieVal, 0, "/", false);
        }
        
        refreshRVOList();
    }
}

function refreshRVOList()
{
    if ($('recentlyViewed') != undefined)
    {
        var cookieVal = getCookie("rvo");
        var rvoListHTML = "";
        if (cookieVal != undefined && cookieVal != '')
        {
            // enable see all link
            $('rvoSeeAll').style.display='block';
            // disable empty message
            $('rvoEmpty').style.display='none';
            
            if ($('emailIconImg') != undefined)
            {   
                $('emailIcon').style.display='block';
            }

            // add existing cookies
            offerCount = 0;
            
            var offers;
            if (cookieVal.indexOf("||") == -1)
            {
                offers = new Array(1);
                offers[0] = cookieVal;
            }
            else
            {
                offers = cookieVal.split("||");
            }
            
            for (i = 0 ; (i < offers.length); i++)
            {
               offerCount ++;
               offer = offers[i];
               offerData = offer.split(":::");
               offerId = offerData[0];
               merchantName = offerData[1];
               
               // generate the links, but only show 3
               if (i < 3)
               {
                   rvoListHTML = rvoListHTML + "<li>";
                   rvoListHTML = rvoListHTML + "<a href=\"javascript:void(0)\" onclick=\"" + viewOfferOnclick(offerId) + "\">";
                   rvoListHTML = rvoListHTML + merchantName;
                   rvoListHTML = rvoListHTML + "</a>";
                   rvoListHTML = rvoListHTML + "</li>"
               }
            }
            
            // update offer count
            $('rvCount').innerHTML=offerCount;      
        }
        else
        {
            $('rvCount').innerHTML=0;
            $('rvoSeeAll').style.display='none';
            $('rvoEmpty').style.display='block';
            if ($('emailIconImg') != undefined)
            {   
                $('emailIcon').style.display='none';
            }
        }
        
        $('rvoDetails').innerHTML = rvoListHTML;
    }
}

function getCookie(name) {
   var start = document.cookie.indexOf(name+"=");
   var len = start+name.length+1;
   if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
   if (start == -1) return null;
   var end = document.cookie.indexOf(";",len);
   if (end == -1) end = document.cookie.length;
   return unescape(document.cookie.substring(len,end));
}

function setCookie(name,value,expires,path,domain,secure) {
    var cookieString = name + "=" +escape(value) +
       ( (expires) ? ";expires=" + expires.toGMTString() : "") +
       ( (path) ? ";path=" + path : "") +
       ( (domain) ? ";domain=" + domain : "") +
       ( (secure) ? ";secure" : "");
    document.cookie = cookieString;
} 
