/**
 * jQuery Default Value Plugin v1.0
 * Progressive enhancement technique for inital input field values
 *
 * The MIT License
 * 
 * Copyright (c) 2007 Paul Campbell (pauljamescampbell.co.uk)
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @param		String
 * @return		Array
 */
(function($) {
	
	$.fn.defaultvalue = function() {
		
		// Scope
		var elements = this;
		var args = arguments;
		var c = 0;
		
		return(
			elements.each(function(i) {				
				
				// Default values within scope
				var field = $(this);
				var promptField = field;
				var promptText = args[c++];
				
				if (field.attr("type") == "password") {
					promptField = $('<input type="text"></input>');
					promptField.attr('title', field.attr('title'));
					promptField.attr('class', field.attr('class'));
					field.hide();
					field.after(promptField);
				}

				promptField.val(promptText).focus(function() {
					if(promptField.val() == promptText) {
						field.val("");
						if (field.attr("type") == "password") {
							promptField.hide();
							field.show();
							field.focus();
						}
					}
				});
				
				field.blur(function() {
					if(field.val() == "") {
						field.val(promptText);
						if (field.attr("type") == "password") {
							field.hide();
							promptField.show();
						}
					}
				});
				
			})
		);
	}
})(jQuery)

jQuery.fn.extend({
	scrollpanel: function(scrollPanelParent, submenuArea, childSelector, itemWidth, jumpPixels, alignCentered, includePageGutter, additionalCssClass) {
		return this.each(function() {
		
			// These two CSS settings have to be hardcoded
			// IE does not like $.css property when the HTML dom is appended and loaded dynamically
			// when we change the design / images of these two, we might need to change these values as well
			var scrollGutterWidth = 749;
			var scrollHandleWidth = 107;
			var scrollArrowHoldSlideIncrement = 15; // in pixels
			var scrollPanelParentInnerWidth = scrollPanelParent.innerWidth();
			var scrollGutterLeftOffset;
			var scrollHandleLeftOffset;
			var isLeftMouseDown = false;
			var isRightMouseDown = false;
			var slideTimeout = 2;
			var slideDirection;
			
			var scrollPanel = $(this);
			var contentWidth = 0;
			var adjustedContentWidth = 0;
			var menuWidth = 0;
			var pageGutterWidth = 0;
			var animationTimeout = null;
			var animationInterval = 40;
			var target_x;
			var current_x;
			var scrollbar;
			var scrollbarInner
			var scrollbarLeftArrow;
			var scrollbarRightArrow;
			var scrollGutter;
			var scrollHandle;
			var initialScrollHandlePos;
			var initialMousePos;
			var scrollbarCreated = false;
			var scrollbarAdded = false;

			//Helper functions
			var initialAnimation = function() {				
				if (animationTimeout == null) animationTimeout = setInterval(animatePanelMovement, animationInterval);
				setScrollHandlePos();
			}
			var kickOffAnimation = function() {				
				if (animationTimeout == null) animationTimeout = setInterval(animatePanelMovement, animationInterval);
			}
			var kickOffSlideAnimation = function(direction) {
			    if (animationTimeout == null) animationTimeout = setInterval(slidePanelMovement, slideTimeout);
			}
			var animatePanelMovement = function() {
				current_x = scrollPanel.offset().left;
				var movement_x = Math.round(((target_x + menuWidth) - current_x) / 5);
				if (movement_x == 0) {
					current_x = target_x + menuWidth;
				    clearInterval(animationTimeout);
				    animationTimeout = null;
				} else if (movement_x > 0) {
					current_x += movement_x + 1;
				} else {
					current_x += movement_x - 1;
				}
				scrollPanel.css('left', current_x + 'px');
				
				// set cookies to remember scroll position
				$.cookie('scrollPanelPosition', target_x + menuWidth, { path: '/' });
				$.cookie('currentURL', window.location.pathname, { path: '/' });
				$.cookie('scrollTarget', target_x, { path: '/' });	
			}
			var slidePanelMovement = function() {
			    if (isMouseDown) {
			        if (slideDirection == "left") {
			            if (scrollPanel.offset().left + scrollArrowHoldSlideIncrement > menuWidth) {
	                        target_x = 0;
	                        movePanel();
                        } else {
	                        target_x = (scrollPanel.offset().left - menuWidth) + scrollArrowHoldSlideIncrement;
	                        movePanel();
                        }
			        } else {
			            if (adjustedContentWidth + (scrollPanel.offset().left - menuWidth) - scrollArrowHoldSlideIncrement < scrollPanelParentInnerWidth) {
					        target_x = 0 - (adjustedContentWidth - scrollPanelParentInnerWidth);
					        movePanel();
				        } else {
					        target_x = (scrollPanel.offset().left - menuWidth) - scrollArrowHoldSlideIncrement;
					        movePanel();
				        }
			        }
			    } else {
			        clearInterval(animationTimeout);
				    animationTimeout = null;
				
				    // set cookies to remember scroll position
				    $.cookie('scrollPanelPosition', target_x + menuWidth, { path: '/' });
				    $.cookie('currentURL', window.location.pathname, { path: '/' });
				    $.cookie('scrollTarget', target_x, { path: '/' });	
			    }
			}
			var movePanel = function() {
			    current_x = scrollPanel.offset().left;
				var movement_x = target_x + menuWidth - current_x;
				current_x += movement_x;
				scrollPanel.css('left', current_x + 'px');
				setScrollHandlePos();
				
				// set cookies to remember scroll position
				$.cookie('scrollPanelPosition', target_x + menuWidth, { path: '/' });
				$.cookie('currentURL', window.location.pathname, { path: '/' });
				$.cookie('scrollTarget', target_x, { path: '/' });	
			}
			var setScrollHandlePos = function() {	
				scrollGutterLeftOffset = scrollGutter.offset().left;
				var gutterStart = scrollGutterLeftOffset - scrollbarInner.offset().left;
				var scrollPos = (0 - target_x) / (adjustedContentWidth - scrollPanelParentInnerWidth);
				scrollHandle.css('left', (gutterStart + Math.round((scrollGutterWidth - scrollHandleWidth) * scrollPos)) + 'px');
				scrollHandleLeftOffset = scrollHandle.offset().left;
				initialScrollHandlePos = scrollHandleLeftOffset - scrollGutterLeftOffset;
			}
			
			var createScrollbar = function() {				
				if (!scrollbarCreated) {				
					//Create the scrollbar area
					scrollbar = $("<div></div>");
					scrollbar.addClass("scrollbar");
					
					//Add the actual scrollbar to the scroll area
					scrollbarInner = $("<div></div>");
					scrollbarInner.addClass("scrollbarInner");
					scrollbar.append(scrollbarInner);
					
					//Add the left arrow to the scrollbar
					scrollbarLeftArrow = $('<a href="#"></a>');
					scrollbarLeftArrow.addClass("leftScrollArrow");
//					scrollbarLeftArrow.click(function(e) {
//						e.preventDefault();
//						if (scrollPanel.offset().left + jumpPixels > menuWidth) {
//							target_x = 0;
//							movePanel();
//						} else {
//							target_x = (scrollPanel.offset().left - menuWidth) + jumpPixels;
//							movePanel();
//						}
//						setScrollHandlePos();
//					});
                    scrollbarLeftArrow.mousedown(function(e) {
                        isMouseDown = true;
                        slideDirection = "left";
                        kickOffSlideAnimation();
					});
					scrollbarLeftArrow.mouseout(function(e) {
                        isMouseDown = false;
					});
					scrollbarLeftArrow.mouseup(function(e) {
                        isMouseDown = false;
					});
					scrollbarInner.append(scrollbarLeftArrow);
					
					//Add the right arrow to the scrollbar
					scrollbarRightArrow = $('<a href="#"></a>');
					scrollbarRightArrow.addClass("rightScrollArrow");
//					scrollbarRightArrow.click(function(e) {
//						e.preventDefault();
//						if (adjustedContentWidth + (scrollPanel.offset().left - menuWidth) - jumpPixels < scrollPanelParentInnerWidth) {
//							target_x = 0 - (adjustedContentWidth - scrollPanelParentInnerWidth);
//							movePanel();
//						} else {
//							target_x = (scrollPanel.offset().left - menuWidth) - jumpPixels;
//							movePanel();
//						}
//						setScrollHandlePos();
//					});
					scrollbarRightArrow.mousedown(function(e) {
                        isMouseDown = true;
		                slideDirection = "right";
		                kickOffSlideAnimation();
					});
					scrollbarRightArrow.mouseout(function(e) {
                        isMouseDown = false;
					});
					scrollbarRightArrow.mouseup(function(e) {
                        isMouseDown = false;
					});
					scrollbarInner.append(scrollbarRightArrow);
					
					//Add the clickable scroll gutter to the scrollbar
					scrollGutter = $("<div></div>");
					scrollGutter.addClass("scrollGutter");
					scrollGutter.click(function(e) {
						var scrollPos = (e.pageX - scrollGutterLeftOffset) / scrollGutterWidth;
						target_x = Math.round((0 - (adjustedContentWidth - scrollPanelParentInnerWidth)) * scrollPos);
						movePanel();
						setScrollHandlePos();
					});
					scrollbarInner.append(scrollGutter);
					
					//Add the scroll handle to the scroll gutter (needs to be done after the scrollbar has been added so the gutter has a width)
					scrollHandle = $('<a href="#"></a>');
					scrollHandle.addClass("scrollHandle");
					var dragStart = function(e) {
						initialMousePos = e.pageX - scrollGutterLeftOffset;
						initialScrollHandlePos = scrollHandle.offset().left - scrollGutterLeftOffset;
						scrollHandle.css('background-position', '0 bottom');
					}
					var dragStop = function(e) {
						scrollHandle.css('background-position', '0 0');
						// set cookies to remember scroll position
						$.cookie('scrollPanelPosition', target_x + menuWidth, { path: '/' });
						$.cookie('currentURL', window.location.pathname, { path: '/' });
						$.cookie('scrollTarget', target_x, { path: '/' });
						scrollHandleLeftOffset = scrollHandle.offset().left;
					}
					var dragMove = function(e) {
						var movementX = ((e.pageX - scrollGutterLeftOffset) - initialMousePos);
						var scrollPos = (initialScrollHandlePos + movementX) / (scrollGutterWidth - scrollHandleWidth);
						if (scrollPos < 0) {
						    scrollPos = 0;
						} else if (scrollPos > 1) {
						    scrollPos = 1;
						}
						target_x = (0 - adjustedContentWidth + scrollPanelParentInnerWidth) * scrollPos;
						target_x = Math.round(target_x);
						scrollPanel.css('left', target_x + menuWidth + 'px');
					}
					scrollHandle.draggable({axis: 'x', containment: scrollGutter, cursor: 'w-resize', start: dragStart, stop: dragStop, drag: dragMove});

					scrollbarInner.append(scrollHandle);
					
					scrollbarCreated = true;
				}
			}
			var addOrRemoveScrollbar = function() {			
				//Get the menu width and add it to the content width
				menuWidth = submenuArea.outerWidth() + submenuArea.offset().left;
				
				//Also add the right hand gutter width
				if (includePageGutter) pageGutterWidth = menuWidth - 167; //167 is the how far the menu comes into the content area
									
				//Add the menu width and the page gutter width to the content area to be used for scrolling
				adjustedContentWidth = contentWidth + menuWidth + pageGutterWidth;
			
				//Add the scrollbar if the content is wider than the browser window
				if (contentWidth > (scrollPanelParentInnerWidth - menuWidth - pageGutterWidth)) {
					
					//Create the scrollbar if not already created
					if (!scrollbarCreated) createScrollbar();
					
					//Add the scrollbar if not already added
					if (!scrollbarAdded) {
						scrollPanel.after(scrollbar);
						scrollbarAdded = true;
					}
					
					//Set the initial scroll handle and content positions
					if ($.cookie('currentURL') == window.location.pathname) {
						// remember scroll position.
						target_x = $.cookie('scrollTarget');
						scrollPanel.css('left', $.cookie('scrollPanelPosition') + 'px');
					} else if (alignCentered) {
						if (contentWidth < scrollPanelParentInnerWidth) {
							var gapWidth = scrollPanelParentInnerWidth - contentWidth;
							target_x = 0 - (menuWidth - gapWidth);
							scrollPanel.css('left', gapWidth + 'px');
						} else {
							var centerOffsetWidth = Math.round((contentWidth - scrollPanelParentInnerWidth) / 2);
							target_x = 0 - (menuWidth + centerOffsetWidth);
							scrollPanel.css('left', -centerOffsetWidth + 'px');
						}
					} else {
						target_x = 0;
						scrollPanel.css('left', menuWidth + 'px');
					}
					setScrollHandlePos();
					
				} else {
					
					//Position the content to the left of the menu as no scroll bars are used
					scrollPanel.css('left', menuWidth + 'px');
					
					//Remove the scrollbar if required
					if (scrollbarAdded) {
						scrollbar.remove();
						scrollbarAdded = false;
					}
									
				}
			}
			
			//Add the required CSS class
			scrollPanel.addClass(additionalCssClass);
			
			contentWidth = $(".productView", scrollPanel).length * itemWidth;

			scrollPanel.css('width', contentWidth + 'px');
		
			//Add the scrollbar
			addOrRemoveScrollbar();
			
			//Bind the resize event of the browser to the add or remove scrollbar function
			$(window).resize(function() {
				addOrRemoveScrollbar();
			});
			
		});
	}
});

