/* This script and many more are available free online at
The JavaScript Source :: http://javascript.internet.com
Created by: Down Home Consulting :: http://downhomeconsulting.com */

/*
Country State Drop Downs v1.0.
(c) Copyright 2005 Down Home Consulting, Inc.
www.DownHomeConsulting.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, itness for a particular purpose and noninfringement. in no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software.

*/

// If you have PHP you can set the post values like this
//var postState = '<?= $_POST["state"] ?>';
//var postCountry = '<?= $_POST["country"] ?>';

var postState = '';
var postCountry = 'US:United States';
var isPlanSelected = 'false';
var formValid = 'false';
var nameValid = 'false';
var stateValid = 'false';
var cityValid = 'false';
var addrsValid = 'false';
var zipValid = 'false';
var detailValid = 'false';
var agreeValid = 'false';
var totalperiod = 3;
var installments = 0;
var valCount = 0;
var refSelect = 0;

// State table
//
// To edit the list, just delete a line or add a line. Order is important.
// The order displayed here is the order it appears on the drop down.
//
var state = '\
US:AL:Alabama|\
US:AK:Alaska|\
US:AZ:Arizona|\
US:AR:Arkansas|\
US:CA:California|\
US:CO:Colorado|\
US:CT:Connecticut|\
US:DE:Delaware|\
US:DC:District of Columbia|\
US:FL:Florida|\
US:GA:Georgia|\
US:HI:Hawaii|\
US:ID:Idaho|\
US:IL:Illinois|\
US:IN:Indiana|\
US:IA:Iowa|\
US:KS:Kansas|\
US:KY:Kentucky|\
US:LA:Louisiana|\
US:ME:Maine|\
US:MD:Maryland|\
US:MA:Massachusetts|\
US:MI:Michigan|\
US:MN:Minnesota|\
US:MS:Mississippi|\
US:MO:Missouri|\
US:MT:Montana|\
US:NE:Nebraska|\
US:NV:Nevada|\
US:NH:New Hampshire|\
US:NJ:New Jersey|\
US:NM:New Mexico|\
US:NY:New York|\
US:NC:North Carolina|\
US:ND:North Dakota|\
US:OH:Ohio|\
US:OK:Oklahoma|\
US:OR:Oregon|\
US:PA:Pennsylvania|\
US:RI:Rhode Island|\
US:SC:South Carolina|\
US:SD:South Dakota|\
US:TN:Tennessee|\
US:TX:Texas|\
US:UT:Utah|\
US:VT:Vermont|\
US:VA:Virginia|\
US:WA:Washington|\
US:WV:West Virginia|\
US:WI:Wisconsin|\
US:WY:Wyoming|\
';

// Country data table
//
// To edit the list, just delete a line or add a line. Order is important.
// The order displayed here is the order it appears on the drop down.
//
var country = 'US:United States';

function TrimString(sInString) {
  if ( sInString ) {
    sInString = sInString.replace( /^\s+/g, "" );// strip leading
    return sInString.replace( /\s+$/g, "" );// strip trailing
  }
}

// Populates the country selected with the counties from the country list
function populateCountry(defaultCountry) {
  if ( postCountry != '' ) {
    defaultCountry = postCountry;
  }
  var countryLineArray = country.split('|');  // Split into lines
  var selObj = document.getElementById('countrySelect');
  selObj.selectedIndex = 0;
  for (var loop = 0; loop < countryLineArray.length; loop++) {
    lineArray = countryLineArray[loop].split(':');
    countryCode  = TrimString(lineArray[0]);
    countryName  = TrimString(lineArray[1]);
    if ( countryCode != '' ) {
      selObj.options[loop] = new Option(countryName, countryCode);
    }
    if ( defaultCountry == countryCode ) {
      selObj.selectedIndex = loop + 1;
    }
  }
}

