var ToGuest = ToGuest || {};

$.postJSON = function(url, data, callback) {
 $.post(url, data, callback, "json");
};

ToGuest.Maps = {
  locationIcons: null,
  movable_pushpin: null,
  init: function() {
    ToGuest.Maps.locationIcons = [ new GIcon(G_DEFAULT_ICON), new GIcon(G_DEFAULT_ICON), new GIcon(G_DEFAULT_ICON) ];
    ToGuest.Maps.locationIcons[0].image = "/images/map_icon_a.png";
    ToGuest.Maps.locationIcons[1].image = "/images/map_icon_b.png";
    ToGuest.Maps.locationIcons[2].image = "/images/map_icon_c.png";
    ToGuest.Maps.initializeMaps();
    ToGuest.Maps.fillMapsWithPlaces();
    ToGuest.Maps.fillMapsWithSinglePlace();
    ToGuest.Maps.fillMapsWithLocations();
    ToGuest.Maps.fillMapsWithMovablePushpin();
    ToGuest.Maps.placeSearch();
    ToGuest.Maps.personSearch();
  },
  initializeMaps: function() {
    $('.map').jmap('init', { 'mapType':'map', 'mapShowjMapsIcon':false } );
    $('.map').hide(); // starts hidden
    $('.map').each(function() {
      $this = $(this);
      var hash = ToGuest.Utilities.hashFromClassesForElement($this);
      if(hash["centerlat"]!=null && hash["centerlng"]!=null){
        $this.jmap('MoveTo', { 'mapCenter': [hash["centerlat"]||0.0, hash["centerlng"]||0.0], 'mapZoom': (hash["zoom"]||1) } );
      }
    });
  },
  fillMapsWithLocations: function() {
    $("#person_list_spinner").show();
    $("#person_list").hide();
    $(".with_locations").each(function(){
      $this = $(this);
      map_object = Mapifies.MapObjects.Get($this);
      var hash = ToGuest.Utilities.hashFromClassesForElement($this);
      url = '/locations.json'
      if(hash.user)
      {
        url = '/people/'+hash.user+url;
        ToGuest.Maps.retrieveLocationsForMap.call(map_object, url, hash.user);
      }
      GEvent.addListener(map_object, "moveend", function(){
        ToGuest.Maps.retrieveLocationsForMap.call(map_object, url, hash.user);
      });
    });
  },
  fillMapsWithSinglePlace: function() {
    $(".with_place").each(function(){
      $this = $(this);
      var hash = ToGuest.Utilities.hashFromClassesForElement($this);
      $.getJSON('/places/'+hash.place+'.json', function(data,status) {
        $this.jmap('AddMarker', { 'pointLatLng': [data.lat, data.lng], 'pointHTML': data.name }, function(marker,options) {});
        $this.show();
      });
    });
  },
  fillMapsWithPlaces:function() {
    $("#place_list_spinner").hide();
    $("#place_list").hide();
    $(".with_places").each(function(){
      $this = $(this);
      map_object = Mapifies.MapObjects.Get(this);
      //ToGuest.Maps.retrievePlacesForMap.call(map_object);
      GEvent.addListener(map_object, "moveend", ToGuest.Maps.retrievePlacesForMap);
    });
  },
  retrievePlacesForMap: function(page)
  {
    this.clearOverlays();
    var map = this;
    if($("#new-stuff").size()==0 || $("#new-stuff").is(":hidden")) // we have triggered a search
    {
     $("#place_list_spinner").show();
     $("#place_list").hide();
    }
    $("#place_list div.featured").remove();
    var bounds = this.getBounds();
    var sw = bounds.getSouthWest();
    var ne = bounds.getNorthEast();
    $.getJSON('/places.json', $('#searchform.places').serialize()+"&minlat="+sw.lat()+"&minlng="+sw.lng()+"&maxlat="+ne.lat()+"&maxlng="+ne.lng()+"&page="+(page||1), function(data,status) {
      // Pagination stuff: BEGIN
      var places = data.slice(0,data.length-1);
      // alert(places[0].text_link); // placesssssssssssss
      var pagination = data[data.length-1];
      $("#place_list h2 span:first-child").html(pagination.total_entries); // the last item is the total entries
      if(pagination.total_pages>1)
      {
        $("#place_list h2 span+span").html("(showing "+((pagination.current_page-1)*pagination.per_page+1)+"-"+(Math.min(pagination.total_entries,pagination.current_page*pagination.per_page))+")");
        $("#place_list h2 span+span").show();
        pagination_ul = $("#pagination div ul");
        pagination_ul.empty();
        for(var i=1;i<=pagination.total_pages;i++)
        {
          if(Math.abs(pagination.current_page-i)<=2 || i == 1 || i == pagination.total_pages)
          {
            var new_a = $("<a href='#main-map'>"+i+"</a>");
            pagination_ul.append(new_a);
            new_a.wrap("<li></li>");
            if(i==pagination.current_page)
              new_a.wrap("<strong></strong>");
          }
          else if(Math.abs(pagination.current_page-i)==3)
            pagination_ul.append("<li>...</li>");
        }
        pagination_ul.find("a").click(function(){
          ToGuest.Maps.retrievePlacesForMap.call(Mapifies.MapObjects.Get($(".with_places")),$(this).text());
        });
        $("#pagination").show();
      }
      else
      {
        $("#person_list h2 span+span").hide();
        $("#pagination").hide();
      }
      // Pagination stuff: END
      $.each(places, function(index,value) {
      // alert(value.text_link);
        pointHTML = value.image_link + value.short_text_link + value.owner_link + "<ul><li>"+value.place_type+"</li><li>"+value.place_sleeps+" sleeps</li><li>"+value.place_price+" / night</li></ul>";
        $this.jmap('AddMarker', { 'pointLatLng': [value.lat, value.lng], 'pointHTML': pointHTML }, function(marker,options) {});
								// ToGuest.GeneratedTemplates.alert_box();
								ToGuest.GeneratedTemplates.place_largebox( value.image_link, value.text_link, value.owner_link, value.place_type, value.place_sleeps, value.place_price );
        $("#place_list").append(
           ToGuest.GeneratedTemplates.place_largebox( value.image_link,value.text_link,value.owner_link,value.place_type,value.place_sleeps,value.place_price )
							 );
      });
      $this.show();
      Engine.design.switcher('#place_list div.featured-c p.image img','/images/thumb-c.png');
      if($("#new-stuff").size()==0 || $("#new-stuff").is(":hidden")) // we have triggered a search
      {
        $("#place_list_spinner").hide();
        $("#place_list").show();
      }
      else
      {
        $("#pagination").hide();
      }
    });
  },
  retrieveLocationsForMap: function(url, scoped_to_user, page)
  {
    this.clearOverlays();
    var map = this;
    $("#person_list_spinner").show();
    $("#person_list").hide();
    $("#person_list div.featured").remove();
    var bounds = this.getBounds();
    var sw = bounds.getSouthWest();
    var ne = bounds.getNorthEast();
    $.getJSON(url, $('#searchform.people').serialize()+"&minlat="+sw.lat()+"&minlng="+sw.lng()+"&maxlat="+ne.lat()+"&maxlng="+ne.lng()+"&page="+(page||1), function(data,status) {
      // Pagination stuff: BEGIN
      var locations = data.slice(0,data.length-1);
      var pagination = data[data.length-1];
      $("#person_list h2 span:first-child").html(pagination.total_entries); // the last item is the total entries
      if(pagination.total_pages>1)
      {
        $("#person_list h2 span+span").html("(showing "+((pagination.current_page-1)*pagination.per_page+1)+"-"+(Math.min(pagination.total_entries,pagination.current_page*pagination.per_page))+")");
        $("#person_list h2 span+span").show();
        pagination_ul = $("#pagination div ul");
        pagination_ul.empty();
        for(var i=1;i<=pagination.total_pages;i++)
        {
          if(Math.abs(pagination.current_page-i)<=2 || i == 1 || i == pagination.total_pages)
          {
            var new_a = $("<a href='#main-map'>"+i+"</a>");
            pagination_ul.append(new_a);
            new_a.wrap("<li></li>");
            if(i==pagination.current_page)
              new_a.wrap("<strong></strong>");
          }
          else if(Math.abs(pagination.current_page-i)==3)
            pagination_ul.append("<li>...</li>");
        }
        pagination_ul.find("a").click(function(){
          ToGuest.Maps.retrieveLocationsForMap.call(Mapifies.MapObjects.Get($(".with_locations")),"/locations.json",false,$(this).text());
        });
        $("#pagination").show();
      }
      else
      {
        $("#person_list h2 span+span").hide();
        $("#pagination").hide();
      }
      // Pagination stuff: END
      $.each(locations, function(index,value) {
        if(scoped_to_user) // Already scoped to a user
          pointHTML = value.name;
        else // Not scoped: present the user as well
          pointHTML = value.image_link + "<a href='"+value.user_url+"'>"+value.user_display_name + "</a>" + value.name;
        if(value.start_year && value.end_year)
          pointHTML += " ("+value.start_year+"-"+value.end_year+")";
        $this.jmap('AddMarker', { 'pointLatLng': [value.lat, value.lng], 'pointHTML': pointHTML, 'pointIcon' : ToGuest.Maps.locationIcons[value.category] }, function(marker,options) {});
        $("#person_list").append(
          ToGuest.GeneratedTemplates.person_largebox(
            value.image_link,value.text_link,value.additional_info,value.number_of_friends,value.number_of_mutual_friends));
      });
      $this.show();
      Engine.design.switcher('#person_list div.featured-c p.image img','/images/thumb-c.png');
      $("#person_list_spinner").hide();
      $("#person_list").show();
    });
  },
  fillMapsWithMovablePushpin: function() {
    $(".with_movable_pushpin").each(function(){
      var $this = $(this);
      var hash = ToGuest.Utilities.hashFromClassesForElement($this);
      if(!isNaN(hash.currentlat) && !isNaN(hash.currentlng))
      {
        $this.jmap('AddMarker', { 'pointLatLng': [hash.currentlat, hash.currentlng], 'pointHTML': null, 'pointIsDraggable': true }, function(marker,options) {
          ToGuest.Maps.movable_pushpin = marker;
        });
        $this.jmap('MoveTo', { 'mapCenter': [hash.currentlat, hash.currentlng], 'mapZoom': 12 } );
        $this.show();
      }
    });
  },
  placeSearch: function() {
    var show_search_results = (location.search ? true : false); // for the homepage: don't show the results on first load except if there is a search query
    $('#searchform.places').submit(function(){
	  
      if(show_search_results)
      {
        $("#new-stuff").hide();
        if(!logged_in)
		      location.href = "/static/join";
	    }
      show_search_results = true;
      // We recenter the map
      $.postJSON('/geocodings.json', { 'q' : $(this).find("input[name=place_search[q]]").val() }, function(data,status) {
        if(data && data["lat"] && data["lng"])
          $('.map').jmap('MoveTo', { 'mapCenter': [data["lat"], data["lng"]], 'mapZoom': new Array(2,4,6,10,12,13,16,16,17)[data["accuracy"]] } );
        else
          $('.map').jmap('MoveTo', { 'mapCenter': [0.0, 0.0], 'mapZoom': 1 } );
      });
      // Places are automatically fetched because the map is moved
      return false;
    });
    $('#searchform.places select, #searchform.places input[type=radio], #searchform.places input[type=checkbox]').change(function(){
      $('#searchform.places').submit();
    });
    $('#searchform.places').submit();
  },
  personSearch: function() {
    $('#searchform.people').submit(function(){
      // We recenter the map
      $.postJSON('/geocodings.json', { 'q' : $(this).find("input[name=person_search[q]]").val() }, function(data,status) {
        if(data && data["lat"] && data["lng"])
          $('.map').jmap('MoveTo', { 'mapCenter': [data["lat"], data["lng"]], 'mapZoom': new Array(2,4,6,10,12,13,16,16,17)[data["accuracy"]] } );
        else
          $('.map').jmap('MoveTo', { 'mapCenter': [0.0, 0.0], 'mapZoom': 1 } );
      });
      // People are automatically fetched because the map is moved
      return false;
    });
    $('#searchform.people input[type=radio]').change(function(){
      $('#searchform.people').submit();
    });
    $('#searchform.people').submit();
  }
};

