/*!
* Sharded JavaScript Library v1.0.2
*
* Copyright (c) 2011 Secondamano
*
* Date: 2011-08-01
*
* Description:  gestisce i comportamenti di alcuni controlli nel nuovo inserimento annuncio in admin
*
* Author: Fernando Arturi, Giuseppe Corbo, Cristian Nobili, Daniele Cammarata
*
* Review: Daniele Cammarata Date: 16/11/2011
*/

//ondocument load
$(document).ready(function() {
    $("#aspnetForm").validate(
        {
            errorLabelContainer: $('div.allarm-div'),
            wrapper: 'p',
            onsubmit: false,
            onfocusout: false,
            onclick: false,
            onkeyup: false
        });

    if (typeof (window.currentInsAdvStep) != 'undefined') {
        if (window.currentInsAdvStep == 2) {
            PrepareProductButtons();
        } else if (window.currentInsAdvStep == 4) {
            PrepareGoogleMap();
        } else if (window.currentInsAdvStep == 3) {
            PrepareFileUpload();
        }
    }

    //prevent enter key
    $('#aspnetForm').keypress(function(event) {
        if (event.keyCode == '13') {
            var srcElem = event.srcElement ? event.srcElement : event.target;
            if ((srcElem.tagName.toUpperCase() == 'SELECT' || srcElem.tagName.toUpperCase() == 'TEXTAREA')
                    && !srcElem.readOnly && !srcElem.disabled)
                return true;
            event.preventDefault();
        }
        return true;
    });

    $("[id$='_btnLogin']").click(function(evt) {
        $("[id$='_txtUserName']").rules('add', { required: true, email: true, messages: { required: "Il campo email è obbligatorio", email: "Il valore inserito non è un email valido"} });
        $("[id$='_txtPassword']").rules('add', { required: true, messages: { required: "Il campo password è obbligatorio"} });
        var isValid = $("#aspnetForm").valid();

        if (!isValid) {
            evt.preventDefault();
        }
        else {
            $("[id$='_txtUserName']").rules('remove', 'required email');
            $("[id$='_txtPassword']").rules('remove', 'required');
        }
    });

    $("[id$='_btnContinue']").click(function() {
        $('#aspnetForm').validate().resetForm();
    });

    $("[id$='_btnConfirm']").click(function(evt) {
        if (ValidateInputForm()) {
            $("#__EVENTTARGET").val($("[id$='_btnConfirm']")[0].name);
        }
        else {
            evt.preventDefault();
        }
    });

    $("[id$='_btnUpdateProfile']").click(function(evt) {
        if (ValidateProfileForm()) {
            $("#__EVENTTARGET").val($("[id$='_btnUpdateProfile']")[0].name);
        }
        else {
            $('label.error').css('color', 'red');
            evt.preventDefault();
        }
    });

    $('input[type=radio]').css({ width: "20px" });
});

function InitializeAddressForm() {
    try {
        if ($("[id$='_ddlCountry']").val() == -1 && $("[id$='_hdProvinceId']").val() == 0) {
            $("[id$='_ddlCountry']").val("1");
            getProvinces();
        }
        else {
            if ($("[id$='_ddlCountry']").val() > 0) {
                getProvinces();
                $("[id$='_ddlProvince']").attr('disabled', false);
                if ($("[id$='_hdDisableUnModFields']").size() > 0) {
                    var disableUnModFields = $("[id$='_hdDisableUnModFields']").val().split("|");
                    $.each(disableUnModFields, function(index, item) {
                        if (item == "ddlCountry")
                            $("[id$='_ddlCountry']").attr('disabled', true);
                    });
                }
            }
            if ($("[id$='_hdProvinceId']").val() > 0) {

                getTowns();
                $("[id$='_ddlTown']").attr('disabled', false);
            }
            if ($("[id$='_hdCityId']").val() > 0) {
                getDistricts();
                $("[id$='_ddlDistrict']").attr('disabled', false);
            }
        }
    } catch (ex) { }
}

// product buttons
function PrepareProductButtons() {
    $('.bsu-product').children('ul').hide();
    $('.bsu-product').hover(
            function() { $(this).children('a').css({ 'text-decoration': 'underline' }); },
            function() { $(this).children('a').css({ 'text-decoration': 'none' }); }
            ).css({ 'cursor': 'pointer' }).click(function() {
                $(this).children('ul').toggle();
                $cai = $(this).children('a').children('img');
                if ($cai.attr('src') == "../Shared/Content/Images/arrow-top.gif")
                    $cai.attr('src', '../Shared/Content/Images/arrow-bottom.gif');
                else if ($cai.attr('src') == "../Shared/Content/Images/arrow-bottom.gif")
                    $cai.attr('src', '../Shared/Content/Images/arrow-top.gif');
            });
    $('.bsu-product').children('a').click(function(e) { e.preventDefault(); });
}
//shared
// prepare functions upload
function PrepareFileUpload() {
    // field 1
    var uploadForm1 = new AjaxUpload($("#uploadFile_1"), {
        action: '../Shared/Webservices/FileUpload.ashx',
        data: { vert: $("[id$='_curVertical']").val() },
        autoSubmit: false,
        onSubmit: function(file, extension) {
            if (CheckUploadByAdv(file, extension, $("#uploadFile_1"))) {
                blockUIUpload();
                return true;
            }
            else {
                $("#uploadFileText_1").val('');
                return false;
            }
        },
        onChange: function(file, extension) {
            $("#uploadFileText_1").val(file);
        },
        onComplete: function(file, response) {
            CheckResponse(file, response);
            $("#uploadFileText_1").val("");
        }
    });
    // field 2
    var uploadForm2 = new AjaxUpload($("#uploadFile_2"), {
        action: '../Shared/Webservices/FileUpload.ashx',
        data: { vert: $("[id$='_curVertical']").val() },
        autoSubmit: false,
        onSubmit: function(file, extension) {
            if (CheckUploadByAdv(file, extension, $("#uploadFile_2"))) {
                blockUIUpload();
                return true;
            }
            else {
                $("#uploadFileText_2").val('');
                return false;
            }
        },
        onChange: function(file, extension) {
            $("#uploadFileText_2").val(file);
        },
        onComplete: function(file, response) {
            CheckResponse(file, response);
            $("#uploadFileText_2").val("");
        }
    });
    // field 3
    var uploadForm3 = new AjaxUpload($("#uploadFile_3"), {
        action: '../Shared/Webservices/FileUpload.ashx',
        data: { vert: $("[id$='_curVertical']").val() },
        autoSubmit: false,
        onSubmit: function(file, extension) {
            if (CheckUploadByAdv(file, extension, $("#uploadFile_3"))) {
                blockUIUpload();
                return true;
            }
            else {
                $("#uploadFileText_3").val('');
                return false;
            }
        },
        onChange: function(file, extension) {
            $("#uploadFileText_3").val(file);
        },
        onComplete: function(file, response) {
            CheckResponse(file, response);
            $("#uploadFileText_3").val("");
        }
    });
    // upload event
    $("#uploadButton").click(function() {
        uploadForm1.disable();
        uploadForm2.disable();
        uploadForm3.disable();
        uploadForm1.submit();
        uploadForm1.enable();
        uploadForm2.submit();
        uploadForm2.enable();
        uploadForm3.submit();
        uploadForm3.enable();
        return false;
    });
}

