//<![CDATA[
$(document).ready(function () {
    FixHeight();
    $.prettyLoader();
    $(".button").button();
});

function FixHeight() {
   /* arr = new Array();
    arr[0] = $("#main-left").css('height').replace('px','');
    arr[1] = $("#main-right").css('height').replace('px','');
    arr[2] = $("#main-center").css('height').replace('px','');
    highest = 0;
    
    for (i=0;i<3;i++) {
        if (parseInt(arr[i])>parseInt(highest)) {
            highest = arr[i]
        }
    }
    
    if (highest != arr[1]) highest = parseInt(highest) + parseInt($("#banners-box").css('height'));
    $("#main-center").css('height', parseInt(highest))*/
    $("#banners-box").css('visibility', 'visible')
}

function SearchArticolo() {
    Param = document.getElementById('ricercaprodotto').value; 
    Marca = document.getElementById('ctl00_ddlMarchi1').value;
    
    if ( Param != 'Modello o parola chiave') {
        if (Param.length < 3) ShowDialog('Errore', 'Devi inserire almeno 3 caratteri.');
            else if (Marca != 0) window.location.href = '/search.aspx?search='+Param+'&marca='+Marca+'&page=1';
            else window.location.href = '/search.aspx?search='+Param+'&page=1';
    } else ShowDialog('Errore', 'Devi inserire almeno 3 caratteri.');
}

function SearchConsumabili() {
    Codice = document.getElementById('ricercacodconsumabili').value;
    if (Codice == "") Param = document.getElementById('ricercaconsumabili').value; 
    Marca = document.getElementById('ctl00_ddlMarchi2').value;
   
   if (Codice != '') {
        if (Codice.length < 3) ShowDialog('Errore', 'Devi inserire un codice di almeno 3 caratteri.');
            else if (Marca != 0) window.location.href = '/search.aspx?code='+Codice+'&marca='+Marca+'&cons=true&page=1';
            else window.location.href = '/search.aspx?code='+Codice+'&cons=true&page=1';
   } else if ( Param != 'Modello o parola chiave') {
        if (Param.length < 3) ShowDialog('Errore', 'Devi inserire almeno 3 caratteri.');
            else if (Marca != 0) window.location.href = '/search.aspx?search='+Param+'&marca='+Marca+'&cons=true&page=1';
            else window.location.href = '/search.aspx?search='+Param+'&cons=true&page=1';
    } else ShowDialog('Errore', 'Devi inserire almeno 3 caratteri.');
}

function CheckLogin()
{
    if (document.getElementById("username").value == "" || document.getElementById("username").value == "username")
    {
        ShowDialog("Errore!", "Inserisci un username valido!", false);
        document.getElementById("username").focus();
        return false;
    }
    
    if(document.getElementById("password").value == "" || document.getElementById("password").value == "password")
    {
        ShowDialog("Errore!", "Inserisci una password valida!", false);
        document.getElementById("password").focus();
        return false;
    }
    
    document.getElementById("ctl00_usr").value = document.getElementById("username").value;
    document.getElementById("ctl00_pwd").value = document.getElementById("password").value;
    
    var frm = document.aspnetForm;
    frm.ctl00_act.value = "log";
    frm.submit();
}

function CheckLoginPopup()
{
    if (document.getElementById("usernamepopup").value == "" || document.getElementById("usernamepopup").value == "username")
    {
        ShowDialog("Errore!", "Inserisci un username valido!", false);
        document.getElementById("usernamepopup").focus();
        return false;
    }
    
    if(document.getElementById("passwordpopup").value == "" || document.getElementById("passwordpopup").value == "password")
    {
        ShowDialog("Errore!", "Inserisci una password valida!", false);
        document.getElementById("passwordpopup").focus();
        return false;
    }
    
    document.getElementById("ctl00_usr").value = document.getElementById("usernamepopup").value;
    document.getElementById("ctl00_pwd").value = document.getElementById("passwordpopup").value;
    
    var frm = document.aspnetForm;
    frm.ctl00_act.value = "log";
    frm.submit();
}

