﻿$(document).ready(init);
var firstLoad = true;
var splitView = false;
var map;
var mapCenter;
var ajaxWait = false;
var data;
var pinsArray;
var startPos;
var endPos;
var pageSize = 3;
var page = 1;
var pageL = 1;
var lastPage = 1;
var lastPageL = 1;
var curStore;
var startPin;
var endPin;
var cStores;
var oStores;
var mapHgt = 744; //544
var featured = -1;
var errorCondition = false;
var unableToSplit = false;
var ddMode = false;
var oldAddr;
var locPin;
var rdy = false;
var apt = false;
var cmp = false;
var aff = false;
var exd = false;
var nbk = false;
var origPos;
var origZoom;

function init()
{       
    if (Utilities.ie6)
    {
        Utilities.fixPng(document.getElementById('poiPntr'));
        Utilities.fixPng(document.getElementById('legStar'));
    }

    var winW = 1024;
    //var winH = 768;
    var winH = 1100; // 900
    pageSize = 6;
    
    //if (screen.height > 768)
    //{
        //winH = 900;
        //pageSize = 4;
    //}
    
    if (jQuery.browser.safari) pageSize = 6;
    
    window.resizeTo(winW,winH);    
    
    $('#resultsMarketing').fadeIn('def');
    
    //if (winH < 900) $('#eligDiv').hide();

   // $(window).bind('resize', broswerResize);
    //broswerResize();
    
    $('input').bind('keypress', keyPress);
    
    if (location.search != "")
    {
        var rdyQ = queryString('rdy');
        if (rdyQ != null)
            if (rdyQ == '1') rdy = true;
        
        var aptQ = queryString('apt');
        if (aptQ != null)
            if (aptQ == '1') apt = true;

        var cmpQ = queryString('cmp');
        if (cmpQ != null)
            if (cmpQ == '1') cmp = true;
            
        var affQ = queryString('aff');
        if (affQ != null)
            if (affQ == '1') aff = true;
        
        var exdQ = queryString('exd');
        if (exdQ != null)
            if (exdQ == '1') exd = true;

        var nbkQ = queryString('nbk');
        if (nbkQ != null)
            if (nbkQ == '1') {
                nbk = true;
                $('input[id=chk_nbk]').attr('checked', true);
            }
            
        
        var loc = queryString('loc');
        if (loc != null)
        {
            $('#AddressBox').val(loc);
            if (queryString('rpr'))
                $('#RepairRadio').attr('checked','checked');
            else
                $('#SalesRadio').attr('checked','checked');
            initialSubmit();
        }
    }
    
   // if ($('#AddressBox').val() == '')
    //{
      //  $("input[@name=InitGroup]").bind('click', function () {
        //    $('#InitButton').attr('src','img/btn_find.gif');
          //  $('#InitButton').bind('click',initialSubmit);
            //$("input[@name=InitGroup]").unbind('click');    
        //});
    //} else 
    //{
        $('#InitButton').attr('src','img/btn_find.gif');
        $('#InitButton').bind('click',initialSubmit);
    //}
    
}

function keyPress(e)
{
    if (e.which == 13)
    {
        //if (firstLoad && ($("input[@name=InitGroup]:checked").val()))
        if (firstLoad)
            initialSubmit();
        else if (!firstLoad)
        {
            if (ddMode) redoDD();
            else filterSubmit();
        }
        
        return false;
    }
}

function broswerResize()
{
    var mainW = $(window).width() - 30;
    if (mainW < 970) mainW = 970;
    var mapW = mainW - 495;
    //$('#mainFrame').width(mainW);
    //$('#rightFrame').width(mapW);
    
    var mapH = $(window).height() - 280;
    if (mapH < 300) mapH = 300;
    
    mapHgt = mapH + 100;
    
    if (firstLoad)
    {
        $('#map').height(mapHgt);
        //$('#map').width(mapW-2);
    } else {
        //map.resize(mapHgt, mapW-2);
    }
    
    $('#resultsFrame').height(mapH);
    
}

