﻿/*! Copyright © 2009 Great Wolf Resorts */
/**
 * GWR Namespace
 * Allows for easy namespace and provides common functions to set up namespace hierarchies
 */
(function() {
    // Define the GWR namespace
    var ns = window.GWR = window.GWR || {};

    var initFunctions = [];

    /**
    * Adds a function to the init list.
    * These functions will be called prior to OnDomReady.
    * Ideally immediately after the main content wrapper dom element is created.
    * @param fnInit
    *   Function to add to init list.
    * To execute initialization of all queued init functions, 
    * call this function with no parameters
    */
    ns.Init = function(fnInit) {
        // Queue the function to execute on content ready
        if (fnInit && $.isFunction(fnInit)) {
            initFunctions.push(fnInit);
        }
        else {
            for (var i in initFunctions) {
                initFunctions[i]();
            }
            ns.Log('GWR.Init() Completed');
        }
    }

    // Internal jquery element to bind events to
    var eventWatcher = $('<div></div>');

    /**
    * Binds a function to an event
    * @param {string} eventName 
    *   Event name that will trigger the function.
    * @param {function} fn
    *   Function to call when 
    */
    ns.Bind = function(eventName, fn) {
        eventWatcher.bind(eventName, fn);
    }

    /** 
    * Triggers an event.
    * @param {sting} eventName
    *   Event name to trigger
    * @param {object} data (optional)
    *   Data to pass to event handler functions
    */
    ns.Trigger = function(eventName, data) {
        GWR.Log('Trigger event: ' + eventName);
        eventWatcher.triggerHandler(eventName, data);
    }

    // Array to hold debug messages
    var log = [];

    /**
    * Logs a debug message.
    * Defaults output to the Firebug console log.
    * An error stack is used if Firebug is unavailable.
    */
    ns.Log = function(s) {
        if (window.console) {
            try {
                if (arguments.length > 1) {
                    console.log(arguments);
                }
                else {
                    console.log(s);
                }
            } catch (e) { }
        }
        else {
            log.push(s + '');
        }
    }

    /**
    * Displays the log in an alert dialog
    */
    ns.ShowLog = function() {
        alert(log.join('\n'));
    }

    ns.Try = function(fn) {
        try {
            fn();
        }
        catch (ex) {
            ns.Log('Error: ' + ex.message);
        }
    }

    // Associative array to store settings values
    var settings = {};

    /** 
    * Sets and gets options to make php/c# to javascript easier
    *
    * Examples:
    *   // Set "world" to "42"
    *   GWR.Settings("world", "42");
    *
    *   // Get config option "world" (returns "42")
    *   GWR.Settings("world");
    *
    *   // Set multiple option values
    *   GWR.Settings({config1: "AAA", config2: "BBB"});
    */
    ns.Settings = function(key, value) {
        if (typeof key == 'string') {
            if (value) {
                settings[key] = value;
            }
            return settings[key];
        }

        // Import object into 
        return $.extend(settings, key);
    }

    /**
    * Replaces all beta links with live links
    * Be careful when testing!!!!!
    */
    ns.BetaNavElements = function(live, beta) {
        $('a').each(function() {
            var link = $(this).attr('href');
            if (link && link.indexOf(live) > -1) {
                $(this).attr('href', link.replace(live, beta));
            }
        });
    }

    /**
    * Imports or creates a namespace
    * @param {string} namespace
    *   Namespace to create
    * @returns {object} Namespace object
    */
    ns.Namespace = function() {
        // Adapted from Yahoo YUI
        var a = arguments, o = null, i, j, d;
        for (i = 0; i < a.length; i = i + 1) {
            d = ("" + a[i]).split(".");
            o = ns;
            for (j = (d[0] == "GWR") ? 1 : 0; j < d.length; j = j + 1) {
                o[d[j]] = o[d[j]] || {};
                o = o[d[j]];
            }
        }

        return o;
    }
	
	var keywordToken = '#';
	
	/** 
	* Parses the current hash url and returns a collection of paramater values keyed by the paramater name
	*/ 
	var getHashParams = function() {
		var params = {};
		var hash = window.location.hash;
		if(hash && hash.length > 1) {
			// remove the # char if it's attached
			if(hash.substr(0,1) == keywordToken) {
				hash = hash.substring(1);
			}
			var split1 = hash.split('&');
			for(var i = 0; i < split1.length; i++) {
				var s = split1[i];
				var split2 = s.split('=');
				if(split2.length == 2) {
					params[split2[0]] = split2[1];
				}
				else {
					params[s] = keywordToken;
				}
			}
		}
		return params;
	}

	/** 
	* Gets a currently set hash parameter.
	*/
	var getHashParam = function(param) {
		var params = getHashParams();
		return params[param];
	}

	/** 
	* Sets a hash parameter.  Set to null to remove
	*/
	var setHashParam = function(param, value) {
		GWR.Log('set',arguments);
	
		// Retrieve current params
		var params = getHashParams();
		
		// Set new param value
		params[param] = value == '' ? keywordToken : value;

		GWR.Log(params);
		
		setHashString(params);
		
		return params;
	}

	// Sets a collection of params
	var setHashString = function(params,keywords) {	
		// create the hash string
		var pairs = [];
		for(var s in params) {
			var val = params[s];
			if(val && val != '' && val != keywordToken) {
				pairs.push(s + '=' + val);
			}
			else if(val == keywordToken) {
				pairs.push(s);
			}
		}
		
		// set the hash string
		window.location.hash = pairs.length > 0 ? pairs.join('&') : '#';
	}
	
	/**
	 * Sets and gets elements from the url #hash string
	 *
	 * http://www.greatwolf.com/dells/waterpark#Primary%20Content&Another Keyword&key1=val1&key2=val2
	 *
	 * GWR.Hash() - return all keys in the hash as an associative array including keywords
	 * GWR.Hash("foo", "bar") - set key "foo" to "bar" (ie. #foo=bar&foo2=bar2)
	 * GWR.Hash("foo", "") - set key "foo" to be a keyword (ie. #foo&foo2=bar2)
	 * GWR.Hash("foo", null) - unset key "foo" (ie. #foo2=bar2)
	 * GWR.Hash("foo") - get key "foo" (ie. returns "bar");
	 * GWR.Hash(obj) - set all keys in the object to the hash
	 * GWR.Hash(null) - clears all hash and values including keywords
	 */
	ns.Hash = function() {
		// return all keys in the hash as an associative array
		if(arguments.length <= 0) {
			return getHashParams();
		}
		
		var arg0 = arguments[0];
		
		// clears all hash and values including keywords
		if(arg0 == null) {
			window.location.hash = '';
		}
		
		// set all keys in the object to the hash
		if(typeof arg0 == "object") {
			var params = getHashParams();
			$.extend(params, arg0);
			setHashString(params);
			return params;
		}
		
		if(typeof arg0 == "string") {
			// get key "foo" (ie. returns "bar");
			if(arguments.length == 1) {
				return getHashParam(arg0);
			}
			
			var arg1 = arguments[1];
			
			// unset key "foo" (ie. #foo2=bar2)
			if(arg1 == null) {
				GWR.Log('unset', arg0);
				var params = getHashParams();
				for(var i in params) {
					if(i == arg0) {
						delete params[i];
					}
				}
				setHashString(params);
				return params;
			}
			
			// set key "foo" to "bar" (ie. #foo=bar&foo2=bar2)
			// set key "foo" to be a keyword (ie. #foo&foo2=bar2)
			else {
				return setHashParam(arg0, arg1);
			}
		}
		
	}
	
	/**
	 * Gets an array of hash keywords that are non-paired
	 * Spaces and %20 are converted to underscore
	 */
	ns.GetHashKeywords = function() {
		var keywords = [];
		var params = getHashParams();
		for(var i in params) {
			if(params[i] == keywordToken) {
				keywords.push(i);
			}
		}
		return keywords;
	}

	/**
	 * Removes all keywords form the hash
	 * Key/value pairs in the has are not affected
	 */
	ns.ClearHashKeywords = function() {
		var params = getHashParams();
		for(var i in params) {
			if(params[i] == keywordToken) {
				delete params[i];
			}
		}
		setHashString(params);
		return params;
	}
	
	var smush = function(s) {
		var removeChars = /[^\d^\w]/g;
		return $.trim(s).replace(removeChars,'');
	}
	
	/**
	 * Encodes a string to make it url hash friendly
	 */
	ns.HashString = function(s, hash) {
		if(s && s.length > 0) {
			s = smush(s);
			
			if(arguments.length == 2) {
				if(hash && hash.length > 0) {
					hash = smush(hash);
					return s.toUpperCase() == hash.toUpperCase();
				}
				return false;
			}
			
			return s;
		}
	}
})();
/**
 * Utility functions
 * Most of these are miscellaenous and may be put into their own files later on.
 */
