/* teaser rotation */
var countTeaser;
var currentTeaser = 0;

/* svg planner options */
var svg;
var optRotate;
var optDel;
var objRot;
var stageField;
var isRotating = false;
var startAngle;
var animating = false;

/**
 * delete the dashed border by clicken on a link (type3 fuction)
 */
function blurLink(i){
    i.blur();
}


/**
 * show Text in the BlogNavi on mouse-over
 */
(function($){
    $.fn.showBlogNaviText = function(){
        $(".sitenavi a").hover(function(){
            $('.navitext').html($(this).html());
        }, function(){
            $('.navitext').html('');
        });
    }
}(jQuery));

/**
 * scale images on the start page
 */
(function($){
    $.fn.scaleIndexImages = function(){
        $("#indexpage div h2").hover(function(e){
            if (e.relatedTarget != null) {
                this.image = $(this).children('a').children('img:first');
                if (!this.image.hasClass("hover")) {
                    this.newMargin = -(this.image.width() / 100 * 2);
                    this.oldHeight = this.image.height();
                    this.newHeight = this.oldHeight / 100 * 104;
                    this.oldWidth = this.image.width();
                    this.newWidth = this.oldWidth / 100 * 104;
                    this.oldZindex = $(this).parent().css('z-index');
                    this.image.addClass("hover");
                }
                this.image.stop().animate({
                    marginLeft: this.newMargin,
                    width: this.newWidth,
                    height: this.newHeight
                }, 150);
                $(this).parent().css({
                    'z-index': '8010'
                });
            }
        }, function(e){
            if (e.relatedTarget != null) {
                $(this).parent().css({
                    'z-index': this.oldZindex
                });
                if (this.image != undefined) 
                    this.image.animate({
                        marginLeft: '0',
                        width: this.oldWidth,
                        height: this.oldHeight
                    }, 150);
            }
        });
    };
}(jQuery));

/**
 * show shopSubMenu in shop navi
 */
(function($){
    var naviTimer = null;
    var childInputIsBlur = true;
    $.fn.showSubMenu = function(){
    
        $('.quicknavi li a.topiclink').click(function(){
            var checkElement = $(this).next();
            
            // hide submenu
            if ((checkElement.is('.submenu')) && (checkElement.is(':visible'))) {
                clearTimeout(naviTimer);
                checkElement.parent().removeClass("hi");
                checkElement.fadeOut('fast');
                return false;
            }
            // show submenu
            if ((checkElement.is('.submenu')) && (!checkElement.is(':visible'))) {
                $(this).parent().find('.submenu').hover(function(){
                    clearTimeout(naviTimer);
                }, function(){
                    clearTimeout(naviTimer);
                });
                
                clearTimeout(naviTimer);
                $('.quicknavi .submenu:visible').fadeOut('slow');
                $('.quicknavi .submenu:visible').parent().removeClass("hi");
                
                checkElement.fadeIn('slow');
                checkElement.parent().addClass("hi");
                $(this).parent().find('.submenu').hover(function(){
                    clearTimeout(naviTimer);
                }, function(){
                    naviTimer = setTimeout(function(){
                        checkElement.parent().removeClass("hi");
                        checkElement.fadeOut('fast');
                        return false;
                    }, 2000);
                });
                
                return false;
            } //is.submenu
        });
    }
}(jQuery));


/**
 * show shopSubMenu in shop navi
 */
(function($){
    var naviTimer = null;
    var childInputIsBlur = true;
    $.fn.showShopSubMenu = function(){
        $('.shopnavi').find('.submenu').hover(function(){
            clearTimeout(naviTimer);
        }, function(){
            naviTimer = setTimeout(function(){
                $('.submenu').parent().removeClass("hi");
                $('.submenu').fadeOut('fast');
                return false;
            }, 2000);
        });
        $('.shopnavi li.node a').bind('click', function(){
            var checkElement = $(this).next();
            
            // hide submenu
            if ((checkElement.is('.submenu')) && (checkElement.is(':visible'))) {
                clearTimeout(naviTimer);
                checkElement.parent().removeClass("hi");
                checkElement.fadeOut('fast');
                return false;
            }
            // show submenu
            if (($(this).parent().is('.node')) && (!checkElement.is(':visible'))) {
            
                $(this).parent().find('.submenu').hover(function(){
                    clearTimeout(naviTimer);
                }, function(){
                    clearTimeout(naviTimer);
                });
                
                clearTimeout(naviTimer);
                $('.shopnavi .submenu:visible').fadeOut('slow');
                $('.shopnavi .submenu:visible').parent().removeClass("hi");
                
                // get menu from generated page
                var currentPath = window.location.href.split('/', 3);
                var host = currentPath[2];
                var href = $(this).attr('href');
                var link = (href.indexOf("http") == -1) ? 'http://' + host + '/' + href : href;
                $.ajax({
                    url: link,
                    type: 'GET',
                    async: false,
                    error: function(){
                    },
                    success: function(data){
                        $('.shopnaviwrapper').html($(data).find(".shopnaviwrapper").html());
                        $('.shopnavi').showShopSubMenu();
                        if ($('#teamContainer').length > 0) {
                            $('.shopnavi').subMenuLinkTeam();
                        }
                        else {
                            $('.shopnavi').subMenuLink();
                        }
                    }
                });
                return false;
            } //is.submenu
        });
    }
}(jQuery));


/**
 * links in submenu of shop navi
 */
(function($){
    $.fn.subMenuLink = function(){
        $('.shopnavi .bgVignetteMiddle ul li a').bind('click', function(event){
            event.preventDefault();
            var label = $(this).text();
            // fade out any submenues while requesting new menu
            $('.shopnavi .submenu:visible').fadeOut('slow');
            $('.shopnavi .submenu:visible').parent().removeClass("hi");
            // get menu from generated page and content where available
            var currentPath = window.location.href.split('/');
            var host = currentPath[2];
            var href = $(this).attr('href');
            var link = (href.indexOf("http") == -1) ? 'http://' + host + '/' + href : href;
            $.ajax({
                url: link,
                type: 'GET',
                dataType: 'html',
                async: false,
                error: function(){
                },
                success: function(data){
                    $('.shopnaviwrapper').html($(data).find(".shopnaviwrapper").html());
                    document.title = $(data).find('span.pagetitle').text();
                    var result = $(data).find("#endnode").html();
                    if (result) {
                        $(".vignetteBoxes").children().fadeOut("fast", function(){
                            $(".vignetteBoxes").children().remove();
                            $(".vignetteBoxes").append(result).children().hide().fadeIn("fast");
                            $('.gmlink').css('display', 'block').attr('href', '#metaMap');
                            /*$('.street-address').each(function(e){
                             if ($(this).children().length > 1) {
                             $(this).parent().parent().find('.gmlink').hide();
                             }
                             });*/
                            $('.gmlink').nyroModal({
                                bgColor: '#fff',
                                padding: 15,
                                windowResize: false,
                                showTransition: false
                            });
                        });
                        var slideshowData = $(data).find(".slideSources").children();
                        var slideSources = [];
                        slideshowData.each(function(i){
                            slideSources[i] = $(this).attr('src');
                        });
                        if (slideSources.length > 1) {
                            $(".srImg").slideshow({
                                slideImages: slideSources
                            });
                        }
                        pageTracker._trackPageview(link);
                    }
                    $('.shopnavi').showShopSubMenu();
                    $('.shopnavi').subMenuLink();
                    
                }
            });
            
            return false;
        });
    }
}(jQuery));


/**
 * links in submenu of team navi
 */
(function($){
    $.fn.subMenuLinkTeam = function(){
        $('.shopnavi .bgVignetteMiddle ul li a').bind('click', function(event){
            event.preventDefault();
            var label = $(this).text();
            // fade out any submenues while requesting new menu
            $('.shopnavi .submenu:visible').fadeOut('slow');
            $('.shopnavi .submenu:visible').parent().removeClass("hi");
            // get menu from generated page and content where available
            var currentPath = window.location.href.split('/');
            var host = currentPath[2];
            var href = $(this).attr('href');
            var link = (href.indexOf("http") == -1) ? 'http://' + host + '/' + href : href;
            $.ajax({
                url: link,
                type: 'GET',
                dataType: 'html',
                async: false,
                error: function(){
                },
                success: function(data){
                    $('.shopnaviwrapper').html($(data).find(".shopnaviwrapper").html());
                    document.title = $(data).find('span.pagetitle').text();
                    var result = $(data).find(".endnode").html();
                    if (result) {
                        $("#teamContainer").children().fadeOut("fast", function(){
                            $("#teamContainer").children().remove();
                            $("#teamContainer").append(result).children().hide().fadeIn("fast");
                            $(".teamTiles div").setTeamTiles().scaleTileImages();
                        });
                        pageTracker._trackPageview(link);
                    }
                    $('.shopnavi').showShopSubMenu();
                    $('.shopnavi').subMenuLinkTeam();
                    
                }
            });
            
            return false;
        });
    }
}(jQuery));




/**
 * updates tiles after using the category filter
 */
(function($){
    $.fn.updateCollectionTiles = function(){
        return this.each(function(i){
            $(this).bind('click', function(e){
                $(".topiclink").addClass("actual");
                var link = $(this).attr("href");
                var label = $(this).text();
                $.ajax({
                    url: link,
                    type: 'GET',
                    dataType: 'html',
                    timeout: 3000,
                    error: function(){
                    },
                    success: function(data){
                        var newData = ($('<div>' + data + '</div>').find('.collectionTiles'));
                        $(".collectionTiles").children().fadeOut("fast", function(){
                            $(".collectionTiles").children().remove();
                            $(newData.html()).appendTo(".collectionTiles");
                            $(".collectionTiles div").setPriority();
                            $(".collectionTiles div").scaleTileImages();
                            $(".quicknavi .close").show();
                            $("#topiclink").text("\"" + label + "\"");
                        });
                    }
                });
                return false;
            });
        });
    }
}(jQuery));

/**
 * updates stage and stagecontrols when clicking products
 */
(function($){
    $.fn.updateStage = function(){
        return this.each(function(i){
            $(this).bind('click', function(e){
                if (!$(this).hasClass("active")) {
                    var $this = $(this);
                    var link = $(this).attr("href");
                    $(".stage").children().hide();
                    $(".stageArea .stage").children().remove();
                    $(".stageArea .stage").append($("<div class='loader'><div></div></div>"));
                    $.ajax({
                        url: link,
                        type: 'GET',
                        dataType: 'html',
                        async: false,
                        error: function(){
                        },
                        complete: function(xmlHttp, status){
                        },
                        success: function(data, status){
                        	var newData = ($('<div>' + data + '</div>').find('.stage').first());
                        	// play collection
                        	var customize = ($('<div>' + data + '</div>').find('.customize'));
	                        $(".customize").children().remove();
	                        $(".customize").append(customize.html()).children().hide().fadeIn("fast");
	                        $(".customize .colorWrapper a").updatePreviewAndStage();
                            if (newData.length > 0) {
                                $this.parents(".stageControls").children("div").children("a").removeClass("active");
                                $(".stageControls div a").removeClass("active");
                                $this.addClass("active");
                                setHash($this.attr("href"));
                                setPageParameters($(data).find('span.pagetitle').text(), link);
                                
                                $(".stage").children().fadeOut("fast", function(){
                                    if (newData.children().length > 0) {
                                        $(".stageArea .stage").children().remove();
                                        $(".stageArea .stage").prepend(newData.children());
                                    }
                                });
                                pageTracker._trackPageview(link);
                            }
                            if ($('.property1').length > 0) {
                                $(".customize").css("min-height", "260px");
                            }
                            if ($('.property2').length > 0) {
                                $(".customize").css("min-height", "310px");
                            }
                            if ($('.property3').length > 0) {
                                $(".customize").css("min-height", "400px");
                            }
                            if ($('.property4').length > 0) {
                                $(".customize").css("min-height", "480px");
                            }  
                            var colors = $('<div>' + data + '</div>').find('#color');
                            $("#color").children().remove();
                            $("#color").append(colors.html());
                            $("#color .colorWrapper a").updatePreviewAndStage();
                        }
                    });
                    return false;
                }
            });
        });
    }
}(jQuery));

