﻿$(function() {
    /*if ($("#picbox").length > 0) {
    onLoadModel();
    }*/

    $("#search").keypress(function(event) {
        if (event.keyCode == '13') {
            document.location.href = "/models/search/" + $("#dept").val() + "?s=" + $("#search").val();
        }
    })

    if ($("#printbook").length > 0) {
        $("#printbook").attr("href", "/pdf/" + $("div.book-view ul:eq(0)").attr("id").substr(1));
        $("#printTools").show();
    }

    if ($(".vbook-view").length > 0) {
        $f("vp", "/Content/flowplayer-3.1.5.swf", {
            clip: { scaling: "fit" },
            plugins: { controls: null }
        }).playlist(".playlist").controls("appleControls");
    }

    if ($('ul.jcarousel-skin-tango').length > 0) {
        jQuery('ul.jcarousel-skin-tango').jcarousel({
            vertical: true,
            scroll: 3
        });

        $('div.jcarousel-skin-tango').hide();
        $('div.jcarousel-skin-tango').eq(0).show();
        $('div.jcarousel-skin-tango').eq(0).find('ul').show();
        $('div.jcarousel-skin-tango').eq(0).find('li').show();
        $('div.jcarousel-skin-tango').eq(0).find('a').eq(0).trigger('onclick');
    }

    if ($("#covers").length > 0) {
        $("#covers img").each(function() {
            var i = $(this);
            $(i).hide();
            var imgpath = $(i).attr("src");
            var img1 = new Image();
            var h2 = 0;
            $(img1).load(function() {
                var img1h = img1.height;
                var img1w = img1.width;
                h2 = getComputedHeight(img1w, 140, img1h);
                $(i).width(140);
                $(i).height(h2);
                $(i).show();
            }).error(function() {
                alert("can't load");
            }).attr('src', imgpath);
        })

        FillArrayWithCookie();
        $("#covers li a img").draggable({
            cursor: 'pointer',
            cursorAt: { top: 10, left: 10 },
            zIndex: 2700,
            appendTo: 'body',
            helper: function(event) {
                return $('<img src="' + $(this).attr("src") + '" height="80" alt="' + $(this).parent().attr("id") + '" />');
            }
        });

        $("#favbar div").droppable({
            tolerance: 'pointer',
            hoverClass: 'active',
            drop: function(event, ui) {
                if (AddToFavourites($(ui.draggable).parent().attr("id"), $(ui.draggable).parent().attr("title"), $(ui.draggable).attr("src"))) {
                    $(this).empty();
                    $(this).append('<img src="' + $(ui.draggable).attr("src") + '" height="80" alt="' + $(ui.draggable).parent().attr("id") + '" />');
                    $(this).bind("click", function() {
                        window.location.href = $(ui.draggable).parent().attr("href");
                    });
                }
            }
        });
    }
});


function checkWindow() {
    var ww = $(window).width();
    var wh = $(window).height();
    return [ww, wh];
}

function getContentHeight(wind) {
    return wind[1] - 280;
}

function getPictureHeight(wind) {
    return wind[1] - 300;
}

function getComputedWidth(h1, h2, w) {
    var ratio = h2 / h1;
    return Math.floor(w * ratio);
}

function getComputedHeight(w1, w2, h) {
    var ratio = w2 / w1;
    return Math.floor(h * ratio);
}

function onLoadModel() {
    $(".mrhide").hide();
    var windim = checkWindow();
    $(".content").height(getContentHeight(windim));
    
    
    var bookSelector = function() {
        if ($(".booktitles a").length > 1) {
            $(".actualbook").html($(".booktitles a").eq(0).html()).show();
            $(".booktitles a").each(function(i, item) {
                $(item).click(function() {
                    $(".actualbook").html($(item).html());
                    onLoadBook($("ul.thumbs").eq(i).find("li"), windim);
                    $(".actualbook").click();
                })
            });
            $(".actualbook").toggle(function() {
                $(".booktitles").show("slow");
                $(".actualbook").addClass("unfolded");
            }, function() {
                $(".booktitles").hide("slow");
                $(".actualbook").removeClass("unfolded");
            });
        } else {
            $(".booktitles").hide();
            $(".actualbook").html($(".booktitles a").eq(0).html()).hide();
            $(".actualbook").addClass("no-folded");
        }
    }
    
    bookSelector();
    var li_selected = $("ul.thumbs:eq(0)>li");
    onLoadBook(li_selected, windim);
}


