$.voidF = function(value){ return value; };

$.fn.option = function(options){
  var options = $.extend({
    inverse: false,
    statusClass: 'sel',
    select: $.voidF,
    unselect: $.voidF
  }, options);
  
  var selected = options.inverse;
  var statusClass = options.statusClass;
  var callbacks = {
    select: function(object){
      options.select(object);
      selected = true;
    },
    unselect: function(object){
      options.unselect(object);
      selected = false;
    }
  };
  
  this.click(function(){
    if(selected){
      callbacks.unselect(this);
    } else{
      callbacks.select(this);
    }
    $(this).toggleClass(statusClass);
    return false;
  });
  
  return this;
};

$.fn.chain_checkbox = function(){
  return this.each(function(){
    cbx = $(this);
    var options = {
      id: "#"+cbx.attr('id')+'_options',
      inverse: cbx.attr('checked')
    };
    
    var check = function(tagid){
      (options.inverse)? $(tagid).hide() : $(tagid).show();
    };

    var uncheck = function(tagid){
      (options.inverse)? $(tagid).show() : $(tagid).hide();
    };

    cbx.click(function(){
      ($(this).attr("checked"))? check(options.id) : uncheck(options.id);
    });
  });
};

if(!window.console){
  var console = { debug: $.voidF, error: $.voidF, ward: $.voidF };
  console.log = function(message){ alert(message); };
}

jQuery.easing.def = "easeInOutCubic";

