// base JavaScript file for applejacks.com

// namespace

var Kellogg = {
	debug: false // set to true to enable console logging
};

// tracking functions
Kellogg.trackers = [];

Kellogg.track = function (str) {
	for (var i = 0, l = Kellogg.trackers.length; i < l; i++) {
		if (typeof Kellogg.trackers[i]._trackPageview === "function") {
			if (str) {
				Kellogg.trackers[i]._trackPageview(str);
			} else {
				Kellogg.trackers[i]._trackPageview();
			}
		}
	}
};

Kellogg.Nav = {
	$n: null,
	
	$w: null,
	
	$f: null,
	
	_flash: null,
	
	_status: "closed",
	
	init: function () {
		this.$n = $("#nav");
		this.$w = $("#wrapper");
		this.$f = $("#footer");
		$("#nav a").click(function (e) {
			Kellogg.Nav.toggle();
			e.stopPropagation();
			if (this.id === "nav-close") {
				e.preventDefault();
			}
		});
	},
	
	_show: function () {
		var that = this;
		this.$w.stop().animate({top: 0}, 1000, "easeOutBounce", function () {
			that._notify();
		});
		this.$f.stop().animate({marginTop: 10}, 1000, "easeOutBounce");
		this._status = "open";
	},
	
	_hide: function () {
		var that = this;
		this.$w.stop().animate({top: -225}, 1000, "easeInOutElastic", function () {
			that._notify();
		});
		this.$f.stop().animate({marginTop: -215}, 1000, "easeInOutElastic");
		this._status = "closed";
	},
	
	_notify: function () {
		this.$n.trigger("toggle.nav");
		try { // notify actionscript of state change
			this._flash = this._flash || $("#flashcontent")[0];
			this._flash.asNavToggle(this._status);
		} catch (err) {
			Kellogg.Util.log(err);
		}
	},
	
	toggle: function () {
		switch (this._status) {
			case "open":
				this._hide();
				break;
			case "closed":
				this._show();
				break;
		}
	}
};

// utility methods

Kellogg.Util = {
	
	log: function () {
		if (Kellogg.debug || window.location.hash.match(/debug/i)) {
			try {
				if (typeof loadFirebugConsole === "function" && typeof console === "undefined") {
					window.loadFirebugConsole();
				}
				console.log(arguments);
			} catch (err) {}
		}
	},
	
	stripTags: function (s) {
		return (s) ? s.replace(/<[^>]+>/g, "") : s;
	},
	
	query: (function () {
		var qString, queryStart, query, parts, bits, subbits, returnVals = {};
		qString = window.location.toString();
		queryStart = qString.indexOf('?');
		if (queryStart==-1) {
			return returnVals;
		}
		query = qString.substring(queryStart + 1, qString.length);
		parts = query.split("&");
		for (var i=0; i<parts.length; i++) {
			bits = parts[i].split("=");
			if (bits[1]) {
				subbits = bits[1].split("#");
				returnVals[bits[0].toLowerCase()] = subbits[0]; // query properties are lowercase!
			}
		}
		return returnVals;
	}) (), // self-invoking!
	
	cookie: function (name, value, options) { // adapted from http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/
	    if (typeof value != 'undefined') { // name and value given, set cookie
	        options = options || Kellogg.Util.cookie.options || {};
	        if (!isNaN(options)) { // options can be an object, or a number representing days to expiration
	        	options = {
	        		expires: options * 1 // coerce to number in case we've received a string from Flash
	        	};
	        }
	        if (value === null) {
	            value = '';
	            options.expires = -1;
	        }
	        var expires = '';
	        if (options.expires && (!isNaN(options.expires) || options.expires.toUTCString)) {
	            var date;
	            if (!isNaN(options.expires)) {
	                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
	        }
	        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, l = cookies.length; i < l; i++) {
	                var cookie = cookies[i].replace(/^\s+|\s+$/g, "");
	                // 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;
	    }
	},
	
	getPageSize: function () {
		var x = Math.max(document.documentElement.scrollWidth || document.body.scrollWidth, document.body.offsetWidth);
		var y = Math.max(document.documentElement.scrollHeight || document.body.scrollHeight, document.body.offsetHeight);
		return {"x": x, "y": y};
	},
	
	getViewportSize: function () {
		var x = self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
		var y = self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
		return {"x": x, "y": y};
	},
	
	getScrollOffset: function () {
		var x = self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
		var y = self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
		return {"x": x, "y": y};
	}, 
	
	getElemPosition: function (el) {
		var x = 0, y = 0;
		if (el.offsetParent) {
			do {
				x += el.offsetLeft;
				y += el.offsetTop;
			} while (el = el.offsetParent);
		}
		return {"x": x, "y": y};
	},
	
	highlight: function (el, classname) {
		classname = classname || "highlight";
		el.toggleClass(classname);
		return el; // chainable
	},
	
	popup: function(URL,windowName,width,height) {
		var w = screen.availWidth;
		var h = screen.availHeight;
		var leftPos = Math.round((w-width)/2);
		var topPos = Math.round((h-height)/2);
		var defaults = "scrollbars, resizable";
		var centerOnScreen = "top="+topPos+", left="+leftPos+", width="+width+", height="+height;
		var options = centerOnScreen + " ," + defaults;
		var msgWindow = window.open(URL,windowName,options);
		if(!msgWindow) {
			return false;
		} else {
			msgWindow.creator=self;
			msgWindow.focus();
		}
	  return true;
	}
	
};

// extending cookie functions to make it possible to set cookie options from Flash externalInterface

Kellogg.Util.cookie.options = {};

Kellogg.Util.cookie.setOption = function (name, value) {
	Kellogg.Util.cookie.options[name] = value;
};

Kellogg.Util.cookie.clearOptions = function () {
	Kellogg.Util.cookie.options = {};
};

// from http://gsgd.co.uk/sandbox/jquery/easing/
jQuery.extend( jQuery.easing, 
{
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	}
});