/*
Application Classes

edoras GmbH & Co. KG
Bleichstrasse 94
75173 Pforzheim
http://edoras.de/

Project:		Ritter Sport
Version:		1.4
Last change:    20.06.2010
Author:			Manuel Richarz

Based on jQuery 1.4.2 & jQuery-UI 1.7.2 & JavaScript 1.5

*/
//Extend jQuery with Array to hold ProductScenes
jQuery.ProductScenes = new Array();

/* GUID Generator */
function S4() {
    return ((1 + Math.random()) * 65536 | 0).toString(16).substring(1);
}
function guid() {
    return S4() + S4() + S4() + S4();
}

//Price format
// wert -> Int or Float to format
// ds -> Digits after ,
function tFix(wert,ds){
    var wert=(wert.toFixed)?wert.toFixed(ds):Math.floor(wert)+"."+(Math.pow(10,ds)+Math.round((wert-Math.floor(wert))*Math.pow(10,ds))+"").substr(1,ds);
    return wert.toString().replace(/\./,',');
}

//FadeOut Fix for jQuery
jQuery.fn.fFix = function() {
    return jQuery(this).css("opacity","");
};

/* Array Functions */
// Checks if the given value exists in the array
// needle -> SearchString you want to find
// haystack -> Array to search in
// argStrict -> Must find exact Value and Type in Array to return true
// likeSearch -> With true you can use this Function like a Search
function in_array(needle,haystack,argStrict,likeSearch) {
    var key = '', e = likeSearch || false;
    if (argStrict) {
        for (var key = 0; key < haystack.length; ++key) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (var key = 0; key < haystack.length; ++key) {
            if (haystack[key] == needle) {
                return true;
            }
			if(e && (haystack[key].toLowerCase().indexOf(needle.toLowerCase()) != -1)) {
				return true;
			}
        }
    }
    return false;
}
// Array Remove
function array_remove(arr, start, end) {
    if(arr != null) {
        var temp = arr.slice((end || start)+1 || arr.length);
        arr.length = start < 0 ? arr.length + start : start;
        return arr.push.apply(arr, temp);
    }
    return null;
};

// Class Pattern
// Object can given as Return-Value or as Parameter
jQuery.fn.generateObject = function(domObject) {
    var check = false;
        (domObject = jQuery(this) || jQuery(domObject) || null) && domObject.each(function(){
                //Check if Object already exsist
                var t = jQuery(this);
                if(!jQuery.data(t.get(0),"object")) {
                    var className = t.attr('jsclass') || null;
                    var options = t.attr('jsoptions') || "";
                    //Check if ClassName is defined
                    if(className) {
                        //Generating Object
                        var obj = null;
                        eval('obj = new '+className+'({'+options+'});');
                        if(obj) {
                            if(jQuery.isFunction(obj.draw)) {
                                switch(className) {
                                //Special Constructor
                                case "ProductScene":
                                    obj.draw(jQuery(this).parent(),true);
                                    break;
                                //Default Constructor
                                case "Scenicslider":
                                case "Tooltip":
                                default:
                                    obj.draw();
                                    break;
                                }
                            }
                            check = true;
                        }
                    }
                }
            });
    return check;
};


/*
 * Extending jQuery CSS-Selector
 */
jQuery.extend(jQuery.expr[':'],{
		//Extend the CSS-Selector to select Elements containing "navid" with or without Value
        navid: function(a,i,m) {
            if ((m[3] != null) && (m[3] !== undefined) && (m[3] != "")) { //Check the Content of "navid"-Attribute
        	    if (jQuery(a).attr("navid") === m[3]) {
                    return true;
                }
		    } else { //Check if Attribute exsist
                if (jQuery(a).attr("navid")) {
                    return true;
                }
            }
            return false;
        },
		//Extend the CSS-Selector to select Elements containing "navbinding" with or without Value
		navbinding: function(a,i,m) {
            if ((m[3] != null) && (m[3] !== undefined) && (m[3] != "")) { //Check the Content of "navbinding"-Attribute
        	    if (jQuery(a).attr("navbinding") === m[3]) {
                    return true;
                }
            } else { //Check if Attribute exsist
                if (jQuery(a).attr("navbinding")) {
                    return true;
                }
            }
            return false;
        },
        //Extend the CSS-Selector to select Elements containing "tooltip" with or without Value
        tooltip: function(a,i,m) {
            if ((m[3] != null) && (m[3] !== undefined) && (m[3] != "")) { //Check the Content of "tooltip"-Attribute
        	    if (jQuery(a).attr("tooltip") === m[3]) {
                    return true;
                }
            } else { //Check if Attribute exsist
                if (jQuery(a).attr("tooltip")) {
                    //jQuery.log("Found Tooltip");
                    return true;
                }
            }
            return false;
        },
        //Extend the CSS-Selector to select Elements containing "tooltipcontent" with or without Value
        tooltipcontent: function(a,i,m) {
            if ((m[3] != null) && (m[3] !== undefined) && (m[3] != "")) { //Check the Content of "tooltipcontent"-Attribute
        	    if (jQuery(a).attr("tooltipcontent") === m[3]) {
                    return true;
			    }
            } else { //Check if Attribute exsist
                if (jQuery(a).attr("tooltipcontent")) {
                    return true;
                }
            }
            return false;
        },
        //Extend the CSS-Selector to select Elements containing "start" with or without Value
        start: function(a,i,m) {
            if ((m[3] != null) && (m[3] !== undefined) && (m[3] != "")) { //Check the Content of "start"-Attribute
        	    if (jQuery(a).attr("start") === m[3]) {
                    return true;
                }
            } else { //Check if Attribute exsist
                if (jQuery(a).attr("start")) {
                    return true;
                }
            }
            return false;
        },
        //Extend the CSS-Selector to select Elements are displayed
        display: function(a,i,m) {
            if ((m[3] != null) && (m[3] !== undefined) && (m[3] != "")) { //Check the Content of CSS-Display State
        	    if (jQuery(a).css("display") === m[3]) {
                    return true;
                }
            } else { //Check if Content is Displayed
                if (jQuery(a).css("display") != "none") {
                    return true;
                }
            }
            return false;
        },
        //Extend the CSS-Selector to select Elements containing "jsclass" with or without Value
        jsclass: function(a,i,m) {
            if(a){
                if ((m[3] != null) && (m[3] !== undefined) && (m[3] != "")) { //Check the Content of "jsclass"-Attribute
                    if (jQuery(a).attr("jsclass") === m[3]) {
                        return true;
                    }
                } else { //Check if Attribute exsist
                    if (jQuery(a).attr("jsclass")) {
                        return true;
                    }
                }
            }
            return false;
        },
        //Extend the CSS-Selector to select Elements containing "jsoptions" with or without Value
        jsoptions: function(a,i,m) {
            if ((m[3] != null) && (m[3] !== undefined) && (m[3] != "")) { //Check the Content of "jsoptions"-Attribute
        	    if (jQuery(a).attr("jsoptions") === m[3]) {
                    return true;
                }
            } else { //Check if Attribute exsist
                if (jQuery(a).attr("jsoptions")) {
                    return true;
                }
            }
            return false;
        },
		//Extend the CSS-Selector to select Elements containing "postloadpath" with or without Value
        postloadpath: function(a,i,m) {
            if ((m[3] != null) && (m[3] !== undefined) && (m[3] != "")) { //Check the Content of "postloadpath"-Attribute
        	    if (jQuery(a).attr("postloadpath") === m[3]) {
                    return true;
                }
            } else { //Check if Attribute exsist
                if (jQuery(a).attr("postloadpath")) {
                    return true;
                }
            }
            return false;
        },
        //Extend the CSS-Selector to select Elements containing "products" with or without Value
        products: function(a,i,m) {
            if ((m[3] != null) && (m[3] !== undefined) && (m[3] != "")) { //Check the Content of "products"-Attribute
        	    if (jQuery(a).attr("products") === m[3]) {
                    return true;
                }
            } else { //Check if Attribute exsist
                if (jQuery(a).attr("products")) {
                    return true;
                }
            }
            return false;
        },
        //Extend the CSS-Selector to select Elements containing "rel" with or without Value
        rel: function(a,i,m) {
            if ((m[3] != null) && (m[3] !== undefined) && (m[3] != "")) { //Check the Content of "rel"-Attribute
        	    if (jQuery(a).attr("rel") === m[3]) {
                    return true;
                }
            } else { //Check if Attribute exsist
                if (jQuery(a).attr("rel")) {
                    return true;
                }
            }
            return false;
        }
});
//Write Debug Output
jQuery.log = function(text) {
if(false) {
    if((window.console !== undefined && !jQuery.browser.msie)) {        	 
		console.log(text);
	} else {
            if(jQuery("body #ie-debug-log").length > 0) {
                jQuery("body #ie-debug-log ul").append("<li>"+text+"</li>");
            } else {
                jQuery("body").append("<div style=\"overflow:auto; position:absolute; top:10px; left:10px; border:1px solid black; background:#fff; width:300px; height:500px;\" id=\"ie-debug-log\"><p><strong>IE Debug Console</strong></p><ul></ul></div>");
                jQuery("body #ie-debug-log ul").append("<li>"+text+"</li>");
            }
        }
}
};
jQuery.group = function(text,collapsed){
    collapsed = collapsed || false;
    if((window.console !== undefined)) {
        collapsed ? console.groupCollapsed(text) : console.group(text);
    } else {
        jQuery.log(text);
    }
};
jQuery.groupEnd = function() {
    (window.console !== undefined) && console.groupEnd();
};


/*
 *	Scenicslider
 */