/**
 * changes the stage image when clicking gallery pictures or pressimages
 */
(function($){
    $.fn.addImageToStage = function(){
        return this.each(function(i){
            $(this).bind('click', function(e){
                $this = $(this);
                if (!$this.hasClass("active")) {
                    $(".stageControls div a").removeClass("active");
                    $this.addClass("active");
                    if ($(".jquery-reel").length > 0) {
                        var stageImg = new Image();
                        $(stageImg).load(function(){
                            $(this).hide();
                            $(".stageArea .stage").children().remove();
                            $('<img/>', {
                                src: $this.attr("href")
                            }).appendTo('.stage').hide().fadeIn('fast');
                        }).attr("src", $this.attr("href"));
                    }
                    else {
                        $(".stage img").fadeOut("fast", function(){
                            $(".stage span").hide();
                            $(".stage img").attr("src", $this.attr("href")).fadeIn("fast");
                        });
                    }
                    if ($this.hasClass('press')) 
                        pageTracker._trackEvent('Kollektion', 'Pressefreisteller', $this.children().attr('alt'));
                    else 
                        if ($this.hasClass('reel')) 
                            pageTracker._trackEvent('Kollektion', '360Grad', $this.children().attr('alt'));
                        else 
                            pageTracker._trackEvent('Kollektion', 'Galerie', $this.children().attr('alt'));
                    return false;
                }
                else {
                    e.preventDefault();
                }
            });
        });
    }
}(jQuery));


/**
 * manage reel image for 360°
 */
(function($){
    $.fn.addReelToStage = function(){
        return this.each(function(i){
            $(this).bind('click', function(e){
                $this = $(this);
                if (!$this.hasClass("active")) {
                    $(".stageControls div a").removeClass("active");
                    $this.addClass("active");
                    $(".stageArea .stage").children().remove();
                    $(".stageArea .stage").append($("<div class='loader'><div></div></div>"));
                    var reelImg = new Image();
                    
                    $(reelImg).load(function(){
                        $(this).hide();
                        $(".stageArea .stage").children().remove();
                        $('<img/>', {
                            src: $this.attr("href"),
                            width: 715,
                            height: 472,
                            rel: $this.attr('rel')
                        }).appendTo('.stage').load(function(){
                            $(this).reel({
                                footage: 4,
                                frames: 32,
                                reversed: true
                            });
                        }).hide().fadeIn('fast');
                    }).attr('src', $this.attr('rel'));
                    return false;
                }
                else {
                    e.preventDefault();
                }
            });
        });
    }
}(jQuery));


/**
 * updates stage, stagecontrols, customize and moodboard when choosing a color
 */
(function($){
    $.fn.updatePreviewAndStage = function(){
        return this.each(function(i){
            $(this).hover(function(){
                this.oldTitle = $(this).parent().parent().parent().find(".colorLabel").text();
                this.newTitle = $(this).attr("title");
                $(this).parent().parent().parent().find(".colorLabel").text(this.newTitle);
                $(this).addClass("hover");
            }, function(){
                $(this).removeClass("hover");
                $(this).parent().parent().parent().find(".colorLabel").text(this.oldTitle);
            });
            $(this).bind('click', function(e){
                if (!$(this).hasClass("active")) {
                    $(this).parents(".colorBlock").find(".colorWrapper").find("a").removeClass("active");
                    $(this).addClass("active");
                    setHash($(this).attr("href"));
                    var title = $(this).attr("title");
                    this.oldTitle = title;
                    $(this).parent().parent().parent().find(".colorLabel").text(title);
                    var link = $(this).attr("href");
                    if ($(this).parents(".colorBlock").attr("id") != "color") {
                        var preview = $(this).attr("rel");
                        var image = $(this).parents(".colorBlock").attr("id");
                        $("." + image).fadeOut("fast", function(){
                            $(this).attr("src", preview).fadeIn("fast");
                        });
                    }
 					
 		// play collection 
                    if ($(this).parents(".colorBlock").attr("id") == "propertytype-1" || $(this).parents(".colorBlock").attr("id") == "propertytype-2" || $(this).parents(".colorBlock").attr("id") == "propertytype-3" || $(this).parents(".colorBlock").attr("id") == "propertytype-4" || $(this).parents(".colorBlock").attr("id") == "propertytype-5" || $(this).parents(".colorBlock").attr("id") == "propertytype-6" || $(this).parents(".colorBlock").attr("id") == "propertytype-7" || $(this).parents(".colorBlock").attr("id") == "propertytype-8" || $(this).parents(".colorBlock").attr("id") == "propertytype-9" || $(this).parents(".colorBlock").attr("id") == "propertytype-10" || $(this).parents(".colorBlock").attr("id") == "propertytype-11" || $(this).parents(".colorBlock").attr("id") == "propertytype-12" || $(this).parents(".colorBlock").attr("id") == "propertytype-13" || $(this).parents(".colorBlock").attr("id") == "propertytype-14" || $(this).parents(".colorBlock").attr("id") == "propertytype-15" || $(this).parents(".colorBlock").attr("id") == "propertytype-16" || $(this).parents(".colorBlock").attr("id") == "propertytype-17" || $(this).parents(".colorBlock").attr("id") == "propertytype-18" || $(this).parents(".colorBlock").attr("id") == "propertytype-19" || $(this).parents(".colorBlock").attr("id") == "propertytype-20" || $(this).parents(".colorBlock").attr("id") == "propertytype-21" || $(this).parents(".colorBlock").attr("id") == "propertytype-22" || $(this).parents(".colorBlock").attr("id") == "propertytype-23" || $(this).parents(".colorBlock").attr("id") == "propertytype-24" || $(this).parents(".colorBlock").attr("id") == "propertytype-25" || $(this).parents(".colorBlock").attr("id") == "propertytype-26" || $(this).parents(".colorBlock").attr("id") == "propertytype-27" || $(this).parents(".colorBlock").attr("id") == "propertytype-28" || $(this).parents(".colorBlock").attr("id") == "propertytype-29" || $(this).parents(".colorBlock").attr("id") == "propertytype-30" || $(this).parents(".colorBlock").attr("id") == "propertytype-31" || $(this).parents(".colorBlock").attr("id") == "propertytype-32" || $(this).parents(".colorBlock").attr("id") == "propertytype-33" || $(this).parents(".colorBlock").attr("id") == "propertytype-34" || $(this).parents(".colorBlock").attr("id") == "propertytype-35" || $(this).parents(".colorBlock").attr("id") == "propertytype-36" || $(this).parents(".colorBlock").attr("id") == "propertytype-37" || $(this).parents(".colorBlock").attr("id") == "propertytype-38" || $(this).parents(".colorBlock").attr("id") == "propertytype-39" || $(this).parents(".colorBlock").attr("id") == "propertytype-40" || $(this).parents(".colorBlock").attr("id") == "propertytype-41"  ) {                   	 
                    	$.ajax({
                            url: link,
                            type: 'GET',
                            dataType: 'html',
                            async: false,
                            error: function(){
                            },
                            success: function(data){
                                var stage = ($('<div>' + data + '</div>').find('.stage'));
                                var stageControls = ($('<div>' + data + '</div>').find('.stageControls'));
                                var plannerControls = ($('<div>' + data + '</div>').find('.plannerControls'));
                                var customize = ($('<div>' + data + '</div>').find('.customize'));
                                $(".customize").children().remove();
                                $(".customize").append(customize.html()).children().hide().fadeIn("fast");
                                $(".customize .colorWrapper a").updatePreviewAndStage();
                                setPageParameters($(data).find('span.pagetitle').text(), link);
                                
                                // gallery or rotation is selected
                                if ($(".stageControls .gallery").prev("a.accordion").hasClass("active") || $(".stageControls .rotation").prev("a.accordion").hasClass("active")) {
                                    $(".plannerControls .products").remove();
                                    $(".stageControls .accordion").first().after(stageControls.children(".products"));
                                    $(".products").first().children("a").randomizeOrder().scaleTileImages();
                                    setTimeout(function(){
                                        $(".products").first().hide(1, function(){
                                            $(".products").children("a.prod").updateStage();
                                            $(".products").children("a.press").addImageToStage();
                                            if ($(".stageControls .gallery").prev("a.accordion").hasClass("active")) {
                                                $(".gallery").children("a").first().click();
                                            }
                                            else {
                                                $(".rotation").children("a").first().click();
                                            }
                                        });
                                    }, 10);
                                }
                                // products are selected
                                else {
                                    $(".stage").children().first().fadeOut("fast", function(){
                                        $(".stageArea .stage").children().remove();
                                        $(".stageArea .stage").append(stage.html()).children().hide().fadeIn("fast");

                                    });
                                }
                            }
                        });
                    }                   
                    
                    if ($(this).parents(".colorBlock").attr("id") == "color") {
                        /*if (!$(".stageControls .gallery").prev("a.accordion").hasClass("active")) {
                         $(".stage").children().hide();
                         $(".stageArea .stage").children().remove();
                         $(".stageArea .stage").append($("<div class='loader'><div></div></div>"));
                         }*/
                        $.ajax({
                            url: link,
                            type: 'GET',
                            dataType: 'html',
                            async: false,
                            error: function(){
                            },
                            success: function(data){
                                var stage = ($('<div>' + data + '</div>').find('.stage'));
                                var stageControls = ($('<div>' + data + '</div>').find('.stageControls'));
                                var customize = ($('<div>' + data + '</div>').find('.customize'));
                                $(".customize").children().remove();
                                $(".customize").append(customize.html()).children().hide().fadeIn("fast");
                                $(".customize .colorWrapper a").updatePreviewAndStage();
                                setPageParameters($(data).find('span.pagetitle').text(), link);
                                
                                // gallery or rotation is selected
                                if ($(".stageControls .gallery").prev("a.accordion").hasClass("active") || $(".stageControls .rotation").prev("a.accordion").hasClass("active")) {
                                    $(".stageControls .products").remove();
                                    $(".stageControls .accordion").first().after(stageControls.children(".products"));
                                    $(".products").first().children("a").randomizeOrder().scaleTileImages();
                                    setTimeout(function(){
                                        $(".products").first().hide(1, function(){
                                            $(".products").children("a.prod").updateStage();
                                            $(".products").children("a.press").addImageToStage();
                                            if ($(".stageControls .gallery").prev("a.accordion").hasClass("active")) {
                                                $(".gallery").children("a").first().click();
                                            }
                                            else {
                                                $(".rotation").children("a").first().click();
                                            }
                                        });
                                    }, 10);
                                }
                                // products are selected
                                else {
                                    $(".stage").children().first().fadeOut("fast", function(){
                                        $(".stageArea .stage").children().remove();
                                        $(".stageArea .stage").append(stage.html()).children().hide().fadeIn("fast");
                                        
                                        $(".stageControls").children().fadeOut("fast", function(){
                                            $(".stageControls").children().remove();
                                            $(".stageControls").append(stageControls.html()).children().hide().fadeIn("fast");
                                            $(".products").first().children("a").randomizeOrder().scaleTileImages();
                                            setTimeout(function(){
                                                $(".products").first().children("a.prod").updateStage().bind("click", function(e){
                                                    e.preventDefault();
                                                });
                                                $(".products").first().children("a.press").addImageToStage().bind("click", function(e){
                                                    e.preventDefault();
                                                });
                                                var ac = false;
                                                $(".products").first().children("a").each(function(){
                                                    if ($(this).hasClass("active")) 
                                                        ac = true;
                                                });
                                                if (!ac) 
                                                    $(".products").first().children("a").first().addClass("active");
                                            }, 100);
                                            $(".gallery").first().children("a").randomizeOrder().scaleTileImages().addImageToStage();
                                            $(".rotation").first().children("a").randomizeOrder().scaleTileImages().addReelToStage();
                                            if ($(".products").first().children("a").length == 0) 
                                                $(".products").prev().css("background", "0 none");
                                            if ($(".gallery").first().children("a").length == 0) 
                                                $(".gallery").prev().css("background", "0 none");
                                            if ($(".rotation").first().children("a").length == 0) 
                                                $(".rotation").prev().css("background", "0 none");
                                            $(".accordion").slideBoxes();
                                        });
                                    });
                                }
                            }
                        });
                    }
                    pageTracker._trackEvent($('.stage span.producttext').text(), $(this).parents(".colorBlock").attr("id"), title);
                }
                return false;
            });
        });
    }
}(jQuery));


