﻿var btnStatus = false;
var isComplete = false;

/* login form */
	function validateSignIn(e) {
		if (isValidLoginFields()) {
			disableCtlById('btnSubmit', false, 'continueBtn');
			btnStatus = true;
		}
		else {
			disableCtlById('btnSubmit', true, 'continueBtn-disabled');
			btnStatus = false;
		}
		// submit for on enter
		if (btnStatus == true) doClick('btnSubmit',e);
	}

	function validateLogin(e) {
		if (isValidLoginFields()) {
			disableCtlById('btnSubmit', false, 'loginBtnSm');
			btnStatus = true;
		}
		else {
			disableCtlById('btnSubmit', true, 'loginBtnSm-disabled');
			btnStatus = false;
		}
		// submit for on enter
		if (btnStatus == true) doClick('btnSubmit',e);
	}

	function isValidLoginFields() {
		var isValid = false;
		if (document.getElementById('txtLogin').value.length > 0 && document.getElementById('txtPass').value.length > 0) isValid = true;
		return isValid;
	}

/* forgot password form */
	function validateForgotPass(e) {
		if (isValidForgotPassFields()) {
			disableCtlById('btnSubmit', false, 'passwordBtn');
			btnStatus = true;
		}
		else {
			disableCtlById('btnSubmit', true, 'passwordBtn-disabled');
			btnStatus = false;
		}
		// submit for on enter
		if (btnStatus == true) doClick('btnSubmit',e);
	}

	function isValidForgotPassFields() {
		var isValid = false;
		var loginID = document.getElementById('txtLNameID').value;
		var loginIDConfirm = document.getElementById('txtLNameConfirmID').value;
		
		if(loginID.length > 0 && loginID == loginIDConfirm) isValid = true;
		return isValid;
	}

/* contact us form */
	function validateContact(e) {
		if (isValidContactUsFields()) {
			disableCtlById('btnSubmit', false, 'submitBtn');
			btnStatus = true;
		}
		else {
			disableCtlById('btnSubmit', true, 'submitBtn-disabled');
			btnStatus = false;
		}
		// submit for on enter
		if (btnStatus == true) doClick('btnSubmit',e);
	}

	function isValidContactUsFields(showMsg) {
	    var isValid = false;
	    // fields to validate
	    var validFieldID = new Array("First", "Last", "Company", "Phone", "ContactMessage");
	    var emailID = document.getElementById('Email').value

	    // make sure that the fields in validFieldID have a value
	    if(validFieldLength(validFieldID)) {
            // make sure that the email address has a valid format
	    	if (validEmail(emailID))
	    	{
	    		isValid = true;
	    	}
	    }
	   
		if (showMsg == true && isValid != true)
		{
			alert("Please check your email address and all required fields.  Please press OK and fill in the required fields (marked with an *) and press Submit.  Thank you for your cooperation.");
		}
		return isValid;
	}

