function getposOffset(overlay, offsettype){
	var totaloffset=(offsettype=="left")? overlay.offsetLeft : overlay.offsetTop;
	var parentEl=overlay.offsetParent;
	while (parentEl!=null){
		totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
		parentEl=parentEl.offsetParent;
	}
	return totaloffset;
}

var s = "";

function showCart(which, store) {
	if(s != store) hideCart();
	toggle('cartCallout');
	obj = document.getElementById("cartCallout");
	obj2 = document.getElementById(which);
	obj3 = document.getElementById("store");
	temp = getposOffset(obj2, "top") + 8;
	temp2 = getposOffset(obj2, "left") - 295;
	obj.style.top = temp + "px";
	obj.style.left = temp2 + "px";
	s = store;
	obj3.innerHTML = store + " Store";
}

function hideCart() {
	obj = document.getElementById("cartCallout");
	obj.style.display = h = "none";
}

var h = "none";

function toggle(theDiv) {
     var elem = document.getElementById(theDiv);
     elem.style.display = (h == "none")?"block":"none";
	 h = elem.style.display;
}

function showTip(which) {
	if(!document.getElementById("tip")) {
		var body = document.getElementsByTagName("body")[0];
		var d = document.createElement('div');
	
		body.appendChild(d);
		d.setAttribute("id", "tip");
	}
	obj = document.getElementById("tip");
	curobj = document.getElementById(which);
	temp = getposOffset(curobj, "top") + 29;
	temp2 = getposOffset(curobj, "left");	
	
	obj.style.display = "block";
	obj.style.top = temp + "px";
	obj.style.left = temp2 + "px";
	obj.innerHTML = '<img src="/content/presentation/www/images/' + which + '.png" alt="" />';	
}

function hideTip() {
	document.getElementById("tip").style.display = "none";
}

var tabStores = {
	makeRequest:function(url)
	{
        var httpRequest;
		url = "/content/includes/www/stores_tab_" + url + ".html";
		
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
            if (httpRequest.overrideMimeType) {
                httpRequest.overrideMimeType('text/xml');                
            }
        } else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!httpRequest) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        httpRequest.onreadystatechange = function() { tabStores.displayStore(httpRequest); };
        httpRequest.open('GET', url, true);
        httpRequest.send(null);
    },	
	displayStore:function(httpRequest)
	{
		if (httpRequest.readyState == 4) {
            if (httpRequest.status == 200) {
                var obj = document.getElementById("storesTabs");
				obj.innerHTML = httpRequest.responseText;				
            } else {
                //
            }
        }		
	}

}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

addDOMLoadEvent=(function(){var e=[],t,s,n,i,o,d=document,w=window,r='readyState',c='onreadystatechange',x=function(){n=1;clearInterval(t);while(i=e.shift())i();if(s)s[c]=''};return function(f){if(n)return f();if(!e[0]){d.addEventListener&&d.addEventListener("DOMContentLoaded",x,false);/*@cc_on@*//*@if(@_win32)d.write("<script id=__ie_onload defer src=//0><\/scr"+"ipt>");s=d.getElementById("__ie_onload");s[c]=function(){s[r]=="complete"&&x()};/*@end@*/if(/WebKit/i.test(navigator.userAgent))t=setInterval(function(){/loaded|complete/.test(d[r])&&x()},10);o=w.onload;w.onload=function(){x();o&&o()}}e.push(f)}})();

function clearParentNwsltr(emailTextBox) {
	if ( emailTextBox.value == "Please enter your email address" )
		emailTextBox.value = "";
}

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) return pair[1];    
  }   
}

function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	var arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

function getPageSize(){
	
	var pageHeight, pageWidth, xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	var arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

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;
}

function setMediaPlayerLinks() {
	var links = document.getElementsByTagName("a");
	var area = document.getElementsByTagName("area");
	for ( var i = 0, n = links.length; i < n; i++ ) {
		if ( links[i].className.indexOf("mediaPlayerLink") > -1 ) {						
			links[i].onclick = function() {
				//window.open(this.href, this.target, 'width=613,height=484');
				var handle = window.open(this.href, 'media_player', 'width=613,height=484');
				handle.focus();
				return false;
			};
		}
	}
	for ( var j = 0; j < area.length; j++ ) {
		if ( area[j].className.indexOf("mediaPlayerLink") > -1 ) {
			area[j].onclick = function() {
				//window.open(this.href, 'mediaPlayer', 'width=613,height=484');
				var handle = window.open(this.href, 'media_player', 'width=613,height=484');
				handle.focus();
				return false;
			};
		}
	}
}

