// lang javascript
function round(number, roundTo){
	return Math.round(number*Math.pow(10,roundTo))/Math.pow(10,roundTo);
}
function byid(id)
{
 if (document.getElementById)
  return document.getElementById(id);
 if (document.all)
  return document.all[id];
 if (document.layers)
  return document.layers[id];
 return '';
}

function IsNumeric(sText)

{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;


   for (i = 0; i < sText.length && IsNumber == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsNumber = false;
         }
      }
   return IsNumber;

   }

function tgl(ref,state)
{
 try {
  if (typeof ref=='string')
   ref=byid(ref)
  ref.style['display']=(typeof state!='undefined') ? state :
   ref.style['display']=='none' ? '' : 'none'
 } catch (e) {}
}

function p2f(obj)
{
 if (typeof obj=='string')
 {
  if (!byid(obj))
    return alert(obj)
  obj=byid(obj);
 }
 var price=(typeof obj.value !='undefined') ? obj.value : obj.innerHTML
 if (!price)
  return 0
 price=price.replace(/[^0-9\.\,]/g,'')
 price=price.replace(/,/,'.')
 price=parseFloat(price)
 if (isNaN(price))
   price=0
 return price
}

function f2p(obj,price)
{
 if (typeof obj=='string')
  obj=byid(obj)
 val=Math.floor(price)
 if (isNaN(val))
  val=0
 val=String(val).replace(/,/,'.')
 val=val.replace(/(\d*)(\d{3})/g,'$1 $2')
 val=val+' '+byid('currency').value
 if (obj.value!==undefined)
  obj.value=val;
 else
  obj.innerHTML=val;
}

function calcCosts()
{
 var price=p2f('price')
 var firstPay=p2f('first_pay_cent')/100*price
 f2p('firstPay',firstPay)
 f2p('kaskoCost',p2f('kasko_cent')/100*price)
 var months=p2f('months')
 f2p('fuelCost', p2f('run')/100*p2f('average_fuel')*p2f('fuel_price'))
 f2p('serviceCost',p2f('run')*p2f('service_per_km')*12)
 var resid_cent={6:75,12:70,24:60,36:50,48:40,60:30}
 var r_cent=0
 for (m in resid_cent)
 {
  if (m > months)
   break;
  r_cent=resid_cent[m];
 }
 r_sel=byid('residual_cent');
 r_opt=r_sel.options;
 for (i=0;i<r_opt.length;i++)
 {
  if (r_opt[i].value==r_cent)
  {
    r_sel.selectedIndex=i;
    break;
  }
 }
 f2p('residualSum', p2f(r_sel)/100 * (price-firstPay) )


  if (byid('calc_type').selectedIndex!=0) //fin
  {
   tgl('mileage','none')
   tgl('left_value','none')
   r_sel.selectedIndex=0;
  }
  else //oper
  {
   tgl('mileage','')
   tgl('left_value','')
  }
  var leaseCost=
  (
   (p2f('lease_cent') / 100 / 12) *
   (
    (p2f('price')-firstPay)-
    (
     (p2f('price') * p2f('residual_cent') / 100) / Math.pow( ( p2f('lease_cent') / 100 / 12) + 1, p2f('months') )
    )
   )
   /
   ( 1 - (1 / Math.pow(( p2f('lease_cent') / 100 / 12) + 1, p2f('months') )))
 );
 leaseCost=Math.round(leaseCost);
 f2p('leaseCost',leaseCost);
 f2p('monthlyCost',
  leaseCost+
   ( p2f('kaskoCost')+p2f('octaCost')+p2f('dutyCost')+p2f('serviceCost') )/12+
   p2f('fuelCost')
 )
}

function changePrice(price, plus, currency){
	var currPrice = p2f('priceWithEquipmentTop');
	if (plus)
		currPrice+= price;
  else
		currPrice-= price;
  f2p('priceWithEquipmentTop',currPrice)
	f2p('priceWithEquipmentBottom',currPrice);
  if (byid('price'))//calc
  {
   f2p('price',currPrice)
   calcCosts()
  }
}