Scenicslider = function(options) {
	this.settings = jQuery.extend({
		debug: false, //Write Debug Output?
		object: jQuery(".slider-wrapper"), //Define Targetobject to build the Scenicslider
		width: "940px", //Width of Scenicslider
		height: "378px", //Height of Scenicslider
		scenicScrollerSelector: "div:first", //Define CSS-Selector to select the Scroller
		sceneSelektor: ".slider-page", //Define CSS-Selector to select a Scene
		sceneContentSelector: ".slider-content", //Define CSS-Selector to select Scene-Content
        scenePageSelector: ".slider-page", //Define CSS-Class for ScenePage
		scenewidth: "848px", //Width of Scene
		sceneoffsetwidth: "861px", //Width of Scene (incl. Padding, Border and Margin)
		sceneheight: "378px", //Height of Scene
		sceneoffsetheight: "378px", //Height of Scene (incl. Padding, Border and Margin)
        drawSceneShadows: true, //Draw SceneShadows?
        displayScrollButton: true, //Draw ScrollButton?
		scrollButtonWidth: "22px", //Define the Width of ScrollButton
		scrollButtonHeight: "27px", //Define the Height of ScrollButton
		scrollButtonImage: "images/scenicslider_scroll_button.png", //Define the image for ScrollButton
		scrollButtonTop: null, //Define the Top-Position of ScrollButton
		scrollButtonBottom: "34px", //Define the Bottom-Position of ScrollButton
		scrollButtonLeft: null, //Define the Left-Position of ScrollButton
		scrollButtonRight: "0px", //Define the Right-Position of ScrollButton
		scrollSpeed: 500, //Define the scrollspeed in milliseconds.
		scrollButtonFadeSpeed: 100, //Define the speed to fadein/fadeout the ScrollButton
		onLeftScroll: null, //function(e) {/*CODE*/} - Define Event-Function if Scenicslider scrolls.
		beforeMoveOutScene: null,
		afterMoveInScene: null,
        autoSwitch: false, //Define if the Scenicslider switch automaticly
        autoSwitchSpeed: 5000 //Define the Speed of autoSwitch
	},options);
    this.uniqueid = guid(); //Generating a unique ID to mark anything of this Scenicsliders.
	this.object = null; //Hold the DOM-Object of this Scenicslider
	this.stages = []; //Hold Scenes of this Scenicslider.
};
var S = Scenicslider.prototype;
//Write Debug Output
S.log = function(text) {
	if (false) {
		(this.settings.debug) && (window.console !== undefined) && console.log(text);
	}
};
//Draw the Scenicslider
S.draw = function() {
	var tobj = this.settings.object;
	if(tobj != null) {
		this.log("Draw Scenicslider");
		//Remove Scenicslider if exsist
		this.remove();
		//Create Hidden-Storage
		jQuery("body").append("<div id=\"hiddenstorage-"+this.uniqueid+"\" style=\"display:none;\"></div>");
		//Find and get Stages
		var t = this, scs = tobj.find(this.settings.sceneSelektor).length;
        if(scs <= 2) {
            this.log("Extending Scenicslider Stages to perform a clean output");
            tobj.find(this.settings.sceneSelektor).each(function(){
                jQuery(this).clone().appendTo(jQuery(this).parent());
                (scs <= 1) && jQuery(this).clone().appendTo(jQuery(this).parent());
            });
        }
		tobj.find(this.settings.sceneSelektor).each(function() {
            t.log("Found Scene");
			//Add Scene to Pool
			var index = t.addScene(
				new Scene({
					debug:t.settings.debug,
					object:tobj.find(t.settings.scenicScrollerSelector),
					width:t.settings.scenewidth,
					height:t.settings.sceneheight,
					contentSelector:t.settings.sceneContentSelector,
                    sceneClass:t.settings.scenePageSelector,
                    drawShadows:t.settings.drawSceneShadows,
					content:jQuery(this).find(t.settings.sceneContentSelector).children("*"),
                    navbinding:jQuery(this).attr("navbinding")
				})
			);
			//Check Navbinding
			var navbinding = jQuery(this).attr("navbinding");
			if(navbinding) {
				//Get binded NavigationItem
				var navitem = jQuery(":navid("+navbinding+")");
				//Set ScrollTo-Function to all matched Elements
				navitem.each(function(){
					jQuery(this).click(function(){
						t.scrollToScene(index);
						return false;
					});				  
				});
			}
			//Make sure that this Scene is not drawed
			t.stages[index].remove();
			t.log("Has added Scene ["+index+"] to Scenicslider");
		});
		//Make sure that Scenicslider-Content is empty
		var scroller = tobj.find(this.settings.scenicScrollerSelector);
		scroller.empty();
		//Draw first and second Scene
		(this.stages[0]) && this.stages[0].draw();
		(this.stages[1]) && this.stages[1].draw();
		//Set the global Object for Scenicslider
		this.object = tobj;
        this.log("Reference Object to DOM");
		//Bind this Class-Object to HTML-Object, so we can find the Object easier if we need
		jQuery.data(this.object.get(0),"object",this);
		
		//Draw the ScollButton
		this.DrawScrollButton();
		//Set Width
		this.Width();
		//Set Height
		this.Height();
		
		//Adjust Scroller
		scroller.css("left","0px"); //Reset the Scroller-Position
		//Set Scroller-Width for 2 Scenes
		var width = parseInt(this.settings.sceneoffsetwidth.replace(/px/,""));
		scroller.css("width",(width*2)+"px");
		//Set Scroller Event onLeftScroll
		(jQuery.isFunction(this.settings.onLeftScroll)) && jQuery(this.object).bind("onLeftScroll", { "object": this, "element": this.object }, this.settings.onLeftScroll);
		jQuery(this.object).bind("onLeftScroll", { "object": this, "element": this.object }, function(e){
			var object = e.data.object;
			object.log("Event-Trigger: Left scroll of Scenicslider");
			object.nextScene();
		});
		//Set MoveIn and Out Events
        this.log("Set Events");
		(jQuery.isFunction(this.settings.beforeMoveOutScene)) && jQuery(this.object).bind("beforeMoveOutScene", { "object": this, "element": this.object }, this.settings.beforeMoveOutScene);
		(jQuery.isFunction(this.settings.afterMoveInScene)) && jQuery(this.object).bind("afterMoveInScene", { "object": this, "element": this.object }, this.settings.afterMoveInScene);
        //Start AutoSwitch
        this.autoSwitchRun();
		this.log("Finished");
		return true;
	}
	this.log("Can't draw the Scenicslider! No Target-Object defined!");
	return false;
};
//Remove the Scenicslider
S.remove = function() {
	if(this.Drawed()) {
		this.log("Remove Scenicslider");
		jQuery("#hiddenstorage-"+this.uniqueid).remove();
		this.object.remove();
		this.object = null;
		return true;
	}
	return false;
};
//Set or get AutoSwitch Status of Scenicslider
S.autoSwitch = function(value) {
    this.settings.autoSwitch = value || this.settings.autoSwitch;
    if(value === false) { this.settings.autoSwitch = false; }
    return this.settings.autoSwitch;
};
//Set or get AutoSwitchSpeed of Scenicslider
S.autoSwitchSpeed = function(speed) {
    this.settings.autoSwitchSpeed = speed || this.settings.autoSwitchSpeed;
    return this.settings.autoSwitchSpeed;
};
//Run AutoSwitch Scenicslider
S.autoSwitchRun = function() {
    var t = this;
    (t.settings.autoSwitch) && setTimeout(function(){t.nextScene();t.autoSwitchRun()},t.settings.autoSwitchSpeed);
};
//Get Index of current Scene
S.CurrentSceneIndex = function() {
	this.log("Get current SceneIndex...");
	if(this.Drawed()) {
		var curscene = this.object.find(this.settings.sceneSelektor+":first"), curindex = null;
		var cursceneid = curscene.attr("id");
        jQuery.each(this.stages,function(i){
            if(this.settings.id == cursceneid) {
                curindex = parseInt(i);
                return false;
            }
        });
		this.log("Current Scene: "+curindex);
		return curindex;
	}
	return null;
};
S.CurrentScene = function() {
	this.log("Get current Scene...");
	if(this.Drawed()) { return this.stages[this.CurrentSceneIndex()]; }
	return null;
};
//Move to next Scene
S.nextScene = function(callback,btnfadeout,btnfadein) {
	if(this.Drawed()) {
		callback = callback;
		btnfadeouta = btnfadeout || true;
		if(btnfadeout == false) btnfadeouta = false;
		btnfadeina = btnfadein || true;
		if(btnfadein == false) btnfadeina = false;
		//FadeOut ScrollButton
		var scrollbtn = this.object.children(".scrollbutton");
		if((btnfadeouta) && (scrollbtn.length > 0)) {
			jQuery.browser.msie ? scrollbtn.hide() : scrollbtn.fadeOut(this.settings.scrollButtonFadeSpeed);
		}
		//First get current Scene-Index
		curindex = this.CurrentSceneIndex();
		//Find Scroller
		var scroller = this.object.find(this.settings.scenicScrollerSelector);
		//Set Scroller-Width for 3 Scenes
		var width = parseInt(this.settings.sceneoffsetwidth.replace(/px/,""));
		scroller.css("width",(width*3)+"px");
		//Draw third Scene (Next Scene or First Scene if end of Stages reached)
		var tmp = this.stages[(curindex+1)] || null;
                this.log(this.stages);
		if(tmp != null) {
			var stage3 = this.stages[(curindex+2)] || this.stages[0];
		} else {
			var stage3 = this.stages[1] || this.stages[0];
            var tmp = this.stages[0];
		}
		//Draw new Stage if not drawed
		(!stage3.Drawed()) && stage3.draw();
        //Draw Content of Scene if AjaxContent
        if(stage3.settings.ajaxaddress != null) {
            this.log("Draw Stage3 Ajax-Content");
            stage3.Content();
        }
        this.log("Adding Stage to Scroller");
		//Add Stage to Scroller
		scroller.append(stage3.object);
		if(stage3 != null) {
            this.log("Fire afterMoveInScene Event");
            this.object.trigger("afterMoveInScene",[stage3,tmp]);
            this.log("FadeIn Sub-Navigation");
            //FadeIn Sub-Navigation
            (jQuery.browser.msie) ? tmp.object.find("ul.nav-sub").show() : tmp.object.find("ul.nav-sub").fadeIn(1000);
            //Generate Child-Objects
            this.log("Generate Child-Objects of Scene");
            var stage3classes = stage3.object.find(":jsclass");
            this.log(stage3classes);
            (!stage3classes.generateObject()) && (stage3classes.get(0)) && (prodscene = jQuery.data(stage3classes.get(0),"object")) && (jQuery.isFunction(prodscene.View)) && prodscene.View(null,true);
		}
		//Scroll left
		var t = this;
        t.log("Scroll the Scenicslider");
		scroller.animate({"left": "-"+this.settings.sceneoffsetwidth},this.settings.scrollSpeed,function() {
            t.log("Finished Scrolling");
		    //Remove First Stage and correct Left-Value
		    var cursceneobj = t.CurrentScene();
		    if(cursceneobj != null) {
			    t.object.trigger("beforeMoveOutScene",[cursceneobj]);
                //FadeOut Sub-Navigation
                jQuery.browser.msie ? cursceneobj.object.find("ul.nav-sub").hide() : cursceneobj.object.find("ul.nav-sub").fadeOut(500);
		    }
		    jQuery("body #hiddenstorage-"+t.uniqueid).append(cursceneobj.object);
		    scroller.css("left","0px");
            //Set Navigation Highlight for stage3
            var navbinding = t.CurrentScene().settings.navbinding;
            if(navbinding != null) {
                (navbinding == 0) && jQuery(":navid a").removeClass("active");
                var navlink = jQuery(":navid("+navbinding+") a");
                navlink.parent().parent().children("li").children("a").removeClass("active");
                navlink.addClass("active");
            }
		    //FadeIn ScrollButton
		    if((btnfadeina) && (scrollbtn.length > 0)) {
			    jQuery.browser.msie ? scrollbtn.show() : scrollbtn.fadeIn(t.settings.scrollButtonFadeSpeed);
		    }
		    //Fire Callback-Function if exsist
		    (jQuery.isFunction(callback)) && callback();	
	    });
	}
};
//Scroll to [index] Scene
S.scrollToScene = function(index) {
	if(this.Drawed()) {
		if(index != null) {
			//Get current index
			var currentsceneindex = this.CurrentSceneIndex();
			//We are at this scene?
			if(currentsceneindex == index) {
				return true;	
			}
			//Scroll to nextScene
			var t = this;
			this.nextScene(function(){
				t.scrollToScene(index);
			},false,false);
		}
	}
	return false;
};
//Add Scene to Scenicslider
S.addScene = function(scene,redraw) {
	this.log("Adding Scene to Scenicslider");
	redraw = redraw || false;
	var index = this.stages.push(scene)-1;
    this.log(this.stages);
	//Redraw
	if(redraw) { this.draw(); }
	return index;
};
//Remove Scene from Scenicslider
S.removeScene = function(value) {
	if(this.stages[value] != null) {
		this.log("Remove Scene ["+value+"] from Scenicslider");
		this.stages.splice(value,1);
		//Redraw
		this.draw();
		return true;
	} else {
		var index = null;
        jQuery.each(this.stages,function(i){
	        if(this.Id() == value) {
                index = i;
                return false;
	        }
        });
		if(index != null) {
			this.log("Remove Scene ["+index+"] from Scenicslider");
			this.stages[index].splice(index,1);
			//Redraw
			this.draw();
			return true;
		}
	}
	return false;
};
//Remove all Stages
S.clearStages = function() {
	this.log("Clear all Stages from Scenicslider");
	this.stages = new Array();
	//Redraw
	this.draw();
};
//Check if Scenicslider is drawed
S.Drawed = function() {
	if(this.object != null) {
		return true;	
	}
	return false;
};
//Set or get the Width of the Scenicslider
S.Width = function(value) {
	this.log("Set or get Width of Scenicslider");
	this.settings.width = value || this.settings.width;
	(this.Drawed()) && this.object.css("width",this.settings.width);
	return this.settings.width;
};
//Set or get the Height of the Scenicslider
S.Height = function(value) {
	this.log("Set or get Height of Scenicslider");
	this.settings.height = value || this.settings.height;
	(this.Drawed()) && this.object.css("height",this.settings.height);
	return this.settings.height;
};
//Set or get the ScrollButtonImage of the Scenicslider
S.ScrollButtonImage = function(value) {
	this.log("Set or get ScrollButtonImage of Scenicslider");
	this.settings.scrollButtonImage = value || this.settings.scrollButtonImage;
	(this.Drawed()) && this.DrawScrollButton();
	return this.settings.scrollButtonImage;
};
//Set or get the ScrollButtonWidth of the Scenicslider
S.ScrollButtonWidth = function(value) {
	this.log("Set or get ScrollButtonWidth of Scenicslider");
	this.settings.scrollButtonWidth = value || this.settings.scrollButtonWidth;
	(this.Drawed()) && this.DrawScrollButton();
	return this.settings.scrollButtonWidth;
};
//Set or get the ScrollButtonHeight of the Scenicslider
S.ScrollButtonHeight = function(value) {
	this.log("Set or get ScrollButtonHeight of Scenicslider");
	this.settings.scrollButtonHeight = value || this.settings.scrollButtonHeight;
	(this.Drawed()) && this.DrawScrollButton();
	return this.settings.scrollButtonHeight;
};
//Set or get the ScrollButtonTop of the Scenicslider
S.ScrollButtonTop = function(value) {
	this.log("Set or get ScrollButtonTop of Scenicslider");
	this.settings.scrollButtonTop = value || this.settings.scrollButtonTop;
	(this.Drawed()) && this.DrawScrollButton();
	return this.settings.scrollButtonTop;
};
//Set or get the ScrollButtonBottom of the Scenicslider
S.ScrollButtonBottom = function(value) {
	this.log("Set or get ScrollButtonBottom of Scenicslider");
	this.settings.scrollButtonBottom = value || this.settings.scrollButtonBottom;
	(this.Drawed()) && this.DrawScrollButton();
	return this.settings.scrollButtonBottom;
};
//Set or get the ScrollButtonLeft of the Scenicslider
S.ScrollButtonLeft = function(value) {
	this.log("Set or get ScrollButtonLeft of Scenicslider");
	this.settings.scrollButtonLeft = value || this.settings.scrollButtonLeft;
	(this.Drawed()) && this.DrawScrollButton();
	return this.settings.scrollButtonLeft;
};
//Set or get the ScrollButtonRight of the Scenicslider
S.ScrollButtonRight = function(value) {
	this.log("Set or get ScrollButtonRight of Scenicslider");
	this.settings.scrollButtonRight = value || this.settings.scrollButtonRight;
	(this.Drawed()) && this.DrawScrollButton();
	return this.settings.scrollButtonRight;
};
S.DrawScrollButton = function() {
    if((this.Drawed()) && (this.settings.displayScrollButton)) {
		this.log("Draw ScrollButton in Scenicslider");
		//Remove if exsist
		this.object.children(".scrollbutton").remove();
		//Draw the ScrollButton
		this.object.append("<div class=\"scrollbutton\"></div>");
		var sbtn = this.object.children(".scrollbutton");
		//Adjust the Button
		sbtn.css({
			"width":this.settings.scrollButtonWidth,
			"height":this.settings.scrollButtonHeight,
			"background-image":"url("+this.settings.scrollButtonImage+")",
			"top":this.settings.scrollButtonTop,
			"left":this.settings.scrollButtonLeft
		});
		(this.settings.scrollButtonBottom != null) && sbtn.css({"bottom":this.settings.scrollButtonBottom,"top":""});
		(this.settings.scrollButtonRight != null) && sbtn.css({"right":this.settings.scrollButtonRight,"left":""});
		//Set ScrollButton click-Event
		t = this;
		sbtn.click(function() {	t.object.trigger("onLeftScroll"); });
		return true;
	}
	return false;
}


/*
 * Scene - Struct Class
 */