ToGuest.UI = {
  init: function() {
    ToGuest.UI.picturesSlideshow();
    ToGuest.UI.requestRefreshOnFormUpdate();
  },
  picturesSlideshow: function() {
    $('.slideshow').each(function(){
      var
        $this = $(this),
        children_li = $this.children(),
        children_count = children_li.size(),
        steps_ul = $this.next(),
        previous_li = steps_ul.children().eq(0),
        next_li = steps_ul.children().eq(1),
        current_i,
        caption_p = steps_ul.next(),
        slide_to = function(i) {
          children_li.hide();
          children_li.eq(i).show();
          caption_p.text(children_li.eq(i).children().eq(0).attr("alt"));
          current_i = i;
          if(i==0) {
            previous_li.hide();
            if(children_count > 1)
              next_li.show();
            else
              next_li.hide();
          }
          else if(i==(children_count -1)) {
            previous_li.show();
            next_li.hide();
          }
          else {
            previous_li.show();
            next_li.show();
          }
        };
      previous_li.find("a").click(function(){ slide_to(current_i - 1); });
      next_li.find("a").click(function(){ slide_to(current_i + 1); });
      slide_to(0); // we automatically show the first one
    });
  },
  requestRefreshOnFormUpdate: function()
  {
    $('form#new_request select').change(function() { window.location = "/requests/new?" + $('form#new_request').serialize() });
  }
};