function CheckUploadByAdv(file, ext, objToClear) {
    ext = ext.toUpperCase();

    switch (ext) {
        case 'JPG': case 'PNG': case 'JPEG': case 'BMP': case 'GIF':
            var maxImg = $("[id$='maxImagesUpload']").val();
            var imgLoaded = $("[id$='imagesLoaded']").val().split('|').length;

            if (maxImg == 0) {
                SetError("Non è possibile inserire foto per questo tipo di annuncio");
                return false;
            }
            if (imgLoaded > maxImg) {
                SetError("Superato il limite per tipo di annuncio");
                return false;
            }
            return true;

        case 'PDF': case 'DOC': case 'TXT':
            var maxDoc = $("[id$='maxDocUpload']").val();
            var docLoaded = $("[id$='documentsLoaded']").val().split('|').length;

            if (maxDoc == 0) {
                SetError("Non è possibile inserire documenti per questo tipo di annuncio");
                return false;
            }
            if (docLoaded > maxDoc) {
                SetError("Superato il limite per tipo di annuncio");
                return false;
            }
            return true;

        case 'MOV': case 'AVI': case 'MP4': case 'MPEG': case 'MPG': case 'WMV':
            var maxV = $("[id$='maxVideoUpload']").val();
            var videosLoaded = $("[id$='videosLoaded']").val().split('|').length;

            if (maxV == 0) {
                SetError("Non è possibile inserire video per questo tipo di annuncio");
                return false;
            }
            if (videosLoaded > maxV) {
                SetError("Superato il limite per tipo di annuncio");
                return false;
            }
            return true;

        default:
            SetError("Tipo di file non valido");
            return false;
    }
}

function SetError(msg) {
    $("#lblResult1").html('');
    $("#lblResult1").append(msg);
    $("#lblResult1").css({ 'visibility': 'visible' });
}

function CheckResponse(file, response) {
    unblockUIUpload();
    $("#lblResult1").css({ 'visibility': 'hidden' });
    var result = "";
    var message = "";
    var type = "";
    var videoUrl = "";
    if (response.toLowerCase().indexOf('<pre') != -1) {
        response = response.substr(response.indexOf('>') + 1).replace('</pre>', '').replace('</PRE>', '');
        result = response.split('|')[0].toLowerCase();
        message = response.split('|')[1];
        try {
            type = response.split('|')[2];
        }
        catch (e) { }
        try {
            videoUrl = response.split('|')[3];
        }
        catch (e) { }
    }
    if (result == "ok" && type.toUpperCase() == "IMAGE") {
        CreateThumbDiv(file, message, 'imagesPreview');
    } else if (result == "ok" && type.toUpperCase() == "TEXT") {
        CreatePdfThumbDiv(file, message, 'documentsPreview');
    } else if (result == "ok" && type.toUpperCase() == "VIDEO") {
        CreateVideoThumbDiv(file, message, videoUrl, 'videosPreview');
    }
    else if (result == "ko") {
        SetError(message);
    } else {
        //alert("else");
    }
}

function CreateThumbDiv(filename, urlthumb, divFather) {
    var htmlOut = "<div class=\"imageForm\"><img alt=\"" + filename + "\" src=\"" + urlthumb + "\">";
    htmlOut += "<div class=\"cl\"></div><label>" + filename + "</label><a class=\"btn_elim\" title=\"Elimina\" >Elimina</a> </div>";
    $("#" + divFather).append(htmlOut);

    var urls = $("[id$='imagesLoaded']").val();
    var pipe = urls.substring(urls.length - 1, urls.length);

    if (urls.length > 0 && pipe != "|") {
        $("[id$='imagesLoaded']").val($("[id$='imagesLoaded']").val() + "|");
    }
    $("[id$='imagesLoaded']").val($("[id$='imagesLoaded']").val() + urlthumb + "|");
    $('.imageForm:not([id="summary"]) img').click(function() {
        $(this).parent().siblings().removeClass('selected');
        $(this).parent().addClass('selected');
        $("[id$='imageCover']").val($(this)[0].src);
        $(this).parent().parent().children("H2").children('.subt').text($(this).parent().children('label').text() + ' è stata selezionata come immagine di copertina!');
    });
    $('.imageForm .btn_elim').click(function() {
        if ($(this).parent().children("img")[0].href == $("[id$='imageCover']").val()) {
            $(this).parent().removeClass('selected');
            $("[id$='imageCover']").val("");
            $(this).parent().parent().children("H2").children('.subt').text('Seleziona una foto per inserirla come copertina!');
        }
        $("[id$='imagesLoaded']").val($("[id$='imagesLoaded']").val().replace($(this).parent().children("img")[0].src + "|", ""));
        $(this).parent().remove();
    });
}


function CreatePdfThumbDiv(filename, urlthumb, divFather) {
    var urlPdf = "/images/imagedoc.gif";
    var htmlOut = "<div class=\"documentForm\"><img alt=\"" + urlPdf + "\" src=\"" + urlPdf + "\">";
    htmlOut += "<div class=\"cl\"></div><label>" + filename + "</label><a class=\"btn_elim\" title=\"Elimina\" >Elimina</a> </div>";
    $("#" + divFather).append(htmlOut);

    $("[id$='documentsLoaded']").val($("[id$='documentsLoaded']").val() + urlthumb + "|");

    $('.documentForm .btn_elim').click(function() {
        $("[id$='documentsLoaded']").val($("[id$='documentsLoaded']").val().replace($(this).parent().children("img")[0].href + "|", ""));
        $(this).parent().remove();
    });
}

function CreateVideoThumbDiv(filename, urlthumb, videoUrl, divFather) {
    var urlThumbVideo = "/Images/imageVid.gif";
    var htmlOut = "<div class=\"videoForm\"><img alt=\"" + urlThumbVideo + "\" src=\"" + urlThumbVideo + "\">";
    htmlOut += "<div class=\"cl\"></div><label>" + filename + "</label><a class=\"btn_elim\" title=\"Elimina\" >Elimina</a> </div>";
    $("#" + divFather).append(htmlOut);

    $("[id$='videosLoaded']").val($("[id$='videosLoaded']").val() + videoUrl + "|");

    $('.videoForm .btn_elim').click(function() {
        $("#videosLoaded").val($("#videosLoaded").val().replace($(this).parent().children("img")[0].href + "|", ""));
        $(this).parent().remove();
    });
}

function deleteMedia(divToDelete, th, mediaLoaded) {
    $("[id$='" + divToDelete + "']").hide();
    var elements = $("[id$='_" + mediaLoaded + "']").val().split("|");

    $.each(elements, function(index, item) {
        if (item == th) {
            $("[id$='_" + mediaLoaded + "']").val($("[id$='_" + mediaLoaded + "']").val().replace(th + '|', ''));
        }
    });
}


function PrepareGoogleMap() {
    try {
        /// initializze gmap
        if ($("[id$='_hdnMapCoords']").length > 0 && $("[id$='_hdnMapCoords']").val() != "") {
            var strAdvCoords = $("[id$='_hdnMapCoords']").val();
            var advCoords = strAdvCoords.split("|");

            $('#map-cp2').jmap('init', {
                'mapType': window.G_NORMAL_MAP,
                'mapCenter': [advCoords[0], advCoords[1]],
                'mapShowjMapsIcon': false,
                'mapZoom': 16
            }).jmap('AddMarker', {
                'pointLatLng': [advCoords[0], advCoords[1]],
                'pointHTML': getAddress(),
                'pointIsDraggable': true
            });
        }
        else {
            $('#map-cp2').jmap('init', {
                'mapType': window.G_NORMAL_MAP,
                'mapCenter': [42.15, 11.83],
                'mapZoom': 5,
                'mapShowjMapsIcon': false
            });
        }
    }
    catch (e) { }
}