jQuery.fn.extend({
	draggableImage: function(params){
		return this.each(function(){
			var clicked = false;
			var current_x;
			var current_y;
			var target_x;
			var target_y;
			var backgroundPos_x = 0;
			var backgroundPos_y = 0;
			var drag_div = $(this);
			var animationTimeout = null;
			var animationInterval = 40;
			var trappableMargin = 60;
			var img_height;
			var img_width;
			
			//Set the hidden image as a bg image
			var bgimg = $(this).children('img');
			img_width = bgimg.width();
			img_height = bgimg.height();
			$(this).css('background-position', "0 0");
			$(this).css('background-repeat', "no-repeat");
			$(this).css('background-image', "url('"+bgimg.attr('src')+"')");
			bgimg.css('display', 'none');
			
			//Bind mouse down event
			$(this).mousedown(function(e){
				$(this).css('cursor', 'move');
				clicked = true;
				current_x = Math.round(e.pageX - $(this).eq(0).offset().left);
				current_y = Math.round(e.pageY - $(this).eq(0).offset().top);
				target_x = current_x;
				target_y = current_y;
			});
			
			//Bind the mouse up
			$(this).mouseup(function(e){
				$(this).css('cursor', 'default');
				clicked = false;
			});
			
			//Bind the mouse move
			var animateImageMovement = function() {				
				var movement_x = Math.round((target_x - current_x) / 5);
				var movement_y = Math.round((target_y - current_y) / 5);
				backgroundPos_x += movement_x;
				backgroundPos_y += movement_y;
				
				if (img_width > drag_div.width()) {
					if (backgroundPos_x < 0 - (img_width - drag_div.width())) backgroundPos_x = 0 - (img_width - drag_div.width());
					if (backgroundPos_x > 0) backgroundPos_x = 0;
				} else {
					if (backgroundPos_x < 0) backgroundPos_x = 0;
					if (backgroundPos_x > drag_div.width() - img_width) backgroundPos_x = drag_div.width() - img_width;
				}
				if (img_height > drag_div.height()) {
					if (backgroundPos_y < 0 - (img_height - drag_div.height())) backgroundPos_y = 0 - (img_height - drag_div.height());
					if (backgroundPos_y > 0) backgroundPos_y = 0;
				} else {
					if (backgroundPos_y < 0) backgroundPos_y = 0;
					if (backgroundPos_y > drag_div.height() - img_height) backgroundPos_y = drag_div.height() - img_height;
				}
				/*if (x < 0 - (img_width - trappableMargin)) x = 0 - (img_width - trappableMargin);
				if (x > drag_div.width() - trappableMargin) x = drag_div.width() - trappableMargin;
				if (y < 0 - (img_height - trappableMargin)) y = 0 - (img_height - trappableMargin);
				if (y > drag_div.height() - trappableMargin) y = drag_div.height() - trappableMargin;*/
				current_x += movement_x;
				current_y += movement_y;
				
				drag_div.css('background-position', backgroundPos_x + "px " + backgroundPos_y + "px");
				
				if (movement_x == 0 && movement_y == 0) {
					clearInterval(animationTimeout);
					animationTimeout = null;
				}
			}
			$(this).mousemove(function(e){
				if (clicked) { //as we only want this to work while they have clicked	
					target_x = Math.round(e.pageX - $(this).eq(0).offset().left);
					target_y = Math.round(e.pageY - $(this).eq(0).offset().top);
					if (animationTimeout == null) animationTimeout = setInterval(animateImageMovement, animationInterval);
				}
			});
			
		});
	}
});

