$(window).load(function(){

	//cut bg-image and insert on top of the page... IE6
	$('#bg-image').insertBefore('#container');
	//$('#bg-image img').attr('src',$('#bg-image').attr('src').replace('.jpg','_small.jpg'));
	
	/* IE>6 needs display: table for wittmann-collection */
	/*if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
		$(".user-wittmanncollections-pi1").css("display", "table");
	}*/

    /***********************
    * THUMBNAILS SLIDER
    ************************/
    function positionThumbnails() {
        
        var containerWidth = $(".pagination").width();
        var maxWidth = $("#loopedSlider").width() - 55;
        
        if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
            maxWidth = 580;
        }
        
        
        // left position
        var prevWidth = 0;
        $(".thumb_view .thumbs ul li.active").prevAll().each(function() {
            prevWidth += $(this).width();
        });
        // right position (incl. active element)
        var nextWidth = $(".thumb_view .thumbs ul li.active").width();
        $(".thumb_view .thumbs ul li.active").nextAll().each(function() {
            nextWidth += $(this).width();
        });
    
        // set left position
        $(".pagination").css("left", -prevWidth);
        
        // calculate width
        var found = false, newWidth = $(".thumb_view .thumbs ul li.active").width();
        $(".thumb_view .thumbs ul li.active").nextAll().each(function() {
            if (!found && newWidth + $(this).width() < maxWidth) {
                newWidth += $(this).width();
            } else {
                found = true;
            }
        });
    
        // last elements don't go too far left
        if (nextWidth < maxWidth) {
            var tmpWidth = 0, resultWidth = 0;
            $($(".thumb_view .thumbs ul li").get().reverse()).each(function() {
                tmpWidth += $(this).width();
                if (tmpWidth < maxWidth) {
                    resultWidth = tmpWidth;
                }
            });
            // overwrite newWidth
            newWidth = resultWidth;
    
            $(".pagination").css("left", -(containerWidth - resultWidth));
        }

        // set width, center visible elements
        $(".thumb_view").width(newWidth);
        var tmpLeft = (maxWidth - newWidth) / 2;
        $(".thumb_view").css("margin-left", tmpLeft);
        $(".thumb_view .next_prev").css("margin-left", maxWidth - tmpLeft);
        
        // show/hide arrows
        $("#btn_next, #btn_prev").show();
        $("#btn_next_disabled, #btn_prev_disabled").remove();
        var currentID = $(".thumb_view .thumbs ul li.active a").attr("rel");
        if (currentID == $(".thumb_view .thumbs ul li:first-child a").attr("rel")) {
            $("#btn_prev").hide();
            $(".next_prev").prepend($('<span id="btn_prev_disabled" class="previous"></span>'));
        }
        if (currentID == $(".thumb_view .thumbs ul li:last-child a").attr("rel")) {
            $("#btn_next").hide();
            $(".next_prev").append($('<span id="btn_next_disabled" class="previous"></span>'));     
        }
        $("#btn_next_disabled, #btn_prev_disabled").css("opacity", 0.2);    
    }
    
    
    positionThumbnails();
    
    
    $("#loopedSlider").css({opacity: 0, visibility: 'visible'});
    $("#loopedSlider").animate({ opacity: 1}, 500);
            
    $("#btn_next, #btn_prev").click(positionThumbnails);
    $(".pagination li a").click(positionThumbnails);


    //IE Bugfix
    //positionFooter();	
	
    //ZOOM IMG
    //zoomImg();
});

function ie6FixPositionFooter() {
    if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
        documentHeight = $(document).height();
        screenHeight = $("#container").height();
        //alert('DH: '+documentHeight+' SH: '+screenHeight);
        if (screenHeight < documentHeight) {
			var pos = documentHeight + 'px';
            $('#footer').css({'position': 'absolute', 'top': pos})
        }
    }
}

function positionFooter() {
    documentHeight = $(document).height();
    screenHeight = $("#container").height(); 
    
    if (screenHeight < documentHeight) {
        $("#container").css("height", "auto");
    } else {
        $("#container").css("height", "100%");
    }
    
    
    //IE6 Bugfix => position footer horizontally centered
    if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
        windowWidth = $(window).width();
        contentWidth = $("#container").width();
        $("#footer").css("left", (windowWidth - contentWidth) / 2 );
    }
    
};

