Trourist = {
    say_hello: function() {
      alert("Hello trourist world!");
      return false;
    },

    newMap: function(id, markers, with_index){
        if(GBrowserIsCompatible() && document.getElementById(id)){
            var map = new GMap2(document.getElementById(id));

            var center = new GLatLng(markers[0][0], markers[0][1]);
            map.setCenter(center);

            map.addControl(new GLargeMapControl());
            map.addControl(new GMapTypeControl());

            var bounds = new GLatLngBounds();
            for(var i=0; i< markers.length; i++) {
              if (with_index != undefined) 
                marker = Trourist.newMarker(map, markers[i][0], markers[i][1], Trourist.iconForMaps(i+1), markers[i][2]);
              else
                marker = Trourist.newMarker(map, markers[i][0], markers[i][1], Trourist.iconForMaps(), markers[i][2]);
              
              bounds.extend(marker.getPoint());
            }
            map.setZoom(map.getBoundsZoomLevel(bounds));
            map.setCenter(bounds.getCenter());
            return map;
        } else {
            return false;
        }
    },
    
    newClusterMap: function(id, markers){
      if(GBrowserIsCompatible() && document.getElementById(id)){
        var map = new GMap2(document.getElementById(id));

        var center = new GLatLng(markers[0][0], markers[0][1]);
        map.setCenter(center);
        
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        
        var icon = Trourist.iconForMaps();
        
        var markers_cluster = [];
        var bounds = new GLatLngBounds();
        for(var i=0; i< markers.length; i++) {
          marker = Trourist.newMarker(map, markers[i][0], markers[i][1], Trourist.iconForMaps(), markers[i][2], false);
          bounds.extend(marker.getPoint());
          markers_cluster.push(marker);
        }
        map.setZoom(map.getBoundsZoomLevel(bounds));
        map.setCenter(bounds.getCenter());
        
        new MarkerClusterer(map, markers_cluster);
      }
    },

    newMarker: function(map, lat, lon, custom_icon, html, overlay){
      if (overlay==undefined) overlay = true
      
      if(map != undefined && lat != undefined && lon != undefined){
          var center = new GLatLng(lat, lon);
          if(custom_icon != undefined) {
              var marker = new GMarker(center, { icon:custom_icon });
          } else {
              var marker = new GMarker(center);
          }
          
          if (html != undefined) {
            GEvent.addListener(marker, 'click', function(){ 
              marker.openInfoWindowHtml(html); 
            });
          }
          
          if (overlay) {
            map.addOverlay(marker);
          }
          return marker;
      } else {
          return false;
      }
    },

    iconForMaps: function(index) {
      var ic = new GIcon();
      if (index != undefined){
        ic.image = "/images/pin/pin_"+index+".png";
        ic.shadow = "/images/pin_alfanumerico_shadow.png";
        ic.iconSize = new GSize(23.0, 40.0);
        ic.shadowSize = new GSize(44.0, 40.0);
        ic.iconAnchor = new GPoint(11.0, 20.0);
        ic.infoWindowAnchor = new GPoint(23.0, 20.0);
      }else{
        ic.image = "/images/pin.png";        
        ic.shadow = "/images/pin_shadow.png";
        ic.iconSize = new GSize(19.0, 26.0);
        ic.shadowSize = new GSize(33.0, 26.0);
        ic.iconAnchor = new GPoint(9.0, 13.0);
        ic.infoWindowAnchor = new GPoint(9.0, 13.0);
      }
      return ic;
    }
}




datepicker_values = {showOn: 'button', buttonImage: '/images/css/bullets/calendar.png', buttonImageOnly: true, dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true, yearRange: '1900:2012'}

