var NeedHelp = {
	
	container: null,
	boxContainer: null,
	
	
	init: function(){
		NeedHelp.container = $('div.container');
		NeedHelp.boxContainer = NeedHelp.container.find('div.need_help,div.need_help_special');
		NeedHelp.boxContainer.find('input:text').bind('focus', {}, NeedHelp.onTextFieldFocus);
		NeedHelp.boxContainer.find('input:text').bind('blur', {}, NeedHelp.onTextFieldBlur);
		
		NeedHelp.boxContainer.find('input:text').bind('blur', {}, NeedHelp.onTextFieldBlur);
		
		NeedHelp.boxContainer.find("[name='Area']").focus();
		NeedHelp.boxContainer.find("[name='Area']").blur();
	  	NeedHelp.boxContainer.find('form#needHelp').bind('submit', {}, NeedHelp.onSubmit);

        //set the country in the contact me section from geoIP
		NeedHelp.container.find('table.need_help_table select[name="Country"]').find('option[value="' + AppData.GEOIPCountry + '"]').attr('selected','selected');
		
		NeedHelp.container.find('#countryNeedHelp').selectbox(
				{
					inputClass: 'selectboxBig',
					containerClass: 'selectbox-wrapperBig',
					scrollBar: true,
					chainTitle: true,
					onChange: function( name, value, element ) {
						$.post(
							'rpcProxy/getCountryPrefix',
							{countryId: value},
							function(data){
							if (data==48){
								General.container.find('form#needHelp input[name="phone_prefix"]').val('+' + data);
								General.container.find('form#needHelp input[name="phone_area"]').val('0').hide();
								General.container.find('form#needHelp input[name="Phone"]').parent().addClass('extra');
								
							}
							else if (data!=null){
							//alert("data"+data);
								General.container.find('form#needHelp input[name="phone_prefix"]').val('+' + data);
								General.container.find('form#needHelp input[name="phone_area"]').val('').show()
								General.container.find('form#needHelp input[name="Phone"]').parent().removeClass('extra');
							}
							
							else{
								General.container.find('form#needHelp input[name="phone_prefix"]').val('');
								General.container.find('form#needHelp input[name="phone_area"]').val('').show()
								General.container.find('form#needHelp input[name="Phone"]').parent().removeClass('extra');
							}
						},
					'json');
					}
				}
		)
		
		
				NeedHelp.container.find('#currency').selectbox(
				{
					inputClass: 'selectboxBig',
					containerClass: 'selectbox-wrapperBig',
					scrollBar: true,
					chainTitle: true,
					onChange: function( name, value, element ) {
						$.post(
							'rpcProxy/getCountryPrefix',
							{countryId: value},
							function(data){
							if (data!=null){
								General.container.find('form#needHelp input[name="Prefix"]').val('+' + data);
							}
							else{
								General.container.find('form#needHelp input[name="Prefix"]').val('');
							}
						},
					'json');
					}
				}
			)
		
		NeedHelp.boxContainer.find('input[name="repeatPasswordFake"]').bind('focus',function(){
		$('input[name="repeatPasswordFake"]').hide();
		NeedHelp.boxContainer.find('input[name="repeatPassword"]').show();
		NeedHelp.boxContainer.find('input[name="repeatPassword"]').focus();
		
		});
		
		NeedHelp.boxContainer.find('input[name="repeatPassword"]').bind('blur',function(){
		if (NeedHelp.boxContainer.find('input[name="repeatPassword"]').val()==""){
		NeedHelp.boxContainer.find('input[name="repeatPasswordFake"]').show();
		NeedHelp.boxContainer.find('input[name="repeatPassword"]').hide();
		}
		});

	},


	onTextFieldFocus: function(event){
		var field = $(event.target);
		var value = $.trim(field.val());
		if(value == field.attr('default')) field.val('');
		
	},
	
	onTextFieldBlur: function(event){
		var field = $(event.target);
		var value = $.trim(field.val());
		if(value == '') field.val(field.attr('default'))
	},
	checkNames: function(field){
		var alphaExp = /^[a-zA-Z]+$/;
		if(field.val().match(alphaExp)){
			return "1";
		}else{
			return "0";
		}
	},

	validateEmail: function(field){
		var email = field.val();
		var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (!filter.test(email))
			return false;
},

	IsNumeric :function (strString)
// check for valid numeric strings   
	{
		var strValidChars = "+0123456789";
		var strChar;
		var blnResult = true;

		if (strString.length == 0) 
			return false;
		// test strString consists of valid characters listed above
		for (i = 0; i < strString.length && blnResult == true; i++)
		{
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1)
		{
		blnResult = false;
		}
		}
		return blnResult;
	},
	
	onSubmit: function(event){
		//validation
		var isValid = true;
		
		//for special nedd help use regular(not ajax Post)
		
		
		var form = $(event.target);
		var aErrors = [];
		var validFirstName=NeedHelp.checkNames(NeedHelp.boxContainer.find("[name='FirstName']"));
		var validLastName=NeedHelp.checkNames(NeedHelp.boxContainer.find("[name='LastName']"));
		var vEmail=NeedHelp.validateEmail(NeedHelp.boxContainer.find("[name='email']"));
		
		form.find('input:text').each(function(index){
			if($(this).val() == $(this).attr('default')){
                                aErrors[aErrors.length] = $(this).val() + ' is a must field.';
				isValid = false;
			}
		});
		
		if(NeedHelp.boxContainer.find("[name='FirstName']").val()!=NeedHelp.boxContainer.find("[name='FirstName']").attr('default') || NeedHelp.boxContainer.find("[name='LastName']").val()!=NeedHelp.boxContainer.find("[name='LastName']").attr('default'))
		{
			if(validFirstName=="0")
			{
				aErrors[aErrors.length]=AppData.generalLang.cannotContainNumbersFirstName;
				isValid = false;	
			}
			if(validLastName=="0"){
				aErrors[aErrors.length]=AppData.generalLang.cannotContainNumbersLastName;
				isValid = false;
			}
		}
		
		if(NeedHelp.boxContainer.find("[name='email']").val()!=NeedHelp.boxContainer.find("[name='email']").attr('default'))
		{
			if(vEmail==false)
			{
					aErrors[aErrors.length]=AppData.generalLang.emailIsNotValid;
					isValid = false;
			}
		}
		if(NeedHelp.boxContainer.find("[name='password']").val()=="" || NeedHelp.boxContainer.find("[name='repeatPassword']").val()==""){
		aErrors[aErrors.length]=AppData.generalLang.passwordIsEmpty;
		isValid = false;
		}
		var password=NeedHelp.boxContainer.find("[name='password']").val();
		var repeatPassword=NeedHelp.boxContainer.find("[name='repeatPassword']").val();
		
		if(password!=repeatPassword){
		aErrors[aErrors.length]=AppData.generalLang.passwordNotMatch;
		isValid = false;
		}
		var phonePrefixValidNumric=NeedHelp.IsNumeric(NeedHelp.boxContainer.find("[name='phone_prefix']").val());
	    var phone_areaValidNumric=NeedHelp.IsNumeric(NeedHelp.boxContainer.find("[name='phone_area']").val());
	    var phoneValidNumric=NeedHelp.IsNumeric(NeedHelp.boxContainer.find("[name='Phone']").val());
				
		if(phonePrefixValidNumric==false || phone_areaValidNumric==false || phoneValidNumric==false)
		{
			aErrors[aErrors.length]=AppData.generalLang.phoneNumberNotValid;
			isValid = false;
		}
		

		if(NeedHelp.boxContainer.find("[name='acceptTerms']").attr("checked")==false){
					aErrors[aErrors.length]=AppData.generalLang.approveTheTerms;
			isValid = false;
		}

                if (! isValid ){
                   alert(AppData.generalLang.PleaseCorrectTheFormErrors+'\r\n' + aErrors.join('\r\n'));	
				}
		var formParams = form.serializeArray();
		
		if(NeedHelp.container.find('div.need_help_special').size()){
			if(isValid) return true;
			else return false;
		}
		alert("isvaild:"+isValid);
		if(isValid){
		alert("insideValid"+isValid);
			$.ajax({
						type: "POST",
						url: 'rpcProxy/needHelp',
						data: formParams,
						async: true,
						dataType: 'json',
						error : function() {
							alert('error');
						},
						success: function(data){
							if(data.status != true) { //failed
                                for (i in data.errors) {
                                    alert(data.errors[i]);
                                }
                            }
							else{ //success
								form.remove();
								NeedHelp.container.find('div#thankYou').removeClass('hidden');

								//Use an iframe so if the campaign code is JS, it will fire.
								var campaignCodeFrame = $('<iframe id="campaignFrame" frameborder="0" height="1" width="1" scrolling="no" src="rpcProxy/campaignCodeLoader/' + data.leadId + '"></iframe>');
                                NeedHelp.container.find('div#thankYou').append(campaignCodeFrame);

                                var googleIframe = $('<iframe id="googleFrame" frameborder="0" height="1" width="1" scrolling="no"></iframe>').attr('src',AppData.url + 'GoogleAnalytics');
								$('div#thankYou').append(googleIframe);
							}
					    }
					});
		}
		return false;
	}
	
	
	
}

$(document).ready(function() { 
	NeedHelp.init();
}); 
