$(document).ready(function(){
  //when any 'datetime' field gets clicked it will open the datatime dropdown
  $(".datetime").datepicker({
    duration: '',
    showTime: true,
    constrainInput: true,
    yearRange: "-20:+2"
  });
  
  //when any 'date' field gets clicked it will open the date dropdown
  $(".date").datepicker({
    duration: '',
    showTime: false,
    constrainInput: true,
    yearRange: "-20:+2"
  });
  
  //when any ajax form get submitted, handle the request
  $(".ajax").live('click',function(){
    var form = $(this).parents("form");
    var action = form.attr("action");
    //this will update CKEditor's content so the correct data is carried accross
    for(instance in CKEDITOR.instances){
      CKEDITOR.instances[instance].updateElement();
    }
    form_data = form.serialize();
    $.ajax({
      type: "post",
      url: action,
      data: form_data,
      success: function(returnText){
        if(returnText.indexOf("error") >= 0){
          $.fn.colorbox({html:returnText});
        }
        else{
          document.location = returnText;
        }
      },
      error: function(){
        $.fn.colorbox({html:"There was an error while trying to submit your form, please try again."});
      }
    });
    return false;
  });
  
  //when any 'colorbox' link gets clicked open a colorbox modal window
  $(".colorbox").colorbox();
  $(".colorbox_iframe").colorbox({maxWidth:'100%',maxHeight:'100%',iframe:'true',height:'590px',width:'642px'});
  
  $('#data_table').dataTable();
  
  $('.extra').change(function(){
    var extra_array = $('#extra').val().split(',');
    var extra = $(this);
    extra.children('option').each(function(){
      //alert($(this).val());
      for(var i in extra_array){
        if(extra_array[i] == $(this).val()){
          //remove from array
          extra_array.splice(i,1);
          $('#extra').val(extra_array.join(','));
        }
      }
    });
    var extra_value = ($("#extra").val() == "") ? $(this).val() : (($(this).val() == '') ? $('#extra').val() : $("#extra").val() + ',' + $(this).val());
    $("#extra").val(extra_value);
    //alert($('#extra').val());
  });
  
});