function FlashOpenMediaPlayer (url) {
	window.open(url, 'media_player', 'width=613,height=484');
}

/***********************************
	transitional ad
************************************/
document.write('<script type="text/javascript" src="/content/_js/www/g_ta.js"><\/script>');

/***********************************
	doubleclick
************************************/
var axel = Math.random() + "", ord = axel * 1000000000000000000, dctile = 0;


var c4 = readCookie('header');
var c4page = location.pathname.split('/').pop();
var c4teacher = { "lessonplans.jsp" : true, "learn.jsp" : true, "scholasticNews.jsp" : true, "math.jsp" : true, "socialstudies.jsp" : true, "science.jsp" : true, "languagearts.jsp" : true, "read.jsp" : true, "connect.jsp" : true, "teach.jsp" : true, "tresourcegrade.jsp" :true };
var c4parent = { "parentsHome.jsp" : true, "parentchild.jsp" : true, "schoolandlearning.jsp" : true, "booksandreading.jsp" : true, "activities.jsp" : true, "activities.jsp" : true, "familylife.jsp" : true };

if ( c4teacher[c4page] ) { 
	schlAudience = 'teacher';
	document.writeln('<script type="text/javascript" src="/content/_js/foresee/foresee-trigger.js"><\/script>');	
	document.writeln('<!-- header = ' + c4 + ', schlAudience = ' + schlAudience + ', cookie override = yes -->');
}
else if ( c4parent[c4page] ) { 
	schlAudience = 'parents';
	document.writeln('<script type="text/javascript" src="/content/_js/foresee/foresee-trigger.js"><\/script>');
	document.writeln('<!-- header = ' + c4 + ', schlAudience = ' + schlAudience + ', cookie override = yes -->');
}
else if ( c4 == null || c4.indexOf('teacher') != -1 ) {
	schlAudience = 'teacher';
	document.writeln('<script type="text/javascript" src="/content/_js/foresee/foresee-trigger.js"><\/script>');	
	document.writeln('<!-- header = ' + c4 + ', schlAudience = ' + schlAudience + ' -->');
}
else if ( c4 == 'parents' ) {
	schlAudience = 'parents';
	document.writeln('<script type="text/javascript" src="/content/_js/foresee/foresee-trigger.js"><\/script>');
	document.writeln('<!-- header = ' + c4 + ', schlAudience = ' + schlAudience + ' -->');
}

/***********************************
	omniture link tagging
************************************/
var oHelper = [];
function schlOmnitureHelper(elem, context) {
	var strOmniture, tree, link, known = null;
	tree = jQuery(elem).parents().map(function(){
		if ( this.id ) {
			return this.id;
		}
	}).get().join('/');
				
	if ( elem.tagName == 'A' ) {
		if ( jQuery(elem).children().length > 0 ) {
			if ( jQuery(elem).children(':first').is('img') ) {
				var tmp = jQuery.trim(jQuery(elem).children(':first').attr('alt')) || 'n/a';
					link =  '[img][' + tmp + ']';
				}
				else {
					link = '[text][' + jQuery.trim(jQuery(elem).children(':first').text()) + ']';
				}
			}
			else {
				link = '[text][' + jQuery.trim(jQuery(elem).text()) + ']';
			}
		}
		else {
			var t = jQuery.trim(jQuery(elem).attr('alt')) || 'n/a';
			link = '[imgMap][' + t + ']';
		}
		link = link.replace(/\%/,'');
				
		var that = elem;
		var containerID = tree.split('/')[0],
			pos,
			hm = jQuery('#' + containerID + ' ' + elem.tagName).each(function(index){
				if ( that === this ) {
					pos = index + 1;				
					return false;
				}
			}).length;
			
		tree = tree.split('/');
		var tempTree = tree;
		for (var i = tempTree.length - 1; i >= 0; i--) {
			if ( tempTree[i] != 'schlTC' && tempTree[i] != 'pageWrapper' ) {
				tree.pop();
			}
			else break;
		}
		tree = tree.join('/');
				
		tree = '[' + tree + ']';

		strOmniture = '[' + location.pathname + ']';
		strOmniture += known || tree;
				strOmniture += '[' + pos + '_' + hm + ']' + link;
			   
				document.cookie = 'omni_PromoCode=' + strOmniture + '; domain=scholastic.' + document.domain.split('.').pop() + '; path=/';

				
}

