
function createCookie(name,value,days) {
        if (days) {
                var date = new Date();
                date.setTime(date.getTime()+(days*24*60*60*1000));
                var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
}

function eraseCookie(name) {
        createCookie(name,"",-1);
}

function creditcard(mDesc, mDebt, mRate, mIntrorate, mIntromonth, mIntroyear, mOffermonths, mPaytype, mMinpay, mOverpay, mMonrate, mMonintrorate) {
        this.mdesc = mDesc;
        this.mdebt = mDebt;
        this.mrate = mRate;
        this.mintrorate = mIntrorate;
        this.mintromonth = mIntromonth;
        this.mintroyear = mIntroyear;
        this.moffermonths = mOffermonths;
        this.mpaytype = mPaytype;
        this.mminpay = mMinpay;
        this.moverpay = mOverpay;
        this.mmonrate = mMonrate;
        this.mmonintrorate = mMonintrorate;
}


function sortByApr(a, b) {
        var x = a.mrate;
        var y = b.mrate;
/*         return ((x < y) ? -1 : ((x > y) ? 1 : 0));  */
        return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}

function IsNumeric(sText)

{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;


   for (i = 0; i < sText.length && IsNumber == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsNumber = false;
         }
      }
   return IsNumber;

   }

function snowerase(form)         /* erases all cookies */
{
eraseCookie('snbase');
eraseCookie('snlmp1'); eraseCookie('snlmp2');  eraseCookie('snlmp3');
eraseCookie('snuns1'); eraseCookie('snuns2'); eraseCookie('snuns3'); eraseCookie('snuns4'); eraseCookie('snuns5'); eraseCookie('snuns6');
eraseCookie('snuns7'); eraseCookie('snuns8'); eraseCookie('snuns9'); eraseCookie('snuns10'); eraseCookie('snuns11'); eraseCookie('snuns12');
eraseCookie('snuns13'); eraseCookie('snuns14'); eraseCookie('snuns15'); eraseCookie('snuns0');
eraseCookie('snsec1'); eraseCookie('snsec2'); eraseCookie('snsec3'); eraseCookie('snsec4'); eraseCookie('snsec5');
}

function snowsave(form)                          /* saves user entered data in cookies for later use */
{
snowcheck(form);

if (warningfound=="Yes" || errorfound=="Yes")
    {
    useraction= window.confirm('There are error and/or warning messages on the form. Press OK to save your Snowball now or press Cancel to return to the form to check the messages.');
    if (useraction)
        {
        }
    else
        {
        return;
        }
    }
/* create base cookie */
basecookie=+totalavailable +'~' +committed +'~' +spend +'~' +includesec;
createCookie('snbase', basecookie, 200);

/* Read back base cookie to check that cookies are accepted */

testbase=readCookie ('snbase');
if (testbase==null)
    {
    alert('The Snowball Calculator has NOT been able to save your data, because your browser is not accepting cookies.');
    return;
    }
else
    {
    basearray = new Array();
    basearray = testbase.split('~');
    ttotal=basearray[0];
    tcommit=basearray[1];
    tspend=basearray[2];
    tinclude=basearray[3];
    if (ttotal!=totalavailable)
        {
        alert('The Snowball Calculator has NOT been able to save and check your data.');
        return;
        }
    }

/* create lumpsum cookies */
if (lumpdesc1!="" || lumpsum1!=0 || lumpmonth1!=0 || lumpyear1!=0)
    {
    lumpcookie=lumpdesc1 +'~' +lumpsum1 +'~' +lumpmonth1 +'~' +lumpyear1;
    createCookie('snlmp1', lumpcookie, 200);
    }
else
    {
    eraseCookie('snlmp1');
    }
if (lumpdesc2!="" || lumpsum2!=0 || lumpmonth2!=0 || lumpyear2!=0)
    {
    lumpcookie=lumpdesc2 +'~' +lumpsum2 +'~' +lumpmonth2 +'~' +lumpyear2;
    createCookie('snlmp2', lumpcookie, 200);
    }
else
    {
    eraseCookie('snlmp2');
    }
if (lumpdesc3!="" || lumpsum3!=0 || lumpmonth3!=0 || lumpyear3!=0)
    {
    lumpcookie=lumpdesc3 +'~' +lumpsum3 +'~' +lumpmonth3 +'~' +lumpyear3;
    createCookie('snlmp3', lumpcookie, 200);
    }
else
    {
    eraseCookie('snlmp3');
    }

/* Create unsecured debts cookies */
j=0;
while (j<16)
       {
       desc=creditcards[j].mdesc;
       debt=creditcards[j].mdebt;
       rate=creditcards[j].mrate;
       introrate=creditcards[j].mintrorate;
       intromonth=creditcards[j].mintromonth;
       introyear=creditcards[j].mintroyear;
       paytype=creditcards[j].mpaytype;
       minpay=creditcards[j].mminpay;
       overpay=creditcards[j].moverpay;
       if (desc!="" || debt!=0 || rate!=0 || minpay!=0)
           {
           unscookie=desc +'~' +debt +'~' +rate +'~' +introrate +'~' +intromonth +'~' +introyear +'~' +paytype +'~' +minpay +'~' +overpay;
           createCookie('snuns' +j, unscookie, 200);
           }
       else
           {
           eraseCookie('snuns' +j);
           }
       j=j+1;
       }

/* Write Secured Debts Cookies */
for (i = 1; i <= 5; i++)
     {
     if (sdebtdesc[i]!="" || sdebtminp[i]!=0 || sdebtendm[i]!=0 || sdebtendy[i]!=0)
         {
         seccookie=sdebtdesc[i] +'~' +sdebtdebt[i] +'~' +sdebtrate[i] +'~' +sdebtminp[i] +'~' +sdebtendm[i] +'~' +sdebtendy[i];
         createCookie('snsec' +i, seccookie, 200);
         }
     else
         {
         eraseCookie('snsec' +i);
         }
     }


alert('Your data has been saved. You can restore it within the next 200 days by using the Load Data button.');
}

