var map = null;
var gps = null;
var locationName = '';
var locationAddressLine1 = '';
var locationAddressLine2 = '';
var clearMePrevious = '';

function geoPositionFound(p)
{
    gps = p;
    console.log(p);
    $('#mapFormFieldset').append("<button value='Use GPS' class='submitBtn' id='gpsButton'><span>Use GPS</span></button>" );
}

function geoPositionError(e) {
    console.log(e);
    //$('#gps').html(e.code + ": " + e.message);
}

$(function() {

    // clear input on focus
    $('.clearMeFocus').focus(function()
    {
        if($(this).val() != '')
        {
            clearMePrevious = $(this).val();
            $(this).val('');
        }
    });

    // if field is empty afterward, add text again
    $('.clearMeFocus').blur(function()
    {
        if($(this).val()=='')
        {
            $(this).val(clearMePrevious);
        }
    });

    if(gps==null)
    {
        if (geo_position_js.init()) {
          geo_position_js.getCurrentPosition(geoPositionFound, geoPositionError);
        }
    }

    $( "#errorDialog" ).dialog({
        autoOpen: false,
        resizable: false,
        position: [300, 'center'],
        modal: true,
        draggable:false,
        buttons: {
            Ok: function() {
                $( this ).dialog( "close" );
            }
        }
    });

    $( "#loadingDialog" ).dialog({
        autoOpen: false,
        resizable: false,
        position: [300, 'center'],
        modal: true,
        draggable:false
    });

    $('.submitBtn').hover(
        // mouseover
        function(){ $(this).addClass('submitBtnHover'); },

        // mouseout
        function(){ $(this).removeClass('submitBtnHover'); }
    );

    $(document).pngFix();

    $("a[rel^='prettyPhoto']").prettyPhoto({
        theme: 'dark_rounded', /* light_rounded / dark_rounded / light_square / dark_square */
        social_tools: ''
    });

    $('#mapForm').submit(function(){
        findShelters();
        return false;
    });

    $('#submit').click(function(){
        findShelters();
        return false;
    });

    $('#gpsButton').live('click', function(){
        $('#start').val(gps.coords.latitude + "," + gps.coords.longitude);
        findShelters();
        return false;
    });

    $('.shelterList > li > h3 > a').live('click', function(){

        var start = querySt($(this),'start');
        var end = querySt($(this),'end');

        locationName = $(this).html();
        locationAddressLine1 = $(this).parent().next().html();
        locationAddressLine2 =  $(this).parent().next().next().html();

        $( "#loadingDialog span.dialogMessage" ).html("Getting directions...");
        $( "#loadingDialog" ).dialog("open");

        map.getCredentials(function(credentials) {
            var routeRequest = 'http://dev.virtualearth.net/REST/v1/Routes?wp.0=' + start + '&wp.1=' + end + '&routePathOutput=Points&output=json&jsonp=RouteCallback&key=' + credentials;
            var mapscript = document.createElement('script');
            mapscript.type = 'text/javascript';
            mapscript.src = routeRequest;
            document.getElementById('myMap').appendChild(mapscript);
        });

        return false;
    });

});

function querySt(node, param) {
    hu = node.attr("href");
    gy = hu.split(/[\?\&]+/);
    for (i=0;i<gy.length;i++) {
        ft = gy[i].split("=");
        if (ft[0] == param) {
            return ft[1];
        }
    }
}

