// CLASSES ***************************************************************************************************************************************************

/*
	@Class:			Rotator
	@Author:		Brandon Gray for O3 World 2011
	@Brief:			Controls the display of content in a rotator callout
	@Requirements:	Mootools 1.3
*/
var Rotator = new Class ({

	Implements: [ Options ],

	options: {},

	initialize: function( options ) {

		this.setOptions( options );

		this.links	= $$( '.rotator ul a' );	// Collection of rotator navigation links
		this.content	= $$( '.rotator .slide' );	// Collection of rotator content images
		this.pos		= 0;						// Current position
		this.total	= this.links.length;		// Total - duh
		this.isPaused	= false;					// Boolean for whether or not the rotator has been paused - again...duh
		this.timer	= null;  // Periodical timer function
		
		if ( this.links.length < 2 ) {
			$$( '.rotator ul' )[ 0 ].setStyle( 'display', 'none' );
			this.content[ 0 ].setStyle( 'visibility', 'visible' );
		} else {
			this.timer = this.updateCount.bind( this ).periodical( 4000 );
			
			for ( var i = 0, len = this.total; i < len; i++ ) {
				// Assign events to each of the navigation items
				this.links[ i ].addEvent( 'click', this.updateCount.bindWithEvent( this, [ i ] ) );
				// Set some default styles to stack the images correctly
				this.content[ i ].setStyles({
					'z-index': 	this.total - i,
					'visibility': 	'visible'
				});
			}
		}

	},

	updateCount: function( event, i ) {

		// Update the position
		( this.pos != ( this.total - 1 ) ) ? this.pos++ : this.pos = 0;

		// If an event is passed it means the user clicked a link, so put a stop to the auto rotating from here on out
		if ( event ) {
			$clear( this.timer );
			this.timer		= null;
			this.isPaused	= true;
			this.pos		= i;  // Overwrite the currently updated position with the one the user clicked on
			event.stop();
		};

		this.setMenu();
		this.setContent();

	},

	setMenu: function() {

		// Remove the active state from all links
		for ( var i = 0, len = this.total; i < len; i++ ) {
			this.links[ i ].removeClass( 'active' );
		};

		// Set the active display on the current link
		this.links[ this.pos ].addClass( 'active' );
		// Display the appropriate content
		this.setContent( );

	},

	setContent: function() {

		for ( var i = 0, len = this.total; i < len; i++ ) {

			this.content[ i ].setStyle( 'display', 'none' );
			this.content[ i ].setStyle( 'opacity', '0' );

		};

		this.content[ this.pos ].setStyle( 'display', 'block' );
		this.content[ this.pos ].fade( '1' );

	}

});

/*
	@Class:			Tabs
	@Author:		Brandon Gray for O3 World 2011
	@Brief:			Provide functionality for tabbing system on the professional's detail page
	@Requirements:	Mootools Core 1.3
*/
var Tabs = new Class({

	initialize: function() {

		this.tabLinks	= $$( '#pro_tabs a' );
		this.tabDivs	= $$( '.tab_content' );
		this.tabTotal	= this.tabLinks.length;

		for ( var i = 0, len = this.tabTotal; i < len; i++ ) {
			this.tabLinks[ i ].addEvent( 'click', this.switchTab.bindWithEvent( this, [ i ] ) );
		};

	},

	switchTab: function( event, i ) {

		for ( var j = 0, len = this.tabTotal; j < len; j++ ) {
			this.tabLinks[ j ].removeClass( 'active' );
			this.tabDivs.setStyle( 'display', 'none' );
		};

		this.tabLinks[ i ].addClass( 'active' );
		this.tabDivs[ i ].setStyle( 'display', 'block' );

		event.stop();

	}

});


