// validate functions
function validateForm()
{
	// variables
	var firstname = jQuery.trim(jQuery('#txtFirstName').val());
	var lastname  = jQuery.trim(jQuery('#txtLastName').val());
	var username = jQuery.trim(jQuery('#txtUsername').val());
	var password = jQuery.trim(jQuery('#txtPassword').val());
	var confirm = jQuery.trim(jQuery('#txtConfirm').val());
	var email = jQuery.trim(jQuery('#txtEmail').val());
	var phonenum = jQuery.trim(jQuery('#txtPhone').val());
	var dateBirth = jQuery.trim(jQuery('#txtBirth').val());
	var address = jQuery.trim(jQuery('#txtAddress').val());


	// check first name
	if(firstname == "")
	{
		jQuery('#msgError').html('First name is mandatory');
		//document.getElementById('txtFirstName').focus();
		jQuery('#hddErrorField').val('txtFirstName');
		showPopUpError('First name is mandatory');
		return false;
	}
	// check last name
	if(lastname == "")
	{
		jQuery('#msgError').html('Last name is mandatory');
		//document.getElementById('txtLastName').focus();
		jQuery('#hddErrorField').val('txtLastName');
		showPopUpError('Last name is mandatory');
		return false;
	}
	if(jQuery('#hddIsLogin').val() == "0")
	{
		// check username
		if(username == "")
		{
			jQuery('#msgError').html('Username is mandatory');
			//document.getElementById('txtUsername').focus();
			jQuery('#hddErrorField').val('txtUsername');
			showPopUpError('Username is mandatory');
			return false;
		}
		else
		{
			if(username.length < 6)
			{
				jQuery('#msgError').html('Username must be at least 6 characters');
				//document.getElementById('txtUsername').focus();
				jQuery('#hddErrorField').val('txtUsername');
				showPopUpError('Username must be at least 6 characters');
				return false;
			}
			else if(username.indexOf(' ') > 0)
			{
				jQuery('#msgError').html('Invalid username');
				//document.getElementById('txtUsername').focus();
				jQuery('#hddErrorField').val('txtUsername');
				showPopUpError('Invalid username');
				return false;
			}

		}
		// check password
		if(password == "")
		{
			jQuery('#msgError').html('Password is mandatory');
			//document.getElementById('txtPassword').focus();
			jQuery('#hddErrorField').val('txtPassword');
			showPopUpError('Password is mandatory');
			return false;
		}
		else if(password.length < 6)
		{
			jQuery('#msgError').html('Password must be at least 6 characters');
			//document.getElementById('txtPassword').focus();
			jQuery('#hddErrorField').val('txtPassword');
			showPopUpError('Password must be at least 6 characters');
			return false;
		}

		//check confirm pass
		if(password != confirm)
		{
			jQuery('#msgError').html('Password and Confirm password must match');
			//document.getElementById('txtConfirm').focus();
			jQuery('#hddErrorField').val('txtConfirm');
			showPopUpError('Password and Confirm password must match');
			return false;
		}

		// check email
		if(email == "")
		{
			jQuery('#msgError').html('Email is mandatory');
			//document.getElementById('txtEmail').focus();
			showPopUpError('Email is mandatory');
			jQuery('#hddErrorField').val('txtEmail');
			return false;
		}
		else if(!validateEmail(email))
		{
			jQuery('#msgError').html('Invalid email');
			//document.getElementById('txtEmail').focus();
			showPopUpError('Invalid email');
			jQuery('#hddErrorField').val('txtEmail');
			return false;
		}
	}
	// check phone number
	if(phonenum == "")
	{
		jQuery('#msgError').html('Phone number is mandatory');
		//document.getElementById('txtPhone').focus();
		showPopUpError('Phone number is mandatory');
		jQuery('#hddErrorField').val('txtPhone');
		return false;
	}
	// check date birth
	if(dateBirth == "")
	{
		jQuery('#msgError').html('Date of birth is mandatory');
		//document.getElementById('txtBirth').focus();
		showPopUpError('Date of birth is mandatory');
		jQuery('#hddErrorField').val('txtBirth');
		return false;
	}
	else if(!validateDateBirth(dateBirth))
	{
		//document.getElementById('txtBirth').focus();
		jQuery('#hddErrorField').val('txtBirth');
		return false;
	}
	// check address
	if(address == "")
	{
		jQuery('#msgError').html('Address is mandatory');
		//document.getElementById('txtAddress').focus();
		jQuery('#hddErrorField').val('txtAddress');
		showPopUpError('Address is mandatory');
		return false;
	}
	// check accept
	if(!jQuery('#ckAgree').is(":checked"))
	{
		jQuery('#msgError').html('Agreement on rules and terms must be checked to proceed.');
		showPopUpError('Agreement on rules and terms must be checked to proceed.');
		return false;
	}

	// ajax for submit
	ajaxUrl = jQuery('#hddAjaxUrl').val();
	var dataInput = "display_name=" + username + "&username=" + username;
	dataInput = dataInput + "&email=" + email + "&password=" + password;

	var arrBirthday = dateBirth.split("/");
	var arrTemp = new Array();
	arrTemp[0] = arrBirthday[2];
	arrTemp[1] = arrBirthday[0];
	arrTemp[2] = arrBirthday[1];
	dataInput = dataInput + "&date_of_birth=" + arrTemp.join("-");
	dataInput = dataInput + "&last_name=" + lastname;
	dataInput = dataInput + "&first_name=" + firstname;
	dataInput = dataInput + "&city=" + jQuery.trim(jQuery('#txtCity').val());
	dataInput = dataInput + "&state_id=" + jQuery.trim(jQuery('#cmbState').val());
	dataInput = dataInput + "&country_id=" + jQuery.trim(jQuery('#cmbCountry').val());
	dataInput = dataInput + "&phone=" + phonenum;
	dataInput = dataInput + "&address=" + address;
	dataInput = dataInput + "&line1=" + jQuery.trim(jQuery('#txtLine1').val());
	dataInput = dataInput + "&line2=" + jQuery.trim(jQuery('#txtLine2').val());
	dataInput = dataInput + "&zipcode=" + encodeURIComponent(jQuery('#txtZip').val());
	dataInput = dataInput + "&capcha=" + jQuery.trim(jQuery('#txtCapcha').val());
	dataInput = dataInput + "&islogin=" + jQuery.trim(jQuery('#hddIsLogin').val());


	jQuery.ajax({
	   type: "POST",
	   url: ajaxUrl,
	   data: dataInput + "&type=submit&ajax=1",
	   success: function(msg){
		    switch(msg)
			{
				case '0':
				{
					var ran_number=Math.random()*15;
					jQuery('#imgCapcha').attr("src",jQuery('#hddImageUrl').val() + "?a=" + ran_number);
					jQuery('#msgError').html('The username you have chosen is already in use');
					showPopUpError('The username you have chosen is already in use');
					//document.getElementById('txtUsername').focus();
					jQuery('#hddErrorField').val('txtUsername');
					break;
				}
				case '1':
				{
					var ran_number=Math.random()*15;
					jQuery('#imgCapcha').attr("src",jQuery('#hddImageUrl').val() + "?a=" + ran_number);
					jQuery('#msgError').html('The email you have chosen is already in use');
					showPopUpError('The email you have chosen is already in use');
					//document.getElementById('txtEmail').focus();
					jQuery('#hddErrorField').val('txtEmail');
					break;
				}
				case '2':
				{
					var ran_number=Math.random()*15;
					jQuery('#imgCapcha').attr("src",jQuery('#hddImageUrl').val() + "?a=" + ran_number);
					jQuery('#msgError').html('Verification code and the text on the image must match');
					showPopUpError('Verification code and the text on the image must match');
					//document.getElementById('txtCapcha').focus();
					jQuery('#hddErrorField').val('txtCapcha');
					break;
				}
				case '3':
				{
					var ran_number=Math.random()*15;
					jQuery('#imgCapcha').attr("src",jQuery('#hddImageUrl').val() + "?a=" + ran_number);
					jQuery('#msgError').html('Sorry, the service is currently unavailable. Please try again later');
					showPopUpError('Sorry, the service is currently unavailable. Please try again later');
					break;
				}
				default:
				{
					if(jQuery('#hddIsLogin').val() == "0")
					{
						jQuery('#registerForm').css({'display' : 'none'});
						jQuery('#successForm').css({'display' : 'block'});
					}
					else
					{
						jQuery('#registerForm').css({'display' : 'none'});
						jQuery('#updateSuccForm').css({'display' : 'block'});
					}
					break;
				}
			}
	   },
	   error: function(){
	   	var ran_number=Math.random()*15;
	   	jQuery('#imgCapcha').attr("src",jQuery('#hddImageUrl').val() + "?a=" + ran_number);
	   	jQuery('#msgError').html('Sorry, the service is currently unavailable. Please try again later');
	   	showPopUpError('Sorry, the service is currently unavailable. Please try again later');
	   }
	 });
	return false;
}
function validateEmail(strEmail)
{
	var filter=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
	if (!filter.test(strEmail)) {
		return false;
	}
	return true;
}