$(document).ready(function () {

  $('a[rel*=facebox]').facebox()


  // SEARCH
  // Toggle
  $("#topBarSearchTerm").toggleVal();
  $("#topBarSearch").submit(function() {
    $(this).find(".toggleval").each(function() {
      if($(this).val() == $(this).data("defText")) {
        $(this).val("");
      }
    });
  });

  // Control del hover de la flecha
  $(".multiSearchBtnArrow").hover(
    function () {$(this).css({'background' : 'url(/images/css/bg/multiSearchBtnArrow-hover.gif)', 'cursor' : 'pointer'});},
    function () {$(this).css({'background' : 'url(/images/css/bg/multiSearchBtnArrow.gif)', 'cursor' : 'pointer'});}
  );
  // Alterna en cada click las acciones de mostrar/ocultar las opciones del buscador
  $(".multiSearchBtnArrow").toggle(
    function () {$(".multiSearchOptions").css({'display' : 'block'});},
    function () {$(".multiSearchOptions").css({'display' : 'none'});}
  );

  // EXP BY EMAIL
  $("#toEmail").toggleVal();
  $("#toMessage").toggleVal();
  $("#experienceByMailForm").submit(function() {
    $(this).find(".toggleval").each(function() {
      if($(this).val() == $(this).data("defText")) {
        $(this).val("");
      }
    });
  });

  $('#experienceByMail h3').click(function(){
    $('#experienceByMailForm').toggle();
    return false;
  })
  $('#experienceByMailFormCancel').click(function(){
    $('#experienceByMailForm').toggle();
    return false;
  })

  // STAGES
  $('.add_stage_to_trip').click(function(){
    $('#addedStages').show();
    $('#add_new_stage_link').hide();
    $('#save_new_stage_link').show();
    $('#cancel_new_stage_link').show();
    $('#stage_destination').focus();
    return false;
  })

  $('.cancel_stage_to_trip').click(function(){
    $('#add_new_stage_link').show();
    $('#save_new_stage_link').hide();
    $('#cancel_new_stage_link').hide();
    
    $('#addedStages').hide();
    $('#stageStartDate').val("");
    $('#stage_destination_woeid').val("");
    $('#stage_destination').val("");
    $('#add_stage_error').remove();
    return false;
  })

  $('#create_stage_form').submit(function() {
    if ($('#stageStartDate').val() != "" && $('#stageEndDate').val() != "" && $('#stage_destination_woeid').val() != "" && $('#stageStartDate').val() <= $('#stageEndDate').val()){
      return true;
    } else {
      $('#add_stage_error').remove();
      $('#addedStages').after("<div class='errorBox' id='add_stage_error'>Check the destination, from date or till date</div>");
      return false;
    }
  });

  $('.delete_stage_from_trip').each(function(){set_stage_erasable(this)})
  $('.edit_stage_from_trip').each(function(){set_stage_editable(this);})

  // ADVISORS
  $('.add_suggested_advisor').click(function(){
    var li = $(this).parent();
    var id = li.attr('id').split("_")[0]
    $.post($("#createEditFormStepAdvisors").attr("action"),
           {'trourist_request[requested_id]':id, 'trourist_request[role]':'advisor'},
            function(data){
              $('#advisorsActions').append(data);
              li.remove();
              return false;
            })
  })

  // WOEID
  $('.woeid').autocomplete("/location/search", {
    formatItem: function(row) {return row.name + ', ' +  row.admin1 + ', ' + row.country_code;},
    parse: function(data) {
      return $.map(eval(data), function(row) {
        return {
          data: row,
          value: row.name,
          result: row.name
        }
      });
    }
  }).result(function(e,item){
    $('#' + this.id + '_woeid').val(item.woeid)
    this.value = item.name + ', ' +  item.admin1 + ', ' + item.country_code
  });

  // EXPERIENCE MAP
  $('.remove_map').click(function(){
    $('#experienceMapfieldsAndCo').hide();
    $('#experienceLocation').val('');
  })

  // CALENDAR
  $(".calendarized").datepicker(datepicker_values);

  $(".edit_profile_link").click(function(){
    $('#profile_data').toggle();
    $('#edit_profile').toggle();
  });

  // BOOKMARK
  $('.bookmark_it').each(function(){set_bookmark_it(this)})
  $('.remove_bookmark').each(function(){set_remove_bookmark(this)})
  $('.bookmark_trip').submit(function(){
    var id = this.id.split("_")[0];
    var t_s = $("#"+this.id).children(".bookmark_select").val();
    var t = t_s.split("_")[0];
    var s = t_s.split("_")[1];
    
    var href = "/trips/"+t+"/stages/"+s+"/attached_experiences";
    $.post(href, {'attached_experience[experience_id]':id},
           function(data){
             $('#'+id+'_bookmark_form_button').after("<span class='btnAlternateOption' id='"+id+"_bookmark_form_span'>Bookmarked!</span>");
             setTimeout(function() {
               $('#'+id+'_bookmark_form_span').hide()
             }, 4000);
           });
    return false;
    
  });

  // EXP TABS
  $('#exps_map_view').hide();
  $('#exps_bookmark_view').hide();
  
  $("#experience_list_view").click(function(){
    $('#experience_list_view').addClass("btnActive");
    $('#exps_list_view').show();
    $('#experience_map_view').removeClass("btnActive");
    $('#exps_map_view').hide();
    $('#experience_bookmark_view').removeClass("btnActive");
    $('#exps_bookmark_view').hide();
  });

  $("#experience_map_view").click(function(){
    $('#experience_list_view').removeClass("btnActive");
    $('#exps_list_view').hide();
    $('#experience_map_view').addClass("btnActive");
    $('#exps_map_view').show();
    $('#experience_bookmark_view').removeClass("btnActive");
    $('#exps_bookmark_view').hide();
  });

  $("#experience_bookmark_view").click(function(){
    $('#experience_list_view').removeClass("btnActive");
    $('#exps_list_view').hide();
    $('#experience_map_view').removeClass("btnActive");
    $('#exps_map_view').hide();
    $('#experience_bookmark_view').addClass("btnActive");
    $('#exps_bookmark_view').show();
    $("#bookmarkTabFriends").click();
  });
  $("#experience_bookmark_view_empty").click(function(){
    $('#experience_bookmark_view_empty').toggleClass("btnActive");
    $('#exps_bookmark_view').show();  
    $("#bookmarkTabFriends").click();
  });

  // BOOKMARK TABS   
  $('#bookmarkExperiencesFriends').hide();
  $('#bookmarkExperiencesTrourist').hide();

  $("#bookmarkTabFriends").click(function(){
    $('#bookmarkTabTrourists').removeClass("active");
    $('#bookmarkExperiencesTrourist').hide();
    $('#bookmarkTabFriends').addClass("active");
    $('#bookmarkExperiencesFriends').show();
  });  

  $("#bookmarkTabTrourists").click(function(){
    $('#bookmarkTabFriends').removeClass("active");
    $('#bookmarkExperiencesFriends').hide();
    $('#bookmarkTabTrourists').addClass("active");
    $('#bookmarkExperiencesTrourist').show();
  });  


  // LIMIT TEXTAREAS
  $('.limit_360').limit('360','#chars_left');
  $('.limit_1400').limit('1400','#chars_left');

  // EXTERNAL LINKS
  $('a.external').click(function(){
    window.open(this.href);
    return false;
  });

  // REMOVE ENTER
  $("#createEditExperienceForm input").keypress(function (e) {
    if (e.which == 13) {
      if (this.id=="experienceLocation") {
        $("#search_and_locate_it").click();
      }
      return false;
    }
  });

  // AUTOCOMPLETE SEARCH
  $('#topBarSearchTerm').autocomplete("/location_and_people", {
    dataType: "json",
    parse: function(data) {
      return $.map(data, function(row) {
        return {
          data: row,
          value: row.name,
          result: row.name
        }
      });
    },
    formatItem: function(item) {
      return "<a href='"+item.url+"'>"+item.icon+"<span>"+item.name+"</span></a>"
    },
    minChars: 2,
    resultsClass: "suggestedOptions",
    width: "23em",
    scroll: false,
    selectFirst: false
  }).result(function(e,item){
    location.href = item.url;
  });

});