function Logout()
{
    var frm = document.aspnetForm;
    frm.ctl00_act.value = "out";
    frm.submit();
}

// Funzioni Varie
function SubmitAction(act)
{
    if (act == 'out') { scriviCookie('consumabili','0','') }
    var frm = document.aspnetForm;
    frm.ctl00_act.value = act;
    frm.submit();
}

function toURL(pgName) {
    if (pgName != '') {
    window.location.href = '/'+pgName+'.aspx';
    }
}

function ShowBasicDialog(title, message, modal, cfx, timeout) {
    if ( modal == null ) modal = true;
    if ( cfx == null) cfx = "fadeOut";
    if ( timeout == null) timeout = 4000;
    
    var $dialog = $('<div class="basic-dialog"><\/div>').html('<span class="ui-icon ui-icon-info" style="float:left; margin:0 7px 20px 0;"><\/span>' + message).dialog({
        autoOpen: false,
        title: title,
        minHeight: 100,
        maxHeight: 200,
        hide: cfx,
        zIndex: 9999,
        modal: modal,
        open: function (event, ui) {

            if (timeout > 0) {
                setTimeout(function() {
                    $dialog.dialog('close');
                }, timeout);
            }
        }
    });
    $dialog.dialog('open');
}

function ShowDialog(title, message, modal, txtbtnclose) {
    if ( modal == null ) modal = true;
    if ( txtbtnclose == null ) txtbtnclose = "Chiudi";
    var $dialog = $('<div><\/div>').html('<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"><\/span>' + message).dialog({
        autoOpen: false,
        title: title,
        minHeight: 100,
        maxHeight: 200,
        zIndex: 9999,
        modal: modal,
        buttons: [
            {
                text: txtbtnclose,
                click: function() { $(this).dialog("close"); }
            }
        ],
        open: function (event, ui) {
//              var scrollTop = $('#__SCROLLPOSITIONY').val()
//                        
//            if ((typeof(scrollTop) == 'undefined') || (scrollTop == '0')) {
//                var scrollTop = document.documentElement.scrollTop;
//            }
//            var windowWidth = document.documentElement.clientWidth;
//            var windowHeight = document.documentElement.clientHeight;
//            
//            $('.ui-dialog').each(function(index) {
//                var popupHeight = $(this).height();
//                var popupWidth = $(this).width();

//               $(this).css({
//                    'position': 'absolute',
//                    'top': (parseInt(windowHeight / 2) + parseInt(scrollTop) - parseInt(popupHeight / 2)),
//                    'left': windowWidth / 2 - popupWidth / 2
//                }); 
//            });
        }
    });
    $dialog.dialog('open');
}

function ShowConfirmationDialog(title, message, modal, txtbtnclose, txtbtnok) {
    if ( modal == null ) modal = true;
    if ( txtbtnclose == null ) txtbtnclose = "Chiudi";
    if ( txtbtnok == null ) txtbtnok = "Ok";
    var $dialog = $('<div><\/div>').html('<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"><\/span>' + message).dialog({
        autoOpen: false,
        title: title,
        minHeight: 100,
        maxHeight: 200,
        zIndex: 9999,
        modal: modal,
        buttons: [
            {
                text: txtbtnclose,
                click: function() { $(this).dialog("close"); }
            },
            {
                text: txtbtnok,
                click: function() { DialogOKFunction(); }
            }
        ],
        open: function (event, ui) {
//            var scrollTop = $('#__SCROLLPOSITIONY').val()
//            if ((typeof(scrollTop) == 'undefined') || (scrollTop == '0')) {
//                var scrollTop = document.documentElement.scrollTop;
//            }
//            var windowWidth = document.documentElement.clientWidth;
//            var windowHeight = document.documentElement.clientHeight;
//            $('.ui-dialog').each(function(index) {
//                var popupHeight = $(this).height();
//                var popupWidth = $(this).width();
//                $(this).css({
//                    'position': 'absolute',
//                    'top': (parseInt(windowHeight / 2) + parseInt(scrollTop) - parseInt(popupHeight / 2)),
//                    'left': windowWidth / 2 - popupWidth / 2
//                }); 
//            });
        }
    });
    $dialog.dialog('open');
}

