/***************************************************************************

 Copyright:     Azotel Technologies Ltd 2009

 NAME:
       amo.js

 SYNOPSIS:
       This script contains the different javascript functions
       used for the web pages

 AUTHOR:
       David TRAN

 REVISION HISTORY:
 08/Apr/2004    trand     Initial Version 001
 15/Apr/2004    trand     Modified validateForm function
 26/Apr/2004    trand     Deleted functions for images swap
                          because menu changed (links instead of images)
 24/May/2004    trand     Added functions :
                          deleteContacts, updateVat, updateSageId,
                          updateFreq, setVisible, setHidden, trim
 25/May/2004    trand     Added function to get the date of today
 26/May/2004    trand     Added functions for products subscription
 16/Jun/2004    trand     Added confirmDel function
 28/Jun/2004    trand     Updated MM_validateForm function
                          to accept float numbers
 13/Jul/2004    trand     Added IP address verification
 16/Jul/2004    trand     Added showList function
 09/Mar/2005    trand     Added updateStatus function
 10/Mar/2005    trand     Added updateDNAT function
 11/May/2005    trand     Added functions to add/delete WIB numbers
 10/Jun/2005    trand     Added function to set preferred contact
 05/Jul/2005    trand     Modified updateStatus function to enable
                          Priority feature when 'waiting for install'
 12/Jul/2005    trand     Added functions to add/delete cc emails
 11/Nov/2005    trand     Added functions for email details (operators)
 16/Jan/2006    trand     Corrected UpdateEmailFields to correctly display
                          subject and body fields
 01/Feb/2006    trand     Modified some fields names due to
                          the modifications of form_modCust.pl
 12/Jun/2006    gawl      bugfix - Select/Deselect form checkboxes
 30/Mar/2007    gawl      form tools -> check post customers equipment
 27/Jun/2007    gawl      bugfix - MM_displayUpdate() had a bug introduced
                          13% VAT breakup. Due to this bug, Total amounts
                          were not updated properly while using Global Setup
                          in 'Frist Invoices' or 'Generate Invoices',
 17/Jul/2007    gawl      Installer additions
 25/Oct/2007    sjs       Added isMAC verification
 13/Mar/2008    gawl      Removed 192.168 IP prefix from script controling
                          Prov-Nov form, this update was introduced with
                          ICSL operator, as they refused to use 192.168
                          IP addresses for they private ranges
 29/Apr/2008    gawl      MM_URL function
 07/May/2007    gawl      updated value checking in MM_updateProducts()
 22/May/2008    gawl      "installer tracking" addons
 23/May/2008    sjs       Minor updates to isEmail check to disallow white
                          space and semi-colons
 03/Sep/2008    sjs       Update inRange to allow leading 0
 31/Dec/2008    gawl      Rouding Fix, Label Fix
 07/Jan/2009    gawl      Tax label from database in MM_updateProducts
 08/Jan/2009    gawl      MM_updateProductTotalPrice function
 06/Apr/2009    gawl      added two functions:
                          oneShot - to execute AJAX when typing is finished
                          checkFieldUpdate - update both warning message and
                          field plus hide, show DIV - this is to allow using
                          styles on DIV's
 14/May/2009    gawl      language correction
 29/Jun/2009    gawl      per product VAT / TAX rate
 09/Jul/2009    gawl      fix to MM_updateProductTotalPrice - set vat to
                          zero if undefined
 29/Jul/2009    gawl      TAX / VAT flexible fraction section
 28/Oct/2009    julz      Corrected updating subscription (products) list MM_updateProducts
 30/Oct/2009    pawel     Added functions to add and delete mobiles to list
 9/Nov/2009     julz      Added color comparison utility
 5/Jan/2010     gawl      custom invoice override price / description
 5/Jan/2010     arisk     Update to support 'waiting for survey' status
 22/Apr/2010    pawel     Added MM_valButton
 13/May/2010    keith     Added fields and relevent show/hide functionality for Provisioning Notes
 14/May/2010    pawel     Make MM_valButton more generic
 26/May/2010    gawl      Tax Modes / Tax Zones to custom invoicing
 27/Jul/2010	pawel	  SAND excluded
 23/Aug/2010    lee	  Added MM_addEmailAddress, MM_deleteEmailAddress function
 13/Sep/2010	pawel	  Reset IP traffic
 30/Sep/2010	pawel 	  MM_getDate(), MM_calculate_prorating_coeff and non_prorating
 13/Oct/2010	mateusz	  Added two functions: MM_deletePhone(), MM_updatePhone(); updated MM_updateContacts()
 20/Oct/2010	sjs	  Hide/reveal new fields on tools page
 26/Oct/2010	mateusz	  Rollback MM_updateContacts(), added new function MM_updateCustomerContacts()
 26/Oct/2010	mateusz	  Addded new funtions for notes feature: toogleWindow(), backgroundWindow(), windowPositioning(), popUpWindow(), resize(), findClientWidth(), findClientHeight(), findScrollLeft(), findScrollTop(), findClientWidth(), filterResults()
 29/Oct/2010	mateusz	  Updated putDataIntoBox()
 03/Nov/2010	mateusz	  Updating MM_deletePhone(), MM_updatePhone(), MM_updateCustomerContacts() for multi nums to main contact,update from Juliusz
 05/Nov/2010	pawel	Some additions to MM_updateStatus
 24/Nov/2010    julz	Updated ValidateMandatoryFields
 28/Nov/2011	pawel	Two functions to time usage feature
 14/Feb/2011	mateusz Added function MM_theSameAssress
 27/May/2011	pawel	Update to post reason
 09/Jun/2011	pawel	Function to maintenance types
 11/Jan/2012	pawel	function to validate spanish bank account number
 10/Feb/2012	pawel	checkCustomerCoverage
 16/Feb/2012	pawel	fix to putDataIntoBox
 
 PARAMETERS:

 DESCRIPTION:

 SETUP:

***************************************************************************/

var one_day=1000*60*60*24;

//Find an object on the web page
function MM_findObj(n, d) {
  var p,i,x;

  if(!d) d=document;
  if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document;
    n=n.substring(0,p);
  }
  if(!(x=d[n])&&d.all)
    x=d.all[n];
  for (i=0;!x&&i<d.forms.length;i++) {
    x=d.forms[i][n];
    if (x=='searchform') x='';
  }
  for(i=0;!x&&d.layers&&i<d.layers.length;i++)
    x=MM_findObj(n,d.layers[i].document);

  return x;
}

//Check fields on a form
function MM_validateForm() {
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;

  for (i=0; i<(args.length-2); i+=3) {
    test=args[i+2];
    val=MM_findObj(args[i]);
	
    if (val) {
      nm=val.name;
	
      if ((val=trim(val.value))!="") {
        if (test.indexOf('isEmail')!=-1) {
          p=val.indexOf('@');
          if (p<1 || p==(val.length-1))
            errors+='- '+nm+' must contain an e-mail address.\n';
	  if (val.indexOf(';') != -1)
	    errors+='- '+nm+' separate addresses with a comma, not a semi-colon.\n';
          if ((val.indexOf(' ') != -1) || (val.indexOf('\t') != -1))
	    errors+='- '+nm+' must not contain white space.\n';

        }
        else if (test.indexOf('isDate')!=-1) {
          var exp = /^([0-2]?\d|3[0-1])[\/](0?[1-9]|1[0-2])[\/](\d{2}|\d{4})$/;
          if (! exp.test(val))
            errors+='- '+nm+' must contain a date (DD/MM/YY) or (DD/MM/YYYY).\n';
        }
        else if (test.indexOf('isANC')!=-1) {
          var exp = /^[0-9a-zA-Z_]*$/;
          if (! exp.test(val))
            errors+='- '+nm+' must contain alphanumeric characters only or \'_\'.\n';
        }
        else if (test.indexOf('isAlpha')!=-1) {
          var exp = /^[0-9a-zA-Z_\-]*$/;
          if (! exp.test(val))
            errors+='- '+nm+' must contain alphanumeric characters only or \'_\' or \'-\'.\n';
        }
        else if (test.indexOf('isIPfull')!=-1) {
          var exp = /^([0-1]?\d?\d|2[0-4]\d|25[0-5])[\.]([0-1]?\d?\d|2[0-4]\d|25[0-5])[\.]([0-1]?\d?\d|2[0-4]\d|25[0-5])[\.]([0-1]?\d?\d|2[0-4]\d|25[0-5])$/;
          if (! exp.test(val)) {
            errors+='- '+nm+' must contain a valid IP address : x.y.z.t\n';
          }
        }
        else if (test.indexOf('isIP')!=-1) {
          var exp = /^([0-1]?\d?\d|2[0-4]\d|25[0-5])(\.?|\.([0-1]?\d?\d|2[0-4]\d|25[0-5])(\.?|\.([0-1]?\d?\d|2[0-4]\d|25[0-5])(\.?|\.([0-1]?\d?\d|2[0-4]\d|25[0-5]))))$/;
          if (! exp.test(val)) {
            errors+='- '+nm+' must contain a valid IP address template:\n';
            errors+='\'x.y.z.t\' or \'x.y.z\' or \'x.y\' or \'x\'\n';
            errors+='where x,y,z and t are numbers.\n';
          }
        }
        else if (test.indexOf('isInt')!=-1) {
          num = parseInt(val);
          if (val!=''+num) errors+='- '+nm+' must contain an integer.\n';
	        else if (test.indexOf('isIntRange')!=-1) {
            p=test.indexOf(':');
            min=test.substring(11,p); max=test.substring(p+1);
            if (num<min || max<num)
              errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
          }
        }
        else if (test.indexOf('isMAC')!=-1) {
          var exp = /^[0-9a-fA-F]{2,2}[-:][0-9a-fA-F]{2,2}[-:][0-9a-fA-F]{2,2}[-:][0-9a-fA-F]{2,2}[-:][0-9a-fA-F]{2,2}[-:][0-9a-fA-F]{2,2}$/;
          if (! exp.test(val)) {
            errors+='- '+nm+' must contain a valid MAC address : xx:xx:xx:xx:xx:xx\n';
          }
        }
        else if (test!='R') {
          p=val.indexOf('.');
          if (p != -1) {
            while (val.substring(val.length-1) == '0') {
              val = val.substring(0,val.length-1);
            }
            if (val.substring(val.length-1) == '.')
              val = val.substring(0,val.length-1);
          }
          num = parseFloat(val);
          if ((val!=''+num) && (val!='0'+num))
            errors+='- '+nm+' must contain a number.\n';
          if (test.indexOf('inRange') != -1) {
            p=test.indexOf(':');
            min=test.substring(8,p); max=test.substring(p+1);
            if (num<min || max<num)
              errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
          }
        }
      }
      else if (test.charAt(0) == 'R') {
        errors += '- '+nm+' is required.\n';
      }
    }
  }
	
  if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}

//Update contacts scrolling list on customer page
function MM_updateCustomerContacts() {
  var contacts_list, contact, crole, cmail, ctext, cphone, phone_length, i, tmp_label, tmp_phone;
  
  if (document.Form.cphone.value != '') MM_updatePhone(0);

  contact=trim(document.Form.contact.value);
  phone_length=document.Form.scroll_phone.length;
  crole=trim(document.Form.crole.value);
  cmail=trim(document.Form.cmail.value);
  cskype=trim(document.Form.cskype.value);
  
  if (contact) {
    ctext = contact;
    contact = contact + ':::';
   
    if (phone_length) {
      	for (i = 0; i < phone_length; i++) {
		cphone=document.Form.scroll_phone.options[i].value;
      		contact = contact + cphone;
		if (cphone.charAt(0)=='(') {
			tmp_label = cphone.substring(0,3);	
			tmp_phone = cphone.substring(3,cphone.length);
			ctext = ctext +  ', ' + tmp_label + ' ' + tmp_phone;
		} else {
      			ctext = ctext + ', ' + cphone;
		}
		if ( i < (phone_length - 1)) contact = contact + ', ';
	}
    }

    contact = contact + ':::';
    if (crole) {
      contact = contact + crole;
      ctext = ctext + ', ' + crole;
    }

    contact = contact + ':::';
    if (cmail) {
      contact = contact + cmail;
      ctext = ctext + ', ' + cmail;
    }
	
    contact = contact + ':::';
    if (cskype) {
      contact = contact + cskype;
      ctext = ctext + ', ' + cskype;
    }

    contacts_list = document.Form.contacts_list.value;
    if (! contacts_list) listsize = 0;
    else listsize = document.Form.contacts.length;

    document.Form.contacts.length = listsize + 1;
    document.Form.contacts.options[listsize].value = contact;
    document.Form.contacts.options[listsize].text = ctext;
    document.Form.contacts.options[listsize].selected = true;

    if (! contacts_list) {
      document.Form.contacts_list.value = contact;
      document.Form.contacts.options[listsize].text = '(P) ' + ctext;
    }
    else document.Form.contacts_list.value = contacts_list + '///' + contact;
   
    document.Form.contact.value = '';
    document.Form.cphone.value = '';
    document.Form.phone_list.value = '';
    document.Form.crole.value = '';
    document.Form.cskype.value = '';
    document.Form.cmail.value = '';

    for (i = (phone_length-1); i >= 0; i--) {
		document.Form.scroll_phone.options[i].value = '';
		document.Form.scroll_phone.options[i].text = '';
		document.Form.scroll_phone.options[i] = null;
    }    
  }
  document.Form.contact.focus();
}

