$(document).ready(function() {

    $('#webpage').height($(window).height() - 120);

    if ($("#nav li.products .sub ul.areas").height() < $("#nav li.products .sub ul").height()) { $("#nav li.products .sub ul.areas").height($("#nav li.products .sub ul").height()) }

    // recolor Body
    if ($('#colorpicker #picker').length > 0) {
        var bgColor = getCookie('bgColor');
        if ((bgColor == null)) { bgColor = '#444'; }
        $('html').css({ 'background-color': bgColor });
        var f = $.farbtastic('#colorpicker #picker');
        f.setColor(bgColor);
        f.linkTo(function() {
            $('html').css('background-color', f.color);
            setCookie('bgColor', f.color);
        });
    }

    // Hover Background Effect f. Productlist
    $('#productlist li')
		.append('<span class="hover">&nbsp;</span>')
		.find('.hover').css('opacity', 0).end()
		.hover(function() {
		    $('#productlist li div').hide();
		    $(this).css('z-index', 9999);
		    $(this).find('.hover').stop().animate({ 'opacity': 1 }, 500);
		    $(this).find('div').slideToggle('fast');
		}, function() {
		    $(this).find('div').hide();
		    //$('#productlist li div').hide();
		    $(this).css('z-index', 100);
		    $(this).find('.hover').stop().animate({ 'opacity': 0 }, 500);
		});
    $('#productlist li div').hover(function() { $('#productlist li div').hide(); });

    // Hover Background Effect f. EAN
    $('#EAN').click(function() {
        $('#EAN2').toggle();
    });

    //	Menu accordion on detail page
    $('#webpage .accordion ul')
    if ($('#webpage').hasClass('noscroll') == false) { $('#webpage .accordion ul').hide() }
    $('#webpage .accordion ul').prev('h3').css({ 'cursor': 'pointer' }).click(function() {
        $('.accordion ul:visible').slideUp();
        $(this).next('ul').not(':visible').slideToggle();
        setTimeout(function() {
            resizeProduct();
        }, 500);
    });

    // Subnavigation Accordion */
    $('.subnav ul ul').hide();
    $('.subnav span.active + ul').show();
    $('.subnav ul span').click(function() {
        $('.subnav ul ul:visible')
			.not($(this).nextAll('ul'))
			.slideUp()
			.prevAll('span')
			.removeClass('active');
        $(this).nextAll('ul').slideToggle();
        $(this).toggleClass('active');
    });

    //	listedmore
    $('.listed2 a.listedmore').click(function() {
        $('.listed2 div').slideUp();
        $('.listed2').css("background", "url(/img/bg/black_80.png)");
        $(this).parents("li").children('div').not(':visible').slideToggle();
        $(this).parents("li").css("background", "url(/img/bg/black_40.png)");
    });

    // Navigation
    if (navigator.userAgent.indexOf('iPad') != -1) {
        $('#nav li a.ipadnav').click(function() {
            $("#nav .sub").animate({ 'height': 0 }, 200);

            if ($(this).next().height() > 50) {
                $(this).next().stop().animate({ 'height': 0 }, 200);
            } else {
            var subHeight = $(this).next().children('ul:last-child').height()
            $(this).next()
			    .stop()
			    .animate({ 'height': subHeight }, 300);
            }

        }, function() {
            $(this).next()
			    .stop()
			    .animate({ 'height': 0 }, 200);
        });

    } else {
        $('#nav li').hover(function() {
            var subHeight = $(this).children('.sub').children('ul:last-child').height()
            $(this).children('.sub')
			    .stop()
			    .animate({ 'height': subHeight }, 300);
        }, function() {
            $(this).children('.sub')
			    .stop()
			    .animate({ 'height': 0 }, 200);
        });
    }



    // disable Image rightclick
    $('#productzoomer').bind("contextmenu", function(e) {
        e.preventDefault();
    });

    // icons tooltip
    $(".badgesi a[title]").tooltip({
        offset: [12, -63],
        effect: 'slide'
    });

    // FOOTER background hover opacity
    $('#footerbg')
    	.css({ 'opacity': 0 })
    	.parent('#footer').hover(
    		function() { $(this).find('#footerbg').stop().animate({ 'opacity': 1 }, 300); },
    		function() { $(this).find('#footerbg').stop().animate({ 'opacity': 0 }, 300); }
		);

    // Hide Colorpicker & Zoom
    $('#colorpicker .toggle').click(function() {
        $('#picker, #zoomer #controls').slideToggle('fast');
        $(this).toggleClass('open');
    });

    //PRODUKTBILDER SCROLLER
    $(".scrollable").scrollable({ easing: 'swing' });

    // Series & Latest & productimages
    var currentClass = '.current_page_item';
    var $el, leftPos, newWidth,
        $thumbs = $(".thumbs");

    $thumbs
    	.append('<em class="magic-bg">&nbsp;</em>');
    var $magicBG = $(".magic-bg");

    $magicBG
        .width('60px')
        .css("left", "-60px")
        .data("origLeft", "-60px")
        .data("origWidth", $magicBG.width());

    $(".thumbs a").hover(function() {
        $el = $(this);
        leftPos = $el.position().left;
        newWidth = $el.width() + 20;
        $(this).nextAll('em').stop().animate({
            left: leftPos,
            width: newWidth
        });
    }, function() {
        $(this).nextAll('em').stop().animate({
            left: $magicBG.data("origLeft"),
            width: $magicBG.data("origWidth")
        });
    });

    // Autovalue
    $('.autovalue').focus(
	    function() { $(this).val('') },
		function() { if ($(this).val() == '') { $(this).val($(this).attr("alt")) } }
	);
    $('.autovalue').blur(
		function() { if ($(this).val() == '') { $(this).val($(this).attr("alt")) } }
	);

    /* FADE THINGS */
    $(".fade").hover(function() {
        $(this).animate({ opacity: 0.40 }, 100);
    }, function() {
        $(this).animate({ opacity: 1 }, 100);
    });

    //EXTERNES FENSTER ÖFFNEN 
    $("a[rel='external']").click(function(event) {
        window.open($(this).attr("href"));
        event.preventDefault();
    });

    //ZOOMBARRIKADE
    $("#header").droppable({ tolerance: 'pointer' });
    $("#footerbg").droppable({ tolerance: 'pointer' });

    //SUCHE ausblenden
    $(".ajax").blur(function() {
        $(".results").delay(700).slideUp();
    });

    $('#background_images').cycle({
        fx: 'fade',
        speed: 2000,
        timeout: 10000
    });

});