(function() {

    // Define Util namespace
    var ns = GWR.Namespace("Util");

    // Define private variables
    var cornerHtml =
        '<div class="top-left"></div><div class="top-right"></div>' +
        '<div class="inside"><div class="inside-content"></div></div>' +
        '<div class="bottom-left"></div><div class="bottom-right"></div>';
    var clearDiv = '<div class="clear"></div>';
    var roundClass = 'rounded';

    /**
    * Wraps the element with HTML necessary to create rounded borders
    * Custom CSS and images are required
    * @param element
    *   jQuery object or selector
    * @return
    *   jQuery object
    */
    ns.MakeRound = function(element) {
        return $(element).each(function() {
            if (!$(this).hasClass(roundClass)) {
                // remove any script elements to prevent duplicate code processing
                $(this).find('script').remove();

                var children = $(this).contents();
                $(cornerHtml)
                    .appendTo(this)
                    .find('.inside-content')
                    .append(children)
                    .append(clearDiv);

                $(this).addClass(roundClass);
            }
        });
    }

    var dialogHtml =
		'<div class="dialog-container">' +
		'<table cellspacing="0" cellpadding="0">' +
		'<tr><td class="c1"></td><td class="c2"></td><td class="c3"></td><td class="c4"></td><td class="c5"></td></tr>' +
		'<tr class="top"><td colspan="2" class="TL X"></td><td class="T"></td><td colspan="2" class="TR X"></td></tr>' +
		'<tr class="middle"><td class="L"></td><td class="dialog-content" colspan="3"></td><td class="R"></td></tr>' +
		'<tr class="bottom"><td colspan="2" class="BL X"></td><td class="B"></td><td colspan="2" class="BR X"></td></tr>' +
		'</table></div>';

    var dialogClass = 'util-dialog';

    ns.MakeDialog = function(element) {
        return $(element).each(function() {
            if (!$(this).hasClass(dialogClass)) {
                // remove any script elements to prevent duplicate code processing
                $(this).find('script').remove();

                var children = $(this).contents();
                $(dialogHtml)
                    .appendTo(this)
                    .find('.dialog-content')
                    .append(children);

                $(this).addClass(dialogClass);
            }
        });
    }

    var modalDialog = null;


    var dialogThemes = {
        'util-dialog': {
            centerColumn: 60,
            contentWidth: 34,
            contentHeight: 85
        }
    };

    /**
    * Shows a modal dialog
    * @param {obj} element
    *   jQuery object, DOM element, or html string that will be made into a modal dialog.
    */
    ns.ShowModalDialog = function(element, width, height, theme) {
        modalDialog = $(element);

        // Assign default width and height if null or invalid
        if (isNaN(width) || width <= 0) {
            width = 710;
        }

        // Assign default theme if null or not defined
        if (!theme || !dialogThemes[theme]) {
            theme = 'util-dialog';
        }

        var myTheme = dialogThemes[theme];

        if (!modalDialog.hasClass(dialogClass)) {
            // This will add dialogClass to the element
            modalDialog = ns.MakeDialog(element);

            // Set the width of the center column
            // default = 650
            $('.c3', modalDialog).width(width - myTheme.centerColumn);

            // Set the width and height of the content
            // default = 676
            $('.dialog-content', modalDialog).width(width - myTheme.contentWidth)

            // default = 415
            if (isFinite(height) && height > 0) {
                $('.dialog-content', modalDialog).height(height - myTheme.contentHeight);
            }
        
            // Initialze the jQuery UI dialog   
            modalDialog.dialog({
                height: height,
                width: width,
                modal: true,
                resizable: false
            });
        }
        
        modalDialog.dialog('open');

        // Clicking the modal overlay will close the search dialog
        $('.ui-widget-overlay').one('click', function() {
            GWR.Util.HideModalDialog();
        });

        return modalDialog;
    }

    /**
     * Hides any modal dialogs that are currently displayed
     */
    ns.HideModalDialog = function() {
        if (modalDialog) {
            modalDialog.dialog('close');
        }
    }
	
	ns.PreloadImages = function(images) {
		if(images && images.length > 0) {
			for(var i = 0; i < images.length; i++) {
				img = new Image(1, 1); 
				img.src = images[i];
			}
		}
	}

    /**
     * Navigates the user to the splash page
     */
    GWR.ViewAllLocations = function() {
        // delete cookies 
        $.cookie("GWR_LOCNAME", null, { path: "/" });
        $.cookie("GWR_LOCATION", null, { path: "/" });
        $.cookie("GWR_LOCATION", null);

        window.location.href = "/";
    }

    /**
     * Validates an email address string and returns true if valid
     */
    ns.ValidEmailString = function(s) {
        // from http://xyfer.blogspot.com/2005/01/javascript-regexp-email-validator.html
        var emailRegex = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
        return emailRegex.test(s) === true;
    }

    /** 
     * Template Initialization
     * Set up rounded corners
     * Attach event handlers to page controls
     */
    GWR.Init(function() {
        //if ($('#body').hasClass('rounded-template')) {
            ns.MakeRound('#body .rounded-template');
        //}
    });
    
    // Define an unbindable event propagation stopper function
    ns.ReturnFalse = function() { return false; };
	
	/**
     * Adds and removes a classname on hover
     */
	$.fn.extend({
		hoverClass: function(className) {
			$(this).hover(function() {
				$(this).addClass(className);
			},
			function() {
				$(this).removeClass(className);
			});
		}
	});
})();