function zoomImg() {
        
	var wBefore = $('.background_animation').attr('width');
	var hBefore = $('.background_animation').attr('height');
	var lBefore = 0;
	var tBefore = 0;
	
	//berechnung
	var wAfter = parseInt(wBefore * 1.2);
	var hAfter = parseInt(hBefore * 1.2);
	
	//console.log('wBefore: '+ wBefore + ' // wAfter: '+wAfter);
	//console.log('hAfter: '+hAfter);
	
	var lAfter = ((wAfter - wBefore) * -1);
	var tAfter = (hAfter - hBefore) * -1;
	
	//console.log('lAfter: '+lAfter);
    //console.log('tAfter: '+tAfter);
        
	setTimeout(function() {
		$('.background_animation').animate( {	    
			width: wAfter + 'px',
			height: hAfter + 'px',	//safari-problem mit height
			left: lAfter + 'px',
			top: tAfter + 'px'
		}, {
			duration: 12000/*, 
			step: function(){
			    $('.background_animation').css({
			        //margin: '0px 5px'
			    });
			},
			complete: function() {
			    console.log('Animation complete.');
			}*/
		});
	}, 500);
}

var i = 0;
function furnitureFadeIn() {
    var count = 5;
    var current = i % count;
    var next = (current + 1) % count;
    
	var curImage = $('#NC-slider-container li').eq(current);
	var nextImage = $('#NC-slider-container li').eq(next);	
	
	curImage.fadeOut(3000);
	//nextImage.css('filter', 'alpha(opacity=05)');
    nextImage.delay(3050).fadeIn(6000);
	
    i++;
}

