// 
//
// These are utility methods that can be used by other javascript
// methods as required. They are generally simple date parsing, number
// manipulating methods

// Ayinde Yakubu, September, 2003
// Copyright (c) 2003, Unisen Inc
//

//Define some global variables
var MAP_SIZE = 7;
var debugOn = false;
// 
var gPeriods = new Array(MAP_SIZE);
var gPeriodValue = new Array(MAP_SIZE);
var helpWindow;

//TODO. Will this call the method on startup??
initMap();

//This method contains a percentage to ordinary number
function percent(value)
{
   var tempvalue =  value / 100.0;
   displayMessage ( "value: " + value + " result " + tempvalue);
   return tempvalue;
}

//-- varify that input is valid
function verifyInput(fieldName)
{
  // 
  // 
  //
}
// -- Converts str into ordinal numbers e.g. 11.24% to 0.1124
// 
function preparePercent(str)
{ 
    //alert(str);
    var val = str;
    if ( isNaN(str) )
    { 
       val = extractLastSign(str, "%");
    }
    result = percent(val);
    return result;
}

// -
//Utility Methods
function isEmpty(field)
{
  return ( (field.value==null || field.value=="" ) ? true : false);
}
// -- Convert string that may contain dollar sign and commas into 
// number e.g. $82,999.92 is converted to 82999.92. The string
//can contain any number of commas and $ sign 
//
function prepareNumber(str)
{
   if ( isNaN(str) == false )
   {
       return    str.valueOf();
   }
   
   var regex = /^\$|([0-9]+\,)\.[0-9]*/;

   var tempStr = str;
   if ( str.lastIndexOf("$") != -1 ) 
   {
       tempArray1 = str.split("$");
	   tempStr = tempArray1.join("");
   }
   var tempStr2 = tempStr;
   if ( tempStr.lastIndexOf(",") != - 1 )
   {
       tempArray2  = tempStr.split(",");
       tempStr2 = tempArray2.join("");
   }
   
   //alert(tempStr2);
      
   var val = parseFloat(tempStr2.valueOf());
   //alert(val);
   
   return val;
}

// -- String formatting routines
// - Take 12122.34639 and return $12,122.35
// -- 
function convertToMoney(amount, decplace)
{
  var _dollars=parseInt(amount);
  var _cents=parseInt((amount - _dollars)*100);
  var _negative = _dollars <0;
  if(_negative)
  {  _dollars = -_dollars;
     _cents=-_cents;
  }
  
  while(_cents.toString().length < 2)
     _cents="0"+_cents;
  
  var _dA=_dollars.toString().split("");
  var _d="";
  for(var i=_dA.length-1;i>=0;i--)
  {
    var _comma="";
	if((_dA.length-i)%3==0 && i!=0)_comma=",";
    _d=_comma+_dA[i]+_d;
  }
  var _neg_sign=_negative?"-":"";
  var _result=""+_neg_sign+_d+"."+_cents;
  return _result;
}

// -- Format numbers to given decimal places
function formatNumber(number, decpoints)
{
   var str = new String(number);
   var values = str.split(".");
   var val ="";
   if ( values.length == 2 )
   {
      var decimalPart =  values[1].substr(0, decpoints);
      val = values[0] + "." + decimalPart;
   }
   else
   {
       val = str;
   }
   
//   alert (" Number->" + number + " val-> " + val);
   
   return val;

}

// truncate a number to some specified digits after the decimal
function truncateNumber(value, dec)
{
   var decPlace = parseInt(dec);
   var str = value.toString();
   var result = str;
   var pos = str.indexOf(".");
   if ( pos != - 1 ) {
      var parts = str.split(".");
      var tempStr =  parts[1].substr(0, decPlace);
      result = parts[0] + "." + tempStr;
   }   	  
   
   return result;
}
//Extracts % sign from the rate input
function extractLastSign(aItem, aSign)
{
   var result="";
   //alert ( aItem );
   if ( aItem != null && aSign != null )
   {
       pos=aItem.lastIndexOf(aSign);
	   if (pos != - 1 )
	   {
	      result=aItem.substr(0,pos);
	   }
	   else
	   {
	      result=aItem;
	   }
   }
   //alert(result);
   return result;
}

//Display a simple alert or message box
function displayMessage(value)
{
   if ( debugOn == true )
   {
       //alert (value);
   }
   else 
   { 
     // document.write("<em>" + value + "</em>");
   }
}