function SetMapPoint() {
    var address = getAddress();
    $('#map-cp2').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) {
                $('#map-cp2').jmap('init', {
                    'mapCenter': [point.Point.coordinates[1], point.Point.coordinates[0]],
                    'mapShowjMapsIcon': false
                }).jmap('AddMarker', {
                    'pointLatLng': [point.Point.coordinates[1], point.Point.coordinates[0]],
                    'pointHTML': point.address,
                    'pointIsDraggable': true

                });
                $("[id$='_hdnMapCoords']").val(point.Point.coordinates[1] + '|' + point.Point.coordinates[0]);
            });
        } else {
            $('#address-cp2').val(valid.message);
        }
    });
    return false;
}

// drop down nazione change
$(function() {
    DdlCountryChangeEventHandler();
});

// event handler for ddlCountry change, available for sync and async requests
function DdlCountryChangeEventHandler() {
    //$("[id$='_ddlCountry']").change(getProvinces);
}

function getProvinces() {
    if ($("[id$='_ddlCountry']").val() == "-1") {
        $("[id$='_ddlProvince']").val(-1);
        $("#obbProvince").hide();
        $("[id$='_ddlProvince']").attr('disabled', true);
        return;
    }

    $.ajax({
        type: "POST",
        url: document.URL.indexOf('/annuncio/Inserimento/Pagamento.aspx') != -1 ? "../../Shared/Webservices/WSGetData.asmx/GetProvinces" : "../Shared/Webservices/WSGetData.asmx/GetProvinces",
        data: "{countryCode: '" + $("[id$='_ddlCountry']").val() + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            var pr = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;

            $("[id$='_ddlProvince']").attr('disabled', false).change(getTowns).removeOption(/./).addOption('-1', 'Seleziona');
            if (pr.length == 0) {
                $("[id$='_ddlProvince']").attr('disabled', true);
            }
            $("[id$='_ddlTown']").attr('disabled', true);
            $("[id$='_ddlDistrict']").attr('disabled', true);

            if (pr.length == 1) {
                $("[id$='_ddlProvince']").addOption(pr[0].Value, pr[0].Text, true);
            } else {
                for (var i = 0; i < pr.length; i++) {
                    var val = pr[i].Value;
                    var text = pr[i].Text;

                    if ($("[id$='_hdProvinceId']").val() == val) {
                        $("[id$='_ddlProvince']").addOption(val, text, true);
                    }
                    else {
                        $("[id$='_ddlProvince']").addOption(val, text, false);
                    }

                }
            }

            if ($("[id$='_hdDisableUnModFields']").size() > 0) {
                var disableUnModFields = $("[id$='_hdDisableUnModFields']").val().split("|");
                $.each(disableUnModFields, function(index, item) {
                    if (item == "ddlProvince")
                        $("[id$='_ddlProvince']").attr('disabled', true);
                });
            }
        }
    });

    $('#aspnetForm').validate().resetForm();
    if ($("[id$='_ddlCountry']").val() == '1') {
        $("#obbProvince").show();
    }
    else {
        $("#obbProvince").show();
    }
}


function getTowns() {
    var provinceCode = $("[id$='_ddlProvince']").val();

    if (($("[id$='_hdProvinceId']").val() > 0) && (provinceCode == "-1")) {
        provinceCode = $("[id$='_hdProvinceId']").val();
    }

    $.ajax({
        type: "POST",
        url: "../Shared/Webservices/WSGetData.asmx/GetTowns",
        data: "{provinceCode: '" + provinceCode + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            var pr = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;

            $("[id$='_ddlTown']").attr('disabled', false).change(getDistricts).removeOption(/./).addOption('-1', 'Seleziona');
            if (pr.length == 0) {
                $("[id$='_ddlTown']").attr('disabled', true);
            }
            $("[id$='_ddlDistrict']").attr('disabled', false);

            for (var i = 0; i < pr.length; i++) {
                var val = pr[i].Value;
                var text = pr[i].Text;

                if ($("[id$='_hdCityId']").val() == val) {
                    $("[id$='_ddlTown']").addOption(val, text, true);
                }
                else {
                    $("[id$='_ddlTown']").addOption(val, text, false);
                }
            }

            if ($("[id$='_hdDisableUnModFields']").size() > 0) {
                var disableUnModFields = $("[id$='_hdDisableUnModFields']").val().split("|");
                $.each(disableUnModFields, function(index, item) {
                    if (item == "ddlTown")
                        $("[id$='_ddlTown']").attr('disabled', true);
                });
            }
        }
    });

    $('#aspnetForm').validate().resetForm();
    if ($("[id$='_ddlCountry']").val() == '1') {
        if ($("[id$='_generateTownRequiredValidator']").val() == 'true') {
            $("#obbTown").show();
        }
        else {
            $("#obbTown").hide();
        }
    }
}

function getDistricts() {
    var townCode = $("[id$='_ddlTown']").val();

    if (($("[id$='_hdCityId']").val() > 0) && (townCode == "-1")) {
        townCode = $("[id$='_hdCityId']").val();
    }
    getPostCodes();

    $.ajax({
        type: "POST",
        url: "../Shared/Webservices/WSGetData.asmx/GetDistricts",
        data: "{townCode: '" + townCode + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            var pr = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;

            $("[id$='_ddlDistrict']").attr('disabled', false).removeOption(/./).addOption('-1', 'Seleziona');
            if (pr.length == 0) {
                $("[id$='_ddlDistrict']").attr('disabled', true);
            }

            for (var i = 0; i < pr.length; i++) {
                var val = pr[i].Value;
                var text = pr[i].Text;

                if ($("[id$='_hdDistrictId']").val() == val) {
                    $("[id$='_ddlDistrict']").addOption(val, text, true);
                }
                else {
                    $("[id$='_ddlDistrict']").addOption(val, text, false);
                }
            }

            if ($("[id$='_hdDisableUnModFields']").size() > 0) {
                var disableUnModFields = $("[id$='_hdDisableUnModFields']").val().split("|");
                $.each(disableUnModFields, function(index, item) {
                    if (item == "ddlDistrict")
                        $("[id$='_ddlDistrict']").attr('disabled', true);
                });
            }
        }
    });
}

function getPostCodes() {
    var idTownDistrict = $("[id$='_ddlTown']").val();

    if (($("[id$='_hdCityId']").val() > 0) && (idTownDistrict == "-1")) {
        idTownDistrict = $("[id$='_hdCityId']").val();
    }

    if (typeof (idTownDistrict) !== 'undefined') {

        $.ajax({
            type: "POST",
            url: "../Shared/Webservices/WSGetData.asmx/GetPostCodes",
            data: "{idTownDistrict: '" + idTownDistrict + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(response) {
                var pr = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;

                $("[id$='_ddlPostCode']").attr('disabled', false).removeOption(/./).addOption('-1', 'Seleziona');
                if (pr.length == 0) {
                    $("[id$='_ddlPostCode']").attr('disabled', true);
                }
                for (var i = 0; i < pr.length; i++) {
                    var val = pr[i].Value;
                    var text = pr[i].Text;

                    if ($("[id$='_hdPostalCodeId']").val() == text) {
                        $("[id$='_ddlPostCode']").addOption(val, text, true);
                    }
                    else {
                        $("[id$='_ddlPostCode']").addOption(val, text, false);
                    }

                    if ($("[id$='_ddlPostCode'] option").length == 2) {
                        val = '-1';
                        $("[id$='_ddlPostCode'] option").each(function() {
                            if ($(this).val() != -1) {
                                val = $(this).val();
                            }
                        });
                        $("[id$='_ddlPostCode']").val(val);
                    } else {
                        $("[id$='_ddlPostCode']").val(-1);
                    }
                }

                if ($("[id$='_hdDisableUnModFields']").size() > 0) {
                    var disableUnModFields = $("[id$='_hdDisableUnModFields']").val().split("|");
                    $.each(disableUnModFields, function(index, item) {
                        if (item == "ddlPostCode")
                            $("[id$='_ddlPostCode']").attr('disabled', true);
                    });
                }
            }
        });
    }
}

