﻿var flag;
var altezzaFrame;
var altezzaDivProdotti = 0;
var imgCount = 0, imgTot = 0;
var numeroProdotti = 0;
var imgCaricate = 0;
var larghezzaPrecedente;
var schedaAnimating = false;

function apriMenu(idBrand, idFotoBrand, isDefault) {
    var idVoceMenu;
    var html;

    hideProdottoTab();
    
    $('#brand a').show();
    $('#lnk' + idBrand).hide();

    $('#menu').empty();
    $('#prodotti').empty();
    $("#su").hide();
    $("#giu").hide();

    var url = "Prodotti.aspx?w=menu";
    var lang = parent.GetCurrentCodeLang() ;
    if (lang != null) 
        url += "&lang=" + lang;
    $.getJSON(url + "&idBrand=" + idBrand, "",
       function(result) {
           $.each(result, function(entryIndex, entry) {
               if (entry['Id'] != null) {
                   html = '<div id="mnu' + entry['Id'] + '" class="CategoriaMenuItem" onclick="apriGallery(\'' + entry['Id'] + '\');"  onmouseover="evidenzia(this);" onmouseout="togliEvidenzia(this);" >' + entry['NomeLink'] + '</div>';
                   $('#menu').append(html);
                   if (entryIndex == 0) apriGallery(entry['Id']);
               }
           });
       });
}


function evidenzia(div) {
    $('#' + div.id).css('font-weight', 'bold');
}

function togliEvidenzia(div) {
    $('#' + div.id).css('font-weight', 'normal');
}

function apriGallery(idVoceMenu) {
    var left, top;
    var width = $("body").width() - $("#brand").width() - $("#menu").width();
    var height = $("#brand").height();
    var h;
    var altezzaMax, altezza, larghezzaMax, larghezza;

    hideProdottoTab();

    var url = "Prodotti.aspx?w=gallery";    
    var lang = parent.GetCurrentCodeLang() ;
    if (lang != null)
        url += "&lang=" + lang;
    
    $.getJSON(url + "&idVoceMenu=" + idVoceMenu, "",
       function(result) {
           left = 0;
           top = 0;
           numeroProdotti = 0;
           imgCaricate = 0;
           $('#prodotti').empty();
           $('#prodotti').css("top", 0);

           $.each(result, function(entryIndex, entry) {
               altezzaMax = 85;
               larghezzaMax = 96;
               altezza = entry['Altezza'];
               larghezza = entry['Larghezza'];

               altezza = Math.round(altezza * larghezzaMax / larghezza);
               larghezza = larghezzaMax;
               if (altezza > altezzaMax) {
                   larghezza = larghezza - (altezza - altezzaMax);
                   altezza = altezzaMax;
               }

               altezza = (100 - altezza) / 2;
               html = '<div class="galleria" onclick="showProdottoTab(\'' + entry['IdArticolo'] + '\');">'
                    + '<div  class="ThumImageBox"  >'
                    + '<img style="position:relative;left:2px;top:' + altezza + 'px;" id="tmb' + entry['IdArticolo'] + '"   class="ThumbImage" src="ImgManager.aspx?HMax=85&WMax=96&fileid=' + entry['Id'] + '" alt="' + entry['NomeArticolo'] + '" onmouseover="animazioneFotoOver(this)" onmouseout="animazioneFotoOut(this)"  />'
                    + '</div>'
                    + '<div class="ThumbImageText">' + entry['NomeArticolo'] + '</div>'
                    + '</div>';
               if (numeroProdotti == 0) numeroProdotti = entry['CountProdotti'];

               left = left + 138;

               if (left + 138 >= width - 100) {
                   left = 0;
                   top = top + 138;
               }
               $('#prodotti').append(html);
           });

           altezzaDivProdotti = $('.scrollable').height();
           scrollGallery(altezzaDivProdotti, altezzaFrame);
       });

}

var currentProduct = null;