function populateState() {
  var selObj = document.getElementById('stateSelect');
  var foundState = false;
  // Empty options just in case new drop down is shorter
  if ( selObj.type == 'select-one' ) {
    for (var i = 0; i < selObj.options.length; i++) {
      selObj.options[i] = null;
    }
    selObj.options.length=null;
    selObj.options[0] = new Option('--Please Select State--','');
    selObj.selectedIndex = 0;
  }
  // Populate the drop down with states from the selected country
  var stateLineArray = state.split("|");  // Split into lines
  var optionCntr = 1;
  for (var loop = 0; loop < stateLineArray.length; loop++) {
    lineArray = stateLineArray[loop].split(":");
    countryCode  = TrimString(lineArray[0]);
    stateCode    = TrimString(lineArray[1]);
    stateName    = TrimString(lineArray[2]);
  if (document.getElementById('countrySelect').value == countryCode && countryCode != '' ) {
    // If it's a input element, change it to a select
      if ( selObj.type == 'text' ) {
        parentObj = document.getElementById('stateSelect').parentNode;
        parentObj.removeChild(selObj);
        var inputSel = document.createElement("SELECT");
        inputSel.setAttribute("name","bstate");
        inputSel.setAttribute("id","stateSelect");
        parentObj.appendChild(inputSel) ;
        selObj = document.getElementById('stateSelect');
        selObj.options[0] = new Option('--Please Select State--','');
        selObj.selectedIndex = 0;
      }
      if ( stateCode != '' ) {
        selObj.options[optionCntr] = new Option(stateName, stateCode);
      }
      // See if it's selected from a previous post
      if ( stateCode == postState && countryCode == postCountry ) {
        selObj.selectedIndex = optionCntr;
      }
      foundState = true;
      optionCntr++
    }
  }
  // If the country has no states, change the select to a text box
  if ( ! foundState ) {
    parentObj = document.getElementById('stateSelect').parentNode;
    parentObj.removeChild(selObj);
  // Create the Input Field
    var inputEl = document.createElement("INPUT");
    inputEl.setAttribute("id", "stateSelect");
    inputEl.setAttribute("type", "text");
    inputEl.setAttribute("name", "bstate");
    inputEl.setAttribute("size", 20);
    inputEl.setAttribute("value", postState);
    parentObj.appendChild(inputEl) ;
  }
}

function initCountry(country) {
  populateCountry(country);
  populateState();
}

function validateName(){

	var bname = document.getElementById('bnameID');
	var nameVal = document.getElementById('lblValidName');
	if ( bname.value == "" || bname.value == null){
		nameVal.innerHTML="Name is required!";
		nameVal.style.display='';
		nameValid = 'false';
		}
	else if (bname.value.length > 0)
	{
	   if (bname.value.match(/^[a-z \-]+$/i) && bname.value.length > 4) {
		nameVal.innerHTML="";
		nameVal.style.display='none';
		nameValid = 'true';
	    }
	   else {
		nameVal.innerHTML="Invalid or insufficient characters!";
		nameVal.style.display='';
		nameValid = 'false';
	}
	}
}

function stateSelected(){
	var state = document.getElementById('stateSelect');
	var country = document.getElementById('countrySelect');
	if (state.selectedIndex == 0){
	   document.getElementById('selectAState').style.display='';
	   stateValid = 'false';
	   }
	else {
	   document.getElementById('selectAState').style.display='none';
	   stateValid = 'true';
	   }
	}
	

function validateCity(){
	var bcity = document.getElementById('bcityID');
	var cityVal = document.getElementById('lblValidCity');
	if ( bcity.value == "" || bcity.value == null){
		cityVal.innerHTML="City is required!";
		cityVal.style.display='';
		cityValid = 'false';
		}
	else if (bcity.value.length > 0)
	{
	if (bcity.value.match(/^[a-z][0-9a-z \-]+$/i) && bcity.value.length > 3) {
		cityVal.innerHTML="";
		cityVal.style.display='none';
		cityValid = 'true';
	}
	else {
		cityVal.innerHTML="Invalid or insufficient characters!";
		cityVal.style.display='';
		cityValid = 'false';
	}
	}
}


function validateAddress(){
	var baddress = document.getElementById('baddressID');
	var addressVal = document.getElementById('lblValidAddress');
	if ( baddress.value == "" || baddress.value == null){
		addressVal.innerHTML="Address is required!";
		addressVal.style.display='';
		addrsValid = 'false';
		}
	else if (baddress.value.length > 0)
	{
	if (baddress.value.match(/^[0-9a-z \-.,]+$/i) && baddress.value.length > 5) {
		addressVal.innerHTML="";
		addressVal.style.display='none';
		addrsValid = 'true';
	}
	else {
		addressVal.innerHTML="Invalid or insufficient characters!";
		addressVal.style.display='';
		addrsValid = 'false';
	}
	}
}


function validateZip(){
	var bzip = document.getElementById('bzipID');
	var zipVal = document.getElementById('lblValidZip');
	if ( bzip.value == "" || bzip.value == null){
		zipVal.innerHTML="Zip Code is required!";
		zipVal.style.display='';
		zipValid = 'false';
		}
	else if (bzip.value.length > 0)
	{
	if (bzip.value.match(/^[0-9]{5}$/i)) {
		zipVal.innerHTML="";
		zipVal.style.display='none';
		zipValid = 'true';
	}
	else {
		zipVal.innerHTML="Invalid or insufficient characters!";
		zipVal.style.display='';
		zipValid = 'false';
	}
	}
}
	