function onLoadBook(lis, windim) {
    
    $("#picbox").show();
    var imgpath = "";
    var imgpath2 = "";
    var page = 0;

    var ulid = $(lis).parent().attr("id")
    var idbook = Number(ulid.substring(1));
    $("#printbook").find("a").attr("href","/pdf/" + idbook)

    var goToPage = function(pn) {
        if (pn >= $(lis).length) {
            page = 0;
        } else if (pn < 0) {
            page = ($(lis).length - 1);
        } else {
            page = pn;
        }
        setPage();
    };

    var updateButtons = function() {
        $("a.nav").unbind("click");
        $("a#npic").click(function() {
            goToPage(page + 1);
        });
        $("a#lpic").click(function() {
            goToPage(page - 1);
        });
    }

    var setPage = function() {
        clear();
        litoload = $(lis).eq(page);
        loadImages();
        updateButtons();
        $("#thumbstripe div img").removeClass("selected")
        $("#thumbstripe div img[title=p" + page + "]").addClass("selected");
        if (isIndexOpen) scrollThumbs();
    }

    var clear = function() {
        $('#picbox div').empty().addClass("loading");
    }

    var loadThumbs = function() {
        $("#thumbstripe div").empty();

        var stripewidth = 0;
        $(lis).each(function(i, item) {
            if ($(item).find("a").eq(0).length > 0) {
                $(item).find("a").eq(0).children("img").clone().appendTo("#thumbstripe div").attr("title", "p" + i).click(function() { goToPage(i) });
            }
            if ($(item).find("a").eq(1).length > 0) {
                $(item).find("a").eq(1).children("img").clone().appendTo("#thumbstripe div").attr("title", "p" + i).click(function() { goToPage(i) });
            }
            stripewidth += 270;
        });

        $("#thumbstripe div").width(stripewidth);

        $("#thumbnav a:eq(0)").click(function() {
            $("#thumbstripe").scrollTo('-=400px', 500);
        });
        $("#thumbnav a:eq(1)").click(function() {
            hideThumbs();
        });
        $("#thumbnav a:eq(2)").click(function() {
            $("#thumbstripe").scrollTo('+=400px', 500);
        });

        $("#showthumbs a").click(function() {
            showThumbs();
        });
    }

    var showThumbs = function() {
        $("#thumbstripe").slideDown("slow");
        $("#thumbnav").slideDown("slow");
        isIndexOpen = true;
        scrollThumbs();
        $("#footer").hide();
    }

    var scrollThumbs = function() {
        var goscroll = (page * 220) - 300
        if (goscroll > 0) {
            if (goscroll > $("#thumbstripe div").width()) {
                $("#thumbstripe").scrollTo($("#thumbstripe div").width(), 800);
            } else {
                $("#thumbstripe").scrollTo(goscroll, 800);
            }
        } else {
            $("#thumbstripe").scrollTo(0, 800);
        }
    }

    var hideThumbs = function() {
        $("#thumbstripe").slideUp("slow");
        $("#thumbnav").slideUp("slow");
        isIndexOpen = false;
        $("#footer").show();
    }

    var loadImages = function() {
        var maxheight = 0;
        if ($(litoload).find("a").eq(0).length > 0) {
            imgpath = $(litoload).find("a").eq(0).attr("href");
            var img1 = new Image();
            $(img1)
                    .load(function() {
                        var img1h = img1.height;

                        var img1w = img1.width;
                        $(img1).hide();
                        if (img1h > getPictureHeight(windim)) {
                            var img1hc = getPictureHeight(windim)
                            maxheight = img1hc;
                            $(img1).height(img1hc);
                            img1w = getComputedWidth(img1h, img1hc, img1w);
                        } else {
                            maxheight = img1h;
                        }

                        if ($(litoload).find("a").eq(1).length > 0) {
                            imgpath2 = $(litoload).find("a").eq(1).attr("href");
                            var img2 = new Image();
                            $(img2)
                            .load(function() {
                                var img2h = img2.height;
                                var img2w = img2.width;
                                $(img2).hide();


                                if (img2h > getPictureHeight(windim)) {
                                    var img2hc = getPictureHeight(windim)
                                    $(img2).height(img2hc);
                                    img2w = getComputedWidth(img2h, img2hc, img2w);
                                    if (img2hc > maxheight) {
                                        maxheight = img2hc;
                                    }
                                } else {
                                    if (img2h > maxheight) {
                                        maxheight = img2h;
                                    }
                                }

                                if (img1h < getPictureHeight(windim)) {
                                    var mt = Math.floor((getPictureHeight(windim) - img1h) / 2);
                                    $(img1).css("margin-top", mt + "px");
                                }
                                if (img2h < getPictureHeight(windim)) {
                                    var mt = Math.floor((getPictureHeight(windim) - img2h) / 2);
                                    $(img2).css("margin-top", mt + "px");
                                }
                                
                                

                                var totw = img1w + img2w;

                                if (totw > (windim[0] - 40)) {
                                    //le immagini sono troppo larghe
                                }
                                $("#picbox").width(totw + 10);

                                $("#lpic").css("top", (Math.floor(maxheight/2)-10) + "px");
                                $("#npic").css("top", (Math.floor(maxheight / 2) - 10) + "px");
                                
                                showPicture(1, img1);
                                showPicture(2, img2);
                            })
                            .error(function() {
                                alert("can't load");
                            })
                            .attr('src', imgpath2);
                        } else {
                            $('#picbox div:eq(1)').removeClass('loading').addClass('empty').height(maxheight);
                            var totw = img1w;
                            $("#picbox").width(totw + 10);

                            $("#lpic").css("top", (Math.floor(maxheight / 2) - 10) + "px");
                            $("#npic").css("top", (Math.floor(maxheight / 2) - 10) + "px");
                            
                            showPicture(1, img1);
                        }

                    })
                    .error(function() {
                        alert("can't load");
                    })
                    .attr('src', imgpath);
        } else {
            $('#picbox div:eq(0)').removeClass('loading').addClass('empty');
        }

    };

    var showPicture = function(n, im) {
        var onclickpicture = null;
        if (n == 1) {
            onclickpicture = function() { goToPage(page - 1); }
        } else {
            onclickpicture = function() { goToPage(page + 1); }
        }

        $('#picbox div:eq(' + (n - 1) + ')')
                .removeClass('loading')
                .append(im)
                .unbind("click")
                .click(function() { onclickpicture(); });
        $(im).fadeIn();
    }

    hideThumbs();
    var isIndexOpen = false;
    
    loadThumbs();
    setPage();
}



