// error array
var WrkInput = '';
var WrkMonth = '';
var WrkDay = '';
var WrkYear = '';
var num_of_submits = 0;

// slider variables
var timerlen = 5;
var slideAniLen = 500;

var timerID = new Array();
var startTime = new Array();
var obj = new Array();
var endHeight = new Array();
var moving = new Array();
var dir = new Array();

var err_num = '';
var errorArray = new Array(15);
errorArray[0] = 'no errors detected.';
errorArray[1] = 'does not appear to be valid.';
errorArray[2] = 'does not appear to be a valid date.';
errorArray[3] = 'does not appear to be a valid email address.';
errorArray[4] = 'contains illegal characters.';
errorArray[5] = 'contains illegal characters. Only letters, numbers, hyphens and underscores are allowed.';
errorArray[6] = 'contains illegal characters. Only letters, numbers, spaces, hyphens, underscores and apostrophes are allowed.';
errorArray[7] = '';
errorArray[8] = '';
errorArray[9] = '';
errorArray[10] = 'must not be less than 6 or more than 12 characters.';
errorArray[11] = 'must contain at least one lower case letter, one upper case letter and one number';
errorArray[12] = 'must be numeric.';
errorArray[13] = 'is required';
errorArray[14] = '';
errorArray[15] = '';


function targetModal(passid,wdth,hght) {
    modwidth = 450;
    modheight = 450;
    if(wdth){
        modwidth = wdth;
    }
    if(hght){
        modheight = hght;
    }
     m = new Control.Modal($(passid),{
         iframe: true,
         opacity: 0.6,
         position: 'absolute',
         width: modwidth,
         height: modheight,
         overlayCloseOnClick: false
         });
     m.open();
}

// education topic display
function edu_topic(catid,id) {
	newurl = "/edu_discussion_topics.php?cat=" + catid + "&id=" + id;
	eduwin = window.open(newurl,target="EDUWind", "toolbar=no,location=no,directories=no,scrollbars=yes,resizable=yes,width=780,height=400");
	//if (window.focus) {
	//	EDUWind.focus();
	//}
}

function newaction(url,fc) {
	if(document.getElementById("fin_lib")){
		if(document.getElementById("fin_lib").selectedIndex < 1 || document.getElementById("fin_lib").options[document.getElementById("fin_lib").selectedIndex].value == ''){
			alert("Please select another Discussion Topic.");
			return;
		}
		
		newUrl = url + "&fc=" + fc + "&fid=" + document.getElementById("fin_lib").options[document.getElementById("fin_lib").selectedIndex].value;
		document.eduform.action = newUrl;
		document.eduform.submit();
	}
}

function fin_edu(url) {
	indiv_art='no';
	urlquery=url.split("?");
	if(urlquery[1]){
		urlterms=urlquery[1].split("&");

		if(urlterms.length){
			for(i=0;i < urlterms.length;i++){
				valuepairs = urlterms[i];
				if(valuepairs.indexOf('aid',0) != -1){
					indiv_art='yes';
				}
			}
		}
	}

   newurl = url;
	
	if(indiv_art=='no'){
		if(document.getElementById("fin_article")){
			if(document.getElementById("fin_article").selectedIndex < 1 || document.getElementById("fin_article").options[document.getElementById("fin_article").selectedIndex].value == ''){
				alert("Please select another Article.");
				return;
			} else {
				newurl = url + "&aid=" + document.getElementById("fin_article").options[document.getElementById("fin_article").selectedIndex].value;
			}
		}
	}
	eduwin = window.open(newurl,target="artwin", "toolbar=no,location=no,directories=no,scrollbars=yes,resizable=yes,width=780,height=400");
    //document.location = newurl;
}