function addInputFile(nr){
	var ai = document.getElementById('add_images');
	var newDiv = document.createElement('div');
	var count = document.getElementById('upload_file_count');
	newDiv.innerHTML = '<input id="image_'+nr+'" type="file" onChange="addInputFile('+(nr+1)+')" name="image['+nr+']"/>';
	count.value = nr;
	ai.appendChild(newDiv);
	document.getElementById('image_'+(nr-1)).setAttribute('onChange', 'return false;');
}

function addInputGroupFile(group,nr){
  var ai = document.getElementById('add_images_'+group);
  var newDiv = document.createElement('div');
  var count = document.getElementById('upload_file_count_'+group);
  newDiv.innerHTML = '<input id="image_'+group+'_'+nr+'" type="file" onChange="addInputGroupFile('+group+','+(nr+1)+')" name="image['+group+']['+nr+']"/>';
  count.value = nr;
  ai.appendChild(newDiv);
  document.getElementById('image_'+group+'_'+(nr-1)).setAttribute('onChange', 'return false;');
}


function addInputField(nr, inputName, divId){
	var parentDiv = document.getElementById(divId);
	var newDiv = document.createElement('div');
	newDiv.innerHTML = '<input type="text" name="'+inputName+'['+nr+']" id="'+inputName+'_'+nr+'" onKeyUp="addInputField('+(nr+1)+', \''+inputName+'\', \''+divId+'\')"/>';
	parentDiv.appendChild(newDiv);
	document.getElementById(inputName+'_'+(nr-1)).setAttribute('onKeyUp', 'return false;');
}

function addNewField(nr){
	var ans = document.getElementById('answers');
	var newDiv = document.createElement('div');
	var count = document.getElementById('answerCount');
	newDiv.innerHTML = (nr+1)+'. <input id="answer_'+nr+'" type="text" style="width:300px;" name="answer['+nr+']"/><span id="add_'+nr+'"><a href="#" onClick="addNewField('+(nr+1)+');return false;">&nbsp;+</a></span>';
	count.value = nr+1;
	ans.appendChild(newDiv);
	document.getElementById('answer_'+nr).focus();
	document.getElementById('add_'+(nr-1)).innerHTML = '';
}

function closeModel(id){
	document.getElementById('openModel').style.display='none';
  document.getElementById('model_'+id).style.display='';
}

//calculateCosts
function calculateCosts(){
	var r = ptof('run');
	var afu = ptof('average_fuel_usage');
	var fc = ptof('fuel_cost');
	var p = ptof('price');
	var k = ptof('kasko');
	var sc = ptof('servicing_cost');
	
	var fuel = round(((r/100)*afu*fc),2);
	var kasko = round(((p*k/100)/12),2);
	var octa = ptof('octaCost');
	var duty = ptof('dutyCost');
	var leasing = ptof('monthPay');
	var service = round((r*sc),2);
	var full = round(fuel+service+leasing+kasko+duty+octa,2);
	var suff=' '+byid('currency').value;
	byid('fuelCost').value = fuel+suff;
	byid('serviceCost').value = service+suff;
	byid('leasingCost').value = leasing+suff;
	byid('kaskoCost').value = kasko+suff;
	byid('monthPay').value = full+suff;
}

