﻿// JScript File
var ValidAddress = false;

function TabSelected(TabId){
    if(TabId == 1){
        FAS = "on"
        BOL = "off"
        //Bottom styles
        document.getElementById(GlobalFormId + "_tdFindAStoreTab").className = "tdFindAStoreTabOn"
        document.getElementById(GlobalFormId + "_tdBuyOnlineTab").className = "tdBuyOnlineTabOn"
        document.getElementById(GlobalFormId + "_hlFindAStore").style.color="#555555"; //change button text to black
        document.getElementById(GlobalFormId + "_hlBuyOnline").style.color="#879d17"; //change button text to olive green
        
        //Show Find A Store Content
        document.getElementById(GlobalFormId + "_rpv_small_findastore").style.display = "block"
        document.getElementById(GlobalFormId + "_rpv_small_buyonline").style.display = "none"
        document.getElementById(GlobalFormId + "_lblSmall_footertext").innerHTML = document.getElementById(GlobalFormId + "_hfFindAStoreFooterText").value
    } else {
        FAS = "off"
        BOL = "on"
        //Bottom styles
        document.getElementById(GlobalFormId + "_tdFindAStoreTab").className = "tdFindAStoreTabOff"
        document.getElementById(GlobalFormId + "_tdBuyOnlineTab").className = "tdBuyOnlineTabOff"
        document.getElementById(GlobalFormId + "_hlFindAStore").style.color='#879d17'; //change button text to olive green
        document.getElementById(GlobalFormId + "_hlBuyOnline").style.color='#555555'; //change button text to black
        
        //Show Buy Online Content
        document.getElementById(GlobalFormId + "_rpv_small_findastore").style.display = "none"
        document.getElementById(GlobalFormId + "_rpv_small_buyonline").style.display = "block"
        document.getElementById(GlobalFormId + "_lblSmall_footertext").innerHTML = document.getElementById(GlobalFormId + "_hfBuyOnlineFooterText").value
    }
}
function PrintPage(){
    LeaveWyeth("GooglePrint",SearchString + ":+" + NewAddress)
}

//========================================
//   Dropdown & Textbox functions
//========================================
function SetAddress(Control){
    reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
    if(reZip.test(Control.value)) {
        NewAddress = Control.value
        ValidAddress = true;
    } else {
        if(Control.value != "Enter Zip Code or City, State") {
            var citystate = Control.value
            if(citystate.indexOf(",") < 1){
                try{
                    document.getElementById(GlobalFormId + "_lblError1").innerHTML = "&nbsp;Enter a Valid Zip Code or City, State"
                } catch(err){
                    document.getElementById(GlobalFormId + "_lblError2").innerHTML = "Enter a Valid Zip Code or City, State"
                }
                ValidAddress = false;
                try {
                    sender.clear();
                } catch(err){
                
                }
            } else {
                NewAddress = Control.value
                ValidAddress = true;
                try{
                    document.getElementById(GlobalFormId + "_lblError1").innerHTML = ""
                } catch(err){
                    document.getElementById(GlobalFormId + "_lblError2").innerHTML = ""
                }
            }
        } else {
            try{
                document.getElementById(GlobalFormId + "_lblError1").innerHTML = "&nbsp;Enter a Valid City, State"
            } catch(err){
                document.getElementById(GlobalFormId + "_lblError2").innerHTML = "Enter a Valid City, State"
            }
            ValidAddress = false;
            try {
                sender.clear();
            } catch(err){
            
            }
        }
    }
}

