// global variables
var WrkInput = '';
var WrkMonth = '';
var WrkDay = '';
var WrkYear = '';
var num_of_submits = 0;
var fbpager_on = 0;

// target _blank with a class of nyroModal indicates this is an external link
$(document).ready(function(){
   $.nyroModalSettings({
     processHandler: function(settings) {
        var from = settings.from;
        if (from && from.href && from.target == '_blank') {
          $.nyroModalSettings({
            height: 600,
            width: 700
          });
        }
      }
   });

   $(".JQSlider").click(function (event) {
        event.preventDefault();
        this_href = $(this).attr("href").replace(/javascript:/i,'');
        eval(this_href);
        div_2_toggle = $(this).parent(".JQSlider_parent").children(".slider_content").get(0);
        if($(this).parent(".JQSlider_parent").children(".faq_icon").length > 0){
            faq_icon = $(this).parent(".JQSlider_parent").children(".faq_icon").get(0);
            if($(faq_icon).attr("src") == '/img/icon_faq.gif'){
                $(faq_icon).attr({ src : "/img/icon_faq_open.gif"});
            } else {
                $(faq_icon).attr({ src : "/img/icon_faq.gif"});
            }
        }
        $(div_2_toggle).slideToggle() ;
    });

   $(".JQGlossary").each( function () {
        var id = $(this).attr("href").toString().split("=")[1];
        $(this).attr("href",$(this).attr("href").toString().split("?")[0]);
        encoded_params = 'id=' + id + '&catid=0&rt=glossary&divid=&requrl=';
        $(".JQGlossary").cluetip({
            closePosition : "title",
            sticky : true,
            mouseOutClose : true,
            arrows: true,
            ajaxSettings : {
                type : "GET",
                data : encoded_params
            }
        });
    });

    $('a.rounded').cluetip({
      splitTitle: '|',
      cluetipClass: 'rounded',
      positionBy: 'auto',
      sticky: false,
      showTitle: false,
      fx: {open:       'fadeIn', // can be 'show' or 'slideDown' or 'fadeIn'
           openSpeed:  '6000'
      }
    });
    $(".JQQuickOption").change(function (event) {
        event.preventDefault();
        if(isAllSpaces($(this).val())){
            return false;
        }
        if($(this).val().substr(0,9) == 'speedbump'){
            $.nyroModalManual({
                  url: $(this).val()
            });
            return false;
        } else {
            window.location = $(this).val();
        }
    });
    $('#fadingbanners').after('<div id="fbpager">').cycle({
//    $('#fadingbanners').cycle({
        fx:     'fade',
        speed:  'slow',
        speedIn:  2000,
        speedOut:  2000,
        timeout: 10000,
        pager:  '#fbpager',

        // callback fn that creates a title to use as pager anchor
        pagerAnchorBuilder: function(idx, slide) {
            return '<li><a href="#">' + banner_array[idx] + '</a></li>';
        }
    });

    $('#ManualSubmit').click(function(e) {
        e.preventDefault();
        $.nyroModalManual({
            url: 'speedbump_notify.php'
        });
        return false;
    });


    $('input[type=file]').change(function() {
        document.getElementById("submitstory").disabled = true;
        fn = $(this).attr('value');
        fn_array = fn.split('\\');
        idx = fn_array.length - 1;
        $('.pd_filename').html(fn_array[idx]);
        $('.pd_status').html('uploading');
        $('#progressdiv').show();
        $(this).upload('/upload_attach_1.php',
            function (data){
                resp_array = data.split('||'); // first slot contains 0 = successful, 1 = error
                if(resp_array[0] == '1'){
                    element_name = '';
                    element_value = '';
                    if(resp_array[1]){
                        keyval = resp_array[1];
                        if(keyval.indexOf('~~~') > 0){
                            keyval_array = keyval.split('~~~');
                            $('#pd_errors').html(keyval_array[1]);
                        }
                    }
                    $('.pd_filename').html('Attachment Failed');
                    $('.pd_status').html('');
                    $('.pd_process').hide();
                    document.getElementById("submitstory").disabled = false;
                } else {
                    element_name = '';
                    element_value = '';
                    if(resp_array[1]){
                        keyval = resp_array[1];
                        if(keyval.indexOf('~~~') > 0){
                            keyval_array = keyval.split('~~~');
                            element_name = keyval_array[0];
                            element_value = keyval_array[1];
                            $('#' + keyval_array[0]).attr('value',keyval_array[1]);
                            $('#attachRemove').show();
                            document.getElementById('attachRemove').style.display = 'block';
                        }
                    }
                    $('.pd_status').html('Attached');
                    $('.pd_process').hide();
                    $('#attachRemove').show();
                    document.getElementById("submitstory").disabled = false;
                }
            },
            'html');

    });

});