function validatePhoneNum(the_phone_num)
{
	/* Set whether the user should use a -, a space, or one long number without divisions.
     Use the following values to set:
	 1 = Use - (i.e 123-456-7890)
	 2 = Use a space (i.e. 123 456 7890)
	 3 = Use none (i.e. 1234567890)
  */
 	var num_division = 1;

	var phone_num_OK = false;
	var the_delim = "";
	var the_ph_test = "";

	if (num_division == 1) {
		the_delim = "-";
		the_ph_test = /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/;
	   	phone_num_OK = the_ph_test.test(the_phone_num);
	}
	else if (num_division == 2) {
		the_delim = " ";
		the_ph_test = /^[0-9]{3} [0-9]{3} [0-9]{4}$/;
	    phone_num_OK = the_ph_test.test(the_phone_num);
	}
	else if (num_division == 3) {
		the_delim = "";
		the_ph_test = /^[0-9]{10}$/;
	    phone_num_OK = the_ph_test.test(the_phone_num);
	}
	else {
		window.alert("Cannot validate.");
		return false;
	}
    return phone_num_OK;
}

function validateDateBirth(dtStr)
{
	var dtCh= "/";
	var minYear= jQuery("#hddMinBirth").val();
	var maxYear=jQuery("#hddMaxBirth").val();

	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		jQuery('#msgError').html('Invalid date of birth');
		showPopUpError('Invalid date of birth');
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		jQuery('#msgError').html('Invalid date of birth');
		showPopUpError('Invalid date of birth');
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		jQuery('#msgError').html('Invalid date of birth');
		showPopUpError('Invalid date of birth');
		return false;
	}
	if(strYear.length != 4 || year==0)
	{
		jQuery('#msgError').html('Invalid date of birth');
		showPopUpError('Invalid date of birth');
		return false;
	}
	if (year<minYear || year>maxYear){
		jQuery('#msgError').html('Sorry, you do not meet the age requirement for registration.');
		showPopUpError('Sorry, you do not meet the age requirement for registration.');
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		jQuery('#msgError').html('Invalid date of birth');
		showPopUpError('Invalid date of birth');
		return false;
	}
	return true;
}

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   }
   return this;
}