function bindProdottoTab(obj) {
    $('#titolo').text(obj['Titolo']);
    $('#testo').append(obj['Testo']);
    $('#mainPhoto').attr("src", obj['PathImg1'] + '&HMax=' + hImgSchedaProdotto + '&WMax=' + wImgSchedaProdotto).load(checkImgLoad(null)); ;
    $('#prezzo').html(obj['Prezzo']);
    $('#subProdottiSelector').css('display', 'none');
    if (obj['PathImg2'] != '') { imgTot++; $('#smallPhoto1').attr("src", obj['PathImg2'] + '&HMax=' + hImgSchedaProdotto + '&WMax=' + wImgSchedaProdotto).load(checkImgLoad(null)).show(); }
    else { $('#smallPhoto1').hide(); }
    if (obj['PathImg3'] != '') { imgTot++; $('#smallPhoto2').attr("src", obj['PathImg3'] + '&HMax=' + hImgSchedaProdotto + '&WMax=' + wImgSchedaProdotto).load(checkImgLoad(null)).show(); }
    else { $('#smallPhoto2').hide(); }
    if (obj['PathImg4'] != '') { imgTot++; $('#smallPhoto3').attr("src", obj['PathImg4'] + '&HMax=' + hImgSchedaProdotto + '&WMax=' + wImgSchedaProdotto).load(checkImgLoad(null)).show(); }
    else { $('#smallPhoto3').hide(); }
    if (obj['PathImg5'] != '') { imgTot++; $('#smallPhoto4').attr("src", obj['PathImg5'] + '&HMax=' + hImgSchedaProdotto + '&WMax=' + wImgSchedaProdotto).load(checkImgLoad(null)).show(); }
    else { $('#smallPhoto4').hide(); }

    if (obj['PathImg2'] == '' && obj['PathImg3'] == '' && obj['PathImg4'] == '' && obj['PathImg5'] == '') {
        $('#mainPhoto').css('left', '550px');
        $('#testo').css('width', '470px');
    }
    else {
        $('#mainPhoto').css('left', '280px');
        $('#testo').css('width', '200px');
    }
}

function showMainProdottoTab() {
    $('#subProductsSelector').hide();
    bindProdottoTab(currentProduct);

    if (currentProduct["SubProdotti"] != null && currentProduct["SubProdotti"].length > 0) {
        $('#subProductsSelector').show();
        $('#mainSubProdottiSelector').hide();
        $('#secondarySubProdottiSelector').show();
        var backupHtml = $('#secondarySubProdottiSelector').children()[0].outerHTML;
        var subProduct;
        $('#secondarySubProdottiSelector').html(backupHtml);
        for (var idx = 0; idx < currentProduct["SubProdotti"].length; idx++) {
            subProduct = currentProduct["SubProdotti"][idx];
            $('#secondarySubProdottiSelector').append("<span class='subProductLinkSelector' onclick='showSubProdottoTab(" + idx + ");\'>" + subProduct['Titolo'] + "</span>");
        }
    }
}

function showSubProdottoTab(idx) {
    var subProduct = currentProduct["SubProdotti"][idx];
    bindProdottoTab(subProduct);

    $('#mainSubProdottiSelector').show();
    $('#secondarySubProdottiSelector').hide();
}

function ResizeProdottoTab() {
    $('#prodottoTab').width($('body').width() - margineSinistroAnimazione);
    $('#prodottoSheet').width($('#prodottoTab').width() - 50);
    $('#prodottoSheet').height($('#prodottoTab').height() - 20);
}