function isRepair()
{
    if (firstLoad && ($("input[@name=InitGroup]:checked").val() == 1)) return true;
    if ($('#chk_rpr:checked').val() && !$('#chk_sls:checked').val() && !$('#chk_bpy:checked').val() && !$('#chk_exp:checked').val() ) return true;
    return false;
}

function dataDone(obj)
{
    Analytics.MetricData.locationValue = $('#AddressBox').val();
    ajaxWait = false;
    if (obj.error) 
    {
        $('#resultsWait').fadeOut('def', function () {
            $('#resultsGeneral').fadeIn('def');
        });
        
        var errorHtml = '<div style="background-color: #eeeeee; height: 100%;"><div style="padding: 10px;">';
        if (isRepair())
            errorHtml += 'There are no repair centers within 50 miles of your location. Please use our <a href="javascript:launch(\'https://indirect3.sprint.com/apps/advanceexchange/aeCriteria.do?method=displayCriteria&FROM_SPRINT=Y&withinRange=N\');">Self Service Phone Replacement option<a/>.';
        else
            errorHtml += 'There are no stores within 50 miles of you location. Please visit our <a href="javascript:launch(\'http://www.nextel.com/en/shop/\');">online store</a> to make a purchase from our entire catalog of handsets, accessories, and services or call telesales at 1-800-SPRINT1';
        
        errorHtml += '</div></div>';
        
        $('#featuredFrame').hide();
        featured = -1;
        recalcZoom();
        $('#resultsGeneral').html(errorHtml);
        errorCondition = true;
        
        Analytics.StoreLocatorMaps.trackError('user','no results found');
        
        return;
    }
    
    if (errorCondition)
    {
        $('#resultsGeneral').hide();
        $('#resultsWait').show();
        errorCondition = false;
    }
    
    data = obj;
    featured = -1;
    
    $('#featuredFrame').hide();
    
    if (firstLoad)
    {
        $('#commandDiv').fadeIn();
        $('#initialForm,#startMap').fadeOut('def', function () {
            $('#filterForm,#legendMap').fadeIn('def');
            recalcZoom();
        });      
    }
    
    
    $('#resultsWait').fadeOut('def', function () {
        $('#resultsGeneral').fadeIn('def');
    });
    
    oStores = new Array();
    cStores = new Array();
    
    var zoomPos = new Array();
    
    
    for (var i=0; i<data.stores.length; i++)
    {
        if ((data.stores[i].type.indexOf('EXCLUSIVE') > -1) && (data.stores[i].rdynow == false))
            oStores.push(i);
        else
        {
            cStores.push(i);
            if (data.stores[i].featured)
            {
                if (!isRepair())
                    featured = i;
                
            }
        }
        //if (i < 5)
             zoomPos.push(new Position(data.stores[i].lat + ' ' + data.stores[i].lon));
    }
    
    if (featured < 0) recalcZoom();
    
    unableToSplit = false;
    if (splitView)
    {
        if ((oStores.length == 0) || (cStores.length == 0))
        {
            splitView = false;
            unableToSplit = true;
        }
    }
    
    mapCenter = new Position(((obj.swLat + obj.neLat) / 2) + ' ' + ((obj.swLon + obj.neLon) / 2));
    var bbox = new BoundingBox(new Position(obj.swLat + ' ' + obj.swLon),new Position(obj.neLat + ' ' + obj.neLon));
    
    if (firstLoad)
    {
        map = new Map(document.getElementById("map")); 
        map.addCopyrightMessage("&copy;2008 Maps.com, Map data &copy;2008 Tele Atlas");
        map.centerOnPosition(mapCenter, function () {            
            //zoomLevel = map.getZoomController().getZoomLevelToFitBoundingBox(bbox);
            if (data.stores.length == 1) zoomLevel = 4;
            else      
                zoomLevel = map.getZoomController().getZoomLevelToFitPositions(zoomPos);
            zoomBuildBar();
            map.getZoomController().zoomToNewLevel(zoomLevel);
            $('#map').bind('mousedown',function() { hidePop(); });
            origZoom = zoomLevel;
        });
        map.setRoutePreference(new RoutePreference("Fastest",new UOM("MI")));
        firstLoad = false;
    } else
    {
        if (oldAddr != $('#AddressBox').val())
            map.centerOnPosition(mapCenter);
        map.getZoomController().zoomToNewLevel(origZoom);
    } 
    
    oldAddr = $('#AddressBox').val();    
    
    
    //if (!featured) map.resize(mapHgt,$('#map').width());

    resetPages();
    buildResults();
    buildPins();   
    
    if (featured > -1)
        doFeatured(data.stores[featured]);        
    
    Analytics.StoreLocatorMaps.screenChangeHelperFunction('locatorresults_english');
}

