﻿var destClassPrefix = "destinazionePopupFilterClass_";
var ideAttr = "data-ide_destinazione";
var zoneClass = "checkboxZona";
var labelIdPrefix = "labelPopupFilterId_";
var checkboxIdPrefix = "zonaPopupFilterId_";

$(function() {
    //pre ogni click sulla destinazione aggiungo la funzione per selezionare tutte le sue zone
    $.each($(".colBoxTitle"), function(index, item) { AddSelectedZoneForDestination(item); });
    //per ogni checkbox aggiungo la funzione che al click ricalcola gli id selezionati
    $.each($("#destination :checkbox"), function(index, item) { CheckboxZoneOnChange(item); });
    //controllo se in pagina ho degli id_zona salvati
    var ids = $("#src_ZoneIds").val().split(",");
    $.each(ids, function(index, id) { SetCheckbox(id); });
    //aggiorno le icone delle checkbox tramite una funzione della libreria StyledCheckbox.js
    //Custom.clear();
});

function SetCheckbox(id) {
    $("#" + checkboxIdPrefix + id).attr("checked", true);
}

function AddSelectedZoneForDestination(item) {
    $(item).click(function() {
        //prendo l'id_destinazione
        var ideDest = $(this).attr(ideAttr);
        //per ogni zona con l'id_destinazione cliccato cambio lo stato dell'attributo checked
        $("." + destClassPrefix + ideDest).attr("checked", !$("." + destClassPrefix + ideDest).first().is(":checked"));
        //aggiorno le icone delle checkbox tramite una funzione della libreria StyledCheckbox.js
        Custom.clear();
        //updateSelectedZone();
        $("." + destClassPrefix + ideDest).trigger('change');
    });
}

function CheckboxZoneOnChange(item) {
    $(item).change(function() {
        //alert($(item).val());
        updateSelectedZone();
    });
}

function updateSelectedZone() {
    var allIds = [];
    var allName = [];
    $("." + zoneClass + ":checked").each(function() {
        allIds.push($(this).val());
        var end = $("#" + labelIdPrefix + $(this).val()).text().indexOf("(");
        var name = $("#" + labelIdPrefix + $(this).val()).text().substring(0, end);
        allName.push(name);
    });
    $(".view_src_ZoneIds").val(allIds);
    $("#src_ZoneIds").val(allIds);
    $(".view_src_ZoneNames").val(allName);
    $("#src_ZoneNames").val(allName);
}

function ResetPopupFilter() {
    $("." + zoneClass + ":checked").each(function() {
        $(this).attr("checked", false);
    });
    Custom.clear();
    $("#src_ZoneIds").val("");
    $("#src_ZoneNames").val("");
    $(".view_src_ZoneIds").val("");
    $(".view_src_ZoneNames").val("");
}
