/**
 *	File		global.js
 *	Created		11/23/10
 *	Updated		n/a
 *
 *	This is our company-wide javascript file.  Ideally it should be included
 *	across every site EPS has.  It contains very general, yet useful, javascript
 *	functions.
 *
 *	!! Important Note !! – this file is dependent on jQuery.  Make sure jQuery is
 *	referenced first before including this file in your <head> tags 	
 *
 *	Please note that some of the functions in this file are deprecated
 * 
 */ 


/* getInternetExplorerVersion()
	Returns the version of Internet Explorer or a -1
	
	note: this is a deprecated function.  Use the built in jQuery.browser function
*/
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;
}

/* ieBrowser()
	Returns a booleon based on param matching ie version
	
	note: this is a deprecated function.  Use the built in jQuery.browser function.
	currently being used for ie6 header menu (drop-downs).  delete this function after
	ie6 is no longer supported
*/
function ieBrowser(version){
	thisVersion = getInternetExplorerVersion();
	return (version == thisVersion) ? true : false;
}

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

/* notifyAdmin()
	This function attempts to make an ajax request that emails the site admin.
	It is usually invoked when an error occurs.
	
	It also flashes the browser depending on the 'flash' parameter
*/
function notifyAdmin(errorStr,flash){
	try{		
		$.ajax({			
			type: "POST",
			url: "/eps_common/ajax/remote_proxy.cfm",
			data:{			   
			   	cfcFile:"eps_common.cfc.global",
			   	cfcMethod:"ajaxNotifyAdmin",
			   	cfcParams:{
					customObj: errorStr,
					customReferer: window.location.href
				}
			},
			success: function(data){
				if (flash)
					(flash !== true) ?	flashBrowser(flash) : flashBrowser("We're sorry, but an error has occurred");
								
			},
			datatype: "json",
			error:function(xhr,txt,err){		
				// error
				flashBrowser('unqiue error: '+txt);							
			}
		});		
	} catch(err) {
		flashBrowser(site_copy(0));
	}
}

var flash_count = 0;
function flashBrowser(message){
/*
	flash_container = $('#flash_wrap');
	
	if (!flash_container.length) { 
		// container not present on page, create container, and new flash element
		$('body').prepend('<div id="flash_wrap"></div>');
		flash_container = $('#flash_wrap');		
	} 
	
	flash_container.append('\
		<div id="flashid_'+flash_count+'" class="flash" style="display:none;">\
			'+message+' \
			<a href="#" onclick="removeFlash($(this).parent(\'div.flash\')); return false;" class="close_flash">close</a>\
		</div>\
	');	
	$("#flashid_"+flash_count).fadeIn();
	
	flash_count++;	
}

function removeFlash(elem){
	elem.fadeOut(function(){
		$(this).remove();
		if (!$(".flash").length){
			$('#flash_wrap').remove();
		}
	});
*/
}

/* spEmailSignUp()
	This function makes an ajax call to add en email to a silverpop email list.
	It calls our silverpop.cfc file, which does the xml constructing and API call
	
	@todo
		* write better exception handling for when errors occur.  I recommend
		changing the ajax call to "asynchronous:false", and writing a separate
		ajax function that emails cmb_ecom to notify them of the error -RB
		
		* function currently gets xml returned to it (from silverpop.cfc).  I 
		recommend having it return json instead, as that's easier to deal with
		across browser types -RB
*/
function spEmailSignUp(list){
				
	emailAddr = $('#join_newsletter').val();		
	isValid = isValidEmailAddress(emailAddr);

	if (isValid){
		
		spShowResponse('loading');
		try{			
			$.ajax({
			   	type: "POST",
			   	url: "/eps_common/ajax/remote_proxy.cfm",
				data:{			   
				   	cfcFile:"eps_common.cfc.silverpop",
				   	cfcMethod:"addRecipient",
				   	cfcParams:{
					   	spEmail:emailAddr,
					   	spJoin:list					   	
				   	}
				},			  
			   	datatype: "json",
				success: function(data){
					xml = readyXml(data);
				   	xmlVal = findNode(xml,'SUCCESS');
							   
				   	if (xmlVal == 'TRUE')
						spShowResponse(true);
				   	else
						spShowResponse(false);	
			   	},
			   	error:function(xhr,txt,err){						
					notifyAdmin(txt,true);
					spShowResponse(false);	
			   	}
			});	
		} catch(err){
			notifyAdmin(err,true);
		}
		
		return false;
	}else {
		spShowResponse('invalid');
		return false;
	}
}

/* spShowResponse()
	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(site_copy(1));
				silverpopResponse.fadeIn(850);					
			});
			newsletter_btn.removeAttr('disabled');
			break;
		
		//display failure
		default:
			emailForm.fadeOut(850, function(){
				silverpopResponse.css({display:"none"});
				silverpopResponse.html(site_copy(2));	
				silverpopResponse.fadeIn("slow");	
			});
			newsletter_btn.removeAttr('disabled');
	}	
}

/* findNode()
	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;
}

/* readyXml()
	function formats xml to support IE browsers. If not IE, do nothing and return the xml
*/
function readyXml(xml) { 
	if (jQuery.browser.msie) {  
		//Internet explorer
		var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");  
		xmlDoc.loadXML(xml);  
		xml = xmlDoc;  
	} else {
		//All other browsers – I don't believe this is necessary.  commented out for now.
		//xml = (new DOMParser()).parseFromString(xml, 'text/xml');
	}
	return xml;  
}  