// end validate functions

// ajax functions
function resetState()
{
	ajaxUrl = jQuery('#hddAjaxUrl').val();
	jQuery.ajax({
	   type: "GET",
	   url: ajaxUrl,
	   data: "countryId=" + jQuery('#cmbCountry').val() + "&type=state&ajax=1",
	   success: function(msg){
	     jQuery('#cmbState').html(msg);
	   }
	 });
	 return;
}


// function for login form

function loginValidate()
{
	var loginUser = jQuery.trim(jQuery('#txtLoginUsername').val());
	var loginPass  = jQuery.trim(jQuery('#txtLoginPassword').val());

	if(loginUser == "")
	{
		jQuery('#msgLoginError').html('Username is mandatory');
		document.getElementById('txtLoginUsername').focus();
		return false;
	}
	else if(loginUser.indexOf(' ') > 0)
	{
		jQuery('#msgLoginError').html('Invalid username');
		document.getElementById('txtLoginUsername').focus();
		return false;
	}

	if(loginPass == "")
	{
		jQuery('#msgLoginError').html('Password is mandatory');
		document.getElementById('txtLoginPassword').focus();
		return false;
	}

	// ajax for login
	ajaxUrl = jQuery('#hddAjaxLoginUrl').val();
	var dataInput = "username=" + loginUser;
	dataInput = dataInput + "&password=" + loginPass;

	jQuery.ajax({
	   type: "POST",
	   url: ajaxUrl,
	   data: dataInput + "&ajaxlogin=1",
	   success: function(msg){
			if(msg == "0")
			{
				jQuery('#msgLoginError').html('Invalid username or password');
				document.getElementById('txtLoginUsername').focus();
			}
			else
			{
				window.location = jQuery('#hddAjaxUrl').val();
			}
	   },
	   error: function(){
		   	jQuery('#msgLoginError').html('Sorry, the service is currently unavailable. Please try again later');
	   }
	 });
	return false;
}

