﻿/******* LOCAL SEARCH AND BROWSE **************/

function ExpandAllRefinements(groupName, currentMoreLink)
{
    var expandableDivArray = $('slRefinements').getElementsBySelector('[expandedGroup="' + groupName + '"]');
    var originalDivArray = $('slRefinements').getElementsBySelector('[originalGroup="' + groupName + '"]');
    if ((expandableDivArray.size() >= 1)&&(originalDivArray.size() >= 1))
    {
        expandableDivArray[0].setStyle({display: 'block'});
        originalDivArray[0].setStyle({display: 'none'});
        currentMoreLink.setStyle({display: 'none'});
    }
}
/*******  LOCAL SEARCH AND BROWSE **************/

/******* IMAGES **************/

// Hide broken images			
function FixMissingImage(img)
{
	try{
		img.onerror = null;
		img.src = "/images/dot_clear.gif";
	}
	catch(e){}
}

function readSubCookie(name,subname)
{
	var tmpCookie=getCookie(name);//this is the values in the cookie
	if(tmpCookie)
	{
		uCookies=(tmpCookie.split("&"));
		var found=-1;
		for(i=0;i<uCookies.length;i++)
		{
			if (uCookies[i].indexOf(subname)!=-1) 	 
				{//extract the value
					var start =uCookies[i].indexOf("=");
					return uCookies[i].substring(start+1);
				}
		}	
	}		
}

function getCookie(Name) {
        var search = Name + "=" 
        var CookieString = document.cookie 
        var result = null 
        if (CookieString.length > 0) { 
			offset = CookieString.indexOf(search) 
			if (offset != -1) { 
					offset += search.length 
					end = CookieString.indexOf(";", offset) 
					if (end == -1) {
						end = CookieString.length }
						result = CookieString.substring(offset, end)
                } 
        }
        return result; 
}


/******* END IMAGES **************/

/**************** START GOOGLE ADSENSE FOR SEARCH STUFF ***************************/

function renderAds( adsSource, adTarget, redirectUrl, numberOfAdsWrittenBefore ) {
    var numberOfAdsWritten = 0;
    var gasOuterDiv = $( adTarget.divId );
    
    if ( gasOuterDiv != null ) {
        if ( adsSource.length > 0 ) {
            var targetDiv = gasOuterDiv.select( '.gasAfsInner' ).first();
        
            if ( targetDiv !== undefined && targetDiv != null ) {                            
                adTarget.numberOfAds.times( function( n ) {
                    var googleAd = adsSource.shift();
                    
                    if ( googleAd !== undefined && googleAd != null ) {
                        var currentAdIndex = numberOfAdsWritten + numberOfAdsWrittenBefore;
                        
                        targetDiv.appendChild(createGoogleAdElement(buildAdRedirectUrl(redirectUrl,
                                                                                       currentAdIndex,
                                                                                       googleAd),
                                                                    googleAd,
                                                                    adTarget.adFormat));
                                                                      
                        if ( n < adTarget.numberOfAds - 1 ) {
                            targetDiv.appendChild( document.createElement( 'br' ) );
                            targetDiv.appendChild( document.createElement( 'br' ) );
                        }

                        numberOfAdsWritten++;
                    }
                } );
            }
        } else {
            gasOuterDiv.hide();
        }
    }
    
    return numberOfAdsWritten;
}


function insertAdSeparators( adElements ) {
    return adElements.inject( [], 
                              function( acc, elm, index ) { 
                                  acc.push( elm );
                                  
                                  if ( index < adElements.size() - 1 ) {
                                      acc.push( document.createElement( 'br' ) );
                                      acc.push( document.createElement( 'br' ) );
                                  }
                                  
                                  return acc;
                              } );
}


function emitNotEnoughAdsPixel( numberOfAdsRequested, 
                                numberOfAdsReturned,
                                query,
                                siteId,
                                channelIds,
                                adFormat ) {
    
    var img = new Image();
    
    img.src = 'http://pt.crossmediaservices.com/pt/adsense?' + 
                    'adsrequested=' + numberOfAdsRequested + 
                    '&n=' + numberOfAdsReturned + 
                    '&keyword=' + query + 
                    '&siteid=' + siteId +
                    '&channel=' + channelIds +
                    '&format=' + adFormat;
    
    img.height = 1;
    img.width = 1;
    img.border = 0;
}