// --
// This function ensures that only valid numbers are entered in the field.
// Valid numbers are 0-9, . - and , A regular expression is the best way
// to parse this field
// 
function validateNumber(str, min, max)
{
   
   var temp = str.replace("$",'');
   var temp2 = temp.replace(",",'');
   var val = parseFloat(temp2);
   var minval = parseFloat(min);
   var maxval = parseFloat(max);

   //alert (val)
   if ( isNaN(val) )
   {
      alert("Entry must be a number.");
      return false;
   }
   else
   {
	   if ( minval == null && maxval == null )
	   {
 	      return true;
 	   }
 	   
 	   if( isNaN(minval) == false )
 	   {
 	       if ( isNaN(maxval) == false )
 	       {
 	          if ( val >= minval && val <= maxval )
 	          {
 	             return true;
 	          }
		      else
	          {
	         	  //alert("Value must be equal to or less than: " + maxval);
		          return false;
		      }   
		    }
		    if ( val < minval )
		    {
		     	  //alert("Value must be greater than or equal to : " + minval);
		          return false;
		    }
		    return true; 
	   }

       return true;
   }
}





///
// Ensure that the number of years to retirment is less than 100 
//
//
function checkYearsToRetirement(myForm)
{
     var str = myForm.yearsToRetire.value;
     if ( validateNumber(str,0,80) == true )
     {
        return true;
     }
     else
     {
        alert("The number of years before retirement cannot be more than 80.");
	    myForm.yearsToRetire.value = "80.0";
	    myForm.yearsToRetire.focus();
	    return false;
     }
 }
 
 //-- Check the number of years funds should last for
 function checkYearsFundToLast(myForm)
 {
     var str = myForm.txtYearsFundToLast.value;
     if ( validateNumber(str, 0, 50) == true )
     {
        return true;
     }
     else
     {
        alert("Funds cannot last more than 50 years.");
	    myForm.txtYearsFundToLast.value = "50.0";
	    myForm.txtYearsFundToLast.focus();
	    return false;
     }
 
 }
///
// Ensure that the inflation rate cannot be more than 50%
//
//
function checkInflationRate(myForm)
{
     var str = myForm.inflationRate.value;
     if ( validateNumber(str, 0, 50) == true )
     {
         return true;
     }
     else
     {
	    alert("Inflation rate cannot be greater than 50% ");
	    myForm.inflationRate.value = "50.0";
	    myForm.inflationRate.focus();
	    return false;
     }
 }
          
// -- This method initializes all the periods used within the calculators
function initMap()
{
	//TODO - Ensure that these arrays never passed the MAP_SIZE
	gPeriods[0] = "annual";       gPeriodValue[0] = 1.0;
	gPeriods[1] = "semi-annual";  gPeriodValue[1] = 2.0;
	gPeriods[2] = "quarterly";    gPeriodValue[2] = 4.0;
	gPeriods[3] = "monthly";      gPeriodValue[3] = 12.0;
	gPeriods[4] = "bi-monthly";   gPeriodValue[4] = 24.0;
	gPeriods[5] = "bi-weekly";    gPeriodValue[5] = 26.0;
    gPeriods[6] = "weekly";       gPeriodValue[6] = 52.0;
}

//-- 
// Build a list of all contribution/income frequencies
//--
function buildPeriodList()
{
  var descriptions ="";
  for ( i = 0; i < MAP_SIZE; i++)
  { 
     descriptions =  descriptions + "<option>" + gPeriods[i] + "<br>";
  }
  return descriptions;
}

// -- Find the period description given an index
//
function getPeriodDesc(val)
{
    var indx = 0.0;
    var tmpval = 0.0;
    for ( i = 0; i < MAP_SIZE; i++ )
    {
        tmpval =  gPeriodValue[i];
        if ( tmpval == val )
        {
          indx = i;
          break;
        }
    }
    return gPeriods[indx];  
}

// -- Parse dates
// The date must be of the format 01-01-2003 or 01/01/2003 --dd-mm-year
// Use a a regular expression

function stringToDate(str)
{
	 var regexp = /(^[0-3][0-9])(\/|\.|\-)([0-1][0-9])(\/|\.|\-)([1-3][0-9]{3}$)/;

	 if ( regexp.test(str) == true ) 
	 {
	    
	     //alert("Valid date");
	     var result = str.match(regexp);
	     if ( result != null )
	     {
	        //alert (result[0]);
	        var daystr = result[1];
	        //alert (result[2]);
	        var monthstr = result[3];
	        //alert(result[4]);	        	        
   	        var yearstr = result[5];	        	        
	        //alert (result[6]);	        	        
	
			var day = parseFloat(daystr);
			var mth = parseFloat(monthstr) - 1;
			var year = parseFloat(yearstr);
			if ( day == 0 || mth == -1 || year == 0 || day > 31 || mth >= 12 )
			{
			    alert("Invalid date entry.");
			    return false;
			}

			var rs = new Date(year, mth, day,0,0,0,0);
			//alert(day + ":" + rs.getDate())
			//alert(mth + ":" + rs.getMonth())
		    //alert(year + ":" + rs.getFullYear())
			if ( day != rs.getDate() || mth != rs.getMonth()  || year!= rs.getFullYear())
		    {
		        alert("Invalid date entry.");
			    return false;
			}
			return (rs);
	     }
	 }

     alert("Invalid date entry.");
     return false;
}


