/*
	@Class:		moopop 1.1
	@Author:		copyright (c) 2007-2008 by gonchuki - http://blog.gonchuki.com
	@License:		This work is licensed under a Creative Commons Attribution-Share Alike 3.0 License. http://creativecommons.org/licenses/by-sa/3.0/
	@Brief:		Unobtrusive javascript popups via late binding
	@Example: 	<a href="print.cfm" rel="popup[765, 600]">Print This</a>
	@Requirements:	Mootools 1.2
*/

var moopop={width:0,height:0,captureByRel:function(attrVal,parent){this.capture((parent||document).getElements('a[rel*='+(attrVal||'popup')+']'));},capture:function(el,width,height){if($defined(width)&&$defined(height)){this.width=width;this.height=height;}
switch($type(el)){case'string':el=$$(el);case'element':case'array':$splat(el).each(this.add_pop_to,this);}
this.width=null;this.height=null;},add_pop_to:function(el){el.addEvent('click',function(e){e.stop();this.popup(el);}.bind(this));var size=el.get('rel').match(/\[(\d+),\s*(\d+)/)||['',this.width,this.height];var resizable=el.get('rel').match(/,(r)/)||[];if(size[1])el.store('popupprops','top=0, left=0, scrollbars=yes, width='+size[1]+', height='+size[2]+(resizable[1]?', scrollbars=yes, resizable=yes':''));},popup:function(el){window.open(el.get('href'),el.get('name')||'',el.retrieve('popupprops')||'');}};window.addEvent('domready',function(){moopop.captureByRel('popup');});


/*
	mediaboxAdvanced v1.2.0 - The ultimate extension of Slimbox and Mediabox; an all-media script
	updated 2010.01.24
	(c) 2007-2009 John Einselen <http://iaian7.com>
		based on
	Slimbox v1.64 - The ultimate lightweight Lightbox clone
	(c) 2007-2008 Christophe Beyls <http://www.digitalia.be>
	MIT-style license.
*/
var Mediabox;(function(){var A,h,P,H,O,n,F,l,m,k,J,y,t,z=new Image(),V=new Image(),r=false,w=false,S,b,j,c,U,E,M,T,W,e,D,Q,G,x,B,o,i="none",f,d="mediaBox",C;window.addEvent("domready",function(){$(document.body).adopt($$([S=new Element("div",{id:"mbOverlay"}).addEvent("click",N),b=new Element("div",{id:"mbCenter"})]).setStyle("display","none"));j=new Element("div",{id:"mbImage"}).injectInside(b);c=new Element("div",{id:"mbBottom"}).injectInside(b).adopt(new Element("a",{id:"mbCloseLink",href:"#"}).addEvent("click",N),e=new Element("a",{id:"mbNextLink",href:"#"}).addEvent("click",g),T=new Element("a",{id:"mbPrevLink",href:"#"}).addEvent("click",K),E=new Element("div",{id:"mbTitle"}),W=new Element("div",{id:"mbNumber"}),M=new Element("div",{id:"mbCaption"}));y={overlay:new Fx.Tween(S,{property:"opacity",duration:360}).set(0),image:new Fx.Tween(j,{property:"opacity",duration:360,onComplete:I}),bottom:new Fx.Tween(c,{property:"opacity",duration:240}).set(0)}});Mediabox={close:function(){N()},open:function(Z,Y,X){A=$extend({loop:false,stopKey:true,overlayOpacity:0.6,resizeOpening:true,resizeDuration:240,resizeTransition:false,initialWidth:320,initialHeight:180,defaultWidth:640,defaultHeight:360,showCaption:true,showCounter:true,counterText:"({x} of {y})",imgBackground:false,imgPadding:70,scriptaccess:"true",fullscreen:"true",fullscreenNum:"1",autoplay:"true",autoplayNum:"1",autoplayYes:"yes",volume:"100",medialoop:"true",bgcolor:"#000000",wmode:"opaque",useNB:true,playerpath:"/js/NonverBlaster.swf",controlColor:"0xFFFFFF",controlBackColor:"0x000000",showTimecode:"false",JWplayerpath:"/js/player.swf",backcolor:"000000",frontcolor:"999999",lightcolor:"000000",screencolor:"000000",controlbar:"over",controller:"true",flInfo:"true",revverID:"187866",revverFullscreen:"true",revverBack:"000000",revverFront:"ffffff",revverGrad:"000000",usViewers:"true",ytBorder:"0",ytColor1:"000000",ytColor2:"333333",ytQuality:"&ap=%2526fmt%3D18",ytRel:"0",ytInfo:"1",ytSearch:"0",vuPlayer:"basic",vmTitle:"1",vmByline:"1",vmPortrait:"1",vmColor:"ffffff"},X||{});if((Browser.Engine.gecko)&&(Browser.Engine.version<19)){r=true;A.overlayOpacity=1;S.className="mbOverlayFF"}if(typeof Z=="string"){Z=[[Z,Y,X]];Y=0}h=Z;A.loop=A.loop&&(h.length>1);if((Browser.Engine.trident)&&(Browser.Engine.version<5)){w=true;S.className="mbOverlayIE";S.setStyle("position","absolute");L()}q();s(true);n=window.getScrollTop()+(window.getHeight()/2);l=window.getScrollLeft()+(window.getWidth()/2);y.resize=new Fx.Morph(b,$extend({duration:A.resizeDuration,onComplete:R},A.resizeTransition?{transition:A.resizeTransition}:{}));b.setStyles({top:n,left:l,width:A.initialWidth,height:A.initialHeight,marginTop:-(A.initialHeight/2),marginLeft:-(A.initialWidth/2),display:""});y.overlay.start(A.overlayOpacity);return a(Y)}};Element.implement({mediabox:function(X,Y){$$(this).mediabox(X,Y);return this}});Elements.implement({mediabox:function(X,aa,Z){aa=aa||function(ab){x=ab.rel.split(/[\[\]]/);x=x[1];return[ab.href,ab.title,x]};Z=Z||function(){return true};var Y=this;Y.addEvent("contextmenu",function(ab){if(this.toString().match(/\.gif|\.jpg|\.png/i)){ab.stop()}});Y.removeEvents("click").addEvent("click",function(){var ac=Y.filter(Z,this);var ad=[];var ab=[];ac.each(function(af,ae){if(ab.indexOf(af.toString())<0){ad.include(ac[ae]);ab.include(ac[ae].toString())}});return Mediabox.open(ad.map(aa),ab.indexOf(this.toString()),X)});return Y}});function L(){S.setStyles({top:window.getScrollTop(),left:window.getScrollLeft()})}function q(){k=window.getWidth();J=window.getHeight();S.setStyles({width:k,height:J})}function s(X){["object",window.ie?"select":"embed"].forEach(function(Z){Array.forEach(document.getElementsByTagName(Z),function(aa){if(X){aa._mediabox=aa.style.visibility}aa.style.visibility=X?"hidden":aa._mediabox})});S.style.display=X?"":"none";var Y=X?"addEvent":"removeEvent";if(w){window[Y]("scroll",L)}window[Y]("resize",q);document[Y]("keydown",u)}function u(X){switch(X.code){case 27:case 88:case 67:N();break;case 37:case 80:K();break;case 39:case 78:g()}if(A.stopKey){return false}}function K(){return a(H)}function g(){return a(O)}function a(X){if(X>=0){j.set("html","");P=X;H=((P||!A.loop)?P:h.length)-1;O=P+1;if(O==h.length){O=A.loop?0:-1}v();b.className="mbLoading";if(!h[X][2]){h[X][2]=""}Q=h[X][2].split(" ");G=Q.length;if(G>1){B=(Q[G-2].match("%"))?(window.getWidth()*((Q[G-2].replace("%",""))*0.01))+"px":Q[G-2]+"px";o=(Q[G-1].match("%"))?(window.getHeight()*((Q[G-1].replace("%",""))*0.01))+"px":Q[G-1]+"px"}else{B="";o=""}D=h[X][0];D=encodeURI(D).replace("(","%28").replace(")","%29");U=h[P][1].split("::");if(D.match(/quietube\.com/i)){f=D.split("v.php/");D=f[1]}else{if(D.match(/\/\/yfrog/i)){i=(D.substring(D.length-1));if(i.match(/b|g|j|p|t/i)){i="image"}if(i=="s"){i="flash"}if(i.match(/f|z/i)){i="video"}D=D+":iphone"}}if(D.match(/\.gif|\.jpg|\.png|twitpic\.com/i)||i=="image"){i="img";D=D.replace(/twitpic\.com/i,"twitpic.com/show/full");t=new Image();t.onload=p;t.src=D}else{if(D.match(/\.flv|\.mp4/i)||i=="video"){i="obj";B=B||A.defaultWidth;o=o||A.defaultHeight;if(A.useNB){t=new Swiff(""+A.playerpath+"?mediaURL="+D+"&allowSmoothing=true&autoPlay="+A.autoplay+"&buffer=6&showTimecode="+A.showTimecode+"&loop="+A.medialoop+"&controlColor="+A.controlColor+"&controlBackColor="+A.controlBackColor+"&defaultVolume="+A.volume+"&scaleIfFullScreen=true&showScalingButton=true&crop=false",{id:"MediaboxSWF",width:B,height:o,params:{wmode:A.wmode,bgcolor:A.bgcolor,allowscriptaccess:A.scriptaccess,allowfullscreen:A.fullscreen}})}else{t=new Swiff(""+A.JWplayerpath+"?file="+D+"&backcolor="+A.backcolor+"&frontcolor="+A.frontcolor+"&lightcolor="+A.lightcolor+"&screencolor="+A.screencolor+"&autostart="+A.autoplay+"&controlbar="+A.controlbar,{id:"MediaboxSWF",width:B,height:o,params:{wmode:A.wmode,bgcolor:A.bgcolor,allowscriptaccess:A.scriptaccess,allowfullscreen:A.fullscreen}})}p()}else{if(D.match(/\.mp3|\.aac|tweetmic\.com|tmic\.fm/i)||i=="audio"){i="obj";B=B||A.defaultWidth;o=o||"20px";if(D.match(/tweetmic\.com|tmic\.fm/i)){D=D.split("/");D[4]=D[4]||D[3];D="http://media4.fjarnet.net/tweet/tweetmicapp-"+D[4]+".mp3"}if(A.useNB){t=new Swiff(""+A.playerpath+"?mediaURL="+D+"&allowSmoothing=true&autoPlay="+A.autoplay+"&buffer=6&showTimecode="+A.showTimecode+"&loop="+A.medialoop+"&controlColor="+A.controlColor+"&controlBackColor="+A.controlBackColor+"&defaultVolume="+A.volume+"&scaleIfFullScreen=true&showScalingButton=true&crop=false",{id:"MediaboxSWF",width:B,height:o,params:{wmode:A.wmode,bgcolor:A.bgcolor,allowscriptaccess:A.scriptaccess,allowfullscreen:A.fullscreen}})}else{t=new Swiff(""+A.JWplayerpath+"?file="+D+"&backcolor="+A.backcolor+"&frontcolor="+A.frontcolor+"&lightcolor="+A.lightcolor+"&screencolor="+A.screencolor+"&autostart="+A.autoplay,{id:"MediaboxSWF",width:B,height:o,params:{wmode:A.wmode,bgcolor:A.bgcolor,allowscriptaccess:A.scriptaccess,allowfullscreen:A.fullscreen}})}p()}else{if(D.match(/\.swf/i)||i=="flash"){i="obj";B=B||A.defaultWidth;o=o||A.defaultHeight;t=new Swiff(D,{id:"MediaboxSWF",width:B,height:o,params:{wmode:A.wmode,bgcolor:A.bgcolor,allowscriptaccess:A.scriptaccess,allowfullscreen:A.fullscreen}});p()}else{if(D.match(/\.mov|\.m4v|\.m4a|\.aiff|\.avi|\.caf|\.dv|\.mid|\.m3u|\.mp3|\.mp2|\.mp4|\.qtz/i)||i=="qt"){i="qt";B=B||A.defaultWidth;o=(parseInt(o)+16)+"px"||A.defaultHeight;t=new Quickie(D,{id:"MediaboxQT",width:B,height:o,container:"mbImage",attributes:{controller:A.controller,autoplay:A.autoplay,volume:A.volume,loop:A.medialoop,bgcolor:A.bgcolor}});p()}else{if(D.match(/\#mb_/i)){i="inline";B=B||A.defaultWidth;o=o||A.defaultHeight;URLsplit=D.split("#");t=$(URLsplit[1]).get("html");p()}else{A.showCaption=false;A.showCounter=false;i="url";B=B||A.defaultWidth;o=o||A.defaultHeight;d="mediaId_"+new Date().getTime();t=new Element("iframe",{src:D,id:d,width:B,height:o,frameborder:0});p()}}}}}}}return false}function p(){if(i=="img"){B=t.width;o=t.height;if(A.imgBackground){j.setStyles({backgroundImage:"url("+D+")",display:""})}else{if(o>=J-A.imgPadding&&(o/J)>=(B/k)){o=J-A.imgPadding;B=t.width=parseInt((o/t.height)*B);t.height=o}else{if(B>=k-A.imgPadding&&(o/J)<(B/k)){B=k-A.imgPadding;o=t.height=parseInt((B/t.width)*o);t.width=B}}if(Browser.Engine.trident){t=$(t)}t.addEvent("mousedown",function(X){X.stop()}).addEvent("contextmenu",function(X){X.stop()});j.setStyles({backgroundImage:"none",display:""});t.inject(j)}}else{if(i=="obj"){if(Browser.Plugins.Flash.version<8){j.setStyles({backgroundImage:"none",display:""});j.set("html",'<div id="mbError"><b>Error</b><br/>Adobe Flash is either not installed or not up to date, please visit <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" title="Get Flash" target="_new">Adobe.com</a> to download the free player.</div>');B=A.DefaultWidth;o=A.DefaultHeight}else{j.setStyles({backgroundImage:"none",display:""});t.inject(j)}}else{if(i=="qt"){j.setStyles({backgroundImage:"none",display:""});t}else{if(i=="inline"){j.setStyles({backgroundImage:"none",display:""});j.set("html",t)}else{if(i=="url"){j.setStyles({backgroundImage:"none",display:""});t.inject(j)}else{j.setStyles({backgroundImage:"none",display:""});j.set("html",'<div id="mbError"><b>Error</b><br/>A file type error has occoured, please visit <a href="iaian7.com/webcode/mediaboxAdvanced" title="mediaboxAdvanced" target="_new">iaian7.com</a> or contact the website author for more information.</div>');B=A.defaultWidth;o=A.defaultHeight}}}}}j.setStyles({width:B,height:o});E.set("html",(A.showCaption)?U[0]:"");M.set("html",(A.showCaption&&(U.length>1))?U[1]:"");W.set("html",(A.showCounter&&(h.length>1))?A.counterText.replace(/{x}/,P+1).replace(/{y}/,h.length):"");if((H>=0)&&(h[H][0].match(/\.gif|\.jpg|\.png|twitpic\.com/i))){z.src=h[H][0].replace(/twitpic\.com/i,"twitpic.com/show/full")}if((O>=0)&&(h[O][0].match(/\.gif|\.jpg|\.png|twitpic\.com/i))){V.src=h[O][0].replace(/twitpic\.com/i,"twitpic.com/show/full")}B=j.offsetWidth;o=j.offsetHeight+c.offsetHeight;if(o>=n+n-10){F=-(n-10)}else{F=-(o/2)}if(B>=l+l-10){m=-(l-10)}else{m=-(B/2)}if(A.resizeOpening){y.resize.start({width:B,height:o,marginTop:F,marginLeft:m})}else{b.setStyles({width:B,height:o,marginTop:F,marginLeft:m});R()}}function R(){y.image.start(1)}function I(){b.className="";if(i!="url"){if(H>=0){T.style.display=""}if(O>=0){e.style.display=""}}else{T.style.display="none";e.style.display="none"}y.bottom.start(1)}function v(){if(t){t.onload=$empty}y.resize.cancel();y.image.cancel().set(0);y.bottom.cancel().set(0);$$(T,e).setStyle("display","none")}function N(){if(P>=0){t.onload=$empty;j.set("html","");for(var X in y){y[X].cancel()}b.setStyle("display","none");y.overlay.chain(s).start(0)}return false}})();Mediabox.scanPage=function(){var a=$$("a").filter(function(b){return b.rel&&b.rel.test(/^lightbox/i)});$$(a).mediabox({},null,function(c){var b=this.rel.replace(/[[]|]/gi," ");var d=b.split(" ");return(this==c)||((this.rel.length>8)&&c.rel.match(d[1]))})};window.addEvent("domready",Mediabox.scanPage);

var p = window.location.pathname.split( "/" );
if( p[ p.length - 1 ].substr( -1 ) !== "/" ) {
	p[ p.length - 1 ] = "";
};

var relative_path_spanish	= p.join( "/" );
var relative_path			= p.join( "/" );
var relative_path 			= relative_path.replace('sp/','');

//var relative_path	= '/rigidlifelines/trunk/';
//var relative_path	= '/trunk/';
//var relative_path	= '/';

/* //////////////////////////
	validateLogin
*/ //////////////////////////
function validateLogin( x ) {

	if( !checkEmail( x.Login_Email ) ) {
		alert( 'Enter a valid email address to login.' );
		x.Login_Email.focus();
		return false;
	} else if( x.Login_Password.value === '' ) {
		alert( 'Enter your password to login.' );
		x.Login_Password.focus();
		return false;
	} else {
		return true;
	};

};


/* /////////////////////////////
	validateForgottenPassword
*/ /////////////////////////////
function validateForgottenPassword( x ) {

	if( !checkEmail( x.Email ) ) {
		alert( 'Please enter your valid email address.' );
		x.Email.focus();
		return false;
	} else {
		return true;
	};

};


/* //////////////////////////
	validateRegistration
*/ //////////////////////////
function validateRegistration( x ) {

	if( !checkEmail( x.Email ) ) {
		alert( 'Please enter a valid email address.' );
		x.Email.focus();
		return false;
	} else if( x.FirstName.value === '' ) {
		alert( 'Please enter your first name.' );
		x.FirstName.focus();
		return false;
	} else if( x.LastName.value === '' ) {
		alert( 'Please enter your last name.' );
		x.LastName.focus();
		return false;
	} else if( x.Company.value === '' ) {
		alert( 'Please enter the name of your company.' );
		x.Company.focus();
		return false;
	} else if( x.Phone.value === '' ) {
		alert( 'Please enter your phone number.' );
		x.Phone.focus();
		return false;
	} else if( x.Category.value === '' ) {
		alert( 'Please select a category.' );
		x.Category.focus();
		return false;
	} else {
		return true;
	};

};


/* //////////////////////////
	executeSubmitForm
*/ //////////////////////////
function executeSubmitForm( ) {

	var AllForms = $$( 'div.content_wrapper form.ContentForm,div.content_wrapper_sidebar form.ContentForm' );

	if( AllForms.length ) {

		AllForms.each( function( item, index ) {

			item.removeEvents( 'submit' );
			
			$( item.id ).addEvent( 'submit', function( event ) {	
	
				if( validateForm( item.id ) ) {
	
					if( $( 'FormLang' ) && $( 'FormLang' ).value == 'sp' ) {
						var rel_path = relative_path_spanish;
					} else {
						var rel_path = relative_path;
					};					
	
					var MyRequest = new Request( {
										   
						method:		'post',
						url:			rel_path + 'ajax_processing.cfm',
						onRequest: 	function( ) {
							
							$( 'submitBtn' ).addClass( 'hide' );
							$( 'submitWait' ).removeClass( 'hide' );
							$( item.id + '_Form' ).tween( 'opacity', '0.3' );
							
						},
						
						onSuccess: 	function( html ){

							if( html.indexOf( "There was an error" ) > -1 ){
							
								// an error occured, so reshow form and scroll to error message
								if( $( 'form_response' ) ){
								
									$( 'form_response' ).destroy( );
								
								};
								
								var newElement = new Element( 'div' );
								newElement.set( 'id', 'form_response' );
								newElement.set( 'html', html );
								newElement.inject( $( item.id + '_Wrapper' ), 'top' );
								$( 'submitBtn' ).removeClass( 'hide' );
								$( 'submitWait' ).addClass( 'hide' );
								$( item.id + '_Form' ).tween( 'opacity', '1' );
							
								var myFx = new Fx.Scroll( window ).toElement( 'form_response' );
							
							} else {
							
								// form submitted properly, so show response
								$( item.id + '_Wrapper' ).set( 'html', html );
								var myFx = new Fx.Scroll( window ).toElement( item.id + '_Wrapper' );
							};
							
						},
						
						onFailure: 	function( ){
							
							alert( 'Something went wrong... we couldn\'t submit this form. Please try again.' );
							$( 'submitBtn' ).removeClass( 'hide' );
							$( 'submitWait' ).addClass( 'hide' );
							$( item.id + '_Form' ).tween( 'opacity', '1' );
							
						}
						
					} ).send( { data: $( item.id ) } );
	
					event.stop();
	
				};
			
			} );

		} );
	
	};

};

/* //////////////////////////
	validateForm
*/ //////////////////////////
function validateForm( ID ) {
	
	if( $$( '.required' ) ) {
		
		var i		= 0;
		var Valid		= 1;
		var Fields	= $$( 'div.content_wrapper form#' + ID + ' .required' );
		
		if( Fields.length ) {
		
			for( i = 0; i < Fields.length; i++ ) {
			
				if( Fields[i].id.split( '_' )[0] == 'mmmultiple' ) {
				
					var OneChecked = false;
					var NumItems	= Fields[i].id.split( '_' )[1];
									
					for( var j = 0; j < NumItems; j++ ) {
						if( $( Fields[i].name + '_' + j ).checked == true ) {
							OneChecked = true;
							break;
						};
					};
					if( !OneChecked ) {
						alert( 'The ' + Fields[i].name.replace( /_/g, ' ' ) + ' field is a required field.' );
						$( Fields[i].name + '_0' ).focus();
						Valid = 0;
						break;
					};
				
				} else if( Fields[i].getProperty( 'min' ) != null && Fields[i].value.length < parseInt( Fields[i].getProperty( 'min' ) ) ) {
	
					alert( 'The ' + Fields[i].id.replace( '_', ' ' ) + ' field is a requires at least a ' + Fields[i].getProperty( 'min' ) + ' character minimum.' );
					Fields[i].focus();
					Valid = 0;
					break;
	
				} else if( Fields[i].value == '' || Fields[i].value == Fields[i].name || ( Fields[i].name.toLowerCase().indexOf( 'email', 0 ) != -1 && !checkEmail( Fields[i] ) ) ) {
				
					alert( 'The ' + Fields[i].id.replace( '_', ' ' ) + ' field is a required field.' );
					Fields[i].focus();
					Valid = 0;
					break;
				
				};
			
			};
		
		};
		
	} else {
	
		Valid = 0;
	
	};

	if( Valid ){
	
		Valid = checkECommerce( );
		
	};

	return Valid;
	
};


/* //////////////////////////
	checkECommerce
*/ //////////////////////////
function checkECommerce( ){

	var valid = 1;
	
	if( $( 'BillingFirstName' ) ) {
		
		// we are using an ecommerce form
		if( !checkNumeric( $( 'DollarAmount' ) ) ){
		
			alert( 'Please enter the numeric dollar amount without the \'$\' or \',\'' );
			$( 'DollarAmount' ).value = '';
			$( 'DollarAmount' ).focus( );
			valid = 0;
			
		} else if( $( 'DollarAmount_Min' ) && $( 'DollarAmount' ).value < $( 'DollarAmount_Min' ).value ) {
			
			alert( 'The minimum amount allowed is $' + $( 'DollarAmount_Min' ).value );
			$( 'DollarAmount' ).focus( );
			valid = 0;
			
		};
	
	};
	
	return valid;

};


/* //////////////////////////
	checkEmail
*/ //////////////////////////
function checkEmail( FormElement ) {
	if ( !( /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test( FormElement.value ) ) ) {
		return false;	
	} else {
		return true;
	};
};


/* //////////////////////////
	checkNumeric
*/ //////////////////////////
function checkNumeric( FormElement ) {
	if ( !( /^\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$/.test( FormElement.value.trim( ) ) ) ) {
	//if(!(/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/.test( FormElement.value ) ) ) {
		return false;	
	} else {
		return true;
	};
};


/* //////////////////////////
	trim
*/ //////////////////////////
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");    
};


/* //////////////////////////
	initialize
*/ //////////////////////////
function initialize(){
	
	executeSubmitForm();
	
	updateEcommerceTotal();
	
	if( $( 'DollarAmount' ) && $( 'Quantity' ) && $( 'EcommerceTotal' ) ) {
		$( 'EcommerceTotal' ).set( 'html', '$' + ( $( 'DollarAmount' ).value * $( 'Quantity' ).value ).toFixed( 2 ) );
	};

	
};

/* //////////////////////////
	checkMax
*/ //////////////////////////
function checkMax( el, key ) {
	if( el.get( 'max' ) == 0 ) { return true; }
	else { return el.get( 'value' ).length <= el.get( 'max' ); }
	//return ( key != 'backspace' && key != 'delete' ) ? el.get( 'value' ).length <= el.get( 'max' ) : true;	
};

/* //////////////////////////
	validateSendToAFriend
*/ //////////////////////////
function validateSendToAFriend() {

	$( 'SendToAFriendForm' ).removeEvents( 'submit' );
	
	$( 'SendToAFriendForm' ).addEvent( 'submit', function( event ) {	
	
		if( $( 'Name' ).value == "" ) {
			
			alert( 'Please enter your name.' );
			$( 'Name' ).focus();
			
		} else if( !checkEmail( $( 'Email' ) ) ) {
			
			alert( 'Please enter your valid email address.' );
			$( 'Email' ).focus();
			
		} else if( $( 'FriendName' ).value == "" ) {
			
			alert( 'Please enter your friend\'s name.' );
			$( 'FriendName' ).focus();
			
		} else if( !checkEmail( $( 'FriendEmail' ) ) ) {
			
			alert( 'Please enter your friend\'s valid email address.' );
			$( 'FriendEmail' ).focus();
			
		} else if( $( 'TheField' ).value == "" ) {
	
			var MyRequest = new Request( {
				method:		'post',
				url:			relative_path + 'ajax_processing.cfm',
				onRequest: 	function() {
								$( 'ContentForm_Form' ).morph( { height: $( 'ContentForm_Response' ).getSize().y } );
								$( 'ContentForm_Form' ).tween( 'opacity', '0' );
								$( 'ContentForm_Loading' ).tween( 'opacity', '1' );
							},
				onComplete:	function() {
								$( 'ContentForm_Loading' ).morph( { height: 0 } );
								$( 'ContentForm_Loading' ).tween( 'opacity', '0' );
								$( 'ContentForm_Response' ).tween( 'opacity', '1' );
								Initialize( );
							}
			} ).send( { data: $( 'SendToAFriendForm' ) } );
	
		};
		
		event.stop();
		
	} );

};

/* //////////////////////////
	updateEcommerceTotal
*/ //////////////////////////
function updateEcommerceTotal() {

	if( $( 'DollarAmount' ) && $( 'Quantity' ) && $( 'EcommerceTotal' ) ) {
		
		$( 'DollarAmount' ).removeEvents( 'change' );
		$( 'Quantity' ).removeEvents( 'change' );
															
		$( 'DollarAmount' ).addEvent( 'change', function( event ) {
										  
			$( 'EcommerceTotal' ).set( 'html', '$' + ( $( 'DollarAmount' ).value * $( 'Quantity' ).value ).toFixed( 2 ) );
			
			event.stop();
			
		} );
		
		$( 'Quantity' ).addEvent( 'change', function( event ) {
										  
			$( 'EcommerceTotal' ).set( 'html', '$' + ( $( 'DollarAmount' ).value * $( 'Quantity' ).value ).toFixed( 2 ) );
			
			event.stop();
			
		} );
		
	};

};


/* //////////////////////////
	FeaturedProducts
*/ //////////////////////////
var FeaturedProducts = new Class ({
	
	initialize: function()  {
		
		this.pos			= 0;
		this.products		= $$( '#home_feature .product' );
		this.total		= this.products.length;
		
		$( 'pos' ).set( 'text', ( this.pos + 1 ) + ' OF ' + this.total );
		
		$( 'prev' ).addEvent( 'click', function( event ) {
		
			this.fadeProductOut( 'prev' );
			event.stop();
			
		}.bind( this ) );
		
		$( 'next' ).addEvent( 'click', function( event ) {
		
			this.fadeProductOut( 'next' );
			event.stop();
			
		}.bind( this ) );
		
	},
	
	fadeProductOut: function( direction ) {
		
		// Remove button events to prevent people from multi clicking
		$( 'prev' ).removeEvents( 'click' );
		$( 'next' ).removeEvents( 'click' );
		
		// Fade container out
		var newTween = new Fx.Tween( this.products[ this.pos ], { 
										
			onComplete: function() {
				
				this.products[ this.pos ].setStyle( 'display', 'none' );
				this.updatePos( direction );
				
			}.bind( this )
			
		}).start( 'opacity', 0 );
		
	},
	
	updatePos: function( direction ) {
		
		// Update the pos variable
		if ( direction == 'prev' ) {
			
			// If we're currently on the first image then set pos to the last image in the array, otherwise set it to the previous image in the array
			( this.pos == 0 ) ?	this.pos = this.total - 1 : this.pos--;
			
		} else {
			
			// If we're currently on the last image then set pos to the first image in the array, otherwise set it to the next image in the array
			( this.pos == ( this.total - 1 ) ) ? this.pos = 0 : this.pos++;
			
		};
		
		// Set the display position text
		$( 'pos' ).set( 'text', ( this.pos + 1 ) + ' OF ' + this.total );
		
		this.fadeProductIn();
		
	},
	
	fadeProductIn: function() {
		
		this.products[ this.pos ].setStyles({
			
			'display' : 'block',
			'opacity' : 0
									 
		});
		
		var newTween = new Fx.Tween( this.products[ this.pos ], { 
										
			onComplete: function() {
				
				$( 'prev' ).addEvent( 'click', function( event ) {
		
					this.fadeProductOut( 'prev' );
					event.stop();
					
				}.bind( this ) );
				
				$( 'next' ).addEvent( 'click', function( event ) {
				
					this.fadeProductOut( 'next' );
					event.stop();
					
				}.bind( this ) );
						
			}.bind( this )
			
		}).start( 'opacity', 1 );
		
	}
	
});


/* //////////////////////////
	InputClearAndReplace
*/ //////////////////////////
var InputClearAndReplace = new Class ({
	
	options: {
		
		InputElement: '.clear_replace'
		
	},
	
	initialize: function()  {
		
		var inputElementList = $$( this.options.InputElement );
		var originalValue = new Array();
		
		inputElementList.each( function( element, i ) {
			
			originalValue.push( inputElementList[ i ].value );
			
			element.onfocus = function() {
				
				if( this.value == originalValue[ i ] ) this.value = '';
				
			},
			
			element.onblur = function() {
				
				if( this.value == '' ) this.value = originalValue[ i ];
				
			}
			
		});
		
	}

});
	

/* ////////////////////////////////////////////////////////
	ie6NavFix // Drop down display fix for IE6 - typical
*/ ////////////////////////////////////////////////////////
function ie6NavFix() {
	
	var navLists = $$( '#nav li' );
	
	for( var i = 0; i < navLists.length; i++ ) {
	
		if( navLists[i].getChildren( 'div' ).length > 0 ) {
		
			navLists[i].addEvent( 'mouseenter', function() {
				
				this.getChildren( 'div' )[ 0 ].setStyle( 'display', 'block' );
				
			});
			
			navLists[i].addEvent( 'mouseleave', function() {
				
				this.getChildren( 'div' )[ 0 ].setStyle( 'display', 'none' );
				
			});
				
		};
	
	};
	
};

/* //////////////////////////
	ValidateBlogComment
*/ //////////////////////////
function ValidateBlogComment( ) {
	
	// Validate input
	if( $( 'Name' ).value == "" || $( 'Name' ).value == "Name" ) {
		alert( 'Please enter your name.' );
		$( 'Name' ).focus();
		return false;
	} else if( !checkEmail( document.BlogCommentForm.Email ) ) {
		alert( 'Please enter your valid email address.' );
		$( 'Email' ).focus();
		return false;
	} else if( $( 'Comment' ).value == "" || $( 'Comment' ).value == "Comment" ) {
		alert( 'Please enter a comment.' );
		$( 'Comment' ).focus();
		return false;
	} else if( $( 'THP' ).value == "" ) {
		
		// Create new FX's
		var FormFx = new Fx.Tween( $( 'BlogCommentForm' ), { duration: '500', link: 'chain' } );
		if( $( 'comment_form' ) ) { FormFx.start( 'opacity', '1', '1' ); };
		
		var ProcessingFx = new Fx.Tween( $( 'comment_processing' ), { duration: '500', link: 'chain' } );
		if( $( 'comment_processing' ) ) { ProcessingFx.start( 'opacity', '0', '0' ); };
		
		var CompleteFx = new Fx.Tween( $( 'comment_complete' ), { duration: '500', link: 'chain' } );
		if( $( 'comment_complete' ) ) { CompleteFx.start( 'opacity', '0', '0' ); };
		
		// Begin responce
		new Request({
			method:		'post',
			url:			'AJAX_processing.cfm?AJAXRequest=blog_comment',
			link:		'cancel',
			onRequest:	function() {
							FormFx.start( 'opacity', '1', '0' );
							FormFx.start( 'display', 'block', 'none' );
							ProcessingFx.start( 'opacity', '0', '1' );
							//CompleteFx.start( 'opacity', '0', '0' );
						},
			onFailure:	function() {
							//FormFx.start( 'opacity', '0', '0' );
							ProcessingFx.start( 'opacity', '1', '0' );
							$( 'comment_complete' ).set( 'html', '<p>There was an error processing your comment.<br /><br />Please try again.</p>' );
							CompleteFx.start( 'opacity', '0', '1' );
							
							$( 'Name' ).value		= "Name";
							$( 'Email' ).value		= "Email (Will Not Display)";
							$( 'Link' ).value		= "Website";
							$( 'Comment' ).value	= "Comment";

						},
			onSuccess:	function() {
							//FormFx.start( 'opacity', '0', '0' );
							ProcessingFx.start( 'opacity', '1', '0' );
							$( 'comment_complete' ).set( 'html', '<p>Comment submitted successfully!<br /><br />Your comment will appear pending approval.</p>' );
							CompleteFx.start( 'opacity', '0', '1' );

							$( 'Name' ).value		= "Name";
							$( 'Email' ).value		= "Email (Will Not Display)";
							$( 'Link' ).value		= "Website";
							$( 'Comment' ).value	= "Comment";

						}
		}).send( $( 'BlogCommentForm' ) );
				
		return false;
		
	};
};


/* //////////////////////////
	validateSearch
*/ //////////////////////////
function ValidateSearch() {

	$$( '#blog_search' ).removeEvents( 'submit' );
	$$( '#portal_search' ).removeEvents( 'submit' );
	
	$$( '#blog_search, #portal_search' ).each( function( item, index ) {
		$( item.id ).addEvent( 'submit', function( event ) {										  
			var ThisInput = $$( '#' + item.id + ' input.keywords' )[0];
			if( ThisInput.value == "" || ThisInput.value == ThisInput.title ) {
				alert( 'Please enter your search terms.' );
				ThisInput.focus();
			} else {
				$( item.id ).submit();
			};
			event.stop();
		} );
	} );
	
};

/*
	fetchSalesContacts
*/

function fetchSalesContacts( state ) {
	
	var subString = state.substring( 0, state.lastIndexOf( '_' ) );
	if ( subString.indexOf( '_' ) != -1 ) subString = subString.substr( 0, subString.indexOf( '_' ) ) + ' ' + subString.substr( subString.indexOf( '_' ) + 1 );	

	var GetState = new Request.HTML({
		url:			relative_path + 'map.html&AjaxRequest=true&State=' + subString,
		method:		'get',
		evalScripts:	true,
		update:		'content-text'//,
		//onRequest: 	function() {
		//				var coords = $( 'page_wrap' ).getCoordinates();
		//				var myFx = new Fx.Scroll( window, { duration: 350 } ).start( 0, coords.top );
		//			}
	}).send();

};

function setCharAt(str,index,chr) {
	if(index > str.length-1) return str;
	return str.substr(0,index) + chr + str.substr(index+1);
};


// //////////////////////////////////////////////////////////////////////////////////////////////////// //
// //////////////////////////////////////////////////////////////////////////////////////////////////// //
// //////////////////////////////////////////////////////////////////////////////////////////////////// //

window.addEvent( 'domready', function() {
	
	initialize();
	
	if ( Browser.Engine.trident4 ) { ie6NavFix(); };
	
	var InputList = new InputClearAndReplace();
	
	if ( $( 'home_feature' ) ) var featProducts = new FeaturedProducts();
	
	if( $( 'login_wrap' ) && $( 'toggle_login' ) ) {
		$( 'login_wrap' ).setStyle( 'height','auto' );
		// Hide the login panel by default
		var mySlide = new Fx.Slide( 'login_wrap' ).hide();
	
		$( 'toggle_login' ).addEvent( 'click', function( event ) {
			
			mySlide.toggle();
			event.stop();
			
			var arrowSrc = $( 'login_arrow' ).get( 'src' );
			
			if ( arrowSrc == 'images/icon_arrow_white_down.gif' ) {
				$( 'login_arrow' ).set( 'src', 'images/icon_arrow_white_up.gif' )
			} else {
				$( 'login_arrow' ).set( 'src', 'images/icon_arrow_white_down.gif' )
			};
			
		});
	};
	
	if( $( 'SendToAFriendForm' ) ) { validateSendToAFriend(); };

	if( $( 'blog_search' ) || $( 'portal_search' ) ) { ValidateSearch() };
	
	if ( $( 'sales_map' ) ) {
		
		var flashvars 			= {};
		var params    			= {};
		params.wmode 			= "transparent";
		params.menu 			= "false";
		params.allowscriptaccess = "always";
		var attributes 		= {};
		swfobject.embedSWF( relative_path + "flash/map.swf", "sales_map", "716", "700", "9.0.0", relative_path+"expressInstall_PW.fla", flashvars, params, attributes );

	};
	
	if ( $( 'home_flash' ) ) {
		
		var flashvars 			= {};
		var params    			= {};
		params.wmode 			= "transparent";
		params.menu 			= "false";
		params.allowscriptaccess = "always";
		var attributes 		= {};
		swfobject.embedSWF( relative_path + "flash/intro.swf", "flash_intro", "485", "250", "9.0.0", relative_path + "expressInstall_PW.fla", flashvars, params, attributes );

	};
	
} );