function resetLoginForm()
{
	tb_remove();
	jQuery('#txtLoginUsername').val("");
	jQuery('#txtLoginPassword').val("");
	jQuery('#msgLoginError').html("&nbsp;");
}

function openPopup(popupurl, name, width, height)
{
	/*if (jQuery.browser.msie && name == 'terms')
	{
		width = parseInt(width) + 18;
		height = parseInt(height) + 18;
	}*/


	var centerWidth = (window.screen.width - width) / 2;
    var centerHeight = (window.screen.height - height) / 2;

	var otherAttr = "left=" + centerWidth + ", top=" + centerHeight + ", ";
	if(name == 'terms')
	{
		otherAttr = otherAttr + "scrollbars=0, ";
	}
	else
	{
		otherAttr = otherAttr + "scrollbars=1, ";
	}

	otherAttr = otherAttr + "location=0, menubar=0, resizable=0, status=0, titlebar=0, toolbar=0";
	myWindow=window.open(popupurl,name,'width=' + width + ',height=' + height + ',' + otherAttr)
	myWindow.focus()
}

function resizeWindow()
{
	width = parseInt(jQuery('#hddWidth').val());
	height = parseInt(jQuery('#hddHeight').val());
	var agt=navigator.platform.toLowerCase();
	if(agt.indexOf("mac")!=-1)
	{
		//width = width;
		//height = height + 68;//- 11;//68;
		if (jQuery.browser.mozilla)
		{
			width = width;
			height = height + 68;//- 11;//68;
			window.resizeTo(width,height);
		}
		else
		{
			width = width;
			height = height -30; //+ 23;//- 11;//68;
			window.resizeTo(width,height);
		}
	}
	else
	{
		width = width  + 8;
		if (jQuery.browser.mozilla)
		{
			height = height + 21;
			window.resizeTo(width,height);
		}
		else
		{
			height = height + 6;
			window.resizeTo(width,height);
		}
	}
}

function showPopUpError(errMessage)
{
	jQuery('#errPopUpMsg').html(errMessage);
	tb_show(null, '#TB_inline?height=300&width=250&inlineId=error', false);
}
function closeErrorForm()
{
	tb_remove();
	var hddField = jQuery('#hddErrorField').val();
	document.getElementById(hddField).focus();
}