testUserDevice.init(function(){
  $(document).ready(function(){
    var getDate = function(dateText){
      date = dateText.split("/");
      return new Date(date[2], Number(date[1]) - 1, Number(date[0]) + 1);
    };
    $("#day_date_eu").datepicker({
      firstDay: 1,
      onSelect: function(dateText){
        $("#repeat_until").val('').datepicker("destroy");
        $("#repeat_until").datepicker({
          firstDay: 1,
          minDate: getDate(dateText)
        });
      }
    });
    
    $("input.option[type=checkbox]").chain_checkbox();
    
    $("select.slider").each(function(){
      $(this).accessibleUISlider().hide();
    });

    //var accordionOptions = { header: 'h3', autoHeight: false, active: false, alwaysOpen: false };
    
    $("#ac-group-by-zone").option({
      unselect: function(a){
        showOwners = ($(".store-owners").css("display") == "block")? true : false;
        $.getScript(document.url, function(){
          if(showOwners){ $(".store-owners").show(); }
        });
      },
      select: function(a){
        showOwners = ($(".store-owners").css("display") == "block")? true : false;
        $.getScript($(a).attr("href"), function(){
          if(showOwners){ $(".store-owners").show(); }
        });
      }
    });
    
    $("#ac-show-owners").option({
      unselect: function(){
        $('.store-owners').hide();
      },
      select: function(){
        $('.store-owners').show();
      }
    });
    
    $("#ac-hide-drafts").option({
      inverse: true,
      unselect: function(){
        $('#draft-articles').hide();
      },
      select: function(){
        $('#draft-articles').show();
      }
    });
    
    $(".month td a.ajax").click(function(){
      
      if($("#wn")[0]){
        var a = $(this);
        $("#wn-content").hide("slide", {direction: 'up'}, 700, function(){
          $("#wn").remove();
          a.click();
        });
        $(".month").animate({opacity: 1}, 500);
      } else{
        $("#schedule").append(""
          + "<div id='wn'>"
          +   "<div id='wn-busy'></div>"
          +   "<div id='wn-content'>"
          +     "<div id='wn-recipient'></div>"
          +     "<p id='wn-actions'><a href='#cerrar' class='ac-close'><span>Cerrar</span></a></p>"
          +   "</div>"
          + "</div>"
        );
        var wn = $("#wn");
        wn.css({ top: $("#schedule h3").outerHeight() });
        
        $.getScript($(this).attr("href"), function(){
          $("#wn-busy").fadeOut("fast").queue(function(){
            $("#wn-form").submit(function(){
              try{
                 $.ajax({
                   url : $(this).attr("action"),
                   type : "POST",
                   dataType : "script",
                   data : $(this).serializeArray(),
                   success : function(data, status){
                     //Add new time section
                   },
                   error : function(request, status, error){
                     console.log(request.responseText);
                   },
                   complete : function(){
                     //Show the form empty again
                   }
                 });
               } catch(e){
                 console.log(e);
               }
               return false;
            });
            $("#wn-content").show("slide", {direction: 'up', duration: 700});
            $("#wn-form button").hover(
              function(){ $(this).toggleClass('ho'); },
              function(){ $(this).toggleClass('ho'); }
            );
            $(this).dequeue();
          });
          $("#wn-actions a.ac-close").click(function(){
            $("#wn-content").hide("slide", {direction: 'up'}, 700, function(){
              wn.remove();
            });
            $(".month").animate({opacity: 1}, 500);
            return false;
          });
          $(".month").animate({opacity: .4}, 500);
        });
      }
      
      return false;
    });
    
    $(".actions .time-section").each(function(){
      var o = $(this);
      var links = o.find("a");
      o.html('');
      links.each(function(){
        $(this).appendTo(o); // .removeAttr("onclick", "");
        $(this).addClass('ajax-button');
        $(this).not('.del').click(function(){
          $.getScript($(this).attr("href"), function(){
            var form_id = $("form.inline").attr("id");
            var tr_id = "#"+form_id.substring(5, form_id.length);
            $("form.inline a").click(function(){
              $("form.inline").hide().parent().remove();
              $(tr_id).show();
              return false;
            });
            // $("form.inline").submit(function(){
            //   options = {
            //      url: $(this).attr('action'),
            //      type: $(this).attr('method'),
            //      dataType: 'json',
            //      data: $(this).serializeArray(),
            //      success: function(json, status){
            //        $(tr_id).find("th").html(json.time_section.time);
            //        $($(tr_id).find("td")[0]).html(json.time_section.description);
            //      },
            //      error: function(request, status, error){
            //        alert(request.responseText);
            //      },
            //      complete: function(){
            //        $(tr_id).show();
            //        $("#"+form_id).hide().parent().remove();
            //      }
            //    };
            //   $.ajax(options);
            //   return false;
            // });
          });
          return false;
        });
      });
      // o.find("a.del").click(function(){
      //   $.post($(this).attr("href"), { _method: 'delete', authenticity_token: $(this).attr("token") }, null, "script");
      //   return false;
      // });
    });
  
    $("input[type=text]").addClass("typetext");
  
    $("#time_section_time_hour").change(function(){
      $("#time_section_duration_hour").val($(this).val());
    });
    
    $("#time_section_time_minutes").change(function(){
      $("#time_section_duration_minutes").val($(this).val());
    });
    
    $("input.autocomplete").each(function(){
      var input = $(this);
      var url = input.attr("rel");
      $.get(url, {}, function(data){
        input.autocomplete({
          data: data,
          matchContains: true// ,
          //  formatItem: function(row){
          //    item = (result[1][1])? result[0] : "<span class='tag yellow'>Incompleto</span>" + result[0];
          //    return item;
          //    return row[0] + "<strong>vai</strong>";//"<span><span class='tag yellow'>Incompleto</span>" + result[0] + "</span>";
          //  }
        });
        input.autocomplete("result", function(e,data,text){
          window.location = data[1][0];
        });
      }, 'json');
    });
    //autocomplete({url: $("#search_store").attr("rel")});
    // if($('.gal-window')[0]){
    //   $('.gal-window .thumbs a').click(function(){
    //     $('.gal-window .selected').removeClass('selected');
    //     $(this).addClass('selected');
    //     $('.gal-window .image-big img').attr('src', $(this).attr('href').split('#')[1]);
    //   });
    // }
    var map = $('#gmap');
    if(map[0]){
      var coords = $.makeArray(map.children('div').children());
      var gmapi = new GMap(map[0]);
      gmapi.setCenter(new GLatLng(43.460753,-8.2538424), 15);
      gmapi.setUIToDefault();
      gmapi.setMapType(G_HYBRID_MAP);
      if(map.hasClass('multiple')){
        // Multibple markers
        gmapi.setZoom(14);
        if(coords.length > 0){
          $.each(coords, function(i, coord){
            var lat = $('.latitude', coord).text();
            var lng = $('.longitude', coord).text();
            var card = $('.card', coord).html();
            var loc = new GLatLng(lat, lng);
            marker = new GMarker(loc);
            GEvent.addListener(marker, 'click', function(){
              marker.openInfoWindow(card);
            });
            gmapi.addOverlay(marker);
          });
        }
      } else {
        var marker = null;
        if(coords.length > 0){
          var lat = $('.latitude', coords[0]).text();
          var lng = $('.longitude', coords[0]).text();
          var loc = new GLatLng(lat, lng);
          marker = new GMarker(loc);
          gmapi.setCenter(loc);
          gmapi.addOverlay(marker);
        }
      }
      if(map.hasClass('editable')){
        GEvent.addListener(gmapi, 'click', function(overlay, latlng){
          if(!marker){
            marker = new GMarker(latlng);
            gmapi.addOverlay(marker);
          }
          marker.setLatLng(latlng);
          $('#store_latitude').val(latlng.lat());
          $('#store_longitude').val(latlng.lng());
        });
      }
    }
  });
});
