FY = {
	
	_initHooks: [],
	_initialised: false,
	_signedIn: false,
	_searchType: 'studio',
	_results: {},
	
	init: function()
	{
		FY.initSearch();
		FY.initSigninForm();
		FY.initSignup();
		FY.initVerify();
		FY.initForgottenPassword();
		FY.initProfile();
		
		// determine if there is a member signed in or not (need a better solution)
		if ( Aurora.dataAPI.data.load.client && Aurora.dataAPI.data.load.client.memberId && Aurora.dataAPI.data.load.client.memberId.length )
			FY._signedIn = true;
		
		FY._initHooks.each( function( fn ) { fn(); } );
		
		FY._initialised = true;
		
		new SmoothScroll();
		
	},
	
	onInit: function( fn )
	{
		if ( FY._initialised )
			fn();
		else
			FY._initHooks.push( fn );
	},
	
	initProfile: function()
	{
		if ( !$( 'button_editProfile' ) )
			return;
	
		$( 'button_editProfile' ).addEvent( 'click', function(e) {
		
			if ( !Aurora.dataAPI.data.load.client.isVerified ) {
				alert( 'You must first verify your account before editing your profile.\n\nPlease sign out, then sign in again using the temporary password sent to your email address to verify your account.' );
				return;
			}
				
			FY.initProfilePopup();
		});
	
	},
	
	initSearch: function()
	{
		if ( !$( 'searchBox' ) || !$( 'searchForm' ) )
			return;
		
		// Default fields
		FY.FormTools.initDefaultValueAsHint( 'studioForm_nameKeyword', 'name or keyword' );
		FY.FormTools.initDefaultValueAsHint( 'studioForm_cityStateZip', 'city, state, or zip code' );
		
		FY.FormTools.initDefaultValueAsHint( 'teacherForm_nameKeyword', 'name or keyword' );
		FY.FormTools.initDefaultValueAsHint( 'teacherForm_cityStateZip', 'city, state, or zip code' );
		
		FY.FormTools.initDefaultValueAsHint( 'eventForm_cityStateZip', 'city, state, or zip code' );
		
		// Add events to tabs
		$$( '.searchTab' ).each( function( tab ) {
			tab.addEvent( 'click', function(e) {
				e.stop();
				FY.switchTab( tab.getProperty( 'id' ).slice( 4 ) )
			});
		});
		
		// Add events to drop down lists
		$( 'studioForm_styles' ).addEvent( 'click', function() {
			FY.renderDropdown( this, 'yogaStyles', 'studioForm_nameKeyword' );
		});
		
		// Make sure enter events work		
		$( 'studioForm_nameKeyword' ).addEvent( 'keyup', function(e) {
			if ( e.key == 'enter' ) FY.findStudios();
		});
		
		$( 'studioForm_cityStateZip' ).addEvent( 'keyup', function(e) {
			if ( e.key == 'enter' ) FY.findStudios();
		});
		
		$( 'teacherForm_nameKeyword' ).addEvent( 'keyup', function(e) {
			if ( e.key == 'enter' ) FY.findTeachers();
		});
		
		$( 'teacherForm_cityStateZip' ).addEvent( 'keyup', function(e) {
			if ( e.key == 'enter' ) FY.findTeachers();
		});
		
		$( 'eventForm_cityStateZip' ).addEvent( 'keyup', function(e) {
			if ( e.key == 'enter' ) FY.findEvents();
		});
		
		// Find Yoga buttons
		$( 'button_findYogaStudios' ).addEvent( 'click', function(e) {
			FY.findStudios();
		});
		
		$( 'button_findYogaTeachers' ).addEvent( 'click', function(e) {
			FY.findTeachers();
		});
		
		$( 'button_findYogaEvents' ).addEvent( 'click', function(e) {
			FY.findEvents();
		});
		
	},
	
	findStudios: function()
	{
		var keyword = ( $( 'studioForm_nameKeyword' ).value == 'name or keyword' ? '' : $( 'studioForm_nameKeyword' ).value );
		var cityStateZip = ( $( 'studioForm_cityStateZip' ).value == 'city, state, or zip code' ? '' : $( 'studioForm_cityStateZip' ).value );
	
		var url = '/Page/Studios';
		
		if ( cityStateZip )
			url += '/' + cityStateZip;
		
		if ( keyword )
			url += '?keywords=' + keyword.clean();
			
		top.location.href = url;

	},
	
	findTeachers: function()
	{
		var keyword = ( $( 'teacherForm_nameKeyword' ).value == 'name or keyword' ? '' : $( 'teacherForm_nameKeyword' ).value );
		var cityStateZip = ( $( 'teacherForm_cityStateZip' ).value == 'city, state, or zip code' ? '' : $( 'teacherForm_cityStateZip' ).value );
	
		var url = '/Page/Teachers';
		
		if ( cityStateZip )
			url += '/' + cityStateZip;
		
		if ( keyword )
			url += '?keywords=' + keyword.clean();
			
		top.location.href = url;

	},
	
	findEvents: function()
	{	
		var cityStateZip = ( $( 'eventForm_cityStateZip' ).value == 'city, state, or zip code' ? '' : $( 'eventForm_cityStateZip' ).value );
		
		var url = '/Page/Events';
		
		if ( cityStateZip )
			url += '/' + cityStateZip;
			
		top.location.href = url;

	},
	
	renderDropdown: function( button, type, field )
	{
		var $field;
		
		try {
			$field = $( field );
		}
		catch(e) { $log( "FY.renderDropdown :: The HTML Element for field '" + field + "' could not be found." ); }
	
		// Create, position and add events to the dropdown
		var position = button.getPosition();
	
		var posX = ( $field ? position.x - 3 : position.x + 6 );
		var posY = ( $field ? position.y - 3 : position.y + 6 );
	
		var dropdown = new Element( 'div', {
			'class': 'selectfield',
			styles: {
				left: posX + 'px',
				top: posY + 'px',
				width: 'auto'
			}
		});
		
		var setSize = function()
		{
			// Height
			dropdown.setStyle( 'height', 'auto' );
			
			var listSize = dropdown.getSize();
			
			if ( listSize.y > 250 )
				dropdown.setStyle( 'height', '250px' );
				
			// Width (applied if we have no field to work with, defaults to button width)
			if ( !$field )
			{
				var paddingWidth = button.getSize().x -
								   button.getStyle( 'padding-left' ).toInt() -
								   button.getStyle( 'padding-right' ).toInt();
				
				dropdown.setStyle( 'width', paddingWidth );
			}
			else
			{
				// Set a min width if less than the threshold
				if ( listSize.y < 125 )
					dropdown.setStyle( 'width', '125px' );
			}
				
		}
		
		var hideDropdown = function()
		{
			( function() {
			
				dropdown.empty().destroy();
				
			}).delay(1);
			
			unbindEvents();
		}
		
		// Different events in IE	
		if ( window.Browser.Engine.name == 'trident' )
		{		
			var unbindEvents = function() {
				document.removeEvent( 'mousedown', hideDropdown );
			}
			
			document.addEvent( 'mouseup', hideDropdown );
		}
		else
		{
			var unbindEvents = function() {
				window.removeEvent( 'mousedown', hideDropdown );
			}
			
			window.addEvent( 'mouseup', hideDropdown );
		}
		
		// Populate the items into the dropdown
		try {
			var items = Aurora.dataAPI.data.load[ type ].results;
		}
		catch(e) {}
		
		if ( !items )
		{
			$log( 'Item data not available!' );
			return;
		}
		
		if ( !items.length )
		{
			new Element( 'a', { text: '(no items found)', href: 'javascript:;', styles: { display: 'block' } } ).inject( dropdown );
		}
			
		items.each( function( item ) {
		
			var link = new Element( 'a', {
				text: item.name,
				href: 'javascript:;',
				styles: {
					display: 'block'
				}	
			})
			.addEvent( 'click', function(e) {

				var selected = link.get( 'text' );
	
				if ( $field ) {
					$field.fireEvent( 'focus' );
					$field.value += ( $field.value ? ' ' : '' ) + selected + '';
					return;
				}
				
				// If no field is specified, we need to rename the actual link itself to the selected item
				button.set( 'html', '<span class="dropdown">' + selected + '</span>' );
				
			})
			
			link.inject( dropdown );
			
		});
		
		setSize();
		
		// Set the size and inject it
		dropdown.inject( document.body );
				
		setSize();
		
	},
	
	switchTab: function( tab )
	{
		$( 'tab_' + FY._searchType ).removeClass( 'selected' );
		$( 'tab_' + tab ).addClass( 'selected' );
		
		$( FY._searchType + 'Form' ).hide();
		$( tab + 'Form' ).show();
		
		FY._searchType = tab;

	},
	
	initSigninForm: function()
	{		
		// make sure the signin form exists first...
		if ( !$( 'signinForm' ) )
			return;
			
		// IE7 doesn't like changing the type of a field dynamically, so its set to password initial, which means we need to change it back here
		if ( Browser.Engine.name != 'trident' )
			$( 'signinForm_password' ).setProperty( 'type', 'text' );
		
		FY.FormTools.initDefaultValueAsHint( 'signinForm_emailAddress', 'email address' );
		FY.FormTools.initDefaultValueAsHint( 'signinForm_password', 'password', true );
		
		$( 'signinForm' ).addEvent( 'submit', function( e ) {
			
			e.stop();
			FY.signin();
		
		});
	},
	
	signin: function() {
	
		var data = {
			username: $( 'signinForm_emailAddress' ).value,
			password: $( 'signinForm_password' ).value
		}
		
		FY.FormTools.removeDefaults( data, {
			username: 'email address',
			password: 'password'
		});
		
		if ( !FY.FormTools.validateFields( data, {
				'username': 'Please enter your email address to sign in.',
				'password': 'Please enter your password to sign in.'
			}))
			return;
		
		$( 'signinForm_submit' ).set( 'value', '...' ).set( 'disabled', true );
		
		Aurora.callAction({
			
			action: 'member.signIn',
			data: data,
			
			onComplete: function( rtnData ) {
			
				if ( !rtnData.success )
				{
					switch ( rtnData.errorKey )
					{
						case "Not Verified":
							$( 'verifyForm' ).show();
							$( 'signinForm' ).hide();
							$( 'verifyForm_memberId' ).set( 'value', rtnData.verifyMemberId );
							try{ $( 'verifyForm_newPassword' ).focus(); } catch(e) {}
						break;
						
						default:
							alert( 'Oops! Something went wrong. Please check your email address and password and try again.' );
							
							
					}
					
					$( 'signinForm_submit' )
						.set( 'value', ' Go ' )
						.set( 'disabled', false );
					
					return;
				}
				
				var url_sitePart = top.location.href.match(/\/site\/[^\?\/]+/i);
				var redirectPage = rtnData.pages.split(',')[0];
				var redirectHREF = ( ( url_sitePart && url_sitePart.length && url_sitePart[0].length ) ? url_sitePart[0] : '' ) + '/Page/' + redirectPage;
				
				top.location.href = redirectHREF;
			
			}
			
		});
	
	},
	
	initSignup: function()
	{		
		if ( !$( 'signinForm_signupLink' ) )
			return;
		
		$( 'signinForm_signupLink' ).addEvent( 'click', function(e) {
			FY.initSignupPopup();
		});
		
		if ( $( 'addYourOwnListing' ) ) {
			$( 'addYourOwnListing' ).addEvent( 'click', function(e) {
				FY.initSignupPopup();
			});
		}
		
		if ( $( 'button_myStudioSignup' ) ) {
			$( 'button_myStudioSignup' ).addEvent( 'click', function(e) {
				FY.initSignupPopup();
			});
		}
	},
	
	initForgottenPassword: function() {
	
		// make sure the forgot password exists first...
		if ( !$( 'passwordForm' ) )
			return;
		
		// add a click event to the forgotten password link to reveal the form
		$( 'signinForm_forgottenPasswordLink' ).addEvent( 'click', function( e ) {
		
			$( 'signinForm' ).hide();
			$( 'passwordForm' ).show();
		
		});
		
		$( 'passwordForm_cancel' ).addEvent( 'click', function( e ) {
		
			$( 'passwordForm' ).hide();
			$( 'signinForm' ).show();
			
			$( 'passwordForm_emailAddress' ).value = '';
			
			$( 'passwordForm_emailAddress' ).fireEvent( 'blur' );
		
		});
		
		
		FY.FormTools.initDefaultValueAsHint( 'passwordForm_emailAddress', 'email address' );
		
		
		// add a submit event to the form itself
		$( 'passwordForm' ).addEvent( 'submit', function(e) {
	
			e.stop();
	
			var data = {
				emailAddress: $( 'passwordForm_emailAddress' ).value
			}
			
			if ( !FY.FormTools.validateFields( data, {
					'emailAddress': 'Please enter your email address to retrieve your password.'
				}))
				return;
			
			$( 'passwordForm_submit' ).set( 'value', '...' ).set( 'disabled', true );
			
			Aurora.callAction({
				
				action: 'SendPassword',
				data: data,
				
				onComplete: function( rtnData ) {
				
					if ( !rtnData.success )
					{
						alert( "Oops! Something went wrong. Please check your email address and try again." );
						
						$( 'passwordForm_submit' )
							.set( 'value', ' Go ' )
							.set( 'disabled', false );
						
						return;
					}
					
					$( 'passwordForm' ).hide();
					$( 'signinForm' ).show();
					
					$( 'passwordForm_emailAddress' ).set( 'value', '' );
					$( 'passwordForm_submit' ).set( 'value', 'Send' ).set( 'disabled', false );
					
					alert( 'Your password has been sent to your email address! Please check your email and then sign in.' );
				
				}
				
			});

		});
	
	},
	
	initVerify: function() {
		
		// make sure the verify form exists first...
		if ( !$( 'verifyForm' ) )
			return;
		
		FY.FormTools.initDefaultValueAsHint( 'verifyForm_newPassword', 'new password', true );
		FY.FormTools.initDefaultValueAsHint( 'verifyForm_confirmPassword', 'confirm password', true );
		
		$( 'verifyForm' ).addEvent( 'submit', function(e) {
			
			e.stop();
			
			var data = {
				memberId: $( 'verifyForm_memberId' ).value,
				newPassword: $( 'verifyForm_newPassword' ).value,
				confirmPassword: $( 'verifyForm_confirmPassword' ).value
			};
			
			if ( !FY.FormTools.validateFields( data, {
					'memberId': 'Sorry, something went wrong and we can\'t find your member ID. Please try signing in again.',
					'newPassword': 'Please enter your new password.',
					'confirmPassword': 'Please enter your new password again in the "confirm" box.'
				}))
				return;
			
			if ( data.newPassword.length < 6 )
			{
				alert( "Please enter a password at least six characters long." );
				return;
			}
			
			if ( data.newPassword != data.confirmPassword )
			{
				alert( "Please make sure the password you entered in both fields matches." );
				return;
			}
			
			
			$( 'verifyForm_submit' ).set( 'value', '...' ).set( 'disabled', true );
				
			
			Aurora.callAPI({
				
				key: 'update verify',
				data: data,
				
				onComplete: function( rtnData ) {
					
					if ( rtnData.success )
					{
						
						$( 'signinForm_password' ).set( 'value', data.newPassword );
						FY.signin();
						
					}
					else
					{
						$log( rtnData );
						alert( "Sorry, there was an error setting your new password. Please reload the page and try again.\n\nIf you continue to get this message, please get in contact with us." );
						return;
					}
					
				}
				
				
			});
			
		});
		
	},
	
	registerPopup: function()
	{
		var popupHTML = '<div style="text-align: center;">' +
				'<h2 style="font-size: 19px; margin-bottom: 20px;">You need to be signed in to do that!</h2>' +
				'<p style="margin-bottom: 26px;">Register for a free account today!</p>' +
				'<a class="bttn_green" href="javascript:;" id="popup_button_register">' +
					'<span class="wrap1">' +
						'<span class="wrap2">REGISTER</span>' +
					'</span>' +
				'</a>' +
			'</div>';

		var popup = new Aurora.Popup({
				width: 450,
				height: 200,
				zIndex: 100,
				transitionDelay: 4,
				transitionInSteps: 6,
				transitionOutSteps: 6
			})
			.addEvent( 'ready', function() {
	
				new Element( 'div', {
						style: 'font-size: 14px; margin: 20px 25px 20px 20px;'
					})
					.setHTML( popupHTML )
					.inject( this.$content );
					
				$( 'popup_button_register' ).addEvent( 'click', function() {
				
					$( 'container_joinForm' ).setStyles( '-moz-border-radius: 6px; margin-top: -10px; border: 2px solid #0092CF; width: 510px; float: right; padding: 10px; background: #a0ff57;' );
					
					$( 'signinForm' ).hide();
					$( 'joinForm' ).show();
					
					popup.close();
					
					new Fx.Scroll( window ).toElement( 'newTopicForm' );
					
					( function() {
					
						$( 'container_joinForm' ).set( 'tween', { duration: 1500 });
           				$( 'container_joinForm' ).tween( 'background-color', '#fff' );
							
					}).delay( 1500 );

				});
		
			});
		
	}
					
}