// SEND INVITATIONS
$(document).ready(function() {     
  $("#invite-form").ajaxForm({success: handleInvitationSent});
 
  function handleInvitationSent(response, statusText) {  
    $("#friendEmail").val('');
    $("#invitation_result").html(response)
                           .fadeIn('fast')
                           .animate({opacity: 1.0}, 3000)
                           .fadeOut('fast', function() {$(this).html('');});
  }
     
});


function toggle_comment_format(){
  $('#comment_format').toggle();  
  if ($("#comments_bullet").hasClass("bullet_hideCont")){
    $('#comments_bullet').removeClass("bullet_hideCont");
    $('#comments_bullet').addClass("bullet_showCont");        
  } else { 
    $('#comments_bullet').removeClass("bullet_showCont");
    $('#comments_bullet').addClass("bullet_hideCont");
  }
}

function set_bookmark_it(obj){
  $(obj).click(function(){
    var id = this.id.split("_")[0];
    $.post(this.href, {'attached_experience[experience_id]':id},
           function(data){
             $('#'+id+'_bookmark_buttons').html(data);
             $('.remove_bookmark').each(function(){set_remove_bookmark(this)});
           });
    return false;
  });
}

function set_remove_bookmark(obj){
  $(obj).click(function(){
    var id = this.id.split("_")[0];
    $.post(this.href, {'_method': 'delete'},
           function(data){
             $('#'+id+'_bookmark_buttons').html(data);
             $('.bookmark_it').each(function(){set_bookmark_it(this)});
           });
    return false;
  });
}