//Update contacts scrolling list
function MM_updateContacts() {
var contacts_list, contact, cphone, crole, cmail, ctext;
  contact=trim(document.Form.contact.value);
  cphone=trim(document.Form.cphone.value);
  crole=trim(document.Form.crole.value);
  cmail=trim(document.Form.cmail.value);

  if (contact) {
    ctext = contact;
    contact = contact + ':::';
    if (cphone) {
      contact = contact + cphone;
      ctext = ctext + ', ' + cphone;
    }

    contact = contact + ':::';
    if (crole) {
      contact = contact + crole;
      ctext = ctext + ', ' + crole;
    }

    contact = contact + ':::';
    if (cmail) {
      contact = contact + cmail;
      ctext = ctext + ', ' + cmail;
    }

    contacts_list = document.Form.contacts_list.value;
    if (! contacts_list) listsize = 0;
    else listsize = document.Form.contacts.length;

    document.Form.contacts.length = listsize + 1;
    document.Form.contacts.options[listsize].value = contact;
    document.Form.contacts.options[listsize].text = ctext;
    document.Form.contacts.options[listsize].selected = true;

    if (! contacts_list) {
      document.Form.contacts_list.value = contact;
      document.Form.contacts.options[listsize].text = '(P) ' + ctext;
    }
    else document.Form.contacts_list.value = contacts_list + '///' + contact;

    document.Form.contact.value = '';
    document.Form.cphone.value = '';
    document.Form.crole.value = '';
    document.Form.cmail.value = '';
  }
  document.Form.contact.focus();
}

//Delete a contact from the scrolling list
function MM_deleteContacts() {
  var i,tmp,contacts_list,sIndex=document.Form.contacts.selectedIndex;

  contacts_list = '';
  listsize = document.Form.contacts.length;
  for (i=0; i<listsize; i++) {
    if (i != sIndex) {
      if (contacts_list == '') contacts_list = document.Form.contacts.options[i].value;
      else {
        tmp = document.Form.contacts.options[i].value;
        if (tmp) contacts_list = contacts_list + '///' + tmp;
      }
    }
  }
  document.Form.contacts_list.value = contacts_list;
  document.Form.contacts.options[sIndex] = null;

  if ((listsize > 1)&&(sIndex == 0)) {
    tmp = document.Form.contacts.options[sIndex].text;
    document.Form.contacts.options[sIndex].text = '(P) ' + tmp;
  }
}

//Move a contact to the top of the list (preferred contact)
function MM_preferredContacts() {
  var i,tmp,pref_value,pref_text,contacts_list,sIndex=document.Form.contacts.selectedIndex;

  //Already preferred contact
  if (sIndex==0) {
    alert('Contact is already set as preferred contact');
    return;
  }

  pref_value = document.Form.contacts.options[sIndex].value;
  pref_text = document.Form.contacts.options[sIndex].text;
  if (pref_value) {
    tmp = document.Form.contacts.options[0].text;
    tmp = tmp.substring(4);
    document.Form.contacts.options[0].text = tmp;

    for (i=sIndex; i>0; i--) {
      document.Form.contacts.options[i].value = document.Form.contacts.options[i-1].value;
      document.Form.contacts.options[i].text = document.Form.contacts.options[i-1].text;
    }
    document.Form.contacts.options[0].value = pref_value;
    document.Form.contacts.options[0].text = '(P) ' + pref_text;

    contacts_list = '';
    listsize = document.Form.contacts.length;
    for (i=0; i<listsize; i++) {
      if (contacts_list == '') contacts_list = document.Form.contacts.options[i].value;
      else {
        tmp = document.Form.contacts.options[i].value;
        if (tmp) contacts_list = contacts_list + '///' + tmp;
      }
    }
    document.Form.contacts_list.value = contacts_list;
    document.Form.contacts.options[0].selected = true;
  }
}

//Update DNAT scrolling list
function MM_updateDNAT() {
  var dnat_list, dnat_dest, dnat_protocol, dnat_ports, dnat_fw, dnat_text;
  dnat_dest=trim(document.Form.destination.value);
  dnat_protocol=trim(document.Form.protocol.value);
  dnat_ports=trim(document.Form.ports.value);
  dnat_fw=trim(document.Form.forward.value);

  if (dnat_dest) {
    var exp = /^([0-1]?\d?\d|2[0-4]\d|25[0-5])[\.]([0-1]?\d?\d|2[0-4]\d|25[0-5])[\.]([0-1]?\d?\d|2[0-4]\d|25[0-5])[\.]([0-1]?\d?\d|2[0-4]\d|25[0-5])$/;
    if (! exp.test(dnat_dest)) {
      alert('Destination must contain a valid IP address : x.y.z.t\n');
      return;
    }
    dnat_text = dnat_dest;
    dnat_dest = dnat_dest + ':::';
    if (dnat_protocol) {
      dnat_dest = dnat_dest + dnat_protocol;
      dnat_text = dnat_text + ', ' + dnat_protocol;
    }

    dnat_dest = dnat_dest + ':::';
    if (dnat_ports) {
      dnat_dest = dnat_dest + dnat_ports;
      dnat_text = dnat_text + ', ' + dnat_ports;
    }

    dnat_dest = dnat_dest + ':::';
    if (dnat_fw) {
      if (! exp.test(dnat_fw)) {
        alert('ForwardTo must contain a valid IP address : x.y.z.t\n');
        return;
      }
      dnat_dest = dnat_dest + dnat_fw;
      dnat_text = dnat_text + ', ' + dnat_fw;
    }
    else {
      alert('Forward IP address is required');
      return;
    }

    dnat_list = document.Form.dnat_list.value;
    if (! dnat_list) listsize = 0;
    else listsize = document.Form.dnat.length;

    document.Form.dnat.length = listsize + 1;
    document.Form.dnat.options[listsize].value = dnat_dest;
    document.Form.dnat.options[listsize].text = dnat_text;
    document.Form.dnat.options[listsize].selected = true;

    if (! dnat_list) document.Form.dnat_list.value = dnat_dest;
    else document.Form.dnat_list.value = dnat_list + '///' + dnat_dest;

    document.Form.destination.value = '';
    document.Form.protocol.value = '';
    document.Form.ports.value = '';
    document.Form.forward.value = '';
  }
  document.Form.destination.focus();
}

//Delete an element from the DNAT scrolling list
function MM_deleteDNAT() {
  var i,tmp,dnat_list,sIndex=document.Form.dnat.selectedIndex;

  dnat_list = '';
  listsize = document.Form.dnat.length;
  for (i=0; i<listsize; i++) {
    if (i != sIndex) {
      if (dnat_list == '') dnat_list = document.Form.dnat.options[i].value;
      else {
        tmp = document.Form.dnat.options[i].value;
        if (tmp) dnat_list = dnat_list + '///' + tmp;
      }
    }
  }
  document.Form.dnat_list.value = dnat_list;
  document.Form.dnat.options[sIndex] = null;
}

//Update Bucket scrolling list
function MM_updateBucket() {
  var bucket_list, bucket_description, bucket_downlink, bucket_uplink, bucket_text;
  bucket_description=trim(document.Form.description.value);
  bucket_downlink=trim(document.Form.bucket_downlink.value);
  bucket_uplink=trim(document.Form.bucket_uplink.value);

  if (bucket_description) {
    bucket_text = bucket_description;
    if (bucket_downlink) {
      num = parseFloat(bucket_downlink);
      if (bucket_downlink!=''+num) {
        alert('Downlink rate (kbit/s) must contain a number.');
        document.Form.bucket_downlink.focus();
        return;
      }
      bucket_description = bucket_description + ':::' + bucket_downlink;
      bucket_text = bucket_text + ', ' + bucket_downlink;
    } else {
      alert('Downlink rate (kbit/s) must contain a number.');
      document.Form.bucket_downlink.focus();
      return;
    }

    if (bucket_uplink) {
      num = parseFloat(bucket_uplink);
      if (bucket_uplink!=''+num) {
        alert('Uplink rate (kbit/s) must contain a number.');
        document.Form.bucket_uplink.focus();
        return;
      }
      if (bucket_downlink) bucket_description = bucket_description + ':::' + bucket_uplink;
      else bucket_description = bucket_description + '::::::' + bucket_uplink;
      bucket_text = bucket_text + ', ' + bucket_uplink;
    } else {
      alert('Uplink rate (kbit/s) must contain a number.');
      document.Form.bucket_uplink.focus();
      return;
    }

    bucket_list = document.Form.bucket_list.value;
    if (! bucket_list) listsize = 0;
    else listsize = document.Form.bucket.length;

    document.Form.bucket.length = listsize + 1;
    document.Form.bucket.options[listsize].value = bucket_description;
    document.Form.bucket.options[listsize].text = bucket_text;
    document.Form.bucket.options[listsize].selected = true;

    if (! bucket_list) document.Form.bucket_list.value = bucket_description;
    else document.Form.bucket_list.value = bucket_list + '///' + bucket_description;

    document.Form.description.value = '';
    document.Form.bucket_downlink.value = '';
    document.Form.bucket_uplink.value = '';
  }
  document.Form.description.focus();
}

//Delete an element from the Bucket scrolling list
function MM_deleteBucket() {
  var i,tmp,bucket_list,sIndex=document.Form.bucket.selectedIndex;

  tmp = document.Form.bucket.options[sIndex].value;
  if (tmp.indexOf('--CANNOT DELETE')!=-1) {
    tmp = tmp.substring(0,tmp.indexOf('--CANNOT DELETE'));
    alert('You cannot delete this bucket');
  }
  else {
    bucket_list = '';
    listsize = document.Form.bucket.length;
    for (i=0; i<listsize; i++) {
      if (i != sIndex) {
        if (bucket_list == '') bucket_list = document.Form.bucket.options[i].value;
        else {
          tmp = document.Form.bucket.options[i].value;
          if (tmp) bucket_list = bucket_list + '///' + tmp;
        }
      }
    }
    document.Form.bucket_list.value = bucket_list;
    document.Form.bucket.options[sIndex] = null;
  }
}

function MM_updateProductTotalPrice(vat_rate) {
  var price,round_method;
  price        = document.Form.price.value;
  round_method = document.Form.round.value;
  tax          = vat_rate;
  if (document.Form.tax_mode.value == 'fixed') {
    tax =  document.Form.tax_rate.value;
  }
  if (!tax) {
    tax = 0;
  }
  tax = parseFloat(tax);
  document.Form.price_total.value = toCurrency(price*(100+tax)/100,round_method);
}



function MM_getDate(date,separator) {
	var array_Date=new Array();
	array_Date = date.split(separator,3);
	var objDate;
	if (separator == '/') {
		objDate = new Date(array_Date[2],array_Date[1]-1,array_Date[0]);
	} else if (separator == '-') {
		objDate = new Date(array_Date[0],array_Date[1]-1,array_Date[2]);
	}
	return objDate;
}

function MM_calculate_prorating_coeff(date_1,date_2, divider) {
	var diff = Math.ceil((date_2.getTime()-date_1.getTime())/(one_day));
	var coeff = 1;
	if (divider) {
		coeff = diff / divider;
	}
	return coeff;
}



