//	jquery.custom.js contains code that is customized for fluid.com v5. This code requires jquery.js (jQuery 1.1.2 or greater).


// ////////////////////////////////////////////////////////////////////////////
// jQuery Plug-ins and Modifications
// ////////////////////////////////////////////////////////////////////////////


/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @return    The object (aka "this") that called hoverIntent, and the event object
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);


/**
* Extend jQuery browser detection to find pre-7 versions of IE so we can protect them from transparent PNG issues.
*/
(function($){
	var ua = navigator.userAgent.toLowerCase(); // user agent
	var av = parseFloat( ua.substring( ua.indexOf('msie ') + 5 ) ); // app version
	var ex = { msie_pre7: false }; // set to false by default
	if ($.browser.msie) { ex.msie_pre7 = av < 7; } // adjust if msie
	jQuery.browser = jQuery.extend($.browser,ex); // extend jQuery $.browser object
})(jQuery);


// ////////////////////////////////////////////////////////////////////////////
// Document Ready
// ////////////////////////////////////////////////////////////////////////////


/**
* Built-in jQuery method that executes code when the HTML DOM is ready.
* This is used instead of window.onload, as that event fires after all
* elements on the page (including images) have been loaded into the browser.
*/
$(document).ready(function(){
	//alert("ready");
	// detect links that need to pop new windows when clicked and make them work
	$("a.launch").click(function(){ window.open(this.href);	return false; });
	// init primary navigation
	navigation.initialize();

	// init input button image rollovers
	var inputTags = document.getElementsByTagName("input");
	if (inputTags) {
		for (var i=0; i<inputTags.length; i++) {
			if (inputTags[i].type == "image" && inputTags[i].src) {
				//alert("id,=" + inputTags[i].id + ",name=" + inputTags[i].name + ",type=" + inputTags[i].type + ".");
				jqSelector = "#" + inputTags[i].id;
				$(jqSelector).each( navigation.initRoll ).hover( navigation.rollOver , navigation.rollOut  );
			}
		}
	}
	//above code replaces following line which causes an error in firefox
	//[Exception... "'Syntax error, unrecognized expression: [@type="image"][@src]' 
	//$('input[@type="image"][@src]').each( navigation.initRoll ).hover( navigation.rollOver , navigation.rollOut  );
	
	// init share form
	if ( document.getElementById('shareForm') ) { share.initialize(); }
	// init register form
	if ( document.getElementById('registerForm') ) { register.initialize(); }

});


// ////////////////////////////////////////////////////////////////////////////
// Navigation
// ////////////////////////////////////////////////////////////////////////////


// navigation properties and functions
var navigation = new Object();


/**
* This function adds IE6 work-arounds, removes non-Javascript preventative 
* measures, and sets up event listeners for the primary navigation.
*/
navigation.initialize = function() {

	if ( $.browser.msie_pre7 ) {
		// correct IE6 PNG transparency rendering issue
		$("#nav_bg1, #nav_bg2").each(function () {
			var src = $(this).css("background-image");
			src = src.substring( src.lastIndexOf('/images') , src.length-2 );
			$(this).css({
				'backgroundImage': 'none',
				'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "')"
			});
		});

		// mimic li:hover in IE6
		var toggleColumn = function(){ $(this).toggleClass("highlight"); };
		$('#nav_p, #nav_s, #nav_c').hover(toggleColumn,toggleColumn);
	}

	// set maximum (expanded) and  minimum (collapsed) height for navigation
	var maxMenuHeight = parseInt( $('#nav').css("height") );
	var minMenuHeight = parseInt( $('#navWrapper').css("height") );

	// remove background GIF that provides IE and non-javascript compatibility
	$( '#nav' ).css('background-image','none');

	// functions that show/hide the ... umm... menu
	var showMenu = function(){ $('#navWrapper').animate({ height: maxMenuHeight }, 200); };
	var hideMenu = function(){ $('#navWrapper').animate({ height: minMenuHeight }, 200); };

	// hoverIntent attaches event listeners
	$( '#navWrapper' ).hoverIntent( showMenu , hideMenu );
};