/**
 * show color titles and update stage
 */
(function($){
    $.fn.updateTitlesAndStage = function(){
        return this.each(function(i){
            $(this).hover(function(){
                this.oldTitle = $(this).parent().parent().parent().find(".colorLabel").text();
                this.newTitle = $(this).attr("title");
                $(this).parent().parent().parent().find(".colorLabel").text(this.newTitle);
                $(this).addClass("hover");
            }, function(){
                $(this).removeClass("hover");
                $(this).parent().parent().parent().find(".colorLabel").text(this.oldTitle);
            });
            $(this).bind('click', function(e){
                if (!$(this).hasClass("active")) {
                    $this = $(this);
                    $(this).parents(".colorBlock").find(".colorWrapper").find("a").removeClass("active");
                    $(this).addClass("active");
                    var title = $(this).attr("title");
                    this.oldTitle = title;
                    $(this).parent().parent().parent().find(".colorLabel").text(title);
                    $(".stage img").fadeOut("fast", function(){
                        $(".stage img").attr("src", $this.attr("rel"));
                        $(".stage img").fadeIn("fast");
                    });
                }
                return false;
            });
        });
    }
}(jQuery));


/**
 * fade-in the page after loading
 */
(function($){
    $.fn.pageFadeIn = function(){
        $('#content').css({
            opacity: 0
        })
        $('#content').animate({
            opacity: 1
        }, 800);
    }
}(jQuery));

/**
 * Showrooms slideshow
 */
(function($){
    $.fn.slideshow = function(options){
        var opts = $.extend({
            slideKey: 1,
            slideDelay: 0
        }, options);
        
        window.clearTimeout(opts.slideDelay);
        
        function runSlideshow(slideKey){
            var slideImg = new Image();
            /*if (opts.slideDelay == 0) {
             clearTimeout(opts.slideDelay);
             }*/
            opts.slideDelay = setTimeout(function(){
                opts.slideDelay = 0;
                $(slideImg).load(function(){
                    $(this).hide();
                    $('.srImg img').fadeTo('slow', 0, function(){
                        $('.srImg img').remove();
                        $('.srImg').append($(slideImg));
                        $(slideImg).fadeTo('slow', 1);
                    });
                }).attr('src', opts.slideImages[slideKey]);
                slideKey++;
                if (slideKey == opts.slideImages.length) {
                    slideKey = 0;
                }
                runSlideshow(slideKey);
            }, 4000);
        }
        runSlideshow(opts.slideKey);
    }
}(jQuery));


/**
 * teaser rotation for webspecial teaser on startpage
 */
(function($){
    $.fn.initTeaserRotation = function(){
        countTeaser = $(".t8").hide().size();
        $(".t8:eq(" + currentTeaser + ")").show();
        if (countTeaser > 1) 
            setInterval(rotateTeaser, 4000);
    }
})(jQuery);

/**
 * teaser rotation core function
 */
function rotateTeaser(){
    oldTeaser = currentTeaser % countTeaser;
    newTeaser = ++currentTeaser % countTeaser;
    $(".t8:eq(" + newTeaser + ")").fadeIn("slow", function(){
        $(".t8:eq(" + oldTeaser + ")").fadeOut("slow");
    });
}

/**
 * set the priority and direction of the tiles on the collection page
 */
(function($){
    $.fn.setPriority = function(){
        var z = 8000;
        var count = this.length;
        return this.each(function(i){
            var $this = $(this);
            $this.css('position', 'absolute').css("z-index", z);
            if ($this.prev().length != 0) {
                var posTop = (Math.floor(i / 4) * $this.height()) + (Math.floor(i % 2) * 15) + (Math.floor(i % 6 / 5) * 10);
                var posLeft = (Math.floor(i % 4) * $this.width()) + (Math.floor(i % 8 / 4) * 30);
                $this.css("top", posTop).css("left", posLeft);
            }
            else {
                $this.css("left", 0).css("top", 0);
            }
            z--;
            if (i == count - 1) 
                $this.parent().height($this.position().top + $this.height());
        });
    };
})(jQuery);


/**
 * set the priority and direction of the images of the collection thumbs
 */
(function($){
    $.fn.randomizeOrder = function(){
        var z = 8000;
        var count = this.length;
        return this.each(function(i){
            var $this = $(this);
            $this.css('position', 'absolute').css("z-index", z);
            var posTop = 0;
            var posLeft = 0;
            if ($this.prev().length != 0) {
                posTop = Math.floor(i / 3) * $this.height() + Math.floor(i / 3) * 7;
                posLeft = Math.floor(i % 3) * $this.width() + Math.floor(i % 3) * 2;
                $this.css("top", posTop).css("left", posLeft);
                if (i > 2) {
                    posLeft = posLeft + 2;
                }
                if (i % 3 - 1 == 0) 
                    $this.css("top", posTop + 7);
                if (i % 3 - 2 == 0) 
                    $this.css("top", posTop + 14);
            }
            else {
                $this.css("left", 0).css("top", 0);
            }
            z--;
            if (i == count - 1) {
                $this.parent().height($this.position().top + $this.height());
            }
        });
    };
})(jQuery);

/**
 * set the priority and direction of the tiles on the "DEDON Team" page
 */
(function($){
    $.fn.setTeamTiles = function(){
        var z = 8000;
        var x = 2;
        var count = this.length;
        return this.each(function(i){
            var $this = $(this);
            $this.css('position', 'absolute').css("z-index", z);
            if ($this.prev().length != 0) {
            
                if (i % 5 == 0) 
                    x = 3;
                
                var posTop = (Math.floor(i / 5) * ($this.height() + 30)) + (Math.floor(i % x) * 15) + (Math.floor(i % 6 / 5) * 10);
                var posLeft = (Math.floor(i % 5) * ($this.width() + 8)) + (Math.floor(i % 10 / 5) * 30);
                $this.css("top", posTop).css("left", posLeft);
            }
            else {
                $this.css("left", 0).css("top", 0);
            }
            z--;
            if (i == count - 1) 
                $this.parent().height($this.position().top + $this.height());
        });
    };
})(jQuery);

/**
 * set the priority and direction of the images on the start page
 */
(function($){
    $.fn.randomizeOrderCompany = function(){
        var z = 80;
        var count = this.length;
        return this.each(function(i){
            var $this = $(this);
            $this.css('position', 'absolute').find("img").parents("div").css("z-index", z);
            if ($this.prev().length != 0) {
                $this.css("top", $this.prev().position().top + $this.height() * 2 / 3);
                
                if (i % 2 == 0) {
                    if ($this.width() < 480) {
                        $this.css("right", 480).css("text-align", "right");
                    }
                    else {
                        $this.css("left", 40);
                    }
                }
                else {
                    if ($this.width() < 480) {
                        $this.css("left", 480);
                    }
                    else {
                        $this.css("right", 40).css("text-align", "right");
                    }
                }
            }
            else {
                if ($this.width() < 480) {
                    $this.css("right", 480).css("top", 0);
                }
                else {
                    $this.css("left", 0).css("top", 0);
                }
            }
            z -= 1;
            if (i == count - 1) 
                $this.parent().height($this.prev().position().top + $this.height());
        });
    };
})(jQuery);

/**
 * scale tile images on the collection page
 */
(function($){
    $.fn.scaleTileImages = function(){
        return this.each(function(i){
            var $this = $(this);
            $this.hover(function(e){
                if (!$this.hasClass("hover")) {
                    this.newMargin = -($this.width() / 100 * 2);
                    this.oldHeight = $this.height();
                    this.newHeight = this.oldHeight / 100 * 110;
                    this.oldWidth = $this.width();
                    this.newWidth = this.oldWidth / 100 * 110;
                    this.oldZindex = $this.css('z-index');
                    $(this).addClass("hover");
                }
                $this.stop().animate({
                    marginLeft: this.newMargin,
                    marginTop: this.newMargin,
                    width: this.newWidth,
                    height: this.newHeight
                }, 150);
                $this.css({
                    'z-index': '8000'
                });
                if ($("#companyindex").length > 0) 
                    $this.parents("div").first().css({
                        'z-index': '80'
                    });
                if ($("#collectionContainer").length > 0) 
                    $this.parents("h2").first().css({
                        'z-index': '80'
                    });
            }, function(e){
                $this.css({
                    'z-index': this.oldZindex
                });
                if ($("#companyindex").length > 0) 
                    $this.parents("div").first().css({
                        'z-index': this.oldZindex
                    });
                if ($("#collectionContainer").length > 0) 
                    $this.parents("h2").first().css({
                        'z-index': this.oldZindex
                    });
                if ($this != undefined) 
                    $this.animate({
                        marginLeft: '0',
                        marginTop: '0',
                        width: this.oldWidth,
                        height: this.oldHeight
                    }, 150);
            });
        });
    };
}(jQuery));

/**
 * toggle accordion
 */
(function($){
    $.fn.slideBoxes = function(){
        return this.each(function(i){
            if (!$(this).hasClass("active")) {
                $(this).next("div").hide();
            }
            $(this).click(function(){
                if (!$(this).hasClass("active")) {
                    $this = $(this);
                    $(".accordion").next().slideUp("fast");
                    $(".accordion").removeClass("active");
                    $(this).next().delay(200).slideDown("fast", function(){
                        $this.next().children("a").first().click();
                    });
                    $(this).addClass("active");
                    if ($(this).next().hasClass("gallery")) 
                        $(".stage span").hide();
                    
                }
                return false;
            });
        });
    };
}(jQuery));


/**
 * toggle accordion for planner controls
 */