//Update the products scrolling list
function MM_updateProducts(taxlabel) {
  var subscription_list,sIndex,productid,code,quantity,discount,vat,met,met_label,productprice,productround,premium,tax_mode,tax_zone,non_prorating;

  if (!taxlabel) {
    taxlabel='Tax';
  }
  sIndex=document.Form.products.selectedIndex;
  productid=document.Form.products.options[sIndex].value;
  code=document.Form.products.options[sIndex].text;
  quantity=document.Form.quantity.value;
  discount=document.Form.discount.value;
  premium=document.Form.premium.value;
  tax_mode=document.Form.tax_mode.value;
  tax_zone=document.Form.tax_zone.value;
  non_prorating=document.Form.non_prorating.value;

  productprice = document.Form.price_override.value;
  if (!productprice) {
    productprice = products[sIndex];
  }

  pdescription = document.Form.description_override.value;
  if (!pdescription) {
    pdescription = pdesc[sIndex];
  }

  vat = ptax[sIndex];
  if (document.Form.vat) {
    vat=document.Form.vat.value;
  }

  if (document.Form.met) {
    met=document.Form.met.value;
  } else {
    met = 'product default'
  }

  productround = pround[sIndex];
  num  = parseFloat(discount);
  qnum = parseFloat(quantity);
  vnum = parseFloat(vat);
  amount = parseFloat(document.Form.amount.value);
  total_tax = parseFloat(document.Form.total_tax.value);
  total_amount = parseFloat(document.Form.total_amount.value);

  if (met == 'product default') {
     met_label = met;
     met = productround;
  } else {
     met_label = met;
  }

  var exp = /^[0-9]*\.?[0-9]+$/;

  if (! exp.test(discount))
    alert('- discount must contain a number.');
  else if (! exp.test(premium))
    alert('- quantity must contain a number.');
  else if (! exp.test(quantity))
    alert('- quantity must contain a number.');
  else if (! exp.test(vat))
    alert('- vat must contain a number.');
  else if ((discount < 0)||(discount > 100))
    alert('- discount must contain a number between 0 and 100.');
  else if ((vat < 0)||(vat > 100))
    alert('- vat must contain a number between 0 and 100.');	
  else if (quantity <=0)
    alert('- quantity must contain a number greater than 0.');	
  else if (productid) {
    subscription_list = document.Form.subscription_list.value;
    if (! subscription_list) listsize = 0;
    else listsize = document.Form.subscription.length;

    document.Form.subscription.length = listsize + 1;

    var option_value = productid+":::"+code+":::"+quantity+":::"+discount+":::"+vat+":::"+toCurrency(toCurrency(quantity*productprice*(1+premium/100),met)*(1-discount/100),met)+":::"+toCurrency(toCurrency(quantity*productprice*(1+premium/100),met)*(1-discount/100)*(vat/100),met)+":::"+toCurrency(toCurrency(quantity*productprice*(1+premium/100),met)*(discount/100),met)+":::"+vat+":::"+met_label+":::"+premium+":::"+toCurrency(quantity*productprice*(premium/100),met)+":::"+productprice+":::"+pdescription+":::"+tax_mode+":::"+tax_zone+":::"+non_prorating;
    document.Form.subscription.options[listsize].value=option_value;
    document.Form.subscription.options[listsize].text = code + " - Quantity: " + quantity;
    if (premium > 0)
      document.Form.subscription.options[listsize].text += " - Premium " + premium + "%";
    if (discount > 0)
      document.Form.subscription.options[listsize].text += " - Discount " + discount + "%";
    if (vat > 0)
      document.Form.subscription.options[listsize].text += " - " + taxlabel + " Rate: " + vat + "%";
    document.Form.subscription.options[listsize].text += " - Amount: " + toCurrency(toCurrency(quantity*productprice*(1+premium/100),met)*(1-discount/100),met) + " - " + taxlabel + ": " + toCurrency(toCurrency(quantity*productprice*(1+premium/100),met)*(1-discount/100)*(vat/100),met);
    document.Form.subscription.options[listsize].text += " - Rounding Method: " + met_label;
    document.Form.subscription.options[listsize].text += " - Description: " + pdescription;
    document.Form.subscription.options[listsize].selected = true;

    if (! subscription_list)
      document.Form.subscription_list.value=option_value;
    else
      document.Form.subscription_list.value=subscription_list+'///'+option_value;
    document.Form.discount.value = '0';
    document.Form.premium.value = '0';
    document.Form.amount.value = toCurrency(amount + toCurrency(quantity*productprice*(1+premium/100),met)*(1-discount/100),met);
    document.Form.total_tax.value = toCurrency(total_tax + toCurrency(quantity*productprice*(1+premium/100),met)*(1-discount/100)*(vat/100),met);
    document.Form.total_amount.value = toCurrency( parseFloat(document.Form.amount.value) + parseFloat(document.Form.total_tax.value), met);
  }
}

//Delete a product from the products
function MM_deleteProducts() {
  var i,tmp,tmp1,subscription_list,quantity,discount,vat,productprice,amount,total_tax,total_amount;
  sIndex=document.Form.subscription.selectedIndex;
  if (sIndex != -1) {
	amount = parseFloat(document.Form.amount.value);
	total_tax = parseFloat(document.Form.total_tax.value);
	total_amount = parseFloat(document.Form.total_amount.value);
	subscription_list = '';
	listsize = document.Form.subscription.length;
	for (i=0; i<listsize; i++) {
		if (i != sIndex) {
		if (subscription_list == '') subscription_list = document.Form.subscription.options[i].value;
		else {
			tmp = document.Form.subscription.options[i].value;
			if (tmp) subscription_list = subscription_list + '///' + tmp;
		}
		} else {
			tmp = document.Form.subscription.options[i].value;
			tmp1 = tmp.split(":::");
			quantity=tmp1[2];
			discount=tmp1[3];
			vat=tmp1[6];
			productprice = tmp1[5];
		}
	}
	document.Form.subscription_list.value = subscription_list;
	document.Form.subscription.options[sIndex] = null;
	document.Form.amount.value = toCurrency(amount - productprice);
	document.Form.total_tax.value = toCurrency(total_tax - vat);
	document.Form.total_amount.value = toCurrency((total_amount - productprice -vat));
  } else {
	alert('You need to click on the invoice position you want to remove.');
  }
}

function toCurrency(num,met,prec)
{
	var n;
	if (!prec) {
		prec = 2;
	}
	var mult = Math.pow(10,prec);
	if (met == 'up')
	{
		n = Math.ceil(num * mult) / mult;
	} else if (met == 'down') 
	{
		n = Math.floor(num * mult) / mult;
	} else
	{
		n = Math.round(num * mult) / mult;
	}
	
	var m = n.toString();
	var loc = m.indexOf(".");
	if(loc < 0)
	{
		loc = m.length;
		m += ".";
	}
	
	while(loc + 1 + prec > m.length)
	{
		m += '0';
	}
	return m;
}

//Update the WIB numbers scrolling list
function MM_updateWIB() {
  var wibnumbers_list, wibnumber;
  wibnumber=trim(document.Form.wibnumber.value);

  if (wibnumber) {
    num = parseInt(wibnumber);
    if (wibnumber!=''+num) alert('- WIB number must contain a number.');
    else {
      wibnumbers_list = document.Form.wibnumbers_list.value;
      if (! wibnumbers_list) listsize = 0;
      else listsize = document.Form.wibnumbers.length;

      for (i=0; i<listsize; i++) {
        if (document.Form.wibnumbers.options[i].value == wibnumber) {
	        alert('WIB number already added !');
	        return;
        }
      }

      document.Form.wibnumbers.length = listsize + 1;
      document.Form.wibnumbers.options[listsize].value = wibnumber;
      document.Form.wibnumbers.options[listsize].text = wibnumber;
      document.Form.wibnumbers.options[listsize].selected = true;

      if (! wibnumbers_list) document.Form.wibnumbers_list.value = wibnumber;
      else document.Form.wibnumbers_list.value = wibnumbers_list + ':::' + wibnumber;

      document.Form.wibnumber.value = '';
    }
  }
  document.Form.wibnumber.focus();
}

//Delete a WIB number from the list
function MM_deleteWIB() {
  var i,tmp,wibnumbers_list,sIndex=document.Form.wibnumbers.selectedIndex;

  wibnumbers_list = '';
  listsize = document.Form.wibnumbers.length;
  for (i=0; i<listsize; i++) {
    if (i != sIndex) {
      if (wibnumbers_list == '') wibnumbers_list = document.Form.wibnumbers.options[i].value;
      else {
        tmp = document.Form.wibnumbers.options[i].value;
        if (tmp) wibnumbers_list = wibnumbers_list + ':::' + tmp;
      }
    }
  }
  document.Form.wibnumbers_list.value = wibnumbers_list;
  document.Form.wibnumbers.options[sIndex] = null;
}

//Update the CC emails scrolling list
function MM_updateCC() {
  var cc_list, ccmail;
  ccmail=trim(document.Form.ccmail.value);

  if (ccmail) {
    var p=ccmail.indexOf('@');
    if (p<1 || p==(ccmail.length-1)) alert('- CC email must contain an e-mail address.\n');
    else {
      cc_list = document.Form.cc_list.value;
      if (! cc_list) listsize = 0;
      else listsize = document.Form.ccscr.length;

      for (i=0; i<listsize; i++) {
        if (document.Form.ccscr.options[i].value == ccmail) {
	        alert('Email address already added !');
	        return;
        }
      }

      document.Form.ccscr.length = listsize + 1;
      document.Form.ccscr.options[listsize].value = ccmail;
      document.Form.ccscr.options[listsize].text = ccmail;
      document.Form.ccscr.options[listsize].selected = true;

      if (! cc_list) document.Form.cc_list.value = ccmail;
      else document.Form.cc_list.value = cc_list + ':::' + ccmail;

      document.Form.ccmail.value = '';
    }
  }
  document.Form.ccmail.focus();
}

//Delete a CC email from the list
function MM_deleteCC() {
  var i,tmp,cc_list,sIndex=document.Form.ccscr.selectedIndex;

  cc_list = '';
  listsize = document.Form.ccscr.length;
  for (i=0; i<listsize; i++) {
    if (i != sIndex) {
      if (cc_list == '') cc_list = document.Form.ccscr.options[i].value;
      else {
        tmp = document.Form.ccscr.options[i].value;
        if (tmp) cc_list = cc_list + ':::' + tmp;
      }
    }
  }
  document.Form.cc_list.value = cc_list;
  document.Form.ccscr.options[sIndex] = null;
}

// Prompt add notes form functions
// Change visibility for a window
function toogleWindow(div_id) {
	var element_toogle = document.getElementById(div_id);

	if ( element_toogle.style.display == 'none' ) {	element_toogle.style.display = 'block';}
	else {element_toogle.style.display = 'none';}
	
	
	
}

// Changes the size/height of a pop-up window and background layer
function backgroundWindow(popUpDivVar) {
	var transparentLayer = document.getElementById('transparentLayer');	
	var popUpDiv = document.getElementById(popUpDivVar);
	var windowHeightCorrect = findClientHeight();
	var scrollTop = findScrollTop();

	if (windowHeightCorrect < document.body.scrollHeight) { transparentLayer.style.height = document.body.scrollHeight + "px"; }
	else { transparentLayer.style.height = windowHeightCorrect + "px"; }

	popUpDivHeight = scrollTop + windowHeightCorrect*(0.25);
	popUpDiv.style.top = popUpDivHeight + 'px';
		
}

// Adjust the pop-up window horizontal
function windowPositioning(popUpDivVar) {
	var transparentLayer = document.getElementById('transparentLayer');
	var popUpDiv = document.getElementById(popUpDivVar);
	var windowWidthCorrect = findClientWidth();
	var scrollLeft = findScrollLeft();

	if (windowWidthCorrect < document.body.scrollWidth) { transparentLayer.style.width = document.body.scrollWidth + "px"; }
	else { transparentLayer.style.width = windowWidthCorrect + "px"; }
	
	windowWidthCorrect=windowWidthCorrect/2-150;
	popUpDiv.style.left = scrollLeft + windowWidthCorrect + 'px';
}

// Pop-up a div with note form (empty)
function popUpWindow(divname) {
	document.FormNote.title.value = '';
	document.FormNote.note.value = '';
	var Today = new Date();
	if (document.getElementById('reminder')) {
		document.getElementById('reminder').checked=false;
		document.getElementById('reminder').title="";
		document.getElementById('remind_table').style.display="none";
	}
	document.getElementById('date_Month_ID').selectedIndex = Today.getMonth() + 1;
	document.getElementById('date_Day_ID').selectedIndex = Today.getDate() - 1;
	document.getElementById('date_Year_ID').value = Today.getFullYear();
	document.FormNote.date.value = Today.getFullYear() + '-' + Today.getMonth() + '-' + Today.getDate();
	if (date_Object) {
                date_Object.changeMonth(document.getElementById('date_Month_ID'));
                date_Object.changeDay(document.getElementById('date_Day_ID'));
                date_Object.checkYear(document.getElementById('date_Year_ID'));
        }

	backgroundWindow(divname);
	windowPositioning(divname);
	toogleWindow('transparentLayer');
	toogleWindow(divname);
}

// Resize the note form
function resize(){ 
	var transparentLayer = document.getElementById('transparentLayer');
	var popUpDiv = document.getElementById('popUpDivForm');
	

	if (transparentLayer && popUpDiv) {
		var windowWidthCorrect = findClientWidth();
		var scrollLeft = findScrollLeft();
		var windowHeightCorrect = findClientHeight();
		var scrollTop = findScrollTop();

		document.body.style.width = 100 + "%";
 		
		if (windowWidthCorrect < document.body.scrollWidth) { transparentLayer.style.width = document.body.scrollWidth + "px"; }
		else { transparentLayer.style.width = windowWidthCorrect + "px"; }

		if (windowHeightCorrect < document.body.scrollHeight) { transparentLayer.style.height = document.body.scrollHeight + "px"; }
		else { transparentLayer.style.height = windowHeightCorrect + "px"; }
	
		windowWidthCorrect=windowWidthCorrect/2-150;
		popUpDiv.style.left = scrollLeft + windowWidthCorrect + 'px';
		popUpDivHeight = scrollTop + windowHeightCorrect*(0.25);
		popUpDiv.style.top = popUpDivHeight + 'px';
	}
} 