/* credit card validation */
	// initialize vars
	var selectedCCIndex = 0;
	var isValid = false;
	var ccInfoIsValid = false;
	
	ccGroupArray = new Array(
		new Array("Visa", "VISA",
			new Array("4"),
			new Array("13", "16")
		),
		new Array("MasterCard", "MasterCard",
			new Array("51", "52", "53", "54", "55"),
			new Array("16")
		),
		new Array("Amex", "American Express",
			new Array("34", "37"),
			new Array("15")
		),
		new Array("Discover", "Discover",
			new Array("6011"),
			new Array("16")
		)/* ,
		new Array("DinersClubCard", "Diners Club",
			new Array("30", "36", "38"),
			new Array("14")
		),
		new Array("enRouteCard", "enRoute",
			new Array("2014", "2149"),
			new Array("15")
		),
		new Array("JCBCard", "JCB",
			new Array("3088", "3096", "3112", "3158", "3337", "3528"),
			new Array("16")
		) */
	);

	function setSelectedCCIndex(index) {
		this.selectedCCIndex = index;
	}

	function getSelectedCCIndex() {
		for (i in ccGroupArray) {
			if (document.getElementById(ccGroupArray[i][0]).className == 'ccImage selected') {
				return i;
			}
		}
	}
	// set selected cc image border
	function setSelectedCC(obj) {
		// get the selected index
		setSelectedCCIndex(getSelectedCCIndex());
		
		if (obj.id != ccGroupArray[selectedCCIndex][0]) {
			addClass(document.getElementById(ccGroupArray[selectedCCIndex][0]), 'selected', true);

			getSelectedCCIndex();
			
			for (i in ccGroupArray) {
				if (ccGroupArray[i][0] == obj.id) {
					setSelectedCCIndex(i);
					addClass(document.getElementById(ccGroupArray[selectedCCIndex][0]), 'selected', false);
				}
			}
			// set focus on cc number
			//document.getElementById("cNumID").focus();
		}
	}
	// function to make sure the value is a number
	function isNum(num) {
		num = num.toString();
		if (num.length == 0) return false;
		for (var n = 0; n < num.length; n++) {
			if (num.substring(n, n + 1) < "0" || num.substring(n, n + 1) > "9") return false;
		}
		return true;
	}

	// boolean luhnCheck([String CardNumber]) - return true if CardNumber pass the luhn check else return false.
	function luhnCheck(cardNumber) {
		// luhn test
		var no_digit = cardNumber.length;
		var oddoeven = no_digit & 1;
		var sum = 0;

		for (var count = 0; count < no_digit; count++) {
			var digit = parseInt(cardNumber.charAt(count));
			if (!((count & 1) ^ oddoeven)) {
				digit *= 2;
				if (digit > 9)
					digit -= 9;
			}
			sum += digit;
		}
		if (sum % 10 == 0)
			return true;
		else
			return false;
	}

	// validates the credit card number
	function checkCardNumber() {
		// initialize vars
		var ccNumObj = document.getElementById("cNumID");
		var cardNumber = ccNumObj.value;
		var isValid = false;
		var startDigitLen;

		// make sure that the value entered is a number
		if (!isNum(cardNumber)) {
			return false;
		}
		// check the length of the card number
		for (var i in ccGroupArray[this.selectedCCIndex][3]) {
			if (cardNumber.length == ccGroupArray[this.selectedCCIndex][3][i] && !isValid) {
				// check the start digits of the cc number are valid
				for (var j in ccGroupArray[this.selectedCCIndex][2]) {
					// get the length of the valid start digits
					startDigitLen = ccGroupArray[this.selectedCCIndex][2][j].length;
					if (ccGroupArray[this.selectedCCIndex][2][j] == cardNumber.substring(0, startDigitLen) && !isValid) {
						isValid = true;
						break;
					}
				}
			}
		}
		if (!isValid) return false;
		// make sure that the number passes the luhn test
		if (!this.luhnCheck(cardNumber)) {
			return false;
		}
		return true;
	}

	// validates all credit card data
	function validateCard(obj) {
		// check card num
		if (checkCardNumber()) {
			this.isValid = true;
		} else {
			alert("The credit card number entered is not valid");
			//obj.focus();
			this.isValid = false;
		}
	}

	function checkExpDate(obj) {
	// initialize vars
		var cardExp = obj.value;
		var isValid = false;
		var d = new Date();
		var minExpDate = (d.getMonth() + 12 * d.getFullYear());

		// make sure that the value entered is a number
		if(!isNum(cardExp)){
			return false;
		}
		// make sure it is current
		if (cardExp.length == 4) {
			var modCardExp = (parseInt(cardExp.substr(0, 2)) + parseInt(20 + cardExp.substr(2, 4)) * 12);
			if (modCardExp >= minExpDate) {
				isValid = true;
			} else {
				isValid = false;
				alert("The credit card expiration date has passed.");
			}
		}else{
			isValid = false;
		}
		return isValid;
	}
	// run on key up
	function isValidPurchaseFields() {
		// fields to validate
		var isValid = false;
		var validFieldID = new Array("cNumID","cSecCodeID","cExpID","fNameID","lNameID","bCompanyNameID","bAddressID","bCityID","bZipID","bStateID","uPhoneID","uEmailID");
		
		// make sure that the fields in validFieldID have a value
		(validFieldLength(validFieldID) ? isValid = true : isValid = false);

		// make sure that the email address has a valid format
		(validEmail(document.getElementById('uEmailID').value) && isValid ? isValid = true : isValid = false);
		
		// credit card number to pass Luhn Test
		(checkCardNumber() && isValid ? isValid = true : isValid = false);

		// make sure that the expiration date is valid
		(checkExpDate(document.getElementById('cExpID')) && isValid ? isValid = true : isValid = false);
		
		return isValid;
	}

	// run on form submit
	function isPurchaseFieldsFinal() {
		// fields to validate
		var validFieldID = new Array("cNumID", "cSecCodeID", "cExpID", "fNameID", "lNameID", "bCompanyNameID", "bAddressID", "bCityID", "bZipID", "bStateID", "uPhoneID", "uEmailID");

		// make sure that the fields in validFieldID have a value
		if (!validFieldLength(validFieldID)) {
			alert("One or more of the required fields is missing a value.");
			return false;
		}

		// make sure that the email address has a valid format
		if (!validEmail(document.getElementById('uEmailID').value)) {
			alert("Please enter in a valid email address.");
			document.getElementById('uEmailID').focus();
			return false;
		}

		// credit card number to pass Luhn Test
		if (!checkCardNumber()){
			alert("The credit card entered does not appear to be valid. Please check the card you selected and the number entered.");
			document.getElementById('cNumID').focus();
			return false;
		}

		// make sure that the expiration date is valid
		if (!checkExpDate(document.getElementById('cExpID'))) {
			alert("The credit card expiration date has passed.");
			document.getElementById('cExpID').focus();
			return false;
		}
		return true;
	}

	function validatePurchase() {
		// if complete, set button
		if (isValidPurchaseFields()) {
			disableCtlById('btnSubmit', false, 'submitBtn');
		} else {
			disableCtlById('btnSubmit', true, 'submitBtn-disabled');
		}
	}