(function($){
    $.fn.slidePlannerBoxes = function(){
        return this.each(function(i){
            if (!$(this).hasClass("active")) {
                $(this).next("div").hide();
            }
            $(this).click(function(){
                if (!$(this).hasClass("active")) {
                    $this = $(this);
                    if (!$(this).parent().hasClass('plannerSubContainer')) {
                        $(".plannerAccordion").next().slideUp("fast");
                        $(".plannerAccordion").removeClass("active");
                        $(this).next().delay(200).slideDown("fast");
                        $(this).addClass("active");
                    }
                    else {
                    	$(".plannerSubContainer .products").slideUp("fast");  // play collection
                    	$(".plannerSubContainer .plannerThumbs").slideUp("fast");
                        $(".plannerSubContainer .plannerAccordion").removeClass("active");
                        $(this).next().delay(200).slideDown("fast");
                        $(this).addClass("active");
                    }
                }
                return false;
            });
        });
    };
}(jQuery));


function initMetaLayerScrollPane(oid){
    $(oid).jScrollPane({
        showArrows: true,
        arrowSize: 20,
        scrollbarWidth: 14,
        dragMinHeight: 14,
        scrollbarMargin: 20
    });
}

/* Social Media - Facebook / Twitter */

function connectFacebook(){
    $("#connectLogin").html('<div class="connectLoggedIn clear"><fb:profile-pic uid="loggedinuser" size="square" facebook-logo="true"></fb:profile-pic><ul><li><span><fb:name uid="loggedinuser" useyou="false" linked="false"></fb:name></span></li><li><a href="#" onclick="logoutFacebook(); return false;" class="logout">Log out</a></li></ul></div>');
    $("#connectLogin").removeClass("connectLogin");
    
    $('#li_commentauthor').html('<input type="hidden" name="tx_t3blog_pi1[blogList][facebookUser]" value="' + FB.Facebook.apiClient.get_session().uid + '" />');
    $('#li_commentauthoremail').html('');
    FB.XFBML.Host.parseDomTree();
}

function logoutFacebook(){
    FB.Connect.logout();
    $("#connectLogin").html('<p>Comment as guest or login below.</p><ul class="clear"><li><a href="#" onclick="FB.Connect.requireSession(); return false;" class="facebookConnect"><span>Connect with Facebook</span></a></li><li><a href="#" onclick="connectTwitter(); return false;" class="twitterConnect">Sign in with Twitter</a></li></ul>');
    $("#connectLogin").addClass("connectLogin");
    
    $('#li_commentauthor').html('<div class="clear"><input type="text" id="commentauthor" title="Name" class="text displace" name="tx_t3blog_pi1[blogList][commentauthor]" value="Name" /></div>');
    $('#li_commentauthoremail').html('<div class="clear"><input type="text" title="Email (will not be shown)" class="text displace" name="tx_t3blog_pi1[blogList][commentauthoremail]" value = "Email (will not be shown)" /></div>');
    FB.XFBML.Host.parseDomTree();
}

function connectTwitter(){
    var url = '/index.php?eID=twitterconnect&url=' + window.location;
    window.location = url;
}

function logoutTwitter(){
    $('#socialLogin').load('/index.php?eID=twitterlogout');
    $('#li_commentauthor').html('<div class="clear"><input type="text" id="commentauthor" title="Name" class="text displace" name="tx_t3blog_pi1[blogList][commentauthor]" value="Name" /></div>');
    $('#li_commentauthoremail').html('<div class="clear"><input type="text" title="Email (will not be shown)" class="text displace" name="tx_t3blog_pi1[blogList][commentauthoremail]" value = "Email (will not be shown)" /></div>');
}

function setPageParameters(title, link){
    document.title = title;
    $(".addthis_toolbox div a").attr("addthis:url", "http://www.dedon.de/" + link);
    $(".addthis_toolbox div a").attr("addthis:title", link);
    if (window.addthis) {
        window.addthis.ost = 0;
        window.addthis.ready();
    }
}

// Redirect the page if Hash is given
function redirectHash(){
    var hash = window.location.hash;
    if (hash) {
        hash = hash.substr(1);
        var path = window.location.pathname;
        var ext = path.substr(path.lastIndexOf('.'));
        path = path.substr(0, path.lastIndexOf('/'));
        path = path.substr(0, path.lastIndexOf('/') + 1);
        path = path + hash + ext;
        window.location.href = path;
    }
}

// Extract Hash from URL
function setHash(url){
    var path = url;
    path = path.substr(0, path.lastIndexOf('/'));
    path = path.substr(0, path.lastIndexOf('/'));
    window.location.hash = url.substr(path.length + 1, url.lastIndexOf('.') - (path.length + 1));
}

/* GoogleMaps for shops */
var apikey_dev = "ABQIAAAApy5xfn5SOY98AP3mOFGM4BRdDPip7q9ghW7JFjBZtK4pDnLLghQOvdPR7_Grmit-msuu6MQGM_PZtQ";
var apikey_prod = "ABQIAAAApy5xfn5SOY98AP3mOFGM4BRSBUIQ-Q0FHvVTyQzEZGWvUIy_YRSODLf8pYd6F-TFK00x-58m4J9U3Q";
var apikey = (window.location.href.indexOf("www.dedon.de") == -1) ? apikey_dev : apikey_prod;
var address;
var geolocation;

function initLoader(obj){
    var adr = $(obj).parents(".vcard").find(".adr");
    var arrAdr = new Array($(adr).children(".street-address").html(), $(adr).children(".postal-code").text(), $(adr).children(".locality").text(), $(adr).children(".country-name").text());
    address = $(obj).parents(".vcard").find(".fn.org").text() + '<br />' + arrAdr[0] + '<br />' + arrAdr[1] + ' ' + arrAdr[2];
    var geo = $(obj).parents(".vcard").find(".geo");
    if (geo.length > 0) {
        geolocation = $(geo).children(".latitude").text() + "," + $(geo).children(".longitude").text();
    }
    else {
        geolocation = arrAdr.join(' ');
    }
    var script = document.createElement("script");
    script.src = "http://maps.google.com/maps/api/js?sensor=false&key=" + apikey + "&callback=loadMaps";
    script.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(script);
}