Scene = function(options) {
	this.settings = jQuery.extend({
		id: "scene-"+guid(),
  		debug: false, //Write Debug Output?
		width: "848px", //Width of Scene
		height: "378px", //Height of Scene
		object: null, //Targetobject to build the Scene
		contentSelector: ".slider-content", //Define CSS-Selector to select SceneContent
        sceneClass: ".slider-page", //Define CSS-Class of ScenePage
		content: null, //Content of Scene
		ajaxaddress: null, //Ajaxaddress to get content for this Scene
		ajaxdata: null ,//Ajax Parameter
        drawShadows: true, //Draw Shadows?
        navbinding: null //Define the Navbinding of this Scene
	},options);
	this.object = null; //Hold the DOM-Object of this Scene
};
var SC = Scene.prototype;
//Write Debug Output
SC.log = function(text) {
    (this.settings.debug) && (window.console !== undefined) && console.log(text);
};
//Draw the Scene
SC.draw = function() {
	var tobj = this.settings.object;
	if(tobj != null) {
		this.log("Draw Scene");
		//Remove Scene if exsist
		this.remove();
		//Draw Scene
        if(this.settings.drawShadows) {
            tobj.append("<div id=\""+this.settings.id+"\" class=\""+this.settings.sceneClass.replace(/\./,"")+"\">"+
                        "<div class=\""+this.settings.contentSelector.replace(/\./,"")+"\"></div>"+
			            "<div class=\"slider-shadow-right\"><hr class=\"hide\" \/></div>"+
			            "<div class=\"slider-shadow-bottom\"><hr class=\"hide\" \/></div>"+
                        "</div>");
        } else {
            tobj.append("<div id=\""+this.settings.id+"\" class=\""+this.settings.sceneClass.replace(/\./,"")+"\">"+
                        "<div class=\""+this.settings.contentSelector.replace(/\./,"")+"\"></div>"+
                        "</div>");
        }
		//Set Object
		this.object = tobj.children("#"+this.settings.id);
		//Bind this Class-Object to HTML-Object, so we can find the Object easier if we need
		jQuery.data(this.object.get(0),"object",this);
		
		//Set the Width of the Scene
		this.Width();
		//Set the Height of the Scene
		this.Height();
		
		//Set the Content of Scene
        (this.settings.ajaxaddress == null) && this.Content();
        
        this.log("Scene drawed");
		return true;
	}
	this.log("Can't draw Scene! No Target-Object defined.");
	return false;
};
//Remove the Scene
SC.remove = function() {
	if(this.Drawed()) {
		this.log("Remove Scene");
		this.object.remove();
		this.object = null;
		return true;
	}
	return false;
};
//Check if Scene is drawed
SC.Drawed = function() {
	if(this.object != null) {
		return true;	
	}
	return false;
};
//Get the current Id
SC.Id = function() {
	return this.settings.id;
};
//Set or get the Width of the Scene
SC.Width = function(value) {
	this.log("Set or get Width of Scene");
	this.settings.width = value || this.settings.width;
	(this.Drawed()) && this.object.css("width",this.settings.width);
	return this.settings.width;
};
//Set or get the Height of the Scene
SC.Height = function(value) {
	this.log("Set or get Height of Scene");
	this.settings.height = value || this.settings.height;
	(this.Drawed()) && this.object.css("height",this.settings.height);
	return this.settings.height;
};
//Get or set the Content of Scene
SC.Content = function(object,classobject,ajaxfirst) {
	var ajax = ajaxfirst || false;
	var classa = classobject || false;
	object = object || this.settings.content;
	if(this.Drawed()) {
		if(object != null) {
			this.log("Set Scene Content");
			//Find ContentContainer
			var container = this.object.find(this.settings.contentSelector);
			//Ajax-Source
			if((ajax) && (this.settings.ajaxaddress != null)) { //Overwrite Parameter-Source
				classa = false;
				container.load(this.settings.ajaxaddress, this.settings.ajaxdata); // Load Fix HTML
                                //TODO: Load Ajax json with calling the Script for the Scene Content
				return container.html();
			}
			if((!ajax) && (object == null) && (this.settings.ajaxaddress != null)) { //Not overwriting Parameter-Source
				classa = false;
				container.load(this.settings.ajaxaddress, this.settings.ajaxdata); //Load Fix HTML
                                //TODO: Load Ajax json with calling the Script for the Scene Content
				return container.html();
			}
			//Parameter Source
			if(classa) { //Content is a Class-Object
				//Remove Class-Object if drawed
				object.remove();
				//Clear Content if exsist
				container.empty();
				//Draw Class-Object
				object.draw(container);
			} else { //Content is a string or HTML-Code or jQuery-Object
				this.log("Draw direkt HTML-Content");
				//Clear Content if exsist
				container.empty();
				//Draw direkt HTML-Content
				container.append(object);
			}
            this.log("Finished Content");
			return container.html();
		}
		this.log("No Object defined!");
		return false;
	}
	return false;
};


/*
 *  Ritter Sport Tooltip
 */
Tooltip = function(options) {
    this.settings = jQuery.extend({
        id: null, //ID of the Tooltip (of the Product)
        url: "", //Ajax URL to recieve Tooltip-Content
        fadeIn: 175, //Time in milliseconds
        fadeOut: 175, //Time in milliseconds
        object: null, //Product Object
        debug: false,
        bottom: false //Arrow on Bottom of Tooltip
    },options);
    this.object = null; //Hold the DOM-Object of this Tooltip
    this.tpool = jQuery("div#tootippool");
    if(!this.tpool.length > 0) { //Make sure TooltipPool exsists
        jQuery("body").append('<div id="tootippool"></div>');
        this.tpool = jQuery("div#tootippool");
    }
    this.area = {x:0,y:0,x1:0,y1:0};
    this.inside = true;
};
var T = Tooltip.prototype;
//Write Debug Output
T.log = function(text) {
    (this.settings.debug) && (window.console !== undefined) && console.log(text);
};
//Draw Tooltip
T.draw = function(object) {
    var t = this;
    var s = t.settings;
    s.object = jQuery(s.object) || jQuery(object);
    if(s.id && s.object) {
        //Hide Title and Alt-Tags
        t.hideTitle();
        //Search for exsiting Tooltip
        t.object = t.tpool.find(':tooltipcontent('+s.id+')');
        //Create Tooltip if not exsist
        if(!t.object.length > 0) {
            t.object = null;
            t.log("Draw Tooltip: "+s.id);
            t.tpool.append('<div tooltipcontent="'+s.id+'" style="display:none; z-index:9999;"><div class="loader"></div></div>');
            t.object = t.tpool.find(':tooltipcontent('+s.id+')');
        }
        //Reference Tooltip to DOM
        jQuery.data(s.object.get(0),"tooltip",t);
        //Set Events
        t.setEvents();
        return true;
    }
    return false;
};
T.setEvents = function() {
    var t = this;
    t.unsetEvents();
    t.log("Set Tooltip Events: "+t.settings.id);
    //Set mouseEnter on Product
    t.settings.object.mouseenter(function(){
        if(t.object.css('display') == 'block') { return; }
        var o = jQuery(this);
        var offset = o.offset();
        //If Loader exsists, so remove Loader and load the Tooltip
        if(t.object.children('.loader').length > 0) {
            t.log("Load Content of Tooltip: "+t.settings.id);
            jQuery.ajax({type:"GET", url:t.settings.url,async:true,
                success: function(c){
                    t.object.fadeOut(t.settings.fadeOut,function(){
                        //Add Height and Width of the TargetObject to find the MiddlePoint
                        offset.top+= (o.height()/2);
                        offset.left+= (o.width()/2);
                        t.object.empty();
                        t.log("Tooltip ["+t.settings.id+"] loaded.");
                        t.object.append(jQuery(c).find('div:tooltipcontent').html());
                        t.object.find('.close').bind('click', {t:t}, function(e){
                        	e.data.t.hide();
                        	setTimeout(function(){ e.data.t.object.remove(); }, e.data.t.setting.fadeOut);
                        });
                        //Adjust Arrow if it is not in middle
                        (t.settings.bottom) && t.object.find('div.tooltip-arrow').addClass('bottom');
                        //Add Height and Width of the Tooltip itself to find the MiddlePoint with the Arrow
                        offset.top-= (t.object.height()/2);
                        if(t.settings.bottom) {
                            offset.top-= (t.object.height()/2)-(t.object.height()/10)-28;
                        }
                        offset.left+= 20;
                        t.object.css({"position":"absolute","left":offset.left+"px","top":offset.top+"px"});
                    });
                }
            });
        }
        //Add Height and Width of the Tooltip itself to find the MiddlePoint with the Arrow
        //offset.top-= (t.object.height()/2);
        //if(t.settings.bottom) {
        //    offset.top-= (t.object.height()/2)+(t.object.height()/10)-28;
        //}
        //offset.left+= 20;
        //t.object.css({"position":"absolute","left":offset.left+"px","top":offset.top+"px"});
        t.object.css({"position":"absolute"});
        t.show();
    });
};
T.updateArea = function() {
    var t = this;
    if(t.settings.object) {
        var offset = t.settings.object.offset();
        var height = t.settings.object.height();
        var width = t.settings.object.width();
        t.area.y = offset.top;
        t.area.x = offset.left;
        t.area.y1 = offset.top+height;
        t.area.x1 = offset.left+width;
    }
};
T.inArea = function(x,y) {
    var a = this.area;
    if((y && x) && (y >= a.y) && (y <= a.y1) && (x >= a.x) && (x <= a.x1)) { return true; }
    return false;
};
T.show = function() {
    var t = this;
    //Get Area from Product
    t.updateArea();
    t.tpool.children('div').stop().hide();
    t.log("Show Tooltip: "+t.settings.id);
    (t.object) && (!jQuery.browser.msie) && t.object.stop().fadeIn(t.settings.fadeIn,function(){jQuery(this).fFix();});
    (t.object) && (jQuery.browser.msie) && t.object.show();
    //Leave Event
    jQuery("body").mousemove(function(e){
        var x = e.pageX, y = e.pageY;
        if(!t.inArea(x,y)) {
            t.inside = false;
            setTimeout(function(){
                (!t.inside) && t.hide() && jQuery("body").unbind('mousemove');
            },200);
        } else {
            t.inside = true;
        }
    });
    return true;
};
T.hide = function() {
    var t = this;
    t.log("Hide Tooltip: "+t.settings.id);
    (t.object) && (!jQuery.browser.msie) && t.object.stop().fadeOut(t.settings.fadeOut,function(){jQuery(this).fFix();});
    (t.object) && (jQuery.browser.msie) && t.object.hide();
    return true;
};
T.unsetEvents = function() {
    var t = this;
    t.log("Unset Tooltip Events: "+t.settings.id);
    (t.settings.object) && t.settings.object.unbind('mouseenter');
};
T.hideTitle = function() {
    var o = this.settings.object;
    (o) && o.find('a,img').each(function(){
        var a = jQuery(this);
        var title = a.attr('title'), alt = a.attr('alt');
        //(a.get(0)) && jQuery.data(a.get(0),"oldtitle",title);
        //(a.get(0)) && jQuery.data(a.get(0),"oldalt",alt);
        a.attr('title','').attr('alt','');
    });
};

/*
 * ProductScene
 */