/* end cc validation */


/* validate signup form */
	function validateSignUp() {
		// if complete, set button
		if (isValidSignUpFields()) {
			disableCtlById('btnSubmit', false, 'signupBtn');
		}else {
			disableCtlById('btnSubmit', true, 'signupBtn-disabled');
		}
	}

	function validateNewSignUp() {
		// if complete, set button
		if (isValidSignUpFields()) {
			disableCtlById('btnSubmit', false, 'continueBtn');
		}else {
			disableCtlById('btnSubmit', true, 'continueBtn-disabled');
		}
	}

	function isValidSignUpFields() {
		// fields to validate
			var validFieldID = new Array("txtFnameID", "txtLnameID", "txtCnameID", "txtEmailID", "txtPhoneID");

		// make sure that the fields in validFieldID have a value
		(validFieldLength(validFieldID) ? isComplete = true : isComplete = false);

		// make sure that the email address has a valid format
		(validEmail(document.getElementById('txtEmailID').value) && isComplete ? isComplete = true : isComplete = false);

		return isComplete;
	}
	
	function validFieldLength(ar) {
		// initialize vars
		numFields = ar.length;
		var num = 0;
		
		while (numFields > num) {
			// Debug: alert (num + '='+ document.getElementById(validFieldID[num]).value)
			if (document.getElementById(ar[num]))
			{
				if (document.getElementById(ar[num]).value.length == 0)
				{
					return false;
				}
			}
			num++;
		}
		return true;
	}

	function validEmail(eID, showMsg) {
		if (eID.match(/^([\w\-]+)(\.[\w\-]+)*@([\w\-]+\.){1,5}([A-Za-z]){2,4}$/))
		{
			return true;
		}
		else
		{
			if (showMsg === true)
			{
				alert("The email address you have entered is invalid.");
			}
		}
		return false;
	}

	function doClick(buttonName, e) {
		var key;
		if (window.event)
			key = window.event.keyCode;		//IE
		else
			key = e.which;					//firefox

		if (key == 13) {
			//Get the button the user wants to have clicked
			var btn = document.getElementById(buttonName);
			if (btn != null) { //If we find the button click it
				btn.click();
				event.keyCode = 0
			}
		}
	}

	function cancelSignupConfirm() {
		var title = "Message from BRTNow";
		var message = "Press \"OK\" to continue or press \"Cancel\" to return to the Signup Form.\n\nAfter completing the form, you will receive email instructions for\nimmediate access to your trial account.";
		var answer = confirm(message, title)
		if (answer) {
			window.location = "default.aspx";
		}
	}