function buildAdRedirectUrl( redirectUrl, currentAdIndex, currentGoogleAd ) {
    return redirectUrl + 
            '&position=' + currentAdIndex +
            '&regionname=' + escape( currentGoogleAd.regionname ) +
            '&redirect=' + escape( currentGoogleAd.url );
}


function createGoogleAdElement(adUrl, googleAd, adFormat) {
    var adLink = document.createElement( 'a' );    
    adLink.href = 'javascript:void(null);'
    adLink.style.textDecoration = 'none';
    adLink.className = 'gasAfsText';
    adLink.rel = 'nofollow';
    
    adLink.onclick = function() { 
        window.open(    adUrl, 
                        "_blank",
                        "toolbar=1,scrollbars=1,status=1,location=1,menubar=1,resizable=1");
    };
    
    adLink.onmouseout = function() { 
        window.status = '';
        return true;
    };
    
    adLink.onmouseover = function() { 
        window.status = 'go to ' + googleAd.visible_url;
        return true;
    };
    
    adLink.appendChild( createGoogleAdLine( 'div', 'gasAfsLineOne', googleAd.line1 ) );
    
    if (adFormat == "WideFormat") { 
        adLink.appendChild(createGoogleAdLine('div', 'gasAfsLineTwo', googleAd.line2 + ' ' + googleAd.line3));
    } else {
        adLink.appendChild(createGoogleAdLine('div', 'gasAfsLineTwo', googleAd.line2));
        adLink.appendChild(createGoogleAdLine('div', 'gasAfsLineTwo', googleAd.line3));
    }
    
    adLink.appendChild( createGoogleAdLine( 'span', 'gasAfsSiteName', googleAd.visible_url ) );

    return adLink;
}


function createGoogleAdLine( tagName, className, innerHTML ) {
    var line = document.createElement( tagName );  
    line.className = className;
    line.innerHTML = innerHTML;
    return line;
}

/************************* END GOOGLE ADSENSE FOR SEARCH STUFF *********************/

/************************* CHANGE SHOPPING ZONE ***********************************/

function DrawChangeZoneForm() {
    var weatherbubblechangezone = $('weatherbubblechangezone');
    weatherbubblechangezone.show();
    $('citystatezip').focus();
}
function closeChangeLocation() {
    var weatherbubblechangezone = $('weatherbubblechangezone');
    weatherbubblechangezone.style.display = 'none';
}
/************************* END CHANGE SHOPPING ZONE ***********************************/

/************************* LOCAL SEARCH SORT ***********************************/

function redirectForSort(newSortValue, sortParameter, currentSortExp)
{
  doRedirectForSort(document.URL, newSortValue, sortParameter, currentSortExp);
}

function doRedirectForSort(currentUrl, newSortValue, sortParameter, currentSortExp)
{
    var currentSortRegex = new RegExp("[\\?&]" + sortParameter + "=([^&]+)");
    if(newSortValue == "")
    {
        currentUrl = currentUrl.replace(currentSortRegex, "");
    }
    else if(currentUrl.indexOf("&" + sortParameter + "=") > -1)
    {
        currentUrl = currentUrl.replace(currentSortRegex, "&" + sortParameter + "=" + newSortValue);
    }
    else
    {
        if(currentUrl.indexOf(".fp") > -1)
        {
            currentUrl += "?&" + sortParameter + "=" + newSortValue;
        }
        else
        {
            currentUrl += "&" + sortParameter + "=" + newSortValue;
        }
    }
    window.location.replace(currentUrl);
}

/************************* END LOCAL SEARCH SORT ***********************************/