function removeAttach(){
    $('#attachment1').attr('value','');
    $('.pd_filename').html('');
    $('.pd_status').html('');
    $('.pd_errors').html('');
    $('#attachRemove').hide();
}

function login(){
    document.getElementById("theLform").submit();
}
function item_disp(reqtype,id,catid,selstmtid,divid,requrl,newwin){
    justslider = 0;
    /* reqtype selarticle = retrieve the article id from the select box
               selfindisc = retrieve the financial discussion article from the select box
               article = retrieve the requested article
               findisc = retrieve the requested financial discussion item
               faq = retrieve the requested FAQ item
       id = the id of the record to retrieve
       catid = the id of the category the record is associated with
       selstmtid = the id of the select statement (for reqtype selarticle and selfindisc only)
       divid = id of the div holding the content to be displayed (for article and findisc only);
       requrl = the url to pass control to (optional)
       newwin = open in new window '1' otherwise '0'
    */
    switch(reqtype){
      case 'selarticle':
        selObj = document.getElementById(selstmtid);
        if(selObj.selectedIndex < 1 || selObj.options[selObj.selectedIndex].value == ''){
            alert("Please select another Article.");
            return;
            break;
        }
        id = selObj.options[selObj.selectedIndex].value;
        break;
      case 'selfinlib':
        selObj = document.getElementById(selstmtid);
        if(selObj.selectedIndex < 1 || selObj.options[selObj.selectedIndex].value == ''){
            alert("Please select another Article.");
            return;
            break;
        }
        id = selObj.options[selObj.selectedIndex].value;
        break;
      case 'article':
      case 'finlib':
        break;
      case 'faq':
      case 'calc':
      case 'external':
      case 'glossary':
        break;
      default:
        return;
        break;
    }
    if(isNaN(id) || isNaN(catid)){
        return;
    }

    encoded_params = 'id=' + id + '&catid=' + catid + '&rt=' + reqtype + '&divid=' + divid + '&requrl=' + requrl;
    $.ajax({
        type: "GET",
        async: false,
        url: "/php/process/ajax_getinfo.php",
        data: encoded_params,
        success: function(response){
            response_area = response;
            if(response_area.substr(0,6) == 'Please'){  // invalid topic selection
                alert(response_area);
                return;
            }
            switch(reqtype){
                case 'article':
                case 'selarticle':
                case 'selfinlib':
                case 'finlib':
                case 'faq':
                case 'glossary':
                  resp_array = response_area.split('|');
                  for(i=0;i<resp_array.length;i++){
                      itemarray = new Array(2);
                      itemarray[0] = '';
                      itemarray[1] = '';
                      if(resp_array[i]){
                          keyval = resp_array[i];
                          if(keyval.indexOf('~') > 0){
                              keyval_array = keyval.split('~');
                              for(y=0;y<keyval_array.length;y++){
                                  itemarray[y] = keyval_array[y];
                              }
                              // set the individual items
                              label = itemarray[0];
                              switch(label){
                                  case 'htmlblock':
                                    if(reqtype != 'glossary'){
                                        tmpid = divid;
                                        document.getElementById(tmpid).innerHTML = itemarray[1];

                                        $('#' + divid + ' a.nyroModal').each( function () {
                                          //  alert( $(this).attr("href"));
                                            $(this).nyroModal();
                                            if ($(this).attr("target") == '_blank') {
                                              $.nyroModalSettings({
                                                height: 600,
                                                width: 700
                                              });
                                            }
                                        });
                                     
                                    } else {
                                        document.itemarray[1];
                                    }
                                    break;
                                  case 'webbug':
                                    if(document.getElementById("webbug_div")){
                                      document.getElementById("webbug_div").innerHTML = itemarray[1];
                                    }
                                    break;
                                  case 'advisor':
                                    if(document.getElementById("advisor_div")){
                                      document.getElementById("advisor_div").innerHTML = itemarray[1];
                                    }
                                    break;
                                  case 'callouts':
                                    if(document.getElementById("promotions_div")){
                                      document.getElementById("promotions_div").innerHTML = itemarray[1];
                                    }
                                    break;
                                  default:
                                    break;
                              }
                          }
                      }
                  }
                  break;
                case 'calc':
                case 'external':
                    if(newwin == 1){
                        WinId = window.open(requrl,target="PopWin", "toolbar=no,location=no,directories=no,scrollbars=yes,resizable=yes,width=730,height=790");
                    } else {
                        window.location.href = requrl;
                    }
                    break;
                default:
                    break;
            }

        },
        error: function(data){
            alert("We're Sorry, you're request could not be processed.");
        }
    });

}
function readynamevalue(pform){
    param_array = new Array();
    theform = pform;
    for(i=0;i<theform.elements.length;i++){
        var the_element = theform.elements[i];
        switch (the_element.type){
            // bypass buttons
            case "button":
            case "submit":
            case "reset":
                break;
            // checkboxes/radio buttons - only return the value if the control is checked
            case "checkbox":
            case "radio":
                if(!the_element.checked){
                    break;
                }
            // text/hidden/password all return the values
            case "text":
                param_array.push(encodenamevalue(the_element.name,the_element.value,'0'));
                break;
            case "hidden":
            case "password":
                param_array.push(encodenamevalue(the_element.name,the_element.value));
                break;
            // everything else
            default:
                switch(the_element.tagName.toLowerCase()){
                    case "select":
                    if(the_element.selectedIndex != -1){
                        param_array.push(encodenamevalue(the_element.name,the_element.options[the_element.selectedIndex].value));
                    }
                    break;
                    default:
                        param_array.push(encodenamevalue(the_element.name,the_element.value));
                        break;
                }
        }
    }
    return param_array.join("&");
}
function encodenamevalue(pname,pvalue,surrogate_ind){
    if(surrogate_ind == null){
        surrogate_ind = '0';
    }
    var wrk_param = encodeURIComponent(pname);
    wrk_param += "=";
    if(surrogate_ind == '0'){
        wrk_param += encodeURIComponent(pvalue);
    } else {
        wrk_param += encodeURIComponent (uni2ent(pvalue));
    }
    return wrk_param;
}

