/***************************************************************************************
* @author Diabetes Victoria
* @date 20/Oct/2015
* @description This file is used to validate and submit clothing form
****************************************************************************************/

var clothingDetails={
	/******* Variable Decleration to use throughout the page *****/
	formData:[],
	dateList:{},
	clothData:{},
	pageUrl:window.location.origin,
    /********* Code for  getValueFromID *************/
	getValueFromID : function(itemID) {
	  var valueOfRecord = $("#"+itemID).val();
		  if(valueOfRecord){
			return valueOfRecord;
		  }else{
			return "";
		  }
	},
	/***** email Validation function *********/
	emailValidation : function(values){
		intRegex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
		 var emailflag = intRegex.test(values);
		if(!emailflag){
	 		return false;
		} else {
			return true;
		}
	},
	/******* Checking for Number only *******/
   checkInputNumber: function(number) {
       if(number == "") {
           return false;
       } else {
			var numNum = +number;
			if (isNaN(number)) {
				return false;
			} else {
				return true;
			}
       }
   },
	/****** function for Contact Validation ********/
	contactValidation: function(contact) {

        if(contact == "") {
           return false;
        }

		var numNum = +contact;
		if (isNaN(numNum)) {
			return false;
		}

		if(contact.length != 10) {
			return false;
		}

		if(contact.indexOf(0) != 0) {
					return false;
				}

		return true;

	},
	/******** Checking All Validations ********/
    clothingValidationCheck: function() {

		var userTitle = clothingDetails.getValueFromID("titleField");
		if (userTitle == "") {
			alert("Title is required");
			return true;
		}
        var fnameUser = clothingDetails.getValueFromID("firstNameField");
        if(fnameUser == "") {
        	alert("First Name Is Required");
        	return true;
        }
        var lastName = clothingDetails.getValueFromID("lastNameField");
        if(lastName == "") {
        	alert("Last Name Is Required");
        	return true;
        }
		var contact = clothingDetails.getValueFromID("phoneField");
		if(!clothingDetails.contactValidation(contact)) {
		 alert("Phone must be 10 digit no. - area code or phone number must start with 0, without spaces or brackets");
		 return true;
		}
		var emailUser = clothingDetails.getValueFromID("emailField");
          if(emailUser == ""){
          	alert("Email is required");
            return true;
           } else {
               if(!clothingDetails.emailValidation(emailUser)) {
                 alert("Enter valid Email Address");
                 return true;
               }
          }
		var streetAddress = clothingDetails.getValueFromID("streetAddressField");
		if (streetAddress == "") {
			alert("Please enter your address");
			return true;
		}
        var userCityName = clothingDetails.getValueFromID("suburbField");
        if(userCityName == "") {
        	alert("Please enter City name");
        	return true;
        }
        var userPostcode = clothingDetails.getValueFromID("postCodeField");
        if(userPostcode == "") {
        	alert("Please enter a postcode");
        	return true;
        } else if(!clothingDetails.checkInputNumber(userPostcode) || userPostcode.length > 4) {
        	alert("Please enter a valid postcode");
        	return true;
        }
		// var mobile = clothingDetails.getValueFromID("mobileField");
		// if(mobile != null) {
			// if(!clothingDetails.contactValidation(mobile)) {
			 // alert("Mobile number must be 10 digit no. - without spaces or brakets");
			 // return true;
			// }
		// }

        var collectionDate = clothingDetails.getValueFromID("collectionIdField");
        if(collectionDate == "") {
        	alert("Please choose a collection date");
        	return true;
        }

        var clothingOption = clothingDetails.getValueFromID("clothingToCollectField");
        var othersOption   = clothingDetails.getValueFromID("othersToCollectField");

        if(clothingOption == false && othersOption == false) {
        	alert("Please choose option from itesm to be collected.");
        	return true;
        }
		if($("#donateAmt").prop('checked')){

				if(clothingDetails.getValueFromID("donationAmt") == "" ){
					alert("Please Enter Donation Amount.");
					return true;
				}
				if(clothingDetails.getValueFromID("donationAmt") == "" && clothingDetails.getValueFromID("donationAmt") == "pls"){
					alert("Please Select Card Type.");
					return true;
				}
				if(clothingDetails.getValueFromID("creditCardNumber") == ""){
					alert("Please Enter Card Number.");
					return true;
				}
				if(clothingDetails.getValueFromID("creditCardNumber") == ""){
					alert("Please Enter Card Number.");
					return true;
				}
				if(clothingDetails.getValueFromID("cardHolderName") == ""){
					alert("Please Enter Card Holder Name.");
					return true;
				}
				if(clothingDetails.getValueFromID("expMonth") == "" && clothingDetails.getValueFromID("expMonth") == "month"){
					alert("Please Select Expiry Month.");
					return true;
				}
				if(clothingDetails.getValueFromID("expYear") == "" && clothingDetails.getValueFromID("expYear") == "Year"){
					alert("Please Select Expiry Year.");
					return true;
				}
				if(clothingDetails.getValueFromID("cvv") == ""){
					alert("Please Enter CVV Number.");
					return true;
				}
		}

        return false;
    },
	/******* Call to Sales Force Service to Save Clothing Data *********/
	submitClothingForm : function(clothingData) {
			//$("div#showLoader").show();
		try {
				console.log(clothingData);
				$.orchestracmsRestProxy.doAjaxServiceRequest('DV_OCMS_ClothingCollection_Service', clothingData, function(testStatus, json, xhr) {
				console.log(json);
				if(json.success){
					var donation=clothingDetails.getValueFromID("donationAmt");
					//$('div#showLoader').hide();
					if(donation !=""){
							console.log("donation Amount - >",donation);
							//$("#showLoader").show();
							if(json.Clothing.firstTime){
								setTimeout(function(){console.log("first loop");clothingDetails.resendData(json)},30000);
							}
							if(json.Clothing.Redirect){
								console.log('if clothing redirect');
								window.location.href=clothingDetails.pageUrl+'/Thank-You'+'?tags=Thank+you/clothing-collection';
								$('div#showLoader').hide();
							}
					}else{
						console.log('else clothing redirect');
						window.location.href=clothingDetails.pageUrl+'/Thank-You'+'?tags=Thank+you/clothing-collection';
						$('div#showLoader').hide();
					}
				}else if(json.Fraudarant_Opportunity){
					window.location.href = '/Payment-Error';
				}else{
					$("div#showLoader").hide();
					alert(json.Clothing.Message);
				}
			}, null, false);
		} catch (err) {
			$("div#showLoader").hide();
			alert("error = " + err);
		}
	},

	resendData:function(json) {
		var newJson=json;
		newJson["action"]='ProcessClothingCollectionRetry';
		newJson['AccountId']=newJson.Clothing.AccountId;
		newJson["Amount"]=newJson.Clothing.Amount;
		newJson['ApexJobId']=newJson.Clothing.ApexJobId;
		newJson['OppId']=newJson.Clothing.OppId;
		newJson['PickUpId']=newJson.Clothing.PickUpId;
		newJson["allowCallouts"]="true";
		console.log("resendData",newJson);
		clothingDetails.submitClothingForm(newJson)
		//$("#showLoader").show();
	},

	generateUserDetail : function(clothingData) {
		try {
				$.orchestracmsRestProxy.doAjaxServiceRequest('DV_OCMS_ClothingCollection_Service', clothingData, function(testStatus, json, xhr) {
					console.log(json);
					if(json.success) {
							clothingDetails.clothData=json;
							clothingDetails.salutation();
							if(clothingDetails.clothData.customerDetails){
									clothingDetails.userDetail();
								}
					} else{

					}
				}, null, false);

		} catch (err) {
			alert("error = " + err);
		}
	},
	/****** Adding salutations *******/
	salutation:function(){
		if(clothingDetails.clothData.salutations){
			var options='';
			for(var i=0;i<clothingDetails.clothData.salutations.length;i++){
				options=options+'<option value="'+clothingDetails.clothData.salutations[i].salutation+'">'+clothingDetails.clothData.salutations[i].salutation;
			}
			$('#titleField').append(options);
		}
	},
	/****** generating user Details *******/
	userDetail:function(){

		if(clothingDetails.clothData.customerDetails.Salutation){
			$('#titleField').val(clothingDetails.clothData.customerDetails.Salutation);
		}
		if(clothingDetails.clothData.customerDetails.FirstName){
			$('#firstNameField').val(clothingDetails.clothData.customerDetails.FirstName);
		}
		if(clothingDetails.clothData.customerDetails.LastName){
			$('#lastNameField').val(clothingDetails.clothData.customerDetails.LastName);
		}
		if(clothingDetails.clothData.customerDetails.Phone){
			$('#phoneField').val(clothingDetails.clothData.customerDetails.Phone);
		}
		if(clothingDetails.clothData.customerDetails.PersonMobilePhone){
			$('#mobileField').val(clothingDetails.clothData.customerDetails.PersonMobilePhone);
		}
		if(clothingDetails.clothData.customerDetails.PersonEmail){
			$('#emailField').val(clothingDetails.clothData.customerDetails.PersonEmail);
		}
		if(clothingDetails.clothData.customerDetails.ShippingStreet){
			$('#streetAddressField').val(clothingDetails.clothData.customerDetails.ShippingStreet);
		}
		if(clothingDetails.clothData.customerDetails.ShippingState){
			$('#stateField').val(clothingDetails.clothData.customerDetails.ShippingState);
		}
		if(clothingDetails.clothData.customerDetails.ShippingCity){
			$('#suburbField').val(clothingDetails.clothData.customerDetails.ShippingCity);
		}
		if(clothingDetails.clothData.customerDetails.ShippingCountry){
			$('#countryField').val(clothingDetails.clothData.customerDetails.ShippingCountry);
		}
		// if(clothingDetails.clothData.customerDetails.ShippingPostalCode){
			// $('#postCodeField').val(clothingDetails.clothData.customerDetails.ShippingPostalCode);
		// }

	},
	/********* Call to salesForce to retrieve Order Date *******/
	callToSalesForce:function(actionData) {
		try {
			$("div#showLoader").show();
			$.orchestracmsRestProxy.doAjaxServiceRequest('DV_OCMS_ClothingCollection_Service', actionData, function(checkStatus, json, xhr) {
				console.log(json);
				if(json.success) {
						console.log(json);
						clothingDetails.dateList=json;
						if(clothingDetails.dateList.Values){
							if($('#collectionIdField').children().length > 1)
							{
								$('#collectionIdField').children().remove();

								$('#collectionIdField').append('<option value="">Select Collection Date</option>');
								for(var i=0;i<clothingDetails.dateList.Values.length;i++){
								$('#collectionIdField').append('<option value="'+clothingDetails.dateList.Values[i].Id+'">'+clothingDetails.dateList.Values[i].Date);
								}
							}else{
								$('#collectionIdField').children().remove();
								$('#collectionIdField').append('<option value="">Select Collection Date</option>');
								for(var i=0;i<clothingDetails.dateList.Values.length;i++){
								$('#collectionIdField').append('<option value="'+clothingDetails.dateList.Values[i].Id+'">'+clothingDetails.dateList.Values[i].Date);
								}
							}
						}
						$("div#showLoader").hide();
				}else{
					console.log(json);
					alert(json.messageToUser);
					$("div#showLoader").hide();
				}
			}, null, false);
		} catch (err) {
			alert("error = " + err);
		}
	},
	/******* Function to call Event Listener **********/
	listener:function(){
		actionData={};
		$('#postCodeField').focusout(function () {
			if($(this).val()!==""){
				actionData["action"]="GetClothingCollectionDate";
				actionData["allowCallouts"]="true";
				actionData["PostCode"]=clothingDetails.getValueFromID('postCodeField');
				console.log("data to send",actionData)
				clothingDetails.callToSalesForce(actionData);
			}
		});
		/******** disabled some inputs and blocks ******/
		$(document).on('click','#clothingSubmitBtn',clothingDetails.submitClothingCollectionInfo);
		$('#clothingSubmitBtn').prop('disabled',true).css({'opacity':'0.6'});
		$('#clothingPackField').prop('disabled',true).css({'opacity':'0.6'});
		$('#clothingQtyField').attr('disabled',true).css({'opacity':'0.6'});
		$('#otherPackField').prop('disabled',true).css({'opacity':'0.6'});
		$('#otherQtyField').attr('disabled',true).css({'opacity':'0.6'});
		$('#otherItemsField').attr('disabled',true).css({'opacity':'0.6'});
		$('#donationAmt').hide();
		$('#paymentDetail').hide();
		$('#noThanks').prop('checked',true);
		//$(document).on('','#phoneField')phoneNovalidation
		 $("#phoneField").unbind('keyup');
		$("#phoneField").bind("keyup", clothingDetails.phoneNovalidation);
		 $("#mobileField").unbind('keyup');
		$("#mobileField").bind("keyup", clothingDetails.phoneNovalidation);

		 $("#clothingQtyField").unbind('keyup');
		$("#clothingQtyField").bind("keyup", clothingDetails.qtyLimit);
		 $("#otherQtyField").unbind('keyup');
		$("#otherQtyField").bind("keyup", clothingDetails.qtyLimit);

		$("#creditCardNumber").unbind('keyup');
		$("#creditCardNumber").bind("keyup", clothingDetails.creditCard);

		$("#cvv").unbind('keyup');
		$("#cvv").bind("keyup", clothingDetails.cvvLimit);

		$("#donationAmt").unbind('keyup');
		$("#donationAmt").bind("keyup", clothingDetails.phoneNovalidation);

		clothingDetails.clothingCheckBox();
		clothingDetails.otherCheckBox();
		clothingDetails.donationRadio();
		clothingDetails.noThanksRadio();
	},
	/******** function to get checked checkbox ********/
	checkboxValue:function(inputId){
		var a=$('input[id="'+inputId+'"]:checked');
		if(a.length > 0 )
		{
			return true;
		}
		else{
			return false;
		}
	},
	humanBeginChk:function(){

		$('#humanCheckboxId').click(function(){
			if($(this).prop('checked')) {
				$('#clothingSubmitBtn').prop('disabled',false).css({'opacity':'1'});
			}else {
				$('#clothingSubmitBtn').prop('disabled',true).css({'opacity':'0.6'});
			}
		});
	},
	clothingCheckBox:function(){
		$('#clothingToCollectField').click(function(){
			if($(this).prop('checked')) {
				$('#clothingPackField').prop('disabled',false).css({'opacity':'1'});
				$('#clothingQtyField').attr('disabled',false).css({'opacity':'1'});
			}else {
				$('#clothingPackField').prop('disabled',true).css({'opacity':'0.6'}).val("None");
				$('#clothingQtyField').attr('disabled',true).css({'opacity':'0.6'}).val("");
			}
		});
	},
	otherCheckBox:function(){
		$('#othersToCollectField').click(function(){
			if($(this).prop('checked')) {
				$('#otherPackField').prop('disabled',false).css({'opacity':'1'});
				$('#otherQtyField').attr('disabled',false).css({'opacity':'1'});
				$('#otherItemsField').attr('disabled',false).css({'opacity':'1'});
			}else {
				$('#otherPackField').prop('disabled',true).css({'opacity':'0.6'}).val("None");
				$('#otherQtyField').attr('disabled',true).css({'opacity':'0.6'}).val("");
				$('#otherItemsField').attr('disabled',true).css({'opacity':'0.6'}).val("");
			}
		});
	},
	donationRadio:function(){
		$("#donateAmt").click(function(){
			if($(this).prop('checked')){
				$('#donationAmt').show();
				$('#paymentDetail').show();
			}else{
				$('#donationAmt').hide();

			}
		});
	},
	noThanksRadio:function(){
		$("#noThanks").click(function(){
			if($(this).prop('checked')){
				$('#donationAmt').hide();
				$('#paymentDetail').hide();
				$('#donationAmt').val("");
			}
		});
	},
	phoneNovalidation :  function(){
   	     this.value = this.value.replace(/[^0-9.]/g,'').substring(0,10);
    },
	qtyLimit:function(){
   	     this.value = this.value.replace(/[^0-9.]/g,'').substring(0,3);
    },
	cvvLimit:function(){
   	     this.value = this.value.replace(/[^0-9.]/g,'').substring(0,4);
    },
	creditCard:function(){
   	     this.value = this.value.replace(/[^0-9.]/g,'').substring(0,16);
    },
	/****** Checking Validation and Collecting all values ********/
	submitClothingCollectionInfo:function(){

		if(!clothingDetails.clothingValidationCheck()){
			$("div#showLoader").show();
			$('#showLoader #loading-content').text("");
		$('#loading-content').append('<p>Your submission is processing. Please do not resubmit or press the browser back button. Please wait...</p>');
			personalInfo = {};
			personalInfo["title"]=clothingDetails.getValueFromID("titleField");
			personalInfo["firstName"]=clothingDetails.getValueFromID("firstNameField");
			personalInfo["lastName"]=clothingDetails.getValueFromID("lastNameField");
			personalInfo["phone"]=clothingDetails.getValueFromID("phoneField");
			personalInfo["mobile"]=clothingDetails.getValueFromID("mobileField");
			personalInfo["email"]=clothingDetails.getValueFromID("emailField");
			personalInfo["streetAddress"]=clothingDetails.getValueFromID("streetAddressField");
			personalInfo["cityName"]=clothingDetails.getValueFromID("suburbField");
			personalInfo["countryName"]=clothingDetails.getValueFromID("countryField");
			personalInfo["stateName"]=clothingDetails.getValueFromID("stateField");
			personalInfo["postCode"]=clothingDetails.getValueFromID("postCodeField");
			personalInfo["collectionId"]=clothingDetails.getValueFromID("collectionIdField");
			personalInfo["clothingToCollect"]=clothingDetails.checkboxValue('clothingToCollectField');
			personalInfo["othersToCollect"]=clothingDetails.checkboxValue("othersToCollectField");
			personalInfo["otherItems"]=clothingDetails.getValueFromID("otherItemsField");
			personalInfo["clothingPack"]=clothingDetails.getValueFromID("clothingPackField");
			personalInfo["otherPack"]=clothingDetails.getValueFromID("otherPackField");
			personalInfo["clothingQty"]=clothingDetails.getValueFromID("clothingQtyField");
			personalInfo["otherQty"]=clothingDetails.getValueFromID("otherQtyField");
			personalInfo["extraInfo"]=clothingDetails.getValueFromID("extraInfoField");
			//payment
			personalInfo["donationAmt"]=clothingDetails.getValueFromID("donationAmt");
			personalInfo["creditCardType"]=clothingDetails.getValueFromID("creditCardType");
			personalInfo["creditCardNumber"]=clothingDetails.getValueFromID("creditCardNumber");
			personalInfo["cardHolderName"]=clothingDetails.getValueFromID("cardHolderName");
			personalInfo["expMonth"]=clothingDetails.getValueFromID("expMonth");
			personalInfo["expYear"]=clothingDetails.getValueFromID("expYear");
			personalInfo["cvv"]=clothingDetails.getValueFromID("ccv");
			personalInfo["action"]="ProcessClothingCollection";
	        personalInfo["allowCallouts"]="true";
			console.log("clothingForm = " , personalInfo);


			clothingDetails.submitClothingForm(personalInfo);
		};
	},

	populateExpiryMonthYear : function(monthInputId, yearInputId) {

		//First of all, we need to empty the state dropdown
		var list = document.getElementById(monthInputId);
		var yearList = document.getElementById(yearInputId);

		// empty the list
		if(list != null) {
			for (i = 1 ; i < list.options.length ; i++) {
				list.options[i] = null;
			}
		}

		if(yearList != null) {
			for (i = 1 ; i < yearList.options.length ; i++) {
				yearList.options[i] = null;
			}
		}

		if(list != null) {
			var i = 0;
			var todayDate = new Date();
			var currentMonth = todayDate.getMonth();
			var currentYear = todayDate.getFullYear();

			list.options[i++] = new Option('January', '01');
			list.options[i++] = new Option('February', '02');
			list.options[i++] = new Option('March', '03');
			list.options[i++] = new Option('April', '04');
			list.options[i++] = new Option('May', '05');
			list.options[i++] = new Option('June', '06');
			list.options[i++] = new Option('July', '07');
			list.options[i++] = new Option('August', '08');
			list.options[i++] = new Option('September', '09');
			list.options[i++] = new Option('October', '10');
			list.options[i++] = new Option('November', '11');
			list.options[i++] = new Option('December', '12');

			for(var j = 0; j < 12; j++) {
				if(j == currentMonth) {
					$(monthInputId).val(list.options[j].value);
				}
			}

			i = 0;

			for(var year = currentYear; year < currentYear + 10; year++) {
					yearList.options[i++] = new Option(year, year.toString().substring(2, 4));
					if(year == currentYear) {
						$(yearInputId).val(year);
					}
			}
		}
	},

	removeParam : function(key) {

	    var url = document.location.href;
	    console.log('@@@ pageURL = ', url);

	    if(url.indexOf('ocmsLang') !== -1) {
		    var params = url.split('?');
		    if (params.length == 1) return;

		    url = params[0] + '?';
		    params = params[1];
		    params = params.split('&');

		    $.each(params, function (index, value) {
		    	console.log('@@@ value = ', value);
		        var v = value.split('=');
		        if (v[0] != key) url += value + '&';
		    });

		    url = url.replace(/&$/, '');
		    url = url.replace(/\?$/, '');

		    console.log('@@@ newURL = ', url);
		    document.location.href = url;
	    }
	}
};

/******* Initializing Function on Document ready **********/
$(document).ready(function() {
	if($('#ClothingCollection').length > 0){
		console.log('Clothing collection form loaded');

		/* To fix collection dates issue. Otherwise the ocmsLang parameter is alerting the dates */
		clothingDetails.removeParam('ocmsLang');

		var dataToSend={};
		/******* Initializing Function after 3 seconds *********/
		setTimeout(function(){clothingDetails.listener()},2000);
		/********** Human being CheckBox *********/
		$('#clothingSubmitBtn').prop('disabled',true).css({'opacity':'0.6'});
		clothingDetails.humanBeginChk();
		/****** Check for user Login *******/
		if(CMS.user_type == 'Guest'){
			dataToSend['action']='fetchSalutation';
			clothingDetails.generateUserDetail(dataToSend);
		}else{
			dataToSend['action']='PopulateLoggedInUserDetails';
			clothingDetails.generateUserDetail(dataToSend);
		}

		clothingDetails.populateExpiryMonthYear("expMonth","expYear");
	}
});
