
$.extend({ 
    URLEncode: function(c) {
        var o = ''; var x = 0; c = c.toString(); var r = /(^[a-zA-Z0-9_.]*)/;
        while (x < c.length) {
            var m = r.exec(c.substr(x));
            if (m != null && m.length > 1 && m[1] != '') {
                o += m[1]; x += m[1].length;
            } else {
                if (c[x] == ' ') o += '+'; else {
                    var d = c.charCodeAt(x); var h = d.toString(16);
                    o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
                } x++;
            } 
        } return o;
    },
    URLDecode: function(s) {
        var o = s; var binVal, t; var r = /(%[^%]{2})/;
        while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '') {
            b = parseInt(m[1].substr(1), 16);
            t = String.fromCharCode(b); o = o.replace(m[1], t);
        } return o;
    }
});

$(document).ready(function(event) {
		
	if (location.hash === '') {
		
		var vanity = window.location.hostname.toLowerCase();
		if (vanity.indexOf("LandRoverIllinois.com".toLowerCase()) != -1)
			vanityRegion = "chicago";
		if (vanity.indexOf("ClevelandAreaLandRover".toLowerCase()) != -1)
			vanityRegion = "cleveland";
		if (vanity.indexOf("DCAreaLandRover.com".toLowerCase()) != -1)
			vanityRegion = "dc";
		if (vanity.indexOf("DelawareValleyLandRover.com".toLowerCase()) != -1)
			vanityRegion = "philadelphia";
		if (vanity.indexOf("LandRoverDET.com".toLowerCase()) != -1)
			vanityRegion = "detroit";
		if (vanity.indexOf("LandRoverPittsburgh.com".toLowerCase()) != -1)
			vanityRegion = "pittsburgh";
		if (vanity.indexOf("LandRoverTristate.com".toLowerCase()) != -1)
			vanityRegion = "tristate";
		if (vanity.indexOf("BayAreaLandRover.com".toLowerCase()) != -1)
			vanityRegion = "bayarea";
		if (vanity.indexOf("PugetSoundLandRover.com".toLowerCase()) != -1)
			vanityRegion = "pugetsound";
		if (vanity.indexOf("LandRoverGA.com".toLowerCase()) != -1)
			vanityRegion = "atlanta";
		if (vanity.indexOf("CarolinasLandRover.com".toLowerCase()) != -1)
			vanityRegion = "carolinas";
		if (vanity.indexOf("BayouLandRover.com".toLowerCase()) != -1)
			vanityRegion = "southlouisiana";
		if (vanity.indexOf("SunCoastLandRover.com".toLowerCase()) != -1)
			vanityRegion = "suncoast";
		if (vanity.indexOf("LandRoverSWFlorida.com".toLowerCase()) != -1)
		    	vanityRegion = "swflorida";
		if (vanity.indexOf("SouthFloridaLandRover.com".toLowerCase()) != -1)
		    	vanityRegion = "southflorida";
		if (vanity.indexOf("SoCalLandRover.com".toLowerCase()) != -1)
		    	vanityRegion = "socal";
		if (vanity.indexOf("BostonLandRover.com".toLowerCase()) != -1)
		    	vanityRegion = "boston";  
		if (vanity.indexOf("DallasFriscoLandRover.com".toLowerCase()) != -1)
		    	vanityRegion = "dallas";  
		if (vanity.indexOf("DenverLandRover.com".toLowerCase()) != -1)
		    	vanityRegion = "denver";  
		if (vanity.indexOf("HoustonAreaLandRover.com".toLowerCase()) != -1)
		    	vanityRegion = "houston";	
		location.href = location.href.replace(/#.*$/, '') + "?region=" + vanityRegion;
	}
		
    var params = {
        scale: "noscale",
        allowScriptAccess: "always",
        wmode: "transparent",
        align: "middle"
    };
    var flashvars = {};
    var attributes = {};

    floodlightEvent = function() {
		
        var hiddenIframeContainer = $('#hiddenIframeContainer');
        return function(region, model) {
            var cat;
             
            var axel = Math.random() + "";
            var a = axel * 10000000000000;
            // SWFAddressEvent.CHANGE fires before window.location.href changes
            // so we need to do this trickery.
            //var u2 = window.location.href.replace(/#.*$/, '') + "#/" + currentRegion + "/" + model;
			var u2 = window.location.href.replace(/#.*$/, '') + "/?region=" + region;
            u2 = $.URLEncode(u2);

            hiddenIframeContainer.html('<iframe src="http://fls.doubleclick.net/activityi;src=2161699;type=t2lan570;cat=' + cat + ';u2=' + u2 + ';ord=' + a + '?" width="1" height="1" frameborder="0"></iframe>');
        };
    } ();

    var onFlashLoad = function() {
        window.location.hash = SWFAddress.getValue().replace(/^!/, '');
        SWFAddress.addEventListener(SWFAddressEvent.CHANGE, GetMap);
        //GetMap();
    };
	
	var doFlash = function() {
		swfobject.embedSWF("swf/main.swf", "swfObj", "100%", "415px", "9.0.0", "expressInstall.swf", flashvars, params, attributes, onFlashLoad);
		GetMap();
	};
	
    var flashTimeout = setTimeout(doFlash, 2000);
    
});	
	

var map = null;
var icon = "<img src='images/lr-icon.png' border='0' />";
var infobox =  "" ;

var lat =  "" ;
var lon =  "" ;
var data =  "" ;
var zipCall = false;
var currentRegion = '';
var storeInfo = [];

var addr = "";
var region = "";
var startAddr = "";
var endAddr = "";

var trackT3ClickThrough = function(region, dealer_title) {
     var trackResult = pageTracker._trackEvent("URL Click", region, dealer_title);
};

var floodlightEvent;

$('.popupInfo').live('click', function (e) {
   var dealer_title = $(e.currentTarget).find('div.address > a').text();
   trackT3ClickThrough(region, dealer_title);
});

function flashMovie(movieName){  
	if(window.document[movieName]){  
		return window.document[movieName];  
	}  
    else {
		return document.getElementById(movieName);  
	}  
}


function sendToFlash(value) {
    if (typeof (flashMovie("swfObj").sendToFlash) == 'function') {
        flashMovie("swfObj").sendToFlash(value);    // the function name here sendToFlash(value) should match the function defined in the swf   \** #tsmith **\
    }
}



function isValidUSZip(zip) {
   return /^\d{5}(-\d{4})?$/.test(zip);
}

function isValidUSAddress(addr) {
//   return /^[a-zA-Z\d]+(([\'\,\.\- #][a-zA-Z\d ])?[a-zA-Z\d]*[\.]*)*$/.test(addr);
}

function callJSON() {
    var zipCode = $('#swiftText').val();
    if (isValidUSZip(zipCode)) {
        pageTracker._trackEvent('Zip Submit', 'Click', zipCode);

	    zipCall = true;
	    getJSONData(zipCode);
	}
	else{
		alert("Please enter a valid 5 digit Zip Code");
	}
}

function getJSONData(zip){

$('div.turns').html('');

var url; 

if(zipCall){
	url = urlZip + zip;
}
else{
	url = urlRegion + region;
}

	$.ajax({
		dataType: 'jsonp',
		type:'GET',
		url: url
	});
}
 
function XXXXXX(obj){
    if (obj != null) {
        AddPushpin(obj)
    }
}

function YYY(obj){
    if (obj != null) {
        AddPushpin(obj)
    }
}

function GetMap() {
    var pathNames = SWFAddress.getPathNames();
	if(currentRegion != pathNames[0]){
		SetRegion(); //read region info from URL to load the dealers in that region
		map = new VEMap('myMap');
		map.LoadMap(new VELatLong(0, 0), 10, VEMapStyle.Road, false, VEMapMode.Mode2D, false);
		map.SetZoomLevel(12);
		zipCall = false;
		getJSONData();
		
		currentRegion = pathNames[0];
    }
    var currentModel = pathNames[1];
    floodlightEvent(currentRegion, currentModel);
}   

function SetRegion(){
	var regionParam = SWFAddress.getPathNames();
	if (typeof regionParam[0] != 'string') {
	    regionParam[0] = "LandRover";
	}

	var vanity = window.location.hostname.toLowerCase();
	if (vanity.indexOf("LandRoverIllinois.com".toLowerCase()) != -1)
	    regionParam[0] = "chicago";
	if (vanity.indexOf("ClevelandAreaLandRover".toLowerCase()) != -1)
	    regionParam[0] = "cleveland";
	if (vanity.indexOf("DCAreaLandRover.com".toLowerCase()) != -1)
	    regionParam[0] = "dc";
	if (vanity.indexOf("DelawareValleyLandRover.com".toLowerCase()) != -1)
	    regionParam[0] = "philadelphia";
	if (vanity.indexOf("LandRoverDET.com".toLowerCase()) != -1)
	    regionParam[0] = "detroit";
	if (vanity.indexOf("LandRoverPittsburgh.com".toLowerCase()) != -1)
	    regionParam[0] = "pittsburgh";
	if (vanity.indexOf("LandRoverTristate.com".toLowerCase()) != -1)
	    regionParam[0] = "tristate";
	if (vanity.indexOf("BayAreaLandRover.com".toLowerCase()) != -1)
	    regionParam[0] = "bayarea";
	if (vanity.indexOf("PugetSoundLandRover.com".toLowerCase()) != -1)
	    regionParam[0] = "pugetsound";
	if (vanity.indexOf("LandRoverGA.com".toLowerCase()) != -1)
	    regionParam[0] = "atlanta";
	if (vanity.indexOf("CarolinasLandRover.com".toLowerCase()) != -1)
	    regionParam[0] = "carolinas";
	if (vanity.indexOf("BayouLandRover.com".toLowerCase()) != -1)
	    regionParam[0] = "southlouisiana";
	if (vanity.indexOf("SunCoastLandRover.com".toLowerCase()) != -1)
	    regionParam[0] = "suncoast";
	if (vanity.indexOf("LandRoverSWFlorida.com".toLowerCase()) != -1)
	    regionParam[0] = "swflorida";
	if (vanity.indexOf("SouthFloridaLandRover.com".toLowerCase()) != -1)
	    regionParam[0] = "southflorida";
	if (vanity.indexOf("SoCalLandRover.com".toLowerCase()) != -1)
	    regionParam[0] = "socal";
	if (vanity.indexOf("BostonLandRover.com".toLowerCase()) != -1)
	    regionParam[0] = "boston";   
	
	region =  regionParam[0];
}


function AddPushpin(dataObj) {
    var dealerObjArray = new Array();
    var divLocationInfo = $('#divLocationInfo');

    // Clear the screen
    divLocationInfo.find('> span, > div').html('');
    
    map.Clear();

    if (dataObj.Status == "Error") {
        if (zipCall) {
            alert("Please enter a valid 5 digit Zip Code");
        }
        sendToFlash("Land Rover Retailer");
        
    }

    var showDealer = function(e) {
        var myshape = map.GetShapeByID(e.elementID);
        if (myshape == null) { return; }
        var shapeId = myshape.GetID();
        if (shapeId != null && dealerObjArray[shapeId] != null) {

            pageTracker._trackEvent("Map Click", region, dealerObjArray[shapeId].trading_title);
            divLocationInfo.find('span.dealerName')
                .html('<a href="http://www.' + dealerObjArray[shapeId].url.replace(/^www./, '') + '" target="_blank">' + dealerObjArray[shapeId].trading_title + '</a>')
                .unbind('click')
                .click(function() {
                    trackT3ClickThrough(region, dealerObjArray[shapeId].trading_title);
                });
            divLocationInfo.find('span.address').html(dealerObjArray[shapeId].street + '<br class="local" /> ' + dealerObjArray[shapeId].town + ', ' + dealerObjArray[shapeId].county + ' ' + dealerObjArray[shapeId].pc);
            divLocationInfo.find('span.street').html(dealerObjArray[shapeId].street);
            divLocationInfo.find('span.town').html(dealerObjArray[shapeId].town);
            divLocationInfo.find('span.county').html(dealerObjArray[shapeId].county);
            divLocationInfo.find('span.phone').html('Phone: ' + dealerObjArray[shapeId].phone);

            var awardWinners = 'Hornburg Land Rover Los Angeles,Land Rover Encino,Land Rover Fort Lauderdale,Land Rover Palm Beach,Land Rover Nashville,Land Rover North Scottsdale,Land Rover Orlando,Land Rover Tampa,Land Rover Austin,Land Rover Dallas,Land Rover Las Vegas,Land Rover Pasadena,Land Rover Birmingham,Land Rover Cape Fear,Land Rover Chattanooga,Land Rover Huntsville'

            if (awardWinners.indexOf(dealerObjArray[shapeId].trading_title) != -1) {
                divLocationInfo.find('span.awardImage').html('<img src="http://qaapps.landrover.wunderman-review.com/landrover-t2/image/LR_PC_LOGO_4C_L.jpg" />');
            } else {
                divLocationInfo.find('span.awardImage').html('');
             }
            if (dealerObjArray[shapeId].email) {
                divLocationInfo.find('span.email').html('Email: <a href="mailto:' + dealerObjArray[shapeId].email + '">' + dealerObjArray[shapeId].email + '</a>');
            }
            divLocationInfo.find('div.visit')
                .html('<a href="http://www.' + dealerObjArray[shapeId].url.replace(/^www./, '') + +'" target="_blank">Visit Retailer Website</a>')
                .unbind('click')
                .click(function() {
                    trackT3ClickThrough(region, dealerObjArray[shapeId].trading_title);
                });
            divLocationInfo.find('div.directions').html('<a onClick="GetMapRouteAddrForm(\'' + dealerObjArray[shapeId].url + '\',\'from\');">Get Directions</a>');
        }
    }
    map.AttachEvent("onclick", showDealer);

    /////////create the layer so we can set map view to bounding box
    var layer = new VEShapeLayer();
    var markers = dataObj.Markers;
    if (typeof (markers) != "object") {
        markers = new Array();
    }

    for (var i = 0; i < markers.length; i++) {
        lat = markers[i].latitude;
        lon = markers[i].longitude;

        var latLong = new VELatLong(markers[i].latitude, markers[i].longitude);

        map.ClearInfoBoxStyles();

        var dealerName = markers[i].dealer_name;
        var street = markers[i].street;
        var town = markers[i].town;
        var county = markers[i].county;
        var phone = markers[i].phone;
        var email = markers[i].email;
        var title = markers[i].trading_title;
        var zip = markers[i].pc;
        var website = markers[i].url;

        addr = street + ' ' + town + ' ' + county + ' ' + zip
		
        if (zipCall) {
            divLocationInfo.find('span.dealerName')
                .html('<a href="http://www.' + website.replace(/^www./, '') + '" target="_blank">' + title + '</a>')
                .unbind('click')
                .click(function() {
                    trackT3ClickThrough(region, title);
                });

            divLocationInfo.find('span.address').html(street + '<br class="local" /> ' + town + ', ' + county + ' ' + zip);
            divLocationInfo.find('span.street').html(street);
            divLocationInfo.find('span.town').html(town);
            divLocationInfo.find('span.county').html(county);
            divLocationInfo.find('span.phone').html('Phone: ' + phone);
            divLocationInfo.find('span.email').html('Email: <a href="mailto:' + email + '">' + email + '</a>');
            divLocationInfo.find('div.visit')
                .html('<a href="http://www.' + website.replace(/^www./, '') + '" target="_blank">Visit Retailer Website</a>')
                .unbind('click')
                .click(function() {
                    trackT3ClickThrough(region, title);
                });
            divLocationInfo.find('div.directions')
                .html('<a onClick="GetMapRouteAddrForm(\'' + addr + '\',\'from\');">Get Directions</a>');
            // This gets set elsewhere during regioncode lookup.
            sendToFlash(title);
        }
        else {
            storeInfo.push({
                dealerName: markers[i].dealer_name,
                street: markers[i].street,
                town: markers[i].town,
                county: markers[i].county,
                phone: markers[i].phone,
                email: markers[i].email,
                title: markers[i].trading_title,
                zip: markers[i].pc,
                website: markers[i].url
            });
        }

        infobox = '<div class="popupInfo"><div class="address"><a href="http://www.' + website.replace(/^www./, '') + '" target="_blank" class="dealerName">' + title + '</a><br class="local" /><span>' + street + ', ' + town + ', ' + county + ' ' + zip + '<br class="local" />Phone: ' + phone + '</span></div><div class="controls"><span><a onClick="GetMapRouteAddr(\'' + addr + '\',\'to\',\'' + storeInfo.length + '\');">Directions to here</a></span> or <span><a onClick="GetMapRouteAddr(\'' + addr + '\',\'from\',\'' + storeInfo.length + '\');">Directions from here</a></span><br class="local" /><span class="inputAddrForm"></span></div></div>';

        var shape = new VEShape(VEShapeType.Pushpin, latLong);
        shape.SetCustomIcon(icon);
        shape.SetDescription(infobox);
        layer.AddShape(shape);
        dealerObjArray[shape.GetID()] = markers[i];
    }
    
   
    //add layer with all shapes to map
    map.AddShapeLayer(layer);
   
    //center and zoom automagically
    map.SetMapView(layer.GetBoundingRectangle());
    
    if (zipCall) {
    	map.SetZoomLevel(10);
    } else if (typeof(currentRegion) == 'string') {       
        var latLong = map.GetCenter();

        if (dataObj.Zoom == null || dataObj.Zoom == 0) {
            dataObj.Zoom = map.GetZoomLevel();    
        }
        if (dataObj.Latitude != null && dataObj.Longitude != null) {
            latLong.Latitude = dataObj.Latitude;
            latLong.Longitude = dataObj.Longitude;
        }
        map.SetCenterAndZoom(latLong, dataObj.Zoom);
    }
}

function GetMapRouteAddr(dealerAddr, f2, dealerInfo){
    $('span.inputAddrForm').html
        ('<form method="POST" action="" onsubmit="MapRoute(\'' + dealerAddr + '\',\'' + f2 + '\',\'' + dealerInfo + '\');return false;"><div class="txt">Enter an address:</div><input id="userAdd" type="text" /><img class="submit" onclick="MapRoute(\'' + dealerAddr + '\',\'' + f2 + '\',\'' + dealerInfo + '\')" src="images/btn_submit.gif" /></form>');
}


function GetMapRouteAddrForm(dealerAddr, f2){
    $('div.inputAddressForm').html
        ('<form method="POST" action="" onsubmit="MapRoute(\'' + dealerAddr + '\',\'' + f2 + '\');return false;"><div class="txt">To get directions, enter your address:</div><input id="userAdd" type="text" /><img class="submit" onclick="MapRoute(\'' + dealerAddr + '\',\'' + f2 + '\')" src="images/btn_submit.gif" /><br/></form>');
}


function MapRoute(dealerAddr, f2, dealerInfo) {
    var userAddr = $('#userAdd').val();

    if (f2 == "from") {
        startAddr = userAddr;
        endAddr = dealerAddr;
    }
    else {
        startAddr = dealerAddr;
        endAddr = userAddr;
    }


    if (userAddr.length > 2) {
        
        var options = new VERouteOptions();
        options.RouteCallback = onGotRoute;        
        map.GetDirections([startAddr, endAddr], options);
    }
    else {
        alert("Please enter a valid address");
    }

    if (typeof (dealerInfo) == "number") {
        var infonum = dealerInfo - 1;
        var dealerInfoObj = storeInfo[infonum]
        if (typeof (dealerInfoObj) != 'object') { return; }

        $('span.dealerName')
		    .html('<a href="http://www.' + dealerInfoObj.website.replace(/^www./, '') + '" target="_blank">' + dealerInfoObj.title + '</a>')
		    .unbind('click')
            .click(function() {
                trackT3ClickThrough(region, dealerInfoObj.title);
            });

        $('span.address').html(dealerInfoObj.street + ' 	<br class="local" /> ' + dealerInfoObj.town + ', ' + dealerInfoObj.county + ' ' + dealerInfoObj.zip);
        $('span.street').html(dealerInfoObj.street);
        $('span.town').html(dealerInfoObj.town);
        $('span.county').html(dealerInfoObj.county);
        $('span.phone').html('Phone: ' + dealerInfoObj.phone);
        //$('span.email').html('Email: <a href="mailto:' + dealerInfoObj.email + '">' + dealerInfoObj.email + '</a>');

        $('span.email').html('Email: ' + dealerInfoObj.email);
        $('div.visit')
		    .html('<a href="http://www.' + dealerInfoObj.website.replace(/^www./, '') + '" target="_blank">Visit Retailer Website</a>')
		    .unbind('click')
            .click(function() {
                trackT3ClickThrough(region, dealerInfoObj.title);
            });
        $('div.directions').html('<a onClick="GetMapRouteAddrForm(\'' + dealerInfoObj.addr + '\',\'from\');">Get Directions</a>');
    }
	
}

function onGotRoute(route)
{
$('div.inputAddressForm').html('');

if (route == null) { return; }

// Hide the Disambiguation Dialog a.k.a "Select a location"
// Non-jquery equivilant of $('#myMap_veplacelistpanel').hide();
{
  var disambiguationDialog = document.getElementById('myMap_veplacelistpanel');
  if (disambiguationDialog != null) { disambiguationDialog.style.display = "none"; }
}

// Unroll route
var legs     = route.RouteLegs;
var turns    = "Total distance: " + route.Distance.toFixed(1) + " mi<ol>";
var numTurns = 0;
var leg      = null;

// Get intermediate legs
for(var i = 0; i < legs.length; i++)
{
   // Get this leg so we don't have to derefernce multiple times
   leg = legs[i];  // Leg is a VERouteLeg object
	  
   // Unroll each intermediate leg
   var turn = null;  // The itinerary leg
	  
   for(var j = 0; j < leg.Itinerary.Items.length; j ++)
   {
	  turn = leg.Itinerary.Items[j];  // turn is a VERouteItineraryItem object
	  numTurns++;
	  turns += "<li> " + turn.Text + " (" + turn.Distance.toFixed(1) + " mi)</li>";
    }
    turns += "</ol> " 
}

$('div.turns').html(turns);
}

function setHash(){
    var hash = SWFAddress.getPathNames();
    if(typeof hash[1] != 'string')
    hash[1] = hash[0];
    callJSON();
    return false;
}