ProductScene = function(options) {
	this.settings = jQuery.extend({
		id: "productscene-"+guid(),
		debug: false, //Debugausgabe aktivieren/deaktivieren
		object:	null, //Definiert das Element welchem diese ProductScene hinzugefuegt werden soll
		productSelector: ".product-1", //Definiert den CSS-Selektor zum selektieren der Produkte
        productsceneSelector: ".productscene", //Definiert den CSS-Selektor zum selektieren der Produktscene
		visible: true, //Gibt an ob die ProductScene gleich zu Anfang sichtbar sein soll oder nicht
        drawNavigation: true, //Gibt an ob eine Navigation gebaut werden soll
		height: "100%", //Definiert die Hoehe des Tooltips
		width: "100%", //Definiert die Breite des Tooltips
		view: "scroller", //Definiert die Ansicht
        zoom: true, //Gibt an ob der Scroller das aktive Product aufzoomt oder nicht
		filter: null, //Definiert den Gruppennamen nach welchem gefiltert werden soll. Standardmaessig werden alle angezeigt.
		filterAsSearch: false, //Definiert ob die Filtermethode auch als Produktsuche dienen soll
		imageGridView: "images/icon_switch_grid_grey.png", //Definiert den Bildpfad fuer den ViewSwitch des Grid-View-Modi
		imageScrollerView: "images/icon_switch_slider_grey.png", //Definiert den Bildpfad fuer den ViewSwitch des Scroller-View-Modi
		products: new Array(), //Hold all Products of this ProductScene
        navigationvisible: false, //Define if the Navigation will display on start or not
        preselectedNavPoint: null, //If this is defined, the preselected Navigation Point will be click-triggered after draw.
        viewGlobal: true, //Define if this ProductScene will switch the View with all other ProductScenes
        onViewSwitch: function() {} //Define the Event Function for onViewSwitch
	},options);
	this.object = null; //Hold the ProductScene HTML-Object
    this.globalId = null;
	if(this.settings.object != null) {
		//Search for Products in given Object
		var content = this.settings.object.find(this.settings.productSelector) || null;
		//Parse Products
		var t = this;
		content.each(function() {
			t.settings.products.push(getProductFromHtml(jQuery(this)));	  
		});
	}
};
var PS = ProductScene.prototype;
//Write Debug Output
PS.log = function(text) {
    (this.settings.debug) && jQuery.log(text);
};
//Draw the ProductScene
PS.draw = function(object,update) {
	var tobj = object || this.settings.object;
	update = update || false;
	if(tobj != null) {
		this.log("Draw ProductScene: "+this.settings.id);
		//Remove ProductScene if exsist
		(!update) && this.remove();
		
		//Correct the Id if update
		if(update) { this.settings.id = tobj.find(this.settings.productsceneSelector).attr("id"); }
		
		//Search for Products in given Object
		if(object != null) {
			var content = tobj.find(this.settings.productSelector) || null;
			//Parse Products
			var t = this;
			content.each(function() {
				t.log("Adding Product to "+t.settings.id+": "+jQuery(this).attr("id"));
				t.settings.products.push(getProductFromHtml(jQuery(this),update));	  
			});
		}
		
		//Clear Target-Object
		(!update) && jQuery(tobj).empty();
		//Draw ProductScene
		(!update) && jQuery(tobj).append("<div id=\""+this.settings.id+"\" class=\""+this.settings.productsceneSelector.replace(/./,"")+"\">"+
                                            "<div class=\"productlist\">"+
                                            "</div>"+
                                            "</div>");
		
		//Set global Object
		if(update) {
			this.object = tobj.find(this.settings.productsceneSelector);
		} else {
			this.object = jQuery("#"+this.settings.id);
		}
		
		//Reference Object to DOM, so we can find the Object easier if we need
		jQuery.data(this.object.get(0),"object",this);

        //Set Events
        (jQuery.isFunction(this.settings.onViewSwitch)) && jQuery(this.object).bind("onViewSwitch", { "object": this, "element": this.object }, this.settings.onViewSwitch);
				
		//Adjust the ProductScene
		//Set the Width
		this.Width();
		//Set the Height
		this.Height();
		//Set View
		this.View(this.settings.view,true,update); //This will also draw the Products with the right Template for current View
		//Draw Navigation
        (this.settings.drawNavigation) && this.drawNavigation(update);
		//Set the Visible-State
		this.Visible();
        if(!this.settings.navigationvisible && this.settings.drawNavigation) {
            this.log("Hide Sub-Nav");
            this.object.children("ul.nav-sub").hide();
        }
        //Trigger Preselected Navigation Point
        this.TriggerNavigation(this.settings.preselectedNavPoint);
        this.log("ProductScene finished");
        //Add to ProductScene Pool if Global View Switch
        if(this.settings.viewGlobal) {
            if(this.globalId == null){
                this.log("Add ProductScene to Global Array");
                this.globalId = (jQuery.ProductScenes.push(this)-1);
            }
        }
		return true;
	}
	this.log("Can't draw ProductScene! No Target-Object defined.");
	return false;
};
//Remove the ProductScene if drawed
PS.remove = function() {
	if(this.Drawed()) {
		this.log("Remove ProductScene");
		this.object.remove();
		this.object = null;
		return true;
	}
	return false;
};
//Draw Navigation of ProductScene
PS.drawNavigation = function(update) {
	update = update || false;
	if(this.Drawed() && (this.settings.drawNavigation)) {
		if(!update) {
			this.log("Draw Navigation of ProductScene");
			//Make sure that Navigation is not drawed
			this.removeNavigation();
			//Draw Navigation
			this.object.prepend("<ul class=\"nav-sub\"></ul>");
		}
		//Get Subnavigation Object
		var subnav = this.object.children("ul.nav-sub");
		
		if(!update) {
			//Find all Groups of Products
			var groups = new Array();
            for (var i = 0; i < this.settings.products.length; ++i) {
				var product = this.settings.products[i];
                for (var a = 0; a < product.settings.groups.length; ++a) {
					if(!in_array(product.settings.groups[a],groups)) {
						groups.push(product.settings.groups[a]);
					}
				}
			}
			//Sort Groups
			groups.sort();
			//Draw Navigation Points
            for (var i = 0; i < groups.length; ++i) {
				var escgroup = escape(groups[i].toLowerCase());
				var group = groups[i];
				subnav.append("<li navid=\""+escgroup+"\"><a href=\"#"+escgroup+"\" title=\""+group+"\">"+group+"</a></li>");
			}
		}
		
		//Set onClick-Event to Navigationpoints
		var th = this;
		subnav.children("li").each(function() {
			var a = jQuery(this).children("a");
			th.log("Set Filter-Event to Navigationpoint: "+a.text());
			//Make sure that Click-Event is not set
			a.unbind("click");
			//Set new Filter for ProductScene on click
			a.click(function(){
				//Remove Tooltips
				jQuery("div#tootippool").empty();
	 			//Get ProductScene ClassObject
				var t = jQuery.data(jQuery(this).parent().parent().parent().get(0),"object");
                jQuery(this).parent().parent().children("li").children("a").removeClass("active");
                jQuery(this).addClass("active");
				t.Filter(jQuery(this).text());
				return false;
			});
		});
		
		return true;
	}
	return false;
};
//Remove Navigation of ProductScene
PS.removeNavigation = function() {
	if(this.Drawed()) {
		this.log("Remove Navigation of ProductScene");
		this.object.children("ul.nav-sub").remove();
		return true;
	}
	return false;
};
//Draw ViewSwitch
PS.drawViewSwitch = function(update) {
	update = update || false;
	this.log("Draw ViewSwitch. Update: "+update);
	if(this.Drawed()) {
		//Remove if exsist
		(!update) && this.object.children("a.changeView").remove();
		switch(this.settings.view.toLowerCase()) {
			case"scroller":
			    this.log("for GridView");
			    //Draw ViewSwitch
				(!update) && this.object.append("<a class=\"changeView\" href=\"#gridview\" title=\"Ansicht wechseln\">"+
                                               "<img src=\""+this.settings.imageGridView+"\" alt=\"Ansicht wechseln\" title=\"Ansicht wechseln\" />"+
                                               "</a>");
				//Make sure that onClick-Event is not set and set onClick-Event to ViewSwitch
				this.object.children("a.changeView").unbind("click").click(function(){
				    jQuery.log("Change View to grid");
				    jQuery("div#tootippool").empty();
					var obj = jQuery.data(jQuery(this).parent().get(0),"object");
					obj.View("grid");
					return false;
				});
			break;
			case"grid":
			default:
			    this.log("for ScrollerView");
			    //Draw ViewSwitch
				(!update) && this.object.append("<a class=\"changeView\" href=\"#scrollerview\" title=\"Ansicht wechseln\">"+
                                               "<img src=\""+this.settings.imageScrollerView+"\" alt=\"Ansicht wechseln\" title=\"Ansicht wechseln\" />"+
                                               "</a>");
				//Make sure that onClick-Event is not set and set onClick-Event to ViewSwitch
				this.object.children("a.changeView").unbind("click").click(function(){
				    jQuery.log("Change View to grid");
				    jQuery("div#tootippool").empty();
					var obj = jQuery.data(jQuery(this).parent().get(0),"object");
					obj.View("scroller");
					return false;
				});
			break;
		}
		return true;
	}
	return false;
};
//Remove ViewSwitch
PS.removeViewSwitch = function(update) {
	if(this.Drawed()) {
		this.log("Remove ViewSwitch of ProductScene");
		this.object.children("ul.nav-sub").remove();
		return true;
	}
	return false;
};
//Check if ProductScene is drawed
PS.Drawed = function() {
	if(this.object != null) {
		return true;
	}
	return false;
};
//Get the current Id
PS.Id = function() {
	return this.settings.id;
};
//Set or get the current Width
PS.Width = function(value) {
	this.log("Set Width of ProductScene");
	this.settings.width = value || this.settings.width;
	(this.Drawed()) && this.object.css("width",this.settings.width);
	return this.settings.width;
};
//Set or get the current Height
PS.Height = function(value) {
	this.log("Set Height of ProductScene");
	this.settings.height = value || this.settings.height;
	(this.Drawed()) && this.object.css("height",this.settings.width);
	return this.settings.height;
};
//Set or get the current Visible
PS.Visible = function(value) {
	this.log("Set Visible-State of ProductScene");
	this.settings.visible = value || this.settings.visible;
	if(this.Drawed()) {
		//Hide or Show if required
		if((this.object.css("display") == "block") && (this.settings.visible == false)) {
			this.object.hide();	
		}
		if((this.object.css("display") == "none") && (this.settings.visible == true)) {
			this.object.show();	
		}
	}
	return this.settings.visible;
};
//Set or get the current View
PS.View = function(value,mustdraw,update) {
    var t = this;
	t.log("Set View-Mode of ProductScene");
	t.log("Current Filter: "+t.settings.filter);
	mustdraw = mustdraw || false;
	update = update || false;
	var obj = t.object;
	var oldview = t.settings.view.toLowerCase();
	t.settings.view = value || t.settings.view;
	//Make sure that viewmode is in lowercase
	t.settings.view = t.settings.view.toLowerCase();
    t.log("Current View: "+t.settings.view);
	//Only redraw if View has changed or must redraw! If not update! 
	if(((!update) || (mustdraw)) && (t.Drawed()) && ((oldview != t.settings.view) || (mustdraw))) {
	    t.log("Redraw View");
		//Make sure that Productlist is empty and Producsscene is free of any modifing CSS-Classes
		var plist = obj.children(".productlist,.productlist-2,.productlist-3,.productlist-scroller,.productlist-2-scroller,.productlist-3-scroller").empty();
		//Remove Scroller if exsist
		obj.children(".scrollbar").remove();
		//Draw the new View-Mode
		switch(t.settings.view) {
			case"scroller":
				t.log("Draw Products in Scroller-View");
				//Prepare ProductScene for Scroller
                (plist.hasClass("productlist-3")) && plist.attr("class","productlist-3-scroller");
                (plist.hasClass("productlist-2")) && plist.attr("class","productlist-2-scroller");
                (plist.hasClass("productlist")) && plist.attr("class","productlist-scroller");
				plist.append("<div class=\"productlist-scroller-content clearfix\"></div>");
				obj.append("<div class=\"scrollbar clearfix\" style=\"display:none;\"><div class=\"leftscroll\"></div><div class=\"scrollcontainer\"><div></div></div><div class=\"rightscroll\"></div></div>");
				plist = plist.children("div.productlist-scroller-content");
				//Draw Products in ProductScene
                for (var i = 0; i < t.settings.products.length; ++i) {
					var product = t.settings.products[i];
					//Filter Products if Filter is set
					if((t.settings.filter != null) && (t.settings.filter != "")) {
						//Check if this Product is in filtered Group
						if(in_array(t.settings.filter,product.settings.groups,false,t.settings.filterAsSearch)) {
							product.draw(plist);
							t.log("Drawed: "+product.Id());
						}
					} else {
						product.draw(plist);
						t.log("Drawed: "+product.Id());
					}
				}
                var prodSelector = t.settings.productSelector, zoom = t.settings.zoom;
                var QprodSelector = prodSelector.replace(/\./,"");
				t.log("The following calculations are really strange! You don't need to understand this! I don't understand this, too.");
                //Get Start Product
                startProduct = plist.find(":start(1):first");
                if(startProduct.length > 0) {
                    t.log("Start Product:");
                    t.log(startProduct);
                }
                //Count Products
                var products = plist.children(prodSelector);
				var count = products.length;
                t.log("Product Count: "+count);
				var scroller = obj.children(".scrollbar");
				var scrollbar = scroller.children(".scrollcontainer").children("div");
				//Minimal count of Products to display the Scroller is 4.
				if(count >= 4) {
					var prodwidth = products.first().width()+(parseInt(products.first().css("padding-left").replace(/px/,""))*2);
					this.log("Product Width (with padding): "+prodwidth+"px");
					//Set start- or first-Product active
                    startProduct.length > 0 ? startProduct.attr("class",QprodSelector+"-active") : products.first().attr("class",QprodSelector+"-active");
					//Setup Scroller
					var activeproduct = plist.children(prodSelector+"-active");
					var aprodwidth = activeproduct.width()+(parseInt(activeproduct.css("padding-left").replace(/px/,""))*2);
					//this.log("Active Product Width (with padding): "+aprodwidth+"px");
					var gesprodwidth = ((count*prodwidth)-prodwidth)+aprodwidth;
					//this.log("Complete Width of Productlist: "+gesprodwidth+"px");
					plist.css({width:gesprodwidth+"px"});
					scroller.show();
					//this.log("Scrollbar Width: "+scrollbar.width()+"px");
					var scrollcntwidth = scrollbar.parent().width();
					//this.log("-Scrollcontainer Width: "+scrollcntwidth+"px");
					//this.log("-------- Difference: "+(scrollcntwidth-scrollbar.width())+"px");
					//this.log("Grid Stepping Width: "+((scrollcntwidth-scrollbar.width())/(count-1))+"px");
					var gridscrollbar = parseInt(((scrollcntwidth-scrollbar.width())/(count-1)).toString().split(".")[0]);
					//this.log("Scrollbar Grid-Width: "+gridscrollbar+"px");
					//Adjust Productlist
					var halfplistcnt = plist.parent().width()/2;
					//this.log("Half Productlist Width: "+halfplistcnt+"px");
					var start = halfplistcnt-(aprodwidth/2);
					//this.log("Start Left-Position: "+start+"px");
					var end = (plist.width()*(-1))+halfplistcnt+(aprodwidth/2);
					//this.log("End Left-Position: "+end+"px");
					plist.css("left",start+"px");
					//Make Scrollbar dragable
					scrollbar.draggable({	grid: [gridscrollbar, 10],
                                                    containment: 'parent',
                                                    start:function(e,u) {
                                                    var c = plist.children(prodSelector+"-active");
                                                    (c.get(0)) && jQuery.data(c.get(0),"tooltip") && jQuery.data(c.get(0),"tooltip").unsetEvents();
                                                    if(zoom){
                                                        c.animate({
                                                            "padding-left": "9px",
                                                            "padding-right": "9px",
                                                            "padding-top": "71px",
                                                            "width": "167px"
                                                            }, 100,function() { jQuery(this).attr("class",QprodSelector); });
                                                    } else {
                                                        c.attr("class",QprodSelector);
                                                    }
                                                },
                                                drag:function(e,u) {
                                                    var left = parseInt(jQuery(this).css("left").replace(/px/,""));
                                                    var curindex = (left/gridscrollbar);
                                                    var centercurindex = ((curindex)*prodwidth);
                                                    //console.log(start+" - "+centercurindex+" = "+(start-centercurindex)+"px");
                                                    plist.css("left",(start-centercurindex)+"px");
                                                },
                                                stop:function(e,u) {
                                                    var left = parseInt(jQuery(this).css("left").replace(/px/,""));
                                                    var curindex = (left/gridscrollbar);
                                                    //console.log("Current Index: "+curindex);
                                                    var c = plist.children(prodSelector+":eq("+curindex+")");
                                                    (c.get(0)) && jQuery.data(c.get(0),"tooltip") && jQuery.data(c.get(0),"tooltip").setEvents();
                                                    if(zoom) {
                                                        c.animate({
                                                            "width": "210px",
                                                            "padding-left": "8px",
                                                            "padding-right": "8px",
                                                            "padding-top": "57px"
                                                            }, 200,function() { jQuery(this).attr("class",QprodSelector+"-active"); });
                                                    } else {
                                                        c.attr("class",QprodSelector+"-active");
                                                    }
                                                }
                                            });
                                        //Scroll Overlay
                                        function clickAble(t,le) {
                                            var scbtnd = jQuery(t).get(0);
                                            //Abort if ScrollButton is locked
                                            if(jQuery.data(jQuery(scbtnd).get(0),"lock")) { return; }
                                            //Lock the ScrollButton for next scroll
                                            jQuery.data(jQuery(scbtnd).get(0),"lock",true);
                                            //Detecting side to move to
                                            var side = true;
                                            if(jQuery(t).hasClass("rightscroll") || jQuery(t).hasClass("scrolloverlayright")) { side = false; }
                                            //Catching information
                                            var st = jQuery(t).parent().parent().find(".scrollcontainer").children("div");
                                            var left = parseInt(st.css("left").replace(/px/,"")) || 0;
                                            var curindex = (left/gridscrollbar);
                                            if (side) {
                                                curindex = curindex-1;
                                            } else {
                                                curindex = curindex+1;
                                            }
                                            //console.log("current index: "+curindex);
                                            if((curindex >= 0) && (curindex < count)) {
                                                var centercurindex = ((curindex)*prodwidth);
                                                //console.log("Current center index: "+centercurindex);
                                                //Deactivate current active Product
                                                var oldactproduct = plist.children(prodSelector+"-active");
                                                if(zoom) {
                                                    oldactproduct.animate({
                                                        "padding-left": "9px",
                                                        "padding-right": "9px",
                                                        "padding-top": "71px",
                                                        "width": "167px" }, 100,function() {
                                                            jQuery(this).attr("class",QprodSelector);
                                                            (jQuery(this).get(0)) && jQuery.data(jQuery(this).get(0),"tooltip") && jQuery.data(jQuery(this).get(0),"tooltip").unsetEvents();
                                                        });
                                                } else {
                                                    oldactproduct.attr("class",QprodSelector);
                                                    (oldactproduct.get(0)) && jQuery.data(oldactproduct.get(0),"tooltip") && jQuery.data(oldactproduct.get(0),"tooltip").unsetEvents();
                                                }
                                                //Move to Position
                                                plist.animate({"left":(start-centercurindex)+"px"},200);
                                                //Move Scrollbar to Position
                                                side ? scrollbar.animate({"left":(left-gridscrollbar)+"px"},200) : scrollbar.animate({"left":(left+gridscrollbar)+"px"},200);
                                                //Remove Click Events from all Products
                                                plist.children("div").unbind("click");
                                                //Set current Product active
                                                //console.log("Current Index: "+curindex);
                                                var currentactproduct = plist.children(":eq("+curindex+")");
                                                if(zoom) {
                                                    currentactproduct.animate({
                                                        "width": "210px",
                                                        "padding-left": "8px",
                                                        "padding-right": "8px",
                                                        "padding-top": "57px"
                                                        }, 200,function() {
                                                            jQuery(this).attr("class",QprodSelector+"-active");
                                                            (currentactproduct.get(0)) && jQuery.data(currentactproduct.get(0),"tooltip") && jQuery.data(currentactproduct.get(0),"tooltip").setEvents();
                                                        });
                                                } else {
                                                    currentactproduct.attr("class",QprodSelector+"-active");
                                                    (currentactproduct.get(0)) && jQuery.data(currentactproduct.get(0),"tooltip") && jQuery.data(currentactproduct.get(0),"tooltip").setEvents();
                                                }
                                                //Set Click Event to Präfix and Sufix Product of current active Product
                                                (curindex < (count-1)) && currentactproduct.next().click(function() { obj.find(".rightscroll").click(); return false; });
                                                (curindex > 0) && currentactproduct.prev().click(function() { obj.find(".leftscroll").click(); return false; });
                                                (curindex < (count-2)) && currentactproduct.next().next().click(function() { obj.find(".rightscroll").dblclick(); return false; });
                                                (curindex > 1) && currentactproduct.prev().prev().click(function() { obj.find(".leftscroll").dblclick(); return false; });
                                                //Release ScrollButton
                                                setTimeout(function(){
                                                    jQuery.data(jQuery(scbtnd).get(0),"lock",false);
                                                    (le) && (le > 1) && clickAble(t,(le-1));
                                                },300);
                                            } else {
                                                //Release ScrollButton
                                                jQuery.data(jQuery(scbtnd).get(0),"lock",false);
                                            }
                                        }
                                        //Make ScrollButtons Clickable
                                        obj.find(".leftscroll, .rightscroll").click(function(){ clickAble(this); return false; }).dblclick(function(){ clickAble(this,2); return false; });
                                        var curactive = plist.children(prodSelector+"-active");
                                        var curindex = curactive.index();
                                        //Set Click Event to Präfix and Sufix Product of current active Product
                                        (curindex < (count-1)) && curactive.next().click(function() { obj.find(".rightscroll").click(); return false; });
                                        (curindex > 0) && curactive.prev().click(function() { obj.find(".leftscroll").click(); return false; });
                                        (curindex < (count-2)) && curactive.next().next().click(function() { obj.find(".rightscroll").dblclick(); return false; });
                                        (curindex > 1) && curactive.prev().prev().click(function() { obj.find(".leftscroll").dblclick(); return false; });
                                        //Scroll to active Product
                                        this.log("Active Index: "+curindex);
                                        var centercurindex = ((curindex)*prodwidth);
                                        (zoom) && curactive.css({"width": "210px","padding-left": "8px","padding-right": "8px","padding-top": "57px"});
                                        //Move to Position
                                        plist.css({"left":(start-centercurindex)+"px","position":"absolute"});
                                        var scrollerleft = (gridscrollbar*curindex);
                                        scrollbar.css({"left":scrollerleft+"px"});
				} else { //So, we don't need the Scroller -> remove it to have lesser HTML-Code for Performance
					scroller.remove();
				}
			break;
			case"grid":
			default:
				this.log("Draw Products in Grid-View");
    	        (plist.hasClass("productlist-3-scroller")) && plist.attr("class","productlist-3");
                (plist.hasClass("productlist-2-scroller")) && plist.attr("class","productlist-2");
                (plist.hasClass("productlist-scroller")) && plist.attr("class","productlist");
				//Draw Products in ProductScene
                for (var i = 0; i < this.settings.products.length; ++i) {
					var product = this.settings.products[i];
					//Filter Products if Filter is set
					if((this.settings.filter != null) && (this.settings.filter != "")) {
						//Check if this Product is in filtered Group
						if(in_array(this.settings.filter,product.settings.groups,false,this.settings.filterAsSearch)) {
							product.draw(plist);
							this.log("Drawed: "+product.Id());
						}
					} else {
						product.draw(plist);
						this.log("Drawed: "+product.Id());
					}
					var prodSelector = this.settings.productSelector;
					var count = plist.children(prodSelector).length;
                    this.log("Product Count: "+count);
					//Switch Grid Size
					plist.attr("class","productlist");
					(count > 8) && plist.attr("class","productlist-2");
					//Kunstkataloge
					(prodSelector == ".product-4") && plist.attr("class","productlist-3");
				}
			break;
		}
        this.object.trigger("onViewSwitch");
        if(this.settings.viewGlobal) {
            this.log(jQuery.ProductScenes);
            for (var i = 0; i < jQuery.ProductScenes.length; ++i) {
                this.log("Change View for ProductScene");
                jQuery.ProductScenes[i].View(this.settings.view,false,false);
            }
        }
        //Generate Tooltips
        var t = this;
        this.object.find(":jsclass('Tooltip')").each(function(){
            var to = jQuery(this);
            var toobj = jQuery.data(to.get(0),"tooltip") || null;
            if(!toobj) {
                eval("toobj = new Tooltip({"+to.attr('jsoptions')+"});");
                toobj.draw();
            }
            if((toobj) && (t.settings.view == "scroller")) {
                if(to.is(t.settings.productSelector+'-active')) {
                    toobj.setEvents();
                } else {
                    toobj.unsetEvents();
                }
            }
            if((toobj) && (t.settings.view == "grid")) {
                toobj.setEvents();
            }
        });
	}
	//Draw ViewSwitch
	this.drawViewSwitch();
	return this.settings.view;
};
//Set or get the current Filter of ProductScene
PS.Filter = function(value) {
	var oldfilter = this.settings.filter;
	this.settings.filter = value || this.settings.filter;
	//Redraw if filter has changed
	(oldfilter != this.settings.filter) && this.log("Filter changed to: "+this.settings.filter);
	(oldfilter != this.settings.filter) && this.View(this.settings.view.toLowerCase(),true);
    //Set Active Product Tooltip Events
	this.log("Set Active Prod Events");
	var ctmp = this.object.children(".productlist,.productlist-2,.productlist-3,.productlist-scroller,.productlist-2-scroller,.productlist-3-scroller").find("div.productlist-scroller-content "+this.settings.productSelector+"-active");
	this.log(ctmp);
	(ctmp.get(0)) && jQuery.data(ctmp.get(0),"tooltip") && jQuery.data(ctmp.get(0),"tooltip").setEvents();
	return this.settings.filter;
};
//Add a Product to this ProductScene
PS.addProduct = function(value) {
	var index = this.settings.products.push(value)-1;
	//Redraw
	this.draw();
	return index;
};
//Clear all Products in this ProductScene
PS.clearProducts = function() {
	this.settings.products = new Array();
	//Redraw
	this.draw();
	return true;
};
//Remove a Product from this ProductScene (by Index or by Id)
PS.removeProduct = function(value) {
	if(this.settings.products[value] != null) {
		this.settings.products.splice(value,1);
		//Redraw
		this.draw();
		return true;
	} else {
		var index = null;
		//Search for ID
        for (var i = 0; i < this.settings.products.length; ++i) {
			if(this.settings.products[i].Id() == value) {
				index = i;
				break;
			}
		}
		//Remove index of ID if found
		if(index != null) {
			this.settings.products[index].splice(index,1);
			//Redraw
			this.draw();
			return true;
		}
	}
	return false;
};
//Trigger a preselected Navigation Point
PS.TriggerNavigation = function(value) {
    if(value) {
        this.log("Preselected Navigation Point");
        this.object.find("ul.nav-sub li a").each(function() {
            var item = jQuery(this);
            if(item.text() == value) {
                item.click();
                return;
            }
        });
    }
};