function uni2ent(srcTxt) {
  var entTxt = '';
  var c, hi, lo;
  var len = 0;
  for (var i=0, code; code=srcTxt.charCodeAt(i); i++) {
    var rawChar = srcTxt.charAt(i);
    // needs to be an HTML entity
    if (code > 255) {
      // normally we encounter the High surrogate first
      if (0xD800 <= code && code <= 0xDBFF) {
        hi  = code;
        lo = srcTxt.charCodeAt(i+1);
        // the next line will bend your mind a bit
        code = ((hi - 0xD800) * 0x400) + (lo - 0xDC00) + 0x10000;
        i++; // we already got low surrogate, so don't grab it again
      }
      // what happens if we get the low surrogate first?
      else if (0xDC00 <= code && code <= 0xDFFF) {
        hi  = srcTxt.charCodeAt(i-1);
        lo = code;
        code = ((hi - 0xD800) * 0x400) + (lo - 0xDC00) + 0x10000;
      }
      // wrap it up as Hex entity
      c = "" + code.toString(16).toUpperCase() + ";";
    }
    else {
      c = rawChar;
    }
    entTxt += c;
    len++;
  }
  return entTxt;
}

// sanitize input
function isEmail(string) {
	err_num = 0;
	if(string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]{2,6}$/)!= -1){
		return true; 
	} else {  
		err_num = 3;
		return false;
	}
}
function isillegalChars(string){
	var illegalChars = /[^\.\-&,\(\)_ ''a-zA-Z0-9[\s]]/; // allow only letters, numbers, spaces, underscores, hyphens,periods and apostrophe
	if(illegalChars.test(string)){
		err_num = 4;
		return true; // illegal characters found
	} else {
		return false; // no illegal characters found
	}
}
function isDate(PassField){
	err_num = 0;
	var re = /\//gi;
	var re1 = /-/gi;

	WrkInput = PassField.replace(re, "-");
	tempInput = WrkInput.replace(re1,"");
	if( !isNumeric(tempInput) ){
		err_num = 2;
		return false;
	}

	WrkLength = PassField.length;

	if (WrkLength < 8 || WrkLength > 10) {
		err_num = 2;
		return false;
	}

	string_array = WrkInput.split("-");
	if(string_array.length != 3){
		err_num = 2;
		return false;
	}

	WrkMonth = string_array[0];
	WrkDay = string_array[1];
	WrkYear = string_array[2];

	// valid day check to include leap year validation
	if (WrkMonth == 2){
		if ((WrkYear % 4) != 0) {
			daylimit = 28;
		} else if((WrkYear % 400) == 0) {
			daylimit = 29;
		} else if((WrkYear % 100) == 0) {
			daylimit = 28;
		} else {
			daylimit = 29;
		}
	} else {
		if (WrkMonth == 4 || WrkMonth == 6 || WrkMonth == 9 || WrkMonth ==11){
			daylimit = 30;
		} else {
			daylimit = 31;
		}
	}

	if (WrkMonth < 1 || WrkMonth > 12) {
		err_num = 2;
		return false;
	}

	if (WrkDay < 1 || WrkDay > daylimit) {
		err_num = 2;
		return false;
	}

	if(WrkYear.length != 4){
		err_num = 2;
		return false;
	}

	if (WrkYear < 1) {
		err_num = 2;
		return false;
	}
    if(WrkDay.length != 2){
        WrkDay = '0' + WrkDay;
    }
    if(WrkMonth.length != 2){
        WrkMonth = '0' + WrkMonth;
    }
	return true;
}