function planClicked(objID, planDetails, customValue) {
	var planArray = planDetails.split(' ');
	var fee = planArray[0].toString();
	var frequency = parseInt(planArray[2]);
	var period = planArray[3].toLowerCase();
	isPlanSelected = 'true';
	var sPlan = document.getElementById("lblSelectAPlan");
        sPlan.innerHTML = '';
						
	document.getElementById('customID').value = customValue.toString();
	document.getElementById('oidID').value = objID;
	fee = fee.replace(/^./g,"");
		
	if (period == 'month' || period == 'months' && frequency > 0 && frequency < 12){
	installments = (totalperiod * 12) / frequency;
	document.getElementById('periodicityID').value = "m" + frequency.toString();
	document.getElementById('installmentsID').value = installments.toString();
	document.getElementById('chargetotalID').value = fee;
	}
	else if (period == 'year' && frequency > 0 && frequency <= totalperiod){
	installments = (totalperiod * 1) / frequency;
	document.getElementById('periodicityID').value = "y" + frequency.toString();
	document.getElementById('installmentsID').value = installments.toString();
	document.getElementById('chargetotalID').value = fee;
	}
	else if (period == 'week' && frequency > 0 && requency < 52){
	installments = (totalperiod * 52) / frequency;
	document.getElementById('periodicityID').value = "w" + frequency.toString();
	document.getElementById('installmentsID').value = installments.toString();
	document.getElementById('chargetotalID').value = fee;
	}
	
}

function refSelected(indx){
        
        var refBy = document.getElementById('lstReferredBy');
        var details = document.getElementById('detailsID');
        var lblDetails = document.getElementById('lblDetails');
        
        if(indx == 2){
        details.value = '';
        details.style.display = '';
        lblDetails.innerHTML = "Coordinator's Name?";
        lblDetails.style.display = '';
        }
        else if (indx == 5){
        details.value = '';        
        details.style.display = '';
        lblDetails.innerHTML = "Any details?";
        lblDetails.style.display = '';
        }
        else{
        details.value = '';        
        details.style.display = 'none';
        lblDetails.innerHTML = '';
        lblDetails.style.display = 'none';
        }
}

function validateAgree(){
	var agree = document.getElementById('agreeID');
	var lblAgree = document.getElementById('lblValidAgree');
	
	if (agree.checked == true) {
	agreeValid = 'true';
	lblAgree.innerHTML="";
	lblAgree.style.display='none';
	}
	else {
	agreeValid = 'false';
	lblAgree.innerHTML="Confirmation is required!";
	lblAgree.style.display='';

	}
}

function valRefDetails(){
        var details2 = document.getElementById('detailsID');
        var lblDetailsErr = document.getElementById('lblDetailsErr');
        if (details2.value.match(/^[0-9a-z \-.]*$/i)) {
		lblDetailsErr.innerHTML="";
		lblDetailsErr.style.display='none';
		detailValid = 'true';
	}
	else {
		lblDetailsErr.innerHTML="Invalid characters!";
		lblDetailsErr.style.display='';
		detailValid = 'false';
	}
        
}

function validateFORM(){
        if (isPlanSelected == 'false' && document.getElementById('chargetotalID').value == ""){
        var sPlan = document.getElementById("lblSelectAPlan");
        sPlan.innerHTML = 'Please select a Plan.';
	sPlan.style.display = '';
	}
	else if (document.getElementById('chargetotalID').value != "") isPlanSelected = 'true';
	
        validateName();
	validateCity();
	validateAddress();
	validateZip();
	stateSelected();
	valRefDetails();
	validateAgree();
	
	var customVal = document.getElementById('customID').value;
	var referredby = document.getElementById('lstReferredBy');
	var detailValue = document.getElementById('detailsID').value;
	
	if (isPlanSelected == 'true' && nameValid == 'true' && stateValid == 'true' && cityValid == 'true' && 
	addrsValid == 'true' && zipValid == 'true' && detailValid == 'true' && agreeValid == 'true' && document.getElementById('periodicityID').value != "" && 
	document.getElementById('installmentsID').value != "" && document.getElementById('chargetotalID').value != ""){
	        if (refSelect == 1) customVal = customVal.substr(0,customVal.lastIndexOf(","));
	        customVal = customVal + "," + referredby.options[referredby.selectedIndex].value + " - " + detailValue;
	        document.getElementById('customID').value = customVal;
	        refSelect = 1;	        
	        return true;
		}
	return false;
}