/*
 * Product - Struct Class
 */
Product = function(options) {
	this.settings = jQuery.extend({
		id: "product-"+guid(),
		name: "",
		groups: new Array(),
		price: "0,00",
		shortdesc: "",
		longdesc: "",
		rel: "",
		images: new Array(),
        jsclass: null,
        jsoptions: null,
        prodSelector: "product-1",
        link: "",
        startProduct: false
	},options);
	this.object = null; //Hold the drawed Product
};
var P = Product.prototype;
//Draw the Product
P.draw = function(object,tpl) {
	object = object || null;
	tpl = tpl || "<div id=\"{idlong}\" {jsclass} {jsoptions} {start} class=\""+this.settings.prodSelector+"\"><a {rel} href=\"{link}\" title=\"{name}\">{image}</a><div class=\"product-info\"><span class=\"product-article\">{name}</span><br /><span class=\"product-price\">{price}</span></div></div>"; //This is the default Template if no Template is given!
	if(object != null) {	
		//Remove if exsist
		this.remove();
		//Parse Tpl
		var id = object.parents(".productscene").attr("id")+"-"+this.Id().replace(/.*[^-]+-(.*)/,"$1");
		var content = tpl.replace(/{idlong}/g,id).replace(/{id}/g,this.Id().replace(/.*[^-]+-(.*)/,"$1"));
		//Draw Image if exsist
		if(this.settings.images.length > 0) {
				(this.settings.images[0].PostloadPath()) &&	this.settings.images[0].Src(this.settings.images[0].PostloadPath());
				content = content.replace(/{image}/g,"<img src=\""+this.settings.images[0].Src()+"\" alt=\"{name}\" title=\"{name}\" />");
		}
		content = content.replace(/{name}/g,this.Name());
		(this.Start()) ? content = content.replace(/{start}/g,"start=\"1\"") : content = content.replace(/{start}/g,"");
        (this.jsClass()) ? content = content.replace(/{jsclass}/g,'jsclass="'+this.jsClass()+'"') : content = content.replace(/{jsclass}/g,"");
        (this.jsOptions()) ? content = content.replace(/{jsoptions}/g,'jsoptions="'+this.jsOptions()+'"') : content = content.replace(/{jsoptions}/g,"");
		content = content.replace(/{price}/g,this.Price());
        content = content.replace(/{link}/g,this.Link());
        content = content.replace(/{rel}/g,"rel=\""+this.Rel()+"\"");
		content = content.replace(/{longdesc}/g,this.LongDesc());
		content = content.replace(/{shortdesc}/g,this.ShortDesc());
		//Draw Product
		object.append(content);
		//Set global Object
		this.object = object.children("#"+id);
		//Bind ClassObject to Element
		jQuery.data(this.object.get(0),"object",this);
		return true;
	}
	return false;
};
//Remove the Product if drawed
P.remove = function() {
	if(this.Drawed()) {
		this.object.remove();
		this.object == null;
		return true;
	}
	return false;
};
//Check if Product is drawed
P.Drawed = function() {
	if(this.object != null) {
		return true;
	}
	return false;
};
//Get the Product ID
P.Id = function() {
	return this.settings.id;
};
//Set or get the Product Name
P.Name = function(value) {
	this.settings.name = value || this.settings.name;
	return this.settings.name;
};
//Set or get the Product Rel
P.Rel = function(value) {
	this.settings.rel = value || this.settings.rel;
	return this.settings.rel;
};
//Set or get the Product Link
P.Link = function(value) {
	this.settings.link = value || this.settings.link;
	return this.settings.link;
};
//Set or get the Product Price
P.Price = function(value) {
	this.settings.price = value || this.settings.price;
	return this.settings.price;
};
//Set or get the Product Short Description
P.ShortDesc = function(value) {
	this.settings.shortdesc = value || this.settings.shortdesc;
	return this.settings.shortdesc;
};
//Set or get the Product Long Description
P.LongDesc = function(value) {
	this.settings.longdesc = value || this.settings.longdesc;
	return this.settings.longdesc;
};
//Set or get the Product Startattribute
P.Start = function(value) {
    if(value != null) {
	this.settings.startProduct = value || false;
    }
    return this.settings.startProduct;
};
//Set or get the Product jsClass
P.jsClass = function(value) {
    this.settings.jsclass = value || this.settings.jsclass;
    return this.settings.jsclass;
};
//Set or get the Product jsOptions
P.jsOptions = function(value) {
    this.settings.jsoptions = value || this.settings.jsoptions;
    return this.settings.jsoptions;
};
//Add a Group to this Product
P.addGroup = function(groupname) {
	return this.settings.groups.push(groupname)-1;
};
//Clear all Groups in this Product
P.clearGroups = function() {
	this.settings.groups = new Array();
	return true;
};
//Remove a Group from this Product (by Index or by Groupname)
P.removeGroup = function(value) {
	if(this.settings.groups[value] != null) {
		this.settings.groups.splice(value,1);
		return true;
	} else {
		var index = null;
		//Search for Groupname
                for (var i = 0; i < this.settings.groups.length; ++i) {
			if(this.settings.groups[i] == value) {
				index = i;
				break;
			}
		}
		//Remove index of Groupname if found
		if(index != null) {
			this.settings.groups[index].splice(index,1);
			return true;
		}
	}
	return false;
};
//Add a ProductImage to this Product
P.addImage = function(image) {
	return this.settings.images.push(image)-1;
};
//Clear all ProductImage in this Product
P.clearImages = function() {
	this.settings.images = new Array();
	return true;
};
//Remove a ProductImage from this Product (by Index or by Src)
P.removeImage = function(value) {
	if(this.settings.images[value] != null) {
		this.settings.images.splice(value,1);
		return true;
	} else {
		var index = null;
		//Search for Src
                for (var i = 0; i < this.settings.images.length; ++i) {
			if(this.settings.images[i].Src() == value) {
				index = i;
				break;
			}
		}
		//Remove index of Src if found
		if(index != null) {
			this.settings.images[index].splice(index,1);
			return true;
		}
	}
	return false;
};
//Build a Product-Object from HTML-Code
function getProductFromHtml(jqueryobject,update) {
	update = update || false;
	if(jqueryobject != null) {
		var obj = jQuery(jqueryobject);
		var id = obj.attr("id").replace(/.*[^-]+-(.*)/,"$1");
		var name = obj.find("div span.product-article").html();
		var rel = obj.find("a").attr('rel') || "";
		var shortdesc = obj.find("p.shortdesc").html();
		var longdesc = obj.find("p.longdesc").html();
		var price = obj.find("div span.product-price").text().replace(/ /g,"").replace(/&euro;/g,"").replace(/EUR/g,"");
		var prodSelector = obj.attr("class");
		var jsclass = obj.attr("jsclass");
		var jsoptions = obj.attr("jsoptions");
		var startProduct = obj.attr("start");
		var link = obj.find("a:first").attr("href");
		//Search for Groups
		var groups = new Array();
		obj.find("ul.product-groups li").each(function() {
			var t = jQuery(this);
			groups.push(t.text());
		});
		//Search for Pics
		var images = new Array();
		obj.find("img").each(function(){
			var t = jQuery(this);
			var src = t.attr("src");
			var postload = t.attr("postloadpath");
			if(t.hasClass("thumb")) {
				images.push(new ProductImage({src:src,type:"thumb",postload:postload}));
			} else {
				images.push(new ProductImage({src:src,type:"image",postload:postload}));
			}
		});
		//Return the Product-Object
		var prod = new Product({
			id: id,
			name: name,
			shortdesc: shortdesc,
			longdesc: longdesc,
			price: price,
			images: images,
			groups: groups,
			rel: rel,
            jsclass: jsclass,
            jsoptions: jsoptions,
            prodSelector: prodSelector,
            link: link,
            startProduct: startProduct
		});
		if(update) { prod.object = jqueryobject; }
		return prod;
	}
	return false;
}


/*
 * ProductImage - Struct Class
 */