function isNumeric(PassField) {
	var legalNum = /\D/; // allow only numbers
	if (PassField.length == 0){
		return false;
	}
	if(legalNum.test(PassField)) {
		return false; // non numeric character found
	} else {
		return true;
	}	
}
function isAllSpaces(inputValue) {
  if(inputValue.search(/^\s*$/) != -1) {
    // the string contains just spaces or is empty
    return true;
  } else {
    // valid input
    return false;
  }
}
// functions to limit submitting of the form to one time
function setoneclick(func2invoke){
	num_of_submits = num_of_submits + 1;
	if(num_of_submits > 1){
		return false;
	}
	eval(func2invoke);
}
function resetoneclick(){
	num_of_submits = 0;
	return false;
}
function searchsubmit(frm) {
  if(frm.s.value.length == 0) {
    return false;
  } else {
    return true;
  }
}
function quicklinks(qlinksel,quicklinkfrm){
    qlinkObj = document.getElementById(qlinksel);
    qlinkFrmObj = document.getElementById(quicklinkfrm);
	if(qlinkObj.selectedIndex == 0 || qlinkObj.selectedIndex == -1){
	 	return false;
	}

	window.location = qlinkObj.options[qlinkObj.selectedIndex].value;
}

function tabbed_content_click(tabid) {
  //  hide all inactive, show active
  for(i=1;i<=10;i++) {
        if (document.getElementById('tab_' + i)) {
            tabel = document.getElementById('tab_' + i);
            tabcontel = document.getElementById('int_content_area_' + i);
            tabela = document.getElementById('tabh_' + i);
            if (i == tabid) {
                tabel.className += " current";
                if (tabela) tabela.blur();
                tabcontel.style.display = 'block';
                tabcontel.style.visibility = 'visible';
            } else {
                removeName(tabel, "current");
                tabcontel.style.display = 'none';
                tabcontel.style.visibility = 'hidden';
            }
        }
  }
}
function removeName(el, name) {
  var i, curList, newList;
  if (el.className == null)
    return;
  // Remove the given class name from the element's className property.
  newList = new Array();
  curList = el.className.split(" ");
  for (i = 0; i < curList.length; i++)
    if (curList[i] != name)
      newList.push(curList[i]);
  el.className = newList.join(" ");
  return true;
}
function prtpage (){
    if(!window.print){
		alert("To print this page, please close this window and hit either CTRL + P or Command + P");
		return;
	} else {
		window.print();
	}
}
function validatecontact(){
	stop_process = 'no';
	for(i=0;i<document.contactform.elements.length;i++){
		if(document.contactform.elements[i].name.substr((document.contactform.elements[i].name.length - 4),4) == '_req'){
			name2chk = document.contactform.elements[i].name.substr(0,(document.contactform.elements[i].name.length - 4));
			chkObj = document.getElementById(name2chk);
			if(name2chk == 'state'){
				if(chkObj.selectedIndex < 1){
					name2get = name2chk + '_lbl';
					chkObj_label = document.getElementById(name2get).innerHTML;
					alert(document.getElementById(name2get).innerHTML + " is required.");
					stop_process = 'yes';
					break;
				}
			} else {

				if(isAllSpaces(chkObj.value)){
					name2get = name2chk + '_lbl';
					chkObj_label = document.getElementById(name2get).innerHTML;
					alert(document.getElementById(name2get).innerHTML + " is required.");
					stop_process = 'yes';
					break;
				}
			}
		}
		if(document.contactform.elements[i].name == 'email'){
			chkObj = document.getElementById('email');
			if(!isEmail(document.getElementById('email').value)){
				alert(document.getElementById('email_lbl').innerHTML + " does not appear to be valid.");
				stop_process = 'yes';
				break;
			}
		}
	}
	if(document.getElementById("message_regarding").type == 'select-one'){
		idx = document.getElementById("message_regarding").selectedIndex;
		document.contactform.subject.value = document.getElementById("message_regarding").options[idx].value;
	}
    if(isAllSpaces(document.getElementById("formkey_user").value)){
        alert("Please enter the code from the security image.");
		document.getElementById("formkey_user").focus();
		return false;
    }
	if(stop_process == 'yes'){
		return false;
	}
    encoded_params = readynamevalue(document.getElementById("contactform"));
    $.ajax({
        type: "POST",
        async: false,
        url: "/php/process/ajax_proccontact.php",
        data: encoded_params,
        success: function(data){
            response_area=data;
            resp_array = response_area.split('~'); // first slot contains 0 = successful, 1 = error
            document.getElementById("contactmsg").innerHTML = resp_array[1];
            if(resp_array[0] == '0'){
                document.getElementById("contact_div").innerHTML = '';
            }
        },
        error: function(data){
          alert("We're sorry, your email could not be sent. Please try another method of contact.");
        }
    });
}