/*
@Class:     	ScrollSpy
@Authors: 		David Walsh (http://davidwalsh.name)
@License: 		MIT-style license
@Requirements:  core/1.2.1:   '*'

*/
var ScrollSpy = new Class({

	/* implements */
	Implements: [Options,Events],

	/* options */
	options: {
		container: window,
		max: 0,
		min: 0,
		mode: 'vertical'/*,
		onEnter: $empty,
		onLeave: $empty,
		onScroll: $empty,
		onTick: $empty
		*/
	},

	/* initialization */
	initialize: function(options) {
		
		/* set options */
		this.setOptions(options);
		this.container = document.id(this.options.container);
		this.enters = this.leaves = 0;
		this.inside = false;
		
		/* listener */
		var self = this;
		this.listener = function(e) {
			/* if it has reached the level */
			var position = self.container.getScroll(),
				xy = position[self.options.mode == 'vertical' ? 'y' : 'x'];
			/* if we reach the minimum and are still below the max... */
			if(xy >= self.options.min && (self.options.max == 0 || xy <= self.options.max)) {
					/* trigger enter event if necessary */
					if(!self.inside) {
						/* record as inside */
						self.inside = true;
						self.enters++;
						/* fire enter event */
						self.fireEvent('enter',[position,self.enters,e]);
					}
					/* trigger the "tick", always */
					self.fireEvent('tick',[position,self.inside,self.enters,self.leaves,e]);
			}
			/* trigger leave */
			else if(self.inside){
				self.inside = false;
				self.leaves++;
				self.fireEvent('leave',[position,self.leaves,e]);
			}
			/* fire scroll event */
			self.fireEvent('scroll',[position,self.inside,self.enters,self.leaves,e]);
		};
		
		/* make it happen */
		this.addListener();
	},
	
	/* starts the listener */
	start: function() {
		this.container.addEvent('scroll',this.listener);
	},
	
	/* stops the listener */
	stop: function() {
		this.container.removeEvent('scroll',this.listener);
	},

	/* legacy */
	addListener: function() {
		this.start();
	}
});


// BASE CLASS EXTENSIONS/IMPLEMENTATIONS *********************************************************************************************************************

String.implement({

	// Formats a input field as a phone number while typing ex: (888) 777-6666
	formatPhone: function() {

		var newphone		= this.replace( /[^\d]/g, "" );
		var phonematches	= newphone.match( /^(\d{0,3})(\d{0,3})(\d{0,4})/ );

		if ( phonematches[ 1 ].length > 0 ) {
			newphone = '(' + phonematches[ 1 ];
		};

		if ( phonematches[ 1 ].length == 3 ) {
			newphone += ') ' + phonematches[ 2 ];
			if ( phonematches[ 2 ].length == 3 ) {
				newphone += '-' + phonematches[ 3 ];
			};
		};

		return newphone;

	}

});

// GLOBAL FUNCTIONS *************************************************************************************************************************************


var locActive = 0;

function locSetActive( locNum ) {
	if( locActive != 0 ) {
		$( 'location_' + locActive ).removeClass( "active" );
	}
	if( locNum != 0 ) {
		$( 'location_' + locNum ).addClass( "active" ).setStyle( 'opacity', 0 ).fade( 1 );
		$( 'info_' + locNum ).getElements( 'a,h1,p,li a' ).setStyle( 'opacity', 0 ).fade( 1 );
	}
	locActive = locNum;
}

