var geocoder;
var _location;
var _userIcon;
var _userMarker;
var _map;
var loki;
var _bootComplite = false;

var all_variables  = ['longitude', 'latitude', 'house_number', 'street', 'city', 'region', 'region_code', 'postal_code', 'country', 'country_code'];

function fillZipCode(response) {
    if(response.postalCodes.length > 0)
        _location.postal_code = response.postalCodes[0].postalCode;
}

function appendScript(src) {
    var scr = document.createElement('script');
    scr.src = src;
    document.body.appendChild(scr);
}

function replaceVariables(source) {
  var result = '' + source;
  var value = '';
  for (var i=0;i<all_variables.length;i++) {
    if (all_variables[i] in _location) {
        value = _location[all_variables[i]];
    }else {
        value = '';
    }
//    value = ('' + value).toLowerCase();
    result = result.replace('#' + all_variables[i] + '#', value);
  }
  return result;
}

function submitChannel(channel_id){
  var channel = channels[channel_id];
  var form = document.createElement('form');
  var url = replaceVariables(channel['url']);
  if (url.indexOf('zipcar') != -1)
      url = url.toLowerCase();
  form.action = url;
  form.id = 'dialog-form';
  form.method = channel.method;
  form.target = '_blank';
  var user_query = false;
  for (var i=0;i<channel.params.length;i++) {
//      if (channel.params[i].value.length) {
          var value = replaceVariables(channel.params[i].value);
//          if (url.indexOf('hotornot')||url.indexOf('zipcar'))
//              value = value.toLowerCase();

          jQuery(form).append('<input type="hidden" name="' + channel.params[i].name + '" value="' + value + '" />');
//      }
  }
  form.style.display = 'none';
  document.body.appendChild(form);
  form.submit();
  document.body.removeChild(form);
}

function setMapPosition(lat, lng) {
  // Hide the error message if its showing
  $('#errorMsg').slideUp();

  var point = new GLatLng(parseFloat(lat), parseFloat(lng));

  document.getElementById('longitude').value = parseFloat(lng);
  document.getElementById('latitude').value = parseFloat(lat);

  // Set user's marker and make it draggable
  if (_userMarker == null) {
    _userMarker = new GMarker(point, {icon:_userIcon, draggable:true, title:"You Are Here"});
    _map.addOverlay(_userMarker);

    GEvent.addListener(_userMarker, "dragend", function(){
      setMapPosition(_userMarker.getPoint().lat(), _userMarker.getPoint().lng());
    });

    //_map.addOverlay(_userMarker);
  } else {
    _userMarker.setLatLng(point);
  }

  _map.setCenter(point, 16);

  geocoder.getLocations(point, function(response){
    if (!response || response.Status.code != 200) {;
      alert("Status Code:" + response.Status.code);
    } else {

        var place = response.Placemark[0];


        var latitude = place.Point.coordinates[1];
        var longitude = place.Point.coordinates[0];
        var src = 'http://ws.geonames.org/findNearbyPostalCodesJSON?lat=' + latitude + '&lng=' + longitude + '&callback=fillZipCode';
        appendScript(src);
        var t_location = new Object();
        t_location.latitude = latitude;
        t_location.longitude = longitude;
        t_location.country_code =  place.AddressDetails.Country.CountryNameCode;
        t_location.country = place.AddressDetails.Country.CountryNameCode;
        t_location.region  = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
        t_location.region_code  = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
        if ('SubAdministrativeArea' in place.AddressDetails.Country.AdministrativeArea) {
                t_location.city  = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
//              if ('Thoroughfare' in place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality) {
//                  t_location.street = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
//              }
        }else {
              t_location.city  =  place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
        }
        _location = t_location;

      $("#current-location").html(response.Placemark[0].address);
    }
  });
}

function onSuccess(location) {
  $('#spinner').hide();
  $.unblockUI();
  _location = location;
  setMapPosition(location.latitude, location.longitude);
}

