  //Cufon.replace('.navigation a');
  Cufon.replace('p.welcomeText');
  Cufon.replace('.headerContainerLogo a');	
  //Cufon.replace('.header h2');	
//  Cufon.replace('.rightColumn h2');  
  
  $.noConflict();
  jQuery(document).ready(function($) {

	//main - home
   	$("a[rel^='prettyPhoto']").prettyPhoto();
	var baseURL = $('.baseURL').attr('title');

   
   	$('.speechBubble').prepend('<a class="btnClose" href="#">close</a>');
	
	var headerPosition = $('.headerContainer .copy').position();
	var bubbleLeftPosition = headerPosition.left;
		
	$('.speechBubble').css({"left":bubbleLeftPosition});
	
	$('a.btnClose').click(function(e)
							{
								e.preventDefault();
								$('.speechBubble').fadeOut(300);
							});

	//if($hideSpeechBubble !='yes' )
	$('.speechBubble').show();

	
	// user login form
	$('.btnLogin').live('click',function(e)
		{
		e.preventDefault();
				
		
		if ( $('.loginUsername').val() != '' && $('.loginPassword').val() != '' )
		{
			$.post( 
				$('.frmLogin').attr('action') + '/', $(".frmLogin").serialize(),
				function(data) {
					if(data == 'NO')
					{
						$('.loginFormContainer').find('.error').remove();
						$('.loginFormContainer').prepend('<div class="error">Invalid username or password</div>').find('.error').hide().fadeIn();
					} else {
						$('.loginFormContainer').find('.error').fadeOut();
						//$(window.location).attr('href', baseURL + 'user/dashboard/');
						window.location = baseURL + 'user/dashboard/';
					}
				});
		
		} 
		});
	
	
	$('.userLogin').click(function(e)
		{
			$("#loginBox").dialog({
				modal: true,
				resizable: false,
				draggable: false
			});
		});
	
	
	$('.btnForgotPassword').click(
		function(e)
		{
			e.preventDefault();
			$('.loginFormContainer').slideUp(300, function()
				{
					$('.forgotPasswordContainer').slideDown(300);	
				});
		});
	
	$('.btnBackToLogin').click(
		function(e)
		{
			e.preventDefault();
			$('.forgotPasswordContainer').slideUp(300, function()
				{
					$('.loginFormContainer').slideDown(300);	
				});
		});
	
	
	
	$('.btnRecover').click(function(e)
		{
			e.preventDefault();
						
			if ( $('.forgotPasswordEmail').val() != '' )
			{
				$.post( 
					$('.frmForgotPassword').attr('action') + '/', $(".frmForgotPassword").serialize(),
					function(data) {
						
						if(data == 'NO')
						{
							$('.forgotPasswordContainer').find('.error, .notice').remove();
							$('.forgotPasswordContainer').prepend('<div class="error">Invalid email address</div>').find('.error').hide().fadeIn();
						} else {
							$('.forgotPasswordContainer').find('.error, .notice').remove();
							$('.forgotPasswordContainer').prepend('<div class="notice">Your new password has been sent to the email address you entered.</div>').find('.notice').hide().fadeIn();
							$('.forgotPasswordEmail').val('');
							//
							//$(window.location).attr('href', baseURL + 'user/dashboard/');
						}
					});
			
			} 
		});
		
		
		
	//side nav
	$('.sideNav .level1').click(function(e)
		{
			e.preventDefault();
			$('.sideNav').find('.selected').removeClass('selected');
			$(this).addClass('selected');
			$('.sideNav .slider').slideUp();
			$('.sideNav').find('.' + $(this).attr('rel')).slideDown();
		});
		
	$('.sideNav .inactive').click(function(e)
		{
			e.preventDefault();
			$("#dialog-modal").attr('title','Coming soon');
			
			if ( $(this).attr('title') != '' )
				$("#dialog-modal").html($(this).attr('title'));
			else
				$("#dialog-modal").html('This section is currently unavailable. Please check back soon.');
			
			$("#dialog-modal").dialog({
				modal: true,
				resizable: false,
				draggable: false
			});
		});
		
	// user login form
	$('.buyShares').click(function(e)
		{
			e.preventDefault();
			$("#buySharesBox").dialog({
				modal: true,
				resizable: false,
				draggable: false,
				width: 920,
				height:517,
				close: function(event, ui) 
					{
						alert('closed');
					}
			});
		});
	/*
	$('.payBoxClick').click(function(e)
		{
			//e.preventDefault();
			$("#payBox").dialog({
				modal: true,
				resizable: false,
				draggable: false,
				width: 920,
				height:517,
				close: function(event, ui) 
					{
						alert('closed');
					}
			});
		});
*/
	//registration
   	$('.submitRegistration').click(function(e)
		{
			$(this).hide();
			$(this).parent().find('.loadingCopy').show();
			
			e.preventDefault();
			
			$('.registerBg span').hide();
			
			var err = '';
			$('.registerBg input.text').each(function()
				{
					if( $(this).val() == '' )
					{
						$('.err' + $(this).attr('id') ).fadeIn();
						err++;
					}
				});
			
			if(err > 0)
			{
				$(this).show();
				$(this).parent().find('.loadingCopy').hide();
			}
			
			var errMsg = '';
			
			if (err == 0)
			{
				errMsg += '<ul>';
				
				if (!isValidUsername( $('#username').val() ))
				{
					errMsg += "<li>Invalid username</li>";	
					err++;
				}
					
				if (!IsValidEmail( $('#email').val() ))
				{
					errMsg += "<li>Invalid email address</li>";	
					err++;
				}
					
				if (!isValidPassword( $('#password').val() ))
				{
					errMsg += "<li>your password must be more than 6 characters long. Alteast 1 digit and atleast 1 lowercase letter</li>";	
					err++;
				}
				
				if ( $('.chkTOC').attr('checked') == false )
				{
					errMsg += "<li>You must agree to terms and conditions</li>";
					err++;
				}
								
				$.ajax({
				  url: $('#registrationForm').attr('action') + '/checkusername/',
				  type: "POST",
				  data: "username=" + $('#username').val() + "&email=" + $('#email').val(),
				  success: function(data) {
					if( data != '' )
					{
						errMsg += data;
						err++;
					}
					
					errMsg += '</ul>';
					
					if( err > 0 )
					{
						$("#dialog-modal").attr('title','Uh ho, form has error(s)');
						$("#dialog-modal").html(errMsg + '<br />If you experience problems with registration please email <a href=\'mailto:hello@thetrib-e.com\'>hello@thetrib-e.com</a>');
						$('.submitRegistration').fadeIn();
						$('.submitRegistration').parent().find('.loadingCopy').hide();
					
						$("#dialog-modal").dialog({
							modal: true,
							resizable: false,
							draggable: false
						});
					} else {
						$.post( 
							$('#registrationForm').attr('action') + '/', $("#registrationForm").serialize(),
							function(data) {
								$('.registerControls').hide();
								$('.registerBg').slideUp(300, function()
								{
									$('.registerFormCopy').fadeOut(300, function()
									{
										$('.registerSuccessMessage').fadeIn();
									});
								});
							});
					}
					
				  }
				});
			}
		});
	
	
		function  IsValidEmail(email)
		{
			var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
			return filter.test(email);
		}
		
		function isValidUsername(username)
		{
			var filter = /^([a-zA-Z])[a-zA-Z_-]*[\w_-]*[\S]$|^([a-zA-Z])[0-9_-]*[\S]$|^[a-zA-Z]*[\S]$/;
			return filter.test(username);
		}
		
		function isValidPassword(password)
		{
			var filter = /(?!^[0-9]*$)(?!^[a-zA-Z!@#$%^&*()_+=<>?]*$)^([a-zA-Z!@#$%^&*()_+=<>?0-9]{6,15})$/; // 6 -40 char long with atleast 1 upper case, 1 lower case and 1 digit
			return filter.test(password);
		}
		
			
		$(document).ready(function()
		{
			$('.button_validation').click(function(e)
			{
				e.preventDefault();	
				
				//initialise a variable to store error msgs
				errors = '';
				
				// loop through the entre input contrls inside a form
				$('form').find(':input').each(function()
					{
						// check if the control requires validation
						if( $(this).hasClass('validate') || $(this).hasClass('required') )
						{
							// grab the value from the input
							var v = $(this).val();
							
							// intialise reponse variable for validation
							var response = '';
							
							// perform validation: if control as a 'required' class OR
							// the value is not empty
							// validate the control and
							// get a response back if validation fails
							if( $(this).hasClass('required') && $(this).val() == '' )
								response = "- " + $(this).attr('title') + " is required\n<br />";
							else if( $(this).hasClass('validate') && $(this).val() != '' )
								response = validateInput(v, $(this).attr('rel'), $(this).attr('title')) + "<br />";
							
							// accumulate the error msgs
							if (response != '')
								errors += response;
						}
					});
				
				// alert out the errors
				if (errors != '')
				{
					$("#dialog-modal").attr('title','Uh ho, form has error(s)');
					$("#dialog-modal").html(errors);
					$("#dialog-modal").dialog({
						modal: true,
						resizable: false,
						draggable: false
					});					
					//alert(errors);
					// refuse to submit the form
					return false;
				} 
				
				$('form').submit();
					
			});
		});
		
		// Validate function
		// val is the input value
		// type is the switch
		// title is the nice sweet name of the control like Address Line 1
		
		function  validateInput(val,type, title)
		{
			switch( type )
			{
				case 'email':
					var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
					var errorMsg = "- There was an error in your " + title + "\n";
					break;
				
				case 'username':
					var filter = /^([a-zA-Z])[a-zA-Z_-]*[\w_-]*[\S]$|^([a-zA-Z])[0-9_-]*[\S]$|^[a-zA-Z]*[\S]$/;
					var errorMsg = "- There was an error in your " + title + "\n";
					break;
				
				case 'password':
					var filter = /(?!^[0-9]*$)(?!^[a-zA-Z!@#$%^&*()_+=<>?]*$)^([a-zA-Z!@#$%^&*()_+=<>?0-9]{6,15})$/; // 6 -40 char long with atleast 1 upper case, 1 lower case and 1 digit
					var errorMsg = "- Your " + title + " must containt atleast 6 characters with atleast 1 number\n";
					break;
				
				/* commented because of multiple countries option
				case 'postcode':
					var filter = /^([a-pr-uwyzA-PR-UWYZ0-9][a-hk-yA-HK-Y0-9][aehmnprtvxyAEHMNPRTVXY0-9]?[abehmnprvwxyABEHMNPRVWXY0-9]? {1,2}[0-9][abd-hjln-uw-zABD-HJLN-UW-Z]{2}|gir 0aa|GIR 0AA)$/; // 
					var errorMsg = "- Your " + title + " is not a valid UK Post Code\n";
					break;
					*/
				
				case 'phone':
					var filter = /[0-9]{10}|[(]{1}[0-9]{0,3}[) -]{0,3}?[0-9]{3}[ -]{0,4}?[0-9]{4}$/; // 
					var errorMsg = "- Your " + title + " number is not valid\n";
					break;
			}
			
			//returns true of ralse
			if ( filter.test(val) )
				return '';
			else 
				return errorMsg;
		}
	
		
	 
  });	