function recenter()
{
    map.centerOnPosition(origPos);
}

function buildPins()
{
    map.removeAllPins();
    
    //var icon = new Icon("img/arrow.gif", 20, 20, 25, 25); 
    //var icon = new Icon("img/arw-left.png", 25, 27, 26, 28); 
    var icon = new Icon("img/pin.png", 6, 35, 24, 48); 
    
    origPos = new Position(data.clat + ' ' + data.clon);
    locPin = new Pin(origPos, null, null, icon);
    map.addPin(locPin);

    
    var pins = data.stores.slice();
    if (splitView)
    {
        pins = new Array();
        for(var i=0; i<cStores.length; i++)
        {
            pins.push(data.stores[cStores[i]]);
        }
    } 
    
    var ci =1;
    var oi = 1;
    
    for (var i=0; i<pins.length; i++)
    {
        //if (splitView)
        //{
          //  if ((data.stores[i].type.indexOf('EXCLUSIVE') > -1) && (data.stores[i].rdynow == false)) { pins[i].num = oi; oi++ }
            //else { pins[i].num = ci; ci++; }
        //} else
            pins[i].num = i+1;      
    }    
    
    pins.sort(sortLat);   
    
    for (var i=0; i<pins.length; i++)
    {
        var store = pins[i];
        var x = 7;
        var y = 5;
        var num = store.num;
        
        if (num.toString().length == 1) x = 11;
        var over = new TextOverlay(num,x,y,"#000000","10pt","verdana");
        var icon = new Icon("img/icon_yellow.png", 1, 36, 29, 36, over);        
      
        if ((store.type.indexOf('EXCLUSIVE') > -1) && (store.rdynow == false))
        {
            x = 5;
            if (num.toString().length == 1) x = 9;
            over = new TextOverlay(num,x,y,"#000000","10pt","verdana");
            icon = new Icon("img/icon_blue.png", 1, 35, 35, 35, over);
        }
        
        if (store.featured)
        {
            x = 7;
            if (num.toString().length == 1) x = 11;
            y = 8;
            over = new TextOverlay(num,x,y,"#000000","9pt","verdana");
            icon = new Icon("img/star.png",15,15,30,29, over);
        }
        
        var pin = new Pin(new Position(store.lat + ' ' + store.lon), null, null, icon);
        pin.keyId = store.keyId;
        pin.name = store.name;

        EventRegistry.addListener(pin,"click", doPin);

        map.addPin(pin);
    }
    
    
}

function resetPages()
{
    if (!splitView)
    {
        page = 1;
        lastPage = Math.ceil(data.stores.length / pageSize);
    } else {
        page = 1;
        //lastPage = Math.ceil(cStores.length / Math.floor(pageSize/2));
        lastPage = Math.ceil(cStores.length / pageSize);
        //pageL = 1;
        //lastPageL = Math.ceil(oStores.length / Math.floor(pageSize/2));
    }
}

function doFeatured(store)
{
    var featuredHtml = '<div style="margin: 2px 7px; background-color: #ffffff; border: solid 1px #808080;">'
        + '<div style="border-bottom: solid 1px #808080; padding: 3px;"><b>Closest Sprint full service location near you</b></div>'
        + getStoreHtml(store, false, false, true)
        + '</div>';    
    
    $('#featuredFrame').html(featuredHtml);
    $('#featuredFrame').show();
    //map.resize(mapHgt-125,$('#map').width());
    recalcZoom();
}