$(document).ready(function(){
    
	if ($('#bg-image').length > 0  || $('#NC-slider').length > 0) {
		WUtils.init();
	} else {
		//IE6 Bugfix => position footer
		ie6FixPositionFooter();
	}
	
	//pngfix
	//$(document).pngFix();	
	
	// translate search menu item
	var language = $.getUrlVar('L');
	if (language == 1) {
	   $("#search_form a").html("Search");
	}
	
	
	//STARTPAGE FADE IN
    $('#NC-slider-container li').eq(0).show();     
    setInterval("furnitureFadeIn()", 9100);

	
	//DETAIL
	if($('#ein_echter_wittmann #more_info .detailverliebt').text() == '') {
		$('#ein_echter_wittmann #more_info .detailverliebt').siblings('.wrap').children().children('a.more_info_detail').attr('style', 'top:90px');
	}
		

    /* footer IE7 bug */ 
    //positionFooter();
    
    /* showroom, haendlersuche slide up */ 
    $(".showroom_arrow").toggle(function() {
        $(this).siblings(".slide_up_content").slideUp(1000, function() {
            $(this).siblings(".showroom_arrow").addClass("side");       
        });
    }, function() {
        $(this).siblings(".slide_up_content").slideUp(1000, function() {
            $(this).siblings(".showroom_arrow").addClass("side");       
        });    
    }); 

    
    /* activate loopedSlider*/
    if ($('#wittmann_box_craft').size() != 0) {
        $('#wittmann_box_craft').loopedSlider({
            slidespeed: 400
        });
    }
    
     /*************************************
     * erlebniswertstatt thumb bg switcher
     **************************************/
    $("#workshop_thumbs ul li img").click(function(){
        var img = $(this).attr("hoversrc");
        $("body img#background").attr('src', img);
    });
    
    /*************************************
     * real_wittmann_box show/hide
     *************************************/
    $("#real_wittmann_box_button").click(function(){
        $(this).nextAll("#wittmann_box_craft, .real_wittmann_box, #ein_echter_wittmann, .next_prev").toggle();
        
        //change close buttons
        var src1 = $(this).find("img").attr("switchsrc");
        var src2 = $(this).find("img").attr("src");
        $(this).find("img").attr({
            src: src1,
            switchsrc: src2
        });
    });
    
	
	 /*************************************
     * contract_box show/hide
     *************************************/
    $("#contract_box_button").click(function(){
        $(this).nextAll(".contract_box").toggle();
        
        //change close buttons
        var src1 = $(this).find("img").attr("switchsrc");
        var src2 = $(this).find("img").attr("src");
        $(this).find("img").attr({
            src: src1,
            switchsrc: src2
        });
    });
	
    
    /*************************************
     * reedition_box show/hide
     *************************************/
    $("#re_edition_box_button").click(function(){
        $(this).nextAll(".re_edition_box").toggle();
        
        //change close buttons
        var src1 = $(this).find("img").attr("switchsrc");
        var src2 = $(this).find("img").attr("src");
        $(this).find("img").attr({
            src: src1,
            switchsrc: src2
        });
    });
    
    
    /*************************************
     * real_wittmann_box content switch
     *************************************/
    clicks = 0; 
    
    $("div.real_wittmann_box.craft_design .slides div").each(function(i){
        var pages = i+1;
        $(this).attr('rel', pages);
    });
    $("div.real_wittmann_box.craft_design .slides div:first-child").addClass("current");
    
    craftContent();
    
    clicks = 0;

    $("#btn_next_craft").click( function() {
        clicks++; 
        if (clicks == 1) {
            craftContent("next");
        }
    });
    $("#btn_prev_craft").click( function() {
        clicks++; 
        if (clicks == 1) {
            craftContent("prev"); 
        } 
    });

    function craftContent(direction) {
    // show/hide arrows
        $('#btn_next_craft').dblclick(function() {
            return false; 
        });
        

        $("#btn_next_craft_disabled, #btn_prev_craft_disabled").remove();
        var currentID = $("div.real_wittmann_box.craft_design .slides div.current").attr("rel");
        currentObject = $("div.real_wittmann_box.craft_design .slides div.current");
 
        $("#btn_prev_craft, #btn_next_craft").show();
            
        setTimeout(function() {
        if (direction == "next") {
            $(currentObject).next().addClass("current");
            $(currentObject).removeClass("current");
            currentID++; 
        } else if (direction == "prev") {
            $(currentObject).prev().addClass("current");
            $(currentObject).removeClass("current");    
            currentID--;             
        } else {
            currentID = 1;    
            /* handwerk, design slider load */
            $("#wittmann_box_craft .slides, .next_prev_craft").css("visibility", "visible");
            $(".next_prev_craft").show();
        }
       
        if (currentID == $("div.real_wittmann_box.craft_design .slides div:first-child").attr("rel")) {
            $("#btn_prev_craft").hide();
            $(".next_prev_craft").prepend($('<span id="btn_prev_craft_disabled" class="previous"></span>'));
        }
        if (currentID == $("div.real_wittmann_box.craft_design .slides div:last-child").attr("rel")) {
            $("#btn_next_craft").hide();
            $(".next_prev_craft").append($('<span id="btn_next_craft_disabled" class="previous"></span>'));     
        }
        $("#btn_next_craft_disabled, #btn_prev_craft_disabled").css("opacity", 0.2);     
        clicks = 0; 
        }, 300);
    }
   
    
    /* wittmann handerk design prev, next slider */
    $("#btn_next, #btn_prev, #btn_next_craft, #btn_prev_craft").hover(function() {
        if ($(this).css("opacity") == 1.0) {
            $(this).addClass("hover"); 
        } else {
            $(this).css("cursor", "default");
        }
    }, function() {
        $(this).removeClass("hover");    
    }); 
    
    
    /**********************
     * DESIGNER OVERLAYS
     **********************/
    designerLinks = $("#designer .list li p a:not(.works)");
    if (designerLinks.length > 0) {
        designerLinks.addClass("EH-overlay");
        designerLinks.css("text-decoration", "underline");
    }
    
    /*******************
     * BACKGROUND IMAGE
     *******************/
	 //WUtils.resizeBackground(); 
    
    /*****************************************
     * UPDATE producttype via active thumbnail 
     *****************************************/
    
    $(".pagination li a").click(function() {
        var furnitureType = $(this).parent().attr("tname");
        var furnitureTypeId = $(this).parent().attr("tid");
        var typeLink = $("#product_detail dl:eq(0) dd a");
		var isLink = true;
		
		if (typeLink.length<=0) {		  
			typeLink = $("#product_detail dl:eq(0) dd");
			isLink = false;
	    }
	    		
        if (furnitureType && furnitureTypeId) {			
			// reset link href
			if (isLink) {
				var link = typeLink.attr("href").replace(/([&?])ft=[0-9]+/, '$1ft=' + furnitureTypeId);
				typeLink.attr("href", link); 
			}
			
			// reset text
            typeLink.html(furnitureType);
        }
    });
    
    $("#loopedSlider .next, #loopedSlider .previous").click(function() {
        setTimeout(function() {
            var furnitureType = $(".pagination li.active a").parent().attr("tname");
            var furnitureTypeId = $(".pagination li.active a").parent().attr("tid");
            var typeLink = $("#product_detail dl:eq(0) dd a");
            var isLink = true;
        
	        if (typeLink.length<=0) {
	            typeLink = $("#product_detail dl:eq(0) dd");
	            isLink = false;
	        }
			
            if (furnitureType && furnitureTypeId) {
				// reset link href
				if (isLink) {
					var link = typeLink.attr("href").replace(/([&?])ft=[0-9]+/, '$1ft=' + furnitureTypeId);
					typeLink.attr("href", link);
				}	
				
				// reset text
                typeLink.html(furnitureType);   
            }
        }, 50);
    });
    
    /*********************************************************
     * UPDATE product dimensions and name via active thumbnail
     *********************************************************/
    
    $(".pagination li a").click(function() {
        var dimensions = $(this).parent().attr("dim");
        var name = $(this).parent().attr("name");
        if (dimensions) {
            $("#main_content p.properties").html(name + " - " + dimensions);
        }
    });
    
    $("#loopedSlider .next, #loopedSlider .previous").click(function() {
        setTimeout(function() {
            var dimensions = $(".pagination li.active").attr("dim");
            var name = $(".pagination li.active").attr("name");
            if (dimensions) {
                $("#main_content p.properties").html(name + " - " + dimensions);
            }
        }, 50);
    });

    //init
    var dimensions = $(".pagination li.active").attr("dim"); 
    var name = $(".pagination li.active").attr("name");
    if (dimensions) {
        $("#main_content p.properties").html(name + " - " + dimensions);
    }
    
    /*
     * fancybox image overlay 
     */
    
    /* This is basic - uses default settings */
    function formatTitle(title, currentArray, currentIndex, currentOpts) {
        return '<div id="title"><span><a href="javascript:;" onclick="$.fancybox.close();"><img src="/data/closelabel.gif" /></a></span>' + (title && title.length ? '<b>' + title + '</b>' : '' ) + 'Image ' + (currentIndex + 1) + ' of ' + currentArray.length + '</div>';
    }
    
    $("a#single_image").fancybox({
        'titlePosition': 'inside',
        'titleFormat': formatTitle
    });

    /* Using custom settings */
    $("a.inline").fancybox({
        'hideOnContentClick': false,
        'autoDimensions': false,
        'width': 963,
        'height': 550,
        'autoScale': false,
		'margin': 0,
		'padding': 0
    });
    
    $(".slides a.inline").live("click", function() {
    });

    /* Apply fancybox to multiple items */
    $("a.group").fancybox({
        'transitionIn'  :   'elastic',
        'transitionOut' :   'elastic',
        'speedIn'       :   600, 
        'speedOut'      :   200, 
        'overlayShow'   :   false
    });
    
    
    
    
    /*************
     * OVERLAYS
     *************/
     $(".EH-overlay").live("click", function() {
        
        // no overlays for IE less than 7
        if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
            $(this).attr("target","_blank");
            return;
        }
        
		var o = $("<div>").addClass("page_overlay");
        $("<div>").attr("id", "overlay_close").appendTo(o);
        $("<div>").attr("id", "overlay_content").appendTo(o);
		
        var minHeight = 450;
        var height = $(window).height() - 60;
		
        
        // prepare overlay
        if ($(".page_overlay").length == 0) {
			if (!$(this).hasClass("image_overlay")) {
		        if (minHeight > height) {
		            o.css({"height": (minHeight)});
		        } else {
		            o.css({"height": (height)});
		        }
				
				// bugfix IE re-position close image
				if ($.browser.msie) {
					o.find('#overlay_close').css({top: 6,right: 20});
				}
			}
			
			o.appendTo("body");
            $("<div>").addClass("overlay-bg").appendTo("body");
        }
        
        var obj = this;
        
        if (!$(this).data("cache")) {
            
            // collection image overlay
            if ($(this).hasClass("image_overlay")) {
                var img = $("<img>").addClass("collection-image").attr("src", $(this).attr("href")).css("margin","0 32px");
                $(obj).data("cache", img);
                
            // site overlay
            } else {
                // load content
                $.ajax({
                    async: false,
                    url: this.href,
                    success: function(response) {
                        var content = response.split("<!-- [OV] -->")[1];
                        $(obj).data("cache", content);
                    }
                });
            }
        }
        
        $("#overlay_content").html($(this).data("cache"));
        
        
        $(".overlay-bg").css({
            "height": $(document).height(),
            "width": $(document).width()
        });
        
        $(".overlay-bg").fadeTo(150, 0.5, function() {
            $(this).show();
        }); 
        $(".page_overlay").fadeIn(200);
        $("html").css("overflow", "hidden"); 
        
        
        return false;
    });
    
    $("#fancybox-overlay, #overlay_close, .overlay-bg").live("click", function(){
        $(".overlay, .page_overlay").fadeOut();
        $(".overlay-bg").fadeTo(150, 0, function() {
            $(this).hide();
        })
        $("#fancybox-overlay").delay(100).fadeOut();
        $("html").css("overflow", "auto"); 
    });
    
    
    
    
    /*****************************
     * MY SELECTION overlay menu
     *****************************/
    
    //var browserWidth  = $(window).width();
    
    
        /* add to selection, create cookie */
    $(".selection").click(function() {
        write_cookie();
    });
    
    
    var alreadyClicked = false; // avoid double clicks
    
    $("#my_selection_open, .selection").live('click', function(){
        
        if (alreadyClicked == true) {
            return false;
        }
        
        alreadyClicked = true;
        
        $("#my_selection").css("z-index", 2000);
        $("#selection_container").css("z-index", 2000);
               
        var cookie = getCookie("selection");
        var content = $("#my_selection_content");
        var close = $("#my_selection_close");
        
        // texts
        var contentHeading = "Ihre Lieblingsst&uuml;cke auf einen Blick";
        var contentPrint = "Drucken";
        var contentGuide = "Hier k&ouml;nnen Sie M&ouml;bel zu Ihrer Selektion hinzuf&uuml;gen";
        var contentGuideImage = "fileadmin/templates/img/my_selection_guide_de.png";
        var contentEmpty = "Derzeit noch kein M&ouml;bel in ihrer Selektion.";
        
        // current language
        var language = $.getUrlVar('L');
        if (language == null) {
            language = 0;
        }
        
        // english texts
        if (language == 1) {
            contentHeading = "Your Wittmann favourites at a glance";
            contentPrint = "Print";
            contentGuide = "Here you can add items to your favourites.";
            contentGuideImage = "fileadmin/templates/img/my_selection_guide_en.png"
            contentEmpty = "You have not added any items to your favourites.";
        }
        
        
        if (cookie != "") {
            //init content
            content.css("opacity", 0);            
            close.css("opacity", 0);            
            
            //IE bugfix
            //current timestamp tricks IE into thinking that page has never been accessed before
            var timestamp = new Date().getTime();
            
            // load content
            $.ajax({
                url: "index.php?eID=sel&l=" + language + "&c=" + cookie + "&timestamp=" + timestamp,
                type: "POST",
                success: function(response){                    
                    content.append("<h2>" + contentHeading +"</h2>");
                    content.append(response);
                    content.append("<span><a target=\"_blank\" href=\"?print=true&eID=sel&l=" + language + "&c=" + cookie + "\">" + contentPrint + "</a></span>");
                    
                    //show content
                    $("#my_selection").animate({ width: 1005 }, 1000, function(){
                        content.slideDown(1000, function(){
                            content.animate({ opacity: 1}, 1000);
                            close.show();
                            close.animate({ opacity: 1 }, 100);
                        });
                    });
                    
                }
            });
            
        }
        else {
            $("#my_selection").animate({ width: 250 }, 1000, function(){
                content.slideDown(0, function(){
                    content.html("<div class='no_selection' style='margin-top: 20px; line-height:1.5; margin-right: 60px; text-decoration: underline; cursor: pointer;'>" + contentEmpty + "</div>");
                    
                    content.animate({ opacity: 1}, 1000);
                    close.show();
                    close.animate({ opacity: 1 }, 100);
                    
                    
                    $(".no_selection").click(function(){
                        content.empty();
                        $("#my_selection").animate({
                            width: 1005
                        }, 1000, function(){
                            content.slideDown(2000, function(){
                                content.html("<img src='" + contentGuideImage + "' style='margin-left: 120px; '/><div style='top: 150px; width: 200px; left: 550px; z-index:200; position: absolute; font-size: 14px; background: #ffffff'>" + contentGuide + "</div>");
                                $("#my_selection_content h2:visible, #my_selection_content div:visible, #my_selection_content span:visible, #my_selection_content img").css("opacity", 0).show().animate({
                                    opacity: 1
                                }, 1000);
                                $("#my_selection_content span, #my_selection_content img").delay(400).fadeIn();
                            });
                        });
                    });
                });
            });
        }
        
        $("#fancybox-overlay").css({
            background: "#000",
            opacity: 0.5
        }, 2000);
        $("#fancybox-overlay").fadeIn();
    });
    
    
    $("#fancybox-overlay, #my_selection_close").click(function(){
        $("#my_selection_close, #my_selection_content span").fadeOut();
        $("#my_selection_content h2:visible, #my_selection_content div:visible").animate({opacity:0}, 100).hide();
        $("#my_selection, #my_selection_content").slideUp( 1000, function() {
            $("#my_selection").animate({ 
                width: 25
            }, 500 );
        });
        $("#fancybox-overlay").delay(1200).fadeOut('slow', function() {
            $("#my_selection").css("z-index", 1000);
            $("selection_container").css("z-index", 1000);
        });
        $("#my_selection_content").empty();
        
        alreadyClicked = false;
    });
    
    
    
    /*
     * hover furniture handlers
     */
       
    $(".favorite").live('mouseover',
    function () {
        $(this).css("cursor", "pointer");
        $(this).children(".close").show();
    });
    
    $(".favorite").live('mouseout',
    function() {
        $(this).children(".close").hide();
    });
    
    $("#my_selection_content div.close").live('click',function() {
        delete_cookie(this);
        alreadyClicked = false;
    });
    

 
 
 
 
    /* wittmann handerk design prev, next slider */
    $("#btn_next, #btn_prev, #btn_next_craft, #btn_prev_craft").hover(function() {
        if ($(this).css("opacity") == 1.0) {
            $(this).addClass("hover"); 
        } else {
            $(this).css("cursor", "default");
        }
    }, function() {
        $(this).removeClass("hover");    
    }); 
    
    
    
    /* selection delete favorite */
    $(".favorite").mouseover(function() {
        $(this).children(".close").css("visibility", "visible"); 
    });
    
    $(".favorite").mouseout(function() {
        $(this).children(".close").css("visibility", "hidden"); 
    });
    
    
    
     /*******************
     * SEARCH
     *******************/
    $("#search_form a").live("click", function() {
        $(this).hide();
        
        var form = $("#search_form form");
        var query = form.find("input[name=query]");
        var lang = form.find("input[name=L]");
        
        var language = $.getUrlVar('L');
        if (language == null) {
            language = 0;
        }
        if (language==1) {
          query.attr("origValue","Search term");
        }
        form.fadeIn(450);
        query.val(query.attr("origValue")).select();
        lang.val(language);
        query.focus();
        return false;
    });
    
    $("#search_form form input[name=query]").live("blur", function() {
        if ($(this).val() == $(this).attr("origValue")) {
            $("#search_form form").fadeOut(150, function(){
                $("#search_form a").show();
            });
        }
    });
    
    
    
});