function snowload(form)                          /* Loads data saved in cookies */
{

useraction= window.confirm('Loading your saved Snowball will overwrite any information that is on the form now. Press OK to continue or press Cancel to return to the form.');
if (useraction)
    {
    }
else
    {
    return;
    }
document.form1.reset();

/* Read base cookie */
basec=readCookie ('snbase');
if (basec==null)
    {
    alert("The calculator is unable to find a Saved Snowball.");
    return;
    }
else
    {
    var basearray = new Array();
    basearray = basec.split('~');
    totalavailable=basearray[0];
    committed=basearray[1];
    spend=basearray[2];
    includesec=basearray[3];
    if (includesec=="Y")
       {
       document.form1.includesec.checked=true;
       }
    else
       {
       document.form1.includesec.checked=false;
       }
    form.totalavailable.value=totalavailable; form.committed.value=committed;  form.spend.value=spend;
    }

/* Read lump sum cookies */
lump1c=readCookie ('snlmp1');
if (lump1c!=null)
    {
    var lump1array = new Array();
    lump1array = lump1c.split('~');
    lumpdesc1=lump1array[0]; lumpsum1=lump1array[1]; lumpmonth1=lump1array[2]; lumpyear1=lump1array[3];
    if (lumpmonth1.length==1)
        {
        lumpmonth1="0" +lumpmonth1;      /* if month is single digit, fill with 0 to make 2 digits */
        }
    form.lumpdesc1.value=lumpdesc1; form.lumpsum1.value=lumpsum1; form.lumpmonth1.value=lumpmonth1; form.lumpyear1.value=lumpyear1;
    }
lump2c=readCookie ('snlmp2');
if (lump2c!=null)
    {
    var lump2array = new Array();
    lump2array = lump2c.split('~');
    lumpdesc2=lump2array[0]; lumpsum2=lump2array[1]; lumpmonth2=lump2array[2]; lumpyear2=lump2array[3];
    if (lumpmonth2.length==1)
        {
        lumpmonth2="0" +lumpmonth2;      /* if month is single digit, fill with 0 to make 2 digits */
        }
    form.lumpdesc2.value=lumpdesc2; form.lumpsum2.value=lumpsum2; form.lumpmonth2.value=lumpmonth2; form.lumpyear2.value=lumpyear2;
    }
lump3c=readCookie ('snlmp3');
if (lump3c!=null)
    {
    var lump3array = new Array();
    lump3array = lump3c.split('~');
    lumpdesc3=lump3array[0]; lumpsum3=lump3array[1]; lumpmonth3=lump3array[2]; lumpyear3=lump3array[3];
    if (lumpmonth3.length==1)
        {
        lumpmonth3="0" +lumpmonth3;      /* if month is single digit, fill with 0 to make 2 digits */
        }
    form.lumpdesc3.value=lumpdesc3; form.lumpsum3.value=lumpsum3; form.lumpmonth3.value=lumpmonth3; form.lumpyear3.value=lumpyear3;
    }


/* Read unsecured debts cookies */
j=0;
x=0;
var desc = new Array(); var debt = new Array(); var rate = new Array(); var introrate = new Array(); var intromonth = new Array();
var introyear = new Array(); var paytype = new Array(); var minpay = new Array(); var overpay = new Array();
while (j<16)
       {
       unsecc=readCookie ('snuns'+j);
       if (unsecc!=null)
           {
           var unsecarray = new Array();
           unsecarray = unsecc.split('~');
           desc[j]=unsecarray[0]; debt[j]=unsecarray[1]; rate[j]=unsecarray[2]; introrate[j]=unsecarray[3]; intromonth[j]=unsecarray[4];
           introyear[j]=unsecarray[5]; paytype[j]=unsecarray[6]; minpay[j]=unsecarray[7]; overpay[j]=unsecarray[8];
           x=(j*1)+1;
           var field2="desc"+x;                  /* Workout description field name */
           document.getElementById(field2).value=desc[j];  /* write item to input field */
           var field2="debt"+x;                  /* Workout description field name */
           document.getElementById(field2).value=debt[j];  /* write item to input field */
           var field2="minpay"+x;                  /* Workout description field name */
           document.getElementById(field2).value=minpay[j];  /* write item to input field */
           var field2="rate"+x;                  /* Workout description field name */
           document.getElementById(field2).value=rate[j];  /* write item to input field */
           var field2="introrate"+x;                  /* Workout description field name */
           document.getElementById(field2).value=introrate[j];  /* write item to input field */
           var field2="intromonth"+x;                  /* Workout description field name */
           if (intromonth[j].length==1)
               {
               intromonth[j]="0" +intromonth[j];      /* if month is single digit, fill with 0 to make 2 digits */
               }
           document.getElementById(field2).value=intromonth[j];  /* write item to input field */
           var field2="introyear"+x;                  /* Workout description field name */
           document.getElementById(field2).value=introyear[j];  /* write item to input field */
           var field2="mpaytype"+x;                  /* Workout description field name */
           document.getElementById(field2).value=paytype[j];  /* write item to input field */
           var field2="overpay"+x;                  /* Workout description field name */
           if (overpay[j]=="Y")
               {
               document.getElementById(field2).checked=true;
               }
           else
               {
               document.getElementById(field2).checked=false;
               }
           }


       j=j+1;
       }


/* Read Secured debts cookies */
j=1;
x=0;
var sdebtdesc = new Array(); var sdebtdebt = new Array(); var sdebtrate = new Array(); var sdebtminp = new Array(); var sdebtendm = new Array(); var sdebtendy = new Array();

while (j<6)
       {
       secuc=readCookie ('snsec'+j);
       if (secuc!=null)
           {
           var secarray = new Array();
           secarray = secuc.split('~');
           sdebtdesc[j]=secarray[0]; sdebtdebt[j]=secarray[1]; sdebtrate[j]=secarray[2]; sdebtminp[j]=secarray[3]; sdebtendm[j]=secarray[4]; sdebtendy[j]=secarray[5];
           x=(j*1);
           var field2="securedesc"+x;                  /* Workout description field name */
           document.getElementById(field2).value=sdebtdesc[j];  /* write item to input field */
           var field2="securedebt"+x;                  /* Workout description field name */
           document.getElementById(field2).value=sdebtdebt[j];  /* write item to input field */
           var field2="securerate"+x;                  /* Workout description field name */
           document.getElementById(field2).value=sdebtrate[j];  /* write item to input field */
           var field2="secminpay"+x;                  /* Workout description field name */
           document.getElementById(field2).value=sdebtminp[j];  /* write item to input field */
           var field2="endmonth"+x;                  /* Workout description field name */
           if (sdebtendm[j].length==1)
               {
               sdebtendm[j]="0" +sdebtendm[j];      /* if month is single digit, fill with 0 to make 2 digits */
               }
           document.getElementById(field2).value=sdebtendm[j];  /* write item to input field */
           var field2="endyear"+x;                  /* Workout description field name */
           document.getElementById(field2).value=sdebtendy[j];  /* write item to input field */
           }


       j=j+1;
       }


/* soacheck(form);    NEW - force read of input fields after load */
}