ProductImage = function(options) {
	this.settings = jQuery.extend({
		src: "", // Path
		type: "image", // or "thumb"
		postload: "" //PostloadPath
	},options);
	//Make sure that Type is lowerCase
	this.settings.type = this.settings.type.toLowerCase();
	//Make sure that type is one of the two possible types
	if((this.settings.type != "image") && (this.settings.type != "thumb")) {
		this.settings.type = "image";	
	}
	//Why not using "this.Type();" ?! Because at this Position in Code this Method doesn't exsist! Browser will throw an Exception!
};
var PI = ProductImage.prototype;
//Set or get the current Image Source
PI.Src = function (value) {
	this.settings.src = value || this.settings.src;
	return this.settings.src;
};
//Set or get the postload Image Source
PI.PostloadPath = function (value) {
	this.settings.postload = value || this.settings.postload;
	return this.settings.postload;
};
//Set or get the current Image Type
PI.Type = function (value) {
	//Make sure that Type is lowerCase
	this.settings.type = value.toLowerCase() || this.settings.type;
	//Make sure that type is one of the two possible types
	if((this.settings.type != "image") && (this.settings.type != "thumb")) {
		this.settings.type = "image";	
	}
	return this.settings.type;
};

function ProductScroller(options) {
    this.settings = jQuery.extend({
            object: null,
            width:893
        },options);
    this.object = null;
};
ProductScroller.prototype.draw = function(object) {
    var t = object || this.settings.object || null;
    if(t != null) {
        var width = this.settings.width || 893;
        var count = t.children("div").children("div").children("div").children("div").length;
        t.find("a.slider-button-left, a.slider-button-right").show();
        //Set CSS Properties to Container
        t.children("div").children("div").css({overflow:"hidden",position:"relative",width:"100%",height:"100%"}).children("div").css({position:"absolute",width:(width*count)+"px"});
        //Set Click-Events to Buttons
        t.children("a.slider-button-left, a.slider-button-right").click(function(){
                var btn = jQuery(this);
                //Abort if Button is locked
                if(jQuery.data(btn.get(0),"lock") == true) {
                    return false;
                }
                var cnt = btn.parent().children("div").children("div").children("div");
                jQuery.data(btn.get(0),"lock",true); //Lock Button
                if(btn.hasClass("slider-button-right")) {
                    //Scroll to next Container
                    cnt.animate({left:"-"+width+"px"},1000,function() {
						//Remove and append first Container
						var firstcnt = cnt.children("div:first");
						cnt.append(firstcnt);
						//Return to Position 0
						cnt.animate({left:"0px"},0);
					});
                } else {
                    //Remove and prepend last Container
                    var lastcnt = cnt.children("div:last");
                    cnt.prepend(lastcnt);
                    //Jump to second Container
                    cnt.animate({left:"-"+width+"px"},0);
                    //Scroll to first Container
                    cnt.animate({left:"0px"},1000);
                }
                jQuery.data(btn.get(0),"lock",false); //Release Button
                return false;
            });
    }
    return false;
};

/*
 * Simple - Class
 */
Simple = function(options) {
	this.settings = jQuery.extend({
        basePrice: 0.0,
        digits:2
	},options);
	this.shoppingcart = jQuery('table.product-page-shoppingcart');    
    this.rows = this.shoppingcart.find('tr:not(.total)');
    this.gespricelbl = this.shoppingcart.find('tr.total span.product-price');
    this.gescounter = this.shoppingcart.find('tr.total input.product-quantity');
    this.submitbtn = this.shoppingcart.find('tr.total input.product-submit');
};
var SI = Simple.prototype;
//Get Totals
SI.getTotals = function() {
    var totalprice = 0, totalcount = 0, t = this;
    //Get totals
    t.rows.each(function(){
        var r = jQuery(this), counter = r.find('input.product-quantity'), price = parseFloat(r.find('span.product-price').text().replace('€','').replace('&euro;','').replace(' ','').replace('&nbsp;','').replace(',','.')) || 0;
        var count = counter.val() ? parseInt(counter.val()) : 0;
        totalcount+=count;
        totalprice+=price*count;
    });
    //Write totals
    t.gescounter.val(totalcount);
    t.gespricelbl.html(tFix(totalprice, t.settings.digits)+'&nbsp;&euro;');
};
//Draw Simple Product
SI.draw = function() {
    var t = this, s = t.settings;
    t.rows.each(function(){
        var r = jQuery(this), decinc = r.find('input.dec, input.inc'), counter = r.find('input.product-quantity');
       
        //De-/Increment Event 
        decinc.click(function(){
    	    var count = parseInt(counter.val());
            (jQuery(this).hasClass('inc')) && counter.val(count+1);
            (jQuery(this).hasClass('dec')) && (count > 0) && counter.val(count-1);
            //calculate result count
            count = parseInt(counter.val());
            t.getTotals();
            return false;
        });
        //Catch ENTER
        counter.keydown(function(e) {
            if(e.keyCode == 13) { t.submitbtn.click(); return false; }
        });
        //Counter Key-Event
        counter.keyup(function(){
            t.getTotals();
            return false;
        }); 
        //Make sure that Count in Counter >= 0
        counter.blur(function() {
            var count = parseInt(counter.val());
            !(count >= 0) && counter.val('0');
            counter.keyup();
        });
    });
};

/*
 * Configurable - Class
 */
Configurable = function(options) {
	this.settings = jQuery.extend({
	    data: {},
	    tasteselector: ".colors",
	    color2selector: ".colors",
	    sizeselector: ".dress-size",
	    genderselector: ".gender",
	    tastepreselect: "input[type=hidden].colorhidden",
	    color2preselect: "input[type=hidden].color2hidden",
	    sizepreselect: "input[type=hidden].sizehidden",
	    genderpreselect: "input[type=hidden].genderhidden",
	    productpreselect: "input[type=hidden].simple-product",
	    imagepath: "",
	    digits:2
	},options);
	this.basePrice = 0;
	this.tax = 0;
	this.products = [];
	this.tasteindex = null;
	this.color2index = null;
	this.sizeindex = null;
	this.genderindex = null;
	this.imagecnt = jQuery('.product-page-2-image');
	//jQuery.log(this.settings.data);
};
var C = Configurable.prototype;
//Draw the Configurable-Options
C.draw = function() {
    var t = this, s = t.settings, a = s.data.attributes, taste = null, color2 = null, size = null, gender = null;
    //jQuery.log(s.data.attributes);
    jQuery.each(a,function(x) {
        var index = this.id;
        //jQuery.log("Index: "+index);
        switch(this.code) {
        case'taste':
            taste = x;
            t.tasteindex = index;
            break;
        case'color2':
            color2 = x;
            t.color2index = index;
            break;
        case'size':
            size = x;
            t.sizeindex = index;
            break;
        case'gender':
            gender = x;
            t.genderindex = index;
            break;
        }
    });
    //Get Price and Tax
    t.basePrice = parseFloat(s.data.basePrice);
    t.tax = parseInt(s.data.taxConfig.currentTax);
    if(color2) {
        //Set Names of Data-Fields
        jQuery(s.color2preselect).attr("name","super_attribute["+t.color2index+"]");
        //Build Color2 (Colors)
        t.buildColor2(a[color2].options);
    } else {
        //Set Names of Data-Fields
        jQuery(s.tastepreselect).attr("name","super_attribute["+t.tasteindex+"]");
        jQuery(s.sizepreselect).attr("name","super_attribute["+t.sizeindex+"]");
        jQuery(s.genderpreselect).attr("name","super_attribute["+t.genderindex+"]");
        //Build Taste (Colors)
        t.buildTaste(a[taste].options);
        //Build Size
        t.buildSize(a[size].options);
        //Build Gender
        t.buildGender(a[gender].options);
        //Show and enable Taste
        t.enable(jQuery(s.tasteselector));
        //Hide and disable Size and Gender
        t.disable(jQuery(s.sizeselector));
        t.disable(jQuery(s.genderselector));
    }
    
    //Build Shoppingcart Functions
    var shoppingcart = jQuery('table.product-page-shoppingcart');
    var decinc = shoppingcart.find('input.dec,input.inc');
    var counter = shoppingcart.find('tr.first input.product-quantity');
    var gespricelbl = shoppingcart.find('tr.total span.product-price');
    var gescounter = shoppingcart.find('tr.total input.product-quantity');
    var submitbtn = shoppingcart.find('tr.total input.product-submit');
    //De-/Increment Event
    decinc.click(function(){
        var count = parseInt(counter.val());
        (jQuery(this).hasClass('inc')) && counter.val(count+1);
        (jQuery(this).hasClass('dec')) && (count > 0) && counter.val(count-1);
        count = parseInt(counter.val());
        gescounter.val(count);
        var price = tFix(t.basePrice*count,t.settings.digits);
        gespricelbl.html(price+'&nbsp;&euro;');
        return false;
    });
    //Catch ENTER
    counter.keydown(function(e) {
        if(e.keyCode == 13) { submitbtn.click(); return false; }
    });
    //Counter Key-Event
    counter.keyup(function(){
        var count = parseInt(counter.val());
        gescounter.val(count);
        var price = tFix(t.basePrice*count,t.settings.digits);
        gespricelbl.html(price+'&nbsp;&euro;');
        return false;
    });
    //Make sure that Count in Counter >= 0
    counter.blur(function() {
        var count = parseInt(counter.val());
        !(count >= 0) && counter.val('0') && counter.keyup();
    });
};
//Get the Images of a Color
C.getImages = function(colorindex) {
    //jQuery.log("Get Images of ColorIndex: "+colorindex);
    var attr = this.settings.data.attributes;
    var images = [];
    jQuery.each(attr,function(){
        if(this.code == 'taste' || this.code == 'color2') {
            jQuery.each(this.options,function(){
                if(this.id == colorindex) {
                    if(this.image1 != "") { images.push(this.image1); }
                    if(this.image2 != "") { images.push(this.image2); }
                    if(this.image3 != "") { images.push(this.image3); }
                    return false;
                }
            });
            if(images.length > 0) { return false; }
        }
    });
    return images;
};
//Enable a Container of the Configurable-Options
C.enable = function(obj) {
    if(obj) {
        obj.find('.active').removeClass('active');
        obj.css("display","");
        obj.find('input').removeAttr("checked");
        return obj;
    }
    return null;
};
//Disable a Container of the Configurable-Options
C.disable = function(obj) {
    if(obj) {
        obj.hide();
        return obj;
    }
    return null;
};
//Filter Products
C.filter = function(color2) {
    //jQuery.group("Filter Products:");
    var prods = this.products;
    var colors2 = jQuery(this.settings.color2selector);
    var colors = jQuery(this.settings.tasteselector);
    var sizes = jQuery(this.settings.sizeselector);
    var gender = jQuery(this.settings.genderselector);
    if(!color2) {
        //Get Products of Color
        var colorprods = colors.find('.active a').attr('products').split(' ') || [];
        //jQuery.log("Color Prods: "+colorprods.join(' '));
        prods = colorprods;
        //jQuery.log("Filtered Products: "+prods.join(' '));
        //Get Products of Size
        if(sizes.find('input').length > 0) {
            var sizeprods = [];
            if(sizes.find('input:checked').length > 0) { sizeprods = sizes.find('input:checked').attr('products').split(' '); }
            (!sizeprods.length > 0 ) && sizes.find('input').each(function(){
                sizeprods = jQuery.merge(sizeprods,jQuery(this).attr('products').split(' '));
            });
            //jQuery.log("Size Prods: "+sizeprods.join(' '));
            prods = jQuery.grep(prods, function (a) { 
                var check = true;
                jQuery.each(sizeprods,function(){
                    if(this == a) {
                        return check = false;
                    }
                });
                return !check;
            });
        } else {
            sizes.remove();
            jQuery(this.settings.sizepreselect).remove();
        }
        //jQuery.log("Filtered Products: "+prods.join(' '));
        //Get Products of Gender
        if(gender.find('input').length > 0) {
            var genderprods = [];
            gender.find('input').each(function() {
                genderprods = jQuery.merge(genderprods,jQuery(this).attr('products').split(' '));
            });
            //jQuery.log("Gender Prods: "+genderprods.join(' '));
            prods = jQuery.grep(prods, function (a) { 
                var check = true;
                jQuery.each(genderprods,function(){
                    if(this == a) {
                        return check = false;
                    }
                });
                return !check;
            });
        } else {
            gender.remove();
            jQuery(this.settings.genderpreselect).remove();
        }
        //jQuery.log("Filtered Products: "+prods.join(' '));
    } else {
        //Get Products of Color
        var colorprods = colors2.find('.active a').attr('products').split(' ') || [];
        //jQuery.log("Filter Colors: "+colorprods.join(' '));
        prods = colorprods;
    }
    this.products = prods;
    var submitbnt = jQuery('input.product-submit');
    (this.products.length == 1) && jQuery(this.settings.productpreselect).attr('value',this.products[0]) && submitbnt.removeAttr('disabled').attr('src',submitbnt.attr('src').replace(/grey/,'blue')) && jQuery(this.settings.productpreselect).change();
    (this.products.length != 1) && submitbnt.attr('disabled','disabled').attr('src',submitbnt.attr('src').replace(/blue/,'grey')) && jQuery(this.settings.productpreselect).attr('value','').change();
    //jQuery.log("Filtered Products: "+this.products.join(' '));
    //jQuery.groupEnd();
    //jQuery.log(this.getProduct(this.products[0]));
};
//Get the Product from Json-Data
C.getProduct = function(prodid) {
    var attr = this.settings.data.attributes;
    var prod = null;
    jQuery.each(attr,function(){
        jQuery.each(this.options,function(){
            jQuery.each(this.products,function(){
                if(this.toString() == prodid) {
                    prod = this;
                    return false;
                }
            });
            if(prod !== null) { return false; }
        });
        if(prod !== null) { return false; }
    });
    return prod;
};
//Build Tastes
C.buildTaste = function(tastes) {
    var code = '', count = 0, t = this, s = t.settings;
    var tcnt = jQuery(s.tasteselector);
    //Reference Object to DOM
    (tcnt.get(0)) && jQuery.data(tcnt.get(0),"object",this);
    //Cleanup if exsits
    tcnt.empty();
    //Iterate Colors
    jQuery.each(tastes,function(x) {
        var l = this.label.split('#');
        var label = l[0], color = l[1], prods = this.products.join(' ');
        //jQuery.log("Build Color [#"+color+"]: "+label);
        if(count == 0) { code+='<tr>\n'; }
        code+='<td class="color" id="color-'+this.id+'">';
        code+='<div><a class="ritter-'+color+'-bg" products="'+prods+'" href="#'+color+'" title="'+label+'">'+label+'</a></div>';
        code+='</td>\n';
        if(count == 13) { code+='</tr>\n'; }
        count++; if(count >= 13) { count = 0; }
    });
    //Auffüllen
    while(count < 13 && count != 0) {
        code+='<td class="color"></td>\n';
        count++;
    }
    //Write to DOM
    tcnt.append(code);
    //Set onClick
    tcnt.find('a').bind('click',function(){
        //Display all Sizes
        var sizes = jQuery(s.sizeselector).find('input');
        sizes.parent().show().next().show();
        //Get Products of this Color
        var prods = jQuery(this).attr('products').split(' ');
        //Display only available Sizes
        sizes.each(function() {
            var sprod = jQuery(this).attr('products').split(' ');
            tmp = jQuery.grep(prods, function (a) { 
                var check = true;
                jQuery.each(sprod,function(){
                    if(this == a) {
                        return check = false;
                    }
                });
                return !check;
            });
            //Ausblenden wenn kein Product vorhanden
            (!tmp.length > 0) && jQuery(this).parent().hide().next().hide();
        });
        //Set Color Active and get ColorId
        var colorid = jQuery(this).parents('td').attr('id').replace(/color-/,'');
        jQuery(s.tastepreselect).attr('value',colorid);
        jQuery(this).parents('table').find('div').removeClass('active');
        jQuery(this).parent().addClass("active");
        var o = jQuery.data(tcnt.get(0),"object");
        o.enable(jQuery(o.settings.sizeselector));
        //Trigger the Filter
        o.filter();
        //Get and show Images to choosen Color
        o.buildImages(colorid);
        return false;
    });
};
//Build Color2
C.buildColor2 = function(colors) {
    var code = '', count = 0, t = this, s = t.settings;
    var ccnt = jQuery(s.color2selector);
    //Reference Object to DOM
    (ccnt.get(0)) && jQuery.data(ccnt.get(0),"object",this);
    //Cleanup if exsits
    ccnt.empty();
    //Iterate Colors
    jQuery.each(colors,function(x) {
        var l = this.label.split('#');
        var label = l[0], color = l[1], prods = this.products.join(' ');
        //jQuery.log("Build Color2 [#"+color+"]: "+label);
        if(count == 0) { code+='<tr>\n'; }
        code+='<td class="color" id="color-'+this.id+'">';
        code+='<div><a class="ritter-'+color+'-bg" products="'+prods+'" href="#'+color+'" title="'+label+'">'+label+'</a></div>';
        code+='</td>\n';
        if(count == 6) { code+='</tr>\n'; }
        count++; if(count >= 6) { count = 0; }
    });
    //Auffüllen
    while(count < 6 && count != 0) {
        code+='<td class="color"></td>\n';
        count++;
    }
    //Write to DOM
    ccnt.append(code);
    //Set onClick
    ccnt.find('a').bind('click',function(){
        //Display all Sizes
        var sizes = jQuery(s.sizeselector).find('input');
        sizes.parent().show().next().show();
        //Get Products of this Color
        var prods = jQuery(this).attr('products').split(' ');
        //Display only available Sizes
        sizes.each(function() {
            var sprod = jQuery(this).attr('products').split(' ');
            tmp = jQuery.grep(prods, function (a) { 
                var check = true;
                jQuery.each(sprod,function(){
                    if(this == a) {
                        return check = false;
                    }
                });
                return !check;
            });
            //Ausblenden wenn kein Product vorhanden
            (!tmp.length > 0) && jQuery(this).parent().hide().next().hide();
        });
        //Set Color Active and get ColorId
        var colorid = jQuery(this).parents('td').attr('id').replace(/color-/,'');
        jQuery(s.color2preselect).attr('value',colorid);
        jQuery(this).parents('table').find('div').removeClass('active');
        jQuery(this).parent().addClass("active");
        var o = jQuery.data(ccnt.get(0),"object");
        //Trigger the Filter
        o.filter(true);
        //Get and show Images to choosen Color
        o.buildImages(colorid);
        return false;
    });
};
//Build the ProductImagesSlider
C.buildImages = function(colorid) {
    var images = this.getImages(colorid);
    var imagecnt = this.imagecnt;
    if(images.length > 1) {
        imagecnt.empty();
        var id = guid();
        imagecnt.attr("id",id);
        jQuery.each(images,function(){
            if(this != "") { imagecnt.append('<img src="'+this+'" class="hide" />'); }
        });
        imagecnt.children('img:first').removeClass('hide').addClass('active');
        imagecnt.append('<div class="product-page-2-image-thumb clearfix" id="'+id+'thumb"></div>');
        var thumbcnt = imagecnt.children('#'+id+'thumb');
        jQuery.each(images,function(){
            if(this != "") { thumbcnt.append('<a href="#"><img style="width:45px;" src="'+this+'" /></a>'); }
        });
        thumbcnt.children('img').click(function(){
            var index = jQuery(this).index(jQuery(this).parent());
            imagecnt.children('img').removeClass('active').addClass('hide');
            imagecnt.children('img:eq('+index+')').removeClass('hide').addClass('active');
        });
    } else {
        imagecnt.children('img').attr('src',images[0]);
    }
};
//Build Sizes
C.buildSize = function(sizes) {
    var scnt = jQuery(this.settings.sizeselector);
    //Reference Object to DOM
    (scnt.get(0)) && jQuery.data(scnt.get(0),"object",this);
    //Cleanup if exsits
    scnt.empty();
    var code = '', s = this.settings, t = this;
    if(sizes.length > 0) {
        //Iterate Sizes
        jQuery.each(sizes,function(x) {
            var label = this.label, prods = this.products.join(' ');
            //jQuery.log("Build Size: Groesse "+label);
            code+='<td class="size" id="size-'+this.id+'">';
            code+='<input type="radio" value="'+label+'" name="size" class="radio" products="'+prods+'" />';
            code+='</td>\n';
            code+='<td colspan="2" class="size-text"> Gr&ouml;&szlig;e '+label+'</td>';
        });
    } else if(gender.length == 1) {
        var label = sizes[0].label, prods = sizes[0].products.join(' ');
        code+='<input products="'+prods+'" type="hidden" name="size" value="'+label+'" />';
        jQuery(s.sizepreselect).attr('value',sizes[0].id);
    }
    //Write to DOM
    scnt.append(code);
    //Set onClick
    scnt.find('input').bind('click',function(){
        jQuery(s.sizepreselect).attr('value',jQuery(this).parent().attr('id').replace(/size-/,''));
        var o = jQuery.data(scnt.get(0),"object");
        jQuery(this).addClass("active");
        o.filter();
        return true;
    });
};
//Build Gender
C.buildGender = function(gender) {
    var gcnt = jQuery(this.settings.genderselector);
    //Reference Object to DOM
    (gcnt.get(0)) && jQuery.data(gcnt.get(0),"object",this);
    //Cleanup if exsits
    gcnt.empty();
    var code = '', s = this.settings, t = this;
    if(gender.length > 1) {
        //Iterate Gender
        jQuery.each(gender,function(x) {
            var label = this.label, prods = this.products.join(' ');
            //jQuery.log("Build Gender: "+label);
            code+='<td class="size" id="gender-'+this.id+'">';
            code+='<input type="radio" value="'+label+'" name="gender" class="radio" products="'+prods+'" />';
            code+='</td>\n';
            code+='<td class="size-text" colspan="2"> '+label+'</td>';
        });
    } else if(gender.length == 1) {
        var label = gender[0].label, prods = gender[0].products.join(' ');
        code+='<input products="'+prods+'" type="hidden" name="gender" value="'+label+'" />';
        jQuery(s.genderpreselect).attr('value',gender[0].id);
    }
    //Write to DOM
    gcnt.append(code);
    //Set onClick
    gcnt.find('input').bind('click',function(){
        jQuery(s.genderpreselect).attr('value',jQuery(this).parent().attr('id').replace(/gender-/,''));
        var o = jQuery.data(gcnt.get(0),"object");
        
        return true;
    });
};