/****************************** START GOOGLE MAPS API ************************************/
var GoogleMapManager = Class.create({
    initialize: function(mapElementId) {
        Event.observe(window, 'unload', GUnload);

        this.map = new GMap2($(mapElementId));
        this.map.addControl(new GSmallMapControl());
        this.map.addControl(new GMenuMapTypeControl());
        this.map.setCenter(new GLatLng(0, 0), 0);
        
        this.geocoder = new GClientGeocoder();
        
        this.baseIcon = new GIcon();
        this.baseIcon.iconSize = new GSize(18, 18);
        this.baseIcon.iconAnchor = new GPoint(9, 34);
        this.baseIcon.infoWindowAnchor = new GPoint(9, 9);
        
    },
    
    getMap: function() {
        return this.map;
    },
    
    setCenter: function(coords) {
        this.map.setCenter(new GLatLng(coords.lat, coords.lng), 13);
    },

    showLocations: function(locations, locationPopupHtmlCallback) {
        this.map.clearOverlays();
        
        if (locations.size() > 0) {
            var pointBounds = new GLatLngBounds();

            locations.each(function(loc) {
                var point = new GLatLng(loc.lat, loc.lng);
                pointBounds.extend(point);
                var marker = new GMarker(point);

                if (locationPopupHtmlCallback) {
                    GEvent.addListener(marker, "click", function() {
                        marker.openInfoWindowHtml(locationPopupHtmlCallback(loc));
                    });
                }
                
                this.map.addOverlay(marker);
            }.bind(this));

            this.map.setCenter(pointBounds.getCenter(),
                               this.map.getBoundsZoomLevel(pointBounds));
        }
    },
    
    showNumberedLocations: function(locations, locationPopupHtmlCallback) {
        this.map.clearOverlays();
        
        if (locations.size() > 0) {
            var pointBounds = new GLatLngBounds();

            locations.each(function(loc) {
                var point = new GLatLng(loc.lat, loc.lng);
                pointBounds.extend(point);
                
                var numberedIcon = new GIcon(this.baseIcon);
                numberedIcon.image = "/images/mappins/pin_" + loc.number + ".gif";
                
                var marker = new GMarker(point, { icon : numberedIcon });

                if (locationPopupHtmlCallback) {
                    GEvent.addListener(marker, "click", function() {
                        marker.openInfoWindowHtml(locationPopupHtmlCallback(loc));
                    });
                }
                
                this.map.addOverlay(marker);
            }.bind(this));

            this.map.setCenter(pointBounds.getCenter(),
                               this.map.getBoundsZoomLevel(pointBounds));
        }
    },
    
    clearLocations: function() {
        this.map.clearOverlays();
    },
    
    showAddress: function(address, latLng, popupHtmlCallback, latLngCallback) {
        var showMapLocation = function(point) {
            if (point) {
                this.map.setCenter(point, 13);
                var marker = new GMarker(point);
                this.map.clearOverlays();
                this.map.addOverlay(marker);
                
                if (popupHtmlCallback) {
                    marker.openInfoWindowHtml(popupHtmlCallback());
                }
                
                if (latLngCallback) {
                    latLngCallback(point);
                }
            } else {
                this.map.setCenter(new GLatLng(41, -92), 3);
            }
        }.bind(this);
    
        if (latLng) {
            showMapLocation(new GLatLng(latLng.lat, latLng.lng));
        } else {
            this.geocoder.getLatLng(storeAddress, showMapLocation);
        }
    }
});

var GoogleDirectionsManager = Class.create({
    initialize: function(mapManager, directionsElementId) {
        this.map = mapManager.getMap();
        this.directions = new GDirections(this.map, $(directionsElementId));
        
        GEvent.addListener(this.directions, 'error', function() {
            
            if(this.directions)
            {
                var status = this.directions.getStatus();
                var errorMessage = "An error has occurred while attempting to retrieve directions!";
                
                if (status.code == G_GEO_UNKNOWN_ADDRESS) {
                    errorMessage = "We couldn't understand this location";
                }
            }
            else
            {
                errorMessage = "We couldn't understand this location";
            }
            alert(errorMessage);
        });
    },
    
    getDirections: function(startAddress, endAddress) {
        this.map.clearOverlays();
        
        this.directions.load("from: " + startAddress + " to: " + endAddress, 
                             { locale: "en_US" });
    }
});
/****************************** END GOOGLE MAPS API **************************************/


/****************************** PRINT FUNCTIONALITY **************************************/
function delayPrint(){
	setTimeout(printframe, 1000);
}

function printFrame(strPage, skipPrint){

    //create Iframe and within page
	var el = document.createElement("iframe");
	
	//set atttibutes of the Iframes
	el.setAttribute('id', '_print');
	el.setAttribute('name', '_print');
	
	//append iframe to page
	document.body.appendChild(el);
	
	//set width and height to 0
	el.style.width = 0 + "px";
	el.style.height = 0 + "px";
	
	//set src of the iframe
	el.setAttribute('src', strPage);
	
	// sc 4.x sites skip this part because the print page executes the print directly via execCommand()
	if(skipPrint==null || skipPrint==undefined){
		el.onload = delayPrint();
	}
 }
/****************************** END PRINT FUNCTIONALITY **************************************/