function getAddress() {
    var address = '';
    if ($("[id$='_txtAddress']").val() != '') {
        address = address + ' ' + $("[id$='_txtAddress']").val();
    }
    if ($("[id$='_ddlPostCode']").val() != '-1') {
        address = address + ' ' + $('option:selected', $("[id$='_ddlPostCode']")).text();
    }
    if ($("[id$='_ddlTown']").val() != '-1') {
        address = address + ' ' + $('option:selected', $("[id$='_ddlTown']")).text();
    }
    if ($("[id$='_ddlProvince']").val() != '-1') {
        if (address !== '') {
            address = address + ' ' + $('option:selected', $("[id$='_ddlProvince']")).text();
        }
        else {
            address = address + ' ' + $('option:selected', $("[id$='_ddlProvince']")).text() + ' ' + $('option:selected', $("[id$='_ddlProvince']")).text();
        }
    }
    if ($("[id$='_ddlCountry']").val() != '-1') {
        address = address + ' ' + $('option:selected', $("[id$='_ddlCountry']")).text();
    }
    return $.trim(address);
}

function uploadFileStarted(sender, args) {
    var uploaderId = sender._element.id;
    var imageLoad = 'loadImg' + uploaderId.substring(uploaderId.length - 1);
    $("#" + imageLoad + "").css({ 'visibility': 'visible' });
}

function uploadFileCompleted(sender, args) {
    var uploaderId = sender._element.id;
    var imageLoad = 'loadImg' + uploaderId.substring(uploaderId.length - 1);

    $.ajax({
        type: "POST",
        url: "../Shared/Webservices/WSGetData.asmx/CheckFileToUpload",
        data: "{\"fileName\":\"" + args.get_fileName() + "\",\"mimeType\":\"" + args.get_contentType() + "\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            var returnMessage = msg.d;
            if (returnMessage.substring(0, 2) != "OK") {
                sender._onError(returnMessage.split('|')[1]);
            }
        },
        error: function() {
            sender._onError("error checking file.");
        }
    });
    $("#" + imageLoad + "").css({ 'visibility': 'hidden' });
}

function uploadFileError(sender, args) {
    var uploaderId = sender._element.id;
    var imgResult = "imgResult" + uploaderId.substring(uploaderId.length - 1);
    var lblResult = "lblResult" + uploaderId.substring(uploaderId.length - 1);
    var imageLoad = 'loadImg' + uploaderId.substring(uploaderId.length - 1);
    $("#" + imgResult + "").css({ 'visibility': 'visible' });
    $("#" + imgResult + "").attr("src", "Shared/Content/Images/error.gif");
    $("#" + imgResult + "").css({ 'visibility': 'visible' });
    $("#" + lblResult + "").text(args.get_errorMessage());
    $("#" + lblResult + "").css({ 'visibility': 'visible' });
    $("#" + imageLoad + "").css({ 'visibility': 'hidden' });
}

//functions data loading
function loadAttributeValuesForChild(advertTypeId, fatherValue, childId) {
    var retArray = new Array();
    $.ajax({
        type: "POST",
        url: "../Shared/Webservices/WSGetData.asmx/GetAttributeValuesForChild",
        data: "{\"advertTypeId\":\"" + advertTypeId + "\",\"fatherValueId\":\"" + fatherValue + "\",\"childId\":\"" + childId + "\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            retArray = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
            var hasValues = retArray.length > 0;
            notifyAjaxCallCompleted(childId, hasValues);
        }
    });
    return retArray;
}


function selectAttributeValueFromRule(fillRule, attribute, emptyValue, isReadOnly) {
    $('#adtInput_' + attribute).val(emptyValue);
    var fillDataExpression = fillRule.split(':')[0].toString() + ":";
    var fillDataFathers = "";
    try {
        fillDataFathers = fillRule.split(':')[1].toString();
    }
    catch (e) {
    }
    for (var i = 0; i < fillDataFathers.split(';').length; i++) {
        var attr = fillDataFathers.split(';')[i].toString();
        try {
            fillDataExpression = fillDataExpression + $('#adtInput_' + attr).val();
            if (i < fillDataFathers.split(';').length - 1) {
                fillDataExpression = fillDataExpression + ";";
            }
        }
        catch (e) {
        }
    }
    var hasValues = false;

    $.ajax({
        type: "POST",
        url: "/Shared/Webservices/WSGetData.asmx/GetValues",
        data: "{\"fillDataExpression\":\"" + fillDataExpression + "\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            var retValues = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
            hasValues = retValues.length > 0;
            notifyAjaxCallCompleted(attribute, hasValues);
            if (hasValues) {
                if ($('#adtHiddenInput_' + attribute).val() != undefined && $('#adtHiddenInput_' + attribute).val() != '') {
                    $('#adtInput_' + attribute).val($('#adtHiddenInput_' + attribute).val());
                }
                else {
                    $('#adtInput_' + attribute).val(retValues[0].Value);
                }
                if (isReadOnly == true) {
                    $('#adtInput_' + attribute).attr('disabled', true);
                }
            }
        }
    });
    if (!hasValues) {
        if ($('#adtHiddenInput_' + attribute).val() != undefined && $('#adtHiddenInput_' + attribute).val() != '') {
            $('#adtInput_' + attribute).val($('#adtHiddenInput_' + attribute).val());
            if (isReadOnly == true) {
                $('#adtInput_' + attribute).attr('disabled', true);
            }
        }
    }
}

function loadDropDownAttributeValueFromRule(fillRule, attribute, clearDropDown, isReadOnly, customSuccessHandler) {
    if (clearDropDown == true) {
        $('#adtInput_' + attribute).removeOption(/./).addOption('-1', 'Seleziona');
    }
    else {
        $('#adtInput_' + attribute).val('-1');
    }
    var fillDataExpression = fillRule.split(':')[0].toString() + ":";
    var fillDataFathers = "";
    try {
        fillDataFathers = fillRule.split(':')[1].toString();
    }
    catch (e) { }
    for (var i = 0; i < fillDataFathers.split(';').length; i++) {
        var attr = fillDataFathers.split(';')[i].toString();
        try {
            fillDataExpression = fillDataExpression + $('#adtInput_' + attr).val();
            if (i < fillDataFathers.split(';').length - 1) {
                fillDataExpression = fillDataExpression + ";";
            }
        }
        catch (e) { }
    }

    $.ajax({
        type: "POST",
        url: "../Shared/Webservices/WSGetData.asmx/GetValues",
        data: "{\"fillDataExpression\":\"" + fillDataExpression + "\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            var retValues = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
            var hasValues = retValues.length > 0;
            if (hasValues) {
                $('#adtInput_' + attribute).attr('disabled', false).removeOption(/./).addOption('-1', 'Seleziona');
                for (i = 0; i < retValues.length; i++) {
                    var val = retValues[i].Value;
                    var text = retValues[i].Text;
                    $('#adtInput_' + attribute).addOption(val, text, false);

                }
                if ($('#adtHiddenInput_' + attribute).val() != "") {
                    $('#adtInput_' + attribute).val($('#adtHiddenInput_' + attribute).val());
                    if ($('#adtInput_' + attribute).val() != $('#adtHiddenInput_' + attribute).val()) {
                        $('#adtInput_' + attribute).each(function() {
                            $('option', this).each(function() {
                                if ($(this).text() == $('#adtHiddenInput_' + attribute).val()) {
                                    $(this).attr('selected', 'selected');
                                };
                            });
                        });
                    }
                    if (isReadOnly == true) {
                        $('#adtInput_' + attribute).attr('disabled', true);
                    }
                }
            }
            else {
                if ($('#adtHiddenInput_' + attribute).val() != "") {
                    $('#adtInput_' + attribute).addOption($('#adtHiddenInput_' + attribute).val(), $('#adtHiddenInput_' + attribute).val(), true);
                }
            }
            notifyAjaxCallCompleted(attribute, hasValues);
            if (typeof (customSuccessHandler) != 'undefined') {
                customSuccessHandler();
            }
        }
    });
    $('#adtHiddenInputRule_' + attribute).val(fillDataExpression);
}

