// 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 wleft = 0;
var wtop = 0;
var popwidth = 0;
var popheight = 0;

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,closeonclick) {
    findcenter();
    modwidth = 450;
    modheight = 450;
    if(wdth){
        modwidth = wdth;
    }
    if(hght){
        modheight = hght;
    }
    if(!closeonclick){
        closeonclick = false;
    }

    var myWidth = 0, myHeight = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
      //Non-IE
      myWidth = window.innerWidth;
      myHeight = window.innerHeight - parseInt(60);
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
      //IE 6+ in 'standards compliant mode'
      myWidth = document.documentElement.clientWidth;
      myHeight = document.documentElement.clientHeight - parseInt(60);
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
      //IE 4 compatible
      myWidth = document.body.clientWidth;
      myHeight = document.body.clientHeight - parseInt(60);
    }

    if(modheight > myHeight){
       modheight = myHeight;
    }

     m = new Control.Modal($(passid),{
         iframe: true,
         opacity: 0.6,
         position: 'absolute',
         offsetTop: wtop,
         offsetLeft: wleft,
         width: modwidth,
         height: modheight,
         overlayCloseOnClick: closeonclick
         });
     m.open();
}

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 edu_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
       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':
      case 'faq':
        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=" + 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 SpeedBump(url,newwin,prefix) {
    if (typeof prefix == 'undefined' ) {
        url = 'http://' + location.hostname + '/speedbump.php?nw=' + newwin + '&url=' + url;
    } else {
        url = url;
    }
     m = new Control.Modal('',{
         iframe: true,
         opacity: 0.6,
         gotohref: url,
         position: 'absolute',
         width: 450,
         height: 450,
         overlayCloseOnClick: true
         });
     m.open();
}


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

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



