var ord;
var adPodRotator;
var adRotationTimeout = 60000;
	
	function setOrd()
	{
		var axel = Math.random() + "";
		ord = axel * 1000000000000000000; 
	}
	
	setOrd();
	
    function countClick(click)
    {
        var obj = document.getElementById('pixel');
		if (obj != null)
		{
			if(click != '%c')
			{
				setOrd();
				var clkad = click + 'http://images.gsngrocers.com/Assets/Common/Images/pixel.gif?rn=' + ord;		
				
				if(obj.src) {
					obj.src = clkad;
	            }
				
				var clkad = '';
			}
		}
    }
   
    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);
    }
   
    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 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){
        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);
		}		
    }

    function logAdRequest(adRequest) {

        if (document.getElementById('ctl00_hfRequestVars') != null) {
            var displayUrl = document.location.href;
            var requestArgs = document.getElementById('ctl00_hfRequestVars').value;

            LogAdRequest(displayUrl, requestArgs, adRequest, null, null);
        }
    }

    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);
        }
        else {
            RefreshAdPods(null);
        }
    }

    function RefreshAdPods(response) {
        try {
            $$('.AdMaster').each(function(e) { ClearStyle(e); Purge(e); });

            var sideBar = $('sidebar');

            if (sideBar != null) {
                ClearStyle(sideBar);
            }

            if (typeof (adPodRotator) == 'number') {
                clearTimeout(adPodRotator);
            }

            setOrd();

            var externalAds = null;

            if (typeof (response) == 'object' && 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;
                        }
                    }
                }
            }
            
            UpdateQuantCast();
            UpdateGoogle();

            adPodRotator = setTimeout('refreshAdPods();', adRotationTimeout);
        }
        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]);
                    }
                }
            }
        }
    }


    adPodRotator = setTimeout('refreshAdPods();', adRotationTimeout);