function DialogOKFunction() {
    $.prettyLoader.show(4000);
    setTimeout(function() {
        window.location.href = 'gestcart.aspx?act=cle';
    }, 300);	
}

// Cart Functions
function addOne(id, maxqta) {
    var val = parseInt($('#qta'+id).val());
    //if (val < maxqta) {
        $('#qta'+id).val(val + 1);
    //}
    //else {
      //  ShowDialog("Attenzione!", "Quantit&agrave; non disponibile!", false, "Chiudi");
    //}
}

function subOne(id) {
    var val = parseInt($('#qta'+id).val());
    if (val != 1) $('#qta'+id).val(val - 1);
}

function gestCart(idart, I, info ) {
    $("#cart-qta").text('');
    $("#cart-lbl").text('');
    $("#cart-loader").show();
    var qta = $("#qta"+I).val();
 
    params = 'act=ADD&idart=' + idart + '&qta=' + qta

    $.ajax({
        url: "/ajax/gestcart.aspx",
        data: params,
        cache: false,
        success: function(html) {
            if (html == 'errorSession') {
                ShowBasicDialog('Errore Login!', "Sessione Scaduta! E' necessario rieffettuare il login!");
                top.location.reload(true);
            } else if (html > 1) {
                testo = ' articoli nel carrello'
            } else {
                testo = ' articolo nel carrello'
            }

            $("#cart-qta").text(html);
            $("#cart-lbl").text(testo);
            $("#cart-loader").hide();
            
            //alert( info[4]*qta + ' ' + info[4] + ' ' + qta);
            testo = '<b>' + info[2] + '</b> - ' + info[3] + '<br / > Articolo: ' + info[1] + ' x ' + qta  + '<br /> Totale: &euro; ' + parseFloat(info[4].replace(",", ".")) * parseInt(qta) + '<br /><br /><a href="javascript:void(0);" onclick="$(\'.basic-dialog\').dialog(\'close\');" style="padding: 4px 6px; margin-left:15px;" class="ui-button ui-state-default ui-corner-all">Torna ai prodotti</a> &nbsp;&nbsp;&nbsp; <a href="/cart.aspx" style="padding: 4px 6px;" class="ui-button ui-state-default ui-corner-all" target="_parent">Vai al carrello</a>';
           
            ShowBasicDialog('Articolo inserito nel carrello', testo, false, "fadeOut", 0);
        },
        error: function() {
            $("#cart-loader").hide();
            $("#dettagli-carrello").text('Grossa Crisi!');
        }
    });
}

function manageCart(mode, idart, I, prezzoitem) {
    $("#cart-qta").text('');
    $("#cart-lbl").text('');
    $("#cart-loader").show();
    var qta = $("input[name=qta" + I +"]").val();
    
    params = 'act='+mode+'&idart=' + idart;

    $.ajax({
        url: "/ajax/gestcart.aspx",
        data: params,
        cache: false,
        success: function(html) {
            if (html == 'errorSession') {
                ShowBasicDialog('Errore Login!', "Sessione Scaduta! E' necessario rieffettuare il login!");
                top.location.reload(true);
            } else if (html > 1) {
                testo = ' articoli nel carrello'
            } else {
                testo = ' articolo nel carrello'
            }

                $("#cart-qta").text(html);
                $("#cart-lbl").text(testo);
                $("#cart-loader").hide();
                $.prettyLoader.hide();
                
                updateCart();
        },
        error: function() {
            $("#cart-loader").hide();
            $("#dettagli-carrello").text('Errore!');
        }
    });
}