function showProdottoTab(idArticolo) {

    if (!schedaAnimating) {
        parent.ShowLoading();
        schedaAnimating = true;
        var url = "SchedaProdotto.aspx?id=" + idArticolo;
        var lang = parent.GetCurrentCodeLang();
        if (lang != null)
            url += "&lang=" + lang;
        $('#prodottoSheet').attr('src', url);
        ResizeProdottoTab();
        return;
    }

    var pos = ($('body').width() - 900) / 2;

    subProducts = null;

    var url = "Prodotti.aspx?w=ProdottoTab";
    var lang = parent.GetCurrentCodeLang();
    if (lang != null)
        url += "&lang=" + lang;
    $.getJSON(url + "&idArticolo=" + idArticolo, "",
           function(result) {
               imgCount = 0;
               imgTot = 1;

               $('#prodottoTab').width($('body').width() - margineSinistroAnimazione);
               $('#subProductsSelector').width($('body').width() - margineSinistroAnimazione);
               $('#subProductsSelector').css('display', 'none');

               currentProduct = result;
               showMainProdottoTab();
           });
}

function checkImgLoad(tag) {
    imgCount++;
    if (imgCount == imgTot) {
        $('#prodottoTab').show().animate({ marginLeft: margineSinistroAnimazione }, 2000, 'linear', function() {
            schedaAnimating = false;
        })
    }
}

function resizeBigPhoto(w, h) {
    h = Math.round(h * 450 / w);
    w = 450;
    if (h > 300) {
        w = w - (h - 300);
        h = 300;
    }

    $('#mainPhoto').css('height', h);
    $('#mainPhoto').css('width', w);
}

function resizeImmagine(idImmagine, larghezzaImg, altezzaImg, larghezzaMax, altezzaMax) {
    altezzaImg = Math.round(altezzaImg * larghezzaMax / larghezzaImg);
    larghezzaImg = larghezzaMax;
    if (altezzaImg > altezzaMax) {
        larghezzaImg = larghezzaImg - (altezzaImg - altezzaMax);
        altezzaImg = altezzaMax;
    }

    $('#' + idImmagine).css('height', altezzaImg);
    $('#' + idImmagine).css('width', larghezzaImg);
}

function GetAltezzaFromResize(larghezzaImg, altezzaImg, larghezzaMax, altezzaMax) {
    altezzaImg = Math.round(altezzaImg * larghezzaMax / larghezzaImg);
    larghezzaImg = larghezzaMax;
    if (altezzaImg > altezzaMax) {
        larghezzaImg = larghezzaImg - (altezzaImg - altezzaMax);
        altezzaImg = altezzaMax;
    }
    return altezzaImg;
}

function resizeImmagine(idImmagine, contesto, larghezzaImg, altezzaImg, larghezzaMax, altezzaMax) {
    altezzaImg = Math.round(altezzaImg * larghezzaMax / larghezzaImg);
    larghezzaImg = larghezzaMax;
    if (altezzaImg > altezzaMax) {
        larghezzaImg = larghezzaImg - (altezzaImg - altezzaMax);
        altezzaImg = altezzaMax;
    }

    $('#' + idImmagine, contesto).css('height', altezzaImg);
    $('#' + idImmagine, contesto).css('width', larghezzaImg);
}

function swapSmallToMainPhoto(img) {
    var src = $('#mainPhoto').attr("src");
    $('#mainPhoto').attr("src", img.src);
    img.src = src;

}

function openProdottoTab() {
    $('#prodottoTab').show().animate({ marginLeft: margineSinistroAnimazione }, 1000, 'linear',
        function() {
            schedaAnimating = false;
            parent.HideLoading();
        });
}

function hideProdottoTab() {
    if (!schedaAnimating) {
        schedaAnimating = true;
        var width = $("body").width();
        $('#prodottoTab').animate({ left: width }, 1000, 'linear', function() {
            $('#titolo').text('');
            $('#testo').text('');
            $('#prezzo').text('');
            $('#mainPhoto').attr("src", '');
            $('#smallPhoto1').attr("src", '');
            $('#smallPhoto2').attr("src", '');
            $('#smallPhoto3').attr("src", '');
            $('#smallPhoto4').attr("src", '');
            $('#prodottoTab').hide();
            $('#prodottoTab').css('left', 0).css('margin-left', width);
            schedaAnimating = false;
        });
        $('#prodottoSheet').attr('src', "");
    }
}