function edu_disp(reqtype,id,catid,selstmtid){
alert('edu_disp('+reqtype+','+id+','+catid+','+selstmtid+')');
    /* 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
       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)
    */
    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;
        pass_reqtype = 'article';
        break;
      case 'selfindisc':
        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;
        pass_reqtype = 'findisc';
        break;
      case 'article':
        pass_reqtype = 'article';
        break;
      case 'findisc':
        pass_reqtype = 'findisc';
        break;
      default:
        return;
        break;
    }
    if(isNaN(id) || isNaN(catid)){
        return;
    }

    var oXHR = zXmlHttp.createRequest();
    oXHR.open("get", "../php/process/ajax_art.php?id=" + id + "&catid=" + catid + "&rt=" + pass_reqtype, false);
    oXHR.send(null);

    if(oXHR.status == 200){
        response_area=oXHR.responseText;
        if(response_area.substr(0,6) == 'Please'){  // invalid topic selection
            alert(response_area);
            return;
        }

        switch(reqtype){
            case 'selarticle':
              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 'email':
                                tmpid = selstmtid + '_email_art';
                                document.getElementById(tmpid).href = itemarray[1];
                                break;
                              case 'prt':
                                tmpid = selstmtid + '_prt_art';
                                document.getElementById(tmpid).href = itemarray[1];
                                break;
                              case 'title':
                                tmpid = selstmtid + '_art_title';
                                document.getElementById(tmpid).innerHTML = itemarray[1];
                                break;
                              case 'subtitle':
                                tmpid = selstmtid + '_art_subtitle';
                                document.getElementById(tmpid).innerHTML = itemarray[1];
                                break;
                              case 'copy':
                                tmpid = selstmtid + '_art_copy';
                                document.getElementById(tmpid).innerHTML = 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 'selfindisc':

                break;
        }
    } else {
        alert(oXHR.responseText);
    }
}
function item_disp(reqtype,id,catid,selstmtid,divid){
    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);
    */
    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':
        break;
      default:
        return;
        break;
    }
    if(isNaN(id) || isNaN(catid)){
        return;
    }

    var oXHR = zXmlHttp.createRequest();
    oXHR.open("get", "../php/process/ajax_inserts.php?id=" + id + "&catid=" + catid + "&rt=" + reqtype + "&divid=" + divid, false);
    oXHR.send(null);

    if(oXHR.status == 200){
        response_area=oXHR.responseText;
        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':
              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':
                                tmpid = divid;
                                document.getElementById(tmpid).innerHTML = 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;
                          }
                      }
                  }
              }
              if(reqtype == 'article' || reqtype == 'finlib' || reqtype == 'faq'){
                slider(divid);
              }
              break;
        }
    } else {
        alert(oXHR.responseText);
    }
}

function fin_art(topicid,artid){
    if(isAllSpaces(artid)){
        selObj = document.getElementById("fin_article");
        if(selObj.selectedIndex < 1){
            alert("Please select another Article.");
            return;
        }
        artid = selObj.options[selObj.selectedIndex].value;
    }
    var oXHR = zXmlHttp.createRequest();
    oXHR.open("get", "../php/process/ajax_art.php?topicid=" + topicid + "&artid=" + artid, false);
    oXHR.send(null);

    if(oXHR.status == 200){
        response_area=oXHR.responseText;
        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 'email':
                          document.getElementById("email_art").href = itemarray[1];
                          break;
                        case 'prt':
                          document.getElementById("prt_art").href = itemarray[1];
                          break;
                        case 'title':
                          document.getElementById("art_title").innerHTML = itemarray[1];
                          break;
                        case 'subtitle':
                          document.getElementById("art_subtitle").innerHTML = itemarray[1];
                          break;
                        case 'copy':
                          document.getElementById("art_copy").innerHTML = 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;
                    }
                }
            }
        }
    } else {
        alert(oXHR.responseText);
    }
}


// function to open the calculator window
function calcWin(calc) {
	calcurl = "/calculators/" + calc;
	WinId = window.open(calc,target="calcWind", "toolbar=no,location=no,directories=no,scrollbars=yes,resizable=yes,width=780,height=400");
}

// function to validate email a friend form
function valemailform(email_form) {
	calcurl = "/calculators/" + calc;
	WinId = window.open(calc,target="calcWind", "toolbar=no,location=no,directories=no,scrollbars=yes,resizable=yes,width=780,height=400");
}

function alertError(disp_text){
	if(isNumeric(err_num) ){
		if(err_num == 0 || err_num > errorArray.length){
		return;
		}
	}
	alert(disp_text + " " + errorArray[err_num]);
	return;
}

// sanitize input
function isPassword(string){
	err_num = 0;
	var illegalChars = /[^\.\!\*a-zA-Z0-9_-]/; // allow only letters, numbers, underscores,periods and hyphens 
	if(illegalChars.test(string)){ // illegal characters found
		err_num = 4;
		return false;
	}
	if ((string.length < 6) || (string.length > 12)) {
		err_num = 10;
      return false;
   }
  return true;
}

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 isZip(string){
	var regex = /^\d{5}([\-]\d{4})?$/; // 5 digits followed by the optional - and 4 digits
	if(regex.test(string)){
		return true;
	} else {
		err_num = 1;
		return false;
	}
}
function isPhone(string){
	var regex = /^(?:\+\d)*\s*(?:\(*\d{3}\)*)*\s*\d{3}\-\d{4}$/; // in the format of (999) 999-9999 with (999) being optional
	if(regex.test(string)){
		return true;
	} else {
		err_num = 1;
		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;
	}
	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;
  }
}