/* end validate signup */

function loginHover(ctl, remove) {
	if (ctl.disable == true) {
		return;
	} else {
		addClass(ctl, 'loginBtnSm-hover', remove);
	}
}

function generalBtnHover(ctl, hoverCss, remove) {
	if (ctl.disable == true) {
		return;
	} else {
		addClass(ctl, hoverCss, remove);
	}
}

// Temporary function until logic is added as code behind
function appMenuButtons(showDemo, showTrial, showBuy, showOver, showChat, showWhitePaper, showCallUs) {
	showWhitePaper == (showWhitePaper == undefined ? false : showWhitePaper);
	showCallUs == (showCallUs == undefined ? true : showCallUs);
	var strHtml = '';
    var chat = '<a id="_lpChatBtn" ' +
		' href="http://server.iad.liveperson.net/hc/77038128/?cmd=file&file=visitorWantsToChat&site=77038128&byhref=1&SESSIONVAR!skill=TechSupport&imageUrl=http://server.iad.liveperson.net/hcp/Gallery/ChatButton-Gallery/English/General/1a" ' +
		' target="chat77038128" ' +
		' onClick="javascript:window.open(\'http://server.iad.liveperson.net/hc/77038128/?cmd=file&file=visitorWantsToChat&site=77038128&SESSIONVAR!skill=TechSupport&imageUrl=http://server.iad.liveperson.net/hcp/Gallery/ChatButton-Gallery/English/General/1a&referrer=\'+escape(document.location),\'chat77038128\',\'width=472,height=320,resizable=yes\');return false;" ' +
		' class="support-chat">Support Chat</a>';
    if (showChat == false) chat = '';
    if(showDemo) strHtml+='<a href="/ArrangeDemo.aspx" class="arrange-demo">Arrange a Free Demonstration</a>'
    if (showTrial) strHtml += '<a href="/TrialSignup.aspx" class="free-trial">Free 30 Day Trial</a>';
    if (showBuy) strHtml += '<a href="/about/packages.html" class="buy-now">Buy Now</a>';
    if (showWhitePaper)
    {
    	strHtml += '<a class="whitepaperLink" href="/GetWhitepaperTopProducer.aspx">Get Top Producer Little Black Book</a>';
    }
    if (showCallUs)
    {
    	strHtml += chat + '<p class="toll-free">Call Toll-Free 800-777-3162</p>';
    }
    if (showOver) strHtml += '<a class="tour" href="/about/tour.html">Take the Tour</a>';
    
    strHtml += "<br />&nbsp;<br />&nbsp;";
    document.getElementById('buttonMenuContainerID').innerHTML = strHtml;
}

function CookieHandler() {
    this.setCookie = function (cName, val, secs){
        if (typeof (secs) != 'undefined'){
            var date = new Date();
            date.setTime(date.getTime() + (secs * 1000));
            var expires = "; expires=" + date.toGMTString();
        }else{
            var expires = "";
        }
        document.cookie = cName + "=" + val + expires + "; path=/";
    }
    this.getCookie = function (cName) {
        cName = cName + "=";
        var carray = document.cookie.split(';');

        for (var i = 0; i < carray.length; i++) {
            var c = carray[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(cName) == 0) return c.substring(cName.length, c.length);
        }
        return null;
    }
    this.deleteCookie = function (cName) {
        this.setCookie(cName, "", -1);
    }
}

function disableCtlById(ctlId, disable, css) {
	var ctl = document.getElementById(ctlId);
	if (ctl) {
		ctl.disabled = disable;
		if (disable == true) {

			addClass(ctl, css);
		}
		else {
			//addClass(ctl, css, true);
			ctl.className = css;
		}
	}
}

function addClass(ctl, cssClass, remove) {
	remove = remove == undefined ? false : remove;
	if (ctl && ctl.className) {
		var classString = ctl.className;
		var clsArray = classString.split(' ');
		var newClsArray = new Array();
		for (var i = 0; i < clsArray.length; i++) {
			if (clsArray[i] != cssClass) {
				newClsArray.push(clsArray[i]);
			}
		}
		if (remove == false) {
			newClsArray.push(cssClass);
		}
		ctl.className = newClsArray.join(' ');
	}
}