/**
* This function preloads rollover images and stores the path
* of those image to the HTML DOM element for later use.
* @param  i  Interation integer passed to this function from jQuery().each()
*/
navigation.initRoll = function(i){
	var sDefaultSrc = this.src;

	if (sDefaultSrc.lastIndexOf('_0.gif') == sDefaultSrc.length-6)
	{
		var sHoverSrc = sDefaultSrc.replace('_0.gif', '_1.gif');

		this.src_0 = sDefaultSrc;
		this.src_1 = sHoverSrc;

		// preload the image
		if(!document.initRollImages){ document.initRollImages=new Array(); }
		document.initRollImages[i] = new Image;
		document.initRollImages[i].src = sHoverSrc;
	}
};


/**
* This function changes the src of the image/input to the hover state.
*/
navigation.rollOver = function(){
	this.src = this.src_1;
};


/**
* This function changes the src of the image/input to the default state.
*/
navigation.rollOut = function(){
	this.src = this.src_0;
};


// ////////////////////////////////////////////////////////////////////////////
// Share This Page
// ////////////////////////////////////////////////////////////////////////////


// share form properties and functions
var share = new Object();
var register = new Object();


/**
* This function gets HTML objects, attaches events, and sets some default values.
*/
share.initialize = function(){
	// get FORM object, set it to display none (initially) and override its submit function
	$('#shareForm').css('display','none').submit( share.submit );

	// get anchor object "Share This Page" and attach functions to it
	$('#share').click( share.toggleShare );

	// get input text fields, attach validation check and clear default text
	$('#shareFields input').blur(share.resetValue).focus(share.resetValue)
	
	// get button objects for attaching events
	$('#btnSend').click( share.submit );

	$('#btnCancel,#btnClose').click( share.toggleShare );
};


/**
* This function gets HTML objects, attaches events, and sets some default values.
*/
register.initialize = function(){
	// get FORM object, set it to display none (initially) and override its submit function
	$('#registerForm').css('display','none').submit( register.submit );

	// get anchor object "Share This Page" and attach functions to it
	$('#register').click( register.toggleShare );

	// get input text fields, attach validation check and clear default text
	$('#registerFields input').blur(register.resetValue).focus(register.resetValue)
	
	// get button objects for attaching events
	$('#btnSend').click( register.submit );

	$('#btnCancel,#btnClose').click( register.toggleShare );
};


/**
* This function resets the values of the email input fields
*/
share.resetValue = function(event){
	if( !event ) {
		// if event does not exist, we are showing the form and fields get reset to default
		$('#shareFields input').each(function(){ this.value = this.alt;	this.className = 'instructions'; });
		return true;
	}
	if( event.type == 'focus') {
		// on focus, if the default text is in the input, remove it and remove the instructions class
		if( this.value == this.alt ) {$(this).val('').removeClass('instructions');}
		return true;	
	}
	if( event.type == 'blur') {
		// on blur, if the value is blank, put the instructions back in
		if( $.trim(this.value) == '' ) {$(this).val(this.alt).not('.error').addClass('instructions');}
		return true;
	}
}


/**
* This function resets the values of the email input fields
*/
register.resetValue = function(event){
	if( !event ) {
		// if event does not exist, we are showing the form and fields get reset to default
		$('#shareFields input').each(function(){ this.value = this.alt;	this.className = 'instructions'; });
		return true;
	}
	if( event.type == 'focus') {
		// on focus, if the default text is in the input, remove it and remove the instructions class
		if( this.value == this.alt ) {$(this).val('').removeClass('instructions');}
		return true;	
	}
	if( event.type == 'blur') {
		// on blur, if the value is blank, put the instructions back in
		if( $.trim(this.value) == '' ) {$(this).val(this.alt).not('.error').addClass('instructions');}
		return true;
	}
}



/**
* This function toggles the visibility of the share form and resets the fields to default values.
*/
share.toggleShare = function() {
	// get shareForm
	var oShareForm = $('#shareForm');

	// toggle class on "Share This Page" anchor link
	$('#share').toggleClass('selected');

	if ( oShareForm.is(":hidden")) {
		$('#shareFields').css('display','block');
		$('#shareResponse').css('display','none');
		$('#shareError').html('');

		share.resetValue();

		oShareForm.fadeIn(200);

	} else {
		oShareForm.fadeOut(200);
	}
	return false;
};