function GoBuyOnline(Layout){
    if(Layout == 0){
        var combo = $find(GlobalFormId + "_ddSmallBuyOnline");
        if(combo.get_value() == -1){
            alert("Please select a store.")
        } else {
            LeaveWyeth("BuyOnline",combo.get_value(),"ChapstickTop")
        }
    } else {
        var combo = $find(GlobalFormId + "_ddLargeBuyOnline");
        if(combo.get_value() == -1){
            alert("Please select a store.")
        } else {
            LeaveWyeth("BuyOnline",combo.get_value(),"ChapstickTop")
        }
    }
}
function GoFindAStore(){
    TestAddress = document.getElementById(GlobalFormId + "_tbSmallZipCode").value;
    reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
    if(reZip.test(TestAddress)) {
        NewAddress = TestAddress
        window.location.href = "/buynow.aspx?Address=" + NewAddress
    } else {
        if(TestAddress == "Enter Zip Code or City, State"){
            document.getElementById(GlobalFormId + "_lblError2").innerHTML = "Enter a Valid Zip Code"
        } else {
            if(TestAddress.indexOf(",") < 1){
                document.getElementById(GlobalFormId + "_lblError2").innerHTML = "Enter a Valid City, State"
            } else {
                NewAddress = TestAddress
                window.location.href = "/buynow.aspx?Address=" + NewAddress
            }
        }
    }
}
function EmailPage(){
    LoadTellAFriend("buynow.aspx?Address=" + NewAddress, "Buy Now", 4)
}
function ZipBlur(ControldId){
    if(ControldId.value == ""){
        ControldId.value = "Enter Zip Code or City, State"
        ControldId.className = "tbBlur"
    }
}
function ZipFocus(ControldId){
    if(ControldId.value == "Enter Zip Code or City, State"){
        ControldId.value = ""
    }
    ControldId.className = "tbFocus"
}
//========================================
//    Custom Scroll Bars for Locations
//========================================
var initialValue;
var initialValue2;
function ScrollBarNeeded(){
    var slider = $find(GlobalFormId + "_rsLocations")
    slider.repaint(); 
    if(document.getElementById(GlobalFormId + "_pnLocations").scrollHeight < parseInt(document.getElementById(GlobalFormId + "_pnLocation_Wrapper").style.height)){
        //slider.set_showDragHandle(!slider.get_showDragHandle());
        //slider.set_enabled(!slider.get_enabled());
    }
}

function HandleClientLoaded(sender, eventArgs)
{
    initialValue = sender.get_minimumValue();
    //var slider = $find(GlobalFormId + "_rsLocations")
    //sender.repaint();
    HandleClientValueChange(sender, null);
}

function HandleClientValueChange(sender, eventArgs)
{
    var wrapperDiv = document.getElementById(GlobalFormId + '_pnLocation_Wrapper');
    var contentDiv = document.getElementById(GlobalFormId + '_pnLocations');
    
    var oldValue = (eventArgs) ? eventArgs.get_oldValue() : sender.get_minimumValue();
    var change = sender.get_value() - oldValue;
    var contentDivHeight = contentDiv.scrollHeight - wrapperDiv.offsetHeight;
    var calculatedChangeStep = contentDivHeight / ((sender.get_maximumValue() - sender.get_minimumValue()) / sender.get_slideStep());
    
    initialValue = initialValue - change * calculatedChangeStep;
    
    if (sender.get_value() == sender.get_minimumValue())
    {
        contentDiv.style.top = 0 + 'px';
        initialValue = sender.get_minimumValue();
    }
    else
    {
        contentDiv.style.top = initialValue + 'px';
    }
}

