(function($){

	$.fn.extend({
        center: function () {
            return this.each(function() {
                var top = ($(window).height() - $(this).outerHeight()) / 2 + $(window).scrollTop();
                var left = ($(window).width() - $(this).outerWidth()) / 2;
                $(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
            });
        }
    });

	$.fn.ageScreener = function(options) {

		var _host = (typeof _schlHost != 'undefined') ? _schlHost : 'www.scholastic.com',
		defaults = {
			age : 13,
			overlayColor : '#555555',
			ageScreenerTitle : 'Customer Form',
			ageScreenerBackground : 'blue',
			under : '<p>Sorry, you can\'t buy the book directly from our site for kids. If you want to get the book online, ask your parent to help you purchase it. Or you can use this search tool to find a local bookstore in your area:</p><p class="local"><b>Find a Local Bookstore</b><br />Enter your address, city, or zip code to find bookstores near you using Google Maps:</p><form action="http://maps.google.com/maps" name="storeNearMe" id="frmGMaps" method="get"><table><tbody><tr><td><input name="near" id="AgeScreenerZip" type="text"><input name="q" value="bookstore" type="hidden"></td><td><input name="find" src="http://www.scholastic.com/kids/lastdragonchronicles/images/find_now.gif" id="AgeScreenerFind" alt="FIND NOW" title="FIND NOW" type="image" onclick="s=window.s;s.tl(true,\'e\',\'Google Maps Exit\');"></td></tr></tbody></table></form></div>',
			defaultMsg : 'Please fill out the form below.<br /><br />Scholastic does not retain this information. Our <a href="/privacy.htm">Privacy Policy</a> is available for your review.<form name="frmAS" id="frmAS" method="post" action="#"><table><tbody><tr><td class="default">Enter your birthdate:<br />mm/dd/yyyy</td><td><input type="text" name="bday" class="b-day" maxlength="10" size="15"></td></tr></tbody></table><input name="find" src="http://www.scholastic.com/kids/stacks/scene/signatures/images/btn_submit.png" class="btn" alt="Submit" title="Submit" type="image"></div></form>',
			ssoExit : isFP() ? 'http://' + _host + '/kids/pac_exit_store.asp' : 'http://' + _host + '/kids/tween_exit_store.asp'
		};
		var options = $.extend(defaults, options);


		return this.each(function(){

			var obj = $(this);

			obj.click(function(){

				if ( readCookie('ecommAS') == 'over' ) {
					if ( obj.attr('href').indexOf("store.scholastic.com") != -1 || obj.attr('href').indexOf("shop.scholastic.com") != -1 )
						window.open(options.ssoExit + "?url="+encodeURIComponent(obj.attr('href')),"exit",'width=1020,height=515');
					else
     					window.open("http://www.scholastic.com/kids/tween_exit.asp?url="+encodeURIComponent(obj.attr('href')),"exit",'width=1020,height=515');
				}
				else {
					showOverlay();
					showScreener(this);
					ecommOmniture('AgeScreener');
				}

				return false;

			});

		});

		function showOverlay() {
			if ( !$('#ageScreenerOverlay').length ) $('body').append('<div id="ageScreenerOverlay"></div>');
			$('#ageScreenerOverlay').css({
				'background' : options['overlayColor'],
				//'width' : $(document).width(),
				'height' : $(document).height()
			}).show();
		}

		function showScreener(which) {
			if ( !$('#ageScreenerContainer').length ) $('body').append('<div id="ageScreenerContainer"><a id="asClose"></a><h2>' + options.ageScreenerTitle + '</h2><div id="asContent"></div></div>');

			if ( readCookie('ecommAS') == 'under' ) {
				$('#asContent').html(options.under);

				$('#frmGMaps').submit(function(){
							exitPageGM(this);
							closeAgeScreener();
							return false;
						});
			}
			else {
				$('#asContent').html(options.defaultMsg);


				$('#frmAS').submit(function(){
					var field = $(this).find('input[type=text]'),
						fieldVal = $.trim(field.val()),
						isValidDate = validateUSDate(fieldVal),
						isUnder;

					if ( !isValidDate ) {
						field.addClass('error');
						if ( !$('#frmASError').length )
							field.parents('table').before('<div id="frmASError">Please enter your birthdate in this format: mm/dd/yyyy (for example, if you were born on January 31, 2000, you\'d enter: 01/31/2000)</div>');
					}
					else {
						field.removeClass('error');
						$('#frmASError').remove();
						isUnder = checkAge(fieldVal);

						if ( isUnder ) {
							$('#asContent').html(options.under);
							createCookie('ecommAS','under',1);
							ecommOmniture('AgeScreener:UnabletoBuy');

							$('#frmGMaps').submit(function(){
								exitPageGM(this);
								closeAgeScreener();
								return false;
							});
						}
						else {

							if ( $(which).attr('href').indexOf("store.scholastic.com") != -1 || $(which).attr('href').indexOf("shop.scholastic.com") != -1)
								window.open(options.ssoExit + "?url="+encodeURIComponent($(which).attr('href')),"exit",'width=1020,height=515');
							else
     							window.open("http://www.scholastic.com/kids/tween_exit.asp?url="+encodeURIComponent($(which).attr('href')),"exit",'width=1020,height=515');

							createCookie('ecommAS','over',1);
							closeAgeScreener();
						}

					}



					return false;
				});

			}


			$('#asClose').click(closeAgeScreener);
			$('#ageScreenerContainer').css({backgroundColor : options.ageScreenerBackground}).center().show();
		}

		function closeAgeScreener() {
			$('#ageScreenerOverlay, #ageScreenerContainer').hide();
		}

		function checkAge(field) {
			  var dateToCheck = new Date(field);
			  var past = new Date();

			  past.setYear(past.getFullYear() - options.age);
			  past.setHours(0);
			  past.setMinutes(0);
			  past.setSeconds(1);

			  if (dateToCheck.getTime() > past.getTime())
			  {
			    return true;
			  }
			  return false;
		}



	};


	$.fn.ageScreenerOnly = function(options) {
		/*
			no exit page
			no omniture tracking
		*/
		var _host = (typeof _schlHost != 'undefined') ? _schlHost : 'www.scholastic.com',
		defaults = {
			age : 13,
			overlayColor : '#555555',
			ageScreenerTitle : 'Customer Form',
			ageScreenerBackground : 'blue',
			under : '<p>Sorry, you can\'t buy the book directly from our site for kids. If you want to get the book online, ask your parent to help you purchase it. Or you can use this search tool to find a local bookstore in your area:</p><p class="local"><b>Find a Local Bookstore</b><br />Enter your address, city, or zip code to find bookstores near you using Google Maps:</p><form action="http://maps.google.com/maps" name="storeNearMe" id="frmGMaps" method="get"><table><tbody><tr><td><input name="near" id="AgeScreenerZip" type="text"><input name="q" value="bookstore" type="hidden"></td><td><input name="find" src="http://www.scholastic.com/kids/lastdragonchronicles/images/find_now.gif" id="AgeScreenerFind" alt="FIND NOW" title="FIND NOW" type="image" onclick="s=window.s;s.tl(true,\'e\',\'Google Maps Exit\');"></td></tr></tbody></table></form></div>',
			defaultMsg : 'Please fill out the form below.<br /><br />Scholastic does not retain this information. Our <a href="/privacy.htm">Privacy Policy</a> is available for your review.<form name="frmAS" id="frmAS" method="post" action="#"><table><tbody><tr><td class="default">Enter your birthdate:<br />mm/dd/yyyy</td><td><input type="text" name="bday" class="b-day" maxlength="10" size="15"></td></tr></tbody></table><input name="find" src="http://www.scholastic.com/kids/stacks/scene/signatures/images/btn_submit.png" class="btn" alt="Submit" title="Submit" type="image"></div></form>',
			onSuccessUnder : null,
			onSuccessOver : null
		};
		var options = $.extend(defaults, options);


		return this.each(function(){

			var obj = $(this);

			obj.click(function(){

				if ( readCookie('ecommAS') == 'over' ) {					
					if ( options.onSuccessOver != null && typeof options.onSuccessOver == 'function' ) options.onSuccessOver();
					window.open(obj.attr('href'));
				}
				else {
					showOverlay();
					showScreener(this);
				}

				return false;

			});

		});

		function showOverlay() {
			if ( !$('#ageScreenerOverlay').length ) $('body').append('<div id="ageScreenerOverlay"></div>');
			$('#ageScreenerOverlay').css({
				'background' : options['overlayColor'],
				//'width' : $(document).width(),
				'height' : $(document).height()
			}).show();
		}

		function showScreener(which) {
			if ( !$('#ageScreenerContainer').length ) $('body').append('<div id="ageScreenerContainer"><a id="asClose"></a><h2>' + options.ageScreenerTitle + '</h2><div id="asContent"></div></div>');

			if ( readCookie('ecommAS') == 'under' ) {
				$('#asContent').html(options.under);

				$('#frmGMaps').submit(function(){
							noExitPageGM(this);
							closeAgeScreener();
							return false;
						});
			}
			else {
				$('#asContent').html(options.defaultMsg);


				$('#frmAS').submit(function(){
					var field = $(this).find('input[type=text]'),
						fieldVal = $.trim(field.val()),
						isValidDate = validateUSDate(fieldVal),
						isUnder;

					if ( !isValidDate ) {
						field.addClass('error');
						if ( !$('#frmASError').length )
							field.parents('table').before('<div id="frmASError">Please enter your birthdate in this format: mm/dd/yyyy (for example, if you were born on January 31, 2000, you\'d enter: 01/31/2000)</div>');
					}
					else {
						field.removeClass('error');
						$('#frmASError').remove();
						isUnder = checkAge(fieldVal);

						if ( isUnder ) {
							$('#asContent').html(options.under);
							createCookie('ecommAS','under',1);

							$('#frmGMaps').submit(function(){
								noExitPageGM(this);
								closeAgeScreener();
								return false;
							});

							if ( options.onSuccessUnder != null && typeof options.onSuccessUnder == 'function' ) options.onSuccessUnder();
						}
						else {							
							createCookie('ecommAS','over',1);
							closeAgeScreener();
							if ( options.onSuccessOver != null && typeof options.onSuccessOver == 'function' ) options.onSuccessOver();
							window.open($(which).attr('href'));
						}

					}

					return false;
				});

			}


			$('#asClose').click(closeAgeScreener);
			$('#ageScreenerContainer').css({backgroundColor : options.ageScreenerBackground}).center().show();
		}

		function closeAgeScreener() {
			$('#ageScreenerOverlay, #ageScreenerContainer').hide();
		}

		function checkAge(field) {
			  var dateToCheck = new Date(field);
			  var past = new Date();

			  past.setYear(past.getFullYear() - options.age);
			  past.setHours(0);
			  past.setMinutes(0);
			  past.setSeconds(1);

			  if (dateToCheck.getTime() > past.getTime())
			  {
			    return true;
			  }
			  return false;
		}



	};


	$.fn.ecommPop = function(options) {

		var _host = (typeof _schlHost != 'undefined') ? _schlHost : 'www.scholastic.com',
		defaults = {
			headline : '<h3>Get the Book!</h3>',
			'local-form' : '<div class="ecomm-local"><strong>Find a Local Bookstore</strong> Enter your address, city, or zip code to find bookstores near you using Google Maps:<form id="frmGMap" name="storeNearMe" method="get" action="http://maps.google.com/maps"><input type="text" class="Zip" name="near"><input type="hidden" value="bookstore" name="q"><input type="image" title="FIND NOW" alt="FIND NOW" class="Find" src="/images/ecomm/but_FindNow.gif" name="find"></form></div>',
			ageScreener : false,
			ageScreenerBackground : 'blue',
			ageScreenerTitle : 'Customer Form',
			under : '<p>Sorry, you can\'t buy the book directly from our site for kids. If you want to get the book online, ask your parent to help you purchase it. Or you can use this search tool to find a local bookstore in your area:</p><p class="local"><b>Find a Local Bookstore</b><br />Enter your address, city, or zip code to find bookstores near you using Google Maps:</p><form action="http://maps.google.com/maps" name="storeNearMe" id="frmGMaps" method="get"><table><tbody><tr><td><input name="near" id="AgeScreenerZip" type="text"><input name="q" value="bookstore" type="hidden"></td><td><input name="find" src="http://www.scholastic.com/kids/lastdragonchronicles/images/find_now.gif" id="AgeScreenerFind" alt="FIND NOW" title="FIND NOW" type="image" onclick="s=window.s;s.tl(true,\'e\',\'Google Maps Exit\');"></td></tr></tbody></table></form></div>',
			ssoExit : isFP() ? 'http://' + _host + '/kids/pac_exit_store.asp' : 'http://' + _host + '/kids/tween_exit_store.asp'
		},
		settings = $.extend({}, defaults, options);

		// add the container for the ecomm popup
		if ( !$('#ecommPOP').length ) {
			$('body').append('<div id="ecommPOP"><a title="Close" class="ecomm-close" href="#"></a><div id="ecommPOPcontent"></div><div class="ecomm-btm"></div></div>');
			$('.ecomm-close').click(function(){
				$('#ecommPOP').hide();
				return false;
			});
		}

		return this.each(function(){

			var obj = $(this);

			if ( obj.is('a') && obj.attr('data-ecomm') != '' ) {

				obj.click(function(){

					setupPop(obj);
					ecommOmniture('Overlay');
					return false;

			});


			}

		});


		function setupPop(which) {
			var strContents = settings['headline'],
				sso = which.attr('href'),
				other = which.attr('data-ecomm');

			strContents += '<div class="ecomm-sso"><img src="/images/ecomm/ecomm-sso.gif" border="0" class="ecomm-sso-logo" />';

				if ( sso.indexOf('store.scholastic.com') != -1 || sso.indexOf('shop.scholastic.com') != -1 ) {
					strContents += '<a href="' + sso + '"><img src="/images/ecomm/buy_now.gif" border="0" class="ecomm-sso-buy" /></a>';
				}
				else {
					strContents += '<img src="/images/ecomm/ecomm-not-available.gif" border="0" class="ecomm-sso-buy" />';
				}
				strContents += '</div>';


				if ( typeof other != 'undefined' && other != '' ) {
					others = eval('(' + other + ')');
					strContents += '<div class="ecomm-other">Or try these other online stores:<br />';
					for ( var key in others ) {
						strContents += '<a href="' + others[key] + '">' + key + '</a> ';
					}
					strContents += '</div>';
				}

				strContents += settings['local-form'];

				//populate the callout
				$('#ecommPOPcontent').html(strContents);

				if ( settings.ageScreener )
					$('#ecommPOPcontent a').ageScreener({ageScreenerBackground : settings.ageScreenerBackground, ageScreenerTitle : settings.ageScreenerTitle, ssoExit : settings.ssoExit, under: settings.under});

				//position and show the callout
				position(which);

				$('#frmGMap').submit(function(){
					 exitPageGM(this);
					 return false;
				});
		}

		function position(which) {
			var button = $(which);
			button.css({'display' : 'block', 'width' : button.width()});
			var	offset = button.offset();
			$('#ecommPOP').css({'left' : offset.left + button.width() + 5, 'top' : offset.top}).show();
		}

	};

	function exitPageGM(frm) {
		var zip=frm.near.value;
		var url=(zip == '') ? 'http://maps.google.com/maps' : escape('http://maps.google.com/maps?near=' + zip + '&amp;q=bookstore');
		window.open("http://www.scholastic.com/kids/tween_exit.asp?url="+url,'exit','width=1020,height=515');
	}

    // Google Maps without exit page
	function noExitPageGM(frm) {
		var zip=frm.near.value;
		var url=(zip == '') ? 'http://maps.google.com/maps' : encodeURIComponent('http://maps.google.com/maps?near=' + zip + '&q=bookstore');
		window.open(decodeURIComponent(url),'exit','width=1020,height=515');
	}

	function ecommOmniture(which) {
		var env = isFP() ? 'FP' : 'STACKS',
		evar40;
		switch (which) {
			case 'Overlay' : evar40 = ' Buy Module Click'; break;
			case 'AgeScreener' : evar40 = ' Age Screener'; break;
			case 'AgeScreener:UnabletoBuy' : evar40 = ' Age Screener Unable to Buy'; break;
			default : break;
		}
		s.manageVars("clearVars");
		s=s_gi(s_account);
		s.pageName='Main:BuyModule:' + env + ':' + which;
		s.channel='BuyModule';
		s.server='buymodule';
		s.prop3='Main:BuyModule:' + env;
		s.prop42='Main:BuyModule:' + which;
		s.eVar40=env + evar40;
		s.hier1='Main|BuyModule|' + env;
		s.t();
	}

	function isFP() {
		var fp = false;
		if ( typeof schlKidsNav != 'undefined' && schlKidsNav == 'FP' ) {
			fp = true;
		}
		else if ( document.getElementById('schlKidsWrapper') ) {
			fp = true;
		}
		return fp;
	}

	// shared age screener functions

	function validateUSDate( strValue ) {
			/************************************************
			DESCRIPTION: Validates that a string contains only valid dates with 2 digit month, 2 digit day, 4 digit year. Date separator can be ., -, or /. Uses combination of regular expressions and string parsing to validate date.
			Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy
			*************************************************/
			  var objRegExp = /^\d{1,2}(\/)\d{1,2}\1\d{4}$/

			  //check to see if in correct format
			  if(!objRegExp.test(strValue))
			    return false; //doesn't match pattern, bad date
			  else{
			    var strSeparator = strValue.substring(2,3)
			    var arrayDate = strValue.split(strSeparator);
			    //create a lookup for months not equal to Feb.
			    var arrayLookup = { '01' : 31,'03' : 31,
			                        '04' : 30,'05' : 31,
			                        '06' : 30,'07' : 31,
			                        '08' : 31,'09' : 30,
			                        '10' : 31,'11' : 30,'12' : 31}
			    var intDay = parseInt(arrayDate[1],10);

			    //check if month value and day value agree
			    if(arrayLookup[arrayDate[0]] != null) {
			      if(intDay <= arrayLookup[arrayDate[0]] && intDay != 0)
			        return true; //found in lookup table, good date
			    }

			    var intMonth = parseInt(arrayDate[0],10);
			    if (intMonth == 2) {
			       var intYear = parseInt(arrayDate[2]);
			       if (intDay > 0 && intDay < 29) {
			           return true;
			       }
			       else if (intDay == 29) {
			         if ((intYear % 4 == 0) && (intYear % 100 != 0) ||
			             (intYear % 400 == 0)) {
			              // year div by 4 and ((not div by 100) or div by 400) ->ok
			             return true;
			         }
			       }
			    }
			  }
			  return false; //any other values, bad date
		}

		function createCookie(name,value,days) {
			var expires = "";
			if (days) {
				var date = new Date();
				date.setTime(date.getTime()+(days*24*60*60*1000));
				expires = "; expires="+date.toGMTString();
			}
			document.cookie = name + "="+value+expires+"; domain=scholastic." + document.domain.split(".").pop() + "; path=/";
		}

		function readCookie(name) {
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for(var i=0;i < ca.length;i++)
			{
				var c = ca[i];
				while (c.charAt(0)==' ') c = c.substring(1,c.length);
				if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
			}
			return null;
		}

})(jQuery);