function locationsMap( ) { if( GBrowserIsCompatible( ) ) {

	var gmapIcon = new GIcon(G_DEFAULT_ICON);

	gmapIcon.image = webRoot + "images/icon_google_map.png";
	gmapIcon.iconSize = new GSize( 56, 48 );
	gmapIcon.shadow = webRoot + "images/icon_google_map_shadow.png";
	gmapIcon.shadowSize = new GSize( 56, 48 );
	gmapIcon.infoWindowAnchor = new GPoint( 10, 10 );
	gmapIcon.infoShadowAnchor = new GPoint( 10, 10 );

	var gmap = new GMap2( $( 'locations_map' ) );

	gmap.addControl( new GLargeMapControl( ) );
	gmap.addControl( new GMapTypeControl( ) );
	gmap.setCenter( new GLatLng( 0, 0 ), 0 );

	var gmapPoint = null;
	var gmapMarker = null;
	var gmapBounds = new GLatLngBounds( );

	var locAnchors = $( 'locations_list' ).getElements( 'a' );
	var locIndex = 0;
	var locNum = locAnchors.length;
	var locData = null;
	var locName = "";
	var locHTML = "";

	for( locIndex = 0; locIndex < locNum; locIndex++ ) {

		locData = JSON.decode( unescape( locAnchors[ locIndex ].get( 'data-map' ) ) );

		if( locData.LATITUDE !== "" && locData.LONGITUDE !== "" ) {

			locName = locAnchors[ locIndex ].get( 'text' );

			gmapPoint = new GLatLng( parseFloat( locData.LATITUDE ), parseFloat( locData.LONGITUDE ) );
			gmapBounds.extend( gmapPoint );
			gmapMarker = new GMarker( gmapPoint, { icon: gmapIcon, title: locName } );

			locHTML = $( 'location_html' ).get( 'html' )
				.replace( "__IMAGE__", locData.IMAGE )
				.replace( "__TITLE__", locAnchors[ locIndex ].get( 'text' ) )
				.replace( "__ADDRESS__", locData.ADDRESS )
				.replace( /__LOCATION__/g, locAnchors[ locIndex ].get( 'href' ) )
				.replace( "__PROFESSIONALS__", locData.PROFESSIONALS )
				.replace( "__DRIVING__", escape( locData.LOCATION ) )
				.replace( "__ID__", ( locIndex + 1 ) );

			gmap.addOverlay( gmapMarker );

			gmapMarker.bindInfoWindowHtml( locHTML, { maxWidth: 450 } );
			GEvent.addListener( gmapMarker, 'infowindowopen', new Function( 'locSetActive( ' + ( locIndex + 1 ) + ' );' ) );
			GEvent.addListener( gmapMarker, 'infowindowbeforeclose', new Function( 'locSetActive( 0 );' ) );

		}

	}

	gmap.setZoom( gmap.getBoundsZoomLevel( gmapBounds ) - 0 );
	gmap.setCenter( gmapBounds.getCenter( ) );

} }


/*-- ________________________________________________________________________________________________________________________________ --*/


function trimTextLineByLine( txtEl ) {
	var txtArr = null;
	var txtI = 0;
	var txtN = 0;
	var txtStr = "";
	txtArr = txtEl.value.split( String.fromCharCode( 10 ) );
	txtN = txtArr.length;
	txtStr = "";
	for( txtI = 0; txtI < txtN; txtI++ ) {
		txtArr[ txtI ] = txtArr[ txtI ].trim( );
		if( txtArr[ txtI ] !== "" ) {
			txtStr += ( txtStr !== "" ? String.fromCharCode( 10 ) : "" ) + txtArr[ txtI ];
		}
	}
	txtEl.value = txtStr;
}


function sanitizeAllText( ) {
	inptArr = $$( 'input[type=text],input[type=email],input[type=tel],textarea' );
	var inptI = 0;
	var inptN = inptArr.length;
	var inptEl = null;
	for( inptI = 0; inptI < inptN; inptI++ ) {
		inptEl = inptArr[ inptI ];
		inptEl.value = inptEl.value.replace( /(<([^>]+)>)/ig, "" ).replace( /[^\x0a\x20-\x7e]/g, "" ).trim( );
		if( inptEl.tagName.toLowerCase( ) === "textarea" ) {
			trimTextLineByLine( inptEl );
		}
	}
}


/*-- ________________________________________________________________________________________________________________________________ --*/


var formPrefix = "content";