function loadDropDownEditAttributeValueFromRule(fillRule, attribute, clear, isReadOnly, customSuccessHandler) {
    if (clear == true) {
        $('#adtInputDDL_' + attribute).removeOption(/./).addOption('-1', 'Seleziona');
    }
    else {
        $('#adtInputDDL_' + attribute).val('-1');
    }
    var fillDataExpression = fillRule.split(':')[0].toString() + ":";
    var allFathersHaveValue = true;
    var fillDataFathers = "";
    try {
        fillDataFathers = fillRule.split(':')[1].toString();
    }
    catch (e) { }
    for (var i = 0; i < fillDataFathers.split(';').length; i++) {
        var attr = fillDataFathers.split(';')[i].toString();
        try {
            fillDataExpression = fillDataExpression + $('#adtInput_' + attr).val();
            if ($('#adtInput_' + attr).val() == '-1') {
                allFathersHaveValue = false;
            }
            if (i < fillDataFathers.split(';').length - 1) {
                fillDataExpression = fillDataExpression + ";";
            }
        }
        catch (e) { }
    }

    $.ajax({
        type: "POST",
        url: "../Shared/Webservices/WSGetData.asmx/GetValues",
        data: "{\"fillDataExpression\":\"" + fillDataExpression + "\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            var retValues = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
            var hasValues = retValues.length > 0;
            if (hasValues) {
                $('#adtInputTXT_' + attribute).hide();
                $('#adtInputDDL_' + attribute).show();
                $('#adtInputDDL_' + attribute).attr('disabled', false).removeOption(/./).addOption('-1', 'Seleziona');
                for (i = 0; i < retValues.length; i++) {
                    var val = retValues[i].Value;
                    var text = retValues[i].Text;
                    $('#adtInputDDL_' + attribute).addOption(val, text, false);

                }
                if ($('#adtHiddenInput_' + attribute).val() != "") {
                    $('#adtInputDDL_' + attribute).val($('#adtHiddenInput_' + attribute).val());
                    $('#adtInput_' + attribute).val($('#adtHiddenInput_' + attribute).val());
                }
            }
            else {
                if (allFathersHaveValue == false) {
                    $('#adtInputTXT_' + attribute).hide();
                    $('#adtInputDDL_' + attribute).show();
                    $('#adtInputDDL_' + attribute).attr('disabled', false).removeOption(/./).addOption('-1', 'Seleziona');
                }
                else {
                    $('#adtInputDDL_' + attribute).hide();
                    $('#adtInputTXT_' + attribute).show();
                    if ($('#adtHiddenInput_' + attribute).val() != "") {
                        $('#adtInputTXT_' + attribute).val($('#adtHiddenInput_' + attribute).val());
                        $('#adtInput_' + attribute).val($('#adtHiddenInput_' + attribute).val());
                    }
                }

            }
            notifyAjaxCallCompleted(attribute, hasValues);
            if (typeof (customSuccessHandler) != 'undefined') {
                customSuccessHandler();
            }
        }
    });
    $('#adtHiddenInputRule_' + attribute).val(fillDataExpression);
}

function loadMultiSelectAttributeValueFromRule(fillRule, attribute, clearAll, isReadOnly) {
    if (clearAll == true) {
        $.each($("input[id^='adtInput_" + attribute + "_']"), function(index) {
            $("#adtInput_" + attribute + "_" + (index + 1).toString()).attr("checked", false);
        });
    }
    var fillDataExpression = fillRule.split(':')[0].toString() + ":";
    var fillDataFathers = "";
    try {
        fillDataFathers = fillRule.split(':')[1].toString();
    }
    catch (e) { }
    for (var i = 0; i < fillDataFathers.split(';').length; i++) {
        var attr = fillDataFathers.split(';')[i].toString();
        try {
            //                        if ($('#adtInput_' + attr).val() == '' || $('#adtInput_' + attr).val() == '-1') {
            //                            return;
            //                        }
            fillDataExpression = fillDataExpression + $('#adtInput_' + attr).val();
            if (i < fillDataFathers.split(';').length - 1) {
                fillDataExpression = fillDataExpression + ";";
            }
        }
        catch (e) { }
    }

    $.ajax({
        type: "POST",
        url: "../Shared/Webservices/WSGetData.asmx/GetValues",
        data: "{\"fillDataExpression\":\"" + fillDataExpression + "\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            var retValues = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
            var hasValues = retValues.length > 0;

            if (hasValues) {
                for (i = 0; i < retValues.length; i++) {
                    $.each($("input[id^='adtInput_" + attribute + "_']"), function(index) {

                        if ($('#adtHiddenInput_' + attribute + '_' + (index + 1).toString()).val() != undefined && $('#adtHiddenInput_' + attribute + '_' + (index + 1).toString()).val() == '1') {
                            $("#adtInput_" + attribute + "_" + (index + 1).toString()).attr("checked", true);
                            if (isReadOnly == true) {
                                $("#adtInput_" + attribute + "_" + (index + 1).toString()).attr('disabled', true);
                            }
                            return;
                        }
                        else if (retValues[i].Value == $("#adtInput_" + attribute + "_" + (index + 1).toString()).val()) {
                            $("#adtInput_" + attribute + "_" + (index + 1).toString()).attr("checked", true);
                            if (isReadOnly == true) {
                                $("#adtInput_" + attribute + "_" + (index + 1).toString()).attr('disabled', true);
                            }
                            return;
                        }
                    });

                }
                notifyAjaxCallCompleted(attribute, hasValues);
            }
            else {
                $.each($("input[id^='adtInput_" + attribute + "_']"), function(index) {
                    if ($('#adtHiddenInput_' + attribute + '_' + (index + 1).toString()).val() != undefined && $('#adtHiddenInput_' + attribute + '_' + (index + 1).toString()).val() == '1') {
                        $("#adtInput_" + attribute + "_" + (index + 1).toString()).attr("checked", true);
                        if (isReadOnly == true) {
                            $("#adtInput_" + attribute + "_" + (index + 1).toString()).attr('disabled', true);
                        }
                        return;
                    }
                });

            }
        },
        error: function() {
            $.each($("input[id^='adtInput_" + attribute + "_']"), function(index) {
                if ($('#adtHiddenInput_' + attribute + '_' + (index + 1).toString()).val() != undefined && $('#adtHiddenInput_' + attribute + '_' + (index + 1).toString()).val() == '1') {
                    $("#adtInput_" + attribute + "_" + (index + 1).toString()).attr("checked", true);
                    if (isReadOnly == true) {
                        $("#adtInput_" + attribute + "_" + (index + 1).toString()).attr('disabled', true);
                    }
                    return;
                }
            });

        }
    });

}

//Multiple Select Boxes Management
function SelectBoxAddOption(selectSourceId, selectDestinationId) {
    var province = $("#" + selectSourceId + " option:selected");
    var selectedProvinceText = province.text();
    var selectedProvinceVal = province.val();

    if (selectedProvinceVal != -1) {
        $("#" + selectDestinationId).append($('<option></option>').val(selectedProvinceVal).text(selectedProvinceText));

        var multipleValues = "";

        $("#" + selectDestinationId + " option").each(function(index, value) {

            multipleValues += value.value + ",";
        });
        $("#hd_" + selectSourceId + "_multi").val(multipleValues);
    }
}