function cPage(dir)
{
    page = page + dir;
    if (page < 1) page = 1;
    if (page > lastPage) page = lastPage;
    
    buildResults();
}

function cPageL(dir)
{
    pageL = pageL + dir;
    if (pageL < 1) pageL = 1;
    if (pageL > lastPageL) pageL = lastPageL;
    
    buildResults();
}

function toggleSplit()
{
    splitView = ! splitView;
    resetPages();    
    buildResults();
    buildPins();
}

function buildResults()
{
    var resultList = '';     
            
    //if (! splitView)
   //{ 
        resultList += '<div style="border-bottom: solid 1px #999999; margin: 0px auto;">';
        
        //if (isRepair()) resultList += '<b>Stores with a repair center near you</b>';
        //else
        //{
        
        var text = "Sprint stores near you";
        var showall = "Show additional retailers";
        
        if (! splitView)
        {
         showall = "Show Sprint stores";
         text = "Retailers near you";
         }
        
        if (isRepair()) text = "Repair centers near you";
        
            if (unableToSplit)
                resultList += '&nbsp;&nbsp;<b>' + text + '</b>';
            else 
                resultList += '<div style="float: left;">&nbsp;&nbsp;<b>' + text + '</b></div><div style="float: right;"><a href="javascript:toggleSplit();">' + showall + '</a>&nbsp;&nbsp;</div><br style="clear: both;" />';
        //}
            
        resultList += '</b></div><div>';  
            
        var sPage = (page-1) * pageSize;
        var ePage = sPage + pageSize;    
            
        if (! splitView)
        {           
            if (ePage > data.stores.length) ePage = data.stores.length;    
            
            for (var i=sPage; i<ePage; i++)
            {
                data.stores[i].num = i+1;
                resultList += getStoreHtml(data.stores[i], (i > sPage), false, false);
            }
        } else {        
            if (ePage > cStores.length) ePage = cStores.length;
        
            for (var i=sPage; i<ePage; i++)
            {
                try {
                data.stores[cStores[i]].num = i+1;
                resultList += getStoreHtml(data.stores[cStores[i]], (i > sPage), false, true);
                } catch (e) { }
            }
        }
        
        resultList += '</div>';
        resultList += '<div class="pager"><div class="pagerContent">';
        if (page != 1) resultList += '<a href="javascript:cPage(-1);"><span style="background-color: #f9f0ae; border: solid 1px #999999; color: black; padding: 0px 2px;">Prev</span></a>&nbsp;&nbsp;';
        if (! splitView)
            resultList += 'Stores ' + (sPage+1) + '-' + ePage + ' of ' + data.stores.length;
        else
            resultList += 'Stores ' + (sPage+1) + '-' + ePage + ' of ' + cStores.length;
        if (page != lastPage) resultList += '&nbsp;&nbsp;<a href="javascript:cPage(1);"><span style="background-color: #f9f0ae; border: solid 1px #999999; color: black; padding: 0px 2px;">Next</span></a>';
        resultList += '</div></div>';
        
        /*
    } else {
        var spltT = '60%';
        var spltL = '40%';
        if (cStores.length == 1) { spltT = '35%'; spltL = '65%'; }
        if (cStores.length == 2) { spltT = '40%'; spltL = '60%'; }
        
        resultList += '<div style="position: relative; height: ' + spltT + '; border-bottom: solid 1px #808080; overflow: hidden;"><div style="margin: 0px auto; background-color: #ffef90;">';
        resultList += '<div style="float: left;">&nbsp;&nbsp;<b>Sprint stores near you</b></div><div style="float: right;"><a href="javascript:toggleSplit();">Show all results by distance</a>&nbsp;&nbsp;</div><br style="clear: both;" />';          
        resultList += '</div>';
        
        var sPageSize = Math.floor(pageSize/2);
        
        //var sPage = (page-1) * sPageSize;
        //var ePage = sPage + sPageSize;
        //var sPageL = (pageL-1) * sPageSize;
        //var ePageL = sPageL + sPageSize;
        var sPage = (page-1) * 3;
        var ePage = sPage + 3;
        var sPageL = (pageL-1) * 2;
        var ePageL = sPageL + 2;
        
        if (ePage > cStores.length) ePage = cStores.length;
        if (ePageL > oStores.length) ePageL = oStores.length;
        
        for (var i=sPage; i<ePage; i++)
        {
            try {
            data.stores[cStores[i]].num = i+1;
            resultList += getStoreHtml(data.stores[cStores[i]], (i > sPage), false, true);
            } catch (e) { }
        }
        
        resultList += '<div class="pager"><div class="pagerContent">';
        if (page != 1) resultList += '<a href="javascript:cPage(-1);"><span style="background-color: #f9f0ae; border: solid 1px #999999; color: black; padding: 0px 2px;">Prev</span></a>&nbsp;&nbsp;';
        resultList += 'Sprint stores ' + (sPage+1) + '-' + ePage + ' of ' + cStores.length;
        if (page != lastPage) resultList += '&nbsp;&nbsp;<a href="javascript:cPage(1);"><span style="background-color: #f9f0ae; border: solid 1px #999999; color: black; padding: 0px 2px;">Next</span></a>';
        resultList += '</div></div></div>';
        
        resultList += '<div style="position: relative; height: ' + spltL + '; overflow: hidden;"><div style="margin: 0px auto;background-color: #c5c9de;">';
        resultList += '&nbsp;&nbsp;<b>Other retailers near you</b>';            
        resultList += '</b></div>';
        
        for (var i=sPageL; i<ePageL; i++)
        {
            try {
            data.stores[oStores[i]].num = i+1;
            resultList += getStoreHtml(data.stores[oStores[i]], (i > sPageL), false, true);
            } catch (e) { }
        }
        
        resultList += '<div class="pager"><div class="pagerContent">';
        if (pageL != 1) resultList += '<a href="javascript:cPageL(-1);"><span style="background-color: #f9f0ae; border: solid 1px #999999; color: black; padding: 0px 2px;">Prev</span></a>&nbsp;&nbsp;';
        resultList += 'Authorized retailers ' + (sPageL+1) + '-' + ePageL + ' of ' + oStores.length;
        if (pageL != lastPageL) resultList += '&nbsp;&nbsp;<a href="javascript:cPageL(1);"><span style="background-color: #f9f0ae; border: solid 1px #999999; color: black; padding: 0px 2px;">Next</span></a>';
        resultList += '</div></div></div>';
    }
    */
    
    $('#resultsGeneral').html(resultList);
}