function soaload(form)                          /* Loads data saved in cookies */
{
useraction= window.confirm('Prefilling from your Saved SOA will overwrite any information that you have already entered on this form. Press OK to continue to prefill from your saved SOA or press Cancel to return to the form.');
if (useraction)
    {
    }
else
    {
    return;
    }
document.form1.reset();


disprow=1;
/* Read HP cookie */
hpc=readCookie ('chp');
if (hpc==null)
    {
    hp=0; hpdebt1=0; hprate1=0;
    }
else
    {
    var hparray = new Array();
    hparray = hpc.split('~');
    hp=hparray[0];
    hpdebt1=hparray[1];
    hprate1=hparray[2];
    if (hp!=0 || hpdebt1!=0 || hprate1!=0)
        {
        var field2="securedesc"+disprow;
        document.getElementById(field2).value="Hire Purchase (HP) Debts"  ;
        var field2="securedebt"+disprow;
        document.getElementById(field2).value=hpdebt1  ;
        var field2="securerate"+disprow;
        document.getElementById(field2).value=hprate1  ;
        var field2="secminpay"+disprow;
        document.getElementById(field2).value=hp  ;
        disprow=disprow+1;
        }
    }

/* Read Totals Cookie */
totc=readCookie ('ctot');
if (totc==null)
    {
    form.spend.value=" ";
    form.totalavailable.value=" ";
    form.committed.value=" ";
    }
else
    {
    var totarray = new Array();
    totarray = totc.split('~');
    preavailable=totarray[0];
    available=totarray[1];
    surplus=totarray[2];
    form.spend.value=available;
    form.totalavailable.value=preavailable;
    committed=preavailable-available;
    form.committed.value=committed;
    }

    /* Read Secured Debts Cookie */
secdebtc=readCookie ('csd1');
if (secdebtc==null)
    {
    mortgagedebt=0;
    securedebt1=0;
    securerate1=0;
    }
else
    {
    var secdebtarray = new Array();
    secdebtarray = secdebtc.split('~');
    mortgagedebt=secdebtarray[0];
    securedebt1=secdebtarray[1];
    securerate1=secdebtarray[2];
    sdebtrow=0;
    if (securedebt1!=0 || securerate1!=0)
        {
        secminpay1=preavailable-available-hp;               /* 1st sec debt payment needs to be derived. Step 1 of calc here. Rest done from cookie CSD3 */
        securedesc1="Secured Debts";
        var field2="securedesc"+disprow;
        document.getElementById(field2).value=securedesc1  ;
        var field2="securerate"+disprow;
        document.getElementById(field2).value=securerate1  ;
        var field2="securedebt"+disprow;
        document.getElementById(field2).value=securedebt1  ;
        sdebtrow=disprow;
        disprow=disprow+1;
        }
    }

/* Check for Additional Secure Debt being stored, then create and populate input fields on screen */
firstextrarow=disprow;
secdebt2=readCookie ('csd2');
if (secdebt2!=null)
    {
    var secdebt2array = new Array();
    secdebt2array = secdebt2.split('~');
    var len=secdebt2array.length  ;
    len=len-1 ;
    rows=len/3 ;
    thisrow=1;
    emptyrows=6-disprow;            /* calculate how many rows are available for these extra debt lines */
    if (rows>emptyrows)
        {
        alert ("You have " +displayrows +" Secured and HP Debts but there is only space to show the first 5. The others will not be loaded");
        }
    while (thisrow<=rows && disprow<=5)
           {
           thisitem=(thisrow*3)-3;
           securedesc=secdebt2array[thisitem];
           var field2="securedesc"+disprow;
           document.getElementById(field2).value=securedesc  ;
           thisitem=(thisrow*3)-2;
           securedebt=secdebt2array[thisitem];
           var field2="securedebt"+disprow;
           document.getElementById(field2).value=securedebt    ;
           thisitem=(thisrow*3)-1;
           securerate=secdebt2array[thisitem];
           var field2="securerate"+disprow;
           document.getElementById(field2).value=securerate   ;
           thisrow=thisrow+1;
           disprow=disprow+1;
           }
    }

/* Read new cookie CSD3 created 18th March 2009. Check for Additional Secure Debt PAYMENTS, then populate input fields on screen */
secdebt3=readCookie ('csd3');
if (secdebt3!=null)
    {
    var secdebt3array = new Array();
    secdebt3array = secdebt3.split('~');
    var len=secdebt3array.length  ;                /* get number of items in array */
    len=len-1 ;                                    /* remove 1 from number to get rid of additional one caused by spare delimeter */
    rows=len/1 ;                                   /* divide by number of items in row to get number of additional rows to be displayed on screen */
    displayrows=rows+2;
    thisrow=1;
    disprow=firstextrarow;
    thisitem=0;
    while (thisrow<=rows)
           {
           thisitem=(thisrow*1)-1;                 /* Set thisitem to point to first row item in array */
           secminpay=secdebt3array[thisitem];        /* Get item out of array */
           var field2="secminpay"+disprow;       /* Workout description field name */
           document.getElementById(field2).value=secminpay  ;              /* write item to input field */
           if (sdebtrow>0)
               {
               secminpay1=secminpay1-secminpay;       /* remove this secure payment from total to derive 1st min pay */
               }
           thisrow=thisrow+1;
           disprow=disprow+1;
           }
    }
if (sdebtrow>0)
    {
    var field2="secminpay"+sdebtrow;       /* Workout description field name */
    document.getElementById(field2).value=secminpay1  ;
    }

unsecdc=readCookie ('cud1');
if (unsecdc==null)
    {
    form.desc1.value=""; form.debt1.value=0;  form.pay1.value=0;  form.rate1.value=0;
    form.desc2.value=""; form.debt2.value=0;  form.pay2.value=0;  form.rate2.value=0;
    form.desc3.value=""; form.debt3.value=0;  form.pay3.value=0;  form.rate3.value=0;
    }
else
    {
    var unsecdarray = new Array();
    unsecdarray = unsecdc.split('~');
    desc1=unsecdarray[0];
    debt1=unsecdarray[1];
    pay1=unsecdarray[2];
    rate1=unsecdarray[3];
    desc2=unsecdarray[4];
    debt2=unsecdarray[5];
    pay2=unsecdarray[6];
    rate2=unsecdarray[7];
    desc3=unsecdarray[8];
    debt3=unsecdarray[9];
    pay3=unsecdarray[10];
    rate3=unsecdarray[11];
    form.desc1.value=desc1;
    form.debt1.value=debt1;
    form.rate1.value=rate1;
    form.desc2.value=desc2;
    form.debt2.value=debt2;
    form.rate2.value=rate2;
    form.desc3.value=desc3;
    form.debt3.value=debt3;
    form.rate3.value=rate3;
    }
/* Check for Additional UNSecure Debt being stored, then create and populate input fields on screen */
unsecd2=readCookie ('cud2');
if (unsecd2!=null)
    {
    var unsecd2array = new Array();
    unsecd2array = unsecd2.split('~');
    var len=unsecd2array.length  ;                /* get number of items in array */
    len=len-1 ;                                    /* remove 1 from number to get rid of additional one caused by spare delimeter */
    rows=len/4 ;                                   /* divide by number of items in row to get number of additional rows to be displayed on screen */
    displayrows=rows+3;
    /* while (displayrows>=indb)
           {
           addunsecure(form);
           } */
    thisrow=1;
    disprow=4;
    if (displayrows>16)
        {
        alert ("You have " +displayrows +" Unsecured Debts but there is only space to show the first 16. The others will not be loaded");
        }
    while (thisrow<=rows && disprow<=16)
           {
           thisitem=(thisrow*4)-4;                     /* Set thisitem to point to first row item in array */
           desc=unsecd2array[thisitem];                /* Get item out of array */
           var field2="desc"+disprow;                  /* Workout description field name */
           document.getElementById(field2).value=desc;  /* write item to input field */
           thisitem=(thisrow*4)-3;                     /* Set thisitem to point to this item in array */
           debt=unsecd2array[thisitem];                /* Get item out of array */
           var field2="debt"+disprow;                  /* Workout debt field name */
           document.getElementById(field2).value=debt;  /* write item to input field */
           thisitem=(thisrow*4)-2;                     /* Set thisitem to point to this item in array */
           pay=unsecd2array[thisitem];                 /* Get item out of array */
           var field2="pay"+disprow;                   /* Workout rate field name */
           thisitem=(thisrow*4)-1;                     /* Set this item to point to this item in array */
           rate=unsecd2array[thisitem];                /* Get item out of array */
           var field2="rate"+disprow;                  /* Workout rate field name */
           document.getElementById(field2).value=rate;  /* write item to input field */
           thisrow=thisrow+1;
           disprow=disprow+1;
           }
      }


/* soacheck(form);    NEW - force read of input fields after load */
}