FY.FormTools = {
	
	removeDefaults: function( data, fields )
	{
		for ( var i in fields )
		{
			if ( data[ i ] == fields[ i ] )
				data[ i ] = '';
		}
		
		return data;
	},
	
	validateFields: function( data, fields )
	{
		var rtn = true;
		
		for ( var i in fields )
		{
			if ( !$chk( data[ i ] ) )
			{
				alert( fields[ i ] );
				rtn = false;
				break;
			}
		}
		
		return rtn;
			
	},
	
	initDefaultValueAsHint: function( field, defaultValue, passwordField )
	{
		var $field = $( field );
		
		if ( !$field )
			return;
		
		if ( !$chk( field.value ) ) {
			
			// testing different solution
			if ( $field.value == defaultValue ) {
			
				$field.value = defaultValue;
				$field.setStyle( 'color', '#a5a5a5' );
				
			}
			else // testing different solution
				$field.setStyle( 'color', '#262626' );
			
		}
		
		$field.addEvent( 'focus', function() {
				
				if ( this.value != defaultValue )
					return;
				
				if ( passwordField && Browser.Engine.name != 'trident' )
					this.setProperty( 'type', 'password' );
				
				this.value = '';
								
				this.setStyle( 'color', '#262626' );
			
			})
			.addEvent( 'blur', function() {
				
				if ( !this.value.length )
				{
					if ( passwordField && Browser.Engine.name != 'trident' )
						this.setProperty( 'type', 'text' );
					
					this.value = defaultValue;
					
					this.setStyle( 'color', '#a5a5a5' );
				}
			
			});
		
		return $field;
	},
	
	getValue: function( form, key )
	{
	    var form = $( form );
	    var inputValue = form[ key ].value; // default to the value of the field in case we sent the function a text input field or a select field
	    
	    // just return the value if its an invalid field (see above)
	    if ( !form[ key ].length )
	        return inputValue;
	
	    // otherwise loop through all the fields until we get a true value, then return it
	    for ( var i = 0; i <= form[ key ].length - 1; i++) {
	    
	        var inputValue = form[ key ][ i ].checked;
	
	        if ( inputValue )
	        {
	            // $log( 'found true value, returning: ' + inputValue )
	            
	            var inputValue = form[ key ][ i ].value;
	            
	            return inputValue; 
	        }
        
		}

	}
	
}

FY.ManageTools = {

	getParameter: function( key, url ) {  
	    
	    if ( arguments.length < 2 ) url = location.href;
	    
	    if ( arguments.length > 0 && key != "" ) {  
	        
	        if ( key == "" ) {  
	            var regex = new RegExp("[]([^$]*)");  
	        } else if ( key == "?"){  
	            var regex = new RegExp("[?]([^$]*)");  
	        } else {  
	            var regex = new RegExp("[?&]"+key+"=([^&]*)");  
	        }
	        
	        var results = regex.exec(url);
	          
	        return (results == null ) ? "" : results[1];
	        
	    } else {
	    
	        url = url.split("?"); 
	         
	        var results = {};  
	        
            if ( url.length > 1 ) {  
            
                url = url[1].split("");
                
                if(url.length > 1) results["hash"] = url[1];
                 
                url[0].split("&").each( function( item, index ) {  
                    item = item.split("=");  
                    results[item[0]] = item[1];  
                });
                
            }
            
	        return results;  
	    }  
	}

}

window.addEvent( 'domready', function() {
	
	FY.init();
	
})