function getStoreHtml(store, notFirst, hideDir, noType)
{
    /*if (store == null) return;*/
    var bgCol = '#ffef90';
        
    var type = store.type;
    if ((type.indexOf('EXCLUSIVE') > -1) && (store.rdynow == false))
    {
        bgCol = '#c5c9de';
        type = 'AUTHORIZED RETAILER';
    } else type = '&nbsp;';        
        
    var style = "background-color: " + bgCol + "; padding-left: 7px;";
    //if (notFirst) style += " border-top: solid 1px #999999; margin-top: 7px;";
    
    var dirStr = '<br/><a href="javascript:doDirections(' + store.keyId + ');">Directions</a>';
    if (hideDir) dirStr = '';
    
    if (noType) type = '&nbsp;';
    
    
        
    var html = '<div style="' + style + '"><div style="float: left;"><b>';
    if (!hideDir)
           html += '<a href="javascript:goTo(' + store.keyId + ')">' + store.num + ") " + store.name + '</a>';
    else
           html += store.num + ") " + store.name;
           
    if (store.pTitle2 != '')
        type = '&nbsp;&nbsp;<a href="javascript:goTo(' + store.keyId + ')" style="font-style:italic;">' + store.pTitle2 + '</a>';      
    
    html += '</b></div><div style="float: right;">' + type + '</div><br style="clear: both;" /></div>'
           + "<table cellpadding='0' cellspacing='0' width='100%' style='padding: 0px 7px;'><tr>"
           + "<td width='215' valign='top' class='details'>" + store.address + "<br/>" + store.phone;
           
    if (store.pTitle != '')
        html += '<br/><a href="javascript:goTo(' + store.keyId + ')" onmouseover="showP(this,\'' + store.pText + '\');" onmouseout="hideP();"><b>' + store.pTitle + '</b></a>';
    if (store.rdynow)
        html += '<br/><a href="javascript:goTo(' + store.keyId + ')">This is a <b><i><font color="#000000">ReadyNow</font></i></b> store</a>';
    
    var appStr = '';
    if (store.appt != "")
        appStr = '<br/><br/><a href="' + store.appt + '" target="_blank">Make&nbsp;an&nbsp;appointment</a>';
    
           
    html += '</td>'
           + "<td width='150' valign='top' class='details'>" + store.specs + "</td>"
           + "<td width='120' valign='top' align='right' class='details'>" + store.dist + " miles"
           + dirStr
           + appStr
           + '</td></TR></table>';
    
    return html;
}