/**  
 * header.js
 * Header specific event handler functions 
 */
(function() {
    var ns = GWR.Namespace("Header");
	var Util = GWR.Namespace("Util");
	
    // Define an unbindable event propagation stopper function
    var returnFalse = function() { return false; };

    /**
    * Hides all dialogs that are in the main dialog group.
    * This makes certain that only one dialog is displayed at a time.
    * Items in this group will be hidden on mouseout.
    */
    ns.HideDialogs = function() {
        $('.gwr-dialog').hide()
			.removeClass('active');

        // Menu nav items
        $('#header .nav > ul > li').removeClass('active');
    }

    /**
    * Hides all dialogs that are in the seconardy dialog group.
    * This makes certain that only one dialog is displayed at a time.
    */
    ns.HideDialogs2 = function() {
        $('.gwr-dialog-2').hide()
			.removeClass('active');
    }

    /**
    * Dialog groups
    */
    $(function() {
        $('body').mouseover(function() {
            ns.HideDialogs();
        });

        $('body').click(function() {
            ns.HideDialogs();
            ns.HideDialogs2();
        });
    });
    /**
    * Logo Onclick event to the splash page
    */
     $(function() {
        $('#header .logo').click(function() {
            GWR.ViewAllLocations();
        });
    });
    /**
    * Returns true if a textbox still has its default value
    */
    var isTextboxDefaultValue = function(textbox) {
        return $(textbox).val() == $(textbox).attr('rel');
    }

    /**
    * Cookies
    */
    $(function() {
        // Set the location ID cookie
        if (ns.LocationId) {
            $.cookie("GWR_LOCATION", ns.LocationId, { expires: 30, path: "/" });
        }
        // set the correct res number in extened restool and footer
        var bookingPhone = ns.PhoneBooking;
        var locURL = ns.LocURL;
        var visitedRespath = $.cookie('VisitedRespath');
        if(visitedRespath){
           $('.restool-extended .phone').html('<div class="label text-bold">Reservations ' + bookingPhone + '</div>');
           $('.footer-phone-text li').html('<a href="' + locURL + '/guestservices/contact" rel="nofollow">' + bookingPhone + '</a>');
        }     
    });

    /** 
    * Change Location
    */
    GWR.Init(function() {
        // Event handler for change location click event
        $('#header .location').click(function() {
            var locationDiv = $('#change-location');

            // Apply rounded corners to the popup div
            var changeLocationDiv = GWR.Util.MakeDialog('#change-location');

            if (!changeLocationDiv.hasClass('active')) {
                // Hide all other dialogs
                ns.HideDialogs();

                changeLocationDiv.addClass('active');

                if (!changeLocationDiv.hasClass('gwr-dialog')) {
                    // Add odd class to every other list item
                    $('#change-location li:even').addClass('odd');
                }

                // Attach event to prevent event propagation
                $('#header,#change-location').mouseover(returnFalse);
				
				// Remove dialog class so the dialog does not hide prematurely
                changeLocationDiv.removeClass('gwr-dialog');
				
				// Clear fire-once events set on body.
				$('body').mouseover();

                // Use slide down effect to show the change location dropdown
                changeLocationDiv.slideDown({
                    easing: 'easeOutQuad',
                    duration: 600,
                    complete: function() {
						setTimeout(function() {			
							// Add event handler to body to hide the dropdown when user's mouse leaves the div
							$('body').one('click mouseover', function() {
								changeLocationDiv.removeClass('active')
									.slideUp('fast');
								$('#header,#change-location').unbind('mouseover', returnFalse);
							});

							// Readd the dialog class to allow mouseout to close the dialog
							changeLocationDiv.addClass('gwr-dialog');
						}, 1000);
                    }
                });

                // Get the location label to calculate offset position
                var label = $('#header .location');

                var labelOffset = label.offset();
                var labelHeight = label.height();

                // Append the dialog to the very bottom of the DOM to fix IE layer order
                locationDiv.appendTo('body');

                locationDiv.css({
                    'position': 'absolute',
                    'top': (labelOffset.top + labelHeight - 17) + 'px',
                    'left': (labelOffset.left - 24) + 'px',
                    'right': 'auto',
                    'bottom': 'auto'
                });
            }
            else {
                changeLocationDiv.removeClass('active')
					.slideUp('fast');
                $('#header,#change-location').unbind('mouseover', returnFalse);
            }
            return false;
        })
        .hover(function() {
            $(this).addClass('location-hover');
        },
		function() {
		    $(this).removeClass('location-hover');
		});

        // Change location click event
        $('#change-location li').click(function() {
            $('#change-location li').removeClass('selected');
            $(this).addClass('selected');
            $('#header .location .label').html($(this).text());
            $('#change-location').hide();
            var navElement = $('a', this);
            if (navElement.length > 0) {
                window.location.href = navElement.attr('href');
                return false;
            }
        })

        .hover(function() {
            $(this).addClass('hover');
        },
		function() {
		    $(this).removeClass('hover');
		});
    });

    /**
    * Navigation Menu and Sub-Menus
    * Site Map, Breadcrumbs
    */
    GWR.Init(function() {
        // Clone the navigation list
        var navTree = $('#header .nav').html();

        $('#header .breadcrumb a').click(function() {
            window.location = $(this).attr('href');
            return false;
        });

        // Breadcrumbs onclick
        $('#header .breadcrumb').click(function() {
            // Create a new div to put in the modal dialog
            var siteMap = $('<div class="sitemap"></div>');
            siteMap.append('<div class="sitemap-title title-text-large">Site Map</div>');

            // Append to our new div
            siteMap.append(navTree);

            // Save a list of the primary menus
            var topMenus = siteMap.children('ul').children('li');

            // Add font class
            topMenus.addClass('menu-text primary');

            // Wrap the menus with a div to help with styles
            siteMap.wrapInner('<div class="sitemap-content"></div>');

            // Display the tree
            GWR.Util.ShowModalDialog(siteMap, 710, 500);

            // Get the height of the first column
            var firstColHeight = 0;
            var secondCol = false;
            topMenus.each(function() {
                if (secondCol) {
                    $(this).addClass('col2');
                }
                else if (firstColHeight > 250) {
                    // Set second column position
                    $(this).addClass('coltop col2')
						.css('margin-top', '-' + firstColHeight + 'px');

                    secondCol = true;
                }

                firstColHeight += $(this).outerHeight(true);
                GWR.Log(firstColHeight);
            });
        });

        // Prevent event propagation on nav items
        $('#header .nav').mouseover(returnFalse);
        $('#header .nav li.menu').mouseover(returnFalse);

        // Mouseover event on primary menu items without submenus to hide any showing
        // submenus to make interface feel smoother
        $('#header .nav > ul').children('li.leaf').mouseover(function() {
            // Hide any dialogs that are showing
            ns.HideDialogs();
            ns.HideDialogs2();

            $(this).addClass('active');
        });

        // Hover on a menu item that has associated dropdown sub menu
        $('#header .nav li.expanded').mouseover(function() {
            // Hide any dialogs that are showing
            ns.HideDialogs();
            ns.HideDialogs2();

            var subMenuDialog = $('.submenu', this);

            if (subMenuDialog.length < 1) {
                var positionLeft = $(this).position().left;

                // Show this sub menu
                var subMenu = $('ul.menu', this)
					.wrap('<div class="submenu"></div>')
					.show();

                var subMenuDialog = GWR.Util.MakeDialog(subMenu.parent());
                subMenuDialog
					.css('left', positionLeft - 17)
					.mouseover(returnFalse)
					.addClass('gwr-dialog')
					.show();

                $('li:first', subMenu).addClass('first');
                $('li:even', subMenu).addClass('odd');

                // Make giftcards pop in new window
                $('li a', subMenu).each(function() {
                    if ($(this).attr('href').indexOf('/giftcards') > 0) {
                        $(this).attr('target', '_blank');
                    }
                });
            }

            subMenuDialog.show();

            $(this).addClass('active');

            return false;
        });

        // Mouse hover event handling to highlight the individual submenu items
        $('#header .nav .menu li').hover(
			function() {
			    $(this).addClass('hover');
			},
            function() {
                $(this).removeClass('hover');
            }
		)

        // Click the child navigation element if the subnav element is clicked
        .click(function() {
            var navElement = $('a', this);
            if (navElement.length > 0) {
                var link = navElement.attr('href');

                // Check for target (gift cards)
                if (navElement.attr('target') == '_blank') {
                    window.open(link,
						'_blank',
						'top=10, left=350, height=700, width=900, location=no, toolbar=no, menubar=no, resizable=yes, scrollbars=yes'
					);
                }
                else {
                    window.location.href = link;
                }

                return false;
            }
        });
        // click for very top giftcards link
        $('#header .links .header-links-text .first').click(function(){
             var navElement = $('a', this);
            if (navElement.length > 0) {
                var link = navElement.attr('href');

                // Check for target (gift cards)
                if (navElement.attr('target') == '_blank') {
                    window.open(link,
						'_blank',
						'top=10, left=350, height=700, width=900, location=no, toolbar=no, menubar=no, resizable=yes, scrollbars=yes'
					);
                }
                else {
                    window.location.href = link;
                }

                return false;
            }       
        });
    })

    /** 
    * Share This Page
    */
    $(function() {
        // Event handler for change location click event
        $('#header .link-share-this-page').click(function() {
            // Apply rounded corners to the popup div
            var div = $('#header > .share-this-page')
                .addClass('gwr-dialog-2');

            GWR.Util.MakeDialog(div);

            if (div.is(':hidden')) {
                // Hide all other dialogs
                ns.HideDialogs();

                // Hide share email divs
                $('.share-email-text,.share-email-confirm,.share-email-wait', '#header').hide();
                $('#header .share-this-page .email').removeClass('selected');

                // Add odd class to every other list item
                $('#header .share-this-page li:even').addClass('odd');

                // Attach event to prevent event propagation
                $('#header,#header .link-share-this-page').mouseover(returnFalse);

                // Use slide down effect to show the change location dropdown
                div.slideDown({
                    easing: 'easeOutQuad',
                    duration: 600,
                    complete: function() {
                        // Add event handler to body to hide the dropdown when user's mouse leaves the div
                        $('body').one('click', function() {
                            div.slideUp('fast');
                        });
                    }
                });
            }
            else {
                div.slideUp('fast');
                $('#header,#header .link-share-this-page').unbind('mouseover', returnFalse);
            }
            return false;
        });

        /**
        * Displays the email textbox for share this page submit functionality.
        */
        $('#header .share-this-page .email').click(function() {
            // Hide any email related divs
            $('.share-email-confirm,.share-email-wait', '#header').hide();

            // Show the div with the email input textbox
            $('#header .share-email-text').slideDown();

            // Add class to keep the highlight on the "Email" item
            $(this).addClass('selected');
            return false;
        });

        $('#share-email-close').click(function() {
            $('.share-email-text,.share-email-confirm,.share-email-wait', '#header').hide();
            $('#header .share-this-page .email').removeClass('selected');
            return false;
        });

        $('#header .send-button').click(function() {
            // get the email address from the textbox
            var email = $('#share-email-input').val();

            if (email && email != '' && GWR.Util.ValidEmailString(email)) {
                GWR.Log('valid email address, sending address to server: ' + email);

                $.ajax({
                    data: {
                        email: email
                    },
                    dataType: 'text',
                    type: 'post',
                    url: '/share-email',
                    success: function(text) {
                        // Hide the wait dialog
                        $('#header .share-email-wait').hide();

                        if (text == 'success') {
                            // Show the success dialog
                            $('#header .share-email-confirm').show();
                        }
                        else {
                            alert('An error has occured.  Please check the email address and try again.');
                            $('#header .share-email-text').show();
                        }
                    }
                });

                $('#header .share-email-text').hide();
                $('#header .share-email-wait').show();
            }
            else {
                GWR.Log('Invalid email address: ' + email);
            }
            return false;
        });

        $('#header .share-this-page .facebook').click(function() {
            var referUrl = encodeURI('http://www.facebook.com/share.php?u=');
            var thisPage = encodeURI(window.location.href);

            window.open(referUrl + thisPage, '_blank');

            return false;
        });

        $('#header .share-this-page .myspace').click(function() {
            var referUrl = encodeURI('http://www.myspace.com/index.cfm?fuseaction=postto&');
            //post title
            referUrl += 't='.encodeURI('Great Wolf Lodge');
            // post URL
            '&u='.encodeURI(window.location.href);
            window.open(referUrl, '_blank');

            return false;
        });
        // Share this page click event
        $('#header .share-this-page li').click(function() {
            var navElement = $('a', this);
            if (navElement.length > 0) {
                var link = navElement.attr('href');
                if (link && link.substring(0, 4) == 'http') {
                    // open the link in a new window
                    window.open(link, '_blank');
                    return false;
                }
            }
        })

        .hover(function() {
            $('#header .share-this-page li').removeClass('hover');
            $(this).addClass('hover');
        },
        function() {
            $(this).removeClass('hover');
        });
    });

    /** 
    * FAQ Dialog
    */
    $(function() {
		var faqDialog = $('#gwr-faq-dialog');
		
		if(faqDialog.length > 0) {
			// Show FAQ Dialog
			$('#header .faq-link a').click(function() {
				GWR.Util.ShowModalDialog('#gwr-faq-dialog', 650, 500);
				$('#gwr-faq-dialog input.search-textbox').blur();
				// Prevent event propagation
				return false;
			});

			/**
			* FAQ dialog close button click event handler
			*/
			$('#gwr-faq-dialog .gwr-faq-header .top-close').live('click', function() {
				GWR.Util.HideModalDialog();
			});
		}
    });

    /**
    * Show the extended restool dialog
    */
    var showRestoolExtend = function() {

        var div = $('#header .restool-extended');

        ns.HideDialogs();

        if (!div.hasClass('active')) {

            // Add class to signify that this dialog is displayed
            div.addClass('active');

            // Check for dialog group class to apply one-time edits
            if (!div.hasClass('gwr-dialog-2')) {
                // Add this dialog to the main dialog group
                div.addClass('gwr-dialog-2');

                // Apply rounded corners to the popup div
                var div = GWR.Util.MakeRound('#header .restool-extended');

                // Attach events to prevent event propagation
                $('#header .restool, #header .restool-extended')
					.click(returnFalse)
					.mouseover(returnFalse);
            }

            // Show the restool extended dialog
            div.show();
        }
    }

    /**
    * Reservation Tool
    */
    GWR.Init(function() {
        // Variable to keep track of errors with the reservation date or location
        var restoolError = false;

        // "Go" reservation submit button click event handler
        $('#header .submit').click(function() {
            var reservationUrl = null;
            var navElement = $(this).parent('a');

            // Detect if the parent element is an "A" element
            if (navElement.length > 0) {
                // if it is, then get the location attribute
                reservationUrl = navElement.attr('href');
            }

            // Use a default URL if location was not set
            if (!reservationUrl || reservationUrl == '') {
                reservationUrl = 'https://reservations.greatwolf.com/';
            }

            // Define a collection to contain the query string parameters
            var params = [];

            // Hide any error messages
            $('#header .restool-error').hide();

            // Check if location control exists.
            // If it does, we will do error checking.
            var locationControl = $('#restool-location');
            if (locationControl.length > 0) {
                var hotelCode = locationControl.val();
                if (!hotelCode || hotelCode == '') {
                    restoolError = true;
                    $('#header .restool-error').show();
                    $('#header .restool-extended').hide()
						.removeClass('active');
                    return false;
                }
                else {
                    params.push('resHotel=' + hotelCode);
                }
            }

            // Get the arrival, departure, adult, child and offer codes
            // Arrival Date
            var arrivalDateText = $('#restool-arrival').val();
            var defaultArrivalText = $('#restool-arrival').attr('rel');
            if (arrivalDateText && arrivalDateText != '' && arrivalDateText != defaultArrivalText) {
                params.push('resArrival=' + arrivalDateText.replace(' ', ''));
            }

            var departureDateText = $('#restool-departure').val();
            var defaultDepartureText = $('#restool-departure').attr('rel');
            if (departureDateText && departureDateText != '' && departureDateText != defaultDepartureText) {
                params.push('resDeparture=' + departureDateText.replace(' ', ''));
            }

            var adultText = $('#restool-adults').val();
            if (adultText && adultText != '') {
                params.push('resAdult=' + adultText);
            }

            var childText = $('#restool-children').val();
            if (childText && childText != '') {
                params.push('resChild=' + childText);
            }

            var offerText = $('#restool-offer-code').val();
            if (offerText && offerText != '') {
                params.push('resPromo=' + offerText);
            }

            var queryDelimiter = '';
            var queryString = '';

            // Check if parameters exist
            if (params.length > 0) {
                // Join the paramters with '&' to follow HTML query standards
                queryString = params.join('&');

                // Specifiy the token to use between the URL and query string
                queryDelimiter = reservationUrl.indexOf('?') >= 0 ? '&' : '?';
            }

            // Navigate the user to the URL
            window.location = reservationUrl + queryDelimiter + queryString;

            // Prevent a double navigation
            return false;
        });

        // Add event to the restool location dropdown box to hide error messages
        $('#restool-location').change(function() {
            if (restoolError) {
                var val = $(this).val();
                if (!val || val == '') {
                    $('#header .restool-error').show();
                }
                else {
                    $('#header .restool-error').hide();
                    restoolError = false;
                }
            }
        });
    });

    /**
    * Restool Datepickers
    */
    $(function() {
        var today = new Date(),
            tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);

        var restoolArrival = $('#restool-arrival'),
            restoolDeparture = $('#restool-departure');

        var dateFormat = 'm/d/yy';

        // Keep track of the currently displayed datepicker
        var currentDatepicker = null;

        // Define common datepicker options
        var options = {
            changeFirstDay: false,
            changeMonth: false,
            changeYear: false,
            showAnim: 'fadeIn',
            dayNamesMin: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
            hideIfNoPrevNext: true,
            showOn: 'none',
            prevText: '',
            nextText: '',
            buttonImageOnly: true,
            dateFormat: dateFormat,
            onClose: function() {
                currentDatepicker = null;
                $.datepicker.dpDiv.hide();
            },
            beforeShow: function() {
                $.datepicker.dpDiv.css('margin-top', '3px');

                // Prevent datepicker from propagating click events
                $.datepicker.dpDiv.click(returnFalse);
                $.datepicker.dpDiv.show();
            }
        }

        // Arrival date was selected by a datepicker
        restoolArrival.datepicker($.extend({
            minDate: today,
            onSelect: function(txt) {
                var d1 = new Date(txt);
                var d2 = new Date(restoolDeparture.val());

                // Calculate a day 5 days after the selected date
                var d3 = new Date(d1);
                d3.setDate(d3.getDate() + 5);

                if (d2 == null || isNaN(d2) || d2 <= d1 || d2 > d3) {
                    d1.setDate(d1.getDate() + 1);
                    restoolDeparture.val($.datepicker.formatDate(dateFormat, d1))
                        .addClass('textbox-text');
                }

                $(this).addClass('textbox-text');

                showRestoolExtend();

                $(this).datepicker('hide');
                $.datepicker.dpDiv.hide();
                currentDatepicker = null;
            }
        },
			options));

        // Departure date was selected by a datepicker
        restoolDeparture.datepicker($.extend({
            minDate: tomorrow,
            onSelect: function(txt) {
                var d1 = new Date(restoolArrival.val());
                var d2 = new Date(txt);

                // Calculate a day 5 days before the selected date
                var d3 = new Date(d2);
                d3.setDate(d3.getDate() - 5);

                if (d1 == null || isNaN(d1) || d2 <= d1 || d1 < d3) {
                    d2.setDate(d2.getDate() - 1);
                    restoolArrival.val($.datepicker.formatDate(dateFormat, d2))
                        .addClass('textbox-text');
                }

                $(this).addClass('textbox-text');

                showRestoolExtend();

                $(this).datepicker('hide');
                $.datepicker.dpDiv.hide();

            }
        },
			options));

        var showArrivalDatepicker = function() {
            if (currentDatepicker == restoolArrival) {
                restoolArrival.datepicker('hide');
            }
            else {
                restoolArrival.datepicker('show');
                currentDatepicker = restoolArrival;
            }
        }

        var showDepartureDatepicker = function() {
            if (currentDatepicker == restoolDeparture) {
                restoolDeparture.datepicker('hide');
            }
            else {
                restoolDeparture.datepicker('show');
                currentDatepicker = restoolDeparture;
            }
        }

        // Add click event handlers to the datepicker icons
        $('#header .restool .arrival-datepicker').mousedown(function() {
            showArrivalDatepicker();
            return false;
        });

        $('#header .restool .departure-datepicker').mousedown(function() {
            showDepartureDatepicker();
            return false;
        });

        // Attach focus events to the arrival and departure textboxes
        // and check if we should show a datepicker or the extended restool
        restoolArrival.click(function() {
            if (isTextboxDefaultValue(restoolArrival) || isTextboxDefaultValue(restoolDeparture)) {
                currentDatepicker = null;
                showArrivalDatepicker();
            }
            else {
                showRestoolExtend();
                restoolArrival.datepicker('hide');
            }

            return false;
        });

        restoolDeparture.click(function() {
            if (isTextboxDefaultValue(restoolArrival) || isTextboxDefaultValue(restoolDeparture)) {
                currentDatepicker = null;
                showDepartureDatepicker();
            }
            else {
                showRestoolExtend();
                restoolDeparture.datepicker('hide');
            }

            return false;
        });
    });

    /**
    * Textbox initial values
    */
    GWR.Init(function() {
        // Check for default values in search boxes
        $('#header input:text').each(function() {
            if (!isTextboxDefaultValue(this)) {
                // Apply class to remove hint dimming
                $(this).addClass('textbox-text');
            }
        });
    });

    /**
    * Textbox keypress event handling
    */
    $(function() {
        // Keyup event makes the text color darker by toggling a CSS class 
        // when the text has changed from the default value
        $('#header input:text').keyup(function(e) {
            // Add or remove the CSS class that will make the text a darker color
            $(this).toggleClass('textbox-text', !isTextboxDefaultValue(this));
        })

        // Blur event handler resets the control to the default value if the text is cleared
        .blur(function() {
            if ($(this).val() == '' && $(this).attr('rel')) {
                $(this).val($(this).attr('rel'))
                       .removeClass('textbox-text');
            }
        })

        // Focus event handler to clear text
        .focus(function() {
            // Check for default value
            if (!isTextboxDefaultValue(this)) {
                // Highlights all text in the textbox
                this.select();
            }
            else {
                // Clear text and switch classes
                $(this).val('')

                // Apply class to remove hint dimming
                    .addClass('textbox-text')
					.click();
            }
        });
    });
 
 

    /**
    * Google Search API
    */
    $(function() {
        // Google's web searcher object
        var webSearch = null;

        /**
        * Create pager links
        * @param results
        *   Results container DOM element or jQuery selector
        */
        function addPaginationLinks(results) {

            if (webSearch && webSearch.cursor) {
                var cursor = webSearch.cursor;

                // Get total number of pages
                var numPages = cursor.pages.length;

                if (numPages > 1) {
                    var currentPage = cursor.currentPageIndex;

                    // Create the pager
                    var pagesDiv = $('<div class="search-pager text"></div>');

                    for (var i = 0; i < numPages; i++) {

                        var page = cursor.pages[i];

                        // If we are on the current page, create a label
                        if (currentPage == i) {
                            $('<span class="pager-label">' + page.label + '</span>')
								.appendTo(pagesDiv);
                        }

                        // If we are not on the current page, create a link to the page
                        else {

                            // Create a navigation element
                            $('<a class="pager-link" href="javascript:;">' + page.label + '</a>')

                            // Save current page number
								.data('page', i)

                            // Append to pager element
								.appendTo(pagesDiv)

                            // Attach click event handler
								.click(function() {
								    GWR.Log('page ' + $(this).data('page'));
								    webSearch.gotoPage($(this).data('page'));
								    return false;
								});
                        }
                    }
                }

                // append pager to results container
                $(results).append(pagesDiv);
            }
        }

        var searchComplete = function() {
            // Check that we got results
            if (webSearch && webSearch.results && webSearch.results.length > 0) {

                GWR.Log(webSearch);

                // Clear out the results container
                var results = $('#gwr-search-results .results-content').empty()
					.scrollTop(0);

                for (var i = 0; i < webSearch.results.length; i++) {
                    var result = webSearch.results[i];

                    // clone the .html node from the result
                    var node = result.html.cloneNode(true);

                    // append to the results list
                    results.append(node);
                }

                // Now add the paging links so the user can see more results.
                addPaginationLinks(results);
            }

            // No results
            else {
                $('#gwr-search-results .results-content').html(
					'<div class="loading text">No results found.  Please try a different search phrase.</div>'
				);
            }
        }

        /**
        * Gets a google web search compatible url string to limit search to
        * current property.
        */
        var getSiteRestriction = function() {
            var baseUrl = "www.greatwolf.com";

            // Check if location website path is set for reservation path
            var locationPath = GWR.Settings("LocationWebsitePath");
            if (locationPath) {
                return baseUrl + "/" + locationPath;
            }

            var splitLocation = window.location.href.split('/');

            if (splitLocation.length > 3) {
                return baseUrl + "/" + splitLocation[3];
            }
            else {
                return baseUrl;
            }
        }

        /** 
        * Uses the Google AJAX Search API to perform a search query
        * http://code.google.com/apis/ajaxsearch/documentation/reference.html
        * http://code.google.com/apis/ajaxsearch/terms.html
        */
        var doSearch = function() {
            if (webSearch == null) {
                // Attach Google branding
                google.search.Search.getBranding(document.getElementById('powered-by-google'));

                // Our WebSearch instance.
                webSearch = new google.search.WebSearch();

                // Restrict to greatwolf.com
                webSearch.setSiteRestriction(getSiteRestriction());

                // Here we set a callback so that anytime a search is executed, it will call
                // the searchComplete function and pass it our ImageSearch searcher.
                // When a search completes, our ImageSearch object is automatically
                // populated with the results.
                webSearch.setSearchCompleteCallback(this, searchComplete, null);

                // request a large number of results (typically 8 results)
                //webSearch.setResultSetSize(google.search.Search.LARGE_RESULTSET);

                // set the target frame
                webSearch.setLinkTarget(google.search.Search.LINK_TARGET_PARENT);

                googleSearchIsLoaded = true;
            }

            // Get the search phrase from the input control
            var searchPhrase = $('#header .search input.search-textbox').val();

            // Execute the search
            webSearch.execute(searchPhrase);
        }

        var googleApiKey = "ABQIAAAAzRQYhFSZRl-WhWFr1AseOhRYANLVubwGylPlv5tTEY_P69MrkBSYL3dpMMMcdh86bHiiN6y2rL53ig";
        var googleLoaderUrl = "http://www.google.com/jsapi?key=" + googleApiKey;
        var googleApiLoaded = false;

        // Event handler for search textbox keypress to detect enter key
        $('#header .search input.search-textbox').keyup(function(e) {
            // Check for default value
            var val = $(this).val();
            var highlight = val != $(this).attr('rel');

            // Check if Enter button was pressed
            if (e.which == 13 && highlight && val != '') {
                // Perform search
                GWR.Log('Keyup Event: Search: ' + val);

                $('#gwr-search-results .results-content').html(
					'<div class="loading text">Loading, please wait...</div>'
				);

                // Show the modal dialog
                GWR.Util.ShowModalDialog('#gwr-search-results');

                // Checks if the search module is loaded
                var search = function() {
                    if (webSearch) {
                        doSearch();
                    }
                    else {
                        // Initialze the search module
                        google.load('search', '1', { "callback": doSearch });
                    }
                }

                // Check if the Google API is loaded
                if (googleApiLoaded) {
                    search();
                }
                else {
                    $.getScript(googleLoaderUrl, function() {
                        googleApiLoaded = true;
                        search();
                    });
                }
            }
        });

        // Search results - Close Button
        $('#gwr-search-results .top-close').live('click', function() {
            GWR.Util.HideModalDialog();
        });
        // Search results - Close Button
        $('#gwr-search-results .dialog-cancel-button').live('click', function() {
            GWR.Util.HideModalDialog();
        });

        // Event handler for FAQ search textbox keypress to detect enter key
        $('#gwr-faq-dialog input.search-textbox').keyup(function(e) {
            // Check for default value
            var val = $(this).val();
            var highlight = val != $(this).attr('rel');

            // Check if Enter button was pressed
            if (e.which == 13 && highlight && val != '') {
                // Perform search
                //GWR.Log('Keyup Event: FAQ Search: ' + val);
                 $('#gwr-faq-dialog .gwr-faq-content').html(
					'<div class="loading text">Searching FAQs, please wait...</div>'
				); 
                // retrieve FAQS related to the search for the location
                 var data = {};
                 data.SearchTerm = val;
                 data.LocationID = ns.LocationId;
                 $.ajax({
                   type: "POST",
                   url: "/faq-items",
                   data: data,
                   dataType:'json',
                   success: function(json){
                        var faqs = '';
                        /* faq url for "More FAQs" link passed so we don't have to try and derive here
                         * The link only appears if the json object is populated
                         */
                        var faqUrl = '';
                        for(key in json) {    
                            var question = json[key].Question;    
                            var answer = json[key].Answer;
                            if (faqUrl.length == 0){
                                faqUrl = json[key].FAQUrl;
                            }
                            faqs += '<div class="faq-item">';
                            faqs += '<div class="faq-question text-large">' + question + '</div>';
                            faqs += '<div class="faq-answer text">' + answer + '</div>';
                            faqs += '</div>';   
                            
                        }
                        if(faqs.length > 0){
                            faqs += '<div class="more-link text">';
                            faqs += '<a href="' + faqUrl + '" class="text">More FAQs</a>';
                            faqs += '</div>';
                            $('#gwr-faq-dialog .gwr-faq-content').html(faqs);  
                        }
                        else{
                            $('#gwr-faq-dialog .gwr-faq-content').html(
                                '<div class="text-bold">Your search returned 0 results.  Please try again</div>'
                            ); 
                        }   
                                               
                   }
                 });
            }
        }); 
        /** Feedback Link 
          * Maintence item - They want the link to disappear if the window is resized small enough to
          * where the link goes over the top of any content.  I forgot they're reasoning for this.
          * Want it to open without toolbars etc, so attaching an onclick intead of just using the link
        ***/
        $(window).bind('resize', function () { 
            var windowWidth = $(window).width();
            if($(window).width() < 1080) {
                $('#feedback-icon').hide();
            }
            else{
                $('#feedback-icon').show();
            }
        });
        $('#feedback-icon a').click(function() {
            window.open($(this).attr('href'),
                '_blank',
                'top=10, left=350, height=700, width=900, location=no, toolbar=no, menubar=no, resizable=yes, scrollbars=yes'
            );            
            return false;
        });        

    });
    
})();

