/**
* # Moving choices
*
* Copy and paste the first available item to the end of the choices.
*
*--------------------------------------------------------------------------*/
$.fn.addChoice = function(){
  var item = $(this);
  var hidden = item.filter(".accessible:first")
    .removeClass("accessible")
    .remove(); 
  var choosen = item.filter(":not(.accessible):last");
  hidden.insertAfter("li:not(.accessible):last", this);
  item.removeRemoveChoice();
}
/**
* # Remove Choice
*--------------------------------------------------------------------------*/
$.fn.removeChoice = function(){
  var item = $(this).parents('li');
  item.addClass("accessible");
  $("li", item.parents("ul")).removeRemoveChoice();
  
}
/**
* # Remove Remove Choice
*--------------------------------------------------------------------------*/
$.fn.removeRemoveChoice = function(){
  var item = $(this);
  var links = $("a.remove_choice", item);
  if(item.filter(":not(.accessible)").length > 1) {
    links.removeClass("accessible");
  } else {
    links.addClass("accessible");        
  }
}
/**
* # Hide date combo
*--------------------------------------------------------------------------*/
$.fn.hideDateCombo = function(){
  $("select[id$=when_1i],select[id$=when_2i],select[id$=when_3i]").addClass("accessible");
}

/**
* $(wadus).jmapAddress(address)
* Address location of a jmap 
*--------------------------------------------------------------------------*/
if($.fn.jmap !== undefined){
    $.prototype.jmapAddress = function(address){
      var item = $(this)
      item.jmap('SearchAddress', {
        'query': address,
        'returnType': 'getLocations'
      }, function(result, options) {
        var valid = Mapifies.SearchCode(result.Status.code);
        if (valid.success) {
          $.each(result.Placemark, function(i, point){
            item.jmap({'mapCenter': [point.Point.coordinates[1], point.Point.coordinates[0]], 'mapZoom': 15 });
            item.jmap('AddMarker',{
              'pointLatLng':[point.Point.coordinates[1], point.Point.coordinates[0]]
            });
          });
        }
      });
    }
}

$(function(){
  /**
  * # Doing the cufon thing
  *--------------------------------------------------------------------------*/
  Cufon.replace('h2');

  /**
  * # Hiding choices 
  *--------------------------------------------------------------------------*/
  // $("#new_event ul.choices li:not(:first)").addClass("accessible");
  // $("#new_event ul.choices li").removeRemoveChoice();

  $(".add_choice").click(function(){
    $("#new_event ul.choices li").addChoice();
    return false;
  });
  $(".remove_choice").live("click", function(){
    $(this).removeChoice()
    return false;
  });
  $("form#new_event").validate({
    success: function(label) {
      var message = '&nbsp;'; // set &nbsp; as text for IE
      label.remove();
    },
    rules: {
      "event[title]": {
        required: true
      },
      "event[creator_name]": {
        required: true
      },
      "event[creator_email]": {
        required: true,
        email: true
      }
    }	
  });
  $("form#new_voter").validate({
    success: function(label) {
      var message = '&nbsp;'; // set &nbsp; as text for IE
      label.remove();
    },
    rules: {
      "voter[email]": {
        required: true,
        email: true
      }
    }	
  });

  /**
  * # Selecting public url
  *--------------------------------------------------------------------------*/
  $(".public_url input, .admin_url input").click(function(){
    this.select();
  });


  /**
  * # Event Choices Maps
  *--------------------------------------------------------------------------*/
  if($.fn.jmap !== undefined){
  
      $(".event_choices_list .event_choice_map").each(function(){
        $(this).jmap('init');
        $(this).jmapAddress($(this).siblings('.event_choice_address').text());
      });
  }

  /**
  * # Calendars
  *--------------------------------------------------------------------------*/
  // $('div.choice_datetime_select').prepend("<input type='text' value='Select the date' class='calendar'/>");
  $('div.choice_datetime_select input.calendar').removeClass('accessible');
  $('.calendar').live("click", function() {
    var item = $(this);
    var today = new Date();
    
    item.DatePicker({
      date: today.getFullYear() + '-' + (today.getMonth()+1) + '-' + today.getDate(),
      onChange: function(formatted, selected_date) {
        year = selected_date.getFullYear();
        month = selected_date.getMonth()+1;
        day = selected_date.getDate();
        $("select[id$=when_1i]", item.closest("li")).val(year);
        $("select[id$=when_2i]", item.closest("li")).val(month);
        $("select[id$=when_3i]", item.closest("li")).val(day);
        item.val(formatted);
        item.DatePickerHide()
      }
    });
    item.trigger("click");
  });
  $().hideDateCombo();
  
  /**
  * # Clear example of where
  *--------------------------------------------------------------------------*/
  $("input[id$=_where]:first").one("click", function(){
    $(this).val('');
  });

});