function showP(itm,txt)
{
    $('#pPop').html(txt);
    var pinPos = $(itm).offset();
    var x = pinPos.left + $(itm).width();
    var y = pinPos.top;
    $('#pPop').css('left',x + 'px');
    $('#pPop').css('top',y + 'px');
    $('#pPop').show();
}

function hideP()
{
    $('#pPop').hide();
}

function initialSubmit()
{
    if (ajaxWait) return;
    
    var opt = $("input[@name=InitGroup]:checked").val();
    if (!opt)
    {
        opt = 2;
        //alert('You must select an option.');
        //return;
    }
    
    var opts = new Object();
    if (opt == 1)
    {
        opts.rpr = 1;
        $('#chk_sls').attr('checked','');
        $('#chk_rpr').attr('checked','checked');
        splitView = false;
    } else 
        splitView = true;
        
    if (rdy) { opts.rdy = 1; splitView = false; }
    if (apt) opts.apt = 1;
    if (aff) opts.aff = 1;
    if (exd) opts.exd = 1;
    if (cmp) opts.cmp = 1;
    if (nbk) opts.nbk = 1;
    
    oldAddr = $('#AddressBox').val();
    
    Analytics.MetricData.selectionType = "radio";
    if (isRepair())
        Analytics.MetricData.selectionValue = "repair";
    else 
        Analytics.MetricData.selectionValue = "all";
    
    processSubmit(opts);      
}

function filterSubmit()
{
    if (ajaxWait) return;
    
    hidePop();
    
    var omniVal = '';
    
    var opts = new Object();
    if ($('#chk_sls:checked').val()){ opts.sls = 1; omniVal += "Sales,"; }
    if ($('#chk_rpr:checked').val()){ opts.rpr = 1; omniVal += "Repair,"; }
    if ($('#chk_bpy:checked').val()){ opts.bpy = 1; omniVal += "Bill Pay,"; }
    if ($('#chk_esp:checked').val()){ opts.esp = 1; omniVal += "Spanish,"; }
    if ($('#chk_gen:checked').val()) { opts.gen = 1; omniVal += "4g,"; }
    if ($('#chk_nbk:checked').val()) { opts.nbk = 1; omniVal += "Netbook,"; }
    
    if (omniVal == '') omniVal = "None";
    else omniVal = omniVal.substr(0,omniVal.length - 1);
    
    if (isRepair())
        splitView = false;
    else
        splitView = true;
        
    Analytics.MetricData.selectionType = "checkbox";
    Analytics.MetricData.selectionValue = omniVal;
        
    processSubmit(opts); 
}