// -- 
// Checks if this is a leap year
//
function isLeap(currentDate)
{
   var year = currentDate.getFullYear();
   return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) ? true : false;
}

// ---
// Get number of days from year
// ---
function getNumberOfDaysInYear(currentDate)
{
    if (isLeap(currentDate)) 
    {
      return 366;
    }
    else
    {
      return 365;
    }
}

// ---
// Days left in a year
// ---
function daysLeftInYear(aCurrentDate)
{
  // Store the current date and time
  var current_date = aCurrentDate;

  // Store the date of the next New Year's Day
  var new_years_date = new Date();

  new_years_date.setYear(current_date.getFullYear() + 1);
  new_years_date.setMonth(0);
  new_years_date.setDate(1);
  new_years_date.setHours(0,0,0,0);

  // Call the days_between function
  //alert ("start date: " + current_date);
  //alert ("end date:" + new_years_date);
  var days_left = daysBetween(current_date, new_years_date);
  return (days_left);
}

//--
// Identify selections in a radio button
// --
function identifyRadioSelection(radioGroup)
{
   var result = "no";
   var pos = 0;
   for (var i = 0; i < radioGroup.length; i++){
    if (radioGroup[i].checked == true ){
        pos = i;
        break;
     }
   }
   if ( pos == 0 ) {  
       result = "yes";
   }
   return result;
}

// ---
//  This method find the days between any two set of dates.
// ---
function daysBetween(oDate_1, oDate_2) 
{
    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24
    iTime_1 = oDate_1.getTime();
    iTime_2 = oDate_2.getTime();
     
    iDiff = Math.abs( iTime_1 - iTime_2 );

    return( Math.round( iDiff / ONE_DAY ) ); // 1000ms * 60secs * 60mins * 24hours = 1 day)
}



//--
// Validate all the fields in a form
//
function validateForm(myForm)
{

  //Get all elements in this form
  var field = "";
  for ( var i = 0; i < myForm.length; i++)
  {
     field = myForm.elements[i];
     if ( field.name == "paymentFreqOptions" )
     {
         break;
     }
     if ( typeof (field) == "string" )
     {
	 if ( field.value == null || field.value =="")
	 { 
	    alert(field.name + " entry is invalid ");
	    return false;
	 }
     }
     else
     {
         if ( field.value == null || field.value =="")
         {
             alert(field.name + " entry is invalid ");
             return false;
         }
     }
  }
  return true;
}
//---
// Reset all the fields of a form
// --
//--
//
function resetForm(myForm)
{
  myForm.reset();
  return ;
}
// --
// Ensure the ROR  value is always below a particular range
// 
function checkRORMax(myForm)
{
    var str = myForm.txtROR.value;
    
    if ( validateNumber(str,0,20) == true )
    {
      return true;
   }
   else
   {
       alert("Expected rate of return cannot be greater than 20% ");
       myForm.txtROR.value = "20.0";
       myForm.txtROR.focus();
       return false;
   }
}

// Ensure that age can never be more than 100
// 
function checkAgeMax(myForm)
{
    var str = myForm.txtToAge.value;
    if ( validateNumber(str,0,100) == true )
    {
      return true;
    }
    else
    {
          alert("The ToAge cannot be more than 100.");
          myForm.txtToAge.value = "100";
          myForm.txtToAge.focus();
          return false;
    }
}

// ---
// Calculates age given a starting date and an end date
// ---
function calculateAge(startDate, endDate)
{
   var s = startDate;
   var e = endDate;
   var   mon, day, year, DD, MM, YY, age;
  
   if ( endDate < startDate )
   {
      return alert("End date cannot be earlier than start date ");
   }
   YY   = s.getFullYear();	// year of birth (4 digits)
   MM   = s.getMonth() + 1;	// month of birth (1-12)
   DD   = s.getDate();	// date of birth (1-31)

   year = e.getFullYear();	// get year of current
   mon  = e.getMonth() + 1;	// get month of current
   day  = e.getDate();	// get date of current

   age = year - YY;
  
   //Handle round offs
   if ((MM > mon) || (MM == mon && day < DD)) age --;

   return age;
}



