// JavaScript Document
var currentCustomer = false;
var selectedRegion  = '';
var errorStyle = "formLabelError";

var arrayRequiredFields = new Array("fname", "lname", "compy", "years_in_business",
									"address", "city", "state", "zipcd", "email", "phone");

var billing_type;
var debug_string = "";

// When page is ready...
$(document).ready(function(){ 
	$("#cc_form").submit(function() {
        var success = true;
        success = ValidateForm();
        if (success == 0) {
            success = false;
        }
        return success;
    });
	
	$("input").focus(function () {
        var tempName = "#" + this.name + "_label";
        $(tempName).removeClass(errorStyle);
    });
	$("select").change(function () {
        var tempName = "#" + this.name + "_label";
        $(tempName).removeClass(errorStyle);
    });
	
	$("#billing_info_question").click(function(){
        Open_Info_Window();
    });
});

function Open_Info_Window()
{
     window.open ("billing-information.php","info_window","menubar=0,location=0,resizable=1,width=400,height=300");
}


function OverrideStyles(newBorder, newImage, newMessage, newLabel)
{
	if (newBorder.length == 2) {
		styleBorderColor = newBorder;
	}
	if (newImage.length == 2) {
		styleImage = newImage;
	}
	if (newMessage.length == 2) {
		styleMessage = newMessage;
	}
	if (newLabel.length == 2) {
		styleLabel = newLabel;
	}
}

function OverrideRequiredFields(newReqFields)
{
	arrayRequiredFields = newReqFields;
}

function SubmitForm(formName)
{
	if ( Form1_Validator() ) {
		document.getElementById(formName).submit();
	}

}

function togglePaymentType(radioObj)
{
	var checkedButtonValue = getCheckedValue(radioObj);
	if (checkedButtonValue != "") {
		if (checkedButtonValue == "0") {  // credit card
			$("#credit_card_info").show();
			$("#billing_information").hide();
			billing_type = 0;
		} else {   // monthly bill
			$("#credit_card_info").hide();
			$("#billing_information").show();
			billing_type = 1;
		}
	}
}

function toggleBillingAddress()
{
	if ($("#bill_addr_same:checked").length == 1) {
		$("#bill_addr_same_div").hide(200);
	} else { // unchecked
		$("#bill_addr_same_div").show(200);
	}
}

function toggleCCBillingAddress()
{
	if ($("#cc_addr_same:checked").length == 1) {
		$("#cc_addr_same_div").hide(200);
	} else { // unchecked
		$("#cc_addr_same_div").show(200);
	}
}

function toggleSalesRep()
{
	referral_type = 0;
}

function togglePaymentPref()
{
	
}

function PageInit()
{
	billing_type = getCheckedValue(document.cc_form.billing);
	toggleCCBillingAddress();
	toggleBillingAddress();
}

function sectionHide(sectionName)
{
	document.getElementById(sectionName).style.display = "none";
}

function sectionShow(sectionName)
{
	document.getElementById(sectionName).style.display = "block";
}

function getCheckedValue(radioObj) {
	if(!radioObj) {
		return "";
	}
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		if(radioObj.checked) {
			return radioObj.value;
		} else {
			return "";
		}
	}
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}



function MessageBox(smBox,smClass,smText)
{
	document.getElementById(smBox).className = smClass;
	document.getElementById(smBox).innerHTML = smText;
	self.scrollTo(0,0);
}

function CheckField(field_name) {
	//alert("checking " + field_name);
	var field_is_valid_binary = 1;

	if (document.getElementById(field_name).value == "")
	{
		//give red border around textbox, red label text, red x image, and red error message.
		MessageBox('successMessage', 'smAttention', stdMessage);
		field_is_valid_binary = 0;
	}
	SetStyles(field_name, field_is_valid_binary);

	return field_is_valid_binary;
}

function SetError(fieldName)
{
	$(fieldName).addClass(errorStyle);
}

// Expects successIndex to be 0 (failed) or 1 (passed)
function SetStyles(fieldName, successIndex) {
 fieldName += "_label";

 if (successIndex != 0) {
  successIndex = 1;
  
 }
 if (successIndex == 0) {
  SetError("#" + fieldName);
 }
}

function ValidateAgreement(agreementIsChecked)
{
	var tempAgreementCheck = 1;
	if (!agreementIsChecked) {
		tempAgreementCheck = 0;
		MessageBox('successMessage', 'smAttention', stdMessage);
	}
	SetStyles("agreement", tempAgreementCheck);
	return tempAgreementCheck;
}

function ValidateEmail(emailString)
{
	var tempEmailCheck = 1;
	var emailRegExp = /^(.+)@([a-z0-9_\-\.]+)\.([a-z]{2,6})$/i;
	emailString += "";
	var result = emailString.match(emailRegExp);
	if ( result == null ) {
		tempEmailCheck = 0;
		MessageBox('successMessage', 'smAttention', stdMessage);
	}
	SetStyles("email", tempEmailCheck);
	return tempEmailCheck;
}

function ValidatePhone(phoneString)
{
	var tempPhoneCheck = 1;
	phoneString += "";
	
	//Phone number Validation #2 - Check If numeric and has acceptable non-numerics (e.g. dash or dot)
	var stripped = phoneString.replace(/[\(\)\.\-\ ]/g, '');
	//strip out acceptable non-numeric characters so we can check whether it is a numeric (NAN means Not a Number in JS)
	if (isNaN(stripped) || (stripped == "") )
	{
		tempPhoneCheck = 0;
		MessageBox('successMessage', 'smAttention', stdMessage);
	}
	SetStyles("phone", tempPhoneCheck);
	return tempPhoneCheck;
}

// validate entire form on submit
function ValidateForm()
{
	var tempCheck = 1;
	isValid = "true";
	stdMessage = "Items on the form need your attention.<br />Please correct any highlighted items and try again.";

	// Check required fields; any failure will multiply tempCheck by 0 and it will remain 0 for the rest of the way.
	// If all checks pass, it will come out as 1 at the end.
	for (var i=0; i<arrayRequiredFields.length; i++) {
		tempCheck *= CheckField(arrayRequiredFields[i]);
		if (arrayRequiredFields[i] == "email") {
			tempCheck *= ValidateEmail(document.getElementById("email").value);
		} else if (arrayRequiredFields[i] == "phone") {
			tempCheck *= ValidatePhone(document.getElementById("phone").value);
		} else if (arrayRequiredFields[i] == "agreement") {
			tempCheck *= ValidateAgreement(document.getElementById("agreement").checked);
		}
	}
	
	// Check special cases for optional billing addresses
	if (!(document.getElementById("bill_addr_same").checked)) {
		tempCheck *= CheckField("bill_contact");
		tempCheck *= CheckField("bill_email");
		tempCheck *= CheckField("bill_phone");
		tempCheck *= CheckField("bill_addr1");
		tempCheck *= CheckField("bill_city");
		tempCheck *= CheckField("bill_state");
		tempCheck *= CheckField("bill_zip");
	}
	
	//all validations succeeded
	if (tempCheck == 1) {
		return (true);
	} else {
		return (false);
	}
}