//$(window).resize(function() {WUtils.resizeBackground();} );
var WUtils = {
	
	MIN_WINDOW_HEIGHT:580,
	MIN_WINDOW_WIDTH:1000,
	RESIZE:true,
	
	//Variables for Background-Scaling on window.resize()
	origWidth:0, 
	origHeight:0, 
	newWindowWidth:0, 
	newWindowHeight:0,
	newBgWidth:0, 
	newBgHeight:0,  
	maxScaleFactor:1.3, //if small-bg-img is more scaled, than maxScaleFactor, the big-bg-img will be used
	scaleFactor:0, //scale-factor for bg-image
	normalizedHeight: 800, //if browser-content has this height, the detail-objects will be scaled with factor 1  
	BG_SMALL_ORIG_WIDTH:1024,
	BG_SMALL_ORIG_HEIGHT:660,
	BG_BIG_ORIG_WIDTH:1600,
	BG_BIG_ORIG_HEIGHT:1031,
	usingSmallBg:true,
	currBgOrigWidth:1024, 
	currBgOrigHeight:660,
	SRC_SMALL:"_small.jpg",
	SRC_BIG:"_big.jpg",
	currBgSrc:"",

    // Background - Fading - Vars
    showBGLength: 9000,
    fadeBGLength: 1000,
	
	init: function() {		
		$(window).resize(function() { 
			WUtils.resizeBackground();
		});

        var usingChangedSrc = true;

        if($('#bg-image-container.on').length !== 0){
            usingChangedSrc = false;
        }

		WUtils.newWindowWidth = $(window).width();
		WUtils.newWindowHeight = $(window).height();
		
		if (usingChangedSrc && $('#bg-image img').attr('src')!=undefined){
			WUtils.currBgSrc = ($('#bg-image img').attr('src')).replace('.jpg','')+WUtils.SRC_SMALL;
        }else if($('#bg-image img').attr('src')!=undefined){
            WUtils.currBgSrc = ($('#bg-image img').attr('src'));
		}else{
			WUtils.currBgSrc = '';
        }
		//console.log(WUtils.currBgSrc);

		//big bg-image is needed	
		if ( (WUtils.newWindowWidth >= (WUtils.BG_SMALL_ORIG_WIDTH * WUtils.maxScaleFactor)) || (WUtils.newWindowHeight >= (WUtils.BG_SMALL_ORIG_HEIGHT * WUtils.maxScaleFactor)) )
		{
			WUtils.usingSmallBg = false;
			WUtils.currBgOrigWidth = WUtils.BG_BIG_ORIG_WIDTH; 
			WUtils.currBgOrigHeight = WUtils.BG_BIG_ORIG_HEIGHT;
            if(usingChangedSrc){
                $('#bg-image img').attr('src',WUtils.currBgSrc.replace(WUtils.SRC_SMALL,WUtils.SRC_BIG));
            }
			//$('#bg-image img').attr('width',1600);
			//$('#bg-image img').attr('height',1031);
		}
		else if(usingChangedSrc){ //small bg-image is needed
		  	$('#bg-image img').attr('src',WUtils.currBgSrc.replace(WUtils.SRC_BIG,WUtils.SRC_SMALL));
			//$('#bg-image img').attr('width',1024);
			//$('#bg-image img').attr('height',660);
		}
				
		WUtils.resizeBackground();
        if($('#background').parents('a').length !== 0){
            $('#container').bind('click', function(e){
               if($(e.target).attr('id') == "container"){
                    var goToL = $('#background').parent().attr('href');
                    if(goToL && goToL !== undefined){
                        window.location.assign(goToL);
                    }
               }
            });
        }

        if($('#bg-image-container').length !== 0){
        	if($('#bg-image-container').attr("class")=="on") {
        		$('.DE-header.header_slider').hide();
	            var actualBgElement = $('#bg-image-container').find('li').eq(0);
    	        setTimeout(function(){
        	        WUtils.fadeBg(actualBgElement);
            	}, WUtils.showBGLength);
            }
            else {
            	$('#bg-image').remove();
            }
        }
	},

    fadeBg : function(actBgElement){
        var nextBgElement = null;

        if(actBgElement.next().length === 0){
            nextBgElement = actBgElement.parent().find('li').eq(0);
        }else{
            nextBgElement = actBgElement.next();
        }

        $('#background').fadeOut(WUtils.fadeBGLength, function(){
            var newLink = nextBgElement.find('a').attr('href'),
                newSrc = nextBgElement.find('img').attr('src'),
                newTitle = nextBgElement.find('a').attr('title');
 
            $('#background').parent().attr({href: newLink, title: newTitle });


            $('#background').bind('load', function(){
               $('#background').fadeIn(WUtils.fadeBGLength, function(){
                $('#background').unbind('load');
                  setTimeout(function(){
                      WUtils.fadeBg(nextBgElement);
                  }, WUtils.showBGLength); 
               });
            });
             $('#background').attr('src', newSrc);
        });
    },
				
	resizeBackground: function() {
                
        WUtils.newWindowWidth = ($(window).width());
		WUtils.newWindowHeight = ($(window).height());
		
		
		if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
			$('body').css({
				'overflow-y': 'hidden'
			});
		}
		
		       		    
        if($(window).height() < WUtils.MIN_WINDOW_HEIGHT) {
           	//$("body").css("overflow-y","visible");
           	WUtils.newWindowHeight = WUtils.MIN_WINDOW_HEIGHT;
			//$("body").height(WUtils.MIN_WINDOW_HEIGHT);
			RESIZE = false;
       	} else {
          	//$("body").css("overflow-y","hidden");
           	WUtils.newWindowHeight = $(window).height();
			//$("body").height($(window).height());
			RESIZE = true;
        }
        
        if($(window).width() < WUtils.MIN_WINDOW_WIDTH)	{
           	
           	WUtils.newWindowWidth = $(window).width();
			$("body").width(WUtils.MIN_WINDOW_WIDTH);
			$("body").css("overflow-x","visible");
			RESIZE = false;
       	}
       	else {
           	//$("body").css("overflow-x","hidden");
           	WUtils.newWindowWidth = $(window).width();
			//$("body").width($(window).width());
			RESIZE = true;
        }
        	
        //big bg-pic is needed
		if ((WUtils.newWindowWidth >= (WUtils.BG_SMALL_ORIG_WIDTH * WUtils.maxScaleFactor)) || (WUtils.newWindowHeight >= (WUtils.BG_SMALL_ORIG_HEIGHT * WUtils.maxScaleFactor)))
		{
			if (WUtils.usingSmallBg) {
				WUtils.usingSmallBg = false;
				$('#bg-image img').attr('src', WUtils.currBgSrc.replace(WUtils.SRC_SMALL,WUtils.SRC_BIG)); //switch to big bg-pic
				WUtils.currBgOrigWidth = WUtils.BG_BIG_ORIG_WIDTH;
				WUtils.currBgOrigHeight = WUtils.BG_BIG_ORIG_HEIGHT;
			}			  
		} else //small bg-pic is needed
		{
			if (!WUtils.usingSmallBg) 
			{
				WUtils.usingSmallBg = true;
				$('#bg-image img').attr('src', WUtils.currBgSrc.replace(WUtils.SRC_BIG,WUtils.SRC_SMALL)); //switch to small bg-pic
				WUtils.currBgOrigWidth = WUtils.BG_SMALL_ORIG_WIDTH;
				WUtils.currBgOrigHeight = WUtils.BG_SMALL_ORIG_HEIGHT;
			}
		}
		            
		if (WUtils.newWindowHeight / WUtils.currBgOrigHeight > WUtils.newWindowWidth / WUtils.currBgOrigWidth) 
      		WUtils.scaleFactor = WUtils.newWindowHeight / WUtils.currBgOrigHeight;
		else
	  		WUtils.scaleFactor = WUtils.newWindowWidth / WUtils.currBgOrigWidth;
						
		
		WUtils.newBgWidth = Math.round(WUtils.currBgOrigWidth * WUtils.scaleFactor);
		WUtils.newBgHeight = Math.round(WUtils.currBgOrigHeight * WUtils.scaleFactor);
		
		if(!RESIZE)
            return false;

        //console.log($('#bg-image img').attr('src'));
        //console.log('W: '+WUtils.newBgWidth+' H:'+WUtils.newBgHeight);
	    
		$('#bg-image img').attr({
			'width': WUtils.newBgWidth,
			'height': WUtils.newBgHeight
		});
		
        $('body').attr({
            'width': WUtils.newBgWidth,
            'height': WUtils.newBgHeight
        });         
    }

};