function SelectBoxRemOption(selectBoxId, selectSourceId) {
    var allOption = $("#" + selectBoxId + " option");
    var province = $("#" + selectBoxId + " option:selected");
    $("#" + selectBoxId).removeOption(/./);
    var multipleValues = "";
    $.each(allOption, function(index) {
        var current = allOption[index];
        var option = current.value;
        var optiontxt = current.text;

        var generate = true;

        $.each(province, function(index2) {

            if (option == province[index2].value) {
                generate = false;
                return;
            }
        });

        if (generate == true) {
            $("#" + selectBoxId).append($('<option></option>').val(option).html(optiontxt));
            multipleValues += option + ",";
        }
    });

    if (selectSourceId)
        $("#hd_" + selectSourceId + "_multi").val(multipleValues);
}

//DetailForm specific scripts
function SetAdvMap(sender, args) {
    $("#map").click(function() {
        setTimeout("InitAdvMap();", 250);
    });
}

function InitTabs(sender, args) {
    $('.tabs').tabs({
        fxFade: true,
        fxSpeed: 'fast'
    });

    try {
        var tabVisibility = $("[id$='_tabVisibility']").val();
        var tabRules = tabVisibility.split('|');
    }
    catch (e) {
        return;
    }

    $.each(tabRules, function(i, rule) {
        var ruleParts = rule.split('=');
        var tabIndex = ruleParts[0];
        var visibility = ruleParts[1];

        if (visibility == "False")
            $("#tab-ap-" + tabIndex).hide();
    });


}
//shared
function InitAdvMap() {
    try {
        var longitude = $("[id$='_hfLongitude']").val();
        var latitude = $("[id$='_hfLatitude']").val();
        var address = $("[id$='_hfAddress']").val();
    }
    catch (exc) {
        return;
    }
    if (longitude == 0 && latitude == 0) {
        $('#map-cp2').hide();
        return;
    }
    $('#map-cp2').jmap('init', {
        'mapCenter': [latitude, longitude],
        'mapShowjMapsIcon': false
    }).jmap('AddMarker', {
        'pointLatLng': [latitude, longitude],
        'pointHTML': address,
        'pointIsDraggable': false
    });
}

function InitDocumentLinks(sender, args) {
    $('img.advDoc').click(function() { window.open(this.docUrl); return false; });
}

jQuery.fn.extend({
    initAdminGallery: function() {
        return this.each(function() {
            $(this).children('.gal-prev').click(function() {
                $galmain = $(this).parent().find('.gal-main img');
                $imgprev = ($(this).parent().children('ul.thumbs').children('li.thumb-active').children('img').attr('src') == $(this).parent().children('ul.thumbs').children('li:first').children('img').attr('src')) ? $(this).parent().children('ul.thumbs').children('li:last') : $(this).parent().children('ul.thumbs').children('li.thumb-active').prev();
                $galmain.attr('src', $imgprev.children('img').attr('rel'));
                $imgprev.parent().children('li').removeClass('thumb-active');
                $imgprev.addClass('thumb-active');
            });
            $(this).find('.gal-main img').click(function() {
                $galmain = $(this);
                $imgnext = ($(this).closest('div.gallery').children('ul.thumbs').children('li.thumb-active').children('img').attr('src') == $(this).closest('div.gallery').children('ul.thumbs').children('li:last').children('img').attr('src')) ? $(this).closest('div.gallery').children('ul.thumbs').children('li:first') : $(this).closest('div.gallery').children('ul.thumbs').children('li.thumb-active').next();
                $galmain.attr('src', $imgnext.children('img').attr('rel'));
                $imgnext.parent().children('li').removeClass('thumb-active');
                $imgnext.addClass('thumb-active');
            });
            $(this).children('.gal-next').click(function() {
                $galmain = $(this).parent().find('.gal-main img');
                $imgnext = ($(this).parent().children('ul.thumbs').children('li.thumb-active').children('img').attr('src') == $(this).parent().children('ul.thumbs').children('li:last').children('img').attr('src')) ? $(this).parent().children('ul.thumbs').children('li:first') : $(this).parent().children('ul.thumbs').children('li.thumb-active').next();
                $galmain.attr('src', $imgnext.children('img').attr('rel'));
                $imgnext.parent().children('li').removeClass('thumb-active');
                $imgnext.addClass('thumb-active');
            });
            $(this).children('ul.thumbs').children('li').click(function() {
                $(this).parent().parent().find('.gal-main img').attr('src', $(this).children('img').attr('rel'));
                $(this).parent().children('li').removeClass('thumb-active');
                $(this).addClass('thumb-active');
            });
        });
    }
});

function checkCanoneMensileSettimanale() {
    var mMese1 = $('#adtInput_46').val();
    var mCanone1 = $('#adtInput_13').val();
    var sMese1 = $('#adtInput_246').val();
    var sSettimana1 = $('#adtInput_51').val();
    var sCanone1 = $('#adtInput_55').val();

    $("#adtInput_46").rules('remove', 'selectRequired');
    $("#adtInput_13").rules('remove', 'required');
    $("#adtInput_246").rules('remove', 'selectRequired');
    $("#adtInput_51").rules('remove', 'selectRequired');
    $("#adtInput_55").rules('remove', 'required');
    $("#adtInput_46").removeClass('error');
    $("#adtInput_13").removeClass('error');
    $("#adtInput_246").removeClass('error');
    $("#adtInput_51").removeClass('error');
    $("#adtInput_55").removeClass('error');

    if (mMese1 != "-1" || mCanone1 != "") {
        if (mMese1 == "-1") { $("#adtInput_46").rules('add', { selectRequired: true, messages: { selectRequired: "Il canone mensile è compilato solo parzialmente: Compilare campo Mese"} }); } else { $("#adtInput_46").rules('remove', 'selectRequired'); }
        if (mCanone1 == "") { $("#adtInput_13").rules('add', { required: true, messages: { required: "Il canone mensile è compilato solo parzialmente: Compilare campo Canone"} }); } else { $("#adtInput_13").rules('remove', 'required'); }
    }
    if (sMese1 != "-1" || sSettimana1 != "-1" || sCanone1 != "") {
        if (sMese1 == "-1") { $("#adtInput_246").rules('add', { selectRequired: true, messages: { selectRequired: "Il canone settimanale è compilato solo parzialmente: Compilare campo Mese"} }); } else { $("#adtInput_246").rules('remove', 'selectRequired'); }
        if (sSettimana1 == "-1") { $("#adtInput_51").rules('add', { selectRequired: true, messages: { selectRequired: "Il canone settimanale è compilato solo parzialmente: Compilare campo Settimana"} }); } else { $("#adtInput_51").rules('remove', 'selectRequired'); }
        if (sCanone1 == "") { $("#adtInput_55").rules('add', { required: true, messages: { required: "Il canone settimanale è compilato solo parzialmente: Compilare campo Canone"} }); } else { $("#adtInput_55").rules('remove', 'required'); }
    }
    if (mMese1 == "-1" && mCanone1 == "" && sMese1 == "-1" && sSettimana1 == "-1" && sCanone1 == "") {
        $("#adtInput_46").rules('add', { selectRequired: true, messages: { selectRequired: "Compilare almeno un canone (Mensile o Settimanale)"} });
        $("#adtInput_246").addClass('error');
    }
    else {
        $("#adtInput_46").rules('remove', 'selectRequired');
        $("#adtInput_246").removeClass('error');
    }

}

