/*
 * Copyright (C) 2006 Baron Schwartz <baron at xaprb dot com>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation, version 2.1.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
 * details.
 *
 * $Id: html-form-input-mask.js,v 1.6 2006-11-03 04:04:29 baron Exp $
 */

/* Set up a global Xaprb object to act as the Xaprb namespace, without colliding
 * with other Xaprb scripts.
 */
if ( typeof(Xaprb) === 'undefined' ) {
   Xaprb = new Object();
}

/* The Xaprb.InputMask object acts as the namespace for input masking
 * functionality.
 */
Xaprb.InputMask = {

   /* Each mask has a format and regex property.  The format consists
    * of spaces and non-spaces.  A space is a placeholder for a value the user
    * enters.  A non-space is a literal character that gets copied to that
    * position in the value.  The regex is used to validate each character, one
    * at a time (it is not applied against the entire value in the form field,
    * just the characters the user enters).
    *
    * The way you name your masks is significant.  If you create a mask called
    * date_us, you cause it to be applied to a form field by a) adding the
    * input_mask class to that form field, which triggers this script to treat
    * it specially, and b) adding the class mask_date_us to the form field,
    * which causes this script to apply the date_us mask to it.
    */
   masks: {
      date_iso: {
         format: '    -  -  ',
         regex:  /\d/
      },
      date_us: {
         format: '  /  /    ',
         regex:  /\d/
      },
      time: {
         format: '  :  :  ',
         regex:  /\d/
      },
      phone: {
         format: '(   )   -    ',
         regex:  /\d/
      },
      ssn: {
         format: '   -  -    ',
         regex:  /\d/
      },
      visa: {
         format: '    -    -    -    ',
         regex:  /\d/
      }
   },

   /* Finds every element with class input_mask and applies masks to them.
    */
   setupElementMasks: function() {
      if ( document.getElementsByClassName ) { // Requires the Prototype library
         document.getElementsByClassName('input_mask').each(function(item) {
            Event.observe(item, 'keypress',
               Xaprb.InputMask.applyMask.bindAsEventListener(item), true);
         });
      }
   },
   

   /* This is triggered when the key is pressed in the form input.  It is
    * bound to the element, so 'this' is the input element.
    */
   applyMask: function(event) {
      var match = /mask_(\w+)/.exec(this.className);
      if ( match.length == 2 && Xaprb.InputMask.masks[match[1]] ) {
         var mask = Xaprb.InputMask.masks[match[1]];
         var key  = Xaprb.InputMask.getKey(event);
		
		if (key >= 96 && key <=105)
            {
              key = key - 48;
            }
        //    var ch      = String.fromCharCode(key);
			
         if ( Xaprb.InputMask.isPrintable(key) ) {
            var ch      = String.fromCharCode(key);
            var str     = this.value + ch;
            var pos     = str.length;
            if ( mask.regex.test(ch) && pos <= mask.format.length ) {
               if ( mask.format.charAt(pos - 1) != ' ' ) {
                  str = this.value + mask.format.charAt(pos - 1) + ch;
               }
               this.value = str;
            }
            Event.stop(event);
         }
      }
   },

   /* Returns true if the key is a printable character.
    */
   isPrintable: function(key) {
      return ( key >= 32 && key < 127 );
   },

   /* Returns the key code associated with the event.
    */
   getKey: function(e) {
      return window.event ? window.event.keyCode
           : e            ? e.which
           :                0; alert(e);
   }
};
function filterNum(str) { if(str=='') str = 0;
re = /^\$|,/g;
// remove "$" and ","
return parseFloat(str.replace(re, ""));
}
function calcACV(){
	
	var percent = $F('AcvPercentage') / 100;  
	var acvalue = filterNum($F('ACV')); 
	var total = (percent * acvalue);
	$('ACVSub').value = formatCurrency(total);
// calcBID	calcGST();
}
function calcBID(){
	
	var percent = $F('GST') / 100;  
	var acvalue = filterNum($F('bidRate')); 
	var total = (percent * acvalue);
	$('GSTTotal').value = formatCurrency(total);
// calcBID	calcGST();
}
function calcPayout(){
	
	var ACVSub = filterNum($F('ACVSub')) ;  
	var acvalue = filterNum($F('bidRate')); 
	var GSTTotal = filterNum($F('GSTTotal')); 
	var total = (ACVSub + GSTTotal + acvalue);// alert(formatCurrency(total));	
	$('ACVPayout').value = formatCurrency(total);
}
function calcStorage(){
	
	var storeDays = $F('StorageDays'); 
	var storage = filterNum($F('Storage')); 
	var total = (storeDays * storage);
	$('StorageTotal').value = formatCurrency(total);
	calcGST();
}
function calcGST(){ 
	
	var StorageTotal = filterNum($F('StorageTotal')); 
	var Towing = filterNum($F('Towing')); 
	var cash = filterNum($F('cash')); 
	var Other = filterNum($F('OtherCharges')); 
	 var LabourGST = filterNum($F('LabourGST')); //  alert(StorageTotal + Towing + Other);
	 var totalGST = ((StorageTotal + Towing + Other) * 0.05) + LabourGST;
	 
	$('TotalGST').value = formatCurrency(totalGST);
	var LabourPST = filterNum($F('LabourPST'));
	var LabourSub = filterNum($F('Labour'));
	
	$('TotalPayout').value = formatCurrency(StorageTotal + Towing + Other + LabourPST + LabourSub + totalGST + cash)
	// */
}
 