/* isValidEmailAddress()
	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);
}

/* site_copy()
	This function holds the copy for the site, that is used by javascript
*/
function site_copy(phrase){	
	var copy = new Array();
	copy[0] = "Unfortunately a servere error has occurred.  \
			So severe, that the website was unable to notify the web developers.  \
			If you have an extra moment, and would be so kind, would you use our \
			<a href=\"/cs\">contact form</a> and let us know what you were trying to do?  \
			That way we can fix this as soon as possible.  We're very sorry about this.";
			
	copy[1] = '<h4>Thank you!</h4>You have successfully joined our e-mail list';
	
	copy[2] = '<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/?sub=Problem%20with%20website" style="text-decoration:underline;">Customer Service</a>';
	
	your_copy = copy[phrase];
	
	if (!isdefined(your_copy)){
		notifyAdmin("The site_copy() function was invoked with an invalid 'phrase' parameter. copy[] element '"+phrase+"' does not exist",false);
		your_copy = 'Undefined copy';
	}

	return your_copy;
		
}

function checkPlaceholders(){
	$('.placeholder').each(function(){	
		input = $('input[name='+$(this).attr('for')+']');	
		if ( input.val() != '') 
			$(this).css('display','none');
	});
}

/* 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 newSelected(current, list){	
	
	var target;
	
	// Remove '.selected' class from the nav elements
	$(list).each(function(){
		//detect if we're dealing with anchor elements or li elements
		if ($(this).is('li'))
			target = 'li';
		else
			target = 'a';
			
		if($(this).is('.selected')){
			$(this).stop(true, true).removeClass('selected',500);
			$(this).stop(true, true).addClass('visited',500);		
		}		
	});

	// Add '.selected' class to element, and add .active to previous
	if (target == 'li') {
		$(current).parent('li').stop(true, true).addClass('selected',300);	
	} else {
		$(current).stop(true, true).addClass('selected',300);	
	}	
	return false;
}


/*----------------------------------------------------------------------------------------------------
						jQuery init function 
----------------------------------------------------------------------------------------------------*/

$(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);											  
	});
	
	
	/* Placeholder labels
		These functions place the label right on top of the input field.
		Once the user starts typing, the label is hidden.
			* sets the <form> positioning to "relative"
			* sets the label positioning to absolute, and gives it "top" and "left" identical to its corresponding input field
			* focus(), blur(), keyup() functions for handling the hiding/showing of label
		
		Note: in order to use this, give the <label> a class of "placeholder",
				and make sure the <form> has a class of "placeholders" (plural)
	*/
	$('form.placeholders').each(function(){
		$(this).css('position','relative');
	});
	
	$('form.placeholders .placeholder').each(function(){			
		$(this).css('position','absolute');
		
		if($('input[name='+$(this).attr('for')+']').length){
			//element is an input field
			input = $('input[name='+$(this).attr('for')+']');
		} else {
			//element is a textarea field	
			input = $('textarea[name='+$(this).attr('for')+']');
		}	
	   	inputPosition = input.position();
	
		$(this).css({
			'left' : inputPosition.left+'px',
			'top' : inputPosition.top+'px',
			'width' : 'auto',
			'cursor' : 'text',
			'-moz-user-select' : 'none',
			'-khtml-user-select' : 'none',
			'color' : '#000000',
			'opacity' : '0.5'
		});
		
		
		if ( input.val() != '') // check if the input field has text on pageload
			$(this).css('display','none');
	});
	
	$('form.placeholders .placeholder').click(function(){
		$('input[name='+$(this).attr('for')+']').focus();
	});
	
	$('form.placeholders input:text').focus(function(){	
		adjacentLabel = $("label[for='"+$(this).attr('name')+"']");
		if ( adjacentLabel.is('.placeholder') ){
			// the focused text input has an adjacent label of class ".placeholder"
			adjacentLabel.stop().animate({
				opacity: 0.2
			})
		}	
	});
		
	$('form.placeholders input:text').blur(function(){	
		adjacentLabel = $("label[for='"+$(this).attr('name')+"']");
		if ( adjacentLabel.is('.placeholder') && $(this).val() == ''){
			adjacentLabel.stop().css({
				'display':'inline',
				'opacity' : '0.5'
			});
		} else if ( adjacentLabel.is('.placeholder') && $(this).val() != ''){			
			adjacentLabel.css('display','none');
		}
	});
	
	$('form.placeholders input:text').keyup(function(){	
		adjacentLabel = $("label[for='"+$(this).attr('name')+"']");
		if ( adjacentLabel.is('.placeholder') && $(this).val() != ''){
			// the focused text input has an adjacent label of class ".placeholder"
			adjacentLabel.css('display','none');
		} else {
			adjacentLabel.css('display','inline');
		}
		//check all other placeholders – they may not be blank if browser has autofill for other fields
		checkPlaceholders();
	});
	
	/* functions for input text selection
		toggles a class for a section style on forms with .selection class
	*/
	$('form.selection input:text, form.selection input:password, form.selection textarea').focus(function(){
		$(this).addClass('selected');
	});
	$('form.selection input:text, form.selection input:password, form.selection textarea').blur(function(){
		$(this).removeClass('selected');
	});
	
	/* auto tick checkbox from label
		This function allows you to have the checkbox ticked on/off by clicking the
		checkbox's label
	*/
	$('form label').click(function(){
		inputCheckbox = $('input[name='+$(this).attr('for')+']:checkbox');
		if (inputCheckbox.length){
			inputCheckbox.attr('checked', !inputCheckbox.attr('checked'));	
		}
	});
	
	
}); //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]);
	}
}