function formSubmit( ) {
	new Request( {
		url:		$( formPrefix + '_form' ).get( 'action' ),
		method:		'post',
		link:		'ignore',
		onRequest:	function( ) {
			$( formPrefix + '_form_error' ).setStyle( 'display', "none" );
			$( formPrefix + '_form_submit' ).setStyle( 'display', "none" );
			$( formPrefix + '_form_wait' ).setStyle( 'display', "block" );
		},
		onFailure:	function( ) {
			$( formPrefix + '_form_wait' ).setStyle( 'display', "none" );
			$( formPrefix + '_form_submit' ).setStyle( 'display', "block" );
			$( formPrefix + '_form_error' ).setStyle( 'display', "block" );
		},
		onSuccess:	function( submitResponse ) {
			$( formPrefix + '_form_wait' ).setStyle( 'display', "none" );
			if( submitResponse.indexOf( "FormSubmit_SUCCESS" ) != -1 ) {
				$( formPrefix + '_form_wait' ).getParent( ).setStyle( 'display', "none" );
				$( formPrefix + '_form_confirmation' ).setStyle( 'display', "block" );
				if( formPrefix === "popup" ) {
					setTimeout( "window.parent.document.getElementById( 'mbCloseLink' ).fireEvent( 'click' );", 3000 );
				}
			} else {
				$( formPrefix + '_form_error' ).setStyle( 'display', "block" );
				$( formPrefix + '_form_submit' ).setStyle( 'display', "block" );
			}
		}
	} ).send( $( formPrefix + '_form' ) );
}

function contentFormSubmit( ) { formPrefix = "content"; formSubmit( ); }

function calloutFormSubmit( ) { formPrefix = "callout"; formSubmit( ); }

function popupFormSubmit( ) { formPrefix = "popup"; formSubmit( ); }


/*-- ________________________________________________________________________________________________________________________________ --*/

var findProRow 	= 1;
var findProAllDone 	= false;
var findProBottom 	= 0;
var findProScroll 	= null;

function findProRowReveal() {
	
	if ( !findProAllDone ) {
		
		var fpArr = $$( 'li[data-row=' + findProRow + ']' );
		var fpI 	= 0;
		var fpN 	= fpArr.length;
		
		if ( fpN != 0 ) {
			
			for( fpI = 0; fpI < fpN; fpI++ ) {
				if( fpArr[ fpI ].getStyle( 'display' ) === "none" ) {
					fpArr[ fpI ].setStyles( { display: 'inline', opacity: 0 } ).fade( 1 );
				};
			};
			
			findProRow++;
			findProBottom = $( 'page_footer' ).getPosition( ).y + $( 'page_footer' ).getSize( ).y;
			
		} else {
			
			findProAllDone = true;
			findProScroll 	= null;
			
		};
	};
	
};


function findProScrollInit() {
	
	if ( findProScroll != null ) findProScroll.stop();
	findProScroll = null;
	
	findProScroll = new ScrollSpy( {
		container:	window,
		min:			window.getScrollSize().y - window.getSize().y  - 172,
		onEnter:		function( ) {
			findProRowReveal( );
			findProScrollInit( );
		}
	});
	
};

function findPro() {
	
	while( !findProAllDone && ( $( 'page_footer' ).getPosition( ).y < window.getSize( ).y ) ) {
		findProRowReveal();
	};
	findProScrollInit();
	
};

// DOMREADY *********************************************************************************************************************************************