Presentbundle = function(options) {
    this.settings = jQuery.extend({
	    data: {},
	    debug:true,
	    object: null
	},options);
    this.container = this.settings.object.children("div").children(":not('#overlay-top'):not('#shoppingcartbar')");
    this.container4 = this.settings.object.children("div").find("#overlay-inner-content4");
    this.links = this.settings.object.children("div").find("a:not('#close-overlay')");
    this.scf = jQuery.find('form#shoppingcartbar');
};
var PB = Presentbundle.prototype;
PB.log = function(text) {
    (this.settings.debug) && jQuery.log(text);
};
//Draw the Presentbundle
PB.draw = function() {
    var t = this;
	var l = t.links, con = t.container;
	t.log(t.scf);
	//Show first Container
    con.hide().first().show();
    
    this.links.each(function() {
    	var l = jQuery(this);
    	(l.attr("id") == 3) && l.attr('disabled', 'disabled')
    });
    
    //Set Click-Event
    this.links.click(function() {
    	
		var l = jQuery(this);
		if (!l.attr('disabled')) {
			con.hide();
			(l.attr("id") != 4) && t.inactiveAll(l.attr("id"));
			var val = l.attr("id");
			var newCont = jQuery(con[(val - 1)]);
			(l.attr("rel") && l.attr("id") == 4) && (t.container4.empty() && t.container4.load(l.attr('rel'),function(){
				t.container4.find(':jsclass').generateObject();  
				t.log(jQuery(t.scf));
				//TODO: remove old object
				t.log("Redraw");
				var scf = jQuery.data(jQuery(t.scf).get(0),"object");
				t.log(scf);
				(scf) && scf.draw(true);
			}));
			jQuery(con[(val - 1)]).show();
		}
	});
   
};
PB.hideAll = function() {
	this.container.hide();
};
PB.inactiveAll = function(id) {
	this.links.each(function() {
		var l = jQuery(this);
		(!l.hasClass('arrow-white')) && l.removeAttr("class");
		//;-)
		(id) && (l.attr("id") == id) && (!l.hasClass('arrow-white')) && l.attr("class","active")
	});
};
/*
 * PresentBundleChocolate - Class
 */
PresentBundleChocolate = function(options) {
	this.settings = jQuery.extend({
		debug:true
	},options);
	
	this.chocolist = jQuery('form.overlay-shoppingcart:not(#shoppingcartbar)');  
	this.dstring = jQuery('form#shoppingcartbar input[type=hidden].descriptionstring');
	this.rows = this.chocolist.find('div.product-1');
    this.getcounter = this.chocolist.find('div.text input.product-quantity');
    this.getmaxcounter = this.chocolist.find('div.text input#product-quantity').val();
    
    
};
var PBC = PresentBundleChocolate.prototype;
PBC.log = function(text) {
    (this.settings.debug) && jQuery.log(text);
};
//Get Totals
PBC.getTotals = function() {
    var totalcount = this.getmaxcounter, t = this;
    //Get totals
    t.rows.each(function(){
        var r = jQuery(this), counter = r.find('input.product-quantity');
        var count = counter.val() ? parseInt(counter.val()) : 0;
        totalcount -= count;
        (totalcount < 0) && (totalcount = 0)
    });
   // t.rows.each(function() {
    	 var inc = this.chocolist.find('input.inc');
    	 if (totalcount <= 0) {
    	     var next = this.chocolist.find('#overlay-next');
    	     (!next.hasClass('active')) && next.addClass('active');
    	     (!next.find('a').hasClass('arrow-white')) && next.find('a').addClass('arrow-white');
        	 inc.attr('disabled','disabled');
        	 t.getDataString();
        	 t.disenb(0);
         } else {
             var next = this.chocolist.find('#overlay-next').removeClass('active');
             next.find('a').removeClass('arrow-white')
        	 inc.removeAttr('disabled');
        	 t.dstring.val('');
        	 t.disenb(1);
         }
    //});
    //Write totals
    t.getcounter.val(totalcount);
};
//Draw  PresentBundleChocolate 
PBC.draw = function() {
	var t = this;
	var s = t.settings;
	t.rows.each(function(){
        var r = jQuery(this), decinc = r.find('input.dec, input.inc'), counter = r.find('input.product-quantity');
        counter.attr('readOnly','readOnly');
        t.disenb(1);
        //De-/Increment Event 
        decinc.click(function(){
    	    var count = parseInt(counter.val());
            (jQuery(this).hasClass('inc')) && counter.val(count+1);
            (jQuery(this).hasClass('dec')) && (count > 0) && counter.val(count-1);
            //calculate result count
            count = parseInt(counter.val());
            t.getTotals();
            return false;
        });
        //Catch ENTER
        counter.keydown(function(e){
            if(e.keyCode == 13){ t.submitbtn.click(); return false; }
        });
        //Counter Key-Event
        counter.keyup(function(){
            var count = parseInt(counter.val());
            t.getTotals();
            return false;
        }); 
        //Make sure that Count in Counter >= 0
        counter.blur(function() {
            var count = parseInt(counter.val());
            (count >= t.getcounter.val()) && counter.val(t.getcounter.val())
            !(count >= 0) && counter.val('0');            
            counter.keyup();
            t.getTotals();
        });
    });
    t.getcounter.blur(function(){
    	var c = parseInt(t.getcounter.val());
    	(c >= 0) && c.val("0");
    });
};
PBC.getDataString = function() {
	var t = this, string = '';
	var rp = 0;
	t.rows.each(function(){
        var r = jQuery(this), counter = r.find('input.product-quantity'), price = r.find('input[type=hidden].product-price'), sku = r.find('input[type=hidden].product-sku');
        var id = r.attr("id").substr(18, 4);
        if (counter.val() > 0) {
	        string += 'IP01X' + sku.val() + ';';
	        string += 'IP02' + counter.val() + ';';
	        rp = counter.val()*price.val();
	        rp = tFix(rp, 2);
	        string += 'IP03' + rp + ';' + 'IP04;';
        }
    });
	t.dstring.val(string);
};
PBC.disenb = function(dis) {
	var link = jQuery('a#3');
	var link2 = this.chocolist.find('a#3');
	if (link.attr('disabled') && dis == 0) {
		link.removeAttr('disabled');
		link2.removeAttr('disabled');
	}			
	else if (dis = 1) {
		link.attr('disabled', 'disabled');
		link2.attr('disabled', 'disabled');
	}
	
};

/*
 * PresentBundleShoppingCartBar - Class
 */
PresentBundleShoppingCartBar = function(options) {
	this.settings = jQuery.extend({
		basePrice: 0.0,
		debug:true
	},options);
	this.shoppingCartBar = null;  
	this.getcounter = null;
    this.getprice = null;
    this.decinc = null;
    this.scbutton = null;
    this.descriptionstring = null;
    this.descriptionstring2 = null;
    this.simpleproduct = null;
    this.productprice = null;
    this.acline = null;
};
var PBSCB = PresentBundleShoppingCartBar.prototype;
PBSCB.log = function(text) {
    (this.settings.debug) && jQuery.log(text);
};