function checkCanoneMensileAnnuale() {
    var canoneMese = $('#adtInput_13').val();
    var canoneAnno = $('#adtInput_14').val();

    $("#adtInput_13").rules('remove', 'required');
    if (canoneMese == "" && canoneAnno == "") {
        $("#adtInput_13").rules('add', { required: true, messages: { required: "Compilare almeno un canone (Mensile o Annuale)"} });
        $("#adtInput_14").addClass('error');
    }
    else {
        $("#adtInput_13").rules('remove', 'required');
        $("#adtInput_14").removeClass('error');
    }
}

function notifyAjaxCallCompleted(attributeId, hasValues) {
    try {
        onAjaxCallCompleted(attributeId, hasValues);
    }
    catch (e) {
        //do nothing
    }

}

function onAjaxCallCompleted(attributeId, hasValues) {
    switch (attributeId) {
        case '254':
            checkIsVersionAutoPresent(hasValues);
            break;
        case '77':
            checkIsVersionEquipmentAutoPresent();
            break;
        case '255':
            checkIsVersionCommPresent(hasValues);
            break;
        case '153':
            checkIsVersionEquipmentCommPresent();
            break;
        case '140':
            checkIsVersionMotoPresent(hasValues);
            break;
        default:
            break;
    }
}

function checkIsVersionAutoPresent(hasValues) {
    if (hasValues) {
        $('#divVersion').show();
        $("#adtInput_254").rules('add', { selectRequired: true, messages: { selectRequired: "Seleziona un valore nella tendina Versione."} });
        $("#adtInput_77").rules('add', { selectRequired: true, messages: { selectRequired: "Seleziona un valore nella tendina Allestimento."} });
        $('#input_allestimento_free').rules("remove");
        $('#divEquipmentFreeInput').hide();
        $('#divVersionEquipment').show();
        $('#adtInput_77').change();
    }
    else {
        var allParentsSelected = true;
        if ($('#adtInput_74').val() == '-1') {
            allParentsSelected = false;
        }
        if ($('#adtInput_76').val() == '-1') {
            allParentsSelected = false;
        }
        if (allParentsSelected) {
            $('#divVersion').hide();
            $('#divEquipmentFreeInput').show();
            $("#input_allestimento_free").rules('add', { required: true, messages: { required: "Il campo Allestimento è obbligatorio."} });
            $('#adtInput_254').rules("remove");
            $('#adtInput_77').rules("remove");
            if ($('#adtHiddenInput_77').val() != '') {
                $('#input_allestimento_free').val($('#adtHiddenInput_77').val());
                inputAlestimentoFreeAutoChanged();
            }
            $('#divVersionEquipment').show();
        } else {
            $('#adtInput_254').rules("remove");
            $('#adtInput_77').rules("remove"); /* le regole di validazione vengono settate da qui e non dalla configurazione in db*/
            $('#divVersionEquipment').hide();
        }
    }
}

function inputAlestimentoFreeAutoChanged() {
    $('#adtHiddenInput_77').val($('#input_allestimento_free').val());
    $('#adtInput_77').change();
}

function checkIsVersionEquipmentAutoPresent() {
    if ($('#divVersion').is(':hidden')) {
        $('#adtInput_77').rules("remove");
    }
    else {
        if ($('#adtHiddenInput_77').val() != '') {
            $('#adtInput_77').val($('#adtHiddenInput_77').val());
            $('#adtInput_77').change();
        }
    }
}

function checkIsVersionCommPresent(hasValues) {
    if (hasValues) {
        $('#divVersion').show();
        $("#adtInput_255").rules('add', { selectRequired: true, messages: { selectRequired: "Seleziona un valore nella tendina Versione."} });
        $("#adtInput_153").rules('add', { selectRequired: true, messages: { selectRequired: "Seleziona un valore nella tendina Allestimento."} });
        $('#input_allestimento_free').rules("remove");
        $('#divEquipmentFreeInput').hide();
        $('#divVersionEquipment').show();
        $('#adtInput_153').change();
    }
    else {
        var allParentsSelected = true;
        if ($('#adtInput_151').val() == '-1') {
            allParentsSelected = false;
        }
        if ($('#adtInput_152').val() == '-1') {
            allParentsSelected = false;
        }
        if (allParentsSelected) {
            $('#divVersion').hide();
            $('#divEquipmentFreeInput').show();
            $("#input_allestimento_free").rules('add', { required: true, messages: { required: "Il campo Allestimento è obbligatorio."} });
            $('#adtInput_255').rules("remove");
            $('#adtInput_153').rules("remove");
            if ($('#adtHiddenInput_153').val() != '') {
                $('#input_allestimento_free').val($('#adtHiddenInput_153').val());
                inputAlestimentoFreeCommChanged();
            }
            $('#divVersionEquipment').show();
        }
        else {
            $('#adtInput_255').rules("remove");
            $('#adtInput_153').rules("remove"); /* le regole di validazione vengono settate da qui e non dalla configurazione in db*/
            $('#divVersionEquipment').hide();
        }
    }
}

function inputAlestimentoFreeCommChanged() {
    $('#adtInput_153').removeOption(/./).addOption($('#input_allestimento_free').val(), $('#input_allestimento_free').val(), true);
    $('#adtInput_153').change();
}

function checkIsVersionEquipmentCommPresent() {
    if ($('#divVersion').is(':hidden')) {
        $('#adtInput_153').rules("remove");
    }
    else {
        if ($('#adtHiddenInput_153').val() != '') {
            $('#adtInput_153').val($('#adtHiddenInput_153').val());
            $('#adtInput_153').change();
        }
    }
}

function checkIsVersionMotoPresent(hasValues) {
    if (hasValues) {
        $('#divVersion').show();
        $('#divEquipmentFreeInput').hide();
        $('#divVersionEquipment').show();
        $('#adtInput_140').change();
    }
    else {
        var allParentsSelected = true;
        if ($('#adtInput_138').val() == '-1') {
            allParentsSelected = false;
        }
        if ($('#adtInput_139').val() == '-1') {
            allParentsSelected = false;
        }
        if ($('#adtInput_142').val() == '-1') {
            allParentsSelected = false;
        }
        if (allParentsSelected) {
            $('#divVersion').hide();
            $('#divEquipmentFreeInput').show();
            if ($('#adtHiddenInput_140').val() != '') {
                $('#input_allestimento_free').val($('#adtHiddenInput_140').val());
                inputAlestimentoFreeMotoChanged();
            }
            $('#divVersionEquipment').show();
        }
        else {
            $('#divVersionEquipment').hide();
        }
    }
}
function inputAlestimentoFreeMotoChanged() {
    $('#adtInput_140').removeOption(/./).addOption($('#input_allestimento_free').val(), $('#input_allestimento_free').val(), true);
    $('#adtInput_140').change();
}

function ShowIdomooUpsellInfo(chkUpsellIdomoo) {
    $("#idomooInfoMessage").dialog({
        width: 238,
        height: 250,
        autoOpen: false,
        resizable: false,
        bgiframe: true,
        modal: true,
        backgroundColor: '#fff'
    });
    $("#chkUpsellIdomooClientId").val(chkUpsellIdomoo);
    $("#ui-dialog-title-idomooInfoMessage").css('float', 'none');
    $("#ui-dialog-title-idomooInfoMessage").css('color', '#fff');
    $("#idomooInfoMessage").dialog("open");
    return false;
}

function ConfirmIdomoUpsell() {
    $("[id$=\'#" + $("#chkUpsellIdomooClientId").val().split('#')[1] + "\']").attr('checked', true);
    setTimeout('__doPostBack(\'' + $("#chkUpsellIdomooClientId").val() + '\',\'\')', 0);
    $("#idomooInfoMessage").dialog("close");
}

