var thumbs_box_height = 150;
var thumbs_box_width = 170;

var thumbsbook_box_height = 120;
var thumbsbook_box_width = 96;

var full_pic_width = 600;
var full_pic_height = 450;

var full_pic_box_width = 600;
var full_pic_box_height = 450;
var lastzindex = 100;

function loadFlashBg() {
    var swf_h = $(document).height();
    var swf_w = $(document).width();
    var swf_max = swf_w;
    if (swf_h > swf_w) swf_max = swf_h;
    if (swf_max < 960) swf_max = 960;
    var divheight = 600;
    if ($(document).height() > 684) {
        $("#div_bg").height($(document).height() - 84);
    }
    var flashvars = {};
    var params = {
        wmode: "transparent"
    };
    var attributes = {};
    swfobject.embedSWF("/_Custom/bg.swf", "bg", swf_max, swf_max, "8.0.0", "expressInstall.swf", flashvars, params, attributes);
}

function loadNoFlashBg() {
    if ($(document).height() > 684) {
        $("#div_bg_noflash").height($(document).height() - 84);
    }
    if ($(document).height() > 684) {
        $("#bg_noflash").height($(document).height() - 84);
    }
}


function checkWindow() {
	var ww = $(window).width();
	var wh = $(window).height();
	return [ww, wh];
}

function getContentHeight() {
    return pic_box_height;
}

function getPictureHeight() {
    return pic_height;
}

function getContentWidth() {
    return pic_box_width;
}

function getPictureWidth() {
    return pic_width;
}

function getComputedWidth(h1, h2, w) {
    if (h1 > 0) {
        var ratio = h2 / h1;
        return Math.floor(w * ratio);
    } else {
        return pic_width;
    }
}

function getComputedHeight(w1, w2, h) {
    if (w1 > 0) {
        var ratio = w2 / w1;
        return Math.floor(h * ratio);
    } else {
        return pic_height;
    }
}

function leftPad(n, len) {  
	return (new Array(len - String(n).length + 1)).join("0").concat(n);  
}

$(function () {
    //applesearch.init();

    if ($("#div_bg").length > 0) {
        loadFlashBg();
        $(window).resize(loadFlashBg);
    }
    if ($("#div_bg_noflash").length > 0) {
        loadNoFlashBg();
        $(window).resize(loadNoFlashBg);
    }

    /*
    if ($("#playerhome").length > 0) {
    $f("playerhome", "/content/flowplayer-3.2.4.swf");
    }
    */

    var today = new Date();
    var today2 = new Date("September 17, 2011");

    var videofile = '/Content/video.flv';
    if (today >= today2) {
        videofile = "/Content/video-home.mp4";
    }
    if ($("#video-home").length > 0) {
        jwplayer('video-home').setup({
            flashplayer: '/Content/jwplayer/player.swf',
            file: videofile,
            height: 360,
            width: 640,
            autostart: true
        });
    }

    if ($("#model-selector").length > 0) {
        createModelSelectorDropDown();
    }

    if ($("#video_place").length > 0) {
        $f("vp", "/Content/flowplayer-3.2.4.swf", { "clip": { scaling: "fit" }, "screen": { "height": "100pct", "top": 0 }, "plugins": { "controls": { "borderRadius": "0px", "timeColor": "#ffffff", "bufferGradient": "none", "slowForward": true, "backgroundColor": "rgba(0, 0, 0, 0)", "volumeSliderGradient": "none", "slowBackward": false, "timeBorderRadius": 20, "time": true, "progressGradient": "none", "height": 26, "volumeColor": "#4599ff", "tooltips": { "marginBottom": 5, "volume": true, "scrubber": true, "buttons": false }, "opacity": 1, "fastBackward": false, "timeFontSize": 12, "volumeSliderColor": "#ffffff", "bufferColor": "#a3a3a3", "border": "0px", "buttonColor": "#ffffff", "mute": true, "autoHide": { "enabled": true, "hideDelay": 500, "hideStyle": "fade", "mouseOutDelay": 500, "hideDuration": 400, "fullscreenOnly": true }, "backgroundGradient": "none", "width": "100pct", "display": "block", "sliderBorder": "1px solid rgba(128, 128, 128, 0.7)", "buttonOverColor": "#ffffff", "fullscreen": true, "timeBgColor": "rgb(0, 0, 0, 0)", "scrubberBarHeightRatio": 0.2, "bottom": 0, "stop": false, "zIndex": 1, "sliderColor": "#000000", "scrubberHeightRatio": 0.6, "tooltipTextColor": "#ffffff", "sliderGradient": "none", "timeBgHeightRatio": 0.8, "volumeSliderHeightRatio": 0.6, "name": "controls", "timeSeparator": " ", "volumeBarHeightRatio": 0.2, "left": "50pct", "tooltipColor": "rgba(0, 0, 0, 0)", "playlist": false, "durationColor": "#b8d9ff", "play": true, "fastForward": true, "progressColor": "#4599ff", "timeBorder": "0px solid rgba(0, 0, 0, 0.3)", "scrubber": true, "volume": true, "builtIn": false, "volumeBorder": "1px solid rgba(128, 128, 128, 0.7)"}} }).playlist(".playlist");
        //.controls("appleControls");
        if ($("#currentvideobook").length > 0) {
            ShowVideoBook2($("#currentvideobook").val());
        }
    }



    if ($("#gallery_place").length > 0) {
        var idb = $("#gallery_place").attr("title");
        var xurl = "/model/books/" + idb + ".xml";
        var flashvars = { xmlurl: xurl };
        var params = { wmode: "transparent" };
        var attributes = {};
        swfobject.embedSWF("/Content/polaroid_d1.swf", "gallery_place", 740, 600, "8.0.0", "expressInstall.swf", flashvars, params, attributes);
        $("#contentBook").css("visibility", "visible");
        $("a.boo").eq(0).addClass("selected");
        $("#print-btn").attr("href", "/pdf/" + idb);
        $('#print-btn').show();
    }

    if ($("#book_viewer").length > 0) {
        book_onload();
    }

    var ws = checkWindow();
    $(".scrollable").height(ws[1] - 280);
    $(".scrollable").jScrollPane();
    $(".scrollableFixed").jScrollPane();

    if ($(".book-covers").length > 0) {
        $(".book-covers li img").one("load", function () {
            var im = $(this);
            var pic_height = $(im).height();
            if (pic_height < thumbs_box_height) {
                var mt = Math.floor((thumbs_box_height - pic_height) / 2);
                $(im).css("margin-top", mt + "px");
            }
            $(im).fadeIn("slow", function () {
                $(this).parent().next().find("h3").fadeIn("slow");
            });
        })
		.each(function () {
		    if (this.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6))
		        $(this).trigger("load");
		});
    }
});