/************
 * cookies
 ************/ 
function deleteWholeCookie (name) {
    if (getCookie(name)) {
        document.cookie = name + "=" + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
        
        /* close selection view */
        $("#my_selection_close, #my_selection_content span").fadeOut();
        $("#my_selection_content h2:visible, #my_selection_content div:visible").animate({opacity:0}, 100).hide();
        $("#my_selection, #my_selection_content").slideUp( 1000, function() {
            $("#my_selection").animate({ 
                width: 25
            }, 500 );
        });
        $("#fancybox-overlay").delay(1200).fadeOut('slow', function() {
            $("#my_selection").css("z-index", 1000);
        });
        $("#my_selection_content").empty();
    }
}

function delete_cookie(object){
    var fid = $(object).parent().attr("fid");
    var cookie = getCookie("selection");
    
    if (cookie != "") {
        var deleteFromString = false;
        var deleteCookie = false;
        
        if (cookie.indexOf(fid + "-") >= 0) {
            deleteFromString = cookie.substring(cookie.indexOf(fid + "-"), cookie.length);
            deleteCookie = deleteFromString.substring(0, deleteFromString.indexOf("x") + 1);
        }
        
        var newCookie = (cookie.replace(deleteCookie, ""));
        var date = new Date();
        date = new Date(date.getTime() + 1000 * 60 * 60 * 24 * 365); // 1 Jahr
        if (newCookie != "") {
            document.cookie = 'selection=' + newCookie + '; expires=' + date.toGMTString() + ';';
        }
        else {
            deleteWholeCookie("selection");
        }
        $(object).parent().remove();
        
        
    }
}


function getCookie(c_name) {
    if (document.cookie.length > 0) {
      c_start=document.cookie.indexOf(c_name + "=");
      if (c_start!=-1) {
        c_start=c_start + c_name.length+1;
        c_end=document.cookie.indexOf(";",c_start);
        if (c_end==-1) c_end=document.cookie.length;
        return unescape(document.cookie.substring(c_start,c_end));
        }
    } 
    return "";
}

function write_cookie() {
    var cookie = getCookie("selection"); 
    var fid = $("li.active").attr("fid");
    var url = window.location.href;
    var start = url.indexOf("&id=");
    var end = url.indexOf("&f=");
    
    if (start != -1) {
        var id = url.substring(start+4,end);
    } else {
        var id = 0; 
    }
    
    var selection = fid+"-"+id+"x";
    var date = new Date();
    date = new Date(date.getTime() +1000*60*60*24*365); // 1 year
    
    if (cookie != "") {
        if (cookie.indexOf(selection) == -1) {
            selection = cookie + selection;
        } else {
            selection = cookie;
        }
    }
    
    document.cookie = 'selection='+selection+'; expires='+date.toGMTString()+';';
}


/****************
 * URL Params
 ****************/
$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});