$(window).bind('load resize', function() {
    resizeProduct();
    resizeBackground();
});

function setCookie(name, value) {
    document.cookie = name + "=" + value + ";path=/";
}

function getCookie(name) {
    var cookieArray = document.cookie.split(';');
    for (var i = 0; i < cookieArray.length; i++) {
        var nameValuePair = cookieArray[i].split('=');
        var xname = nameValuePair[0]
        while (xname.charAt(0) == ' ') {
            xname = xname.substring(1);
        }
        if (xname == name) return nameValuePair[1];
    }
    return null;
}

function resizeBackground() {

    // big background content image
     if ($('#background_images img').length > 0) {
        if (($(window).height() - 120) < $(window).width() / 1.6) {
            $('#background_images img').css("width", "100%");
            $('#background_images img').css("height", "auto");
        } else {
        $('#background_images img').css("height", "100%");
        $('#background_images img').css("width", "auto");
        }
        setTimeout(function() {
        $('#background_images').fadeIn(1000)
        }, 100);
    }
    
}

function resizeProduct() {
    // Page height for detail page
    // special detail jscripting for height and all the other detailed stuff
    if ($('#webpage').hasClass('noscroll')) {

        if (navigator.userAgent.indexOf('iPad') != -1) {
            $(".additional").fadeIn();
            $('#colorpicker .toggle').addClass('open');
            $('#picker, #zoomer #controls').hide();
        } else { 	
        
            var webpageheight = $(window).height() - 120;
            $('.noscroll').height(webpageheight);

            var leftheight = $("#filter").height() + $("#series").height() + 25 + $("#latest").height() + 25 + 60;
            var rightheight = $("#information").height() + 25 + 170 + 60;
            if (leftheight > webpageheight) {
                $(".additional").hide();
                $(".additional").css({ 'left': '240px' });
                $(".additional").fadeIn();
            } else {
                $(".additional").hide();
                $(".additional").css({ 'left': '20px' });
                $(".additional").fadeIn();
            }
            if (rightheight > webpageheight) {
                $('#colorpicker').css({ 'bottom': '335px', 'left': '296px' });
                $('#zoomer').css({ 'bottom': '335px', 'left': '240px' });
                $('#picker, #zoomer #controls').slideUp('fast');
                $('#colorpicker .toggle').removeClass('open');
            } else {
                $('#colorpicker').css({ 'bottom': '80px', 'left': 'auto' });
                $('#zoomer').css({ 'bottom': '80px', 'left': 'auto' });
                $('#picker, #zoomer #controls').slideDown('fast');
                $('#colorpicker .toggle').addClass('open');
            }
            
        };
    };
}