function loadMaps(){
    geocoder = new google.maps.Geocoder();
    geocoder.geocode({
        'address': geolocation
    }, function(results, status){
        if (status == google.maps.GeocoderStatus.OK) {
            var myOptions = {
                zoom: 13,
                center: results[0].geometry.location,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
            var infowindow = new google.maps.InfoWindow({
                content: address
            });
            
            var marker = new google.maps.Marker({
                position: results[0].geometry.location,
                map: map
            });
            
            google.maps.event.addListener(marker, 'click', function(){
                infowindow.open(map, marker);
            });
            infowindow.open(map, marker);
        }
        else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

/**
 * newsletter subscription form
 */
(function($){
    $.fn.newsletterForm = function(){
    
        // --- behavior
        $('.checkboxfake').css('display', 'block');
        $('.input-check').css('display', 'none');
        $('.checkboxfake').click(function(){
            if ($(this).hasClass("off")) {
                // radiobox behavior for checkboxgroup
                if ($(this).prev().attr('name') == 'newslettertype') {
                    $('input[name=newslettertype]').attr('checked', false);
                    $('input[name=newslettertype]').next().removeClass("on").addClass("off");
                }
                $(this).addClass("on").removeClass("off").prev().attr('checked', true);
            }
            else {
                $(this).addClass("off").removeClass("on").prev().attr('checked', false);
            }
        });
        $('.nlsubscr .input-text').toggleValue();
        
        // --- validation
        var action = $('.nlsubscr').attr('action');
        // custom method making the default values invalid
        jQuery.validator.addMethod("defaultInvalid", function(value, element){
            return value != element.defaultValue;
        }, "");
        jQuery.validator.messages.required = "";
        
        $(".nlsubscr").validate({
            invalidHandler: function(e, validator){
                var errors = validator.numberOfInvalids();
                if (errors) {
                    $("p.catalogintro").html($("span.errortext").text());
                    $("p.catalogintro").addClass('errormsg');
                }
            },
            errorPlacement: function(error, element){
            },
            submitHandler: function(form){
                var dataString = $(form).serialize();
                $.ajax({
                    type: 'POST',
                    url: action,
                    data: dataString,
                    success: function(data){
                        var result = $(data).find("#metaContent").html();
                        $("#nyroModalContent").children().fadeOut("fast", function(){
                            $("#nyroModalContent").children().remove();
                            $("#nyroModalContent").append(result).children().hide().fadeIn("fast");
                        });
                    }
                });
            }
        });
    }
}(jQuery));


/**
 * catalog order form
 */
(function($){
    $.fn.catalogForm = function(){
        // --- behavior
        $('.checkboxfake').css('display', 'block');
        $('.input-check').css('display', 'none');
        $('.checkboxfake').click(function(){
            if ($(this).hasClass("off")) {
                // radiobox behavior for checkboxgroup
                if ($(this).prev().attr('name') == 'catalogtype') {
                    $('input[name=catalogtype]').attr('checked', false);
                    $('input[name=catalogtype]').next().removeClass("on").addClass("off");
                }
                $(this).addClass("on").removeClass("off").prev().attr('checked', true);
            }
            else {
                $(this).addClass("off").removeClass("on").prev().attr('checked', false);
            }
        });
        $('#ordercatalog .input-text').toggleValue();
        
        // --- validation
        var action = $('#ordercatalog').attr('action');
        var defaultPobox = $('#pobox').attr('value');
        // custom method making the default values invalid
        jQuery.validator.addMethod("defaultInvalid", function(value, element){
            return value != element.defaultValue;
        }, "");
        // custom method making street and number invalid if PO Box is not filled
        jQuery.validator.addMethod("adressInvalid", function(value, element){
            if ($("#pobox").val() == defaultPobox || $("#pobox").val() == '') 
                return value != element.defaultValue;
            return true;
        }, "");
        jQuery.validator.messages.required = "";
        
        $("#ordercatalog").validate({
            invalidHandler: function(e, validator){
                var errors = validator.numberOfInvalids();
                if (errors) {
                    $("p.catalogintro").html($("span.errortext").text());
                    $("p.catalogintro").addClass('errormsg');
                }
            },
            errorPlacement: function(error, element){
            },
            submitHandler: function(form){
                var dataString = $(form).serialize();
                $.ajax({
                    type: 'POST',
                    url: action,
                    data: dataString,
                    success: function(data){
                        var result = $(data).find("#metaContent").html();
                        $("#nyroModalContent").children().fadeOut("fast", function(){
                            $("#nyroModalContent").children().remove();
                            $("#nyroModalContent").append(result).children().hide().fadeIn("fast");
                        });
                    }
                });
            }
        });
    }
}(jQuery));


/**
 * toggle defaulttext in input fields
 */
(function($){
    $.fn.toggleValue = function(){
        $(this).focus(function(){
            return $(this).each(function(){
                var defaultText = $(this).attr('title');
                if ($(this).val() == defaultText) {
                    $(this).val('');
                }
                $(this).blur(function(){
                    if ($.trim($(this).val()) == '') {
                        $(this).val(defaultText);
                    }
                });
            });
        });
    }
}(jQuery));

(function($){
    var cache = [];
    $.preLoadImages = function(){
        var args_len = arguments.length;
        for (var i = args_len; i--;) {
            var cacheImage = document.createElement('img');
            cacheImage.src = arguments[i];
            cache.push(cacheImage);
        }
    }
})(jQuery);

function cloneAndScaleSVG(){
    var amount = $("#dragwrapper").width() < 650 ? 1 : 650 / $("#dragwrapper").width();
    if ($('#cloneSVG').children().length == 0) {
        $('#dragwrapper').clone(false).appendTo('#cloneSVG');
        $('#cloneSVG').find("*").each(function(index){
            var objId = $(this).attr("id");
            if (objId != "") 
                $(this).attr("id", objId + "_cloned");
        });
        $("#dragwrapper_cloned").css({
            "left": 0,
            "top": 0
        });
    }
    $("#dragwrapper_cloned").width($("#dragwrapper").width() * amount).height($("#dragwrapper").height() * amount);
    $("#dragcon_cloned").width(parseInt($("#dragwrapper").width() * amount)).height(parseInt($("#dragwrapper").height() * amount)).css({
        "background-image": $("#dragcon").css("background-image")
    });
    ;
    $("#dragcon_cloned").find("div").remove();
    $("#dragcon_cloned").find("svg").remove();
    var cloned = Raphael(document.getElementById("dragcon_cloned"), parseInt($("#dragwrapper").width() * amount), parseInt($("#dragwrapper").height() * amount));
    var svgImages = $("#dragcon").find("image");
    for (var i = 0; i < svgImages.length; i++) {
        if (svgImages[i] != undefined) 
            if (svgImages[i].raphael != undefined) {
                var ci = cloned.image(svgImages[i].raphael.image, parseInt(svgImages[i].raphael.attr("x") * amount), parseInt(svgImages[i].raphael.attr("y") * amount), parseInt(svgImages[i].raphael.attr("width") * amount), parseInt(svgImages[i].raphael.attr("height") * amount));
                ci.rotate(svgImages[i].raphael.attr("rotation"), ci.attr("x") + ci.attr("width") / 2, ci.attr("y") + ci.attr("height") / 2);
            }
    }
    var bgImage = $("#dragcon").css("background-image");
    if (bgImage.search("gridSquare") != -1 || bgImage.search("gridLines") != -1) {
        bgImage = bgImage.replace(/"/g, "").replace(/url\(|\)$/ig, "");
        bgImage = bgImage.replace(".png", "Print.png");
        var bg = cloned.image(bgImage, 0, 0, 2000 * amount, 2000 * amount);
        bg.toBack();
    }
}


/**
 *
 */
(function($){
    $.fn.initializeSvg = function(){
        var $this = $(this);
        svg = Raphael(document.getElementById($this.attr("id")), $this.width(), $this.height());
        $this.parent().parent().droppable({
            accept: '.draggableImage',
            tolerance: 'fit',
            scope: 'SVG',
            drop: function(e, ui){
                var droppedImg = svg.image(ui.helper.attr("rel"), ui.helper.offset().left - $this.offset().left, ui.helper.offset().top - $this.offset().top, ui.helper.width(), ui.helper.height());
                droppedImg.attr({
                    cursor: "move"
                });
                if (!isWithinStage(droppedImg)) {
                    droppedImg.animate({
                        opacity: 0
                    }, 1000, ">", function(){
                        droppedImg.remove();
                    });
                }
                else {
                    droppedImg.rot = 0;
                    droppedImg.isNew = true;
                    droppedImg.source = ui.helper.attr("title");
                    droppedImg.id = ui.helper.attr("alt");
                    droppedImg.highlight = ui.helper.attr("src");
                    addImageToHoverList(droppedImg);
                    addEntryToTable(droppedImg);
                    handlePlannerObjects(droppedImg);
                    addSVGListeners(droppedImg);
                    addToStagefield(droppedImg);
                    $(svgElements).each(function(key, elem){
                        if (droppedImg.id == elem.ID) {
                            droppedImg.image = elem.ImageUrl;
                            droppedImg.highlight = elem.ImageHighlightUrl;
                            droppedImg.hover = elem.ImageHoverUrl;
                            droppedImg.list = elem.ImageListUrl;
                        }
                    });
                }
            }
        });
    }
}(jQuery));

/**
 *
 */
(function($){
    $.fn.leaveStage = function(){
        $(this).mouseleave(function(e){
            unhighlightAllSVGImages();
            removeOptions();
            cloneAndScaleSVG();
        });
    }
}(jQuery));

/**
 *
 */
(function($){
    $.fn.addSmallShadows = function(){
        var $this = $(this);
        $this.append("<div style='position:absolute; top:0; left:0; width:8px; height:8px; background:transparent url(fileadmin/blogazine/html/_img/shadows/small_lo.png) no-repeat 0 0;'></div>");
        $this.append("<div style='position:absolute; top:0; right:0; width:8px; height:8px; background:transparent url(fileadmin/blogazine/html/_img/shadows/small_ro.png) no-repeat 0 0;'></div>");
        $this.append("<div style='position:absolute; bottom:0; left:0; width:8px; height:8px; background:transparent url(fileadmin/blogazine/html/_img/shadows/small_lu.png) no-repeat 0 0;'></div>");
        $this.append("<div style='position:absolute; bottom:0; right:0; width:8px; height:8px; background:transparent url(fileadmin/blogazine/html/_img/shadows/small_ru.png) no-repeat 0 0;'></div>");
        $this.append("<div style='position:absolute; top:8px; left:0; width:8px; height:" + ($this.height() - 16) + "px; background:transparent url(fileadmin/blogazine/html/_img/shadows/small_l.png) repeat-y 0 0;'></div>");
        $this.append("<div style='position:absolute; top:8px; right:0; width:8px; height:" + ($this.height() - 16) + "px; background:transparent url(fileadmin/blogazine/html/_img/shadows/small_r.png) repeat-y 0 0;'></div>");
        $this.append("<div style='position:absolute; top:0; left:8px; width:" + ($this.width() - 16) + "px; height:8px; background:transparent url(fileadmin/blogazine/html/_img/shadows/small_o.png) repeat-x 0 0;'></div>");
        $this.append("<div style='position:absolute; bottom:0; left:8px; width:" + ($this.width() - 16) + "px; height:8px; background:transparent url(fileadmin/blogazine/html/_img/shadows/small_u.png) repeat-x 0 0;'></div>");
    }
}(jQuery));

/**
 *
 */
(function($){
    $.fn.handleDraggables = function(){
        var $this = $(this);
        
        $this.draggable({
            scope: 'SVG',
            revert: 'invalid',
            opacity: 0.8,
            cursorAt: {
                cursor: 'move',
                top: 25,
                left: 45
            },
            revert: 'invalid',
            start: function(e, ui){
            },
            helper: function(event, ui){
                var $this = $(this);
                var dragImg;
                var accepted = false;
                $(svgElements).each(function(key, elem){
                    if ($this.attr("id") == elem.ID) {
                        $this.addClass("draggableImage");
                        dragImg = $('<img src="' + elem.ImageHighlightUrl + '" alt="' + elem.ID + '" title="' + elem.Model + '" rel="' + elem.ImageUrl + '" />');
                        dragImg.css({
                            'z-index': '10000'
                        });
                        accepted = true;
                    }
                });
                if (!accepted) 
                    dragImg = $('<div></div>');
                return dragImg;
            },
            stop: function(e, ui){
            }
        });
    }
}(jQuery));

/**
 *
 */
function handlePlannerObjects(obj){
    obj.ow = obj.attr("width");
    obj.oh = obj.attr("height");
    var start = function(){
        this.ox = this.attr("x");
        this.oy = this.attr("y");
        this.rot = 0;
        this.animate({
            opacity: 0.8
        }, 500, ">");
        this.toFront();
        removeSVGListeners(this);
        $("#dragwrapper").draggable({
            disabled: true
        });
    }, move = function(dx, dy){
        this.attr({
            x: this.ox + dx,
            y: this.oy + dy
        });
    }, up = function(){
        highlightSVGImage(this);
        if (!isWithinStage(this)) {
            resetPosition(this);
        }
        else {
            this.animate({
                height: this.oh,
                opacity: 1
            }, 500, ">");
            updateStagefield(this);
            attachOptions(this);
            addSVGListeners(this);
        }
        initDraggableStage();
    };
    obj.drag(move, start, up);
    obj.mouseover(function(event){
        unhighlightAllSVGImages();
        highlightSVGImage(this);
    });
    obj.mouseout(function(event){
        unhighlightSVGImage(this);
    });
}

function highlightSVGImageById(id){
    var svgImages = $("#dragcon").find("image");
    for (var i = 0; i < svgImages.length; i++) {
        if (svgImages[i] != undefined) 
            if (svgImages[i].raphael != undefined) {
                if (svgImages[i].raphael.id == id) {
                    svgImages[i].raphael.attr({
                        src: svgImages[i].raphael.highlight
                    });
                }
            }
    }
}

function unhighlightSVGImageById(id){
    var svgImages = $("#dragcon").find("image");
    for (var i = 0; i < svgImages.length; i++) {
        if (svgImages[i] != undefined) 
            if (svgImages[i].raphael != undefined) {
                if (svgImages[i].raphael.id == id) {
                    svgImages[i].raphael.attr({
                        src: svgImages[i].raphael.image
                    });
                }
            }
    }
}

function highlightSVGImage(obj){
    if (!isRotating) {
        obj.attr({
            src: obj.highlight
        });
    }
}

function unhighlightSVGImage(obj){
    obj.attr({
        src: obj.image
    });
}

function unhighlightAllSVGImages(){
    var svgImages = $("#dragcon").find("image");
    for (var i = 0; i < svgImages.length; i++) {
        if (svgImages[i] != undefined) 
            unhighlightSVGImage(svgImages[i].raphael);
    }
}

function addImageToHoverList(obj){
    $(svgElements).each(function(key, elem){
        if (obj.id == elem.ID) {
            var exists = false;
            for (var i = 0; i < stageField.length; i++) {
                if (elem.ID == stageField[i]["id"]) 
                    exists = true;
            }
            if (!exists) 
                $("#hoverList").append("<img class='hoverImage' src='" + elem.ImageHoverUrl + "' alt='" + elem.ID + "' title='' />");
        }
    });
    setTimeout(function(){
        $("#hoverList").reorderImages();
        $(".hoverImage").mouseover(function(){
            highlightSVGImageById($(this).attr("alt"));
            hoverImage($(this));
        }).mouseout(function(){
            unhighlightSVGImageById($(this).attr("alt"));
        });
    }, 500);
}

function removeImageFromHoverList(obj){
    var exists = false;
    for (var i = 0; i < stageField.length; i++) {
        if (obj.id == stageField[i]["id"]) 
            exists = true;
    }
    if (!exists) {
        $("#hoverList").find("img[alt$='" + obj.id + "']").remove();
        setTimeout(function(){
            $("#hoverList").reorderImages();
            $(".hoverImage").mouseover(function(){
                highlightSVGImageById($(this).attr("alt"));
                hoverImage($(this));
            }).mouseout(function(){
                unhighlightSVGImageById($(this).attr("alt"));
            });
        }, 500);
    }
}

/**
 *
 */
(function($){
    $.fn.reorderImages = function(){
        var $this = $(this);
        var z = 8000;
        $this.children().css({
            "position": "relative",
            "float": "left"
        });
        $this.height(120 * Math.ceil($this.children().length / 4));
        $this.children().each(function(i){
            var $this = $(this);
            $this.css('position', 'absolute').css("z-index", z);
            if ($this.prev().length != 0) {
                var posTop = (Math.floor(i / 4) * $this.height()) + (Math.floor(i % 2) * 15);
                var posLeft = (Math.floor(i % 4) * $this.width()) + (Math.floor(i % 8 / 4) * 30);
                $this.css("top", posTop).css("left", posLeft);
            }
            else {
                $this.css("left", 0).css("top", 0);
            }
            z--;
        });
    };
})(jQuery);

function hoverImage(obj){
    if (!animating) {
        animating = true;
        obj.animate({
            width: '+=10',
            height: '+=10'
        }, 200, function(){
            $(this).animate({
                width: '-=10',
                height: '-=10'
            }, 200, function(){
                animating = false;
            });
        });
    }
}

function highlightHoverImage(obj){
    if (!animating && !obj.isNew) {
        animating = true;
        $("#hoverList").find("img[alt$='" + obj.id + "']").delay(200).animate({
            width: '+=10',
            height: '+=10'
        }, 200, function(){
            $(this).animate({
                width: '-=10',
                height: '-=10'
            }, 200, function(){
                animating = false;
            });
        });
    }
    obj.isNew = false;
}

function addEntryToTable(obj){
    $("#listEntries").show();
    $(svgElements).each(function(key, elem){
        if (obj.id == elem.ID) {
            var exists = false;
            for (var i = 0; i < stageField.length; i++) {
                if (elem.ID == stageField[i]["id"]) 
                    exists = true;
            }
            if (!exists) {
                $("table#listEntries tbody").append("<tr class='" + elem.ID + "'><td class='imagecell'><img src='" + elem.ImageListUrl + "' alt='' title='' /></td><td align='center' class='borderright count'>1</td><td class='borderright'>" + elem.ArticleNo + "</td><td class='borderright'>" + elem.Collection + "</td><td>" + elem.Model + "</td></tr>");
            }
            else {
                var productCounter = $("tr." + elem.ID).find("td.count");
                productCounter.text(parseInt(productCounter.text()) + 1);
                
            }
        }
    });
}

function removeEntryFromTable(obj){
    $(svgElements).each(function(key, elem){
        if (obj.id == elem.ID) {
            var exists = false;
            for (var i = 0; i < stageField.length; i++) {
                if (elem.ID == stageField[i]["id"]) {
                    var productCounter = $("tr." + elem.ID).find("td.count");
                    if (productCounter.text() == "1") {
                        productCounter.parent().remove();
                    }
                    else {
                        productCounter.text(parseInt(productCounter.text()) - 1);
                    }
                    break;
                }
            }
        }
    });
}

function addSVGListeners(obj){
    initDraggableStage();
    obj.mouseover(attachOptions);
}

function removeSVGListeners(obj){
    removeOptions();
    obj.unmouseover(attachOptions);
    initDraggableStage();
}

function attachOptions(evt){
    if (!isRotating) {
        if (evt.ox != undefined) {
            var obj = evt;
        }
        else {
            var obj = this;
        }
        removeOptions();
        if ((obj.attr('x') < 20 || obj.attr('y') < 20 || obj.attr('x') > $("#dragcon").width() - obj.attr('width') - 20) && obj.attr('width') > 50) {
            coordXA = obj.attr('x') + 2;
            coordXB = obj.attr('x') + obj.attr('width') - 22;
            coordY = obj.attr('y') + 2;
        }
        else {
            coordXA = obj.attr('x') - 20;
            coordXB = obj.attr('x') + obj.attr('width');
            coordY = obj.attr('y') - 20;
        }
        optRotate = svg.image("fileadmin/blogazine/html/_img/rotate.png", coordXA, coordY, 21, 23);
        optRotate.active = "fileadmin/blogazine/html/_img/rotateHover.png";
        optRotate.image = null;
        optRotate.inactive = "fileadmin/blogazine/html/_img/rotate.png";
        optRotate.attr({
            cursor: "pointer"
        });
        optRotate.toFront();
        optRotate.mousedown(function(e){
            startAngle = calcAngle(obj, e);
            optRotate.unmouseout(this.optionsOut);
            optDel.unmouseout(this.optionsOut);
            obj.rotateSVGObject(e);
        });
        optDel = svg.image("fileadmin/blogazine/html/_img/delete.png", coordXB, coordY, 18, 18);
        optDel.active = "fileadmin/blogazine/html/_img/deleteHover.png";
        optDel.inactive = "fileadmin/blogazine/html/_img/delete.png";
        optDel.image = null;
        optDel.toFront();
        optDel.attr({
            cursor: "pointer"
        });
        optDel.click(function(){
            deleteSVGObjects(new Array(obj, optDel, optRotate));
        });
        optRotate.mouseout(this.optionsOut);
        optDel.mouseout(this.optionsOut);
        $("#dragcon").mouseup(function(){
            obj.stopRotateSVGObject();
            optRotate.mouseout(this.optionsOut);
            optDel.mouseout(this.optionsOut);
            optRotate.attr({
                src: optRotate.inactive
            });
        });
        optRotate.mouseover(function(){
            optRotate.attr({
                src: optRotate.active
            });
            highlightSVGImage(obj)
        });
        optDel.mouseover(function(){
            optDel.attr({
                src: optDel.active
            });
            highlightSVGImage(obj)
        });
        highlightHoverImage(obj);
    }
}

if (!($.browser.msie && $.browser.version == "6.0")) 
    if (Raphael != null) {
        if (Raphael.el != null) {
            Raphael.el.optionsOut = function(e){
                removeOptions();
                $(svgElements).each(function(key, elem){
                    if (this.id == elem.ID) {
                        this.attr({
                            src: elem.ImageUrl
                        });
                    }
                });
            }
        }
    }

function hideOptions(){
    if (optRotate || optDel) {
        optRotate.hide();
        optDel.hide();
    }
}

function showOptions(){
    if (optRotate || optDel) {
        optRotate.show();
        optRotate.attr({
            src: optRotate.inactive
        });
        optDel.show();
        optDel.attr({
            src: optDel.inactive
        });
    }
}

function removeOptions(){
    if (optRotate || optDel) {
        optRotate.remove();
        optDel.remove();
    }
}

function deleteSVGObjects(arr){
    removeEntryFromTable(arr[0]);
    stageField[arr[0].objId] = {
        'objId': arr[0].objId,
        'id': '',
        'width': 0,
        'height': 0,
        'x': -1000,
        'y': -1000
    };
    removeImageFromHoverList(arr[0]);
    for (var i = 0; i < arr.length; i++) {
        arr[i].remove();
    }
}

if (!($.browser.msie && $.browser.version == "6.0")) 
    if (Raphael != null) {
        if (Raphael.el != null) {
            Raphael.el.rotateSVGObject = function(e){
                isRotating = true;
                var obj = this;
                unhighlightSVGImage(obj);
                e.preventDefault();
                $("#dragwrapper").draggable({
                    disabled: true
                });
                objRot = obj.attr('rotation');
                $("#dragcon").mousemove(function(e){
                    obj.followMouse(e)
                });
                hideOptions();
            }
        }
    }

if (!($.browser.msie && $.browser.version == "6.0")) 
    if (Raphael != null) {
        if (Raphael.el != null) {
            Raphael.el.stopRotateSVGObject = function(e){
                isRotating = false;
                if (optRotate) {
                    if (optRotate.id != undefined) {
                        optRotate.unmousemove(this.followMouse);
                    }
                }
                $("#dragcon").unbind('mousemove');
                initDraggableStage();
                showOptions();
            }
        }
    }

if (!($.browser.msie && $.browser.version == "6.0")) 
    if (Raphael != null) {
        if (Raphael.el != null) {
            Raphael.el.followMouse = function(e){
                try {
                    var rotX = (calcAngle(this, e) - startAngle) * 180 / Math.PI;
                    if ((rotX + objRot) == 360) 
                        objRot -= 360;
                    if ((rotX + objRot) == -360) 
                        objRot += 360;
                    if (((rotX + objRot) > -10) && ((rotX + objRot) < 10)) {
                        this.rotate(0, true);
                    }
                    else 
                        if (((rotX + objRot) > 80) && ((rotX + objRot) < 100)) {
                            this.rotate(90, true);
                        }
                        else 
                            if (((rotX + objRot) > 170) && ((rotX + objRot) < 190)) {
                                this.rotate(180, true);
                            }
                            else 
                                if (((rotX + objRot) > 260) && ((rotX + objRot) < 280)) {
                                    this.rotate(270, true);
                                }
                                else 
                                    if (((rotX + objRot) > -80) && ((rotX + objRot) < -100)) {
                                        this.rotate(270, true);
                                    }
                                    else {
                                        this.rotate(rotX + objRot, true);
                                    }
                } 
                catch (e) {
                    alert(e);
                }
            }
        }
    }

function calcAngle(obj, event){
    if (event.pageX == null) {
        var d = (document.documentElement &&
        document.documentElement.scrollLeft != null) ? document.documentElement : document.body;
        docX = event.clientX + d.scrollLeft;
        docY = event.clientY + d.scrollTop;
    }
    else {
        docX = event.pageX;
        docY = event.pageY;
    }
    
    return Math.atan2(docY - (obj.attr('y') + $("#dragcon").offset().top + obj.attr('height') / 2), docX - (obj.attr('x') + $("#dragcon").offset().left + obj.attr('width') / 2));
}

function addToStagefield(obj){
    obj.objId = stageField.length;
    stageField.push({
        'id': obj.id,
        'objId': obj.objId,
        'width': obj.attr('width'),
        'height': obj.attr('height'),
        'x': obj.attr("x"),
        'y': obj.attr("y"),
        'rot': obj.attr('rotation')
    });
}

function updateStagefield(obj){
    stageField[obj.objId] = {
        'id': obj.id,
        'objId': obj.objId,
        'width': obj.attr('width'),
        'height': obj.attr('height'),
        'x': obj.attr("x"),
        'y': obj.attr("y"),
        'rot': obj.attr('rotation')
    };
}

function isWithinStage(obj){
    var o1h = parseInt(obj.attr('height'));
    var o1w = parseInt(obj.attr('width'));
    var min = o1h <= o1w ? o1h : o1w;
    var o1t = parseInt(obj.attr("y")) + (parseInt(obj.attr('height') / 2) - (min / 2));
    var o1l = parseInt(obj.attr("x")) + (parseInt(obj.attr('width') / 2) - (min / 2));
    o1h = min;
    o1w = min;
    var o2h = $("#dragcon").height();
    var o2w = $("#dragcon").width();
    if (o1l > 0 &&
    o1l + o1w < o2w &&
    o1t > 0 &&
    o1t + o1h < o2h) {
        return true
    }
    else {
        return false;
    }
}

function isNumeric(input){
    return (input - 0) == input && input.length > 0;
}

function resetPosition(obj){
    obj.animate({
        x: obj.ox,
        y: obj.oy,
        opacity: 1
    }, 500, ">", function(){
        updateStagefield(obj);
        addSVGListeners(obj);
    });
}

function initDraggableStage(){
    if ($("#dragwrapper").height() <= $("#dragwrapper").parent().height() && $("#dragwrapper").width() <= $("#dragwrapper").parent().width()) {
        $("#dragwrapper").draggable({
            disabled: true
        });
    }
    else 
        if ($("#dragwrapper").height() < $("#dragwrapper").parent().height()) {
            $("#dragwrapper").draggable({
                containment: [$("#dragwrapper").parent().offset().left - ($("#dragwrapper").width() - $("#dragwrapper").parent().width()), 0, $("#dragwrapper").parent().offset().left, 1000],
                axis: 'x',
                disabled: false
            });
        }
        else 
            if ($("#dragwrapper").width() < $("#dragwrapper").parent().width()) {
                $("#dragwrapper").draggable({
                    containment: [0, $("#dragwrapper").parent().offset().top - ($("#dragwrapper").height() - $("#dragwrapper").parent().height()), 1000, $("#dragwrapper").parent().offset().top],
                    axis: 'y',
                    disabled: false
                });
            }
            
            else {
                $("#dragwrapper").draggable({
                    containment: [$("#dragwrapper").parent().offset().left - ($("#dragwrapper").width() - $("#dragwrapper").parent().width()), $("#dragwrapper").parent().offset().top - ($("#dragwrapper").height() - $("#dragwrapper").parent().height()), $("#dragwrapper").parent().offset().left, $("#dragwrapper").parent().offset().top],
                    disabled: false
                });
            }
}

$(document).ready(function(){
    if (!($.browser.msie && $.browser.version == "6.0")) 
        if ($(".plannerControls").length > 0) {
            $("a.plannerAccordion").first().addClass("active").show();
            $("div.plannerSubContainer").first().show().find("a.plannerAccordion").first().addClass("active").next().show();
            w = 1200;
            h = 800;
            $("span.stageWidth").text(w);
            $("span.stageHeight").text(h);
            w = parseInt(w * 715 / 1200);
            h = parseInt(h * 472 / 800);
            $("#dragcon").width(w).height(h);
            $("#dragwrapper").width(w).height(h);
            $("#content").css("padding-top", "80px")
            $("#topiclink").css("font-size", "14px");
            $("a.showLayer").nyroModal({
                minHeight: 0,
                minWidth: 0,
                windowResize: false,
                bgColor: '#333333',
                showTransition: false,
                closeButton: '<a href="#" class="nyroModalClose planner" id="closeBut" title="close">Close</a>'
            });
            $("a.showLayer").attr("href", "#dragwrapper").click(function(){
                $("#nyroModalWrapper").css("padding", "0px");
                $("#nyroModalContent").css("overflow", "auto");
            });
            $("a.resetLayer").attr("href", "#stageLayer");
            var initial = true;
            var submitted = false;
            stageField = new Array();
            $("#stageShadow").mousedown(function(e){
                e.preventDefault();
            });
            $("a.resetLayer").nyroModal({
                bgColor: '#333333',
                minHeight: 175,
                windowResize: false,
                endRemove: function(){
                    if (!submitted) 
                        $("input.input-submit").click();
                },
                endShowContent: function(){
                    submitted = false;
                    $(".stageLayer .input-text").toggleValue();
                    $(".stageLayer .input-text").bind('keypress', function(e){
                        return (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) ? false : true;
                    });
                    if (initial) {
                        $("div.stageLayer p").hide();
                        $("div.stageLayer p.initial").show();
                    }
                    else {
                        $("div.stageLayer p").hide();
                        $("div.stageLayer p.reset").show();
                    }
                    initial = false;
                    $("input.input-text").bind("keypress", function(e){
                        var code = (e.keyCode ? e.keyCode : e.which);
                        if (code == 13) {
                            $("input.input-submit").click();
                        }
                    });
                    
                    $("input.input-submit").click(function(){
                        submitted = true;
                        $("table#listEntries").hide();
                        $("table#listEntries tbody").find("tr").remove();
                        $("#hoverList").css({
                            "height": "1%"
                        }).find("img").remove();
                        stageField = new Array();
                        $("#dragwrapper").find("svg").remove();
                        $("#dragwrapper").find("div:not(#dragcon)").remove();
                        w = $("input[name$='width']").val();
                        h = $("input[name$='height']").val();
                        w = !isNumeric(w) ? 1200 : w;
                        w = w < 200 ? 200 : w;
                        w = w > 1800 ? 1800 : w;
                        h = !isNumeric(h) ? 800 : h;
                        h = h < 200 ? 200 : h;
                        h = h > 1800 ? 1800 : h;
                        $("span.stageWidth").text(w);
                        $("span.stageHeight").text(h);
                        w = parseInt(w * 715 / 1200);
                        h = parseInt(h * 472 / 800);
                        if (w < h) {
                            var tmp = h;
                            h = w;
                            w = tmp;
                        }
                        $("a.nyroModalClose").click();
                        $("#dragcon").width(w).height(h);
                        $("#dragwrapper").width(w).height(h);
                        if (w <= $("#dragwrapper").parent().width()) {
                            $("#dragwrapper").css({
                                'left': ($("#dragwrapper").parent().width() / 2) - (w / 2)
                            });
                        }
                        else {
                            $("#dragwrapper").css({
                                'left': 0
                            });
                        }
                        if (h <= $("#dragwrapper").parent().height()) {
                            $("#dragwrapper").css({
                                'top': ($("#dragwrapper").parent().height() / 2) - (h / 2)
                            });
                        }
                        else {
                            $("#dragwrapper").css({
                                'top': 0
                            });
                        }
                        $("#dragcon").initializeSvg();
                        $("#dragwrapper").parent().leaveStage();
                        $("#dragcon").addSmallShadows();
                        if (((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPad/i)))) {
                            $("a.plannerThumb").each(function(){
                                $(this).bind("touchstart", function(event){
                                    $this = $(this);
                                    $(svgElements).each(function(key, elem){
                                        if ($this.attr("id") == elem.ID) {
                                            dragImg = $('<div id="' + elem.ID + 'touch"><img src="' + elem.ImageHighlightUrl + '" alt="' + elem.ID + '" title="' + elem.Model + '" rel="' + elem.ImageUrl + '" /></div>');
                                            dragImg.appendTo("body");
                                            dragImg.css({
                                                'z-index': '10000',
                                                'position': 'absolute',
                                                'left': $this.offset().left,
                                                'top': $this.offset().top,
                                            });
                                            $("#" + elem.ID + "touch").touch({
                                                animate: false,
                                                sticky: false,
                                                dragx: true,
                                                dragy: true,
                                                rotate: false,
                                                resort: false,
                                                scale: false
                                            });
                                        }
                                    });
                                }, false);
                            });
                        }
                        else {
                            $("a.plannerThumb").handleDraggables();
                        }
                        $("a.changeBG").click(function(e){
                            e.preventDefault();
                            $('#dragcon').css('background-image', 'url(' + $(this).attr("href") + ')');
                            if ($("#topiclink").find("span").length == 0) {
                                $("#topiclink").append("<span style='color:#EEA500;'> \"" + $(this).text() + "\"</span>");
                            }
                            else {
                                $("#topiclink").find("span").text(" \"" + $(this).text() + "\"");
                            }
                        });
                        initDraggableStage();
                    });
                },
                showTransition: false
            });
            $("a.resetLayer").first().click();
            $(document).keypress(function(e){
                if (e.keyCode == 27) {
                    $("a.resetLayer").first().click();
                }
            });
            $(document).keydown(function(e){
            	if  ($("a.plannerThumb").length > 0) {
	                if (e.ctrlKey == true || e.keyCode == 224) {
	                    unhighlightAllSVGImages();
	                    removeOptions();
	                    cloneAndScaleSVG();
	                    
	                }
            	}
            });
            jQuery.preLoadImages("fileadmin/blogazine/html/_img/rotate.png");
            jQuery.preLoadImages("fileadmin/blogazine/html/_img/delete.png");
            jQuery.preLoadImages("fileadmin/blogazine/html/_img/rotateHover.png");
            jQuery.preLoadImages("fileadmin/blogazine/html/_img/deleteHover.png");
        }
        
    // play collection
    if ($('#sitetools').length > 0) {
        $("#content").css("padding-top", "120px");
    }
    if ($('.property2').length > 0) {
        $(".customize").css("min-height", "310px");
    }
    $(document).ready(function () {
        $('#playGalleryImage').delay(3000).fadeOut(2000);
    });
    
    // hide some teaser on homepage for subdomain macro
    if ($('#indexpage').length > 0) {
        if (window.location.href.indexOf("macro.") != -1) {
            $('.t2').hide();
            $('.t4').hide();
            $('.t8').addClass('t8-macro');
        }
    }
    
    if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
    }
    else {
        // if (!$.browser.msie) 
        //     $('#wrapper').pageFadeIn();
        $('a.floatBox').nyroModal({
            bgColor: '#fff',
            width: 685,
            height: 398,
            padding: 15,
            windowResize: false,
            endShowContent: function(){
                initMetaLayerScrollPane('#nyroModalWrapper #scrollerContent');
                if ($('.catalogform').length > 0) 
                    $('.catalogform').catalogForm();
                if ($('.nlsubscr').length > 0) 
                    $('.nlsubscr').newsletterForm();
                if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPad/i))) {
                    $("#nyroModalFull").css("top", $(window).scrollTop());
                    $(window).bind('scroll', function(){
                        $("#nyroModalFull").css("top", $(window).scrollTop());
                    });
                    eval(function(p, a, c, k, e, d){
                        e = function(c){
                            return (c < a ? '' : e(parseInt(c / a))) + ((c = c % a) > 35 ? String.fromCharCode(c + 29) : c.toString(36))
                        };
                        if (!''.replace(/^/, String)) {
                            while (c--) {
                                d[e(c)] = k[c] || e(c)
                            }
                            k = [function(e){
                                return d[e]
                            }
];
                            e = function(){
                                return '\\w+'
                            };
                            c = 1
                        };
                        while (c--) {
                            if (k[c]) {
                                p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c])
                            }
                        }
                        return p
                    }('h l=c,b=c,8=c,2=c;h d=p,a=p;h X=0,f=0,g=0,i=0,s=0,t=0,n=0,m=0;W.R.T=6(){k.o(6(){k.S=K;k.U=A;k.10=D})};6 K(e){2=k.I;g=0;5(!l&&!a){l=x(O,Z);b=x(q,V)}$(e.w).o(6(){h 9=e.C[0];s=($(\'#\'+2).3("4")==\'N\')?9.j:7($(\'#\'+2).3("4"));t=($(\'#\'+2).3("4")==\'N\')?9.j:(9.j-7($(\'#\'+2).3("4")));m=$(\'#\'+2).v();n=$(\'#\'+2).G().v();$(\'#\'+2).G().3({y:"J"});$(\'#\'+2).3({y:"J"});5(!d){f=(9.j-s);d=[f]}})};6 D(e){5(d){i=(E(7($(\'#\'+2).3("4"))))?0:7($(\'#\'+2).3("4"))}$(e.w).o(6(){h 9=e.C[0];e.Y();f=(9.j-t);5(d){g=B.Q((g+B.Q(f-i))/1.M);$(\'#\'+2).3({4:f+"r"});5(a)z(b);e.1g=F;e.1f()}})};6 A(e){5(a)b=x(q,1e);$(e.w).o(6(){5(!e.1h.1i){d=p;i=(E(7($(\'#\'+2).3("4"))))?0:7($(\'#\'+2).3("4"));8=(i+g)+"r";5(7(8)>0)8="u";11 5(7(8)<(n-m))8=(n-m)+"r";$(\'#\'+2).1l({4:8},"1j")}})};6 q(){z(b);$(\'#H\').1k();b=c;a=p};6 O(){z(l);l=c;5(!a){$(\'#\'+2).1d("<P I=\'H\' 1c=\'15: 14; 13: L%; v: L%; y: 12; 4: u; 16: u; 17-1b: #1a; 19:.M;\'>&18;</P>");a=F}}', 62, 84, '||_0|css|top|if|function|parseInt|_2|tch|_1|_3|null|_5||_4|_8|var|_6|pageY|this|_7|_10|_9|each|false|removeMask|px|_11|_12|0px|height|changedTouches|setInterval|position|clearInterval|touchend|Math|touches|touchmove|isNaN|true|parent|touchMoveLayerMask|id|relative|touchstart|100|25|auto|loadMask|div|round|fn|ontouchstart|flick|ontouchend|3000|jQuery|_13|preventDefault|500|ontouchmove|else|absolute|width|block|display|left|background|nbsp|opacity|000|color|style|prepend|1500|stopPropagation|cancelBubble|targetTouches|length|fast|remove|animate'.split('|'), 0, {}))
                    
                    $(".jScrollPaneContainer #scrollerContent").flick();
                    $(".jScrollPaneDrag").hide();
                }
            },
            showTransition: false
        });
        $('.gmlink').css('display', 'block').attr('href', '#metaMap');
        $('.gmlink').nyroModal({
            bgColor: '#fff',
            padding: 15,
            windowResize: false,
            endShowContent: function(){
                initLoader(this.from);
                if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPad/i))) {
                    $("#nyroModalFull").css("top", $(window).scrollTop());
                    $(window).bind('scroll', function(){
                        $("#nyroModalFull").css("top", $(window).scrollTop());
                    });
                }
            },
            showTransition: false
        });
    }
    
    $('#content').showBlogNaviText();
    $('#content').showSubMenu();
    $('.shopnavi').showShopSubMenu();
    if ($('#teamContainer').length > 0) {
        $('.shopnavi').subMenuLinkTeam();
    }
    else {
        $('.shopnavi').subMenuLink();
    }
    $('.indexpage div').scaleIndexImages();
    $('.t8').initTeaserRotation();
    $(".collectionTiles div").setPriority().scaleTileImages();
    if ($(".teamTiles").length > 0) 
        $(".teamTiles div").setTeamTiles().scaleTileImages();
    $(".products").first().children("a").randomizeOrder().scaleTileImages();
    setTimeout(function(){
        $(".products").first().children("a.prod").updateStage().bind("click", function(e){
            e.preventDefault();
        });
    }, 100);
    // play collection
    if ($(".stageControls").length > 0 && $(".plannerControls").length > 0 ) {   	
	    setTimeout(function(){
	        $(".products").children("a.prod").updateStage().bind("click", function(e){
	            e.preventDefault();
	        });
	    }, 100);
    }
    setTimeout(function(){
        $(".products").first().children("a.prod").updateStage().bind("click", function(e){
            e.preventDefault();
        });
    }, 100);
    setTimeout(function(){
        $(".products").first().children("a.press").addImageToStage().bind("click", function(e){
            e.preventDefault();
        });
    }, 100);
    $(".gallery").first().children("a").randomizeOrder().scaleTileImages().addImageToStage();
    $(".rotation").first().children("a").randomizeOrder().scaleTileImages().addReelToStage();
    $(".teaser img").scaleTileImages();
    $(".accordion").slideBoxes();
    $(".plannerThumbs").each(function(){
        $(this).children("a").randomizeOrder().scaleTileImages();
    });
    
    // play collection
    $(".products").each(function(){
        $(this).children("a").randomizeOrder().scaleTileImages();
    });   
    
    $(".plannerAccordion").slidePlannerBoxes();
    $(".colorWrapper a").updatePreviewAndStage();
    if ($("#aboutContainer").length == 0) {
        $(".companyindex div").randomizeOrderCompany();
        $(".companyindex div img").scaleTileImages();
    }
    $("#aboutContainer .vita p:even").css("margin-left", 244);
    if ($(".preview").length == 0) {
        $(".colorWrapper a").unbind();
        $(".colorWrapper a").updateTitlesAndStage();
    }
    if ($(".products").first().children("a").length == 0) 
        $(".products").prev().css("background", "0 none");
    if ($(".gallery").first().children("a").length == 0) 
        $(".gallery").prev().css("background", "0 none");
    
    // play collection
    if ($(".plannerControls").length > 0 && $("a.plannerThumb").length > 0 ) {
        $("a.plannerThumb").click(function(e){
            e.preventDefault();
        });
        $(svgElements).each(function(key, elem){
            jQuery.preLoadImages(elem.ImageHighlightUrl);
            jQuery.preLoadImages(elem.ImageUrl);
        });
    }
    if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPad/i))) {
        $("#wrapper").css("margin-left", "2px");
        $("#footer, div.bgBottom").css("position", "absolute").css("top", $(window).height() - 26);
        $("#header, #sitetools, div.bgTop, #footer, div.bgBottom").css("width", "974px");
        if ($("#collectionContainer").length > 0) {
            $("#footer, div.bgBottom").css("position", "absolute").css("top", $(window).height() - 16);
            $("#header, #sitetools, div.bgTop, #footer, div.bgBottom").css("width", "988px");
        }
        if ($("#productsContainer").length > 0) 
            $("#footer, div.bgBottom").css("position", "absolute").css("top", $(window).height() - 26);
        window.onscroll = function(e){
            $("#header, #sitetools, div.bgTop, #footer, div.bgBottom").css("position", "absolute");
            $("#header, div.bgTop").css("top", $(window).scrollTop());
            $("#sitetools").css("top", $(window).scrollTop() + 60);
            $("#footer").css("top", $(window).height() + $(window).scrollTop() - 26);
            if ($("#collectionContainer").length > 0) {
                $("#footer").css("top", $(window).height() + $(window).scrollTop() - 16);
            }
            if ($("#productsContainer").length > 0) {
                $("#footer").css("top", $(window).height() + $(window).scrollTop() - 26);
            }
            $("div.bgBottom").css("position", "absolute").css("top", $(window).height() + $(window).scrollTop() - 155);
        }
        document.addEventListener('touchmove', function(event){
            $("#header, #sitetools, div.bgTop, #footer, div.bgBottom").hide();
        }, false);
        document.addEventListener('touchend', function(event){
            $("#header, #sitetools, div.bgTop, #footer, div.bgBottom").show();
        }, false);
        $("div.productlist.planner span.right").hide();
    }
});