function findShelters()
{

    $( "#loadingDialog span.dialogMessage" ).html("Finding shelters...");
     $( "#loadingDialog" ).dialog("open");

    $.getJSON("ajax.php", { start:  $('#start').val()},
        function(data)
        {
            if(data==null || data=='')
            {
                $( '#errorDialog span.dialogMessage' ).html("No open shelters found.");
                $( "#errorDialog" ).dialog("open");
                return false;
            }

            $('#sidebar').hide();

            if(map==null) GetMap();

            map.entities.clear();
            var pushpins = new Array();

            var locs = [];
            var hotels = [];
            var pins = [];



            var floridaShelters = $('<ol>').addClass('shelterList');
            var floridaHotels = $('<ol>').addClass('shelterList');
            var otherShelters = $('<ol>').addClass('shelterList');

            floridaShelters.prepend("<h4>Florida Shelters</h4>");
            floridaHotels.prepend("<h4>Florida Accommodations</h4>");
            otherShelters.prepend("<h4>Shelters in Other States</h4>");

            $.each(data, function(i, item) {

                console.log(data);

                var loc;
                var pin;

                if(item.Type == "shelter")
                {
                    loc = new Microsoft.Maps.Location(item.Latitude, item.Longitude);
                    pin = new Microsoft.Maps.Pushpin(loc, {text: Number(locs.length + 1).toString()});

                    locs.push(loc);
                    pins.push(pin);

                    map.entities.push(pin);
                    var pushpinClick= Microsoft.Maps.Events.addHandler(pin, 'click', onPushpinClick);

                    var output = "<li><h3><a href='../index.php?start=" + $('#start').val() + "&end=" + item.Latitude + "," + item.Longitude + "' >" + item.Name + "</a></h3><p>" + item.Address + "</p><p>" + item.City + ", " + item.State + "</p></li>";

                    if(item.State == 'FL')
                    {
                        floridaShelters.append(output);
                    } else {
                        otherShelters.append(output);
                    }

                }
                else if(item.Type == "accommodation")
                {
                    loc = new Microsoft.Maps.Location(item.Latitude, item.Longitude);
                    pin = new Microsoft.Maps.Pushpin(loc, {textOffset: new
Microsoft.Maps.Point(3,5), icon: '../images/purple.png', text: Number(hotels.length + 1).toString()});

                    hotels.push(loc);
                    locs.push(loc);
                    pins.push(pin);

                    map.entities.push(pin);
                    var pushpinClick= Microsoft.Maps.Events.addHandler(pin, 'click', onPushpinClick);

                    var output = "<li><h3><a href='../index.php?start=" + $('#start').val() + "&end=" + item.Latitude + "," + item.Longitude + "' >" + item.Name + "</a></h3><p>" + item.Address + "</p><p>" + item.City + ", " + item.State + "</p></li>";

                    floridaHotels.append(output);
                }


            });

            if($('li', floridaShelters).length == 0)
            {
                floridaShelters.append("No shelters found in Florida");
            }

            if($('li', floridaHotels).length == 0)
            {
                floridaHotels.append("No accommodations found in Florida");
            }

            $('#list').empty();
            $('#list').append(floridaShelters);
            $('#list').append(floridaHotels);
            $('#list').append(otherShelters);

            var bestview = Microsoft.Maps.LocationRect.fromLocations(locs);
            map.setView({bounds:bestview });
        }
    )
    .error(function(err){
        console.log(err);
        $( '#errorDialog span.dialogMessage' ).html("The location '" + $('#start').val() + "' was not found.");
        $( "#errorDialog" ).dialog("open");
    })
    .complete(function(){
        $( "#loadingDialog" ).dialog("close");
    });
}

function onPushpinClick(e)
{
    var start = $('#start').val();
    var end = e.target.getLocation().latitude + "," + e.target.getLocation().longitude;

    $( "#loadingDialog span.dialogMessage" ).html("Getting directions...");
    $( "#loadingDialog" ).dialog("open");

    map.getCredentials(function(credentials) {
        var routeRequest = 'http://dev.virtualearth.net/REST/v1/Routes?wp.0=' + start + '&wp.1=' + end + '&routePathOutput=Points&du=mi&output=json&jsonp=RouteCallback&key=' + credentials;
        var mapscript = document.createElement('script');
        mapscript.type = 'text/javascript';
        mapscript.src = routeRequest;
        document.getElementById('myMap').appendChild(mapscript);
    });
}

