/**
 * base JavaScript for Pull-Ups.com
 * requires: jquery.js
 */
 
// global page init functions

$(document).ready(function () {
	var log = KC.Util.log, cookie = KC.Util.cookie;
	
	// form hints
	$("input.hint").hint();
	
	// newsletter signup validation
	$("#newsletter-signup form").bind("submit", KC.Form.validateNewsletterSidebar);
	
	// collapse newsletter form?
	if (cookie("newsletter")) {
		var form = $("#newsletter-signup form").hide();
		var thanks = $('<p>Thank you. You are signed up for the newsletter.</p><p><a href="http://www.kimberly-clark.com/registration_update/index.asp?SiteCode=PUL" target="_blank">Update your profile</a></p><p class="signup">Not ' + cookie("newsletter") + '?<br /><a href="#" id="link-signup">Sign up here</a>.<br /><a href="#" id="link-logout">Log out</a></p>').insertBefore(form);
		$("#link-signup").bind("click", function () {
			cookie("newsletter", null, {path: "/"});
			log(cookie("newsletter"));
			thanks.hide();
			form.show();
			return false;
		});
		$("#link-logout").bind("click", function () {
			cookie("newsletter", null, {path: "/"});
			log(cookie("newsletter"));
			thanks.hide();
			form.show();
			return false;
		});
	}
	
	// init dropdown menus
	KC.menus = $("#nav-main > ul > li").hover(function () {
		clearTimeout(KC.menutimer);
		// hide other menus if visible
		$(KC.menus).not(this).each(function () {
			//if ($.data(this, "visible")) {
				var $this = $(this), that = this;
				$this.children("ul").slideUp(150, function () {
					$this.css("overflow", "hidden");
					$.data(that, "visible", false);
				});
			//}
		});
		// show selected menu
		if (!$.data(this, "visible")) {
			$.data(this, "visible", true);
			$(this).css("overflow", "visible")
				.children("ul")
					.hide()
					.slideDown(150);
			$(document).trigger("show.KCmenu");
		}
	}, function () {
		var $this = $(this), that = this;
		KC.menutimer = setTimeout(function () {
			$this.children("ul").slideUp(150, function () {
				$this.css("overflow", "hidden");
				$.data(that, "visible", false);
				$(document).trigger("hide.KCmenu");
			});
		}, 500);
	});
	
	// change the color of the rounded corners on hover/on
	$("#nav-main ul ul li:last-child a")
		.hover(function () {
			$(this).parents("ul").eq(0).addClass("last-on");
		}, function () {
			var $this = $(this);
			if (!$this.hasClass("on")) {
				$this.parents("ul").eq(0).removeClass("last-on");
			}
		})
		.each(function () {
			var $this = $(this);
			if ($this.hasClass("on")) {
				$this.parents("ul").eq(0).addClass("last-on");
			}
		});
		
	// hide select elements in IE < 7 when the drop downs are visible
	if ($.browser.msie && parseInt($.browser.version, 10) < 7) {
		$(document).bind("show.KCmenu", function () {
			$("select").css("visibility", "hidden");
		});
		
		$(document).bind("hide.KCmenu", function () {
			$("select").css("visibility", "visible");
		});
	}
});
 
// namespaces
var KC = {
	debug: true, // FIX change to false before final deployment!
	menus: null,
	menutimer: null
};

KC.Util = {
	log: function () {
		if (KC.debug) {
			try {
				console.log(arguments);
			} catch (err) {}
		}
	},
	
	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};
	},
	
	printContent: function (content) {
		// create hidden iframe to hold content to be printed
		var wind = doc = null, 
			$iframe = $('<iframe>')
				.css({position: "absolute", width: 0, height: 0, top: "-1000px", left: "-1000px"})
				.appendTo("body");
		wind = $iframe[0].contentWindow;
		doc = wind.document;
		// copy styles into iframe
		$("link").each(function () {
			if (this.rel.toLowerCase() == "stylesheet") {
				doc.write('<link type="text/css" rel="stylesheet" href="' + this.href + '" media="' + this.media + '"></link>');
			}
		});
		// insert and print content
		doc.write('<div id="wrapper">' + content + '</div>');
		doc.write('<scri' + 'pt>self.onload = function(){self.focus();self.print();};</scri' + 'pt>');
		doc.close();
	}
};