function onLoadVideoBook(lis) {
	$(".playlist").hide("fast");
	$("#gallery_place").hide("fast");
	if ($(lis).find("a").length > 1) {
		$(lis).show("fast");
	}
	$("#video_place").show("fast");
	$f(0).play();

	$("#print-btn").attr("href", "#");
	$('#print-btn').hide();
}

function ShowVideoBook2(id) {
    $(".playlist").hide();
    if ($('#vb' + id).find("a").length > 1) {
        $('#vb' + id).show("fast");
    }
    $("#video_place").show("fast");
    $("#contentBook").css("visibility", "visible");
    $f(0).play();
}

function ShowVideoBook(id,el) {
    $(".playlist").hide();
    $("#gallery_place").html('').hide();
    if ($('#vb'+id).find("a").length > 1) {
        $('#vb' + id).show("fast");
    }
    $("#video_place").show("fast");
    $f(0).play();
    $("#print-btn").attr("href", "#");
    $('#print-btn').hide();
    $("a.boo").removeClass("selected");
    $(el).addClass("selected");
}

function ShowFlashBook(idb,el) {
    $("#video_place").hide();
    var xurl = "/model/books/" + idb + ".xml";
    var flashvars = { xmlurl: xurl };
    var params = { wmode: "transparent" };
    var attributes = {};
    swfobject.embedSWF("/Content/polaroid_d1.swf", "gallery_place", 740, 600, "8.0.0", "expressInstall.swf", flashvars, params, attributes);
    $("#contentBook").css("visibility", "visible");
    $("a.boo").removeClass("selected");
    $(el).addClass("selected");
	$("#print-btn").attr("href", "/pdf/" + idb);
    $('#print-btn').show();
}



function book_onload(ulvar) {
    $(".book-page").empty();
    
    var ulbook = null;
    switch (typeof ulvar) {
        case null:
        case "undefined":
            ulbook = $("#hiddenbooks ul:first");
            break;
        case "object":
            ulbook = ulvar;
            break;
        case "number":
        case "string":
            ulbook = $("#hiddenbooks ul[id='b" + ulvar + "']");
            break;
        default:
            ulbook = $("#hiddenbooks ul:first");
            break;
    }

    

    var page = 0;
    var npages = $(ulbook).children("li").length;
    var idbook = Number($(ulbook).attr("id").substring(1));
    $("#video_place").hide();
    $("#book_viewer").show();
    $("a.boo").removeClass("selected");
    $("a.boo[id='b" + idbook + "']").addClass("selected");
    page_onload(page, ulbook);
}

function page_onload(p, u) {
    var bp = $(".book-page");
    $(bp).empty();
    var pli = $(u).find("li").eq(p);
    var totw = 0;
    nomargin = false;
    $(pli).find("a").each(function (i, item) {
        var imgpath = $(item).attr("href");
        var img = new Image();
        $(img).load(function () {
            $(this).css("display", "none");
            var c = Math.floor(Math.random() * 8);
            $(this).addClass("rot" + c.toString());
            $(bp).append(this);
            $(this).click(function () { goToPage(p + 1, u); });
            $(this).fadeIn("fast", function () { });
        }).error(function () {
            //non carica foto
        }).attr("src", imgpath);
    });
}

