// JavaScript Document

// Returns the version of Internet Explorer or a -1
function getInternetExplorerVersion() {
	var rv = -1; // Return value assumes failure.
  	if (navigator.appName == 'Microsoft Internet Explorer') {
		var ua = navigator.userAgent;
	    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    	if (re.exec(ua) != null)
      		rv = parseFloat( RegExp.$1 );
	}
	return rv;
}

//returns a booleon based on param matching ie version
function ieBrowser(version){
	thisVersion = getInternetExplorerVersion();
	return (version == thisVersion) ? true : false;
}

//Checks to see if something is defined. returns boolean
function isdefined(thisVar){
	return (thisVar == undefined) ? (false) : (true);
}

//Calculates how many ID elements there are by appending incremented number to the end
function getNumOfThisId(elem){
	num = 0;
	for(p=1;isdefined(document.getElementById(elem+p));p++){
		num++;
	}			
	return num;
}

//Calculates an element's x and y pixel offsets in relation to the user's browser window.
//returns either x or y
function findPos(axis,obj) {
	var curleft = curtop = 0;
	while (obj) {
		curleft += obj.offsetLeft
		curtop += obj.offsetTop
		obj = obj.offsetParent
	}
	
	if (axis == 'x')
		return curleft;
	else if (axis == 'y')
		return curtop;
	else
		return false;
}

// newletter sign-up validation
function spEmailSignUp(list){
				
	thisVal = $('#join_newsletter').val();		
	isValid = isValidEmailAddress(thisVal);

	if (isValid){
		spShowResponse('loading');
					
		$.ajax({
		   type: "POST",
		   url: "/int_cfc/silverpop.cfc",
		   data:{			   
			   method:"addRecipient",
			   spEmail:thisVal,
			   spJoin:list
			   },
		   success: function(data){
			   xml = readyXml(data);
			   xmlVal = findNode(xml,'SUCCESS');
			   
			   if (xmlVal == 'TRUE')
				   spShowResponse(true);
			   else
			   	   spShowResponse(false);				
		   },
		   error:function(msg){
			   alert('failed');
			   spShowResponse(false);
		   }
		});	
		
		return false;
	}else {
		spShowResponse('invalid');
		return false;
	}
}

//function displays different messages when attempting to submitting email subscription to silverpop
function spShowResponse(show){
	errorTxt = $('#join_newsletter_error');
	silverpopResponse = $('#join_newsletter_response');
	newsletter_loading = $('#join_newsletter_loading');
	newsletter_txtbox = $('#join_newsletter');
	newsletter_btn = $('#join_newsletter_btn');
	emailForm = $('#newsletter_submit');	
	
	switch (show){
		//display validation error
		case 'invalid':	
			errorTxt.fadeIn("slow");
			break;
		
		//display loading
		case 'loading':
			newsletter_btn.attr('disabled','disabled');
			errorTxt.fadeOut("fast", function(){				
				newsletter_txtbox.addClass('join_newsletter_loading-txt');
				newsletter_loading.fadeIn(850);
			});	
			break;
		
		//display success
		case true:
			emailForm.fadeOut(850, function(){
				silverpopResponse.css({display:"none"});		  
				silverpopResponse.html('<h4>Thank you!</h4>You have successfully joined our email list');
				silverpopResponse.fadeIn(850);					
			});
			newsletter_btn.removeAttr('disabled');
			break;
		
		//display failure
		default:
			emailForm.fadeOut(850, function(){
				silverpopResponse.css({display:"none"});
				silverpopResponse.html('<h4>We\'re sorry, an error has occurred</h4>Please refresh the page and <b>try again</b>. <br />If the problem persists, please contact <a href="http://eps.schoolspecialty.com/cs" style="text-decoration:underline;">Customer Service</a>');	
				silverpopResponse.fadeIn("slow");	
			});
			newsletter_btn.removeAttr('disabled');
	}	
}


//funcion parses xml, and returns the node data
/* to do:
	* make this more dynamic to be able to return attributes, and other xml elements
*/
function findNode(xml,thisNode){
	yourXmlData = false;	
		
	$(xml).find(thisNode).each(function(){
		yourXmlData = $(this).text();
	});
	
	return yourXmlData;
}

/*	function formats xml to support IE browsers. 
	If not IE, do nothing and return the xml
*/
function readyXml(xml) { 
	if (jQuery.browser.msie) {  
		var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");  
		xmlDoc.loadXML(xml);  
		xml = xmlDoc;  
	} 
	return xml;  
}  

