var gps = null;

function geo_success(p) {
    gps = p;
    $('#locationForm > fieldset > div').append("<input type='submit' id='useGPS' value='Use GPS' data-icon='search' data-inline='true' />" );
    $('#locationForm > fieldset > div').page();
    /*
    //$('#gps').html("<a href='?start=" + p.coords.latitude + "," + p.coords.longitude + "'>Location found, click here to search for shelters</a>");

       */
}

function geo_error(e) {
    $('#currentLocationLabel').html('Enter your location to find currently open shelters:');
    //$('#gps').html(e.code + ": " + e.message);
}

$(function(){

    $('#useGPS').live('click', function(){
        $('#search').val(gps.coords.latitude + "," + gps.coords.longitude);
        $.mobile.pageLoading();
        $('#step2content').html('');
    });

    var clearMePrevious = '';

    // 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)
    {
        //$('#currentLocationLabel').html('Checking for GPS...');

        if (geo_position_js.init()) {
          geo_position_js.getCurrentPosition(geo_success, geo_error);
        }
        else
        {
            //$('#currentLocationLabel').html('GPS not enabled');
        }
    }

    $('div').live('pageshow',function(event, ui){
      $('li').removeClass('ui-btn-active');
    });

    $('#errorButton').click(function(){
       $('.ui-dialog').dialog('close');
        return false;
    });

    $('#locationForm').submit(function(){

        if($('#search').val() == '') return false;

        $.mobile.pageLoading();
        $('#step2content').html('');
        $.get("../ajax.php", { start:  $('#search').val()},
           function(data){

                var floridaShelters = $('<ul data-role="listview" data-icon="false" data-inset="true">');
                var floridaHotels = $('<ul data-role="listview" data-icon="false" data-inset="true">');
                var otherShelters = $('<ul data-role="listview" data-icon="false" data-inset="true">');

               if(data=="not found")
               {
                   $('#errorText').html("Address '" + $('#search').val() + "' not found.");
                   $.mobile.changePage('#error','pop');
               }

               data = $.parseJSON(data);

               $.each(data, function(i, item) {
                   $.jqmData(document.body, item.Name, {Latitude: item.Latitude, Longitude:item.Longitude, Name:item.Name});
                    var output = "<li data-icon='false'><a href='#' class='shelterListItem'><h3>" + item.Name + "</h3><p>" + item.Address + "</p><p>" + item.City + ", " + item.State + "</p></a></li>";

                    if(item.Type == "shelter")
                    {
                        if(item.State == 'FL')
                        {
                            floridaShelters.append(output);
                        } else {
                            otherShelters.append(output);
                        }
                    }
                    else if(item.Type == "accommodation")
                    {
                        floridaHotels.append(output);
                    }

               });
                   $('#step2content').append("<h4>Select a shelter to get driving directions.</h4>");
                 $('#step2content').append("<h2>Florida Shelters</h2>");
               $('#step2content').append(floridaShelters);
                if($('li', floridaShelters).length == 0)
                {
                     $('#step2content').append("No shelters found in Florida");
                }

               $('#step2content').append("<h2>Florida Accommodations</h2>");
              $('#step2content').append(floridaHotels);
                if($('li', floridaHotels).length == 0)
                {
                     $('#step2content').append("No accommodations found in Florida");
                }

                $('#step2content').append("<h2>Shelters in Other States</h2>");
               $('#step2content').append(otherShelters);
             $("ul").listview();
             $.mobile.changePage('#step2');
           });
        return false;
    });

    $('.shelterListItem').live('click', function(){
        $.mobile.pageLoading();
        var tmp = $.jqmData(document.body, $('h3', $(this)).html()).Latitude + "," + $.jqmData(document.body, $('h3', $(this)).html()).Longitude;
        var tmpName = $('h3', $(this)).html();
        var tmpLine1 = $('h3', $(this)).next().html();
        var tmpLine2 = $('h3', $(this)).next().next().html();
        $.get("../ajax.php", { start:  $('#search').val(), end: tmp},
           function(data){

               data = $.parseJSON(data);

               var output = '';

               output = output + "<h4>" + tmpName + "</h4>";
               output = output + "<h5>" + tmpLine1 + " " + tmpLine2 + "</h5>";
               output = output + "<br/>";
               output = output + "<strong>Distance:</strong> " + data.distance + " miles<br />";

               var estSeconds = parseInt(data.duration);
               var estHours = Math.floor(((estSeconds / 60) / 60));
               var estMinutes = Math.floor(estSeconds / 60) - estHours*60;


                output = output + "<strong>Estimated Time:</strong> " + estHours + " hrs, " + estMinutes + " mins";

               output = output + '<ol data-role="listview" data-inset="true">';

               $.each(data.steps, function(i, item) {
                    output = output + "<li>" + item.instruction + "<span class='ui-li-count'>" + item.distance + " mi</span></li>";
                });

               output = output + "</ol>";
               output = output + "<h4>Start</h4>";
               output = output + "<img src='" + data.originImage + "'/>";
               output = output + "<h4>Route</h4>";
               output = output + "<img src='" + data.routeImage + "'/>";
               output = output + "<h4>End</h4>";
               output = output + "<h5>" + tmpLine1 + " " + tmpLine2 + "</h5>";
               output = output + "<img src='" + data.destinationImage + "'/>";

               $('#step3content').html(output);
               $("ol").listview();
             $.mobile.changePage('#step3');
        });
    });
});