//calculate Leasing
function calculateLeasing(){
	var p = ptof('price');
	var fp = ptof('first_pay');
	var rv = ptof('residual_value');
	var y = ptof('months')/12;
	var yp = ptof('percentuage');

  //alert(p+' / '+fp+' / '+rv+' / '+y+' / '+yp)

	var first = round(p*fp/100, 2);
	var residual = round(p*rv/100, 2);

  //mp = monthly pay
  if (byid('calc_type').selectedIndex!=0) //fin
  {
    tgl('mileage','none');
    tgl('left_value','none');
    //alert([p,first,yp,y])
		var mp = round(((p-first)+((p-first)*yp/100)*y)/(y*12),2);
  }
  else //oper
  {
    tgl('mileage','');
    tgl('left_value','');
    //alert([p,first,yp,y,residual])
		var mp = round(((p-residual-first)+((p-residual-first)*yp/100)*y)/(y*12),2);
  }
	var brokerage = ptof('brokerage')
	var full = round(mp*y*12+first+brokerage,2);
  var suff=' '+byid('currency').value
	byid('monthPay').value = mp+suff;
	byid('firstPay').value = first+suff;
  if (byid('residualValue'))
 	 byid('residualValue').value = residual+suff;
	byid('fullPay').value = full + suff;
	
	calculateCosts();
}
//clear admin add mark from in dealers
function cancelAddMakeForm(id){
	document.getElementById('addMakeForm_'+id).innerHTML = '';
}

function clearAutoSelects(nrOfComponents){
	var d = document;
	if(d.getElementById('makeId') != null){
		d.getElementById('makeId').value = '';
	}
	if(d.getElementById('modelId') != null){
		d.getElementById('modelId').value = '';
	}
	if(d.getElementById('modificationId') != null){
		d.getElementById('modificationId').value = '';
	}
	if(d.getElementById('equipmentLevelId') != null){
		d.getElementById('equipmentLevelId').value = '';
	}
	if(d.getElementById('eStockId') != null){
		d.getElementById('eStockId').value = '';
	}
	if(nrOfComponents>1){
		for(var i=1;i<=nrOfComponents;i++){
			if(d.getElementById('makeId'+i) != null){
				d.getElementById('makeId'+i).value = '';
			}
			if(d.getElementById('modelId'+i) != null){
				d.getElementById('modelId'+i).value = '';
			}
			if(d.getElementById('modificationId'+i) != null){
				d.getElementById('modificationId'+i).value = '';
			}
			if(d.getElementById('equipmentLevelId'+i) != null){
				d.getElementById('equipmentLevelId'+i).value = '';
			}
			if(d.getElementById('eStockId'+i) != null){
				d.getElementById('eStockId'+i).value = '';
			}
		}
	}
}
function addComment(request, json){
	var newDiv = document.createElement('div');
	newDiv.setAttribute('id', 'comm_'+json[2][1]);
	newDiv.innerHTML = '<div>'+json[0][1]+'</div><p>'+json[1][1]+'</p>';
	document.getElementById('comments').appendChild(newDiv);
	document.getElementById('addCom').reset();
}
function openEditLinks(type, id){
	var el = document.getElementById(type+'_edit_links');
	if(id>0){
		el.style.display = '';
	}else{
		el.style.display = 'none';
	}
}
function checkComparisonSubmit(form){
	var count = 0;
	for(var i = 0; i < form.elements.length; i++){
		if (form.elements[i].checked){
			count++;
		} 
  }
	if(count<4&&count>0){
		return true;
	}
	if(count>3){
		alert('Izvēlieties tikai 3 auto, ko salīdzināt!');
	}
	if(count==0){
		alert('Izvēlieties, kaut vienu auto, ko salīdzināt!');
	}
	return false;
}
function closeMsg(id){
	document.getElementById('open_msg_'+id).style.display = 'none';
}
function uncheckable(object){
	object.checked = true;
}
var busyTO=0;
Ajax.Responders.register
({
onCreate: function() {
 if(byid('busy') && Ajax.activeRequestCount>0)
 {
   tgl('busy','block')
   busyTO=setTimeout("tgl('busy','none');clearTimeout(busyTO)", 10000);
 }
},
onComplete: function() {
 if(byid('busy') && Ajax.activeRequestCount==0)
 {
   tgl('busy','none')
   clearTimeout(busyTO);
 }
}
});