ToGuest.Utilities = {
  hashFromClassesForElement: function(element) {
    var hash = new Object,
        class_string = $(element).attr("class"),
        classes = class_string.split(" ");
    $.each(classes,function(i,val){ if(val.match(/:/)) hash[val.split(':')[0]] = parseFloat(val.split(':')[1]) });
    return hash;
  }
};

ToGuest.PlaceEdition = {
  init: function() {
    ToGuest.PlaceEdition.dynamic_fields_for_blackout_dates();
    ToGuest.PlaceEdition.activate_geolocate_link();
    ToGuest.PlaceEdition.closest_city_autocomplete();
    ToGuest.PlaceEdition.country_autocomplete();
  },
  dynamic_fields_for_blackout_dates: function() {
    var
      category_div = $("#blackout_dates"),
      remove_parent_when_clicked = function(){
        if(category_div.find("p.weekdays").size()!=1) {
          $(this).parent().find("input:last").attr("value","1").end().hide().prev().hide(); // mark for deletion
        }
        return false;
      },
      add_new_row = function(){
        var newrow = $(ToGuest.GeneratedTemplates.form_blackout_date(category_div.find("p.weekdays").size()));
        newrow.find("a.remove").click(remove_parent_when_clicked);
        $(this).parent().before(newrow);
        return false;
      };
    category_div.find("a.remove").click(remove_parent_when_clicked);
    category_div.find("a.add").click(add_new_row);
  },

  closest_city_autocomplete: function() {
    var set_city_id_on_selection = function(event, item){
      $(event.target).next().attr("value", item[1]);
    };
    $(".city_autocomplete").autocomplete("/cities").result(set_city_id_on_selection);
  },

  country_autocomplete: function() {
    var set_city_id_on_selection = function(event, item){
      $(event.target).next().attr("value", item[1]);
    };
    $(".country_autocomplete").autocomplete("/countries").result(set_city_id_on_selection);
  },

  copy_latlng_from_pushpin: function() {
    var latlng = ToGuest.Maps.movable_pushpin.getLatLng();
    if(!latlng) return;
    $("#place_lat").val(latlng.lat());
    $("#place_lng").val(latlng.lng());
  },
  activate_geolocate_link: function(){
    if(ToGuest.Maps.movable_pushpin) {
      ToGuest.PlaceEdition.copy_latlng_from_pushpin();
      GEvent.addListener(ToGuest.Maps.movable_pushpin, "dragend", ToGuest.PlaceEdition.copy_latlng_from_pushpin);
    }
    $('#geolocate').click(function(){
      var address = [$("#place_street").val(),$("#place_street_number").val(),$("#place_postal_code").val(),$("#place_city").val()].join(" ");
      var map_div = $(this);
      $.postJSON('/geocodings.json', { 'q' : address }, function(data,status) {
        if(data)
        {
          if(ToGuest.Maps.movable_pushpin) {
            $('.with_movable_pushpin').jmap('RemoveMarker',ToGuest.Maps.movable_pushpin);
          }
          $('.with_movable_pushpin').jmap('AddMarker', { 'pointLatLng': [data["lat"], data["lng"]], 'pointHTML': "", 'pointIsDraggable':true }, function(marker,options) {
            ToGuest.Maps.movable_pushpin = marker;
            GEvent.addListener(ToGuest.Maps.movable_pushpin, "dragend", ToGuest.PlaceEdition.copy_latlng_from_pushpin);
          });
          $('.with_movable_pushpin').jmap('MoveTo', { 'mapCenter': [data["lat"], data["lng"]] } );
          ToGuest.PlaceEdition.copy_latlng_from_pushpin();
          $(".with_movable_pushpin").show();
        }
      });
    });
  }
};