// -- 
// retrieve selected item 
//
function makePaymentChoice(myForm, result)
{
   initMap();
   var myIndex  = myForm.paymentFreqOptions.selectedIndex;
   var selValue = gPeriodValue[myIndex];
   //alert(selValue);
   //result=selValue;
   myForm.paymentFreq.value = selValue;
   return selValue;

}


//--
// Show the help  page as a window
// --
function showHelp(helpName)
{ 
   helpWindow = window.open("rrsp_help.html","Help_Window","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=yes, width=600, height=400")

//window.open("http://www.w3schools.com","my_new_window","toolbar=yes, location=yes, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=no, copyhistory=yes, width=400, height=400")
}


//--
// Print the report 
//--
function printReport()
{
   window.print();
}

//---
// Begin the html form
//---
function beginHtml(str)
{
  writeDocumentHead();
  writeHtmlStart();
  writeHeadStart();
  writeTitleStart();
  //document.write(str);
  writeTitleEnd();
  writeStyleLink();
  //writeHttpEquiv();
  includeScripts();
  writeHeadEnd();
}

function writeDocumentHead()
{
   //document.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
}
function writeHtmlStart()
{
   document.write("<html>");
}

function writeHeadStart()
{
   document.writeln("<head>");
}

function writeTitleStart()
{
  document.write("<title>");
}

function writeStyleLink()
{
  document.write("<LINK HREF='/t2scr/static/css/agfstyle_default_11px.css' MEDIA='screen' REL='stylesheet' TITLE='AGF_Small_Text' TYPE='text/css'/>");
  document.write("<LINK HREF='/t2scr/static/css/agfstyle_default_11px.css' MEDIA='screen' REL='alternate stylesheet' TITLE='AGF_Small_Text' TYPE='text/css'/>");
  document.write("<LINK HREF='/t2scr/static/css/agfstyle_default_14px.css' MEDIA='screen' REL='alternate stylesheet' TITLE='AGF_Large_Text' TYPE='text/css'/>");
  document.write("<LINK HREF='/t2scr/static/css/agfstyle_default_18px.css' MEDIA='screen' REL='alternate stylesheet' TITLE='AGF_Larger_Text' TYPE='text/css'/>");
}

function writeHttpEquiv()
{
  document.write("<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>");
}    


function writeHeadEnd()
{
   document.write("</head>");
}

function writeTitleEnd()
{
  document.write("</title>");
}

//
// Include javascripts
//
function includeScripts()
{
  document.write("<script language=\"JavaScript\" src=\"rsp_utility.js\"      type=\"text/javascript\"></script>");
  document.write("<script language=\"JavaScript\" src=\"rspengine.js\" type=\"text/javascript\"></script>");
  document.write("<script language=\"JavaScript\" src=\"rrspresult.js\"      type=\"text/javascript\"></script>");
}
//--
// End html form
//
function endHtml()
{
   document.write("</html>");
}



function writeLinks(title, link)
{

 // alert("<a href= \"" + link + "\">" + title + "</a>");
  document.write("<a href=\"" + link +"\">" + title +"</a>");
  
  
}

// ---
// These are HTML generation statements
// ---



//Print a new line for the specified number of times
function newLine(times)
{

   var loopEnd = 0.0;
   var val = parseInt(times);
   // alert (val);
   if ( isNaN(val) == true )
   {
       loopEnd = 1.0;
   }
   
   for ( i = 0 ; i < loopEnd; i++ )
   {
          document.write("<br>");
   }
}

function beginBody()
{
   document.write("<body>");
}
function endBody()
{
   document.write("</body>");
}
//-- 
// End the table tag
//-- 
function endTable()
{
   document.write("</table>");
}

function beginRow()
{
  document.write("<tr>");
}

function show(str)
{
	document.write(str);
}

function endRow()
{
  document.write("</tr>");
}

function beginHeaderRowData()
{
  document.write("<td align='right' class='reportheader'>");
}

function endHeaderRowData()
{
  document.write("</td>");
}

function beginRowData()
{
  document.write("<td align='left' bgcolor='#ffffff'>");
}

function endRowData()
{
  document.write("</td>");
}


// --
// Format the HTML table containing results
// --
function beginTable(stitle)
{
   document.write("<table width='100%' cellpadding='1' cellspacing='1' border='0'>");
   //document.write("<td colspan='2' BGCOLOR='#E6E5E5'><DIV CLASS='headpad-gray'><strong>");
   //document.write(stitle);  
   //document.write("</strong></div></td>");
}