function schlOmnitureLinkTagging() {	
	var approved = { 'parentsHome.jsp' : true, 'schoolandlearning.jsp' : true, 'booksandreading.jsp' : true, 'activities.jsp' : true, 'familylife.jsp' : true };
	var page = location.pathname.split('/').pop();
	if ( !approved[page] ) return;
	jQuery('a, area').each(function(index){		
		jQuery(this).click(function(){
			var strOmniture, tree, link, known = null;
			var knownList = {
				'schlFooter' : 'global footer',
				'tcNav' : 'teacher nav',
				'tc-dd' : 'teacher nav',
				'unMain' : 'universal nav',
				'unTeachers' : 'universal nav',
				'unParents' : 'universal nav',
				'unKids' : 'universal nav',
				'unAdministrator' : 'universal nav',
				'unLibrarians' : 'universal nav',
				'unMore' : 'universal nav'
			};				
			if ( this.href.indexOf('doubleclick.net') != -1 ) {
				document.cookie = 'omni_PromoCode=; expires=Thu, 01-Jan-70 00:00:01 GMT; domain=scholastic.' + document.domain.split('.').pop() + '; path=/';					
			}
			else {
				tree = jQuery(this).parents().map(function(){
					if ( this.id ) {
						return this.id;
					}
				}).get().join('/');
					
				oHelper[tree] = 1;
					
				if ( this.tagName == 'A' ) {
					if ( jQuery(this).children().length > 0 ) {
						if ( jQuery(this).children(':first').is('img') ) {
							var tmp = jQuery.trim(jQuery(this).children(':first').attr('alt')) || 'n/a';
							link =  '[img][' + tmp + ']';
						}
						else {
							link = '[text][' + jQuery.trim(jQuery(this).children(':first').text()) + ']';
						}
					}
					else {
						link = '[text][' + jQuery.trim(jQuery(this).text()) + ']';
					}
				}
				else {
					var t = jQuery.trim(jQuery(this).attr('alt')) || 'n/a';
					link = '[imgMap][' + t + ']';
				}
				link = link.replace(/\%/,'');
					
				var that = this;
				var containerID = tree.split('/')[0],
					pos,
					hm = jQuery('#' + containerID + ' ' + this.tagName).each(function(index){
						if ( that === this ) {
							pos = index + 1;				
							return false;
						}
					}).length;
					
				tree = tree.split('/');
				var tempTree = tree;
				for (var i = tempTree.length - 1; i >= 0; i--) {
					if ( tempTree[i] != 'schlTC' && tempTree[i] != 'pageWrapper' ) {
						tree.pop();
					}
					else break;
				}
				tree = tree.join('/');
					
				tree = '[' + tree + ']';

				strOmniture = '[' + location.pathname + ']';
				strOmniture += known || tree;
				strOmniture += '[' + pos + '_' + hm + ']' + link;
				   
				document.cookie = 'omni_PromoCode=' + strOmniture + '; domain=scholastic.' + document.domain.split('.').pop() + '; path=/';
			}
		});
	});	
		
	jQuery('body').click(function(event){
		var target = event.target;
		if ( target.nodeName == 'A' || target.nodeName == 'AREA' ) {	
		
			var tree = jQuery(target).parents().map(function(){
				if ( this.id ) {
					return this.id;
				}
			}).get().join('/');		
		
				
			if ( !oHelper[tree] ) {			
				var containerID = tree.split('/')[0];
				containerID = '#' + containerID;
				schlOmnitureHelper(target, containerID);
			}
		}
	});
}

/* ------------------------------------ */
function schlOmniture_AccordionAlt(){
	var page = location.pathname.split('/').pop();
	if ( page != 'parentsHome.jsp' ) return;
	jQuery('#accordionContainer').find('img').each(function(){
		var $this = jQuery(this);
		var alt = $this.attr('alt');
		if ( !alt ) {
			$this.attr('alt', $this.attr('src').split('/').pop());
		}
	});
}
/* ------------------------------------ */
function aShowMyAccount() {
	if ( location.hash == '#done' ) return;
	if ( getQueryVariable('login') == 'y' ) { location.hash='#done'; MA_showLogin(); }
	if ( getQueryVariable('myaccount') == 'y' ) { location.hash='#done'; MA_show(); }
}

/***********************************
	onload
************************************/
addDOMLoadEvent(aShowMyAccount);
addLoadEvent(setMediaPlayerLinks);
addLoadEvent(schlOmniture_AccordionAlt);
addLoadEvent(schlOmnitureLinkTagging);