function GetMap()
{
    map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
        credentials: 'Ahw9LNh--kAOLeYTQ0mzrehVTMXrZ6ReKb1FZZhOhkbOpWdpsIP1SW2JHWrD0Kvp',
        enableClickableLogo: false,
        enableSearchLogo: false,
        showMapTypeSelector:false,
        /*showDashboard:false,*/
        showScalebar:false,
        width: 450,
        height: 350
    });
}

function RouteCallback(result)
{

  var outputString = '';
  outputString = outputString + '<h3>' + locationName + '</h3>';
  outputString = outputString + '<h5>' + locationAddressLine1 + '</h5>';
  outputString = outputString + '<h5>' + locationAddressLine2 + '</h5>';
  outputString = outputString + '<br/>';

  if (result && result.resourceSets && result.resourceSets.length > 0 && result.resourceSets[0].resources && result.resourceSets[0].resources.length > 0)
  {
      //resultsHeader.innerHTML = "Bing Maps REST Route API  <br/>  Route from " + result.resourceSets[0].resources[0].routeLegs[0].startLocation.name + " to " + result.resourceSets[0].resources[0].routeLegs[0].endLocation.name;

      var estSeconds = parseInt(result.resourceSets[0].resources[0].routeLegs[0].travelDuration);
      var estHours = Math.floor(((estSeconds / 60) / 60));
      var estMinutes = Math.floor(estSeconds / 60) - estHours*60;

      outputString = outputString + "<strong>Distance:</strong> " + Math.round(result.resourceSets[0].resources[0].routeLegs[0].travelDistance,1) + " miles<br />"
        + "<strong>Estimated Time:</strong> " + estHours + " hrs, " + estMinutes + " mins";

      outputString = outputString + '<ol class="shelterList">';

      for (var i = 0; i < result.resourceSets[0].resources[0].routeLegs[0].itineraryItems.length; i++)
      {
          outputString = outputString + '<li>' + result.resourceSets[0].resources[0].routeLegs[0].itineraryItems[i].instruction.text + '</li>';
      }

      outputString = outputString + '</ol>';

      $('#list').html(outputString);

      var bbox = result.resourceSets[0].resources[0].bbox;
      var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(bbox[0], bbox[1]), new Microsoft.Maps.Location(bbox[2], bbox[3]));
      map.setView({ bounds: viewBoundaries});

      var zoom=map.getZoom();
      zoom = zoom - 1;
      map.setView({zoom:zoom});

      var routeline = result.resourceSets[0].resources[0].routePath.line; var routepoints = new Array();
      for (var i = 0; i < routeline.coordinates.length; i++)
      {
          routepoints[i]=new Microsoft.Maps.Location(routeline.coordinates[i][0], routeline.coordinates[i][1]);
      }
      var routeshape = new Microsoft.Maps.Polyline(routepoints, {strokeColor:new Microsoft.Maps.Color(200,0,0,200)});

      var startPushpinOptions = {anchor: new Microsoft.Maps.Point(10, 32), icon:"images/poi_custom.png" };
      var startPin= new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(routeline.coordinates[0][0], routeline.coordinates[0][1]), startPushpinOptions);

      var endPushpinOptions = {anchor: new Microsoft.Maps.Point(10, 32)};
      var endPin= new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(routeline.coordinates[routeline.coordinates.length-1][0], routeline.coordinates[routeline.coordinates.length-1][1]), endPushpinOptions);
       map.entities.clear();
      map.entities.push(startPin);
      map.entities.push(endPin);
      map.entities.push(routeshape);

      $( "#loadingDialog" ).dialog("close");

}
else
{
  if (typeof(result.errorDetails) != 'undefined')
  {
      //resultsHeader.innerHTML = result.errorDetails[0];
  }
      //alert("No Route found");
    $( "#loadingDialog span.dialogMessage" ).html("No driving route found for that location.");
}
}