function updateVIN(letter) {
    var sitebase = ''; //'/rush/salvage/'; //alert(letter)
			var url=sitebase +"ajaxreturn.php"; //var d = new Date(); // alert(content)
			var pars = "update=vin&letter="+letter; //superID=" + superID + "&content=" + content + "&ajax=true" + "&time=" + d
		//	var myAjax = new Ajax.Request( 'vehicleYear',url, { method: 'post', parameters: pars }  );  
		var myAjax = new Ajax.Request( url, { method: 'post', parameters: pars ,
			
			onSuccess: function(t) {  qs = t.responseText;  $('vehicleYear').value = t.responseText ;
			
				 					//removeOptions('jobIDs',0);
									//var queries = qs.split(/\&/);
									//alert('The VIN letter you entered is not valid. ' + t.responseText);
									if (letter!='')
									if(t.responseText==' ')  alert('The VIN letter you entered is not valid. ' + t.responseText);
									/*for (var i=0; i<queries.length-1; i++) {
											//query = queries[i].split(/\=/);
											//alert(query[0]);
										addOption(queries[i],queries[i],'jobIDs'); 
										}*/
									} 
				//}
					}
				); 
	return; 
}
function updateLetter(year) {
    var sitebase = ''; //'/rush/salvage/'; //alert(letter)
			var url=sitebase +"ajaxreturn.php"; //var d = new Date(); // alert(content)
			var pars = "update=year&year="+year; //superID=" + superID + "&content=" + content + "&ajax=true" + "&time=" + d
		//	var myAjax = new Ajax.Request( 'vehicleYear',url, { method: 'post', parameters: pars }  );  
		var myAjax = new Ajax.Request( url, { method: 'post', parameters: pars ,
			
			onSuccess: function(t) {  qs = t.responseText;  $('VINletter').value = t.responseText;
			
				 				 	//alert('The VIN letter you entered is not valid. ' + t.responseText);
							//		if (letter!='')
							//		if(t.responseText==' ')  alert('The VIN letter you entered is not valid. ' + t.responseText);
								 	} 
				//}
					}
				); 
	return; 
}
function setLabourTax(){
	var LabourSub = filterNum($F('Labour'));  
	$('LabourPST').value = formatCurrency(LabourSub * 0.08);
	$('LabourGST').value = formatCurrency(LabourSub * 0.05);
	calcStorage();
	//alert($F('VINletter') );
	if($F('VINletter')) if($F('VINletter')!='') updateVIN($F('VINletter'));
	else if($F('vehicleYear')!='')   updateLetter($F('vehicleYear')); //updateVIN($F('VINletter') );
}
function setLabourTax2(){
	var LabourSub = filterNum($F('Labour'));  
	$('LabourPST').value = formatCurrency(LabourSub * 0.08);
	$('LabourGST').value = formatCurrency(LabourSub * 0.05);
	calcStorage();
	//alert($F('VINletter') );
}

function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}