function updateCart() {
    params = '';

    $.ajax({
        url: "/ajax/cart.aspx",
        data: params,
        cache: false,
        success: function(html) {
            if (html == 'errorSession') {
                ShowBasicDialog('Errore Login!', "Sessione Scaduta! E' necessario rieffettuare il login!");
                top.location.reload(true);
            } else {
                $('.html-box').empty();
                $('.html-box').html(html);
                $("a[rel^='prettyPhoto']").prettyPhoto({
                    deeplinking: false,
                    social_tools: false
                });
            }
        },
        error: function() {
            alert('Errore! Contattare HOTMINDS. Codice Errore: updCrt');
        }
    });
}

function refreshModelsList() {
    params = '';

    $.ajax({
        url: "/ajax/refreshmodels.aspx",
        data: params,
        cache: false,
        success: function(html) {
            $('#modelli').empty();
            $('#modelli').html(html);                
        },
        error: function() {
            alert('Errore! Contattare HOTMINDS. Codice Errore: rfshMods');
        }
    });
}

function loadModel() {
    var idmod = $('#ctl00_ContentPlaceHolder_ddlModelli').val();
    if (idmod == 0) {
        ShowBasicDialog('Errore!', "Non hai selezionato alcun modello d'ordine!");
    } else {
        params = 'idmod=' + idmod;

        $.ajax({
            url: "/ajax/loadmodel.aspx",
            data: params,
            cache: false,
            success: function (html) {
                $.prettyLoader.hide();
                if (html == 'True') {
                    updateCart();
                } else if (html == 'errorSession') {
                    ShowBasicDialog('Errore Login!', "Sessione Scaduta! E' necessario rieffettuare il login!");
                    location.reload(true);
                } else {
                     ShowBasicDialog('Errore durante il caricamento dei modelli', html);
                }
            },
            error: function () {
                alert('Errore! Contattare HOTMINDS. Codice Errore: loadModAjax');
            }
        });
    }
}

function saveModel() {
    var name = prompt("Inserisci il nome del modello d'ordine", "Nuovo Modello");
    if (!name) {
        ShowBasicDialog('Errore!', "Devi inserire un nome!");
    } else {
        params = 'name=' + name;
    
        $.ajax({
            url: "/ajax/savemodel.aspx",
            data: params,
            cache: false,
            success: function (html) {
                $.prettyLoader.hide();
                if (html == 'True') {
                    ShowBasicDialog("Salvataggio riuscito!", "Il modello e' stato salvato correttamente.");
                    top.location.reload(true);
                } else if (html == 'errorSession') {
                    ShowBasicDialog('Errore Login!', "Sessione Scaduta! E' necessario rieffettuare il login!");
                    top.location.reload(true);
                } else {
                    ShowBasicDialog('Errore durante il salvataggio', html);
                }
            },
            error: function () {
                alert('Errore! Contattare HOTMINDS. Codice Errore: saveModAjax');
            }
        });
    }
}

function delModel(idmod) {
    var answer = confirm("Sei sicuro di voler cancellare il modello d'ordine?")
    if (answer) {
        params = 'idmod=' + idmod;

        $.ajax({
            url: "/ajax/delmodel.aspx",
            data: params,
            cache: false,
            success: function (html) {
                $.prettyLoader.hide();
                if (html == 'True') {
                    refreshModelsList();
                } else if (html == 'errorSession') {
                    ShowBasicDialog('Errore Login!', "Sessione Scaduta! E' necessario rieffettuare il login!");
                    location.reload(true);
                } else {
                    ShowBasicDialog('Errore durante la cancellazione del modello:', html);
                }
            },
            error: function () {
                alert('Errore! Contattare HOTMINDS. Codice Errore: delMod');
            }
        });
    }
}