window.addEvent( 'domready', function() {

	if ( $( 'login' ) ) {
		$( 'login' ).addEvent( 'click', function( event ) {
			var header = $$( '.head' )[ 0 ].set( 'tween', {
				duration: 500
			});
			var margin = $$( '.head' )[ 0 ].getStyle( 'margin-top' ).toInt();
			if ( margin == 0 ) {
				header.tween( 'margin-top', -72 );
				$( 'login' ).removeClass( 'active' );
			} else {
				header.tween( 'margin-top', 0 );
				$( 'login' ).addClass( 'active' );
			};
			event.stop();
		} );
	};

	if( location.href.indexOf( "logout/" ) != -1 ) {
		Cookie.write( 'sp_login', "_", { domain: ( location.hostname === "localhost" ? false : location.hostname ), path: "/" } );
	};


	/*-- ________________________________________________________________________________________________ --*/


	// Featured home page content
	if ( $$( '.rotator' ).length != 0 ) { var rotator = new Rotator(); };


	// Salon professional detail page
	if ( $( 'pro_tabs' ) ) { var tabs = new Tabs(); };


	// Events to format phone numbers properly
	$$( 'input[type=tel]' ).addEvent( 'keyup', function ( event ) {
		var target = event.target;
		if ( event.key != 'delete' && event.key != 'backspace' ) {
			target.value = target.value.formatPhone();
		};
	});


	/*-- Find a Salon Plaza --*/
	if ( $( 'locations_map' ) ) {
		locationsMap( );
	};


	/*-- Find a Salon Professional --*/
	if ( $( 'find_pro' ) && !$( 'no_results' ) ) {
		findPro( );
		//var findPro = new FindAPro();
	};


		/*-- ________________________________________________________________________________________________ --*/


	if( $( 'content_form' ) ) {
		new FormCheck( 'content_form', {
			submit: false,
			onSubmit: sanitizeAllText,
			onValidateSuccess: contentFormSubmit
		} );
	}

	if( $( 'callout_form' ) ) {
		new FormCheck( 'callout_form', {
			submit: false,
			onSubmit: sanitizeAllText,
			onValidateSuccess: calloutFormSubmit
		} );
	}

	if( $( 'popup_form' ) ) {
		new FormCheck( 'popup_form', {
			submit: false,
			onSubmit: sanitizeAllText,
			onValidateSuccess: popupFormSubmit
		} );
	}


		/*-- ________________________________________________________________________________________________ --*/


	if( $( 'search_form' ) ) {
		var srchEl = $( 'search_filter' );
		if( !srchEl.value ) {
			srchEl.value = srchEl.get( 'hint' );
		}
		srchEl.addEvent( 'focus', function( ) {
			var srchEl = $( 'search_filter' );
			if( srchEl.value === srchEl.get( 'hint' ) ) {
				srchEl.value = "";
			}
		} );
		$( 'search_submit' ).addEvent( 'click', function( ) {
			var srchEl = $( 'search_filter' );
			var srchHref = $( 'search_form' ).get( 'action' ) + $( 'search_location' ).value + $( 'search_specialty' ).value;
			if( !srchEl.get( 'hint' ) ) {
				location.href = srchHref;
			} else {
				var srchStr = srchEl.value
					.replace( /(<([^>]+)>)/ig, "" )
					.replace( /[^\x20-\x7e]/g, "" )
					.replace( /\x20{2,}/g, " " )
					.toLowerCase( ).trim( );
				srchEl.value = srchStr;
				if( srchStr.length > 1 ) {
					location.href = srchHref + "/search/" + escape( srchStr );
				} else {
					srchBrdr = srchEl.getStyle( 'border-color' );
					var srchX = 0;
					var x = 0;
					var t = 0;
					for( var x = 0; x < 3; x++ ) {
						setTimeout( "$( 'search_filter' ).setStyle( 'border-color', '#379699' );", 100 + t );
						setTimeout( "$( 'search_filter' ).setStyle( 'border-color', '" + srchBrdr + "' );", 200 + t );
						t += 200;
					}
					setTimeout( "$( 'search_filter' ).value = '';", t );
					srchEl.set( 'hint', "" );
				}
			}
		} );
	}


		/*-- ________________________________________________________________________________________________ --*/


	if( $( 'location_filter' ) ) {
		$( 'location_filter' ).addEvent( 'change', function( ) {
			var srchEl = $( 'search_filter' );
			var srchStr = ( srchEl.value !== srchEl.get( 'hint' ) ? "/search/" + escape( $( 'search_filter' ).value ) : "" );
			location.href = $( 'location_form' ).get( 'action' )
				+ $( 'location_filter' ).options[ $( 'location_filter' ).selectedIndex ].value
				+ $( 'search_specialty' ).value
				+ srchStr;
		} );
	}


});

window.addEvent( 'resize', function() {
	
	/*-- Find a Salon Professional --*/
	if ( $( 'find_pro' ) && !$( 'no_results' ) ) findPro(); 
		
});