function goback() {
    history.go(-1);
}

function SpeedBump(url,newwin) {
    br = String.fromCharCode(10);
    if (newwin == 1) {
        winmsg = "(The new website will open in a new window.)";
    } else {
        winmsg = "";
    }

    // Choose one and delete the unwanted version of the message:

    // long version:
    dmsg =  "The website you are about to visit is solely the responsibility of the merchant " +
            "or other party providing the site. The content of this third-party site, including " +
            "materials and information, is solely the responsibility of the provider of the site. " +
            "We are not responsible for any such third-party content. " +
            "Any transactions that you enter into with a vendor, merchant or other party that you " +
            "access through this third-party site are solely between you and that vendor, " +
            "merchant or other party. We do not endorse the content contained in this third-party site, " +
            "nor the organization publishing the site, and hereby disclaims any responsibility for such content. " +
            "Our Privacy Policy does not apply to this third-party site, and for further information you should " +
            "consult the privacy disclosures of the third-party site. " +
            br + br +
            "You are now leaving the site.  Click \"OK\" to leave, \"Cancel\" to stay." + br +
            winmsg + br;

    // short version:
    dmsg =  "The link you have just clicked is taking you to a different website. " + br +
            "The content of this third-party site, including " +
            "materials and information, is solely the responsibility of the provider of the site. " +
            br +
            "Our Privacy Policy does not apply to this third-party site, and for further information you should " +
            "consult the privacy disclosures of the third-party site. " +
            br + br +
            "You are now leaving the site.  Click \"OK\" to leave, \"Cancel\" to stay." + br +
            winmsg + br;



		response = confirm(dmsg);
		if(response){
            if (newwin == 0) {
                document.location = url;
            } else {
                this.open(url,"NewExternalWin","toolbar=yes,menubar=yes,location=yes,scrollbars=yes,resizable=yes");
            }
		}
}

// 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 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 findcenter(){
    wleft = (screen.width - popwidth) / 2;
    wtop = (screen.height - popheight) / 2;
    if (wleft < 0) {
        popwidth = screen.width;
        wleft = 0;
    }
    if (wtop < 0) {
        popheight = screen.height;
        wtop = 0;
    }

}
function openradiv(divid){
    divtoopen = eval('document.getElementById("' + divid + '");');
    if(divtoopen){
        command = eval('document.getElementById("' + divid + '").style.visibility;');
        if(command == 'hidden'){
            eval('document.getElementById("' + divid + '").style.display = \'block\';');
            eval('document.getElementById("' + divid + '").style.visibility = \'visible\';');
        } else {
            eval('document.getElementById("' + divid + '").style.display = \'none\';');
            eval('document.getElementById("' + divid + '").style.visibility = \'hidden\';');
        }
    }
}

function slider(objname){
  if(moving[objname]){
    return;
  }
//popUpProperties(document.getElementById(objname));
  if(document.getElementById(objname).style.display != "none"){
    moving[objname] = true;
    dir[objname] = "up";
    startslide(objname);
  } else {
    moving[objname] = true;
    dir[objname] = "down";
    startslide(objname);
  }
}

function startslide(objname){
  obj[objname] = document.getElementById(objname);

  if(dir[objname] =="down"){
    obj[objname].style.height = "1px";
  }

  obj[objname].style.display = "block";
  startTime[objname] = (new Date()).getTime();
  endHeight[objname] = obj[objname].scrollHeight;
  // endHeight[objname] = parseInt(obj[objname].style.height);
  timerID[objname] = setInterval('slidetick(\'' + objname + '\');',timerlen);

}

function slidetick(objname){
  var elapsed = (new Date()).getTime() - startTime[objname];

  if (elapsed > slideAniLen)
    endSlide(objname)
  else {
    var d =Math.round(elapsed / slideAniLen * endHeight[objname]);
    if(dir[objname] == "up")
      d = endHeight[objname] - d;

    obj[objname].style.height = d + "px";
  }

  return;
}

function endSlide(objname){
  clearInterval(timerID[objname]);

  if(dir[objname] == "up")
    obj[objname].style.display = "none";

  obj[objname].style.height = endHeight[objname] + "px";

  delete(moving[objname]);
  delete(timerID[objname]);
  delete(startTime[objname]);
  delete(endHeight[objname]);
  delete(obj[objname]);
  delete(dir[objname]);

  return;
}

function popUpProperties(inobj) {
	op = window.open();
	op.document.open('text/plain');
	for (objprop in inobj) {
	op.document.write(objprop + ' => ' + inobj[objprop] + '\n');
	}
	op.document.close();
}