/*************************************************************
* Functions defined here must also be referenced in AdPod.html
* otherwise Internet Explorer cannot find the definition.
**************************************************************/
var iExplore = /msie/.test(navigator.userAgent.toLowerCase());
var ord;
	
	function setOrd()
	{
		var axel = Math.random() + "";
		ord = axel * 1000000000000000000; 
	}
	
	setOrd();
	
    function countClick(click)
    {
        var obj = document.getElementById('pixel');
		if (obj != null)
		{
			if(click != '%c')
			{
				if(obj.src) {
					obj.src = click;
	            }
			}
		}
    }
   
    function clickThru(click, DepartmentID, BrandName, ProductDescription, ProductCode, Quantity, DisplaySize, RegularPrice, CurrentPrice, SavingsAmount, SavingsStatement, AdCode, CreativeID){
		countClick(click);
		
        var QueryString = new String('');
        QueryString += buildQueryString('DepartmentID', DepartmentID);
        QueryString += '~';
        QueryString += buildQueryString('BrandName', BrandName);
        QueryString += '~';
        QueryString += buildQueryString('ProductDescription', ProductDescription);
        QueryString += '~';
        QueryString += buildQueryString('ProductCode', ProductCode);
        QueryString += '~';
        QueryString += buildQueryString('DisplaySize', DisplaySize);
        QueryString += '~';
        QueryString += buildQueryString('RegularPrice', RegularPrice);
        QueryString += '~';
        QueryString += buildQueryString('CurrentPrice', CurrentPrice);
        QueryString += '~';
        QueryString += buildQueryString('SavingsAmount', SavingsAmount);
        QueryString += '~';
        QueryString += buildQueryString('SavingsStatement', SavingsStatement);
        QueryString += '~';
        QueryString += buildQueryString('Quantity', Quantity);
        QueryString += '~';
        QueryString += buildQueryString('AdCode', AdCode);
		QueryString += '~';
        QueryString += buildQueryString('CreativeID', CreativeID);
        AddAdToShoppingList(QueryString);
    }
    //For testing only
    function clickThruTest(click, DepartmentID, BrandName, ProductDescription, ProductCode, Quantity, DisplaySize, RegularPrice, CurrentPrice, SavingsAmount, SavingsStatement, AdCode, CreativeID){
    		alert('Inside clickThruTest'); 
    		//countClick(click);
    		
            var QueryString = new String('');
            QueryString += buildQueryString('DepartmentID', DepartmentID);
            QueryString += '~';
            QueryString += buildQueryString('BrandName', BrandName);
            QueryString += '~';
            QueryString += buildQueryString('ProductDescription', ProductDescription);
            QueryString += '~';
            QueryString += buildQueryString('ProductCode', ProductCode);
            QueryString += '~';
            QueryString += buildQueryString('DisplaySize', DisplaySize);
            QueryString += '~';
            QueryString += buildQueryString('RegularPrice', RegularPrice);
            QueryString += '~';
            QueryString += buildQueryString('CurrentPrice', CurrentPrice);
            QueryString += '~';
            QueryString += buildQueryString('SavingsAmount', SavingsAmount);
            QueryString += '~';
            QueryString += buildQueryString('SavingsStatement', SavingsStatement);
            QueryString += '~';
            QueryString += buildQueryString('Quantity', Quantity);
            QueryString += '~';
            QueryString += buildQueryString('AdCode', AdCode);
    		QueryString += '~';
            QueryString += buildQueryString('CreativeID', CreativeID);
            alert(QueryString);
    }
   
    function buildQueryString(KeyWord, KeyValue){
        if (KeyValue != null){
          	KeyValue = new String(KeyValue); 
          	if(KeyWord != 'ProductDescription'){ // some product descriptions have '&amp;' which should not be replaced with '`'. 
				KeyValue = KeyValue.replace(/&/, '`'); 
			}
          	return KeyWord + '=' + KeyValue.toString();
        } else{
          return '';
        }
      }
      
    function recipeRedirect(click, recipeID){
        countClick(click);
        
        window.location.replace('http://'+window.location.hostname+'/Recipes/RecipeFull.aspx?recipeid=' + recipeID.toString());
    }

    function brickRedirect(click, offerCode, checkCode) {
        countClick(click);

        if (typeof (GSNContext) == 'object' && GSNContext != null) {
            var redirect = 'http://' + window.location.hostname + '/Ads/CouponsInc/BrickRedirect.aspx?';
            var pinCode = GSNContext.ConsumerID;

            redirect += 'o=' + encodeURIComponent(offerCode);
            redirect += '&c=' + encodeURIComponent(checkCode);
            redirect += '&p=' + encodeURIComponent(pinCode);

            window.open(redirect);
        }
    }
    
    function promotionRedirect(click, adCode){
        countClick(click);
        window.location.replace('http://'+window.location.hostname+'/Ads/Promotion.aspx?adcode=' + adCode.toString());
        
    }
        
    function verifyClickThru(click, url, target) {
    	if(target == undefined || target == '') {
    		target = "_top";
        }
    	countClick(click);
		if(target == "_blank") {
			// this is a link out to open in new window
			window.open(url);	
		} else {
        	// assume this is an internal redirect
        	window.location.replace('http://' + window.location.hostname + url); 
		}
    }

    function logAdImpression(adcode, creativeID, adRequest) {
        try {
            if (document.getElementById('ctl00_hfRequestVars') != null) {
                var displayUrl = document.location.href;
                var requestArgs = document.getElementById('ctl00_hfRequestVars').value;

                LogImpression(displayUrl, requestArgs, adcode, creativeID, adRequest, null, null);
            } else {
                var displayUrl = document.location.href;
                var request = '';
                if (document.getElementById('hfAdRequest')) {
                    var request = document.getElementById('hfAdRequest').value;
                }

                LogExternalAdImpression(document.URL, adcode, creativeID, request, null, null);
            }
        } catch (e) { }	
    }

    function logAdRequest(adRequest) {
        try {
            if (document.getElementById('ctl00_hfRequestVars') != null) {
                var displayUrl = document.location.href;
                var requestArgs = document.getElementById('ctl00_hfRequestVars').value;

                LogAdRequest(displayUrl, requestArgs, adRequest, null, null);
            }
        }
        catch (e) { }
    }

    function UpdateQuantCast() {
        
        try {
            var gsnConsumerID;

            if (typeof (GSNContext) == 'object') {
                gsnConsumerID = GSNContext.ConsumerID.toString();
            }
        
            _qoptions = {
                qacct: "p-1bL6rByav5EUo",
                media: "webpage",
                event: "refresh",
                labels: gsnConsumerID
            };

            quantserve();
        }
        catch (e) { }
    }

    function UpdateGoogle() {

        try {

            if (typeof (pageTracker) == 'object') {
                pageTracker._trackPageview();
            }

            if (typeof (globalPageTracker) == 'object') {
                globalPageTracker._trackPageview();
            }

            if (typeof (chainPageTracker) == 'object') {
                chainPageTracker._trackPageview();
            }
        } catch (e) { }
    }

    function refreshAdPods() {
        if (typeof (GSNServices) == 'object' && typeof (GSNServices.AdService) == 'object') {
            GSNServices.AdService.GetAdRequests(GSNContext.RequestArguments, RefreshAdPods, RefreshAdPods, 2);
        }
        else {
            RefreshAdPods(null);
        }
    }

    function autoRefreshAdPods() {
        if (typeof (GSNServices) == 'object' && typeof (GSNServices.AdService) == 'object') {
            GSNServices.AdService.GetAdRequests(GSNContext.RequestArguments, RefreshAdPods, RefreshAdPods, 3);
        }
        else {
            RefreshAdPods(null);
        }
    }

    function RefreshAdPods(response) {
        try {
            $$('.AdMaster').each(function(e) { ClearStyle(e); Purge(e); });

            var sideBar = $('sidebar');

            if (sideBar != null) {
                ClearStyle(sideBar);
            }
			
            setOrd();

            var externalAds = null;

            if (typeof (response) == 'object' && response != null && response.responseJSON != null) {
                externalAds = response.responseJSON.d;
            }

            if (externalAds != null) {
                for (var i = 0; i < externalAds.AdPods.length; i++) {
                    var adPod = externalAds.AdPods[i];
                    var tile = adPod.Tile;
                    var request = adPod.Request;

                    var iFrames = $$('iframe.adPodFrame' + tile);

                    if (iFrames != null) {
                        iFrames.each(
                            function(i) {
                                ClearStyle(i);
                                i.src = request;
                            });
                    }
                }
            }
            else {
                var iFrames = $$('iframe');

                if (iFrames != null) {
                    String.prototype.contains = function(t) { return this.indexOf(t) >= 0; }

                    for (var z = 0; z < iFrames.length; z++) {
                        var name = iFrames[z].className;

                        if (name.contains("adPod")) {
                            ClearStyle(iFrames[z]);
                            iFrames[z].src = iFrames[z].src.replace(/sourceid=\d;/i, '');
                        }
                    }
                }
            }
            
            UpdateQuantCast();
            UpdateGoogle();
        }
        catch (e) { }

    }

    function ClearStyle(iframe) {

        try {
            if (typeof(iframe.style) != 'undifined') {
                iframe.removeAttribute('style');
            }
        }
        catch (e) {
        }
    }

    function Purge(adPodDiv) {
        if (adPodDiv != null) {
            var childElements = adPodDiv.children;
            if (childElements != null) {
                for (var i = 0; i < childElements.length; i++) {
                    if (childElements[i].tagName.toLowerCase() != 'iframe' && !childElements[i].className.match('No-Remove')) {
                        adPodDiv.removeChild(childElements[i]);
                    }
                }
            }
        }
    }

    function addResizeHandler(iframe) {
        if (iExplore) {
            Event.observe(iframe, 'readystatechange', resizeIframe(iframe));
        }
        else {
            Event.observe(iframe, 'load', resizeIframe(iframe));
        }
    }

    function resizeIframe(frame) {
        try {
            if (frame == null) {
                return;
            }
        
            var innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;

            if (innerDoc == null) {
                return;
            }
            
            var ad = innerDoc.getElementById("ad");
            var height = innerDoc.body.scrollHeight;

            if (height == 0 && ad != null) {
                height = ad.offsetHeight;
            }

            if (height > 50) {
                frame.height = height;
				
				// For 728 banners. Display style causes bugs so use position and visibility hide/show banner.
				frame.style.visibility = "visible";
				frame.style.position = "static";
				frame.style.display = 'block';
            }
			else {
				frame.style.visibility = 'hidden';
				frame.style.display = 'none';
			}
	    
        } catch (e) { }
    }

