/* base JavaScript file for PopTarts Moms */
/* requires: jquery.js */


var Kellogg = {
	debug: false // set to true to enable console logging 
};


// utility methods

Kellogg.Util = {
	
	log: function () {
		if (Kellogg.debug || window.location.hash === "#debug") {
			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 || {};
	        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
	        }
	        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;
	},

	pushOption: function (el, t, v, dsel, sel) {
		el.options[el.options.length] = new Option(t, v, dsel, sel);
	},
	
	clearOptions: function (el, leavefirst) {
		var i = leavefirst ? 1 : 0;
		while (el.options.length > i) {
			el.options[el.options.length - 1] = null;
		}
	}
};


// 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();
			}
		}
	}
};


// from http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
jQuery.fn.hint = function () {
	return this.each(function () {
		// get jQuery version of 'this'
		var t = jQuery(this); 
		// get it once since it won't change
		var title = t.attr('title'); 
		// only apply logic if the element has the attribute
		if (title) { 
			// on blur, set value to title attr if text is blank
			t.blur(function () {
				if (t.val() == '') {
					t.val(title);
					t.addClass('blur');
				}
			});
			// on focus, set value to blank if current value 
			// matches title attr
			t.focus(function () {
				if (t.val() == title) {
					t.val('');
					t.removeClass('blur');
				}
			});
			
			// clear the pre-defined text when form is submitted
			t.parents('form:first()').submit(function() {
				if (t.val() == title) {
					t.val('');
					t.removeClass('blur');
				}
			});
			
			// now change all inputs to title
			t.blur();
		}
	});
};