function doubleSelectionList(listId) {
  $("select[id*=" + listId +"]").each(function() {
    var list = $(this);
    var secondList = $(list).parent().siblings().next("div").children("select");
    if ((list.find("option").length + secondList.find("option").length) == 0) {
      list.attr("disabled", "disabled");
      secondList.attr("disabled", "disabled");
    }
    listId = listId.replace(/\.from$/,"");
    list.dblclick(function() {
      return !list.find("option:selected").remove().appendTo(secondList);
    });
    secondList.dblclick(function() {
      return !secondList.find("option:selected").remove().appendTo(list);
    });
    $("td [id*=" + listId +"] #add").click(function() {
      return !list.find("option:selected").remove().appendTo(secondList);
    });
    $("td [id*=" + listId +"] #remove").click(function() {
      return !secondList.find("option:selected").remove().appendTo(list);
    });
  });
  $("form input[type='submit']").click(function() {
    $("select[id*=" + listId +"]").each(function() {
      $(this).find('option').each(function(i) {
       $(this).removeAttr("selected");
      });
      $(this).parent().siblings().next("div").children("select").find("option").each(function(i) {
        $(this).attr("selected", "selected");
      });
    });
  });
}

function bindDoubleSelect(dependent, dependsOn) {
  $("select[id*=" + dependsOn + "]").each(function() {
    var id = $(this).val();
    $("select[id*=" + dependent +"]").each(function() {
      var list = $(this);
      var secondList = $(list).parent().siblings().next('div').children('select');
      if (id == 0 || (list.find('option').length + secondList.find('option').length) == 0) {
        list.attr("disabled", "disabled");
        secondList.attr("disabled", "disabled");
      }
      dependentId = dependent.replace(/\.from$/,"");
      list.dblclick(function() {
        return !list.find("option:selected").remove().appendTo(secondList);
      });
      secondList.dblclick(function() {
        return !secondList.find("option:selected").remove().appendTo(list);
      });
      $("td [id*=" + dependentId +"] #add").click(function() {
        return !list.find("option:selected").remove().appendTo(secondList);
      });
      $("td [id*=" + dependentId +"] #remove").click(function() {
        return !secondList.find("option:selected").remove().appendTo(list);
      });
    });
  });
  $("form input[type='submit']").click(function() {
    $("select[id*=" + dependent +"]").each(function() {
      $(this).find("option").each(function(i) {
       $(this).removeAttr("selected");
      });
      $(this).parent().siblings().next("div").children("select").find("option").each(function(i) {
        $(this).attr("selected", "selected");
      });
    });
  });
  $("select[id*=" + dependsOn + "]").change(function() {
    var id = $(this).val().replace(/[^0-9]/g,'');
    $("select[id*=" + dependent + "]").each(function() {
      var list = $(this);
      var secondList =  list.parent().siblings().next('div').children('select');
      list.attr("disabled", "disabled");
      secondList.attr("disabled", "disabled");
      if (id > 0) {
        dependentId = dependent.replace(/\.from$/,"");
        $(this).parent("span").addClass("loading");
        $.get("/selection-list-external/" + dependentId + "/" + id + ".html", function(response, statusCode) {
          var options = $(response).find("option");
          var result = "";
          $(options).each(function() {
            result += '<option value="' + $(this).attr("value") + '">' + $(this).text() + "</option>";
          });
          list.html(result);
          list.parent("span").removeClass("loading");
          if ($(options).length > 0) {
            list.removeAttr('disabled');
            secondList.removeAttr('disabled');
          }
          secondList.html('');
        });
      }
      else {
        list.find("option").removeAttr("selected");
        list.html('');
        secondList.html('');
      }
    });
  });
}

function bindCheckbox(checkbox, dependent) {
  $("input[id*=" + checkbox + "]").click(function() {
    var checked = $(this).attr("checked");

    var realDependent = this.id.substring(0, this.id.indexOf(".") + 1) + dependent;
    $("[id*=" + realDependent + "]").each(function() {
      if (this.tagName != "SPAN") {
        var newId = this.id;
        newId = newId.substring(realDependent.length + 1);

        if($(this).attr("disabled"))
          $(this).removeAttr("disabled");
        else
          $(this).attr("disabled", true);

        $(this).toggleClass("disabled");
        if (newId.match("^false"))
          newId = newId.replace(/^false/,"true");
        else if (newId.match("^true"))
          newId = newId.replace(/^true/,"false");

        newId = realDependent + '.' + newId;
        this.id = newId;
        newId = newId.replace(/:input$/,"");
        $(this).attr("name", newId);
      }
    });
  });
}