function processSubmit(opts)
{    
    if ($('#AddressBox').val() == '')
    {
        alert('Please enter a complete address or a valid ZIP Code.');
        return;
    }   
    
    ajaxWait = true;
    
    var url = 'GetData.ashx'; //?addr=' + $('#AddressBox').val()
        //+ '&r=' + $('#radius').val()
        //+ opts;
        
    opts.r = $('#radius').val();
    opts.addr = $('#AddressBox').val();    
   
    var clip = '#resultsGeneral';
    if (firstLoad) clip = '#resultsMarketing';
      $(clip).fadeOut('def', function () {
        $('#resultsWait').fadeIn('def', function() {
        jQuery.getJSON(url, opts,dataDone); 
        });        
    });
}

function goTo(keyId)
{
    for(var i=0; i<map.getPins().length; i++)
    {
        var pin = map.getPins()[i];
        if (pin.keyId == keyId) doPin(pin, true);
    }
}

function doDirections(keyId)
{
    for(var i=0; i<data.stores.length; i++)
    {
        if (data.stores[i].keyId == keyId)
        {
            curStore = data.stores[i];
            break;
        }
    }
    
    hidePop();
    ddMode = true;
    
    startPos = new Position(data.clat + ' ' + data.clon);
    endPos = new Position(curStore.lat + ' ' + curStore.lon);
    
    var posList =  new Array(startPos,endPos);
      
    $('#resultsGeneral').fadeOut('def',function () 
    {
        $('#narrowFrame').hide();
        if (featured > -1)
        {
            $('#featuredFrame').hide();
            //map.resize(mapHgt,$('#map').width())
            recalcZoom(true);
        }

        var h = $('#resultsFrame').height()+65;
        $('#resultsFrame').height(h);
        
        $('#resultsWait').fadeIn('def', function() 
            {              
               for(var i=0; i<map.getPins().length; i++)
                {
                    var pin = map.getPins()[i];
                    pin.hide();
                }         
                map.routeMap(posList, routeCallback); 
            });          
    });
    
    $('#intlDiv').fadeOut('def', function ()
    {
        $('#ddGeoBtn').fadeIn('def');
    });
    
    Analytics.StoreLocatorMaps.screenChangeHelperFunction('drivingdirections');
}

function routeCallback(directions)
{	      
    if(directions==null)
    {
        alert('Unable to calculate a route.');
        ddGoBack();
        return;
    }    
    
    var html = '<div style="width: 95%; border: solid 1px black; margin: 5px auto;">' + getStoreHtml(curStore, false, true, false) + '</div>'
     + '<table cellpadding="0" cellspacing="0" border="0" width="95%" style="margin: 5px auto;">'
     + '<tr><td>Distance</td><td>'+directions.TotalDistance+' miles</td><td align="right"></td></tr>'
     + '<tr><td>Time</td><td>'+directions.TotalTime+'</td><td align="right"></td></tr>'
     + '</table>'
     + '<table cellpadding="0" cellspacing="0" border="0" width="95%" style="margin: 5px auto;">'
     + '<tr><td colspan="2"><div style="margin: 10px 0px;"><b>Start: ' + $('#AddressBox').val() + '</b></div></td></tr>';

    for(var i=0; i<directions.RouteInstructions.length; i++)
    {
        html += '<tr><td>' + (i+1) + ". " + directions.RouteInstructions[i].Instruction + '</td><td align="right">' + directions.RouteInstructions[i].distance + '&nbsp;mi.</td></tr>';
    } 
    
    html += '<tr><td colspan="2"><div style="margin: 10px 0px;"><b>End: ' + curStore.name + '<br/>' + curStore.address + '</div></td></tr>'
        + '<tr><td colspan="2"><a href="javascript:ddGoBack();">Return to search results</a></td></tr></table>';
    
    $('#resultsDD').html(html);
  
    $('#resultsWait').fadeOut('def', function () {
        $('#resultsDD').fadeIn('def');
    });    
 
    var startIcon = new Icon("img/start.gif",20,10,40,19);
    startPin = new Pin(startPos,null,null,startIcon);  
    var endIcon = new Icon("img/end.gif",20,10,40,19);
    endPin = new Pin(endPos,null,null,endIcon);        
    map.addPin(startPin); 
    map.addPin(endPin); 
}