function valRateAlert(){
    encoded_params = readynamevalue(document.getElementById("raform"));
    $.ajax({
        type: "POST",
        async: false,
        url: "/ra_sign_up.php",
        data: encoded_params,
        success: function(response){
            document.getElementById("RateAlertSignUp").innerHTML = response;
        }, // end of success
        error: function(response){
            alert("We're Sorry, The Rate Alert System is currently unavailable.");
         }
    });
    resetoneclick();
}
function valSeminarStep1(){
    num_to_proc = 0;
    if(document.getElementById("chksignup")){
        if(document.getElementById("chksignup").length){
            for(i=0;i<document.getElementById("chksignup").length;i++){
                if(document.getElementById("chksignup")[i].checked){
                    num_to_proc++;
                }
            }
        } else {
            if(document.getElementById("chksignup").checked){
               num_to_proc++;
            }
        }
        if(num_to_proc > 0){
            encoded_params = readynamevalue(document.getElementById("seminarform"));
            $.ajax({
                type: "POST",
                async: false,
                url: "/seminar_sign_up_2.php",
                data: encoded_params,
                success: function(response){
                    document.getElementById("SemSignUp").innerHTML = response;
                }, // end of success
                error: function(response){
                    alert("We're Sorry, The Seminar system is currently unavailable for sign-up.");
                 }
            });
            resetoneclick();
        } else {
            alert("Please confirm that you want to signup for this seminar.");
            resetoneclick();
            return false;
        }
    }
}
function valSeminarStep2(){
    var do_not_process = 0;
    var elements_in_error = '';

    encoded_params = readynamevalue(document.getElementById("seminarSignupform"));
    $.ajax({
        type: "POST",
        async: false,
        url: "/seminar_sign_up_2.php",
        data: encoded_params,
        success: function(response){
            document.getElementById("SemSignUp").innerHTML = response;
        }, // end of success
        error: function(response){
            alert("We're Sorry, The Seminar system is currently unavailable for sign-up.");
         }
    });
    resetoneclick();
}
function valSurvey(){
    encoded_params = readynamevalue(document.getElementById("SurveyForm"));
    $.ajax({
        type: "POST",
        async: false,
        url: "/php/process/procsurvey.php",
        data: encoded_params,
        success: function(response){
            response_array = response.split('~');
            if(response_array[0] == '0'){
                document.getElementById("SurveyFormDiv").innerHTML = response_array[1];
            } else {
                document.getElementById("surveyerrors").innerHTML = response_array[1];
                document.getElementById("fkimage").src = '/scripts/formkey.php?key=' + response_array[2];
                document.getElementById("formkey_sys").value = response_array[2];
                document.getElementById("formkey_user").value = '';
            }
        }, // end of success
        error: function(response){
            alert("We're Sorry, The Survey system is currently unavailable for sign-up.");
         }
    });
    resetoneclick();
}