KC.Form = {
	showError: function (err) { // CURRENTLY UNUSED
		$("input.hint").trigger("blur"); // restore field hints
		$("#error")
			.hide()
			.html(err)
			.fadeIn("slow");
	},
	
	hideError: function () { // CURRENTLY UNUSED
		$("#error").hide();
	},
	
	isEmail: function (s) {
		return /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(s);
	},
	
	isDate: function (s) {
		return /^(0[1-9]|1[012]|[1-9])\/(0[1-9]|[12][0-9]|3[01]|[1-9])\/([0-9][0-9])$/.test(s);
	},
isDateInRange: function (year, month, date) {
	    var iMonth = parseInt(month)-1;
        var oneMinute = 60 * 1000;
        var oneHour = oneMinute * 60;
        var oneDay = oneHour * 24;
        var today = new Date();
        var targetDate = new Date();
        targetDate.setYear("20"+year);
        targetDate.setMonth(iMonth);
        targetDate.setDate(date);
        var diff = targetDate.getTime() - today.getTime();
        diff = Math.floor(diff/oneDay);
        var IntegerDiff = parseInt(diff);
//        alert(today);
//        alert(targetDate);
//        alert(diff);
//        alert(IntegerDiff);
        if(IntegerDiff > 0){
            //alert(">0");
            if(IntegerDiff > 365){
                //alert(">365");
                return false;
            }
         }else{
                //alert("else");
                if(IntegerDiff < -2555){
                    //alert("inside-1460");
                     return false;           
                    }
               }
               return true;
        
	},	
	validateNewsletterSidebar: function () {
		var foc = null, error = "", cookie = KC.Util.cookie;;
		if (!$.trim(this["first_name"].value)) {
			error += "* First name is required.\n";
			foc = this["first_name"];
		}
		if (!KC.Form.isEmail($.trim(this["email_address"].value))) {
			error += "* A valid e-mail address is required.\n";
			foc = foc || this["email_address"];
		}
		if (!KC.Form.isDate($.trim(this["bmonth"].value) + "/" + $.trim(this["bday"].value) + "/" + $.trim(this["byear"].value))) {
			error += "* A valid child's birthday is required.\n";
			foc = foc || this["bmonth"];
		}
		if (!KC.Form.isDateInRange($.trim(this["byear"].value),$.trim(this["bmonth"].value),$.trim(this["bday"].value))) {
			error += "* Child age should be less than 7 years or if you're pregnant, the child birthday should be within a year.\n";;
			foc = foc || this["bmonth"];
		}
		if (error) {
			alert(error);
			$("input.hint").trigger("blur"); // restore field hints
			foc.focus();
			return false;
		}
		// success, store the name in a cookie and submit form
		cookie("newsletter", $.trim(this["first_name"].value), {expires: 365, path: "/"});
		return true;
	}
};


// enable styles for js-enabled browsers
if(document.getElementById && document.createTextNode) {
	document.getElementsByTagName("html")[0].className = "js";
};
 
// prevent background image flicker in IE
try {
	document.execCommand("BackgroundImageCache", false, true);
} catch(err) {};

//// fix PNG transparency in IE
//// from: http://www.twinhelix.com/css/iepngfix/
if (document.all && document.styleSheets && document.styleSheets[0] &&   document.styleSheets[0].addRule) {
	// Feel free to add rules for specific tags only, you just have to call it several times.
	//document.styleSheets[0].addRule('img', 'behavior: url(js/iepngfix.htc)');
	//document.styleSheets[0].addRule('a', 'behavior: url(js/iepngfix.htc)');
	//document.styleSheets[0].addRule('span', 'behavior: url(js/iepngfix.htc)');
	//document.styleSheets[0].addRule('div', 'behavior: url(js/iepngfix.htc)');
}


// jQuery plugins

jQuery.fn.hint = function () { // http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
	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();
		}
	});
};