/**
* This function toggles the visibility of the share form and resets the fields to default values.
*/
register.toggleShare = function() {
	// get shareForm
	var oRegisterForm = $('#registerForm');

	// toggle class on "Share This Page" anchor link
	$('#register').toggleClass('selected');

	if ( oRegisterForm.is(":hidden")) {
		$('#registerFields').css('display','block');
		$('#registerResponse').css('display','none');
		$('#registerError').html('');

		register.resetValue();

		oRegisterForm.fadeIn(200);

	} else {
		oRegisterForm.fadeOut(200);
	}
	return false;
};



/**
* This function validates the form fields and sets the error message if something is wrong.
*/
share.validate = function() {

	// cycle through fields and decrease invalidInputs
	var invalidCount = 0;

	/*$('#shareFields input[@type="text"]').each(function(){
		if ( isValid('email',this.value) ) {
			this.className = '';
		} else {
			invalidCount++;
			this.className = 'error';
		}
	});*/

	switch( invalidCount ) {
		case 0:
			$('#shareError').html(''); break;
		case 1:
			$('#shareError').html('Invalid Email Address'); break;
		case 2:
			$('#shareError').html('Invalid Email Addresses'); break;
	}

	return (invalidCount === 0);
};

/**
* This function validates the form fields and sets the error message if something is wrong.
*/
register.validate = function() {

	// cycle through fields and decrease invalidInputs
	var invalidCount = 0;

	/*$('#registerFields input[@type="text"]').each(function(){
		
		if ( this.value.length > 1 ) {
			this.className = '';
		} else {
			invalidCount++;
			this.className = 'error';
		}
	});*/

	if( invalidCount > 0 ) {
			$('#registerError').html('The fields indicated above are incomplete. Please complete them to complete your registration.');
	}

	return (invalidCount === 0);
};


/**
* This function calls for validation and submits the data if everything checks out.
*/
share.submit = function() {
	var valid = share.validate();

	// if both input fields are valid
	if ( valid ) {

		// get section and page id
		var sEmailFr = document.getElementById( 'email_fr' ).value;
		var sEmailTo = document.getElementById( 'email_to' ).value;
		var sSection = document.getElementById( 'section' ).value;
		var sPageId = document.getElementById( 'page_id' ).value;
		var sPageTitle = document.getElementById( 'page_title' ).value;

		var sUrl = document.getElementById( 'shareForm' ).action;

		// compose parameter string to send
		$.post( sUrl , { email_fr: sEmailFr, email_to: sEmailTo , section: sSection , page_id: sPageId , page_title: sPageTitle},function(data){
			// on success update page
			$('#shareMessage').html(data);
			$('#shareFields').css('display','none');
			$('#shareResponse').css('display','block');
		}); // close callback function and close $.post
	}
	return false;
};


/**
* This function calls for validation and submits the data if everything checks out.
*/
register.submit = function() {
	var valid = register.validate();

	// if both input fields are valid
	if ( valid ) {

		// get section and page id
		var firstName = document.getElementById( 'c_first_name' ).value;
		var lastName = document.getElementById( 'c_last_name' ).value;
		var company = document.getElementById( 'c_company' ).value;
		var phone = document.getElementById( 'c_phone' ).value;
		var email = document.getElementById( 'c_email' ).value;
		var state = document.getElementById( 'c_state' ).value;
		var campaign_id = document.getElementById( 'c_campaign_ID' ).value;
		var reg_message = document.getElementById( 'c_reg_message' ).value;

		var sUrl = document.getElementById( 'registerForm' ).action;


		// compose parameter string to send
		$.post( sUrl , { first_name: firstName, last_name: lastName, company: company, phone: phone, email: email, state: state, campaign_id:campaign_id, reg_message:reg_message },function(data){
			// on success update page
			$('#registerMessage').html(data);
			$('#registerFields').css('display','none');
			$('#registerResponse').css('display','block');
		}); // close callback function and close $.post
	}
	return false;
};


// ////////////////////////////////////////////////////////////////////////////
// Form Validation
// ////////////////////////////////////////////////////////////////////////////


isValid = function( type , data ){
	switch(type){
		case 'email':
			var pattern = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
			return pattern.test($.trim(data));
	}
}
