$(document).ready(function() 
{
	// hide/ show child username Divs
	if ($('#current').is(":visible")){
		$('#new').hide('fast');
		$('input#child_username').removeClass('required username-input');
		$('input#child_password').removeClass('required password-input');
		$('input#child_password2').removeClass('required confirm-password');
		$('select#child_age').removeClass('required');
		$('select#child_cusername').addClass('required');
	}
	
	//disable the state for the loading
	if ($('#customer_country').val() != 'US')
	{
		$('#customer_state').attr('hasError',false); 
		$('#customer_state').attr('disabled',true);
		$("label[for='customer_state']").hide();
		$('#customer_state').hide();
		
	}
	
	$("form").submit(function() 
	{
		if(this.name != "logoutform")
		{
			result = validateForm();
			if (result == true)
			{
				button = $('input[name="submit"]');
				button.removeClass('continue-btn');
				button.addClass('continue-btn-disabled');
				button.attr('disabled','disabled');
				return true;
			}
			
			if ($('input[name="checkout"]').length >0 )
			{
				button = $('input[name="checkout"]');
				button.removeClass('continue-btn');
				button.addClass('continue-btn-disabled');
				button.attr('disabled','disabled');
				return true;
			}
			return false;
		}
		else
			return true;
	});
	
	
	$("input,textarea,select").focus(function()
	{
		clearOldBoxes()
		control = $(this);
		hasMessage = control.attr("message");
		hasError = control.attr("hasError");
		
		if (hasMessage != null || hasError != null)
			displayLabel(this);
	});
	
	$("a").click(function()
	{
		control = $(this);
		haslink = control.attr("link");
		if (haslink != null)
			loadModal(this);
	});
	
	$("select").change(function(){
		control = $(this);
		if (this.name == 'customer_country')
		{
			if (this.value != 'US')
			{
				$('#customer_state').attr('disabled',true);
				$("label[for='customer_state']").hide();
				$('#customer_state').hide();
				$('#customer_country').focus();
					//$('#customer_state').removeAttr('haserror');				
			}
			else
			{
				$('#customer_state').attr('disabled',false);
				$("label[for='customer_state']").show();
				$('#customer_state').show();
				$('#customer_country').focus();
	
			}
		}
	});
	
});

function switchDiv(flag)
{
	if(flag == 1)
		{
			$('input#child_username').removeClass('required username-input');
			$('input#child_password').removeClass('required password-input');
			$('input#child_password2').removeClass('required confirm-password');
			$('select#child_age').removeClass('required');
			$('select#child_cusername').addClass('required');

			$("#current").toggle();
			$("#new").toggle();
		}
	else
		{
			$('input#child_username').addClass('required username-input');
			$('input#child_password').addClass('required password-input');
			$('input#child_password2').addClass('required confirm-password');
			$('select#child_age').addClass('required');
			$('select#child_cusername').removeClass('required');
	
			$("#new").toggle();
			$("#current").toggle();
		}
}

function generateUsername()
{
	value = $('#child_username').val();
	last4char = value.substring(value.length-4, value.length);
	if(!isNaN(last4char))
		value = value.substring(0, value.length-4);
	
	if (value  == '')
		value = 'domino';
	
	$.ajax({
		  url: 'generate-username/username/' + value,
		  async: false,
		  success: function( data ) 
		  {
			  $('#child_username').val(data);
		  }
	});
}

function creditcard(control)
{
	jControl = $(control);
	$('#card_number').attr('validation','creditcard:' + jControl.val());
}
//get the package as parameter
function loadModal(control)
{
	jControl = $(control);
	var link = $(control).attr('link');
	$.ajax({
		  url: link,
		  beforeSend: function()
		  {
				//Set the popup window to center
				$('#mask').css('top',  '20%');
				$('#mask').css('left', '30%');
		  },
		  success: function( data ) 
		  {
			$('#mask').html(data);
		  },
		  complete: function()
		  {
			  $('#mask').show();
		  }
		  
		  
	});
}

function handlePackage(a) 
{
	f = getParam(a);
	addElementToForm(document.packageForm,'package',f);
	document.packageForm.submit();
}		

function handleCurrency(a)
{
	f = getParam(a);
	addElementToForm(document.currencyForm,'currency',f);
	document.currencyForm.submit();			
}

function addElementToForm(form,elemName,elemValue)
{
	var elem = document.createElement('input');
	elem.setAttribute('type','hidden');
	elem.setAttribute('name',elemName);
	elem.setAttribute('value',elemValue);
	form.appendChild(elem);
}