// -- Close a window
function closeIt()
{
  helpWindow.close();
}

// ---
// 
// ---
function makeParams(arry)
{
   var str = arry.join("Z");   
   return str; 
}


function extractParams(str)
{
   var valArray = str.split("Z");   
   return valArray;
}
//-- 
// Ensure that only numbers are accepted as entry
// 
function acceptNumbers(event)
{
	//Define standard keys
	var KEY_SPACE       = 32;
	var KEY_COMMA       = 44;
	var KEY_MINUS       = 45;
	var KEY_DOT         = 46;
	var KEY_FRONT_SLASH = 47;
	var KEY_ZERO        = 48;
	var KEY_ONE         = 49;
	var KEY_NINE        = 57;
	var KEY_RETURN      = 13;
	var KEY_LINEFEED    = 10;
	//var KEY_TAB         = 0;
	var KEY_TAB			= 9;
	var KEY_BACKSPACE	= 8;
	var KEY_DELETE		= 46;
	var KEY_LEFT_ARROW	= 37;
	var KEY_RIGHT_ARROW	= 39;
	var KEY_DELETE_MAC	= 8;
	var KEY_LEFT_ARROW_MAC	= 63234;
	var KEY_RIGHT_ARROW_MAC	= 63235;
		
	var message = "Only numeric entries accepted";

	var browser = detectBrowser();
	
	var keyval = 0;
	var keyCode1 = 0;
		
	if ( browser == "Explorer")
	{
  	 keyval = event.keyCode;
  	 //alert(keyval);
	 
	 if ( keyval == KEY_RETURN || keyval == KEY_LINEFEED)
	 {
	     event.returnValue = true;
	     return true;
	 }
	 
	 if((keyval <= KEY_MINUS || keyval > KEY_NINE ) || (keyval == KEY_FRONT_SLASH))
	 {
	     event.returnValue = false;
	     alert(message);
	 }	 
	 
	}
	else if ( browser == "Firefox" )
	{
	 keyval = event.which;
	 keyCode1 = event.keyCode;	 
 	 //alert ("Key Pressed: " + keyval);
 	 if ( keyval == KEY_RETURN || keyval == KEY_LINEFEED || keyval == KEY_BACKSPACE 
	 || keyCode1 == KEY_TAB || keyCode1 == KEY_DELETE 
	 || keyCode1 == KEY_LEFT_ARROW || keyCode1 == KEY_RIGHT_ARROW)
	 {
	     return true;
	 }

	  if((keyval <= KEY_MINUS || keyval > KEY_NINE ) || (keyval == KEY_FRONT_SLASH))	  
	  {
	     alert(message);
	     return false;
	  }
	  	  
	}
	else if (browser == "Safari")
	{
		if (browserType.indexOf("Mac") != -1)
		{
			keyval = event.which;
	 		keyCode1 = event.keyCode;
	 		
	 		if ( keyval == KEY_RETURN || keyval == KEY_LINEFEED  
			 || keyval == KEY_TAB || keyCode1 == KEY_DELETE_MAC 
			 || keyCode1 == KEY_LEFT_ARROW_MAC || keyCode1 == KEY_RIGHT_ARROW_MAC)
			 {
			     return true;
			 }

			if((keyval <= KEY_MINUS || keyval > KEY_NINE ) || (keyval == KEY_FRONT_SLASH))
			{
			     alert(message);
			     return false;
			}
	 		
		}
		else //Windows
		{
		  	 keyval = event.keyCode;  	 

			 if ( keyval == KEY_RETURN || keyval == KEY_LINEFEED)
			 {
			     event.returnValue = true;
			     return true;
			 }
	
			 if((keyval <= KEY_MINUS || keyval > KEY_NINE ) || (keyval == KEY_FRONT_SLASH))
			 {
			     event.returnValue = false;
			     alert(message);
			 }
		}
	
	}
	
	return true;

}

function detectBrowser()
{
	var browserType = navigator.userAgent.toLowerCase();
	var browser = "";
		
	if(browserType != null ){
		if((browserType.indexOf("msie") != -1)){
			browser = "Explorer";			
		}
		if ((browserType.indexOf("mozilla") != -1) && (browserType.indexOf("spoofer")
	== -1) && (browserType.indexOf("compatible") == -1)) {
			if (browserType.indexOf("firefox") != -1) {
				browser = "Firefox";				
			}
			else if (browserType.indexOf("netscape") != -1) {
				browser = "Netscape";				
			} else {
				browser = "Mozilla";				
			}
		}		
		if (browserType.indexOf("safari") != -1) {
			browser = "Safari";
		}		
	}
	
	return browser;
	
}