/* Copyright (c) 2008 Kean Loong Tan http://www.gimiti.com/kltan
 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * Copyright notice and license must remain intact for legal use
 * jHelpertip
 * Version: 1.0 (Jun 2, 2008)
 * Requires: jQuery 1.2+
 */
(function($) {
		  
	$.fn.jHelperTip = function(options) {
		// merge users option with default options
		var opts = $.extend({}, $.fn.jHelperTip.defaults, options);
		
		// default actions
		// create a ttC is not found
		if ($(opts.ttC).length == 0)
			$('<div id="'+opts.ttC.slice(1)+'"></div>').css('opacity', '0').appendTo("body");
		
		// create a dC is not found
		if ($(opts.dC).length == 0)
			$('<div id="'+opts.dC.slice(1)+'"></div>').appendTo("body");
		
		if ($(opts.aC).length == 0)
			$('<div id="'+opts.aC.slice(1)+'"></div>').css('opacity', '0').appendTo("body");

		
		// initialize our tooltip and our data container and also the close box
		$(opts.ttC).add(opts.aC).css({
			position: "absolute",
			display: "inline"
		}).hide();
		
		$(opts.dC).hide();
		
		// close the tooltip box
		var closeBox = function(){
			var box;
			
			if (opts.source == "attribute" || opts.source == "text") {
				box = $(opts.aC);
				if (opts.source == "attribute" && box.html() != null && box.html() != '') {
					$(this).attr(opts.attrName, box.html());
				}
			} else {
				box = $(opts.ttC);
			}
			
			if (opts.fadeIn) {
				box.stop(true, false).animate({'opacity': '0'}, "fast", null, function() {
					box.hide().empty();
				});
			} else {
				box.hide().empty();
			}
		};
		
		$(".jHelperTipClose").bind("click", closeBox);
		$(opts.ttC).bind("mouseover",function(){
			$(opts.ttC).show();
			return false;
		});

		// the sources of getting data
		var getData = function(obj,e){
			switch (opts.source) {
				case "ajax":
					getPosition(e);
					$(opts.ttC).html('<div><img src="'+opts.loadingImg+'"/> '+opts.loadingText+'</div>').show();
					
					$.ajax({
						type: opts.type,
						url: opts.url,
						data: opts.data,
						success: function(msg){
							$(opts.ttC).html(msg);
							// reInitialize the close controller
							$(".jHelperTipClose").unbind("click", closeBox); 
							$(".jHelperTipClose").bind("click", closeBox);
						}
					});
					break;
				case "container":
					$(opts.ttC).show().empty();
					$(opts.dC).clone(true).show().appendTo(opts.ttC);
					break;
				case "attribute":
					$(opts.aC).html($(obj).attr(opts.attrName));
					$(obj).attr(opts.attrName, '');
					break;
				default:
					$(opts.aC).html(opts.text);
					break;
			}
		};
		
		// used to position the tooltip
		var getPosition = function (e){
			var top = e.pageY+opts.topOff;
			var left = e.pageX+opts.leftOff;
			var box;
			
			if (opts.source == "attribute" || opts.source == "text") {
				box = $(opts.aC);
			} else { 				
				box = $(opts.ttC);
			}
			
			if (opts.fadeIn) {
				box.css({
					top: top,
					left: left
				}).stop(true, false).show().animate({'opacity': opts.opacity}, "normal");
			} else {
				box.css({
					top: top,
					left: left,
					opacity: opts.opacity
				}).show();
			}
		};

		// just close tool tip when not needed usually trigger by anything outside out tooltip target
		if (opts.trigger == "hover") {
			$(this).bind("mouseover", function(e){
				e.preventDefault();
				getData(this, e);
				return false;
			});
			$(this).bind("mousemove", function(e){
				getPosition(e);
				return false;
			});
			
			$(this).bind("mouseout", function(e){
			    closeBox();
				return false;
			});
		}
		
		else if (opts.trigger == "click") {
			$(this).bind("click", function(e){
				getData(this, e);
				getPosition(e);
				$(document).bind("click", function(e){
					if (opts.autoClose) closeBox();
				});
				
				return false;
			});

		}
	};
	
	$.fn.jHelperTip.defaults = {
		trigger: "hover",
		fadeIn: true,
		topOff: 10,
		leftOff: 14,
		source: "container", /* attribute, container, ajax, text */
		attrName: '',
		text: '',
		ttC: "#jHelperTipContainer", /* tooltip Container*/
		dC: "#jHelperTipDataContainer", /* data Container */
		aC: "#jHelperTipAttrContainer", /* attr Container */
		opacity:  1.0,
		loadingImg: "ajax-loader.gif",
		loadingText: "Loading...",
		type: "GET", /* data can be inline or CSS selector */
		//url: '',
		//data: '',
		autoClose: true
	};
		
	
		  

})(jQuery);



/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