//==================================
//        Google Maps Code
//==================================
// Global variables we will set in OnLoad
var map;
var searcher;
var searchControl;
var directions;
var SearchString;
var NewAddress;
var ZipCode = new Array();
var initialLoad = true;
var trafficInfo;
var traffictoggle = 0;
var quote=String.fromCharCode(34);
var GoogleLinks = new Array();
// Second, we set up our function, OnLoad
function GetMap() {
        var cLat;
        var cLng;
        //Get Lat and Lng from Zip Code
        // Next thing we have to do is build two divs to hold our stuff
        var mapContainer = document.getElementById(GlobalFormId + "_pnMap"); // build the map div
        var controlContainer = document.getElementById(GlobalFormId + "_pnLocations"); // build the control div
        // We're ready to build our map...
        map = new google.maps.Map2(mapContainer);
        map.backgroundColor = "#ffffff"

        // ...and add a couple of controls.
        map.addControl(new google.maps.SmallMapControl()); // Add a small map control
        map.addControl(new google.maps.MapTypeControl()); // Add the map type control
        //map.addControl(new google.maps.OverviewMapControl());
        map.addControl(new TrafficControl());
        // We'll wait to the end to actually initialize the map
        // So let's build the search control
        searchControl = new google.search.SearchControl();
        searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET)

        // Initialize a LocalSearch instance
        searcher = new google.search.LocalSearch(); // create the object
        // Set the map's center point and finish!

        // Create a SearcherOptions object to ensure we can see all results
        var options = new google.search.SearcherOptions(); // create the object
        options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);

        //options.setRoot(controlContainer)
        // Add the searcher to the SearchControl
        searchControl.addSearcher(searcher , options);
      
        // And second, we need is a search complete callback!
        searchControl.setSearchCompleteCallback(searcher , function() {
            try{
                map.clearOverlays();
            } catch(err) {
            
            }
            var results = searcher.results; // Grab the results array
            var baseIcon = new GIcon(G_DEFAULT_ICON);
            baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
            baseIcon.iconSize = new GSize(37, 37);
            baseIcon.shadowSize = new GSize(37, 34);
            baseIcon.iconAnchor = new GPoint(9, 34);
            baseIcon.infoWindowAnchor = new GPoint(9, 2);
            controlContainer.innerHTML = ""
            //Clear Results
            for (var i = 0; i < results.length; i++) {
                var result = results[i]; // Get the specific result
                try {
                    var markerLatLng = new google.maps.LatLng(parseFloat(result.lat), parseFloat(result.lng));
                    var numberedIcon = new GIcon(baseIcon);
                    numberedIcon.image = "/images/findastore/icons/" + (i + 1) +".png"
                    markerOptions = { icon:numberedIcon };
                    var marker = new google.maps.Marker(markerLatLng, markerOptions); // Create the marker
                    // Bind information for the infoWindow aka the map marker popup
                    var infoWindow
                    infoWindow = "<b>" + result.titleNoFormatting + "</b><br>"
                    infoWindow += "<span class='GMap_Else'>" + result.streetAddress + "<br>"
                    infoWindow += result.city + ", " + result.region + "</span><br>"
                    infoWindow += "<span class='Links'><a href='Javascript: GoGoogle(" + i + ")' target='_self' class='Links'>Directions to here</a>"
                    marker.bindInfoWindow(infoWindow);
                    result.marker = marker; // bind the marker to the result
                    map.addOverlay(marker); // add the marker to the map
                } catch(err) {
                
                }

                //Add the data to the list
                controlContainer.innerHTML += "<a href=" + quote +  "Javascript: CenterLocation('" + result.lat + "','" + result.lng + "')" + quote + "><img src='/images/findastore/icons/" + (i + 1) + ".png' border='0' /></a><br>"
                controlContainer.innerHTML += "<span class='GMap_Title'>" + result.titleNoFormatting + "</span><br>"
                controlContainer.innerHTML += "<span class='GMap_CityBold'>" + result.city + "</span><br>"
                controlContainer.innerHTML += "<span class='GMap_Else'>" + result.streetAddress + "<br>"
                controlContainer.innerHTML += result.city + ", " + result.region + "</span><br>"
                controlContainer.innerHTML += "<span class='GMap_Else'>"
                try {
                    for (var p = 0; p<result.phoneNumbers.length; p++) {
                        if(result.phoneNumbers[p].type == "") {
                            controlContainer.innerHTML += "Phone: " + result.phoneNumbers[p].number + "</span><br />"
                        } else {
                            controlContainer.innerHTML += result.phoneNumbers[p].type + ": " + result.phoneNumbers[p].number + "</span><br />"
                        }
                    }
                } catch(err) {
                
                }
                GoogleLinks[i] = result.ddUrlToHere
                controlContainer.innerHTML += "<div id='LocationFooter' style='width: " + document.getElementById(GlobalFormId + '_pnLocation_Wrapper').style.width + "'><a href='Javascript: GoGoogle(" + i + ")' target='_self' class='Links'>map & directions</a><br>"
                if(i == 0) {
                    cLat = result.lat
                    cLng = result.lng
                }
            }
            map.setCenter(new google.maps.LatLng(parseFloat(cLat),parseFloat(cLng)),13);
            document.getElementById(GlobalFormId + "_pnSearcher").innerHTML = ""
        });
    
      // Draw the control
      searchControl.draw(document.getElementById(GlobalFormId + "_pnSearcher"));
      HideContent(GlobalFormId + "_pnSearcher")
      LoadAddress(NewAddress);      
}
function GetSessionMap(){
    GetMap()
}
function LoadMap(rad){
    if(initialLoad == true){
        try{
            NewAddress = document.getElementById(GlobalFormId + "_tbSmallZipCode").value
        } catch(err){
        
        }
        try{
            NewAddress = document.getElementById(GlobalFormId + "_tbLargeZipCode").value
        } catch(err){
        
        }
        CheckAddress(NewAddress);
        if(NewAddress == "" || NewAddress == null || NewAddress == "Enter Zip Code or City, State"){
            try{
                document.getElementById(GlobalFormId + "_lblError1").innerHTML = "&nbsp;Enter a Valid Zip Code"
            } catch(err){
                document.getElementById(GlobalFormId + "_lblError2").innerHTML = "Enter a Valid Zip Code"
            }
        } else {
            if(ValidAddress == true){
                ajaxManager = $find(rad);
                ajaxManager.ajaxRequest(NewAddress);
                initialLoad = false
            }
        }
    } else {
        LoadAddress(NewAddress)
    }
}