function set_stage_erasable(obj) {
  $(obj).click(function() {
    $.post(this.href, {'_method': 'delete'}, function(data){})
    $(this).parent().parent().parent().remove();
    return false;
  })
}

function set_stage_editable(obj) {
  $(obj).click(function() {
    var li         = $(this).parent().parent().parent();
    var location   = $("#" + li.attr("id") + "_location").html();
    var start_date = $("#" + li.attr("id") + "_start_date").html();
    var end_date   = $("#" + li.attr("id") + "_end_date").html();
    var form       = ' \
      <ul class="formInline""> \
        <li class="line"> \
          <label for="stage_destination">Destination</label> \
          <div class="fieldsAndCo">'+ location +'</div> \
        </li> \
        <li class="line"> \
          <label for="update_stage_start_date">From</label> \
          <div class="fieldsAndCo"> \
            <input class="calendarized" id="update_stage_start_date" name="stage[start_date]" size="30" type="text" value="'+ start_date +'"/> \
          </div> \
          <label for="update_stage_start_date">&nbsp;&nbsp;Till</label> \
          <div class="fieldsAndCo"> \
            <input class="calendarized" id="update_stage_end_date" name="stage[end_date]" size="30" type="text" value="'+ end_date +'"/> \
          </div> \
        </li> \
      </ul>';
    var button = '<ul class="btnList"><li><input type="button" value="SAVE" class="btn btnKhaki saveButton" /></li><li><input type="button" value="CANCEL" class="btn btnKhaki cancelButton" /></li></ul>';
    var revert = $(li).html();

    $(li).html(form+button);
    $(".calendarized").datepicker(datepicker_values);

    $('.saveButton').click(function(){update_stage_changes(li, obj)});
    $('.cancelButton').click(function(){
      $(li).html(revert);
      $('.edit_stage_from_trip').each(function(){set_stage_editable(this)});
    });
    return false;
  });
}

function update_stage_changes(obj, link) {
  sd = $('#update_stage_start_date').val();
  ed = $('#update_stage_end_date').val();
  if (sd <= ed) {
    $.post(link,
      {'stage[start_date]':sd, 'stage[end_date]':ed, '_method': 'put'},
      function(data){
        obj.replaceWith(data)
        $('.edit_stage_from_trip').each(function(){set_stage_editable(this);})
        return false;
      }
    );
  } else {
    obj.prepend("<div class='errorBox'>From date can't be bigger than Till date</div>")
  }
}