/**
 * footer.js
 * Footer specific event handler functions
 */
(function() {
    // Define local namespace
    var ns = GWR.Namespace("Footer");

    /**
     * Set up rounded corners
     */
    GWR.Init(function() {
		// Round the footer elements
        GWR.Util.MakeRound('#footer .links');
    });
		
	/**
	 * Preferred Partners
	 */
	$(function() {
		// These parameters are defined in the header by includes/partners.inc
		var flashFile = ns.PartnerFlash;
		var images = ns.PartnerImages;
		var sleep = ns.PartnerSleep * 1000;
		var fade = ns.PartnerFade * 1000;
				
		// Display a flash file if it was defined
		if (flashFile && flashFile != "") {
			$('#footer .partners').html('<div id="partner-flash"></div>');
			
			//flashvars, params and attributes set to false
			swfobject.embedSWF(flashFile, 'partner-flash', '305', '100', 
				'9.0.0', "expressInstall.swf", false, {wmode:"transparent"});
		}
		
		// Start the cross-fade javascript slide show if there is more than one image defined
		else if (images && images.length > 0) {
			// Current image cursor starts on second image
			var currentImage = 1;
			var timeout = null;
			
			// Displays an image
			var displayImage = function() {
				var image = images[currentImage];
				
				if(image) {
					$('#footer-partners img.current').fadeOut(fade);
					
					$('#footer-partners img.next')
						.fadeIn(fade, function() {
							$('#footer-partners img.current')
								.attr('src', image.FilePath)
								.show();
						
							// Increment the current image cursor
							if(++currentImage >= images.length) {
								currentImage = 0;
							}
							
							image = images[currentImage];
						
							$('#footer-partners img.next')
								.hide()
								.attr('src', image.FilePath);
								
							timeout = setTimeout(displayImage, sleep);
						});
				}
			}
			
			if(images.length > 1) {
				timeout = setTimeout(displayImage, sleep + 5000);
			}
		}
	});

})();
/**
 * 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.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
        }
        // CAUTION: 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;
    }
};