function snowcheck(form)
{
errorfound="No";
warningfound="No";
clearall=document.getElementById('messages');         /* Clear warning messages ready to rebuild them */
while (clearall.firstChild) {
  clearall.removeChild(clearall.firstChild);
  }
/* Get today's Year and Month */
today= new Date();
currentyear=today.getFullYear();
currentmonth=today.getMonth()+1;  /* Javascript stores January as 0 so add 1 on to bring in line with human numbering! */
currentmonthtot=(currentyear*12)+currentmonth;
<!-- Retrieve input fields
/* Retrieve money available input fields and check numeric  */
totalavailable = form.totalavailable.value*1;
if(document.form1.includesec.checked != true)
   {
   includesec = "N";
   }
else
   {
   includesec = "Y";
   }
if (totalavailable!=parseFloat(totalavailable))
    {
    errorfound="Yes";
    warnings=document.createElement('p');
    warnings.setAttribute("class", "details");
    msg=document.createTextNode("(e) The money available for debt repayments is not numeric. Please correct.");
    warnings.appendChild(msg);
    document.getElementById('messages').appendChild(warnings);
    }
lumpsum1 = form.lumpsum1.value*1;
lumpsum2 = form.lumpsum2.value*1;
lumpsum3 = form.lumpsum3.value*1;
lumpdesc1 = form.lumpdesc1.value;
lumpdesc2 = form.lumpdesc2.value;
lumpdesc3 = form.lumpdesc3.value;
lumpmonth1 = form.lumpmonth1.value*1;
lumpmonth2 = form.lumpmonth2.value*1;
lumpmonth3 = form.lumpmonth3.value*1;
lumpyear1 = form.lumpyear1.value*1;
lumpyear2 = form.lumpyear2.value*1;
lumpyear3 = form.lumpyear3.value*1;
totlumpsum = lumpsum1+lumpsum2+lumpsum3;
if (totlumpsum!=parseFloat(totlumpsum))
    {
    errorfound="Yes";
    warnings=document.createElement('p');
    warnings.setAttribute("class", "details");
    msg=document.createTextNode("(e) One or more of the one-off payments is not numeric. Please correct.");
    warnings.appendChild(msg);
    document.getElementById('messages').appendChild(warnings);
    }


if ((lumpdesc1!="") && (lumpsum1==0 || lumpmonth1==0 || lumpyear1==0))
    {
    errorfound="Yes";
    warnings=document.createElement('p');
    warnings.setAttribute("class", "details");
    msg=document.createTextNode("(e) One-off payment " +lumpdesc1 +" is incomplete. Please ensure that the amount and date are both entered.");
    warnings.appendChild(msg);
    document.getElementById('messages').appendChild(warnings);
    }
if ((lumpdesc1=="") && (lumpsum1!=0 || lumpmonth1!=0 || lumpyear1!=0))
    {
    errorfound="Yes";
    warnings=document.createElement('p');
    warnings.setAttribute("class", "details");
    msg=document.createTextNode("(e) You have entered One-off payment details without a description. Please enter a description");
    warnings.appendChild(msg);
    document.getElementById('messages').appendChild(warnings);
    }
futuremonthtot=(lumpyear1*12)+lumpmonth1;
totlumpmonths1=futuremonthtot-currentmonthtot;  /* works out how many months away the one-off payment is away */
if (lumpyear1!=0 && lumpmonth1==0)
    {
    errorfound="Yes";
    warnings=document.createElement('p');
    warnings.setAttribute("class", "details");
    msg=document.createTextNode("(e) You have selected a year but not month for " +lumpdesc1 +". Please correct.");
    warnings.appendChild(msg);
    document.getElementById('messages').appendChild(warnings);
    }
if (lumpyear1==0 && lumpmonth1!=0)
    {
    errorfound="Yes";
    warnings=document.createElement('p');
    warnings.setAttribute("class", "details");
    msg=document.createTextNode("(e) You have selected a month but not year for " +lumpdesc1 +". Please correct.");
    warnings.appendChild(msg);
    document.getElementById('messages').appendChild(warnings);
    }
if (totlumpmonths1<0 && lumpyear1!=0 && lumpmonth1!=0)
    {
    warningfound="Yes";
    warnings=document.createElement('p');
    warnings.setAttribute("class", "details");
    msg=document.createTextNode("(w) The one-off payment date for " +lumpdesc1 +" is in the past. Please change it to a future date or it will be ignored.");
    warnings.appendChild(msg);
    document.getElementById('messages').appendChild(warnings);
    }

if ((lumpdesc2!="") && (lumpsum2==0 || lumpmonth2==0 || lumpyear2==0))
    {
    errorfound="Yes";
    warnings=document.createElement('p');
    warnings.setAttribute("class", "details");
    msg=document.createTextNode("(e) One-off payment " +lumpdesc2 +" is incomplete. Please ensure that the amount and date are both entered.");
    warnings.appendChild(msg);
    document.getElementById('messages').appendChild(warnings);
    }
if ((lumpdesc2=="") && (lumpsum2!=0 || lumpmonth2!=0 || lumpyear2!=0))
    {
    errorfound="Yes";
    warnings=document.createElement('p');
    warnings.setAttribute("class", "details");
    msg=document.createTextNode("(e) You have entered One-off payment details without a description. Please enter a description");
    warnings.appendChild(msg);
    document.getElementById('messages').appendChild(warnings);
    }
futuremonthtot=(lumpyear2*12)+lumpmonth2;
totlumpmonths2=futuremonthtot-currentmonthtot;  /* works out how many months away the one-off payment is away */
if (lumpyear2!=0 && lumpmonth2==0)
    {
    errorfound="Yes";
    warnings=document.createElement('p');
    warnings.setAttribute("class", "details");
    msg=document.createTextNode("(e) You have selected a year but not month for " +lumpdesc2 +". Please correct.");
    warnings.appendChild(msg);
    document.getElementById('messages').appendChild(warnings);
    }
if (lumpyear2==0 && lumpmonth2!=0)
    {
    errorfound="Yes";
    warnings=document.createElement('p');
    warnings.setAttribute("class", "details");
    msg=document.createTextNode("(e) You have selected a month but not year for " +lumpdesc2 +". Please correct.");
    warnings.appendChild(msg);
    document.getElementById('messages').appendChild(warnings);
    }
if (totlumpmonths2<0 && lumpyear2!=0 && lumpmonth2!=0)
    {
    warningfound="Yes";
    warnings=document.createElement('p');
    warnings.setAttribute("class", "details");
    msg=document.createTextNode("(w) The one-off payment date for " +lumpdesc2 +" is in the past. Please change it to a future date or it will be ignored.");
    warnings.appendChild(msg);
    document.getElementById('messages').appendChild(warnings);
    }

if ((lumpdesc3!="") && (lumpsum3==0 || lumpmonth3==0 || lumpyear3==0))
    {
    errorfound="Yes";
    warnings=document.createElement('p');
    warnings.setAttribute("class", "details");
    msg=document.createTextNode("(e) One-off payment " +lumpdesc3 +" is incomplete. Please ensure that the amount and date are both entered.");
    warnings.appendChild(msg);
    document.getElementById('messages').appendChild(warnings);
    }
if ((lumpdesc3=="") && (lumpsum3!=0 || lumpmonth3!=0 || lumpyear3!=0))
    {
    errorfound="Yes";
    warnings=document.createElement('p');
    warnings.setAttribute("class", "details");
    msg=document.createTextNode("(e) You have entered One-off payment details without a description. Please enter a description");
    warnings.appendChild(msg);
    document.getElementById('messages').appendChild(warnings);
    }
futuremonthtot=(lumpyear3*12)+lumpmonth3;
totlumpmonths3=futuremonthtot-currentmonthtot;  /* works out how many months away the one-off payment is away */
if (lumpyear3!=0 && lumpmonth3==0)
    {
    errorfound="Yes";
    warnings=document.createElement('p');
    warnings.setAttribute("class", "details");
    msg=document.createTextNode("(e) You have selected a year but not month for " +lumpdesc3 +". Please correct.");
    warnings.appendChild(msg);
    document.getElementById('messages').appendChild(warnings);
    }
if (lumpyear3==0 && lumpmonth3!=0)
    {
    errorfound="Yes";
    warnings=document.createElement('p');
    warnings.setAttribute("class", "details");
    msg=document.createTextNode("(e) You have selected a month but not year for " +lumpdesc3 +". Please correct.");
    warnings.appendChild(msg);
    document.getElementById('messages').appendChild(warnings);
    }
if (totlumpmonths3<0 && lumpyear3!=0 && lumpmonth3!=0)
    {
    warningfound="Yes";
    warnings=document.createElement('p');
    warnings.setAttribute("class", "details");
    msg=document.createTextNode("(w) The one-off payment date for " +lumpdesc3 +" is in the past. Please make it a future date or it will be ignored.");
    warnings.appendChild(msg);
    document.getElementById('messages').appendChild(warnings);
    }

/* Read Unsecured Debts Data in loop */
/* Reads into separate arrays for each input field, to preserve order */
/* Also reads into a multi-dimensional array (creditcards) for sorting into APR order */

creditcards = new Array();
desc= new Array();
debt= new Array();
rate= new Array();
introrate= new Array();
intromonth= new Array();
introyear= new Array();
mpaytype= new Array();
minp= new Array();
overpay= new Array();
offermonths= new Array();
monrate= new Array();
monintrorate= new Array();

for (i = 1; i <= 16; i++)
  {
  var field2="desc"+i;
  desc[i]=document.getElementById(field2).value ;
  var field2="debt"+i;
  debt[i]=document.getElementById(field2).value*1 ;
  var field2="rate"+i;
  rate[i]=document.getElementById(field2).value*1 ;
  var field2="introrate"+i;
  introrate[i]=document.getElementById(field2).value*1 ;
  var field2="intromonth"+i;
  intromonth[i]=document.getElementById(field2).value*1 ;
  var field2="introyear"+i;
  introyear[i]=document.getElementById(field2).value*1 ;
  var field2="mpaytype"+i;
  mpaytype[i]=document.getElementById(field2).value ;
  var field2="minpay"+i;
  minp[i]=document.getElementById(field2).value ;
  var field2="overpay"+i;

  /* calculator monthly interest rates equivalent to APR */
  temprate = (rate[i]/100);
  temprate = temprate+1;
  monrate[i] = Math.pow(temprate,(1/12))-1;
  monrate[i] = monrate[i]*100;
  temprate = (introrate[i]/100);
  temprate = temprate+1;
  monintrorate[i] = Math.pow(temprate,(1/12))-1;
  monintrorate[i] = monintrorate[i]*100;

  if(document.getElementById(field2).checked == true)
     {
     overpay[i]="Y";
     }
  else
     {
     overpay[i]="N";
     }

  /* Validate this line */

  if (debt[i]!=parseFloat(debt[i]))
     {
     errorfound="Yes";
     warnings=document.createElement('p');
     warnings.setAttribute("class", "details");
     msg=document.createTextNode("(e) The debt amount for unsecured debt " +desc[i] +" is not numeric. Please correct.");
     warnings.appendChild(msg);
     document.getElementById('messages').appendChild(warnings);
     }
  if (rate[i]!=parseFloat(rate[i]))
     {
     errorfound="Yes";
     warnings=document.createElement('p');
     warnings.setAttribute("class", "details");
     msg=document.createTextNode("(e) The Basic APR amount for unsecured debt " +desc[i] +" is not numeric. Please correct.");
     warnings.appendChild(msg);
     document.getElementById('messages').appendChild(warnings);
     }
  if (introrate[i]!=parseFloat(introrate[i]))
     {
     errorfound="Yes";
     warnings=document.createElement('p');
     warnings.setAttribute("class", "details");
     msg=document.createTextNode("(e) The INTRO APR for unsecured debt " +desc[i] +" is not numeric. Please correct.");
     warnings.appendChild(msg);
     document.getElementById('messages').appendChild(warnings);
     }

  if (minp[i]!=parseFloat(minp[i]))
     {
     errorfound="Yes";
     warnings=document.createElement('p');
     warnings.setAttribute("class", "details");
     msg=document.createTextNode("(e) The Min Payment amount for unsecured debt " +desc[i] +" is not numeric. Please correct.");
     warnings.appendChild(msg);
     document.getElementById('messages').appendChild(warnings);
     }

  if ((desc[i]!="") && (debt[i]==0 || minp[i]==0))
      {
      errorfound="Yes";
      warnings=document.createElement('p');
      warnings.setAttribute("class", "details");
      msg=document.createTextNode("(e) The debt " +desc[i] +" is incomplete. Please ensure that Debt Amount, Basic APR & Min Pay Amt are all entered.");
      warnings.appendChild(msg);
      document.getElementById('messages').appendChild(warnings);
      }
  if ((rate[i]==0) && (debt[i]!=0 || desc[i]!="" || minp[i]!=0))
      {
      warningfound="Yes";
      warnings=document.createElement('p');
      warnings.setAttribute("class", "details");
      msg=document.createTextNode("(w) The debt " +desc[i] +" has a standard APR of 0%. Please check that this is correct.");
      warnings.appendChild(msg);
      document.getElementById('messages').appendChild(warnings);
      }
  if ((desc[i]=="") && (debt[i]!=0 || rate[i]!=0 || minp[i]!=0))
      {
      errorfound="Yes";
      warnings=document.createElement('p');
      warnings.setAttribute("class", "details");
      msg=document.createTextNode("(e) Unsecured debt line " +i +" is incomplete. Please enter a description, Debt Amount, Basic APR & Min Pay Amt.");
      warnings.appendChild(msg);
      document.getElementById('messages').appendChild(warnings);
      }
  futuremonthtot=(introyear[i]*12)+intromonth[i];
  offermonths[i]=futuremonthtot-currentmonthtot;  /* works out how many months the intro offer is for */
  if (introyear[i]!=0 && intromonth[i]==0)
      {
      errorfound="Yes";
      warnings=document.createElement('p');
      warnings.setAttribute("class", "details");
      msg=document.createTextNode("(e) You have selected a year but not month for " +desc[i] +". Please correct the date.");
      warnings.appendChild(msg);
      document.getElementById('messages').appendChild(warnings);
      }
  if (introyear[i]==0 && intromonth[i]!=0)
      {
      errorfound="Yes";
      warnings=document.createElement('p');
      warnings.setAttribute("class", "details");
      msg=document.createTextNode("(e) You have selected a month but not year for " +desc[i] +". Please correct the date.");
      warnings.appendChild(msg);
      document.getElementById('messages').appendChild(warnings);
      }
  if (introrate[i]!=0 && introyear[i]==0 && intromonth[i]==0)
      {
      errorfound="Yes";
      warnings=document.createElement('p');
      warnings.setAttribute("class", "details");
      msg=document.createTextNode("(e) You have entered an intro rate for " +desc[i] +" but not an end date. Please enter the intro end date.");
      warnings.appendChild(msg);
      document.getElementById('messages').appendChild(warnings);
      }
  if (offermonths[i]<0 && introyear[i]!=0 && intromonth[i]!=0)
      {
      warningfound="Yes";
      warnings=document.createElement('p');
      warnings.setAttribute("class", "details");
      msg=document.createTextNode("(w) The End of Intro rate for " +desc[i] +" has past and will be ignored. Change to a future date if still valid.");
      warnings.appendChild(msg);
      document.getElementById('messages').appendChild(warnings);
      }
  if (mpaytype[i]=="P" && minp[i]>5)
      {
      warningfound="Yes";
      warnings=document.createElement('p');
      warnings.setAttribute("class", "details");
      msg=document.createTextNode("(w) You have said that the minimum payment for " +desc[i] +" is " +minp[i] +"%. This seems high. Please check.");
      warnings.appendChild(msg);
      document.getElementById('messages').appendChild(warnings);
      }
  if (mpaytype[i]=="F" && minp[i]<5)
      {
      warningfound="Yes";
      warnings=document.createElement('p');
      warnings.setAttribute("class", "details");
      msg=document.createTextNode("(w) You have said that the minimum payment for " +desc[i] +" is " +minp[i] +" pounds. This seems low. Please check.");
      warnings.appendChild(msg);
      document.getElementById('messages').appendChild(warnings);
      }
  /* Write this line into creditcards array */
  creditcards[creditcards.length++] = new creditcard(desc[i], debt[i], rate[i], introrate[i], intromonth[i], introyear[i], offermonths[i], mpaytype[i], minp[i], overpay[i], monrate[i], monintrorate[i]);
  j=i-1;    /* individual arrays (indexed by i) started at 1, but the creditcards array starts at 0. Therefore take 1 away from i to create new index j */
  carddetails=creditcards[j].mdesc;
  }
creditcards.sort(sortByApr);  /* Sort array by interest rate */


/* Read SECURED Debts Data in Loop */
/* Read debts even if user doesn't want them included so that they can still be saved away. However, only do validation if they are included */
totsdebtpay=0;
debtpaymenterror="No";
sdebtdesc= new Array();
sdebtdebt= new Array();
sdebtrate= new Array();
sdebtminp= new Array();
sdebtendm= new Array();
sdebtendy= new Array();
debtmonths= new Array();
for (i = 1; i <= 5; i++)
  {
  var field2="securedesc"+i;
  sdebtdesc[i]=document.getElementById(field2).value ;
  var field2="securedebt"+i;
  sdebtdebt[i]=document.getElementById(field2).value*1 ;
  var field2="securerate"+i;
  sdebtrate[i]=document.getElementById(field2).value*1 ;
  var field2="secminpay"+i;
  sdebtminp[i]=document.getElementById(field2).value*1 ;
  var field2="endmonth"+i;
  sdebtendm[i]=document.getElementById(field2).value*1 ;
  var field2="endyear"+i;
  sdebtendy[i]=document.getElementById(field2).value*1 ;
  if (sdebtminp[i]!=parseFloat(sdebtminp[i]))                    /* still need to check that that payment is numeric */
     {
     errorfound="Yes";
     debtpaymenterror="Yes";
     warnings=document.createElement('p');
     warnings.setAttribute("class", "details");
     msg=document.createTextNode("(e) The monthly payment for Secured debt line " +i +" is not numeric. Therefore it is not possible for the calculator to work out how much money is needed or available for debt repayments. Please correct the debt repayment");
     warnings.appendChild(msg);
     document.getElementById('messages').appendChild(warnings);
     }
  else
     {
     totsdebtpay=totsdebtpay+sdebtminp[i];
     }
  }

if (debtpaymenterror=="No")
    {
    committed=totsdebtpay;
    spend=totalavailable-committed;
    }
else
    {
    committed="Error";
    spend="Error";
    }
form.committed.value=committed;
form.spend.value=spend;

/* Validate Secured Debts if user wants them included */
if(document.form1.includesec.checked == true)
  {
  for (i = 1; i <= 5; i++)
     {
     /* Validation of this line */
     /* First action is to check for all nulls in main input fields. If null, then set debt amount and APR to null */
     if ((sdebtendy[i]==0) && (sdebtendm[i]==0) && (sdebtminp[i]==0) && (sdebtdesc[i]=="") && (sdebtdebt[i]!=0 || sdebtrate[i]!=0))
         {
         sdebtdebt[i]=0;
         sdebtrate[i]=0;
         var field2="securedebt"+i;
         document.getElementById(field2).value=sdebtdebt[i]
         var field2="securerate"+i;
         document.getElementById(field2).value=sdebtrate[i]
         warningfound="Yes";
         warnings=document.createElement('p');
         warnings.setAttribute("class", "details");
         msg=document.createTextNode("(w) The APR and Debt Amount for Secured Debt line " +i +" have been set to 0, because the description, date and payment have no values. This debt line will be ignored.");
         warnings.appendChild(msg);
         document.getElementById('messages').appendChild(warnings);
         }

     if (sdebtminp[i]!=parseFloat(sdebtminp[i]))
         {
         errorfound="Yes";
         warnings=document.createElement('p');
         warnings.setAttribute("class", "details");
         msg=document.createTextNode("(e) The Monthly Payment for secured debt " +sdebtdesc[i] +" is not numeric. Please correct.");
         warnings.appendChild(msg);
         document.getElementById('messages').appendChild(warnings);
         }


     if ((sdebtdesc[i]!="") && (sdebtminp[i]==0 || sdebtendm[i]==0 || sdebtendy[i]==0))
          {
          errorfound="Yes";
          warnings=document.createElement('p');
          warnings.setAttribute("class", "details");
          msg=document.createTextNode("(e) The debt " +sdebtdesc[i] +" is incomplete. Please enter the Monthly Payment & Last Payment date.");
          warnings.appendChild(msg);
          document.getElementById('messages').appendChild(warnings);
          }
     if ((sdebtdesc[i]=="") && (sdebtminp[i]!=0 || sdebtendm[i]!=0 || sdebtendy[i]!=0))
          {
          errorfound="Yes";
          warnings=document.createElement('p');
          warnings.setAttribute("class", "details");
          msg=document.createTextNode("(e) Secured debt line " +i +" is incomplete. Please enter a description, Monthly Payment & Last Payment.");
          warnings.appendChild(msg);
          document.getElementById('messages').appendChild(warnings);
          }
     futuremonthtot=(sdebtendy[i]*12)+sdebtendm[i];
     debtmonths[i]=futuremonthtot-currentmonthtot;  /* works out how many months until the last payment */
     if (sdebtendy[i]!=0 && sdebtendm[i]==0)
         {
         errorfound="Yes";
         warnings=document.createElement('p');
         warnings.setAttribute("class", "details");
         msg=document.createTextNode("(e) You have selected an end year but not month for the last payment on " +sdebtdesc[i] +".");
         warnings.appendChild(msg);
         document.getElementById('messages').appendChild(warnings);
         }
     if (sdebtendy[i]==0 && sdebtendm[i]!=0)
         {
         errorfound="Yes";
         warnings=document.createElement('p');
         warnings.setAttribute("class", "details");
         msg=document.createTextNode("(e) You have selected an end month but not year for the last payment on " +sdebtdesc[i] +".");
         warnings.appendChild(msg);
         document.getElementById('messages').appendChild(warnings);
         }
     if (debtmonths[i]<0 && sdebtdebt[i]==0 && sdebtendy[i]!=0 && sdebtendm[i]!=0)
         {
         warningfound="Yes";
         warnings=document.createElement('p');
         warnings.setAttribute("class", "details");
         msg=document.createTextNode("(w) The last payment date for " +sdebtdesc[i] +" is in the past, so the debt will be ignored.");
         warnings.appendChild(msg);
         document.getElementById('messages').appendChild(warnings);
         }
     if (debtmonths[i]<0 && sdebtdebt[i]!=0 && sdebtendy[i]!=0 && sdebtendm[i]!=0)
         {
         errorfound="Yes";
         warnings=document.createElement('p');
         warnings.setAttribute("class", "details");
         msg=document.createTextNode("(e) The last payment date for " +sdebtdesc[i] +" is in the past. If this debt has been paid off, please delete the description and monthly payment and set the date to default mm/yy values. The line will then be ignored.");
         warnings.appendChild(msg);
         document.getElementById('messages').appendChild(warnings);
         }
     }

   }

}


