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

// target _blank with a class of nyroModal indicates this is an external link
$(document).ready(function(){
   $.nyroModalSettings({
     minWidth: 100,
     minHeight: 100,
     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").cluetip({
        closePosition : "title",
        positionBy: 'mouse',  
        sticky : true,
        mouseOutClose : true,
        arrows: true,
        ajaxSettings : {
            type : "GET",
            ajaxCache: false
        }
    });

    $(".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'
    });

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

function item_disp(reqtype,id,catid,selstmtid,divid,requrl,newwin){
    justslider = 0;
    tmp_requrl = ''
    tmp_newwin = ''
    if(requrl){
      tmp_requrl = requrl;
    }
    if(newwin){
      tmp_newwin = newwin;
    }
    /* 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;
    }
    switch(reqtype){
        case 'article':
        case 'selarticle':
        case 'selfinlib':
        case 'finlib':
        case 'faq':
        case 'glossary':

        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;
                }
                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;
                              }
                          }
                      }
                  }

                },
                 error: function(data){
                    alert("We're Sorry, you're request could not be processed.");
                }
            });
        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;
    }
}
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":
            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){
                      list_of_items = '';
                        for(idx=0;idx<the_element.options.length;idx++){
                            if(the_element.options[idx].selected == true){
                                if(list_of_items != ''){
                                    list_of_items += ',' + the_element.options[idx].value;
                                } else {
                                    list_of_items += the_element.options[idx].value;
                                }
                            }
                        }
                        param_array.push(encodenamevalue(the_element.name,list_of_items));
                    }
                    break;
                    default:
                        param_array.push(encodenamevalue(the_element.name,the_element.value));
                        break;
                }
        }
    }
    return param_array.join("&");
}
function encodenamevalue(pname,pvalue){
    var wrk_param = encodeURIComponent(pname);
    wrk_param += "=";
    wrk_param += encodeURIComponent(pvalue);
    return wrk_param;
}
// 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 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;

}