function CheckAddress(tAddress){
    reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
    if(reZip.test(tAddress)) {
        NewAddress = tAddress;
        ValidAddress = true;
    } else {
        if(tAddress != "Enter Zip Code or City, State") {
            var citystate = tAddress;
            if(citystate.indexOf(",") < 1){
                try{
                    document.getElementById(GlobalFormId + "_lblError1").innerHTML = "&nbsp;Enter a Valid Zip Code or City, State"
                } catch(err){
                    document.getElementById(GlobalFormId + "_lblError2").innerHTML = "Enter a Valid Zip Code or City, State"
                }
                ValidAddress = false;
            } else {
                NewAddress = tAddress
                ValidAddress = true;
                try{
                    document.getElementById(GlobalFormId + "_lblError1").innerHTML = ""
                } catch(err){
                    document.getElementById(GlobalFormId + "_lblError2").innerHTML = ""
                }
            }
        } else {
            try{
                document.getElementById(GlobalFormId + "_lblError1").innerHTML = "&nbsp;Enter a Valid Zip Code"
            } catch(err){
                document.getElementById(GlobalFormId + "_lblError2").innerHTML = "Enter a Valid Zip Code"
            }
            ValidAddress = false;
        }
    }
}
function LoadAddress(Address){
    try {
        var geocoder = new google.maps.ClientGeocoder();
        geocoder.getLocations(Address,MapAddress)
    } catch(err) {
        if(confirm("It seems that the address/zip code you entered is invalid.  Please try again."))
            window.location.href = "/buynow.aspx";
        else {
            window.location.href = "/buynow.aspx";
        }
    }
}
function MapAddress(response){
    try {
        place = response.Placemark[0];
        ZipCode[0] = place.Point.coordinates[1]
        ZipCode[1] = place.Point.coordinates[0]
        map.setCenter(new google.maps.LatLng(ZipCode[0], ZipCode[1]), 13);
        searcher.setCenterPoint(new google.maps.LatLng(ZipCode[0], ZipCode[1]))
        searchControl.execute(SearchString);
    } catch(err) {
        if(confirm("It seems that the address/zip code you entered is invalid.  Please try again."))
            window.location.href = "/buynow.aspx";
        else {
            window.location.href = "/buynow.aspx";
        }
    }
}

function TrafficOverlay(tmp){
    //Add traffic overlay
    if(traffictoggle == 0){
        tmp.style.backgroundImage = "url(/images/findastore/large/traffic_on.png)";
        var trafficOptions = {incidents:true};
        trafficInfo = new google.maps.TrafficOverlay(trafficOptions);
        map.addOverlay(trafficInfo);
        traffictoggle = 1;
    } else {
        tmp.style.backgroundImage = "url(/images/findastore/large/traffic_off.png)";
        map.removeOverlay(trafficInfo);
        traffictoggle = 0;
    }
}
function CenterLocation(Lat, Lng) {
    map.setCenter(new google.maps.LatLng(Lat, Lng), 13)
}
function GoGoogle(LinkId){
    ajaxManager = $find(GlobalFormId + "_rapSession");
    document.getElementById(GlobalFormId + "_hfGoogleLink").value = GoogleLinks[LinkId]
    ajaxManager.ajaxRequest("Directions");
}
function TrafficControl() {
    
}
try {
// To "subclass" the GControl, we set the prototype object to
// an instance of the GControl object
    TrafficControl.prototype = new GControl();

    TrafficControl.prototype.initialize = function(map) {
      var container = document.createElement("div");

      var zoomInDiv = document.createElement("div");
      this.setButtonStyle_(zoomInDiv);
      container.appendChild(zoomInDiv);
      zoomInDiv.appendChild(document.createTextNode(" "));
      GEvent.addDomListener(zoomInDiv, "click", function() {
        TrafficOverlay(this);
      });

      map.getContainer().appendChild(container);
      return container;
    }

    TrafficControl.prototype.getDefaultPosition = function() {
          return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(207, 7));
        }

        // Sets the proper CSS for the given button element.
    TrafficControl.prototype.setButtonStyle_ = function(button) {
      button.style.textDecoration = "none";
      button.style.backgroundImage = "url(/images/findastore/large/traffic_off.png)";
      button.style.textAlign = "center";
      button.style.width = "67px";
      button.style.height = "19px";
      button.style.cursor = "pointer";
    }
} catch(err) {

}     