function ShowW2PUpsellSelectData(productCode, chkW2PUpsell) {
    $("#w2pSelectData").dialog({
        width: 350,
        height: 300,
        autoOpen: false,
        resizable: false,
        bgiframe: true,
        modal: true
    });
    getAvailableDatesForW2P(productCode, 'listAvailableDates');
    $("#chkW2PUpsellClientId").val(chkW2PUpsell);
    $("#chkW2PUpsellSelectedJsDate").val('');
    $("#w2pSelectData").dialog("open");
    return false;
}

function ConfirmW2PUpsell() {
    if ($("#chkW2PUpsellSelectedJsDate").val().length > 0) {
        $("[id$=\'#" + $("#chkW2PUpsellClientId").val().split('#')[1] + "\']").attr('checked', true);
        setTimeout('__doPostBack(\'' + $("#chkW2PUpsellClientId").val() + '\',\'' + $("#chkW2PUpsellSelectedJsDate").val() + '\')', 0);
    }
    $("#w2pSelectData").dialog("close");
}

function getAvailableDatesForW2P(productCode, chkBoxList) {
    var advId = ($("[id$=\'_showCaseCurrentAdvId\']").length > 0) ? $("[id$=\'_showCaseCurrentAdvId\']").val() : '0';

    $.ajax({
        type: "POST",
        url: "../Shared/Webservices/WSGetData.asmx/GetW2PAvailableDates",
        data: "{\"productCode\":\"" + productCode + "\",\"advId\":\"" + advId + "\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            $('#' + chkBoxList + ' ul li').remove();
            if (response.d.a) {
                var retValues = response.d.a.toString().split(',');
                var dayNames = response.d.dd.toString().split(',');
                if (retValues.length < 1) {
                    $('#' + chkBoxList).hide();
                    $('#listAvailableDatesNoDates').show();
                    return;
                }
                for (var i = 0; i < retValues.length; i++) {
                    $('#' + chkBoxList + ' ul').append(getW2PAvailableDate(chkBoxList, retValues[i], dayNames));
                }
                if (retValues.length == 1) {
                    $('#chk_' + retValues[0]).attr("checked", true);
                    chkW2PDateClick('chk_' + retValues[0]);
                }
                $('#' + chkBoxList + ' ul li').each(function(idx, elm) {
                    if ($(elm).hasClass('alt')) {
                        $(elm).removeClass('alt');
                    }
                    if (idx % 2 == 0) {
                        $(elm).addClass('alt');
                    }
                });
            } else {
                $('#' + chkBoxList).parent().hide();
                $('#listAvailableDatesNoDates').show();
                return;
            }
        },
        error: function(request) {
            alert(request.responseText);
        }
    });
}

function getW2PAvailableDate(chkBoxList, date, dayNames) {
    var formattedDate = new Date(parseInt(date));
    return '<li id="' + chkBoxList + '_' + date + '"><span class="checkbox"><input id="chk_' + date + '" name="chk_' + date + '" type="checkbox" class="checkBoxList" onclick="chkW2PDateClick(\'chk_' + date + '\');"></span>' + padNumber(formattedDate.getDate()) + '/' + padNumber(formattedDate.getMonth() + 1) + '/' + formattedDate.getFullYear() + ' ' + dayNames[formattedDate.getDay()] + '</span><div class="cl"></div></li>';
}

function chkW2PDateClick(chkId) {
    var selectedDates = '';
    $("#" + chkId).closest('ul').find('input:checked').each(function() {
        var formattedDate = new Date(parseInt(this.id.split('_')[1]));
        if (selectedDates != '')
            selectedDates += ';';
        selectedDates += formattedDate.getFullYear() + padNumber(formattedDate.getMonth() + 1) + padNumber(formattedDate.getDate());
    });
    $("#chkW2PUpsellSelectedJsDate").val(selectedDates);
}

function PrepareUpsellDialogs() {
    //Vetrina Advertype
    $(".popupupselldays").dialog({
        width: 650,
        height: 450,
        autoOpen: false,
        resizable: false,
        bgiframe: true,
        modal: true
    });
    $(".popupupselldays").css('background-color', '#eceaeb');
    $("#ui-dialog-title-1").css('float', 'none');
    $("#ui-dialog-title-1").css('color', '#fff');

    //Idomoo Dialog
    $("#idomooInfoMessage").dialog({
        width: 238,
        height: 250,
        autoOpen: false,
        resizable: false,
        bgiframe: true,
        modal: true,
        backgroundColor: '#fff'
    });
    $("#ui-dialog-title-idomooInfoMessage").css('float', 'none');
    $("#ui-dialog-title-idomooInfoMessage").css('color', '#fff');

    //W2P Dialog
    $("#w2pSelectData").dialog({
        width: 350,
        height: 300,
        autoOpen: false,
        resizable: false,
        bgiframe: true,
        modal: true
    });
}

function addPeriod() {
    var status = $('#period2').css("display");
    if (status == 'none') {
        $('#period2').show("slow");
    } else {
        $('#period3').show("slow");
        $('#btnAddPeriod').hide();
    }
}

function closePeriod(id) {
    $('#' + id).find(':input').each(function() {
        switch (this.type) {
            case 'text':
                $(this).val('');
                break;
        }
    });
    $('#' + id).find(':select').each(function() {
        $(this).val('');
    });
    $('#' + id).hide("slow");
    $('#btnAddPeriod').show();
}

function blockUIUpload() {
    $.blockUI({ message: '<div id="progressPopup" style="position: fixed; height: 70px; width: 100%; text-align: center; color: #a0a0a0; top: 300px; left: 0px;"><table border="0" align="center" style="width: 100px;"><tr> <td align="center"><div style="border: 0px outset gray; display: block;"><table style="width: 100%;"><tr><th style="color:#ce000c;"> Attendere ...</th></tr><tr> <td valign="top" style="padding-top: 5px; padding-bottom: 5px;" align="center"><asp:Image runat="server" ID="imgProgress" ImageUrl="~/Images/loading.gif" /></td></tr></table></div></td></tr></table></div>',
        overlayCSS: { backgroundColor: '#FFF', opacity: 0.6 },
        css: { border: 'none' }
    });
}

function unblockUIUpload() {
    try { $.unblockUI(); } catch (e) { }
}

function SetImageMapPoint() {
    var advAddress = getAddress();
    if (advAddress != "" && advAddress != 'undefined') {
        SetAdminMapImageFromAddress(advAddress);
    }
}

function SetAdminMapImageFromAddress(advAddress) {
    $.ajax({
        type: "POST",
        url: "/Shared/Webservices/WSGetData.asmx/GetCoordinates",
        data: "{address: '" + advAddress + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            var xCoord = "";
            var yCoord = "";
            var pr = ((typeof response.d) == 'string') ? eval('(' + response.d + ')') : response.d;

            for (var i = 0; i < pr.Placemark.length; i++) {
                xCoord = pr.Placemark[i].Point.coordinates[0];
                yCoord = pr.Placemark[i].Point.coordinates[1];
            }
            if (xCoord != "" && yCoord != "") {
                SetAdminMapImage(xCoord, yCoord);
            }
        },
        error: function(request, status, error) {
            alert(request.responseText);
        }
    });
}

function SetAdminMapImage(la, lo) {
    if (la != "" && lo != "") {
        var mapImageUrl = "http://maps.google.com/maps/api/staticmap?center=" + lo + "," + la
        + "&zoom=13&size=522x250&maptype=roadmap&sensor=false";
        mapImageUrl += "&markers=color:red|label:S|" + lo + "," + la;
        $("[id$='_hdnMapCoords']").val(lo + '|' + la);
        $("[id$='_mapContainer']").show();
        $("#staticMapImage").attr("src", mapImageUrl);
        $("#staticMapImage").show();
        $("#imageMapContainer").show();
    }
}