PBSCB.setObjects = function() {
	this.shoppingCartBar = jQuery('form#shoppingcartbar');  
	this.getcounter = this.shoppingCartBar.find('input.product-quantity');
    this.getprice = this.shoppingCartBar.find('span.product-price');
    this.decinc = this.shoppingCartBar.find('input.dec, input.inc');
    this.scbutton = this.shoppingCartBar.find('input.product-submit');
    this.descriptionstring = this.shoppingCartBar.find('input[type=hidden].descriptionstring');
    this.descriptionstring2 = this.shoppingCartBar.find('input[type=hidden].descriptionstring2');
    this.simpleproduct = jQuery('form#pbconfigurable input[type=hidden].simple-product');
    this.productprice = jQuery('form#pbconfigurable input[type=hidden].product-price');
    this.acline = this.shoppingCartBar.find('div#overlay-footer');
    this.gltext = jQuery('form#pbconfigurable div#bluetext');
};

//Draw Present Bundle 
PBSCB.draw = function(redraw) {
	var t = this;
	var s = t.settings;
	var price = s.basePrice;
	t.setObjects();
	
	//Reference Object to DOM
	(!redraw) && jQuery.data(t.shoppingCartBar.get(0),"object",t);
	
	t.log("draw PBSCB");
		
	t.decinc.attr('disabled','disabled');
	t.scbutton.attr('disabled','disabled');
	t.log(t.gltext);
	jQuery(t.gltext).hide();
	t.acline.removeAttr('class');
	
	(!redraw) && t.decinc.click(function(){
		var count = parseInt(t.getcounter.val());
        (jQuery(this).hasClass('inc')) && t.getcounter.val(count+1);
        (jQuery(this).hasClass('dec')) && (count > 1) && t.getcounter.val(count-1);
        //calculate result count
       t.getprice.html(tFix(t.getcounter.val()*price, 2) + " &euro;");
        return false;
    });
	(!redraw) && t.getcounter.blur(function(){
		var count = parseInt(t.getcounter.val());
        t.getprice.html(tFix(t.getcounter.val()*price, 2) + " &euro;");
        return false;
	});
	(!redraw) && t.scbutton.click(function(){
		t.log("submit form"); 
		t.collectData();
		return true;
	});
	t.log(t.simpleproduct);
	t.log(t.scbutton);
	t.simpleproduct.bind("change", function() {
		t.log("changeval");
		if (t.simpleproduct.val() != '' && t.descriptionstring.val() != '') {
			t.decinc.removeAttr('disabled');
			t.acline.attr('class', 'active');
			t.gltext.show();
		} else if (t.simpleproduct.val() == '' || t.descriptionstring.val() == '') {
			t.gltext.hide();
			t.decinc.attr('disabled','disabled');
			t.acline.removeAttr('class');
			t.scbutton.attr('disabled','disabled').attr('src',t.scbutton.attr('src').replace(/blue/,'grey'));
		}
	});
};
PBSCB.collectData = function() {	
	var data = this.descriptionstring.val();
	if (this.simpleproduct.val()) {
		var string = 'IP01X' + this.simpleproduct.val() + ';';
	    string += 'IP02' + this.getcounter.val() + ';';
	    rp = this.getcounter.val()*this.productprice.val();
        rp = tFix(rp, 2);
        string += 'IP03' + rp + ';IP04;';  
		data += string;
		this.descriptionstring2.val(data);
	}
};


/*
 * PIVShoppingCartBar - Class
 */
PIVShoppingCartBar = function(options) {
	this.settings = jQuery.extend({
		debug:true
	},options);
    
    this.shoppingCartBar = jQuery('form#shoppingcartbar'); 
	this.getcounter = this.shoppingCartBar.find('input.product-quantity');
    this.getprice = this.shoppingCartBar.find('span.product-price');
    this.decinc = this.shoppingCartBar.find('input.dec, input.inc');
    this.baseprice = this.shoppingCartBar.find('input[type=hidden].product-baseprice');
    this.scbutton = this.shoppingCartBar.find('input.product-submit');
};
var PIVSCB = PIVShoppingCartBar.prototype;
PIVSCB.log = function(text) {
    (this.settings.debug) && jQuery.log(text);
};

//Draw PIV
PIVSCB.draw = function(redraw) {
	var t = this;
	
	t.decinc.attr('disabled','disabled');
	t.scbutton.attr('disabled','disabled');
	
	t.decinc.click(function(){
		var price = t.baseprice.val().replace(/[^0-9,].*/,'').replace(/,/,'.');
		var count = parseFloat(t.getcounter.val());
        (jQuery(this).hasClass('inc')) && t.getcounter.val(count+1);
        (jQuery(this).hasClass('dec')) && (count > 1) && t.getcounter.val(count-1);
        //calculate result count
       t.getprice.html(tFix(t.getcounter.val()*price, 2) + " &euro;");
        return false;
    });
	t.getcounter.blur(function(){
		var price = t.baseprice.val().replace(/[^0-9,].*/,'').replace(/,/,'.');
		var count = parseFloat(t.getcounter.val());
        t.getprice.html(tFix(t.getcounter.val()*price, 2) + " &euro;");
        return false;
	});
};

/*
 * eTracker - Class
 */
eTracker = function(options) {
    this.settings = jQuery.extend({
        pagename: null,
        areas: null,
        ilevel: 0,
        url: "window.location",
        tag: "",
        target: "",
        tval: "0",
        tonr: "",
        tsale: 0,
        cust: 0,
        basket: "",
        lpage: "0",
        trig: "",
        se: "0",
        secureCode: "Cbgvsg",
        appendDOM: jQuery("body")
	},options);
	if((this.settings.pagename) && (jQuery('div#content div.text > h3:first').length > 0)) {
	    this.settings.pagename = jQuery('div#content div.text > h3:first').text();
	}
	if((this.settings.areas) && (jQuery('div#nav-main ul li a.active').length > 0)) {
	    this.settings.areas = jQuery('div#nav-main ul li a.active').text();
	    var areas2 = ('div#productscene ul.nav-sub li a.active').text();
	    if(areas2 != "") {
	        this.settings.areas = this.settings.areas+(' / '+areas2);
	    }
	}
	jQuery.log("eTracker Code");
};
var eT = eTracker.prototype;
eT.draw = function() {
    jQuery.log("Draw eTracker Code");
    //this.drawCode();
    //this.drawVars();
    //this.drawExec();
    jQuery.log("Draw finished");
};

eT.drawCode = function() {
    document.write(String.fromCharCode(60)+"script type=\"text/javascript\" src=\"http"+("https:"==document.location.protocol?"s":"")+"://code.etracker.com/t.js?et="+this.settings.secureCode+"\">"+String.fromCharCode(60)+"/script>");
};

eT.drawVars = function() {
    var vars = "";
    jQuery.each(this.settings,function(a){
        if(a != "secureCode") {
            vars+="var et_"+a+" = "+this+";\n";
        }
    });
    document.write(String.fromCharCode(60)+"script type=\"text/javascript\">"+vars+String.fromCharCode(60)+"/script>");
};

eT.drawExec = function() {
    document.write(String.fromCharCode(60)+"script type=\"text/javascript\">_etc();"+String.fromCharCode(60)+"/script>");
};

//Create an Overlay with Ajax-Content (used by PresentBundle and PIV)
jQuery.fn.Overlay = function(id,address,iframe) {
    var t = jQuery(this);
    id = id || t.attr('rel') || t.attr('id');
    jQuery('body').append('<div id="'+id+'"></div>');
	var o = jQuery('#'+id);
	jQuery('div#overlay-wrapper-bg, div#overlay-wrapper.'+id).fadeIn(175);
	jQuery('div#overlay-wrapper-bg').css({"opacity":"0.5"});
	var url = 'http://'+document.location.host+'/index.php/'+address;
	//Write iFrame
	(iframe) && (address) && o.append('<div id="overlay-wrapper" class="'+id+'">'+
	                                    '<div id="overlay-wrapper-content">'+
	                                    '<iframe style="width:870px; height:100%; overflow:hidden;" id="iframe-'+id+'" src="'+url+'"></iframe>'+
	                                    '<a title="Schließen" href="#" id="close-overlay"><img alt="Schließen" src="/skin/frontend/default/ritter2/images/icon_close_darkgrey.png"></a>'+
	                                    '</div>'+
	                                    '</div>');
    (iframe) && o.find('a#close-overlay').click(function(){
        jQuery(this).parents('div#'+id).fadeOut(175, function(){ jQuery(this).remove(); });
	    jQuery('div#overlay-wrapper-bg').fadeOut(175);
	    return false;
    });
	//Write Ajax-Content
	(!iframe) && (address) && o.load(url, function(){
	    o.find(':jsclass').generateObject();
	    o.find('a#close-overlay').click(function(){
	        jQuery(this).parents('div#'+id).fadeOut(175, function(){ jQuery(this).remove(); });
		    jQuery('div#overlay-wrapper-bg').fadeOut(175);
		    return false;
	    });
    });
};

/*
 * Live-Code
 */ 
//Build Page
jQuery(document).ready(function(){
	// Hide Headline Image (wellcome text)
	setTimeout(function(){
		/*jQuery("h1#headline").fadeOut("slow",function(){jQuery("div#customer-name").show();});*/
		jQuery("h1#headline,div#customer-name").fadeOut("slow");
	},2000);
	// Show temperature layer 
	jQuery("div#temperature").hover(
		function () {
                    (jQuery.browser.msie) ? jQuery("div#shoppingcart-layer").stop().hide() : jQuery("div#shoppingcart-layer").stop().fadeOut(175,function(){jQuery(this).fFix();});
                    (jQuery.browser.msie) ? jQuery("div#temperature-layer").show() : jQuery("div#temperature-layer").fadeIn(175,function(){jQuery(this).fFix();});
		}, 
		function () {
                    (jQuery.browser.msie) ? jQuery("div#temperature-layer").hide() : jQuery("div#temperature-layer").fadeOut(175,function(){jQuery(this).fFix();});
		}
	);
	// Show shoppingcart layer
	jQuery("div#shoppingcart").hover(
		function () {
                    (jQuery.browser.msie) ? jQuery("div#temperature-layer").stop().hide() : jQuery("div#temperature-layer").stop().fadeOut(175,function(){jQuery(this).fFix();});
                    (jQuery.browser.msie) ? jQuery("div#shoppingcart-layer").show() : jQuery("div#shoppingcart-layer").fadeIn(175,function(){jQuery(this).fFix();});
		}, 
		function () {
                    (jQuery.browser.msie) ? jQuery("div#shoppingcart-layer").hide() : jQuery("div#shoppingcart-layer").fadeOut(175,function(){jQuery(this).fFix();});
		}
	);			
	// Hover teaser	
	jQuery("div.teaser-1, div.teaser-2").hover(
		function () {
			jQuery(this).addClass('active');
		}, 
		function () {
			jQuery(this).removeClass('active');
		}
	);
	// Display top navigation
	jQuery("li.nav-point-1").hover(
		function () {
			jQuery("h1#headline,div#customer-name").stop().hide();		
			jQuery("ul#nav-top").css("width","auto");
			
			setTimeout(function(){
				jQuery("li.nav-point-3").fadeIn(175,function(){jQuery(this).fFix();});
			},0);
			
			setTimeout(function(){
				jQuery("li.nav-point-4").fadeIn(175,function(){jQuery(this).fFix();});
			},60);
			
			setTimeout(function(){
				jQuery("li.nav-point-5").fadeIn(175,function(){jQuery(this).fFix();});
			},120);
			
			setTimeout(function(){
				jQuery("li.nav-point-6").fadeIn(175,function(){jQuery(this).fFix();});
			},180);
		}, 
		function () {
		}
	);
	// Hide top navigation
	jQuery("ul#nav-top").mouseleave(
		function () {
			setTimeout(function(){
				jQuery("li.nav-point-3").fadeOut(175,function(){jQuery(this).fFix();});
			},180);
			
			setTimeout(function(){
				jQuery("li.nav-point-4").fadeOut(175,function(){jQuery(this).fFix();});
			},120);
			
			setTimeout(function(){
				jQuery("li.nav-point-5").fadeOut(175,function(){jQuery(this).fFix();});
			},60);
			
			setTimeout(function(){
				jQuery("li.nav-point-6").fadeOut(175,function(){jQuery(this).fFix();});
			},0);	
		}
	);
	
	jQuery("div.product-category-overview-item").hover(
		function () {
			jQuery(this).css("border-color","#a1a1a1");
		},
		function () {
			jQuery(this).css("border-color","#e2e2e2");
		}
	);	
	
	//If the User resizes the window
	jQuery(window).bind("resize",function(e) {
		var newwinH = jQuery(document).height(), newwinW = jQuery(document).width();	
		jQuery("div#overlay-wrapper-bg").css("width",newwinW).css("height",newwinH); 
	});
	jQuery(window).trigger('resize'); //trigger for first adjustment

	//Show hint overlay
	jQuery('a[rel=hint-overlay]').click(function() {
		var e = jQuery(this).attr('href');
		jQuery('#b2bswitch div#overlay-wrapper-content.hint a#hint-forword').attr('href',e);
		jQuery('div#overlay-wrapper-bg,#b2bswitch div#overlay-wrapper.b2bswitch').fadeIn(175);
		jQuery('div#overlay-wrapper-bg').css({"opacity":"0.5"});
		jQuery('#b2bswitch a#close-overlay').click(function(){
		    jQuery(this).parents('div#b2bswitch').fadeOut(175, function(){ jQuery(this).remove(); });
		    jQuery('div#overlay-wrapper-bg').fadeOut(175);
		    return false;
		});
		return false;
	});
	// Show custom product packing overlay (PIV)
	jQuery('a[rel=piv-overlay]').live('click',function() {
		jQuery(this).Overlay('piv','piv/ajax/index/step/init');
		return false;
	});	
	// Show gbundle overlay
	jQuery('a[rel=gbundle-overlay]').live('click',function() {
		jQuery(this).Overlay('presentbundle','presentbundle/ajax/index/product/3157/category/71');
		return false;
	});	
	// Show furtherInfo overlay
	jQuery('a[rel=furtherInfo-overlay]').live('click',function() {
		jQuery('div#overlay-wrapper-bg, #furtherInfo div#overlay-wrapper.furtherInfo').fadeIn(175);
		jQuery('div#overlay-wrapper-bg').css({"opacity":"0.5"});
		jQuery('#furtherInfo a#close-overlay').click(function(){
		    jQuery(this).parents('div#furtherInfo').fadeOut(175, function(){ jQuery(this).remove(); });
		    jQuery('div#overlay-wrapper-bg').fadeOut(175);
		    return false;
		});
		return false;
	});

	//Mini-Login-Form Submit on Enter
	jQuery('#toolbox form.login input').keydown(function(e){
        if (e.keyCode == 13) {
            jQuery(this).parents('form').submit();
            return false;
        }
    });
    //Mini-Login-Form Submit on Click a-Tag
    jQuery('#toolbox form.login a').click(function(){
        jQuery(this).parents('form').submit();
		return false;
    });
	
	//Autodetect Class Pattern
	jQuery(":jsclass").each(function(){
		(jQuery(this) !== undefined) &&	jQuery(this).generateObject();
	});
});