//validates an email address
function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^((&quot;[\w-\s]+&quot;)|([\w-]+(?:\.[\w-]+)*)|(&quot;[\w-\s]+&quot;)([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	
	return pattern.test(emailAddress);
}



/* function is initiated when a menu item is clicked/hovered.  
	it removes the ".selected" class on all ul li elements,
	and adds the ".selected" class to the element that has been clicked
*/
function newHightlight(newElem, id){	
	// Remove '.selected' class from the nav elements
	$('ul'+id+' li').each(function(){
		if($(this).is('.selected')){
			$(this).stop(true, true).removeClass('selected',500);	
		}
	});
	
	// Add '.selected' class to element
	$(newElem).parent('li').stop(true, true).addClass('selected',300);
	
	return false;
}




//jQuery init function for all pages
//----------------------------------------------------------------------------------------------------
$(document).ready(function(){
		
	/* image roll-over function: hover image must be <img name>_hover.*
		for example: logo.png & logo_hover.png
	*/
	$(".img-hover").hover(		
		function() {
			s = $(this).attr("src");
			ext = s.slice(-4);
			s_hover = s.slice(0,s.length-4)+'_hover'+ext;
			$(this).attr("src", s_hover);
		},
		function() {$(this).attr("src", s)}
	);
		
	/* image mousedown function: down image must be named <img name>_down.*
		for example: logo.png & logo_down.png
		
		this code is FAR from "DRY" -- it desparately needs to be optimized
	*/
	$(".img-down").mouseup(function(){		
		sh = $(this).attr("src");
		ext = sh.slice(-4);	
		s_orig = sh.slice(0,sh.length-9)+ext;		
		$(this).attr("src", s_orig);
	}).mousedown(function(){
		sh = $(this).attr("src");
		ext = sh.slice(-4);	
		appendedHover = sh.slice(-10,sh.length-4);
		(appendedHover == '_hover') ? sliceSpot = 10 : sliceSpot = 4;	
		s_down = sh.slice(0,sh.length-sliceSpot)+'_down'+ext;	
		$(this).attr("src", s_down);
	});	
			
	/* Pre Load images
		this is were we create an array of img src's.
		we then call our jquery pre-loaded function, with our array as a parameter
		
		if you want to manually add images to preload, add them to the array declaration.
		
		Otherwise, we automatically append our array with any element that has a class of:
			.img-hover
			.img-down
	*/
	var preLoadThis = new Array(); //manually add img src's here
		
	$('.img-hover').each(function(){
		plHoverSrc = $(this).attr("src");
		plHoverExt = plHoverSrc.slice(-4);
		plHoverSrcThis = plHoverSrc.slice(0,plHoverSrc.length-4) + '_hover' + plHoverExt;
		
		preLoadThis.push(plHoverSrcThis);
	});
	
	$('.img-down').each(function(){
		plDownSrc = $(this).attr("src");
		plDownExt = plDownSrc.slice(-4);
		plDownSrcThis = plDownSrc.slice(0,plDownSrc.length-4) + '_down' + plDownExt;
		
		preLoadThis.push(plDownSrcThis);
	});
	
	//call our preloader function with the "preLoadThis" array as a parameter
	$.preloadImages(preLoadThis);

	
	/* Preserve input text
		these functions:
			* save the default input text
			* hide the default text onfocus()
			* puts back the default text onBlur(), if empty string
		
		Note: this is really temporary until HTML5 becomes more ubiquitous
	*/
	$('.preserveText').each(function(){
		txt = $(this).val();
		jQuery.data($(this)[0],'preserved',txt);		
	});
	
	
	$('.preserveText').focus(function () {
		origInputTxt = jQuery.data($(this)[0],'preserved');		
		currentInputTxt = $(this).val();
		if (currentInputTxt == origInputTxt)
			$(this).val('');			
	});
	
	$('.preserveText').blur(function () {
		origInputTxt = jQuery.data($(this)[0],'preserved');
		currentInputTxt = $(this).val();
		if (currentInputTxt == '')
			$(this).val(origInputTxt);											  
	});

	
}); //close jQuery init



// This is our jquery function that preloads images
jQuery.preloadImages = function() {
	var a = (typeof arguments[0] == 'object') ? arguments[0] : arguments;	
	for(var i = a.length -1; i >= 0; i--) {
		//alert(a[i]);  //this will show us what src's are being "preloaded"
		jQuery("<img>").attr("src", a[i]);
	}
}
