$(document).ready(function() {
	// validate signup form on keyup and submit
	var validator = $("#FormParam").validate({
		rules: {				
		Id: {
		required: true,
		minlength: 5,
		validUserIdChars:true
	},
	Pswd: {
		required: true,
		minlength: 5,
		validChars:true
	},
	RetypePswd: {
		required: true,
		minlength: 5,
		equalTo: "#Pswd"				
	},
	TitleCd: {
		required: true
	},
	ContactPerson: {
		required: true,
		validChars:true
	},
	Email: {
		required: true,
		email: true
	},
	MobileNo: {
		required: true,	
		minlength: 14,   
		maxlength: 15   
	},		
	OffNo: {
		required: true,		
		minlength: 10,   
		maxlength: 18   
	},		
	FaxNo: {
		minlength: 10,   
		maxlength: 18  
	},		
	Designation: {				
		validChars:true   
	},	
	Name: {
		required: true
	},
	IndustryCd: {				
		required:true   
	},
	Addr1: {		
		required:true 
	},
	PostCd: {
		required:true,
		validChars:true
	},
	City: {
		validChars:true
	},
	CountryCd: {				
		required:true    
	},		
	StateCd: {				
		required:true    
	},
	security_code: {
			required: true
	}			
	},
	messages: {			
		Id: {
		required: "Login ID is required",
		minlength: jQuery.format("Login ID must be at least {0} characters"),
		validUserIdChars: "Special Characters are not allowed!"
	},
	Pswd: {
		required: "Password is required",
		validChars: "Special Characters are not allowed!",
		rangelength: jQuery.format("Password must be at least {0} characters")
	},
	RetypePswd: {
		required: "Confirm Password is required",
		minlength: jQuery.format("Confirm Password must be at least {0} characters"),
		equalTo: "Enter the same password as above"
	},
	TitleCd: {
		required: "Salutation is required<br/>&nbsp;"
	},
	ContactPerson: {
		required: "Contact Person is required",
		validChars: "Special Characters are not allowed!"
	},
	Email: {
		required: "Email address is required",
		email: "Please enter a valid email address"
	},
	MobileNo: {		
		required: "Mobile No is required",
		minlength: jQuery.format("Mobile No must be at least {0} digits"),
		maxlength: jQuery.format("Mobile No must be less than {0} digits")
	},
	OffNo: {
		required: "Telephone is required",		
		minlength: jQuery.format("Telephone must be at least {0} digits"),
		maxlength: jQuery.format("Telephone must be less than {0} digits")
	},
	FaxNo: {		
		minlength: jQuery.format("Fax must be at least {0} digits"),
		maxlength: jQuery.format("Fax must be less than {0} digits")
	},
	Designation: {				
		validChars: "Special Characters are not allowed!"
	},	
	Name: {
		required: "Company Name is required"
	},
	IndustryCd: {				
		required: "Industry is required"
	},
	Addr1: {		
		required: "Address is required"
	},
	PostCd: {
		required: "Postcode is required",
		validChars: "Special Characters are not allowed!"
	},
	City: {
		validChars: "Special Characters are not allowed!"
	},
	CountryCd: {				
		required: "Country is required"
	},		
	StateCd: {				
		required: "State is required"
	},
        security_code: {
		required: "Security Code is required"
	}				
	},
	// the errorPlacement has to take the table layout into account
	errorPlacement: function(error, element) {
		if ( element.is(":radio") )
			error.appendTo( element.parent().next().next() );
		else if ( element.is(":checkbox") )
			error.appendTo ( element.next() );
		else
			error.appendTo( element.parent().next() );
	},
	// specifying a submitHandler prevents the default submit
	submitHandler: function() {
		if (document.FormParam.chkTerms.checked == false) {
			alert('You must accept our Terms of Use.\nPlease check on the small box beside the Terms of Use.');
			return;
		}
		
		 if ( $("#FormParam").validate().form()) {				
		
			var errorMsg = $('#errorMsg');
			var params = 'security_code=' + $("#security_code").val();
			
			errorMsg.removeClass('error').html('<img src="/images/loading.gif" height="16" width="16" /> <span  class="clsAjax">&nbsp;Please wait...</span>');

				if (this.timer) clearTimeout(this.timer);
                
                this.timer = setTimeout(function () {
                    $.ajax({
                        url: '/captcha/check.php',
                        data: params,
                        dataType: 'json',
                        type: 'post',
                        success: function (data) {
                        	if (data.success) {
	                            $("#errorMsg").addClass('success').html(data.message).fadeIn('slow');
		                             document.FormParam.submit();                         
	                        } else {
		                        new_captcha();
				    			$("#errorMsg").addClass('error').html(data.message).fadeIn('slow');
	                        }
                        }
                    });
                }, 250);
                
			return false;			
		}	
	},
	// set this class to error-labels to indicate valid fields
	success: function(label) {
		// set &nbsp; as text for IE
		label.html("&nbsp;").addClass("checked");
	}
	});

	// check if confirm password is still valid after password changed
	$("#Pswd").blur(function() {
		$("#RetypePswd").valid();
	});
	
	jQuery(function($){
		   $("#MobileNo").mask("(999) - 9999999");
//		   $("#OffNo").mask("(999) 999 - 99999");
//		   $("#FaxNo").mask("(999) 999 - 99999");		   
		});

	// Id validation logic
	var validateId = $('#validateId');
	$('#Id').keyup(function () {
		// cache the 'this' instance as we need access to it within a setTimeout, where 'this' is set to 'window'
		var t = this;

		// only run the check if the username has actually changed - also means we skip meta keys
		if (this.value != this.lastValue) {

			// the timeout logic means the ajax doesn't fire with *every* key press, i.e. if the user holds down
			// a particular key, it will only fire when the release the key.

			if (this.timer) clearTimeout(this.timer);

			// show our holding text in the validation message space
			validateId.removeClass('error').html('<img src="/images/loading.gif" height="16" width="16" /> checking availability...');

			// fire an ajax request in 1/5 of a second
			this.timer = setTimeout(function () {
				$.ajax({
					url: 'check_client.php',
					data: 'action=check_username&username=' + t.value,
					dataType: 'json',
					type: 'post',
					success: function (j) {
					validateId.removeClass('clsSuccess');
					validateId.removeClass('clsFail');
					if (j.msg == 'Available') {
						validateId.html(j.msg).addClass('clsSuccess');
					} else {
						validateId.html(j.msg).addClass('clsFail');
					}
				}
				});
			}, 250);

			// copy the latest value to avoid sending requests when we don't need to
			this.lastValue = this.value;
		}
	});
	
	
	$.validator.addMethod('validUserIdChars', function (value) {
		
		var result = true;
		// unwanted characters
		var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<> ?";

		for (var i = 0; i < value.length; i++) {

			if (iChars.indexOf(value.charAt(i)) != -1) {
				return false;
			}

		}

		return result;
		
	}, '');

	$.validator.addMethod('validChars', function (value) {

		var result = true;
		// unwanted characters
		var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";

		for (var i = 0; i < value.length; i++) {

			if (iChars.indexOf(value.charAt(i)) != -1) {
				return false;
			}

		}

		return result;

	}, '');

});

function onCountryChange(param) {

	if (trim(param.value) == 'MY') {
		document.getElementById("isOtherState").style.display="none";
		document.getElementById("isState").style.display="";
		document.getElementById("isState2").style.display="";
		document.getElementById("isState3").style.display="";		 
	} else {
		document.getElementById("isState").style.display="none";
		document.getElementById("isState2").style.display="none";
		document.getElementById("isState3").style.display="none";
		document.getElementById("isOtherState").style.display="";
	}
}

maxKeys = 5000;
var IE = (document.all) ? 1 : 0;
var DOM = 0; 
if (parseInt(navigator.appVersion) >=5) {DOM=1};

function ShowTextCount( showCharLeft ) {
    
    // Detect Browser

    if (DOM) {
    	var viewer = document.getElementById("showCounter");
        viewer.innerHTML=showCharLeft;
    }
    else if(IE) {
        document.all["showCounter"].innerHTML=showCharLeft;
    }
}

function keyup(_textarea) 
{
var str = new String(_textarea.value);
var len = str.length;
var charsLeft = maxKeys - len + ' characters left';
if (len > maxKeys) charsLeft += '<br>characters more than ' + maxKeys + ' will be truncated.';
ShowTextCount( '&nbsp;' + charsLeft );
}