function checkCart() {
   $.prettyLoader.show();
    params = '';
            
    $.ajax({
        url: "/ajax/checkcart.aspx",
        data: params,
        cache: false,
        success: function (html) {
            $.prettyLoader.hide();
            if (html == 'errorSession') {
                ShowBasicDialog('Errore Login!', "Sessione Scaduta! E' necessario rieffettuare il login!");
                location.reload(true);
            } else if (html == 'ok') {
                window.location = '/registrazione.aspx';
            } else {
                var cookie = leggiCookie('consumabili');
                if (cookie != 1) {
                    ShowConsumabiliDialog('Attenzione', html, true, 'fadeOut',0);
                } else { window.location = '/registrazione.aspx'; }
            }
        },
        error: function () {
            alert('Errore! Contattare HOTMINDS. Codice Errore: checkCartAjax');
        }
    });
    
    return false;
}

function ShowConsumabiliDialog(title, message, modal, cfx, timeout) {
    if ( modal == null ) modal = true;
    if ( cfx == null) cfx = "fadeOut";
    if ( timeout == null) timeout = 4000;
    
    var $dialog = $('<div class="basic-dialog"><\/div>').html('<span class="ui-icon ui-icon-info" style="float:left; margin:0 7px 0px 0;"><\/span>Per i seguenti articoli non hai acquistato i materiali di consumo:<br /><br />' + message+'<br />Clicca sul prodotto per selezionare i consumabili o premi prosegui per continuare l\'acquisto.').dialog({
        autoOpen: false,
        title: title,
        minHeight: 100,
        maxHeight: 200,
        hide: cfx,
        zIndex: 9999,
        modal: modal,
        buttons: [
            {
                text: "Annulla",
                click: function() { $(this).dialog("close"); }
            },
            {
                text: "Prosegui",
                click: function() { 
                    scriviCookie("consumabili","1","")
                    window.location = '/registrazione.aspx';
                }
            }
        ],
        open: function (event, ui) {

            if (timeout > 0) {
                setTimeout(function() {
                    $dialog.dialog('close');
                }, timeout);
            }
        }
    });
    $dialog.dialog('open');
}


function filterOnlyPromo() {
    var url = location.search;
    var promo = $.query.get('promo');
    if (promo == 'true') {
        url = $.query.REMOVE("promo");
    } else {
        url = $.query.set("promo", "true");
    }
    window.location = window.location.pathname + url;
}

function filterByPrice(type) {
    var url = location.search;
    var price = $.query.get('price');
    if (type == price) {
        url = $.query.REMOVE("price");
    } else {
        url = $.query.set("price", type);
    }
    window.location = window.location.pathname + url;
}

function scriviCookie(nomeCookie,valoreCookie,durataCookie) {
  var scadenza = new Date();
  var adesso = new Date();
  scadenza.setTime(adesso.getTime() + (parseInt(durataCookie) * 60000));
  //document.cookie = nomeCookie + '=' + escape(valoreCookie) + ';expires=' + scadenza.toGMTString() + ';path=/';
  document.cookie = nomeCookie + '=' + escape(valoreCookie) + ';path=/';
}

function leggiCookie(nomeCookie) {
  if (document.cookie.length > 0)
  {
    var inizio = document.cookie.indexOf(nomeCookie + "=");
    if (inizio != -1)
    {
      inizio = inizio + nomeCookie.length + 1;
      var fine = document.cookie.indexOf(";",inizio);
      if (fine == -1) fine = document.cookie.length;
      return unescape(document.cookie.substring(inizio,fine));
    }else{
       return "";
    }
  }
  return "";
}

function PopupLogin() {
   $('.basic-dialog').dialog('close');
   $('#login-popup').dialog({ show: 'slide', width: 486, title: 'Effettua il Login:', modal: true, height:100 });
}
//]]>