function onFailure(error){
  $('#spinner').hide();
  $.unblockUI();
  if (error == 1) $('errorMsg').html('Loki cannot find the scanning service. We recommend that you uninstall and re-install Loki.');
  else if (error == 2) $('#errorMsg .body').html('<p>We cannot detect your wireless adapter. Check to make sure its on and then reload the page or type in your address below.</p>');
  else if (error == 3) $('#errorMsg .body').html('<p>Loki cannot see any Wi-Fi access points in range and therefore cannot determine your location. Type in your address below to set your location.</p>');
  else if (error == 4) $('#errorMsg .body').html('<p>An unauthorized request was performed. Type in your address below to set your location.</p>');
  else if (error == 5) $('#errorMsg .body').html('<p>Server unavailable. Try again in a minute or type in your address below</p>');
  else if (error == 6) $('#errorMsg .body').html('<p>Loki cannot determine your location. You are most likely outside of our coverage area. Type in your address below to set your location.</p>');
  else if (error == 7) $('#errorMsg .body').html('<p>You are using an unauthorized proxy. Contact your network administrator.</p>');
  else if (error == 1000) $('#errorMsg .body').html('<p>Loki could not be installed. Please contact support at <a href="mailto:support@loki.com">support@loki.com</a></p>');
  else if (error == 1001) $('#errorMsg .body').html('<p>The location request was denied. Type in your address below to set your location.</p>');

  $('#errorMsg').slideDown();
  toggleAddressForm();
}

function requestLocation() {
  loki = LokiAPI();

  loki.onSuccess = onSuccess;
  loki.onFailure = onFailure;
  loki.setKey('loki.com');
  if (!('js_content' in window)) {
    $('#spinner').show();
    loki.requestLocation(true,loki.FULL_STREET_ADDRESS_LOOKUP);
  }else{
    if ('error' in js_content) {
      onFailure(js_content['error']);
    } else {
      var t_location = {};
      t_location.latitude = js_content.latitude;
      t_location.longitude = js_content.longitude;
      t_location.city = js_content.city;
      t_location.region = js_content.state;
      t_location.postal_code = js_content.zip;
      _location = t_location;
      setMapPosition(js_content.latitude, js_content.longitude);
    }
  }
}

function loadMap(lat, lng, zoom){

  // Create the "user" icon
  _userIcon                   = new GIcon(G_DEFAULT_ICON);
  _userIcon.image             = "/images/loki_marker.png";
  _userIcon.iconSize          = new GSize(25, 25);
  _userIcon.shadow            = "";
  _userIcon.shadowSize        = new GSize(0, 0);
  _userIcon.iconAnchor        = new GPoint(12, 12);
  _userIcon.infoWindowAnchor  = new GPoint(9, 2);

  // Create the map
  _map = new GMap2(document.getElementById('map'));
  _map.setCenter(new GLatLng(parseFloat(lat), parseFloat(lng)), zoom);
  _map.addControl(new GMapTypeControl());
  _map.addControl(new GSmallMapControl());
  _map.addControl(new GOverviewMapControl());

  // Initialize the Geocoder
  geocoder = new GClientGeocoder();
}

function toggleAddressForm() {
  $('#input-location-address').val($('#current-location').html());
  $('#input-location').toggle();
  $('#current-location').toggle();
  $('#input-location-address').focus();
}

// Initialize the page