function scrollGallery(top, altezza) {
    var objheight = top;
    if (objheight <= altezza) {
        $('#su').hide(); $('#giu').hide();
    } else { $('#su').show(); $('#giu').show(); }

    if (flag == true) {
        $('#giu').click(function() {
            movedown();
        });

        $('#su').click(function() {
            moveup();
        });

        flag = false;
    }
}

function movedown() {
    s_pos = parseInt($('.scrollable').css('top'));

    if (s_pos > (altezzaDivProdotti * -1) + 179)
        $('.scrollable').css('top', s_pos -= 179);
}

function moveup() {
    s_pos = parseInt($('.scrollable').css('top'));

    if (s_pos < 0)
        $('.scrollable').css('top', s_pos += 179);
}

function animazioneFotoOver(element) {
    $('#' + element.id).parent('div').animate({ marginLeft: 5, marginRight: 5, width: 120 }, 250, "", function() {

    });
    larghezzaPrecedente = $('#' + element.id).width();
    $('#' + element.id).animate({ width: larghezzaPrecedente + 4, left: 10 }, 250);
}

function animazioneFotoOut(element) {
    $('#' + element.id).parent('div').animate({ marginLeft: 15, marginRight: 15, width: 102 }, 250, "", function() {

    });
    $('#' + element.id).animate({ width: larghezzaPrecedente, left: 2 }, 250);
}

function CheckUserLogged() {
    $.ajax({
        type: "POST",
        url: "Default.aspx/IsUserLogged",
        data: "{ }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            if (result.d) {
                $("#prezzo").css("visibility", "hidden");
            }
            else {
                $("#prezzo").css("visibility", "hidden");
            }
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert(xhr + ' ' + ajaxOptions + ' ' + thrownError);
        },
        complete: function() {
            //alert('finished');
        }
    });
}


$(document).ready(function() {
    CheckUserLogged();

    flag = true;
    altezzaFrame = parseInt($('#IframeDesign', top.document).height());

    $(window).resize(function() {
        $('.scrollable').css('top', 0);
        altezzaDivProdotti = $('.scrollable').height();
        altezzaFrame = parseInt($('#IframeDesign', top.document).height());
        // Faccio scomparire il navigatore
        if (altezzaDivProdotti <= altezzaFrame) {
            $('#su').hide(); $('#giu').hide(); //$("a.up").hide();
        } else { $('#su').show(); $('#giu').show(); }

        ResizeProdottoTab();
    });
    $('body').ajaxStart(function() { top.ShowLoading(); }).ajaxStop(function() { top.HideLoading(); });
    var html;
    $('#brand').empty();
    var url = "Prodotti.aspx?w=brand";
    var lang = parent.GetCurrentCodeLang();
    if (lang != null)
        url += "&lang=" + lang;
    $.getJSON("Prodotti.aspx?w=brand", "",
       function(result) {
           var firstBrand = null;
           var firstLogo = null;
           var firstDefault = null;
           $.each(result, function(entryIndex, entry) {
               var def = 'False';
               html = '<a class="linkBrand" id="lnk' + entry['idBrand'] + '" href="#" onclick="apriMenu(\'' + entry['idBrand'] + '\',\'' + entry['idLogo'] + '\',\'' + def + '\')"><img src="ImgManager.aspx?fileid=' + entry['idLogo'] + '&WMax=' + wBrand + '&HMax=' + hBrand + '" id="brd' + entry['idLogo'] + '" class="brand"/></a>';
               $('#brand').append(html);
               if (firstBrand == null) {
                   firstBrand = entry['idBrand'];
                   firstLogo = entry['idLogo'];
                   firstDefault = def;
               }
           });

           if (firstBrand != null)
               apriMenu(firstBrand, firstLogo, firstDefault);

       });

    parent.HideLoading();
});

function GetSheetWidth() {
    return $('#prodottoSheet').width();
}

function GetSheetHeight() {
    return $('#prodottoSheet').height();
}