function ddGoBack()
{   
    ddMode = false;
    map.showPins();
    if (startPin)
    {
        map.removePin(startPin);
        map.removePin(endPin);
        map.clearRoute();
        map.reDrawMap();
        startPin = undefined;
    }
    
    $('#resultsDD').fadeOut('def', function () 
    {                
        var h = $('#resultsFrame').height()-65;
        $('#resultsFrame').height(h);
        $('#narrowFrame').show();
        $('#resultsGeneral').fadeIn('def');
        if (featured > -1)
        {
            $('#featuredFrame').show();
            //map.resize(mapHgt-125,$('#map').width())
            recalcZoom();
        }
    });
    
    $('#ddGeoBtn').fadeOut('def', function ()
    {
        $('#intlDiv').fadeIn('def');
    });
}

function redoDD()
{
    map.removePin(startPin);
    map.removePin(endPin);
    hidePop();
    var qryObj = new Object();
    qryObj.addr = $('#AddressBox').val();
   
      $('#resultsDD').fadeOut('def', function () {
        $('#resultsWait').fadeIn('def', function() {
            jQuery.getJSON('GetGeo.ashx',qryObj,ddDone); 
        });        
    });
}

function ddDone(obj)
{
    startPos = new Position(obj.lat + ' ' + obj.lon);
    var posList =  new Array(startPos,endPos);
    map.routeMap(posList, routeCallback);
}

function sortLat(a,b)
{
    return b.lat - a.lat;
}

function doPin(pin, clicked)
{
    hidePop();
    if (!clicked)
    {
        Analytics.StoreLocatorMaps.storeIconLinkHandler();
        EventRegistry.addListener(map, "moveend", function() {
            showInfoBox(pin);
            EventRegistry.clearListeners(map,"moveend"); 
        });
    } else {
        Analytics.StoreLocatorMaps.storeNameLinkHandler();
        setTimeout(function() {
            showInfoBox(pin);
            }, 500);
    }
    map.panToPosition(pin.getPosition());
}

function showInfoBox(pin)
{
    jQuery.getJSON('PoiData.ashx',{ pid: pin.keyId }, function (dataObj) {
        var hdrHtml = '<div><div style="float: left; width: 140px;"><b>' + pin.name + '</b></div><div style="float: right; width: 135px;"><a href="javascript:doStorePage(' + pin.keyId + ');">Print details</a> | <a href="javascript:hidePop();">Hide details</a></div><br class="clearer" /></div>';
        $('#poiHdr').html(hdrHtml);
        $('#poiInfo').html(dataObj.html);
        $('#poiPop').width(dataObj.width);

        var pinPos = $(pin.pinImg).offset();
        var x = pinPos.left - $('#poiPop').width() + 200;
        var y = pinPos.top - $('#poiPop').height() - 25;
        $('#poiPop').css('left',x + 'px');
        $('#poiPop').css('top',y + 'px');
        $('#poiPop').show();
    });
}

function hidePop()
{
    $('#poiPop').hide();
}

function launch(url)
{
    window.open(url);
}

function doMsg(pid)
{
    window.open('Send.aspx?pid='+ pid, 'Send', 'width=700, height=300');
}

function startOver()
{
    location.href = 'Default.aspx';
}

function queryString( key )
{
    var re = new RegExp( "[?&]" + key + "=([^&$]*)", "i" );
    var offset = location.search.search( re );
    if ( offset == -1 ) return null;
    return RegExp.$1;
}

function doPrint()
{
    if (ddMode)
        Analytics.StoreLocatorMaps.directionsPrintHandler();
        
    self.print();
}

function doStorePage(keyId)
{
    Analytics.StoreLocatorMaps.storeDetailsPrintHandler();
    
    launch('StorePage.aspx?prt=1&pid=' + keyId);
}