function goToPage(pn, ul) {
    var page = pn;
    var lis = $(ul).children("li");
    if (pn >= $(lis).length) {
        page = 0;
    } else if (pn < 0) {
        page = ($(lis).length - 1);
    } else {
        page = pn;
    }
    page_onload(page, ul);
}




function ShortlistAdd() {
    $.getJSON($("a.addsl").eq(0).attr("href"), function (data) {
        if (data != null)
            $('#addslbtn').unbind("click").addClass("selected").html("in your shortlist");
    });
}

function toggleSel() {
    $("#applesearch").toggle();
    $("#towatchsel").toggle();
}



//vecchie funzioni

/*
function onLoadBook(lis) {
var page = 0;

//recupero l'id del book
var ulid = $(lis).parent().attr("id")
var idbook = Number(ulid.substring(1));

$("#print-btn").attr("href", "/pdf/" + idbook);
$('#print-btn').show();

$("#video_place").hide("fast");
$("#picture_place").empty();
$("#picture_place").show("fast");

var indice = 0;
$(lis).each(function (indp, lipic) {
if ($(lipic).find("a").eq(0).length > 0) {

imgpath = $(lipic).find("a").eq(0).attr("href");
imgid = $(lipic).find("a").eq(0).attr("id");
var img1 = new Image();
$(img1).load(function () {
var randomnumber = Math.floor(Math.random() * 151);
var randomnumber2 = Math.floor(Math.random() * 401);
$(this).animate({
"top": "+=" + randomnumber + "px", "left": "+=" + randomnumber2 + "px"
}, "fast").css("position", "absolute");
$(img1).draggable({ containment: $("#over_bg") })
.bind("mousedown", function () {
lastzindex += 1;
$(this).css("z-index", lastzindex);
}).fancybox({
titlePosition: 'over'
});
$("#picture_place").append(this);
})
.error(function () {
alert("can't load");
})
.attr('src', imgpath)
.attr('id', imgid);
}
indice++;
});
$("#contentBook").css("visibility", "visible");
}
*/

/*
function onLoadModel() {
$(".mrhide").hide();
$("#book-selector li").eq(0).addClass("sel");

var bookSelector = function () {
$("#book-selector a").each(function (i, item) {
$(item).click(function () {
$("#book-selector li").removeClass("sel");
onLoadBook($("#hiddenbooks ul.thumbs").eq(i).find("li"));
$(item).parent().addClass("sel");
})
});
}

bookSelector();

var videoBookSelector = function () {
$("#videobook-selector a").each(function (i, item) {
$(item).click(function () {
$("#videobook-selector li").removeClass("sel");
onLoadVideoBook($("#video_place div.playlist").eq(i));
$(item).parent().addClass("sel");
})
});
}
videoBookSelector();
var li_selected = $("ul.thumbs:eq(0)>li");
onLoadBook(li_selected);
}
*/

/*
function createModelSelectorDropDown(){
	var source = $("#idm");
	var selected = source.find("option[selected]");
	var options = $("option:gt(1)", source);
	var ms = $("#model-selector");
    $(ms).empty();
	
	$(ms).append('<div class="dropdown"><ul></ul></div>')
	options.each(function(){
		$("div.dropdown ul").append('<li><a id="' + $(this).val() + '" href="#">' + $(this).text() + '</a></li>');
    }); 
    $("div.dropdown").after('<a class="dropdown-selected dd-close" href="#">Choose a model</a>');
	$("div.dropdown ul li a").click(function() {
		window.location.href = "/Models/" + $("#currentdept").val() + "/" + $(this).attr("id") + "/" + $(this).html().toUpperCase().replace(" ","-") + ".html";
		return false;
    });
    var pos_link = $("a.dropdown-selected").position();
    var h_link = $("a.dropdown-selected").outerHeight();
    
    //posiziono il drop-down
    $("div.dropdown").css("top", (pos_link.top + h_link + 2) + "px");
    $("div.dropdown").css("left", (pos_link.left) + "px");
    $("div.dropdown").css("width", $("a.dropdown-selected").width() + "px");

	$("a.dropdown-selected").click(function () {
		if ($("div.dropdown").css("display") == "block") {
			$("div.dropdown").hide("slow");
			$(this).removeClass("dd-open");
			$(this).addClass("dd-close");
		} else {
			$("div.dropdown").show("slow");
			$("div.dropdown ul").jScrollPane();
			$(this).removeClass("dd-close");
			$(this).addClass("dd-open");
		}
	});
	
	$(document).bind('click', function(e) {
		var $clicked = $(e.target);
		if (! $clicked.parents().hasClass("dropdown"))
		{	
			if (! $clicked.hasClass("dropdown-selected")) {
				$("div.dropdown").hide("slow");
				$("a.dropdown-selected").removeClass("dd-open");
				$("a.dropdown-selected").addClass("dd-close");
			}
		}
	});
}
*/