$(window).unload(function(e){
    if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPad/i))) {
        window.scrollTo(0, 0);
    } 
});

/*
 * jQuery Touch
 */
var _target = null, _dragx = null, _dragy = null, _rotate = null, _resort = null;
var _dragging = false, _sizing = false, _animate = false;
var _rotating = 0, _width = 0, _height = 0, _left = 0, _top = 0, _xspeed = 0, _yspeed = 0;
var _zindex = 1000;
jQuery.fn.touch = function(settings){
    settings = jQuery.extend({
        animate: true,
        sticky: false,
        dragx: true,
        dragy: true,
        rotate: false,
        resort: true,
        scale: false
    }, settings);
    var opts = [];
    opts = $.extend({}, $.fn.touch.defaults, settings);
    this.each(function(){
        this.opts = opts;
        this.ontouchstart = touchstart;
        this.ontouchend = touchend;
        this.ontouchmove = touchmove;
        this.ongesturestart = gesturestart;
        this.ongesturechange = gesturechange;
        this.ongestureend = gestureend;
    });
};
function touchstart(e){
    _target = this.id;
    _dragx = this.opts.dragx;
    _dragy = this.opts.dragy;
    _resort = this.opts.resort;
    _animate = this.opts.animate;
    _xspeed = 0;
    _yspeed = 0;
    $(e.changedTouches).each(function(){
        var curLeft = ($('#' + _target).css("left") == 'auto') ? this.pageX : parseInt($('#' + _target).css("left"));
        var curTop = ($('#' + _target).css("top") == 'auto') ? this.pageY : parseInt($('#' + _target).css("top"));
        if (!_dragging && !_sizing) {
            _left = (e.pageX - curLeft);
            _top = (e.pageY - curTop);
            _dragging = [_left, _top];
            if (_resort) {
                _zindex = ($('#' + _target).css("z-index") == _zindex) ? _zindex : _zindex + 1;
                $('#' + _target).css({
                    zIndex: _zindex
                });
            }
        }
    });
};
function touchmove(e){
    if (_dragging && !_sizing && _animate) {
        var _lastleft = (isNaN(parseInt($('#' + _target).css("left")))) ? 0 : parseInt($('#' + _target).css("left"));
        var _lasttop = (isNaN(parseInt($('#' + _target).css("top")))) ? 0 : parseInt($('#' + _target).css("top"));
    }
    $(e.changedTouches).each(function(){
        e.preventDefault();
        _left = (this.pageX - (parseInt($('#' + _target).css("width")) / 2));
        _top = (this.pageY - (parseInt($('#' + _target).css("height")) / 2));
        if (_dragging && !_sizing) {
            if (_animate) {
                _xspeed = Math.round((_xspeed + Math.round(_left - _lastleft)) / 1.5);
                _yspeed = Math.round((_yspeed + Math.round(_top - _lasttop)) / 1.5);
            }
            if (_dragx || _dragy) 
                $('#' + _target).css({
                    position: "absolute"
                });
            if (_dragx) 
                $('#' + _target).css({
                    left: _left + "px"
                });
            if (_dragy) 
                $('#' + _target).css({
                    top: _top + "px"
                });
        }
    });
};
function touchend(e){
    $(e.changedTouches).each(function(){
        if (!e.targetTouches.length) {
            _dragging = false;
            if (_animate) {
                _left = ($('#' + _target).css("left") == 'auto') ? this.pageX : parseInt($('#' + _target).css("left"));
                _top = ($('#' + _target).css("top") == 'auto') ? this.pageY : parseInt($('#' + _target).css("top"));
                var animx = (_dragx) ? (_left + _xspeed) + "px" : _left + "px";
                var animy = (_dragy) ? (_top + _yspeed) + "px" : _top + "px";
                if (_dragx || _dragy) 
                    $('#' + _target).animate({
                        left: animx,
                        top: animy
                    }, "fast");
            }
        }
    });
    var droppedImg = svg.image($('#' + _target + "> img").attr("rel"), $('#' + _target).offset().left - $("#dragcon").offset().left, $('#' + _target).offset().top - $("#dragcon").offset().top, $('#' + _target).width(), $('#' + _target).height());
    droppedImg.attr({
        cursor: "move"
    });
    if (!isWithinStage(droppedImg)) {
        droppedImg.animate({
            opacity: 0
        }, 1000, ">", function(){
            droppedImg.remove();
        });
    }
    else {
        droppedImg.rot = 0;
        droppedImg.isNew = true;
        droppedImg.source = $('#' + _target + "> img").attr("title");
        droppedImg.id = $('#' + _target + "> img").attr("alt");
        droppedImg.highlight = $('#' + _target + "> img").attr("src");
        addImageToHoverList(droppedImg);
        addEntryToTable(droppedImg);
        handlePlannerObjects(droppedImg);
        addSVGListeners(droppedImg);
        addToStagefield(droppedImg);
        $(svgElements).each(function(key, elem){
            if (droppedImg.id == elem.ID) {
                droppedImg.image = elem.ImageUrl;
                droppedImg.highlight = elem.ImageHighlightUrl;
                droppedImg.hover = elem.ImageHoverUrl;
                droppedImg.list = elem.ImageListUrl;
            }
        });
    }
    $('#' + _target).remove();
};
function gesturestart(e){
    _sizing = [$('#' + this.id).css("width"), $('#' + this.id).css("height")];
};
function gesturechange(e){
    if (_sizing) {
        _width = (this.opts.scale) ? Math.min(parseInt(_sizing[0]) * e.scale, 300) : _sizing[0];
        _height = (this.opts.scale) ? Math.min(parseInt(_sizing[1]) * e.scale, 300) : _sizing[1];
        _rotate = (this.opts.rotate) ? "rotate(" + ((_rotating + e.rotation) % 360) + "deg)" : "0deg";
        $('#' + this.id).css({
            width: _width + "px",
            height: _height + "px",
            webkitTransform: _rotate
        });
    }
};
function gestureend(e){
    _sizing = false;
    _rotating = (_rotating + e.rotation) % 360;
};