function snowball(form)
{
snowcheck(form);                  /* Re-validate input form */
if (errorfound=="Yes")
    {
    alert ("There are errors on the form which must be corrected before your snowball can be calculated. Errors are marked (e) in the message area.");
    return;
    }
if (warningfound=="Yes")
    {
    useraction= window.confirm('There are warning messages on the form. Press OK to continue with your Snowball or press Cancel to return to the form to check the messages. They are marked (w) in the message area.');
    if (useraction)
        {
        }
    else
        {
        return;
        }
    }

/* STEP 1  - Do first month's calculations to see if the user has sufficient money available to meet all minimum payments */
/* Step 1a - Work out how much cash is available in month 1 */
firstmonthavailable=totalavailable*1;
if (totlumpmonths1==0)
    {
    firstmonthavailable=(firstmonthavailable+lumpsum1);
    }
if (totlumpmonths2==0)
    {
    firstmonthavailable=(firstmonthavailable+lumpsum2);
    }
if (totlumpmonths3==0)
    {
    firstmonthavailable=(firstmonthavailable+lumpsum3);
    }
firstmonthpay=0;
firstmonthpay=firstmonthpay+totsdebtpay;     /* Secured debt total for month 1 */

/* Now loop through unsecured debts to calculate total minimum payments required */
var v = "";
for (var j=0; j<16; j++)
     {
     monthlypayment=0;
     carddebt=creditcards[j].mdebt*1;
     if(carddebt!=0)
         {
         cardpaytype = creditcards[j].mpaytype;
         cardminpay = creditcards[j].mminpay*1;
         if (cardpaytype=="F")
             {
             monthlypayment=cardminpay*1;
             }
         else
             {
             monthlypayment=carddebt*cardminpay/100;
             }
         firstmonthpay=firstmonthpay+monthlypayment;
         }

     }
if (firstmonthpay>firstmonthavailable)
    {
    alert ("The snowball plan could not be generated because you do not have sufficient money available to meet your minimum monthly debt repayments of " +firstmonthpay +" pounds.");
    return;
    }
/* *********************************** */
/* NOW DO THE FULL SNOWBALL FOR REAL ! */
/* *********************************** */

/* Create Window and write header */
var myWindow=window.open('','','width=1000, height=600, scrollbars=yes, toolbar=yes, location=yes, resizable=yes, menubar=yes') ;
msg= "<h2>Snowball Plan</h2>" ;
myWindow.document.write(msg)   ;
msg= "<h3>Explanation of Snowball Plan Details</h3>";
myWindow.document.write(msg)   ;
msg= "<p>The snowball plan below shows the most effective way of paying off your debts. <b>For each month</b>, the following is shown:</p>" ;
myWindow.document.write(msg)   ;
msg= "<ul><li>The amount of money that is available to pay off your debts</li>" ;
myWindow.document.write(msg)   ;
msg= "<li>The amount required to make your Secured Debt repayments</li>" ;
myWindow.document.write(msg)   ;
msg= "<li>The monthly minimum payments required for each of your unsecured debts</li>" ;
myWindow.document.write(msg)   ;
msg= "<li>At the bottom of the unsecured debts table there will be one or more blue lines. These show the debt(s) that you should snowball (overpay)</li>" ;
myWindow.document.write(msg)   ;
msg= "<li>For the snowball (blue) debts, you should add the overpayment and the minimum monthly payment together when making your monthly payment</li></ul>" ;
myWindow.document.write(msg)   ;
debtstopay="yes";
unsecdebtstopay="yes";
secdebtstopay="yes";
loop=0;
maxloop=240;
while(debtstopay=="yes" && loop<maxloop)       /* main monthly loop */
    {
    loop=loop+1;
    debtstopay="no";
    unsecdebtstopay="no";
    secdebtstopay="no";
    /* Work out how much cash available this month for debts. Any lumpsums due? */
    lumpsumcash=0;
    if (totlumpmonths1==0)
        {
        lumpsumcash=(lumpsumcash+lumpsum1)*1;
        }
    if (totlumpmonths2==0)
        {
        lumpsumcash=(lumpsumcash+lumpsum2)*1;
        }
    if (totlumpmonths3==0)
        {
        lumpsumcash=(lumpsumcash+lumpsum3)*1;
        }
    totlumpmonths1=totlumpmonths1-1;
    totlumpmonths2=totlumpmonths2-1;
    totlumpmonths3=totlumpmonths3-1;
    cashthismonth=(totalavailable*1)+lumpsumcash;
    if (lumpsumcash==0)
        {
        msg1="";
        }
    else
        {
        msg1=" (includes lump sum of &pound;" +lumpsumcash +")";
        }
    msg= "<h3>Month " +loop +"</h3><p>&pound;" +cashthismonth +" available for debt repayments" +msg1 +"</p>" ;
    myWindow.document.write(msg)   ;

    /* Next pay off each secured debt monthly payment */
    msg='<table><tr><td width="80%"><b>Secured Debts</b></td><td align="right" width="20%"><b>Payment(&pound;)</b></td></tr>'   ;
    myWindow.document.write(msg)   ;
    if(document.form1.includesec.checked != true)        /* If user hasn't included Sec Debts in Snowball, still take off total secured amount from available cash */
         {
         if (totsdebtpay!=0)
             {
             cashthismonth=cashthismonth-totsdebtpay;
             msg='<tr><td>Total required for secured debts</td><td align="right">' +totsdebtpay +'</td></tr>';
             myWindow.document.write(msg)   ;
             }
         else
             {
             msg= msg='<tr><td>No Secured Debt Repayments</td><td align="right">' +totsdebtpay +'</td></tr>';
             myWindow.document.write(msg)   ;
             }
         }
    else          /* i.e. if secured debts are to be included */
        {
        for (var j=0; j<6; j++)        /* loop through the 5 lines of secured debts */
             {
             if(debtmonths[j]>=0)
                {
                debtstopay="yes";
                secdebtstopay="yes";
                cashthismonth=cashthismonth-sdebtminp[j];
                msg='<tr><td>' +sdebtdesc[j] +'</td><td align="right">' +sdebtminp[j] +'</td></tr>';
                myWindow.document.write(msg)   ;
                cardminpay = creditcards[j].mminpay*1;
                }
             debtmonths[j]=debtmonths[j]-1;
             }                           /* end of secured debts for loop */

        }
    msg='</table>';
    myWindow.document.write(msg)   ;



    /* Now loop through unsecured debts to calculate total minimum payments required */
    msg='<table><tr><td width="25%"><b>Unsecured Debt</b></td><td align="right" width="15%"><b>Start Balance(&pound;)</b></td><td align="right" width="15%"><b>Interest</b></td><td align="right" width="15%"><b>Payment(&pound;)</b></td><td align="right" width="15%"><b>End Balance</b></td><td align="right" width="15%"><b>Snowball?</b></td></tr>'   ;
    myWindow.document.write(msg)   ;
    var v = "";
    for (var j=0; j<16; j++)
         {
         monthlypayment=0;
         carddebt=creditcards[j].mdebt*1;
         carddebt = Math.round(carddebt*100)/100;
         startdebt = carddebt;
         carddesc=creditcards[j].mdesc;
         offermonths=creditcards[j].moffermonths*1;
         if(carddebt!=0)
            {
            debtstopay="yes";
            unsecdebtstopay="yes";
            if (offermonths>=0)                            /* if intro rate in effect use it for interest calc, otherwise use standard rate */
                {
                userate=creditcards[j].mmonintrorate*1;
                offermonths=offermonths-1;
                creditcards[j].moffermonths=offermonths;
                }
            else
                {
                userate=creditcards[j].mmonrate*1;
                }
            cardinterest = carddebt*userate/100;
            cardinterest = Math.round(cardinterest*100)/100;
            userate = Math.round(userate*100)/100;
            carddebt=carddebt+cardinterest;
            carddebt = Math.round(carddebt*100)/100;
            cardpaytype = creditcards[j].mpaytype;
            cardminpay = creditcards[j].mminpay*1;
            if (cardpaytype=="F")
                {
                monthlypayment=cardminpay*1;
                }
            else
                {
                monthlypayment=carddebt*cardminpay/100;
                if (monthlypayment<5)
                    {
                    monthlypayment=5;
                    }
                }
            if (monthlypayment>carddebt)
                {
                monthlypayment=carddebt;
                }
            monthlypayment = Math.round(monthlypayment*100)/100;
            carddebt=carddebt-monthlypayment;
            carddebt = Math.round(carddebt*100)/100;
            creditcards[j].mdebt=carddebt;
            msg='<tr><td>' +carddesc +'</td><td align="right">' +startdebt +'</td><td align="right">' +cardinterest +'</td><td align="right">' +monthlypayment +'</td><td align="right">' +carddebt +'</td><td align="right">no</td></tr>'   ;
            myWindow.document.write(msg)   ;
            cashthismonth=cashthismonth-monthlypayment;
            cashthismonth = Math.round(cashthismonth*100)/100;
            }
         }
    /* Now overpay cards if possible */
    j=0;
    while (j<16 && cashthismonth>0)
         {
         carddebt=creditcards[j].mdebt*1;
         startdebt=carddebt;
         carddesc=creditcards[j].mdesc;
         overpay=creditcards[j].moverpay;
         if(carddebt!=0 && overpay=="Y")
            {
            debtstopay="yes";
            if (cashthismonth>carddebt)
                {
                cashthismonth=cashthismonth-carddebt;
                overpay=carddebt;
                carddebt=0;
                }
            else
                {
                carddebt=carddebt-cashthismonth;
                overpay=cashthismonth;
                cashthismonth=0;
                }
            carddebt = Math.round(carddebt*100)/100;
            creditcards[j].mdebt=carddebt;
            cashthismonth = Math.round(cashthismonth*100)/100;
            msg='<tr style="color: blue"><td>' +carddesc +'</td><td align="right">' +startdebt +'</td><td align="right">N/A</td><td align="right" >' +overpay +'</td><td align="right">' +carddebt +'</td><td align="right">*snowball*</td></tr>'   ;
            myWindow.document.write(msg)   ;
            }
         j=j+1;
         }
    msg='</table>'
    myWindow.document.write(msg)   ;
    }
myWindow.document.close();
if (debtstopay=="yes")
    {
    monthstoclear="more than " +maxloop;
    debtfreeday="too far away for calculator";
    }
else
    {
    monthstoclear=loop-1;
    var monthname=new Array("January","February","March","April","May","June","July","August","September","October","November","December");
    today= new Date();
    dfdate= new Date();
    currentyear=today.getFullYear();
    currentmonth=today.getMonth();
    dfdate.setFullYear(currentyear);
    dfdate.setMonth(currentmonth+monthstoclear);
    dfyear=dfdate.getFullYear();
    dfmonth=dfdate.getMonth();
    dftextmonth=monthname[dfmonth];
    debtfreeday="in " +dftextmonth +" " +dfyear;
    }
form.monthstoclear.value=monthstoclear;
form.debtfreeday.value=debtfreeday;


/* END OF FULL SNOWBALL */


}