// Functions used to get the width/height of a page and the position of a scroll bar
function findClientWidth() {
	return filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function findClientHeight() {
	return filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function findScrollLeft() {
	return filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function findScrollTop() {
	return filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}

function findClientWidth() {
	return filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}

function filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

// Check if the title/note is empty
function putDataIntoBox(noteId, noteTitle, noteText, reminder, user, day, month, year) {
	popUpWindow('popUpDivForm');
	changeButtonName('Modify');
	document.FormNote.noteid.value = noteId;
	document.FormNote.title.value = noteTitle;
	document.FormNote.note.value = noteText;
	document.FormNote.title_history_old.value = noteTitle;
	document.FormNote.note_history_old.value = noteText;
	
	var Today = new Date();
	if (document.getElementById('reminder')) {
		document.getElementById('reminder').checked=false;
		document.getElementById('reminder').title="";
	}
	document.getElementById('date_Month_ID').selectedIndex = Today.getMonth() + 1;
	document.getElementById('date_Day_ID').selectedIndex = Today.getDate() - 1;
	document.getElementById('date_Year_ID').value = Today.getFullYear();
	document.FormNote.date.value = Today.getFullYear() + '-' + Today.getMonth() + '-' + Today.getDate();
	if (date_Object) {
                date_Object.changeMonth(document.getElementById('date_Month_ID'));
                date_Object.changeDay(document.getElementById('date_Day_ID'));
                date_Object.checkYear(document.getElementById('date_Year_ID'));
        }

	
	if ( reminder && user && day && month && year && document.getElementById('reminder') && document.getElementById('user') && document.getElementById('date_Month_ID') && document.getElementById('date_Day_ID') && document.getElementById('date_Year_ID') && document.getElementById('date_history_old') && document.getElementById('user_history_old')) {
		
		document.getElementById('date_Month_ID').selectedIndex = month;

		if (date_Object) {
                	date_Object.changeMonth(document.getElementById('date_Month_ID'));
        	}
		document.getElementById('date_Day_ID').selectedIndex = day - 1;
		if (date_Object) {
                	date_Object.changeDay(document.getElementById('date_Day_ID'));	
        	}
		document.getElementById('date_Year_ID').value = year;
		if (date_Object) {	
                	date_Object.checkYear(document.getElementById('date_Year_ID'));	
        	}
		document.FormNote.date.value = year + '-' + month + '-' + day;
		
		
		document.getElementById('reminder').checked=reminder;

		
		if (reminder == 'true' ) {
			document.getElementById('reminder').title="read-only";
			document.getElementById('remind_table').style.display="block";
		} else {
			document.getElementById('reminder').title="";
			document.getElementById('remind_table').style.display="none";
		}
		
		document.getElementById('user').value=user;
		document.getElementById('user_history_old').value=user;
		document.getElementById('date_history_old').value=year + '-' + month + '-' + day;
		
	}
		
}

// Check if the title/note is empty
function changeButtonName(name) {
	document.FormNote.note_button.value = name;	
}

// Change sorting on notes page
function changeSorting(url) {
	var tmp = document.Display.desc.value;
	if (tmp == 1) { document.Display.desc.value=0; }
	else { document.Display.desc.value=1; }		
	url += "&desc=" + document.Display.desc.value;
	MM_URL(url);
}

// Change sorting on notes page
function deleteNote(noteid, rightdelete) {
	if (rightdelete == 1){
		var text= 'Are you sure you want to delete this note (ID: ' + noteid + ') ?';
		if (confirm(text)) {
			document.FormNote.choosen.value='Delete';
			document.FormNote.noteid.value = noteid;
			document.FormNote.add_note_value.value=1;
			document.FormNote.submit();
		}
	} else {
		alert('You don\'t have permission to delete this note!');
		return;
	}
}

// Check if the title/note is empty
function checkNote() {
	var title, note;
	title=trim(document.FormNote.title.value);
	note=trim(document.FormNote.note.value);	

	if((title == '')&&(!title)) {
		if (confirm('Do you want to add note without title?'))	{
			if(note == '') {
				alert('Please fill in the note field!');
				return;
			}
			document.FormNote.add_note_value.value=1;
			if (document.FormNote.note_button.value == 'Add' ) document.FormNote.choosen.value='Add';
			else if (document.FormNote.note_button.value == 'Modify' ) document.FormNote.choosen.value='Modify';
			document.FormNote.submit();
		}
		else
			return;
	} else {
		if(note == '') {
			alert('Please fill in the note field!');
			return;
		} else {
			document.FormNote.add_note_value.value=1;
			if (document.FormNote.note_button.value == 'Add' ) document.FormNote.choosen.value='Add';
			else if (document.FormNote.note_button.value == 'Modify' ) document.FormNote.choosen.value='Modify';
			document.FormNote.submit();
		}
	}
}

//Update the phone field

function MM_updatePhone(scroll) {
  var no_wrong_arguments, phone_list, cphone, label, scrollchosen, list, connect;
  
  if (scroll) { 
	label=trim(document.Form.phone_label_main.value);
	cphone=trim(document.Form.phone.value);
	scrollchosen=document.Form.scroll_phone_main;
	list=document.Form.phone_list_main;
	connect=', ';
  }else { 
	label=trim(document.Form.phone_label.value);
	cphone=trim(document.Form.cphone.value);
	scrollchosen=document.Form.scroll_phone;
	list=document.Form.phone_list;
	connect=':::';	
  }
  no_wrong_arguments = true;

  if (cphone) {	// choose only digits with '+' at begin (if exist). If wrong arguments, show alert.
    for (i=0; i<cphone.length; i++){
      if (cphone.charAt(i) != '0' && cphone.charAt(i) != '1' && cphone.charAt(i) != '2' && cphone.charAt(i) != '3' &&
	  cphone.charAt(i) != '4' && cphone.charAt(i) != '5' && cphone.charAt(i) != '6' && cphone.charAt(i) != '7' &&
	  cphone.charAt(i) != '8' && cphone.charAt(i) != '9'){

	  if  (!(cphone.charAt(i) == ' ' || cphone.charAt(i) == '-' || cphone.charAt(i) == '(' || cphone.charAt(i) == ')' || (cphone.charAt(i) == '+' && i == 0))){
		alert ('- wrong argument: \'' + cphone.charAt(i) + '\'');
		no_wrong_arguments = false;
	    	break;
	  }
       }	
     }

     if (no_wrong_arguments) {	
	phone_list = list.value;
    	
     	if (!phone_list) listsize = 0;
      	else listsize = scrollchosen.length; 	
	
	cphone = label + ' ' + cphone;
	      	
	for (i=0; i<listsize; i++) {
       	  	if (scrollchosen.options[i].value == cphone) {
	       		alert('Phone number already added !');
	       		return;
          	}
      	}

      	scrollchosen.length = listsize + 1;
      	scrollchosen.options[listsize].value = cphone;
      	scrollchosen.options[listsize].text = label + ' ' + cphone.substring(3,cphone.length);
      	scrollchosen.options[listsize].selected = true;

	if (! phone_list) list.value = cphone;
      	else list.value = phone_list + connect + cphone; 
	
	if (scroll) { document.Form.phone.value = ''; }
  	else { document.Form.cphone.value = ''; }      	
     }
   }
}

function MM_deletePhone(scroll) {
  var i,tmp,phone_list,sIndex,list,connect;
  
  if (scroll) {
	scrollchosen=document.Form.scroll_phone_main;
	list=document.Form.phone_list_main;
	connect=', ';
  } else {
	scrollchosen=document.Form.scroll_phone;
	list=document.Form.phone_list;	
	connect=':::';
  }

  sIndex=scrollchosen.selectedIndex;
  phone_list = '';
  listsize = scrollchosen.length;
  for (i=0; i<listsize; i++) {
    if (i != sIndex) {
      if (phone_list == '') phone_list = scrollchosen.options[i].value;
      else {
        tmp = scrollchosen.options[i].value;
        if (tmp) phone_list = phone_list + connect + tmp;
      }
    }
  }

  list.value = phone_list;
  scrollchosen.options[sIndex] = null;
}

//Update the alert mobile field

function MM_updateMobile() {
  var no_wrong_arguments, mobiles_list, alert_mobile;
  alert_mobile=trim(document.Form.alert_mobile.value);
  no_wrong_arguments = true;

  if (alert_mobile) {	// choose only digits with '+' at begin (if exist). If wrong arguments, show alert.
    for (i=0; i<alert_mobile.length; i++){
      if (alert_mobile.charAt(i) != '0' && alert_mobile.charAt(i) != '1' && alert_mobile.charAt(i) != '2' && alert_mobile.charAt(i) != '3' &&
	  alert_mobile.charAt(i) != '4' && alert_mobile.charAt(i) != '5' && alert_mobile.charAt(i) != '6' && alert_mobile.charAt(i) != '7' &&
	  alert_mobile.charAt(i) != '8' && alert_mobile.charAt(i) != '9'){

	  if  (alert_mobile.charAt(i) == ' ' || alert_mobile.charAt(i) == '-' || alert_mobile.charAt(i) == '(' || alert_mobile.charAt(i) == ')' || 		      (alert_mobile.charAt(i) == '+' && i == 0)){
		if (alert_mobile.charAt(i) != '+'){
	    	   alert_mobile = alert_mobile.replace(alert_mobile.charAt(i--), '');
                }
	  } else {
	    	alert ('- wrong argument: \'' + alert_mobile.charAt(i) + '\'');
		no_wrong_arguments = false;
	    	break;
	  }
       }	

     }

     if (no_wrong_arguments) {
    	 mobiles_list = document.Form.mobiles_list.value;
     	if (!mobiles_list) listsize = 0;
      	  else listsize = document.Form.mobile_scr.length;

      	for (i=0; i<listsize; i++) {
       	  if (document.Form.mobile_scr.options[i].value == alert_mobile) {
	        alert('Mobile number already added !');
	        return;
          }
      	}	

      	document.Form.mobile_scr.length = listsize + 1;
      	document.Form.mobile_scr.options[listsize].value = alert_mobile;
      	document.Form.mobile_scr.options[listsize].text = alert_mobile;
      	document.Form.mobile_scr.options[listsize].selected = true;

      	if (! mobiles_list) document.Form.mobiles_list.value = alert_mobile;
      	else document.Form.mobiles_list.value = mobiles_list + ':::' + alert_mobile;

      	document.Form.alert_mobile.value = '';
     }
   }

}

function MM_deleteMobile() {
  var i,tmp,mobiles_list,sIndex=document.Form.mobile_scr.selectedIndex;
  mobiles_list = '';
  listsize = document.Form.mobile_scr.length;
  for (i=0; i<listsize; i++) {
    if (i != sIndex) {
      if (mobiles_list == '') mobiles_list = document.Form.mobile_scr.options[i].value;
      else {
        tmp = document.Form.mobile_scr.options[i].value;
        if (tmp) mobiles_list = mobiles_list + ':::' + tmp;
      }
    }
  }
  document.Form.mobiles_list.value = mobiles_list;
  document.Form.mobile_scr.options[sIndex] = null;
}

//Update the alert mobile field

function MM_updateSANDexclude() {
  var sand_excluded, sand_exclude_days;
  sand_exclude_days=trim(document.Form.sand_exclude_days.value);


  if (sand_exclude_days) {	

    
    	 sand_excluded = document.Form.sand_excluded.value;
     	if (!sand_excluded) listsize = 0;
      	  else listsize = document.Form.sand_scr.length;

      	for (i=0; i<listsize; i++) {
       	  if (document.Form.sand_scr.options[i].value == sand_exclude_days) {
	        alert('Date already added !');
	        return;
          }
      	}	

      	document.Form.sand_scr.length = listsize + 1;
      	document.Form.sand_scr.options[listsize].value = sand_exclude_days;
      	document.Form.sand_scr.options[listsize].text = sand_exclude_days;
      	document.Form.sand_scr.options[listsize].selected = true;

      	if (! sand_excluded) document.Form.sand_excluded.value = sand_exclude_days;
      	else document.Form.sand_excluded.value = sand_excluded + ':::' + sand_exclude_days;

      	document.Form.sand_exclude_days.value = '';
     }


}

function MM_deleteSANDexclude() {
  var i,tmp,sand_excluded,sIndex=document.Form.sand_scr.selectedIndex;
  sand_excluded = '';
  listsize = document.Form.sand_scr.length;
  for (i=0; i<listsize; i++) {
    if (i != sIndex) {
      if (sand_excluded == '') sand_excluded = document.Form.sand_scr.options[i].value;
      else {
        tmp = document.Form.sand_scr.options[i].value;
        if (tmp) sand_excluded = sand_excluded + ':::' + tmp;
      }
    }
  }
  document.Form.sand_excluded.value = sand_excluded;
  document.Form.sand_scr.options[sIndex] = null;
}


function MM_updateTimeUsageExclude(monday,tuesday,wednesday,thursday,friday,saturday,sunday) {

	var i, time_usage_excluded, time_usage_excluded_period, label_period;
	time_usage_excluded_period = document.Form.time_usage_excluded_day_from.value+document.Form.time_usage_excluded_hour_from.value+document.Form.time_usage_excluded_minute_from.value+document.Form.time_usage_excluded_day_to.value+document.Form.time_usage_excluded_hour_to.value+document.Form.time_usage_excluded_minute_to.value;

	var myArray = new Array();
	myArray['1'] = monday;
	myArray['2'] = tuesday;
	myArray['3'] = wednesday;
	myArray['4'] = thursday;
	myArray['5'] = friday;
	myArray['6'] = saturday;
	myArray['7'] = sunday;

	label_period = myArray[document.Form.time_usage_excluded_day_from.value]+' '+document.Form.time_usage_excluded_hour_from.value+':'+document.Form.time_usage_excluded_minute_from.value+' - '+myArray[document.Form.time_usage_excluded_day_to.value]+' '+document.Form.time_usage_excluded_hour_to.value+':'+document.Form.time_usage_excluded_minute_to.value;
  	if (time_usage_excluded_period) {	

    
    		time_usage_excluded = document.Form.time_excluded.value;

     		if (!time_usage_excluded) 
			listsize = 0;
      	  	else 
			listsize = document.Form.time_usage_scr.length;

      		for (i=0; i<listsize; i++) {
       	  		if (document.Form.time_usage_scr.options[i].value == time_usage_excluded_period) {
	        		alert('Date already added !');
	        		return;
          		}
      		}	

      		document.Form.time_usage_scr.length 			= listsize + 1;
      		document.Form.time_usage_scr.options[listsize].value 	= time_usage_excluded_period;
      		document.Form.time_usage_scr.options[listsize].text	= label_period;
      		document.Form.time_usage_scr.options[listsize].selected = true;

      		if (! time_usage_excluded) 
			document.Form.time_excluded.value = time_usage_excluded_period;
      		else 
			document.Form.time_excluded.value = time_usage_excluded + ':::' + time_usage_excluded_period;

     }


}



function MM_deleteTimeUsageExclude() {

  	var i,tmp,time_usage_excluded,sIndex=document.Form.time_usage_scr.selectedIndex;
  	
	time_usage_excluded 	= '';
  	listsize 		= document.Form.time_usage_scr.length;

  	for (i=0; i<listsize; i++) {

    		if (i != sIndex) {
      			if (time_usage_excluded == '') 
				time_usage_excluded = document.Form.time_usage_scr.options[i].value;
      			else {
        			tmp = document.Form.time_usage_scr.options[i].value;
        			if (tmp) 
					time_usage_excluded = time_usage_excluded + ':::' + tmp;
      			}
    		}
  	}
	
  	document.Form.time_excluded.value 		= time_usage_excluded;
  	document.Form.time_usage_scr.options[sIndex] 	= null;
}

//Update the subject and body associated to the email type
function MM_updateEmailFields() {
  var p,tmp;

  if (document.Form.etype.selectedIndex >= 0) {
    tmp = document.Form.etype.options[document.Form.etype.selectedIndex].value;
    if (tmp.indexOf(':::') >= 0) {
      p = tmp.indexOf(':::');
      //alert(tmp + ' -- > p1 value='+p);
      tmp = tmp.substring(p+3);
      if (tmp.indexOf(':::') >= 0) {
        p = tmp.indexOf(':::');
        //alert(tmp + ' --> p2 value='+p);
        document.Form.esubject.value = tmp.substring(0,p);
        document.Form.ebody.value = tmp.substring(p+3);
      }
      else {
        //alert(tmp + ' --> 2 No :::');
        document.Form.esubject.value = tmp;
        document.Form.ebody.value = '';
      }
    }
    else {
      //alert(tmp + ' --> 1 No :::');
      document.Form.esubject.value = '';
      document.Form.ebody.value = '';
    }
  }
  else {
    document.Form.esubject.value = '';
    document.Form.ebody.value = '';
  }
  //alert(tmp+'\nsubject: DEB'+document.Form.esubject.value+'FIN body: DEB'+document.Form.ebody.value+'FIN');
}

//Update the list of emails type
function MM_updateEmailType() {
  var i,tmp,type_list,sIndex=document.Form.etype.selectedIndex;

  type_list = '';
  listsize = document.Form.etype.length;
  for (i=0; i<listsize; i++) {
    if (i != sIndex) {
      tmp = document.Form.etype.options[i].value;
    }
    else {
      tmp = document.Form.etype.options[i].text;
      tmp += ':::';
      if (document.Form.esubject.value) tmp += document.Form.esubject.value;
      tmp += ':::';
      if (document.Form.ebody.value) tmp += document.Form.ebody.value;
    }
    if (tmp) {
      if (type_list == '') type_list = tmp;
      else type_list = type_list + '///' + tmp;
    }
    document.Form.etype.options[i].value = tmp;
  }
  document.Form.emailD_list.value = type_list;
}

//Delete an email type
function MM_deleteEmailType() {
  var i,tmp,type_list,sIndex=document.Form.etype.selectedIndex;

  type_list = '';
  listsize = document.Form.etype.length;
  for (i=0; i<listsize; i++) {
    if (i != sIndex) {
      if (type_list == '') type_list = document.Form.etype.options[i].value;
      else {
        tmp = document.Form.etype.options[i].value;
        if (tmp) type_list = type_list + ':::' + tmp;
      }
    }
  }
  document.Form.emailD_list.value = type_list;
  document.Form.etype.options[sIndex] = null;
  MM_updateEmailFields();
}

//Add an email type
function MM_addEmailType() {
  var type_list, newEmailType;
  newEmailType=trim(document.Form.newEmailType.value);

  if (newEmailType) {
    type_list = document.Form.emailD_list.value;
    if (! type_list) listsize = 0;
    else listsize = document.Form.etype.length;

    for (i=0; i<listsize; i++) {
      if (document.Form.etype.options[i].value == newEmailType) {
              alert('Email address already added !');
              return;
      }
    }

    document.Form.etype.length = listsize + 1;
    document.Form.etype.options[listsize].value = newEmailType + '::::::';
    document.Form.etype.options[listsize].text = newEmailType;
    document.Form.etype.options[listsize].selected = true;

    if (! type_list) document.Form.emailD_list.value = newEmailType;
    else document.Form.emailD_list.value = type_list + '///' + newEmailType;

    document.Form.newEmailType.value = '';
    document.Form.esubject.value = '';
    document.Form.ebody.value = '';
  }
  document.Form.newEmailType.focus();
}

//Add a new invoice ID to the billing issues
function MM_addInvoiceID() {
  var invoice_list, invID, sIndex=document.Form.invoiceId.selectedIndex;
  invID = document.Form.invoiceId.options[sIndex].value;

  if (invID) {
    invoice_list = document.Form.issueInv_list.value;
    if (! invoice_list) listsize = 0;
    else listsize = document.Form.invoiceIDlist.length;

    for (i=0; i<listsize; i++) {
      if (document.Form.invoiceIDlist.options[i].value == invID) {
              alert('Invoice ID ' + invID + ' has already been added !');
              return;
      }
    }

    document.Form.invoiceIDlist.length = listsize + 1;
    document.Form.invoiceIDlist.options[listsize].value = invID;
    document.Form.invoiceIDlist.options[listsize].text = document.Form.invoiceId.options[sIndex].text;
    document.Form.invoiceIDlist.options[listsize].selected = true;

    if (! invoice_list) document.Form.issueInv_list.value = invID;
    else document.Form.issueInv_list.value = invoice_list + ':::' + invID;

    document.Form.invoiceId.selectedIndex = 0;
  }
}

//Delete an invoice ID from the billing issues
function MM_deleteInvoiceID() {
  var i,tmp,inv_list,sIndex=document.Form.invoiceIDlist.selectedIndex;

  invoice_list = '';
  listsize = document.Form.invoiceIDlist.length;
  for (i=0; i<listsize; i++) {
    if (i != sIndex) {
      if (invoice_list == '') invoice_list = document.Form.invoiceIDlist.options[i].value;
      else {
        tmp = document.Form.invoiceIDlist.options[i].value;
        if (tmp) invoice_list = invoice_list + ':::' + tmp;
      }
    }
  }
  document.Form.issueInv_list.value = invoice_list;
  document.Form.invoiceIDlist.options[sIndex] = null;
}

//Update the web page to display the vat fields
function MM_updateVat(vat_field) {
  if (vat_field.value == 'Yes') {
    setVisible(document.Form.numberLabel);
    setVisible(document.Form.expiryLabel);
    setVisible(document.Form.number);
    setVisible(document.Form.expiry);
  }
  else {
    setHidden(document.Form.numberLabel);
    setHidden(document.Form.expiryLabel);
    setHidden(document.Form.number);
    setHidden(document.Form.expiry);
  }
}

//Update the web page to display the fields for the customer status
function MM_updateStatus(status_field) {
  	if (status_field.value == 'post') {

    		var items = MM_updateStatus.arguments.length;
		document.Form.reason.length = items-1;
		//alert(items);
    		for (i = 1;i < items; i++){
			document.Form.reason.options[i-1].value = MM_updateStatus.arguments[i];
			document.Form.reason.options[i-1].text = MM_updateStatus.arguments[i];
		}
    
    		setVisible(document.Form.reasonLabel);
    		setVisible(document.Form.reason);
    		setVisible(document.Form.dateLabel);
    		setHidden(document.Form.installerLabel);
    		setHidden(document.Form.installer);
    		setHidden(document.Form.feeLabel);
    		setHidden(document.Form.fee);
    		setHidden(document.Form.maintenanceLabel);
    		setHidden(document.Form.maintenance);
    		setHidden(document.Form.failed_survey);
    		document.Form.reasonLabel.value = 'Reason';
    		document.Form.dateLabel.value = 'End Date';
    		document.Form.postdate.value = today();
    		document.getElementById('postdate_table').style.display='block';
		if (document.Form.reason.value != 'other') {	
			document.getElementById('other_reason_row').style.display='none';
		} else {
			document.getElementById('other_reason_row').style.display='block';
		}
		document.getElementById('failedsurvey_table').style.display='none';
 	}
  else if (status_field.value == 'survey failed') {
    setHidden(document.Form.reasonLabel);
    setHidden(document.Form.reason);
    setVisible(document.Form.dateLabel);
    setVisible(document.Form.failed_survey);
    setHidden(document.Form.installerLabel);
    setHidden(document.Form.installer);
    setHidden(document.Form.feeLabel);
    setHidden(document.Form.fee);
    setHidden(document.Form.maintenanceLabel);
    setHidden(document.Form.maintenance);
    document.Form.dateLabel.value = 'Reason';
    document.Form.failed_survey.value = '';
    document.Form.failed_survey.focus();
    document.getElementById('postdate_table').style.display='none';
    document.getElementById('other_reason_row').style.display='none';failedsurvey_table
	document.getElementById('failedsurvey_table').style.display='block';
  }
  else if (status_field.value == 'waiting for install') {
    var i;
    document.Form.reason.length = 5;
    for (i=0; i<5; i++) {
      document.Form.reason.options[i].value = i+1;
      document.Form.reason.options[i].text = i+1;
    }
    document.Form.reason.options[2].selected = true;
    setVisible(document.Form.reasonLabel);
    setVisible(document.Form.reason);
    setVisible(document.Form.dateLabel);
    setVisible(document.Form.postdate);
    setVisible(document.Form.installerLabel);
    setVisible(document.Form.installer);
    setVisible(document.Form.feeLabel);
    setVisible(document.Form.fee);
    setVisible(document.Form.maintenanceLabel);
    setVisible(document.Form.maintenance);
    setHidden(document.Form.failed_survey);
    document.Form.reasonLabel.value = 'Priority';
    document.Form.dateLabel.value = 'Waiting since (date)';
    document.Form.maintenance.value = 'Customer Installation';
    document.Form.postdate.value = today();
    document.getElementById('postdate_table').style.display='block';
    document.getElementById('other_reason_row').style.display='none';
	document.getElementById('failedsurvey_table').style.display='none';

  }
  else if (status_field.value == 'waiting for survey') {
    var i;
    document.Form.reason.length = 5;
    for (i=0; i<5; i++) {
      document.Form.reason.options[i].value = i+1;
      document.Form.reason.options[i].text = i+1;
    }
    document.Form.reason.options[2].selected = true;
    setVisible(document.Form.reasonLabel);
    setVisible(document.Form.reason);
    setVisible(document.Form.dateLabel);
    setVisible(document.Form.postdate);
    setVisible(document.Form.installerLabel);
    setVisible(document.Form.installer);
    setVisible(document.Form.feeLabel);
    setVisible(document.Form.fee);
    setVisible(document.Form.maintenanceLabel);
    setVisible(document.Form.maintenance);
    document.Form.reasonLabel.value = 'Priority';
    document.Form.dateLabel.value = 'Waiting since (date)';
    document.Form.maintenance.value = 'Customer Survey';
    document.Form.postdate.value = today();
    document.getElementById('postdate_table').style.display='block';
    setHidden(document.Form.failed_survey);
    document.getElementById('other_reason_row').style.display='none';
	document.getElementById('failedsurvey_table').style.display='none';
  }
  else {
    setHidden(document.Form.reasonLabel);
    setHidden(document.Form.reason);
    setHidden(document.Form.dateLabel);
    setHidden(document.Form.postdate);
    setHidden(document.Form.installerLabel);
    setHidden(document.Form.installer);
    setHidden(document.Form.feeLabel);
    setHidden(document.Form.fee);
    setHidden(document.Form.maintenanceLabel);
    setHidden(document.Form.maintenance);
    setHidden(document.Form.failed_survey);
    document.Form.postdate.value = '';
    document.getElementById('postdate_table').style.display='none';
    document.getElementById('other_reason_row').style.display='none';
	document.getElementById('failedsurvey_table').style.display='none';
  }
}

//Create the SageId according to the customer's name
function MM_updateSageId() {
  var name=trim(document.Form.name.value);
  if (name) {
    name = name.toUpperCase();
    name = name.replace(/[^0-9A-Z_]/g,'');
    name = name.substring(0,8);
    document.Form.sageid.value=name;
  }
  else document.Form.sageid.value='';
}

//Write the corresponding value for each frequency
function MM_updateFreq() {
  var num,val;
  val = trim(document.Form.frequency.value);
  num = parseInt(val);

  if (! val) {
    document.Form.frequency.value = '3';
    document.Form.freq_descrpt.value = 'Quaterly';
  }
  else if (val == ''+num) {
    if (num == 1) document.Form.freq_descrpt.value = 'Monthly';
    else if (num == 3) document.Form.freq_descrpt.value = 'Quarterly';
    else if (num == 12) document.Form.freq_descrpt.value = 'Each year';
    else document.Form.freq_descrpt.value = 'Every ' + num + ' months';
  }
  else {
    document.Form.freq_descrpt.value = 'Bad value for frequency';
  }
}

//Update the number of IPs depending on the nat check box
function MM_updateIPnum() {
  if (document.Form.nat.checked == true) {
    document.Form.ip_number.value='1';
    document.Form.ip_number.disabled=true;
  }
  else {
    document.Form.ip_number.disabled=false;
  }
}

//Check date value
function MM_checkDate(field) {
  var errors='',date = field.value;
  var exp = /^([0-2]?\d|3[0-1])[\/](0?[1-9]|1[0-2])[\/](\d{2}|\d{4})$/

  if ((date)&&(! exp.test(date))) {
    errors = 'Invalid date entered (DD/MM/YY) or (DD/MM/YYYY).\n';
    alert(errors);
    field.focus();
  }
  return (errors == '');
}

//Unselect or select every check box on the form
function MM_checkAll(selected,unselected) {
  var i,checkValue;
  if (!selected) selected = 'Uncheck All';
  if (!unselected) unselected = 'Select All';

  checkValue = document.Form.checkButton.value;

  if (checkValue == selected) {
    if (document.Form.checkedCust.length) {
      for (i=0;i<document.Form.checkedCust.length;i++) {
        if (document.Form.checkedCust[i].checked)
          document.Form.checkedCust[i].checked = false;
      }
    }
    else {
      document.Form.checkedCust.checked = false;
    }
    document.Form.checkButton.value = unselected;
  }
  else {
    if (document.Form.checkedCust.length) {
      for (i=0;i<document.Form.checkedCust.length;i++) {
        if ((!document.Form.checkedCust[i].checked)&&(!document.Form.checkedCust[i].disabled))
          document.Form.checkedCust[i].checked = true;
      }
    }
    else {
      document.Form.checkedCust.checked = true;
    }
    document.Form.checkButton.value = selected;
  }
}

//Update the fields for all the checked fields on the bank_invoices page
function MM_bankUpdate() {
  var i,p,invId;

  if (MM_checkDate(document.getElementsByName("payDateChecked")[0])) {
    var checkedCustLength;
    if (document.Form.checkedCust.length) checkedCustLength = document.Form.checkedCust.length;
    else checkedCustLength = 1;

    for (i=0;i<checkedCustLength;i++) {
      var checkedCust;
      if (checkedCustLength == 1) checkedCust = document.Form.checkedCust;
      else checkedCust = document.Form.checkedCust[i];

      if ((checkedCust.checked)&&(!checkedCust.disabled)) {
        invId = checkedCust.value;
        p=invId.indexOf('//');
        invId = invId.substring(0,p);
        document.getElementsByName("payStatus"+invId)[0].value = document.getElementsByName("payStatusChecked")[0].value;
        document.getElementsByName("payDate"+invId)[0].value = document.getElementsByName("payDateChecked")[0].value;
        document.getElementsByName("reference"+invId)[0].value = document.getElementsByName("refChecked")[0].value;
      }
    }
  }
}

//Update the fields for all the checked fields on the display_invoices page
function MM_displayUpdate() {
  var i,p,custId,correct = true;

  if (document.getElementsByName("invDateChecked")[0]) {
    if (! MM_checkDate(document.getElementsByName("invDateChecked")[0])) return false;
  }

  if (! MM_checkDate(document.getElementsByName("payDateChecked")[0])) return false;

  if (document.getElementsByName("setupChecked")[0]) {
    var setup = (document.getElementsByName("setupChecked")[0]).value;
    if (setup) {
      p=setup.indexOf('.');
      if (p != -1) {
        while (setup.substring(setup.length-1) == '0') {
          setup = setup.substring(0,setup.length-1);
        }
        if (setup.substring(setup.length-1) == '.')
          setup = setup.substring(0,setup.length-1);
      }

      var num = parseFloat(setup);

      if ((setup)&&(setup != ''+num)) {
        alert('Setup fees field must contain a number.\n');
        (document.getElementsByName("setupChecked")[0]).focus();
        return false;
      }
    }
  }

  var checkedCustLength;
  if (document.Form.checkedCust.length) checkedCustLength = document.Form.checkedCust.length;
  else checkedCustLength = 1;

  for (i=0;i<checkedCustLength;i++) {
    var checkedCust;
    if (checkedCustLength == 1) checkedCust = document.Form.checkedCust;
    else checkedCust = document.Form.checkedCust[i];

    if ((checkedCust.checked)&&(!checkedCust.disabled)) {
      custId = checkedCust.value;
      p=custId.indexOf('//');
      custId = custId.substring(p+2);
      p=custId.indexOf('//');
      custId = custId.substring(0,p);
      if (document.getElementsByName("payDateChecked")[0].value)
        document.getElementsByName("date"+custId)[0].value = document.getElementsByName("payDateChecked")[0].value;
      document.getElementsByName("sendMethod"+custId)[0].value = document.getElementsByName("sendMethodChecked")[0].value;
      if ((document.getElementsByName("invDateChecked")[0])&&(document.getElementsByName("invDateChecked")[0].value))
        document.getElementsByName("startDate"+custId)[0].value = document.getElementsByName("invDateChecked")[0].value;
      if ((document.getElementsByName("setupChecked")[0])&&(document.getElementsByName("setupChecked")[0].value)&&(document.getElementsByName("setupFees"+custId)[0])) {
        document.getElementsByName("setupFees"+custId)[0].value = document.getElementsByName("setupChecked")[0].value;
        MM_updateAmount(document.getElementsByName("setupFees"+custId)[0],
                        document.getElementsByName("amount"+custId)[0],
                        document.getElementsByName("amount_vat"+custId)[0],
                        document.getElementsByName("setup_apply"+custId)[0].value,
                        document.getElementsByName("vat_apply"+custId)[0].value);
      }
    }
  }
}

//Check amount value and update the total amount
function MM_updateAmount(sfield,afield,field_vat,setup_rate,vat_rate) {
  if (!sfield.value) sfield.value = "0";
  var num,p,setup=sfield.value,amount=afield.value;

  p=setup.indexOf('.');
  if (p != -1) {
    while (setup.substring(setup.length-1) == '0') {
      setup = setup.substring(0,setup.length-1);
    }
    if (setup.substring(setup.length-1) == '.')
      setup = setup.substring(0,setup.length-1);
  }

  num = parseFloat(setup);

  if ((setup)&&(setup != ''+num)) {
    alert('Setup fees field must contain a number.\n');
    sfield.value = '0';
    sfield.focus();
  } else {
    p=amount.indexOf('.');
    if (p != -1) {
      while (amount.substring(amount.length-1) == '0') {
        amount = amount.substring(0,amount.length-1);
      }
      if (amount.substring(amount.length-1) == '.')
        amount = amount.substring(0,amount.length-1);
    }

    num = parseFloat(amount);

    if ((amount)&&(amount != ''+num)) {
      alert('Amount field must contain a number.\n');
      afield.value = '0';
      field_vat.value = '0';
      afield.focus();
    } else {
      amount = parseFloat(amount) * (1 + vat_rate/100) + parseFloat(setup) * (1 + setup_rate/100);
      amount = MM_round(amount, 2);
      field_vat.value = amount;
    }
  }
}


function Decimals(x, dec_sep)
{
    var tmp=new String();
    tmp=x;
    if (!dec_sep) { dec_sep = '.'; }
    if (tmp.indexOf(dec_sep)>-1)
        return tmp.length-tmp.indexOf(dec_sep)-1;
    else
        return 0;
}

//Check amount value and update the total amount
function MM_updateInvoiceAmount(vfield,afield,total_amount,vat_rate,mode) {
  var vat,amount,vat_fraction_digits;
  vat_fraction_digits = 1;
  if (!vfield.value) vfield.value = "0.00"; else vfield.value = toCurrency(vfield.value);
  if (!afield.value) afield.value = "0.00"; else afield.value = toCurrency(afield.value);
  if (!vat_rate.value) {
    vat_rate.value = "0.0"; 
  } else {
    if (!mode) {
      vat_fraction_digits = Decimals(vat_rate.value);
    }
  }
  if (!mode) {
    vat = parseFloat(vfield.value);
    amount = parseFloat(afield.value);
    total_amount.value = toCurrency(vat + amount);
    vat_rate.value = toCurrency(100*vat/amount,0,vat_fraction_digits);
  } else {
    amount = parseFloat(afield.value);
    vat = parseFloat(vat_rate.value);
    total_amount.value = toCurrency(amount*(1+vat/100));
    vfield.value = toCurrency(amount*(vat/100));
  }
}

//Checks the VAT value
function MM_checkVat(vat_field) {
  var num,p,vat_value;
  if ((document.Form.action.value == 'update_vat')
    ||(document.Form.action.value == 'setup_vat'))
  {
    vat_value = vat_field.value;
    p=vat_value.indexOf('.');

    if (p != -1) {
      while (vat_value.substring(vat_value.length-1) == '0') {
        vat_value = vat_value.substring(0,vat_value.length-1);
      }
      if (vat_value.substring(vat_value.length-1) == '.')
        vat_value = vat_value.substring(0,vat_value.length-1);
    }

    num = parseFloat(vat_value);

    if (vat_value != ''+num) {
      alert('VAT field must contain a number.\n');
      vat_field.value = document.Form.vat_rate.value;
      vat_field.focus();
    }
    document.MM_returnValue = (vat_value == ''+num);
  }
}

//Update the wisp scrolling list
function MM_updateWisp() {
  var wisp_list,wispId,listsize;
  wispId=trim(document.Form.wisp.value);

  if (wispId) {
    var exp = /^[0-9a-zA-Z_]*$/;
    if (! exp.test(wispId))
      alert('WISP must contain alphanumeric characters only or \'_\'.');
    else {
      wispId = wispId.toLowerCase();
      wisp_list = document.Form.wisp_list.value;
      if (! wisp_list) listsize = 0;
      else listsize = document.Form.wisps.length;

      document.Form.wisps.length = listsize + 1;
      document.Form.wisps.options[listsize].value = wispId;
      document.Form.wisps.options[listsize].text = wispId;
      document.Form.wisps.options[listsize].selected = true;

      if (! wisp_list) document.Form.wisp_list.value = wispId;
      else document.Form.wisp_list.value = wisp_list + '///' + wispId;

      document.Form.wisp.value = '';
    }
  }
  document.Form.wisp.focus();
}

//Delete a wisp
function MM_deleteWisp() {
  var i,tmp,wisp_list,listsize,sIndex=document.Form.wisps.selectedIndex;

  tmp = document.Form.wisps.options[sIndex].value;
  if (tmp.indexOf('--CANNOT DELETE')!=-1) {
    tmp = tmp.substring(0,tmp.indexOf('--CANNOT DELETE'));
    alert('You can\'t delete ' + tmp + ' WISP');
  }
  else {
    wisp_list = '';
    listsize = document.Form.wisps.length;
    for (i=0; i<listsize; i++) {
      if (i != sIndex) {
        if (wisp_list == '') wisp_list = document.Form.wisps.options[i].value;
        else {
          tmp = document.Form.wisps.options[i].value;
          if (tmp) wisp_list = wisp_list + '///' + tmp;
        }
      }
    }
    document.Form.wisp_list.value = wisp_list;
    document.Form.wisps.options[sIndex] = null;
  }
}

//Displays the list of files for the tools web page
function MM_showList(action_value) {
  if ((action_value == 'restore_psql')||
      (action_value =='update_wib')||
      (action_value == 'update_ser')) {
    setVisible(document.Form.list);
    setHidden(document.Form.list1);
    setHidden(document.Form.updateType3);
    setHidden(document.Form.updateValue3);
    setHidden(document.Form.updateType);
    setHidden(document.Form.updateValue);
    setHidden(document.Form.targetEquipLabel);
    setHidden(document.Form.targetEquipList);
    setHidden(document.Form.targetCustLabel);
    setHidden(document.Form.targetCustList);
    setHidden(document.Form.custMACLabel);
    setHidden(document.Form.custMACData);
    document.getElementsByName('updateType2')[0].style.display='none';
    if(document.getElementsByName('updateValue2').length > 0) {
	document.getElementsByName('updateValue2')[0].style.display='none';
    }
    setHidden(document.Form.percent);
	document.Form.updateValue.style.width = '300px';
	document.getElementById('hideme').style.display='none';
  }
  else if (action_value == 'update_vat') {
    setHidden(document.Form.list);
    setHidden(document.Form.list1);
    setHidden(document.Form.updateType3);
    setHidden(document.Form.updateValue3);
    setHidden(document.Form.targetEquipLabel);
    setHidden(document.Form.targetEquipList);
    setHidden(document.Form.targetCustLabel);
    setHidden(document.Form.targetCustList);
    setHidden(document.Form.custMACLabel);
    setHidden(document.Form.custMACData);
    setVisible(document.Form.updateType);
    setVisible(document.Form.updateValue);
    document.getElementsByName('updateType2')[0].style.display='none';
    if(document.getElementsByName('updateValue2').length > 0) {
	document.getElementsByName('updateValue2')[0].style.display='none';
    }
    setVisible(document.Form.percent);
    document.Form.updateType.size = '15';
    document.Form.updateType.value = 'Default VAT rate';
    document.Form.updateValue.size = '5';
    document.Form.updateValue.value = document.Form.vat_rate.value;
	document.Form.updateValue.style.width = '300px';
	document.getElementById('hideme').style.display='none';
  }
  else if (action_value == 'update_setup') {
    setHidden(document.Form.list);
    setHidden(document.Form.list1);
    setHidden(document.Form.updateType3);
    setHidden(document.Form.updateValue3);
    setHidden(document.Form.targetEquipLabel);
    setHidden(document.Form.targetEquipList);
    setHidden(document.Form.targetCustLabel);
    setHidden(document.Form.targetCustList);
    setHidden(document.Form.custMACLabel);
    setHidden(document.Form.custMACData);
    setVisible(document.Form.updateType);
    setVisible(document.Form.updateValue);
    document.getElementsByName('updateType2')[0].style.display='none';
    if(document.getElementsByName('updateValue2').length > 0) {
	document.getElementsByName('updateValue2')[0].style.display='none';
    }
    setVisible(document.Form.percent);
    document.Form.updateType.size = '16';
    document.Form.updateType.value = 'Default setup VAT rate';
    document.Form.updateValue.size = '5';
    document.Form.updateValue.value = document.Form.setup_vat.value;
	document.Form.updateValue.style.width = '300px';
	document.getElementById('hideme').style.display='none';
  }
  else if (action_value == 'update_currency') {
    setHidden(document.Form.list);
    setHidden(document.Form.list1);
    setHidden(document.Form.updateType3);
    setHidden(document.Form.updateValue3);
    setHidden(document.Form.targetEquipLabel);
    setHidden(document.Form.targetEquipList);
    setHidden(document.Form.targetCustLabel);
    setHidden(document.Form.targetCustList);
    setHidden(document.Form.custMACLabel);
    setHidden(document.Form.custMACData);
    setVisible(document.Form.updateType);
    setVisible(document.Form.updateValue);
    document.getElementsByName('updateType2')[0].style.display='none';
    if(document.getElementsByName('updateValue2').length > 0) {
	document.getElementsByName('updateValue2')[0].style.display='none';
    }
    setHidden(document.Form.percent);
    document.Form.updateType.size = '14';
    document.Form.updateType.value = 'Default currency';
    document.Form.updateValue.size = '14';
    document.Form.updateValue.value = document.Form.currency.value;
	document.Form.updateValue.style.width = '300px';
	document.getElementById('hideme').style.display='none';
  }
  else if (action_value == 'check_db') {
    setHidden(document.Form.list);
    setHidden(document.Form.list1);
    setHidden(document.Form.updateType3);
    setHidden(document.Form.updateValue3);
    setHidden(document.Form.targetEquipLabel);
    setHidden(document.Form.targetEquipList);
    setHidden(document.Form.targetCustLabel);
    setHidden(document.Form.targetCustList);
    setHidden(document.Form.custMACLabel);
    setHidden(document.Form.custMACData);
    setVisible(document.Form.updateType);
    setVisible(document.Form.updateValue);
    document.getElementsByName('updateType2')[0].style.display='none';
    if(document.getElementsByName('updateValue2').length > 0) {
	document.getElementsByName('updateValue2')[0].style.display='none';
    }
    setHidden(document.Form.percent);
    document.Form.updateType.size = '14';
    document.Form.updateType.value = 'Email address';
    document.Form.updateValue.size = '40';
    document.Form.updateValue.value = document.Form.op_email.value;
	document.Form.updateValue.style.width = '300px';
	document.getElementById('hideme').style.display='none';
  }
  else if (action_value == 'provision_now') {
    setHidden(document.Form.list);
    setVisible(document.Form.list1);
    setVisible(document.Form.updateType);
    setVisible(document.Form.updateValue);
    setVisible(document.Form.updateType3);
    setVisible(document.Form.updateValue3);
    setVisible(document.Form.targetEquipLabel);
    setVisible(document.Form.targetEquipList);
    setVisible(document.Form.targetCustLabel);
    setVisible(document.Form.targetCustList);
    setVisible(document.Form.custMACLabel);
    setVisible(document.Form.custMACData);
    if(document.getElementsByName('updateValue2').length > 0) {
	document.getElementsByName('updateType2')[0].style.display='block';
	document.getElementsByName('updateValue2')[0].style.display='block';
    }
    setHidden(document.Form.percent);
    document.getElementById('hideme').style.display='block';
    document.Form.updateType.size = '22';
    document.Form.updateType.value = 'IP address of SM: ';
    document.Form.updateType2.size = '22';
    document.Form.updateType2.value = 'Provisioning Notes: ';
    document.Form.updateType3.size = '22';
    document.Form.updateType3.value = 'Clear IP traffic';
    document.Form.updateValue.size = '3';
    document.Form.updateValue.value = document.Form.equipment_ip.value;
    document.Form.updateValue.style.width = '60px';
	document.getElementById('nowrapping').nowrap='nowrap';
  }
  else if (action_value == 'check_post') {
    setHidden(document.Form.list);
    setHidden(document.Form.list1);
    setHidden(document.Form.updateType3);
    setHidden(document.Form.updateValue3);
    setHidden(document.Form.targetEquipLabel);
    setHidden(document.Form.targetEquipList);
    setHidden(document.Form.targetCustLabel);
    setHidden(document.Form.targetCustList);
    setHidden(document.Form.custMACLabel);
    setHidden(document.Form.custMACData);
    setVisible(document.Form.updateType);
    setVisible(document.Form.updateValue);
    document.getElementsByName('updateType2')[0].style.display='none';
    if(document.getElementsByName('updateValue2').length > 0) {
	document.getElementsByName('updateValue2')[0].style.display='none';
    }
    setHidden(document.Form.percent);
    document.Form.updateType.size = '14';
    document.Form.updateType.value = 'Email address';
    document.Form.updateValue.size = '40';
    document.Form.updateValue.value = document.Form.op_email.value;
	document.Form.updateValue.style.width = '300px';
	document.getElementById('hideme').style.display='none';
  }
  else {
    setHidden(document.Form.list);
    setHidden(document.Form.list1);
    setHidden(document.Form.updateType3);
    setHidden(document.Form.updateValue3);
    setHidden(document.Form.updateType);
    setHidden(document.Form.updateValue);
    setHidden(document.Form.targetEquipLabel);
    setHidden(document.Form.targetEquipList);
    setHidden(document.Form.targetCustLabel);
    setHidden(document.Form.targetCustList);
    setHidden(document.Form.custMACLabel);
    setHidden(document.Form.custMACData);
    document.getElementsByName('updateType2')[0].style.display='none';
    if(document.getElementsByName('updateValue2').length > 0) {
	document.getElementsByName('updateValue2')[0].style.display='none';
    }
    setHidden(document.Form.percent);
	document.Form.updateValue.style.width = '300px';	
	document.getElementById('hideme').style.display='none';
  }
}

//Display the hidden field on the web page
function setVisible(fieldname) {
  fieldname.style.visibility='visible';
}

//Hide a field
function setHidden(fieldname) {
  fieldname.style.visibility='hidden';
}

function checkFieldUpdate(fieldid,fieldvalue,warningid,warningvalue) {

  if (fieldid) {
    document.getElementById(fieldid).value = fieldvalue;
  }

  if (warningid) {
    document.getElementById(warningid).innerHTML = warningvalue;
    if( document.getElementById(warningid).innerHTML == '') {
      document.getElementById(warningid).style.display = 'none';
    } else {
      document.getElementById(warningid).style.display = 'block';
    }
  }

}

//Remove spaces, carriage return, newline at the beginning and end of a string
function trim(string) {
  return string.replace(/(^\s*)|(\s*$)/g,'');
}

//Round a number with the corresponding scale value
function MM_round(number,scale) {
  var int_part, float_part;

  int_part = Math.floor(number);
  float_part = Math.round((number - int_part) * Math.pow(10, scale));
  if (float_part < 10) float_part = '0' + float_part;

  //alert('amount'+number+' int'+int_part+' float'+float_part);
  return (int_part + '.' + float_part);
}

//Return the current date: DD/MM/YYYY
function today() {
  Today = new Date();
  day = Today.getDate();
  month = (Today.getMonth())+1;
  year = Today.getFullYear();
  return day + "/" + month + "/" + year;
}

//Display a confirm window
function MM_confirmDel(type) {
  var answer = confirm('Are you sure you want to delete this ' + type + ' ?')
  document.MM_returnValue = answer;
}

//Display a confirm window
function MM_confirmAction(action) {
  var answer = confirm(action);
  document.MM_returnValue = answer;
}

//Go to URL
function MM_URL(custUrl) {
	this.location = custUrl;
	document.MM_returnValue = 1;
}

function oneshot() {
	var timer;
	return function( fun, time ) {
		clearTimeout( timer );
		timer = setTimeout( fun, time );
	};
}

var suggestOneshot = oneshot(); 
var timer;

function setDelay( fun, time ) {
	clearTimeout( timer );
	timer = setTimeout( fun, time );
};
String.prototype.compareColor = function(){
    if((this.indexOf("#") != -1 && arguments[0].indexOf("#") != -1) || 
      (this.indexOf("rgb") != -1 && arguments[0].indexOf("rgb") != -1)){
      return this.toLowerCase() == arguments[0].toLowerCase()
    }
    else{
      xCol_1 = this;
      xCol_2 = arguments[0];
      if(xCol_1.indexOf("#") != -1)xCol_1 = xCol_1.toRGBcolor();
      if(xCol_2.indexOf("#") != -1)xCol_2 = xCol_2.toRGBcolor();
      return xCol_1.toLowerCase() == xCol_2.toLowerCase()
    }
  }


  String.prototype.toRGBcolor = function(){
    varR = parseInt(this.substring(1,3), 16);
    varG = parseInt(this.substring(3,5), 16);
    varB = parseInt(this.substring(5,7), 16);
    return "rgb(" + varR + ", " + varG + ", " +  varB + ")";
  }

function MM_valbutton(text, radio) {
	// place any other field validations that you require here
	// validate myradiobuttons
	if (radio.value) {
		if (radio.checked) {
			return true;
		} else {
			alert(text);
			return false;
		}
	} else {

		myOption = -1;
		for (i=radio.length-1; i > -1; i--) {
			if (radio[i].checked) {
				myOption = i; i = -1;
			}
		}
	
		if (myOption == -1  ) {
			alert(text);
			return false;
		} 

		return true;
	}
}

//add maintenance email address to list
function MM_addEmailAddress(){
  var i, m_list, listsize, newEmailAddress;
  newEmailAddress=trim(document.Form.newEmailAddress.value);

if (newEmailAddress) {
      m_list = document.Form.mEmailList.value;
      if (! m_list) listsize = 0;
      else listsize = document.Form.mEmails.length;

      for (i=0; i<listsize; i++) {
        if (document.Form.mEmails.options[i].value == newEmailAddress) {
	        alert('Email address already added !');
	        return;
        }
      }

      document.Form.mEmails.length = listsize + 1;
      document.Form.mEmails.options[listsize].value = newEmailAddress;
      document.Form.mEmails.options[listsize].text = newEmailAddress;
      document.Form.mEmails.options[listsize].selected = true;

      if (! m_list) document.Form.mEmailList.value = newEmailAddress;
      else document.Form.mEmailList.value = m_list + ':::' + newEmailAddress;

      document.Form.newEmailAddress.value = '';
  }
  document.Form.newEmailAddress.focus();
}

//Delete a maintenance email address from list
function MM_deleteEmailAddress() {
  var i,tmp,m_list,sIndex=document.Form.mEmails.selectedIndex;

  m_list = '';
  listsize = document.Form.mEmails.length;
  for (i=0; i<listsize; i++) {
    if (i != sIndex) {
      if (m_list == '') m_list = document.Form.mEmails.options[i].value;
      else {
        tmp = document.Form.mEmails.options[i].value;
        if (tmp) m_list = m_list + ':::' + tmp;
      }
    }
  }
  document.Form.mEmailList.value = m_list;
  document.Form.mEmails.options[sIndex] = null;
}

// ****** Add/delete a row in site detail page
// Add a new row into a table
function MM_insRow() {
  var tbl = document.getElementById('myTable');
  var nextRow = tbl.rows.length;
  var x=tbl.insertRow(nextRow);
	
  var cell_0=x.insertCell(0);
  var uname = document.createElement('input');
    uname.type  = 'textfield';
    uname.value = '';
    uname.name  = 'uname'+ nextRow;
    uname.size  = '12';
  cell_0.appendChild(uname);

  var cell_1=x.insertCell(1);
  var pwd = document.createElement('input');
    pwd.type  = 'textfield';
    pwd.value = '';
    pwd.name  = 'pwd'+ nextRow;
    pwd.size  = '12';
  cell_1.appendChild(pwd);

  var cell_2=x.insertCell(2);
  var note = document.createElement('input');
    note.type  = 'textfield';
    note.value = '';
    note.name  = 'notes'+ nextRow;
    note.size  = '12';
  cell_2.appendChild(note);

  var cell_3=x.insertCell(3);
    var button = document.createElement('input');
    button.type  = 'button';
    button.value = 'Delete';
    button.onclick = function(){MM_deleteRow(this);MM_reOrder();};
  cell_3.appendChild(button);
}

// Re-order the cell-names after clicking 'delete'
function MM_reOrder () {
  var tbl = document.getElementById('myTable');
  var nextRow = tbl.rows.length;
  
  for(var i=1; i<nextRow; i++){
	var x = tbl.rows[i].cells;
	x[0].firstChild.name = 'uname' + i;
	x[1].firstChild.name = 'pwd' + i;
	x[2].firstChild.name = 'notes' + i;
  }  
}

// Delete one row from a table
function MM_deleteRow(r) {
  var i=r.parentNode.parentNode.rowIndex;
  var tbl = document.getElementById('myTable');
  tbl.deleteRow(i);
}

// Equipment page, check username and password are in pairs
function MM_checkPairs () {
  var tbl = document.getElementById('myTable');
  var nextRow = tbl.rows.length;
  var errors = '';
  for(var i=2; i<nextRow; i++) {
	var x = tbl.rows[i].cells;
	var cell_1 = x[0].firstChild.value; // username field
	var cell_2 = x[1].firstChild.value; // password field				
	if( ( cell_1 && (cell_2 == '') ) || ( (cell_1 == '') && cell_2 ) ){
		errors = 'Please enter Username and Password in Pairs\n';
	}
  }
  if(errors) alert(errors);
  document.MM_returnValue = (errors == '');
}

// Site page, check custId, siteId and equipmentId fields
function MM_checkOnlyOne() {
  var cField, sField, eField, errors='';
  cField = document.Form.custId.options[document.Form.custId.selectedIndex].value;
  sField = document.Form.siteId.options[document.Form.siteId.selectedIndex].value;
  eField = document.Form.equipmentId.options[document.Form.equipmentId.selectedIndex].value;
  if( (cField && (sField || eField)) || (sField && (cField || eField)) || (eField && (cField || sField)) ) {
	errors = 'only one field can be chosen between custmer, site and equipment.\n';
  }	
  else if(!cField && !sField && !eField)  {
	errors = 'Please choose at least one field from customer,site and equipement.\n';
  }
  if(errors) alert(errors);
  document.MM_returnValue = (errors == '');
}


function ValidateMandatoryFields()
{
    var args=ValidateMandatoryFields.arguments;
    var errors='';
    for (i=0; i<(args.length-1); i+=2) {
        var field = MM_findObj(args[i]);
        if(field.value!= undefined)
        {
            if(field.value == '') errors+= args[i+1]+' is required.\n';
        }
        else if(field.length != undefined)
        {
            var empty=1;
            for(var j = 0; j < field.length; j++) {
                if(field[j].checked) empty = 0;

            }
            if(empty) errors+= args[i+1]+' is required.\n';
        }
    }
    if(errors) {alert(errors);return false;}
    return true;
}

// Function which fills in field of address (for credit card) when the same as customers address
function MM_theSameAddress( 	adress_1,var_address_1,
				adress_2,var_address_2,
				city,var_city,
				county,var_county,
				zip,var_zip,
				country,var_country,
				state,var_state,
				firstname,var_firstname,
				lastname,var_lastname,
				holder,var_holder,
				id) {

	var checkbox_id = 'CHECK_ADDRESS' + id;
	if (document.getElementById(checkbox_id) && document.getElementById(checkbox_id).checked) { 
		if (document.getElementById(adress_1)) {	
			document.getElementById(adress_1).value=var_address_1;
		}
		if (document.getElementById(adress_2)) {	
			document.getElementById(adress_2).value=var_address_2;
		}
		if (document.getElementById(city)) {	
			document.getElementById(city).value=var_city;
		}
		if (document.getElementById(county)) {	
			document.getElementById(county).value=var_county;
		}
		if (document.getElementById(zip)) {	
			document.getElementById(zip).value=var_zip;
		}
		if (document.getElementById(country)) {	
			document.getElementById(country).value=var_country;
		}
		if (document.getElementById(state)) {	
			document.getElementById(state).value=var_state;
		}
		if (document.getElementById(firstname)) {	
			document.getElementById(firstname).value=var_firstname;
		}
		if (document.getElementById(lastname)) {	
			document.getElementById(lastname).value=var_lastname;
		}
		if (document.getElementById(holder) && document.getElementById(holder).disabled != 't') {	
			document.getElementById(holder).value=var_holder;
		}
	} else {
		if (document.getElementById(adress_1)) {	
			document.getElementById(adress_1).value='';
		}
		if (document.getElementById(adress_2)) {	
			document.getElementById(adress_2).value='';
		}
		if (document.getElementById(city)) {	
			document.getElementById(city).value='';
		}
		if (document.getElementById(county)) {	
			document.getElementById(county).value='';
		}
		if (document.getElementById(zip)) {	
			document.getElementById(zip).value='';
		}
		if (document.getElementById(country)) {	
			document.getElementById(country).value='';
		}
		if (document.getElementById(state)) {	
			document.getElementById(state).value='';
		}
		if (document.getElementById(firstname)) {	
			document.getElementById(firstname).value='';
		}
		if (document.getElementById(lastname)) {	
			document.getElementById(lastname).value='';
		}
		if (document.getElementById(holder) && document.getElementById(holder).disabled != 't') {	
			document.getElementById(holder).value='';
		}
	}
}

function updateCPEfields( element ) {

	var selIndex 		= element.selectedIndex;
	var array_list 		= element.options[selIndex].value;
	var fields		= array_list.split(',');

	document.Form.cpe_bandwidth_package_id.value = fields[0];
	document.Form.incoming_traffic_burst.value = fields[1];
	document.Form.incoming_traffic_limit.value = fields[2];
	document.Form.low_priority_downlink_cir.value = fields[3];
	document.Form.low_priority_uplink_cir.value = fields[4];
	document.Form.outgoing_traffic_burst.value = fields[6];
	document.Form.outgoing_traffic_limit.value = fields[7];

}

function CPEtoolVerification() {

	var array = [document.getElementById('itl'),document.getElementById('otl'),document.getElementById('itb'),document.getElementById('otb'),document.getElementById('lpucir'),document.getElementById('lpdcir')];
//	var itl = document.getElementById('itl');
//	var otl = document.getElementById('otl');
//	var itb = document.getElementById('itb');
//	var otb = document.getElementById('otb');
//	var lpucir = document.getElementById('lpucir');
//	var lpdcir = document.getElementById('lpdcir');

	for (var i in array) {
		if (array[i]) {
			var number 	= parseInt(array[i].value);
		
			if (array[i].value!=''+number) {
				alert('Textfield must contain an integer!');
				return false;
			}
		}
	}
	return true;
}

function populateMaintSubtype(maintType,list) {
	
	var selectObject 	= document.Form.subtype;
	selectObject.length = 1;
	selectObject.options[0].value 	= '';
	selectObject.options[0].text 	= '';
	

	var array 		= new Array();
	array			= list.split('///');
	for (var i = 0; i < array.length; i++) {
		var subArray 	= new Array();
		subArray	= array[i].split(':::');
		for (var j = 0; j < subArray.length; j++) {
			if ( j == 0 ) {
				if ( subArray[j] != maintType ) 
					break;
			} else {
				selectObject.length ++;
				selectObject.options[selectObject.length-1].value 	= subArray[j];
				selectObject.options[selectObject.length-1].text 	= subArray[j];
			}
			
		}
	}
}



function changeCIChargeStatus (pusher,receiver,reason) {
	
	if (pusher && receiver && reason) {
		reason.disabled = true;	

		if (pusher.value == 'azotel' || pusher.value == 'azotel-feature') {
			receiver.value = 'YES';
			receiver.disabled = false;
		
		} else {
			receiver.value = '';
			receiver.disabled = true;
			reason.value = '';	
		}
	}
}

function setAccess(pusher,receiver) {

	if (pusher && receiver) {
		if (pusher.value == 'YES') {
			receiver.disabled = true;
		} else {
			receiver.value = '';
			receiver.disabled = false;	
		}
	}

}

function runAjax(url,loaded)
{
	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function()
	{
		if (this.readyState==4)
		{
			loaded(this.responseText,this.status);
		}
	}
	xmlhttp.open("GET",url,true);
	xmlhttp.send();
}

function getSNMP(param,row,ip,oid,community,basestationid,devicetype,comment,datatype) {
	if (ip == 0) {
		alert ('IP address missing!');
		return;
	}
	if (oid == 0) {
		alert ('SNMP OID missing!');
		return;
	}
	if (community == 0) {
		alert ('SNMP Community String missing!');
		return;
	}
	runAjax('/WIB/form_basestations.pl?snmp=1&ip=' + ip + '&oid=' + oid + '&community=' + community + '&baseid=' + basestationid + '&parameter=' + param + '&devicetype=' + devicetype + '&comment=' + comment + '&datatype=' + datatype,function(result,status){ 
		var checkForError = result.substr(0,5);
		
		if (checkForError == 'ERROR') {
			result = result.substr(5);
			alert(result);
			return;
		}

		if (result) { 
			
			if (row) {
				document.getElementById('okdiv').style.display = 'block';
				document.getElementById(param + row).innerHTML = result;
				setTimeout("document.getElementById('okdiv').style.display = 'none'",'1000');
			}
			else {
				document.getElementById(param).value = result;
			}
			
		} 
	});
}


function validateBank(ban) {
	var agency_code 	= ban.substr(0,4);
	var agency_branch	= ban.substr(4,4);
	var control_digits	= ban.substr(8,2);
	var account_number	= ban.substr(10);

	if (control_digits==CalcControlDigits(agency_code+agency_branch,account_number)) 
	{
		if (document.getElementById('code_branch')){
			document.getElementById('code_branch').value = agency_code+agency_branch;
		}

		if (document.getElementById('account_number')){
			document.getElementById('account_number').value = account_number;
		}

		return 1;
	} 
	else 
	{ 
		alert('Account number is not correct.');
		return 0;
	}

	
}

function CalcControlDigits(Bank, Account)
{
      	Weight= new Array(6,3,7,9,10,5,8,4,2,1);
      	var result ='';
     	var iTemp =0;
	  
      	for (var n=0;n<=7;n++){
         	iTemp  = iTemp + Bank.substr(7 - n, 1) * Weight[n];
      	}
      	result = 11 - iTemp % 11;

      	if (result > 9){
        	result=1-result % 10;
      	}
      	iTemp=0;
      	for (var n=0;n<=9;n++){
         	iTemp  = iTemp + Account.substr(9 - n, 1) * Weight[n];
      	}
      	iTemp =11 - (iTemp % 11);
      	if (iTemp > 9){
       		iTemp =1-(iTemp % 10);
      	}
      	result=result*10+iTemp;
	  
	if (result.toString().length == 1){
	  	result = '0'+result;
	}

      	return(result);
}

function RTexist(ticketType,list)
{
	var array 	= new Array();
	array		= list.split(':::');
	var ok 		= 0;
	for (var i=0; i < array.length; i++) {
		if (ticketType == array[i]) {
			ok = 1;
		}
	}

	if (ok) {
		document.getElementById('infoCell').innerHTML = '';
	} else {
		document.getElementById('infoCell').innerHTML = 'Selected Ticket Type is not defined as an RT queue'; 
	}
	
}


function checkCustomerCoverage(customerid,gpsx,gpsy) {
	
	if (customerid || (gpsx && gpsy)) {
		document.getElementById('coverageText').innerHTML = 'Survey in progress...&nbsp;&nbsp;&nbsp;<img width=25 height=25 src="/Common/Images/loading.gif">';
		runAjax("/WIB/coverageGraph.pl?action=customerBase&customerid="+customerid+"&gpsx="+gpsx+"&gpsy="+gpsy,function(result,status){ 
			
			document.getElementById('coverageText').innerHTML = result;

			if (result == 'Survey failed. Customer out of coverage.') {
				document.getElementById('coverageImage').src = '/Common/Images/red-x.gif'
				document.getElementById('coverageBox').style.borderColor='red';
			} else {
			
				document.getElementById('coverageImage').src = '/Common/Images/camera_test.png'
				document.getElementById('coverageBox').style.borderColor='green';
			}
		});
	}
}

function generateCTR(Action,instance,report) {

	var url = '/WIB/progressBar.pl?action=form477&instance='+instance;
	document.getElementById(report).innerHTML = 'Please wait while action is performed...&nbsp;&nbsp;&nbsp;<img height=25 width=25 src="/Common/Images/loading.gif">&nbsp;&nbsp;&nbsp;<iframe id="progress" src="'+ url+'" scrolling="no" width=150px height=17px style="border:1px transparent solid;" marginheight=0 marginwidth=0 frameborder=0 ></iframe>';
	if (report == 'gps') {
		document.getElementById('report').innerHTML = '';
	} else {
		document.getElementById('gps').innerHTML = '';
	}
	runAjax("/WIB/form_477.pl?action=" + Action + "&instance="+instance,function(result,status){ 
		//document.getElementById('report').innerHTML = result;
		window.location.reload()	
	
	});
	
}

function addTechCode(Text) {

	var opt = document.createElement("option");

	var array = new Array;
	var Value;
	for (var i=0; i < document.getElementById('form477_techcode').options.length; i++) {
		var val = document.getElementById('form477_techcode').options[i].value;
		var char = val.substr(0,1);
		if (char == '0') {
			array.push(parseInt(val.substr(1)));
		}
	}
	array.sort(function(a,b){return b - a});

	

	if (array[0]) {
		var number = array[0]+1;
		Value = '0' + number;
	}
	else {
		Value = '01';
	}

	var conf = confirm("Are you sure you want to add new technology code \"" + Value + " - " + Text + "\" to the database ?"  );

	if (!conf) return;
        // Add an Option object to Drop Down/List Box
        document.getElementById('form477_techcode').options.add(opt);

        // Assign text and value to Option object
	var str =  Value + ' - ' + Text;
        opt.text = str
        opt.value = Value;
	opt.selected = true;

	runAjax("/WIB/form_477.pl?action=addTechCode&text="+str+"&value="+Value,function(result,status){ 
			
	});

}