function getParam(a)
{
	f = a.href;
	f = f.substr(f.indexOf("#"));
	f = f.replace(/#/,"");
	return f;
}


function displayLabel(control)
{
	clearOldBoxes();
	
	var controlID = control.id;

	//create the jquery control
	jControl = $('#' + controlID);
	//get the message for this control
	message = jControl.attr('message');
	//create the box based on the arguments
	
	//change the message if error occured
	error = jControl.attr('hasError');
	
	if (error == 'true')
		message = jControl.attr('error');
	
	//check the type of the control and assign the correct css
	boxStyle = 'small';
	adjustPosition = 30;
		
	switch(jControl.get(0).type)
	{
		case 'textarea':
			boxStyle = 'large';
		break;
		case 'checkbox':
			boxStyle = 'check';
			adjustPosition = 52;
		break;
	}
	
	//the graphic
	var box = '<div id="label_'+ controlID +'" class="rollover-'+boxStyle+'"><span>'+ message +'</span></div>';
	//parse the box into jquery
	boxControl = $(box);
	//change the css for this box
	boxControl.css( 'top', jControl.position().top - adjustPosition );
	
	boxControl.css('z-index',50);
	
	if (error == 'true')
	{
		classname = 'error-popup-' + boxStyle;
		boxControl.attr('class',classname);
	}
	
	if (message == null)
		return;
	
	//add the box after the control
	jControl.css('z-index',100);
	jControl.after(boxControl);
}


function clearOldBoxes()
{
	//Remove old boxes
	$("div").each(function(index, domEle) 
	{
		divId = domEle.id;
		
		if (divId)
		{
			//check if the dom have id
			piece = divId.split('_');
			if (piece[0] == 'label')
			{
				$('#'+divId).remove();
			}
			
		}
	}); 	
}
function validateForm()
{
	var isValid = false;
	classes = new Array;
	
	$("form,textarea,select,input").each(function(index, domEle) 
	{
		//get the field
		var field = $(domEle);

		//get the class
		var myClass = field.attr("class");
		
		if (myClass != undefined)
		{
			//split to array
			classes = myClass.split(' ');
		}
		//check if required exitsts
		required = jQuery.inArray('required',classes);

		//if exists procced
		if (required == 0 && field.attr('disabled') == undefined)
		{
			
			field.attr('hasError',""+false);
			//check if the field have validation rules
			var myValidation = field.attr("validation");

			if (myValidation != null)
			{
				//get the all the rules
				rules = myValidation.split(' ');
				
				//loop throw the loops
				$.each(rules, function(index, value) 
				{ 
					var result = false;
					pattern = "";
					//check if we got value assing on the rule
					variable = value.split(':');
					
					switch(variable[0])
					{
						case 'email':
							pattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/gi;
							break;
						case 'alpha':
							pattern = /^\w+$/gi;
							break;
						case 'password':
							pattern = /^[A-Za-z0-9]\w{5,}$/gi;
							break;
						case 'same':
							other = $('#' + variable[1]);
							if (other.val() == field.val())
								result = true;
							break;
						case 'min':
							if (field.val().length >= variable[1])
								result = true;
							break;
						case 'creditcard':
							switch(variable[1])
							{
								case 'VISA':
									pattern = /(^4\d{12}$)|(^4\d{15}$)/gi;
									break;
								case 'SWITCH':
								case 'MAESTRO':
									pattern = /(^(49030)[2-9](\d{10}$|\d{12,13}$)) |(^(49033)[5-9](\d{10}$|\d{12,13}$)) |(^(49110)[1-2](\d{10}$|\d{12,13}$)) |(^(49117)[4-9](\d{10}$|\d{12,13}$)) |(^(49118)[0-2](\d{10}$|\d{12,13}$)) |(^(4936)(\d{12}$|\d{14,15}$)) |(^(564182)(\d{11}$|\d{13,14}$)) |(^(6333)[0-4](\d{11}$|\d{13,14}$)) |(^(6759)(\d{12}$|\d{14,15}$))/gi;
									break;
								case 'MASTERCARD':
									pattern = /^5[1-5]\d{14}$/gi;
									break;
								case 'DISCOVER':
									pattern = /(^(6011)\d{12}$)|(^(65)\d{14}$)/gi;
									break;
								case 'AMEX':
									pattern = /(^3[47])((\d{11}$)|(\d{13}$))/gi;
									break;
								case 'SOLO':
									pattern = /(^(6334)[5-9](\d{11}$|\d{13,14}$)) |(^(6767)(\d{12}$|\d{14,15}$))/gi;
									break;
							}
							//pattern = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/gi;
							break;
						case 'is':
							if (field.val() == variable[1])
								result = true;
						break;
						case 'select':
							if (field.val() != "")
								result = true;
						break;
						case 'username':
							value = field.val(); 
							$.ajax({
								  url: variable[1] + value,
								  async: false,
								  success: function( data ) 
								  {
									  if (data == "true")
										  	result = true;
								  }
							});
							break;
						case 'promotion':
							value = field.val(); 
							$.ajax({
								  url: variable[1] + value,
								  async: false,
								  success: function( data ) 
								  {
									  if (data == "true")
										  	result = true;
								  }
							});
							break;
						case 'cvv':
							pattern = /^([0-9]{3})$|^([0-9]{4})$/gi;
							break;
						case 'check':
								result = field.is(':checked');
							break;
					}
	
					if (pattern != "")
						result = validateField(field,pattern);
					
					if (result == false)
					{
						field.attr('hasError',""+true);
						
						if(variable[0] == 'creditcard' && field.val().length >= 16)
						{
							$('input#card_number').attr('error', 'Please check your card type and card number.'); 
						}	
						else if(variable[0] == 'username' && field.val().length >= 4)
						{
							$('input#child_username').attr('error', "<div style='float:left'><img src='/images/layout/generate-btn-animate.gif' onClick='generateUsername()'></div> This username already exists. Click on the icon to generate one automatically."); 
						}	
						
						field.focus();
					}
					isValid = result;
					return isValid;
				});
			}
			return isValid;
		}
		
	});
	return isValid;
}


function validateField(field,regex)
{
    valueToTest =  field.val();
    result = valueToTest.match(regex);

    if (result == null)
        return false;

    return true;

}