///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// FUNZIONI DRAG & DROP DELLA MODELLA
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var namesArray = new Array();
var idsArray = new Array();
var photoArray = new Array();
var separator = '^#^';

function FillArrayWithCookie() {
    if ($.cookie('nw_favourite_ids') == null || $.cookie('nw_favourite_ids') == '') {
        namesArray = new Array();
        idsArray = new Array();
        photoArray = new Array();
        $.cookie('nw_favourite_ids', null);
        $.cookie('nw_favourite_names', null);
        $.cookie('nw_favourite_photos', null);
        return;
    }

    idsArray = $.cookie('nw_favourite_ids').split(separator);
    namesArray = $.cookie('nw_favourite_names').split(separator);
    photoArray = $.cookie('nw_favourite_photos').split(separator);

    for(var i = 0; i<10; i++)
    {
        if(idsArray[i] != null)
            $('#favbar div').eq(i).html('<img src="' + photoArray[i] + '" height="80" alt="' + idsArray[i] + '" onclick="window.location.href=\'/models/'+idsArray[i]+'/'+escape(namesArray[i].replace(" ","-"))+'.html\';" />');
    }
}

function AddToFavourites(modelid, modelname, modelphoto) {
    if (jQuery.inArray(modelid, idsArray) < 0) {
        idsArray.push(modelid);
        namesArray.push(modelname);
        photoArray.push(modelphoto);
        $.cookie('nw_favourite_ids', idsArray.join(separator), { expires: 2 });
        $.cookie('nw_favourite_names', namesArray.join(separator), { expires: 2 });
        $.cookie('nw_favourite_photos', photoArray.join(separator), { expires: 2 });

        return true;
    }
    return false;
}

function RequestInfoClick() {
    if (namesArray.length > 0) {
        strmail = "mailto:info@boomtheagency.it?subject=portfolio%20request&body=" + escape(namesArray.join("\n"));
        location.href = strmail;
    }
    else {
        alert('You must select at least one model');
    }
}

function ClearFavourites() {
    namesArray = new Array();
    idsArray = new Array();
    photoArray = new Array(); ;
    $.cookie('nw_favourite_ids', null);
    $.cookie('nw_favourite_names', null);
    $.cookie('nw_favourite_photos', null);
    $("#requestinfo").attr("href", '#');
    for (var i = 0; i < 10; i++) {
        $('#favbar div').eq(i).empty();
    }
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function ShowPicture(url, name) {
    $("#picbox").html('<img src="' + url + '" alt="' + name + '" / >');
}

function ShowBook(book) {
    $('div.jcarousel-skin-tango').hide();
    $('.playlist').hide();
    $('.vbook-view').hide();
    $('.book-view').show();
    $('#' + book).parent().parent().parent().show();
    $("#printbook").attr("href", "/pdf/" + book.substr(1));
    $("#printTools").show();
}

function ShowVideoBook(book) {
    $('.thumbs').hide();
    $('.playlist').hide();
    $('.book-view').hide();
    $('.vbook-view').show();
    $('#' + book).show();
    $("#printTools").hide();
}