ToGuest.ProfileEdition = {
  init: function() {
    ToGuest.ProfileEdition.profile_picture();
    ToGuest.ProfileEdition.profile_dynamic_fields("#user_languages",ToGuest.GeneratedTemplates.form_language);
    ToGuest.ProfileEdition.profile_dynamic_fields("#user_educations",ToGuest.GeneratedTemplates.form_education);
    ToGuest.ProfileEdition.profile_dynamic_fields("#user_industries",ToGuest.GeneratedTemplates.form_industry);
    ToGuest.ProfileEdition.profile_dynamic_fields("#lived_in_locationmarks",ToGuest.GeneratedTemplates.form_locationmark_lived_in);
    ToGuest.ProfileEdition.profile_dynamic_fields("#visited_city_locationmarks",ToGuest.GeneratedTemplates.form_locationmark_visited_city);
    ToGuest.ProfileEdition.profile_dynamic_fields("#wished_travel_locationmarks",ToGuest.GeneratedTemplates.form_locationmark_wished_travel);
  },
  profile_picture: function() {
    var profile_picture_img = $("#upload_profile_picture").parents(2).find("img").get(0);
    var profile_picture_description = $("#upload_profile_picture").parents(2).find("h3").eq(0);
    $("#upload_profile_picture").upload({
      name: 'profile[avatar]',
      action: '/profile',
      enctype: 'multipart/form-data',
      params: { '_method' : 'put', 'authenticity_token' : AUTH_TOKEN },
      autoSubmit: true,
      onSubmit: function() {
        profile_picture_img.style.backgroundImage = "url(/images/ajax-loader.gif)"
        profile_picture_img.style.backgroundPosition = "8px 8px"
      },
      onComplete: function(response) {
        json_response = JSON.parse(response);
        profile_picture_img.style.backgroundImage = "url(" + json_response["url"] + ")"; //attr("src",response);
        profile_picture_img.style.backgroundPosition = "0px 0px";
        profile_picture_description.html(json_response["filename"] + " <span>" + json_response["filesize"] + "</span>");
      },
      onSelect: function() {}
    });
  },
  profile_dynamic_fields: function(category_string,row_generator) {
    var
      category_p = $(category_string),
      remove_parent_when_clicked = function(){
        if(category_p.find("span.fields").size()==1)
          $(this).parent().find("input").attr("value","");
        else {
          $(this).parent().find("input:last").attr("value","1"); // mark for deletion
          $(this).parent().hide();
          add_link_on_last();
        }
        return false;
      },
      add_link_on_last = function(){
        if(!category_p.find("span.fields:last").find("a.add").size()){
          category_p.find("a.remove:last").after('<a href="#" class="add">Add <span>+</span></a>');
        }
      },
      set_city_id_on_selection = function(event, item){
        $(event.target).next().attr("value", item[1]);
      },
      add_new_row = function(){
        var brol = $(row_generator(category_p.find("span.fields").size()));
        brol.find("a.remove").click(remove_parent_when_clicked);
        brol.find(".city_autocomplete").autocomplete("/cities").result(set_city_id_on_selection);
        $(this).parent().after(brol);
        $(this).remove();
        add_link_on_last();
        brol.find("a.add").click(add_new_row);
        return false;
      };
    category_p.find(".city_autocomplete").autocomplete("/cities").result(set_city_id_on_selection);
    category_p.find("a.remove").click(remove_parent_when_clicked);
    add_link_on_last();
    category_p.find("a.add").click(add_new_row);
  }
};

if(enableGoogleMaps)
  $(ToGuest.Maps.init);
$(ToGuest.UI.init);
$(ToGuest.PlaceEdition.init);
$(ToGuest.ProfileEdition.init);