function valForSaleContact(){
    encoded_params = readynamevalue(document.getElementById("forsaleContact"));
    $.ajax({
        type: "POST",
        async: false,
        url: "/forsale/reply.php",
        data: encoded_params,
        success: function(response){
            document.getElementById("forsaleForm").innerHTML = response;
        }, // end of success
        error: function(response){
            alert("We're Sorry, The Classified system is currently unavailable.");
         }
    });
    resetoneclick();
}

function valForSalePost(){
    document.getElementById("forsalepost").submit();
    resetoneclick();
}

function getTopics(category,formid){
    if(document.getElementById(category).selectedIndex > 0){
        selIndex = document.getElementById(category).selectedIndex;
        selValue = document.getElementById(category).options[selIndex].value;
        document.getElementById(formid).submit();
    }
}
function ValidateFormInput(formid){
    action = document.getElementById(formid).action;
    // first clear the error divs
    div_nodes = document.getElementsByTagName('DIV');
    for (i=0;i<div_nodes.length; i++) {
        divObj=div_nodes[i];
        startPos = divObj.id.length - 6;
        if(divObj.id.substr(startPos,6) == '_error'){
            document.getElementById(divObj.id).innerHTML = '';
        }
    }

    // now clear the form elements label class name
    elementsObj = eval('document.' + formid + '.elements');
    for(i=0;i<elementsObj.length;i++){
        var the_element = elementsObj[i];
        // clear the labels classname
        if(the_element.id.substr((the_element.id.length - 6),6) == '_label'){
            command = "document.getElementById(\"" + the_element.id + "\").className = \"\";";
            eval(command);
        }
    }
    // include application specific editing here
    // call to process the form
    encoded_params = readynamevalue(document.getElementById(formid));
    errors_occured = 'no';
    $.ajax({
        type: "POST",
        async: false,
        url: action,
        data: encoded_params,
        success: function(data){
            response_area=data;
            resp_array = response_area.split('|');
            for(i=0;i<resp_array.length;i++){
                itemarray = new Array(2);
                itemarray[0] = '';
                itemarray[1] = '';

                if(resp_array[i]){
                    keyval = resp_array[i];
                    if(keyval.indexOf('~~~') > 0){
                        keyval_array = keyval.split('~~~');
                        for(y=0;y<keyval_array.length;y++){
                            itemarray[y] = keyval_array[y];
                        }
                        switch (itemarray[0]){
                            case 'status':
                                if(itemarray[1] == '1'){
                                    errors_occured = 'yes';
                                }
                                break;
                            case 'error_message_area':
                            case 'error_message_items':
                            case 'form_div':
                            case 'title':
                                document.getElementById(itemarray[0]).innerHTML = itemarray[1];
                                break;
                            default:
                                if(itemarray[0].substr((itemarray[0].length - 6),6) == '_error'){
                                    document.getElementById(itemarray[0]).innerHTML = itemarray[1];
                                }
                                break;
                        }
                    }
                }
            }
        },
        error: function(data){
          alert("We're sorry, your submission could not be sent. Please try another method of contact.");
        }
    });

    window.location.hash = "#topofpage";
    return false;

}
function chkKey(evt,type){
    // numeric test only
    type = (type == null) ? 'n' : type; // default to numeric testing

    var e = evt || event; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;
    if(charCode == 9 || charCode == 8 || charCode == 46){
        return true;
    }

    if(type == 'n'){
        if (charCode > 47 && charCode < 58){
            return true;
        } else {
            return false;
        }
    } else if(type == 'a'){
        // alpha test only
        if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8 || charCode == 16 || charCode == 32 || charCode == 222 || charCode == 192 || charCode == 39) {
        	return true;
        } else {
        	return false;
        }
    } else if(type == 'n-'){
        // alpha test only but with hyphen and forward slash
        if ((charCode > 47 && charCode < 58) || charCode == 45 || charCode == 47) {
        	return true;
        } else {
        	return false;
        }
    }
    return true;
}
function validateStory(){
	stop_process = 'no';
	if(isAllSpaces(document.getElementById("member_name").value)) {
		alert('Please enter your Name.');
		document.getElementById("member_name").focus();
		return;
	}

    if(!isEmail(document.getElementById('email_address').value)){
		alert('You must provide a valid Email Address.');
		document.getElementById("email_address").focus();
		return;
	}

    if(!isAllSpaces(document.getElementById("member_since").value)) {
        WrkMonth = '';
	    WrkDay = '';
	    WrkYear = '';
	    if(!isDate(document.getElementById("member_since").value)){
            alert("The date you became a member does not appear to be valid. Please enter it in the format of mm-dd-yyyy.");
            document.getElementById("member_since").focus();
            return resetoneclick();
        }

    } else {
        alert('Please tell us when you became a member.');
		document.getElementById("member_since").focus();
		return;
    }

    if(isAllSpaces(document.getElementById("phone").value)) {
		alert('Please enter your phone number.');
		document.getElementById("phone").focus();
		return;
	}

    if(isAllSpaces(document.getElementById("story_title").value)) {
		alert('Please enter a title for your story.');
		document.getElementById("story_title").focus();
		return;
	}

    if(isAllSpaces(document.getElementById("story").value)) {
		alert('Please enter the text of your story.');
		document.getElementById("story").focus();
		return;
	}

	if (document.getElementById("agree").checked == false) {
		alert('Please read the consent agreement at the bottom of the page and click on the checkbox to show your consent.');
		document.getElementById("agree").focus();
		return;
	}

    encoded_params = readynamevalue(document.getElementById("storyform"));

    $.ajax({
        type: "POST",
        async: false,
        url: "/php/process/ajax_procstory.php",
        data: encoded_params,
        success: function(data){
            response_area=data;
            resp_array = response_area.split('~'); // first slot contains 0 = successful, 1 = error
             if(resp_array[0] == '0'){
                document.getElementById("storydiv").innerHTML = resp_array[1];
            } else {
                alert(resp_array);
            }
        },
        error: function(data){
          alert("We're sorry, your story could not be sent. Please try again later.");
        }
    });
}