$(window).resize(function() {
    if ($('#webpage').hasClass('noscroll')) {
        var webpageheight = $(window).height() - 120;
        var zoomableHeight = $('div#productzoomer img').height();
        var zoomableWidth = $('div#productzoomer img').width();
        $('div#productzoomer img').css({ 'margin-left': zoomableWidth / 2 * -1 });
        $('div#productzoomer img').css({ 'margin-top': ((webpageheight - 60) - zoomableHeight) / 2 });
    }
});

// PRODCUTIMAGE PRELOAD
(function($) {
    var imgList = [];
    $.extend({
        preload: function(imgArr, option) {
            var setting = $.extend({
                init: function(loaded, total) { },
                loaded: function(img, loaded, total) { },
                loaded_all: function(loaded, total) { }
            }, option);
            var total = imgArr.length;
            var loaded = 0;
            setting.init(0, total);
            for (var i in imgArr) {
                imgList.push($("<img />")
					.attr("src", imgArr[i])
					.load(function() {
					    loaded++;
					    setting.loaded(this, loaded, total);
					    if (loaded == total) {
					        setting.loaded_all(loaded, total);
					    }
					})
				);
            }
        }
    });
})(jQuery);

// PRODCUTIMAGE SIZING & ZOOM
function doproductimage(zoomable) {

    // Zoom function
    var zoomDefault = 50;
    var zoomableWidth = $('div#productzoomer img').width();
    var zoomableHeight = $('div#productzoomer img').height();
    // calculate default size & position
    $('div#productzoomer img').width(zoomableWidth * zoomDefault / 100);
    $('div#productzoomer img').height(zoomableHeight * zoomDefault / 100);
    $('div#productzoomer img').css({ 'margin-left': zoomableWidth * zoomDefault / 100 / 2 * -1 });
    $('div#productzoomer img').css({ 'margin-top': (($('#webpage').height() - (zoomableHeight * zoomDefault / 100)) / 2) - 60 });

    // Call slider
    $('#zoomcontrol').slider({
        orientation: 'vertical',
        min: 39,
        max: 101,
        value: 50,
        step: 1,
        slide: function(event, ui) {
            // Show Slider value in Label
            $('#zoomer strong').text($(this).slider('value') + ' %');
        },
        stop: function(event, ui) {
            // Calculate new pixel width for image
            zoomableStretch = zoomableWidth * $(this).slider('value') / 100;
            zoomableStretchh = zoomableHeight * $(this).slider('value') / 100;
            // Resize & Position Image
            $('div#productzoomer img').css({
                'width': zoomableStretch,
                'height': zoomableStretchh,
                'margin-left': zoomableStretch / 2 * -1
            });
            // Restore Label
            $('#zoomer strong').text('Zoom');
        }
    });

    if (zoomable == 1) { zoombu(zoomableWidth, zoomableHeight); }

    // Make Image Draggable
    $('div#productzoomer img').draggable({ revert: "valid" });

}

function zoombu(zoomableWidth, zoomableHeight) {

    $('div#webpage').mousewheel(function(event, delta) {
        if (delta > 0) { $('#zoomer .in').trigger('click'); } else { $('#zoomer .out').trigger('click'); }
        return false;
    });

    // Zoom Buttons
    $('#zoomer .in, #zoomer .out').click(function() {
        var move = parseInt($(this).attr('rel')); // Steps of button
        var current = $('#zoomcontrol').slider('value'); // slider value

        // Calculate new Pixel width based on slider value
        zoomableStretch = zoomableWidth * ($('#zoomcontrol').slider('value') + move) / 100;
        zoomableStretchh = zoomableHeight * ($('#zoomcontrol').slider('value') + move) / 100;

        // Resize & Position Image
        $('div#productzoomer img').css({
            'width': zoomableStretch,
            'height': zoomableStretchh,
            'margin-left': zoomableStretch / 2 * -1
        });
        // Move Slider itself
        $('#zoomcontrol').slider('value', current + move);
    });

}