function init() {

  loadMap(0,0,1);

  if (LokiAPI.isInstalled()) {
    requestLocation();
  } else {
    $.blockUI({message: $('#downloadLoki')});
    setTimeout("requestLocation()",1000);
  }

  $('#input-location-form').submit(function(){

    geocoder.getLatLng($('#input-location-address').val(), function(point) {
      if (!point) {
        $.prompt('Can\'t find specified location!',{buttons: {Ok: true}, focus: 1});
      } else {

      document.getElementById('longitude').value = point.lng();
      document.getElementById('latitude').value = point.lat();

        $('#input-location').toggle();
        $('#current-location').toggle();

        setMapPosition(point.lat(), point.lng(),1);
      }
    });
    return false;
  });

  $('#current-location').click(function(){
    toggleAddressForm();
  });

  $('#current-location').hover(
    function(){
      $(this).css("background-color","#F6F287");
    },
    function(){
      $(this).css("background-color","");
    }
  );

  $('#findme-message-link').click(function(){
    $.cookie('hide_findme_message', 'true', {path: '/', expires: 999});
    $('#findme-message').slideUp();
  });

  if (!$.cookie('hide_findme_message')) $('#findme-message').slideDown();

  $('.delete_channel').click(
       function() {
           $.get('/gallery/uninstall?id='+$(this).attr('channel_id'), {}, null);

           $(this.parentNode).remove();

           if (!$('.channel', $('#installed-chanels')).length) {
               $('h3', $('#installed-chanels')).after('You don\'t have installed chanels');
           }

           return;
       }
  );

  $('.channel_link').click(
       function() {
           if (!_location){
               alert('You should specify your location before using channels!');
               return false;
           }
           var cid = $(this).attr('channel_id');
           if (!cid)
               return true;
           submitChannel(cid);
           return false;
           var channel = channels[cid];
           var form = document.createElement('form');
           form.action = $(this).attr('href');
           form.id = 'dialog-form';
           form.method = channel.method;
           form.target = '_blank';
           var user_query = false;
           for (var i=0;i<channel.params.length;i++) {
             if (channel.params[i].value) {
                 $(form).append('<input type="hidden" name="' + channel.params[i].name + '" value="' + channel.params[i].value + '" />');
             }else if (channel.params[i]['var']) {
                 if (_location&&channel.params[i]['var'] in _location) {
                     var value = _location[channel.params[i]['var']];
                 }else{
                     var value = channel.params[i]['default'];
                     user_query = true;
                 }
                 $(form).append('<label>' + channel.params[i].title + ':<br /></label><input type="text" value="' + value + '" name="' + channel.params[i].name + '"><br />');
             }
           }
           if (false&&user_query) {
               var dialog_content = document.createElement('div');
               dialog_content.id = 'params-dialog';
               document.body.appendChild(dialog_content);
               $(dialog_content).append('<div id="dialog-title">' + channel.name + ' parameters</div>');
               $(dialog_content).append('<div id="dialog-content"></div>');
               $(dialog_content).append('<div id="dialog-buttons"><input type="button" id="dialog-button-ok" value="Ok" /><input type="button" id="dialog-button-cancel" value="Cancel" /></div>');
               $('#dialog-content').append(form);
               $.blockUI(dialog_content, { width: '450px'});

               $('#dialog-button-ok').click(function() {
                   $('#dialog-form').get(0).submit();
                       $.unblockUI();
               });

               $('#dialog-button-cancel').click($.unblockUI);

           }else{
             form.style.display = 'none';
             document.body.appendChild(form);
             form.submit();
             document.body.removeChild(form);
           }
           return false;
       }
  )
  //Event.observe('changeLocationForm', 'submit', changeLocationDo);
}

function localSearch() {

  var container = $('.locations-list');

  if (_location == null) {
    container.html('<li class="location last" style="list-style-type:none;"><div class="location-info">Please set your location before searching.</div></li>');
  }
  container.html('<div class="location-info"><img src="../images/spinner_16_trans.gif" height="16" width="16" align="absmiddle" /> Searching ...</div>');
  container.show();
  $.get('/findme/localsearch', {latitude: $('#latitude').val(), longitude: $('#longitude').val(), "query":$('#search').val() }, function(response) {
    if(response == 'Please enter search terms.' || response == 'Loki could not locate you.'){
      container.html('<div class="location-info">'+response+'</div>');
    }else{
      container.html(response);

      return false;
    }
  });
}

// Wait for the document to be ready then initialize the scripts
$(document).ready(function(){
  init();
  $("#search").focus();
});