function bindSelect(dependent, dependsOn) {
  $("select[id*=" + dependsOn + "]").each(function() {
    if ($(this).val() == 0) {
      $("select[id*=" + dependent +"]").each(function() {
        this.disabled = true;
      });
    }
  });
  $("select[id*=" + dependsOn + "]").change(function() {
    var id = $(this).val().replace(/[^0-9]/g,'');
    $("select[id*=" + dependent + "]").each(function() {
      var list = this;
      list.disabled = true;
      if (id > 0) {
        $(this).parent("span").addClass("loading");
        $.get("/selection-list-external/" + dependent + "/" + id + ".html", function(response, statusCode) {
          var options = $(response).find("option");
          var result = "";
          $(options).each(function() {
            result += '<option value="' + $(this).attr('value') + '">' + $(this).text() + '</option>';
          });
          $(list).html(result);
          $(list).parent("span").removeClass("loading");
          list.disabled = false;
        });
      }
      else {
        $("option", list).removeAttr("selected");
      }
    });
  });
}

function reloadPage(id) {
  var ids = id.split(",");
  for (var i in ids) {
    var elemId = ids[i];
    $("select[id*=" + elemId + "]").change(function() {
      $($(this).parents("form").get(0))
        .append('<input type="hidden" name="forms_submit_id" id="forms_submit_id:input" value="no-validation"/>')
        .submit();
    });
  }
}

function setCalendar() {
  $('input.calendar').each(function() {
    var input = $(this);
    var meta = input.metadata();
    var customYearRange = meta.yearRange;
    var customDefaultDate = new Date(meta.defaultDate);
    var customDateFormat = meta.format;
    var customChangeYear = meta.changeYear;
    var yearSet = meta.yearSet;
    var defaultDateSet = meta.defaultDateSet;
    var dateSetIfAfter = meta.dateSetIfAfter;
    var dateFormat = 'dd/mm/yy';
    if (meta.dateFormat)
      dateFormat = meta.dateFormat;

    input.datepicker({
      changeMonth: true,
      showOn: 'both',
      buttonImage: '/.grafika/ikonki/calendar.gif',
      buttonImageOnly: true,
      changeYear: true,
      dateFormat: dateFormat,
      onChangeMonthYear : function(year, month, inst) {
        if (yearSet !== undefined) {
          var target = $('*[id="' + yearSet + ':input"]');
          var date=new Date();
          var targetDate = target.datepicker('getDate');
          if (targetDate != null)
            date.setFullYear(year, targetDate.getMonth() + 1, targetDate.getDay());
          else
            date.setFullYear(year, month - 1, 1);
          target.datepicker('setDate', date);
        }
      },
      onSelect : function(dateText, inst) {
        var splitedDate = dateText.split('/');
        if (splitedDate.length == 3) {
          var date = new Date();
          date.setFullYear(splitedDate[2], splitedDate[1] - 1, splitedDate[0]);
          if (defaultDateSet !== undefined) {
            var target = $('*[id="' + defaultDateSet + ':input"]');
            target.datepicker('option', 'defaultDate', date);
          }
          if (dateSetIfAfter !== undefined) {
            var target = $('*[id="' + dateSetIfAfter + ':input"]');
            var targetDate = target.datepicker('getDate');
            if (targetDate != null && date > targetDate) {
              target.datepicker('setDate', date);
            }
          }
        }
      }
    });

    if (customChangeYear !== undefined)
      input.datepicker('option', 'changeYear', false);
    if (customDateFormat !== undefined)
      input.datepicker('option', 'dateFormat', customDateFormat);
    if (customYearRange !== undefined)
      input.datepicker('option', 'yearRange', customYearRange);
    if (customDefaultDate !== undefined && !isNaN(customDefaultDate))
      input.datepicker('option', 'defaultDate', customDefaultDate);
  });
}

function setTimePicker() {
  $('input.timepicker').each(function(){
    $(this).timepickr({
      suffix : "",
      buttonImage : "/.grafika/ikonki/clock.gif"
    });
  });
}
