/* 
calcCurrency.js  version 1.0.0

		require: 
		dbcore.js.
		calculatortoolbox.js
		dbtoolboxes.js

*/

calcCurrency = {
	jsversion: '1.0.0',
  	init: function() {
  		var Toolbox = CalculatorToolbox;
    	var CoreCompliance=DBcore.getJSversion(DBcore,'1.6.0');
  		var ToolCompliant=DBcore.getJSversion(CalculatorToolbox,'1.11.0');
  		var ErrorCompliant=DBcore.getJSversion(ErrorHandler,'1.1.0');
    		if (CoreCompliance.compliant && ToolCompliant.compliant && ErrorCompliant.compliant) {
  			 Toolbox.calculatorObj=calcCurrency;
  			 Toolbox.listOfTriggers=['calculate','removeCurrencies'];
			 Toolbox.setJShides();
  			 Toolbox.setClickListeners();
  			 Toolbox.setChangeListeners();
  			 Toolbox.setButtonActivation();
  			 Toolbox.setKeydownListeners();
  			 Toolbox.miscInitiations();
			 Toolbox.overwritePrintIcon();
  			}
    },
	
	
	
// is called  - and calls function to delete selected currencies!	
dispLocalValidators: function(field, classFunction, classParams, eventType) {
		var self = calcCurrency;
		var ok = true;
				
		switch (classFunction) {
			case 'removeCurrencies':
			//alert("in val");
			ok=self.handleDeleteCurrencies();
				break;
			case 'calculate':
			//alert("calc");
			ok=self.handleCalculate(field);
			break;
			
			}
		return ok;
		
	},
	
	handleCalculate: function(button) {
		var self=calcCurrency;
		var Toolbox=CalculatorToolbox;
		
		if (Toolbox.fieldsAreValid(button.form)) {
  			
						
			/*if (!self.IsNumericCheck(document.getElementById("currencyAmount").value)) {
				
				var Values = {minimum:1};
				ErrorHandler.showErrorInline("N1","currencyAmount",Values);	
				
				document.getElementById("currencyAmount").innerHTML = '';
				}
			
			else */if (document.getElementById("currencyFromDropDown").value == "-1") {
				var Values = {minimum:0};
				ErrorHandler.showErrorInline("F1","currencyFromDropDown",Values);
			} else if (document.getElementById("currencyToDropDown").value == "-1") {				
				var Values = {minimum:0};
				ErrorHandler.showErrorInline("F1","currencyToDropDown",Values);
			} else if (document.getElementById("currencyFromDropDown").value == document.getElementById("currencyToDropDown").value) {
				var Values = {minimum:0};
				ErrorHandler.showErrorInline("F17","currencyFromDropDown",Values);
			} else { 
				//alert("Omregn " + document.getElementById("currencyAmount").value + " af " + CurrencyValues[document.getElementById("currencyFromDropDown").value]['name'] + " til " + CurrencyValues[document.getElementById("currencyToDropDown").value]['name']);
				
				// run function to calculate output!
				
				// add new list to array currencyResultarray[amountOfCalculations]
				currencyResultarray[amountOfCalculations] = new Array();
				
				// amount of currency 
				currencyResultarray[amountOfCalculations][0] = document.getElementById("currencyAmount").value;
				currencyResultarray[amountOfCalculations][7] = parseFloat(document.getElementById("currencyAmount").value);
				// amount abbr
				currencyResultarray[amountOfCalculations][1] = CurrencyValues[document.getElementById("currencyFromDropDown").value]['abbreviation'];
				// amountTo abbr 
				currencyResultarray[amountOfCalculations][2] = CurrencyValues[document.getElementById("currencyToDropDown").value]['abbreviation'];
				
				
				// midrate to calc with
						if (extendedVersion) {
							
								
									currencyResultarray[amountOfCalculations][3] =  (parseFloat(CurrencyValues[document.getElementById("currencyFromDropDown").value]['buy']) / parseFloat(CurrencyValues[document.getElementById("currencyToDropDown").value]['buy'])) * 100;
						
						
						
						/* 
						// if brandCurrency then use middrate!	
						*/		
									
								
							if(brandCurrency == currencyResultarray[amountOfCalculations][1] || brandCurrency == currencyResultarray[amountOfCalculations][2]) {
								
								// OK		

									currencyResultarray[amountOfCalculations][3] =  (parseFloat(CurrencyValues[document.getElementById("currencyFromDropDown").value]['buy']) / parseFloat(CurrencyValues[document.getElementById("currencyToDropDown").value]['buy'])) * 100;  
									
									
								} else { // NOT BRAND CURRENCY!
									
									currencyResultarray[amountOfCalculations][3] =  (parseFloat(CurrencyValues[document.getElementById("currencyFromDropDown").value]['buy']) / parseFloat(CurrencyValues[document.getElementById("currencyToDropDown").value]['buy'])) * 100;  
									currencyResultarray[amountOfCalculations][8] = parseFloat(CurrencyValues[document.getElementById("currencyFromDropDown").value]['buy']) / 100 * parseFloat(currencyResultarray[amountOfCalculations][7]);
									}
								
						// ------------------------------------
							
							
							} else { // not ext version
						currencyResultarray[amountOfCalculations][3] =  (parseFloat(CurrencyValues[document.getElementById("currencyFromDropDown").value]['buy']) / parseFloat(CurrencyValues[document.getElementById("currencyToDropDown").value]['buy'])) * 100;
							}
					
					
					
				// get the reversed values for nib, nob and sampo
							if (brand == "NIB" || brand == "NOB" || brand == "FI") {
															
								currencyResultarray[amountOfCalculations][3] = 10000 / parseFloat(currencyResultarray[amountOfCalculations][3]);
								
							}
				//------------------------------------------------
				
				// result
						currencyResultarray[amountOfCalculations][4] = parseFloat(currencyResultarray[amountOfCalculations][0])/100 * (parseFloat(currencyResultarray[amountOfCalculations][3]));
						
						
						if (brand == "NIB" || brand =="NOB" || brand == "FI") {
							currencyResultarray[amountOfCalculations][4] = 10000 / parseFloat(currencyResultarray[amountOfCalculations][4]);
						}
				//---------
							
							
				// store result
				currencyResultarray[amountOfCalculations][6] = currencyResultarray[amountOfCalculations][4];
				
				
				// rate to show
						currencyResultarray[amountOfCalculations][5] = 10000 / parseFloat(currencyResultarray[amountOfCalculations][3]);
						//alert(currencyResultarray[amountOfCalculations][5]); // rate
				// ----------------
				
				// decide how to present data based on brand value
						if (brand == "NIB" || brand =="NOB" || brand == "FI") {
						
						currencyResultarray[amountOfCalculations][5] = currencyResultarray[amountOfCalculations][5] / 100;
						currencyResultarray[amountOfCalculations][5] = self.formatter(currencyResultarray[amountOfCalculations][5], 4, ".");
						currencyResultarray[amountOfCalculations][4] = self.formatter(currencyResultarray[amountOfCalculations][4], 2, ".");
						currencyResultarray[amountOfCalculations][0] = self.formatter(currencyResultarray[amountOfCalculations][0], 2, ".");
					
						} else {
							
						currencyResultarray[amountOfCalculations][5] = self.formatter(currencyResultarray[amountOfCalculations][5], 2);
						currencyResultarray[amountOfCalculations][4] = self.formatter(currencyResultarray[amountOfCalculations][4], 2);
						currencyResultarray[amountOfCalculations][0] = self.formatter(currencyResultarray[amountOfCalculations][0], 2);
						}
				//---------------------------------------------------
				
				
				// output function
					if (extendedVersion) {
						currencyJustDeleted = false;
						self.outputFunctionExt();
						amountOfCalculations++; // extended layout for output
						} else {
						self.outputFunction();		// simple layout for output
					}
				//----------------
				
				// count up amountOfCalculations == next pos in currencyResultarray[amountOfCalculations]
				
				//---------------------------------------------------------------------------------------
				
				
			} 
		}
		
		
		
},
	
	// function takes from and to values and produces result!
outputFunctionExt: function() {
		
		var self=calcCurrency; 
		document.getElementById("currencyAmount").value = '';
		
		
				CurrencytableHeader = '<fieldset><ol><li class="currencyHeader">';
				CurrencytableHeader += '<div class="currencyOutputHeader1Ext">&nbsp</div>';
				CurrencytableHeader += '<div class="currencyOutputHeader2Ext">'+resultHeader1+'</div>';
				CurrencytableHeader += '<div class="currencyOutputHeader3Ext">'+resultHeader2+'</div>';
				CurrencytableHeader += '<div class="currencyOutputHeader4Ext">'+resultHeader3+'</div>';
				CurrencytableHeader += '<div class="currencyOutputHeader4Ext">'+brandCurrency+'</div>';
				
				
				
			
			CurrencytableBody = '';
			var totalValue = 0;
			var middleValue = 0;
			
			
			for(o=0; o<currencyResultarray.length; o++) {
			
			
			CurrencytableBody += '<li class="';
			if (o == 0) { CurrencytableBody += ' first';}
			if (o == currencyResultarray.length-1) { CurrencytableBody += ' last';}
			if (o > 0) {CurrencytableBody += ' whitetop';}
			
			CurrencytableBody += '">';
			
			CurrencytableBody += '<div class="currencyResult1Ext"><input type="checkbox" id="currencyLine'+o+'" value="'+o+'" class="expander"/></div>';
			//alert(o);
			CurrencytableBody += '<div class="currencyResult2Ext">'+currencyResultarray[o][0]+ ' ' + currencyResultarray[o][1] + '</div>';
			CurrencytableBody += '<div class="currencyResult3Ext">'+currencyResultarray[o][5] + '</div>';

// runs popupFunction and displays info about rates...
//handleRatePopCurrencies(currencyResultarray[o][5],currencyResultarray[o][1],currencyResultarray[o][2]);

if (currencyResultarray[o][1] == brandCurrency) // from currency = brand
				{
					
					CurrencytableBody += '<div class="currencyResult4Ext">'+currencyResultarray[o][4] + ' ' + currencyResultarray[o][2] +'</div>';
			    CurrencytableBody += '<div class="currencyResult4Ext">';	
					middleValue = currencyResultarray[o][7];
					//alert(middleValue)
					totalValue = parseFloat(totalValue) + parseFloat(middleValue);
					CurrencytableBody += currencyResultarray[o][0] + ' ' + brandCurrency;
					
				} 
				else if (currencyResultarray[o][2] == brandCurrency) // to currency = brand 
				{
					
					CurrencytableBody += '<div class="currencyResult4Ext">&nbsp;</div>';
					CurrencytableBody += '<div class="currencyResult4Ext">';
					middleValue = parseFloat(currencyResultarray[o][6]);
					//alert(middleValue)
					totalValue = parseFloat(totalValue) + parseFloat(middleValue);
					CurrencytableBody += currencyResultarray[o][4] + ' ' + brandCurrency;
					
				}
				else
				{
					
				CurrencytableBody += '<div class="currencyResult4Ext">'+currencyResultarray[o][4] + ' ' + currencyResultarray[o][2] +'</div>';
			    CurrencytableBody += '<div class="currencyResult4Ext">';	
				
				// calculate amount in brand currency and output it!

				middleValue = parseFloat(currencyResultarray[o][8]);

				totalValue = parseFloat(totalValue) + parseFloat(middleValue);
				CurrencytableBody += self.formatter(middleValue, 2) +' '+ brandCurrency;
				
				}


			CurrencytableBody += '</div>';
			//alert(totalValue);
			}
			
			
			//totalValue = self.formatter(totalValue, 2);
			
			CurrencytableBody += '</li><li class="whitetop last"><div class="currencyOutputHeaderResult1Ext">'+totalValueTekst+'</div><div class="currencyOutputHeaderResult2Ext">';
			
			if (brand == "NIB" || brand =="NOB" || brand == "FI") {
			CurrencytableBody += self.formatter(parseFloat(totalValue) ,2 ,".");
				} else {
			CurrencytableBody += self.formatter(parseFloat(totalValue) ,2);
			}
			
			
			CurrencytableBody += ' ' + brandCurrency + '</div>';
			
			CurrencytableFooter = '</li></ol></fieldset>';
			
			CurrencyOutputCode = CurrencytableHeader + CurrencytableBody + CurrencytableFooter;
			
			document.getElementById("currencyResult").innerHTML = CurrencyOutputCode;
	
	
	currencyElement = document.getElementById("delCurrencyButton");
	currencyElement2 = document.getElementById("currencyResult");
	
	
	
	if (currencyResultarray.length == 0) {
	DisplayToolbox.hideElement(currencyElement);
	DisplayToolbox.hideElement(currencyElement2);
	} else {
		
	
	DisplayToolbox.showElement(currencyElement2);
	self.display();
		
		
		}
			
		//document.getElementById("currencyExtDel").innerHTML = '';
	//alert("calc done")

},

display: function(fieldid){
var self=calcCurrency; 
var currencyElement = document.getElementById("delCurrencyButton");
DisplayToolbox.showElement(currencyElement);
window.setTimeout(function() {document.getElementById('delCurrencyButton').style.display="block";},400);
window.setTimeout(function() {document.getElementById('currencyResult').style.display="block";},400);

},

	// function takes from and to values and produces result!
outputFunction: function() {
		
		var self=calcCurrency; 
		
				CurrencytableHeader = '<fieldset><ol><li class="currencyHeader">';
				CurrencytableHeader += '<div class="currencyOutputHeader1">'+resultHeader1+'</div>';
				CurrencytableHeader += '<div class="currencyOutputHeader2">'+resultHeader2+'</div>';
				CurrencytableHeader += '<div class="currencyOutputHeader2">'+resultHeader3+'</div></li>';
			
			
			
			
			
			CurrencytableBody = '<li class="first last">';
						
			CurrencytableBody += '<div class="currencyResult1">'+currencyResultarray[amountOfCalculations][0]+ ' ' + currencyResultarray[amountOfCalculations][1] + '</div>';
			CurrencytableBody += '<div class="currencyResult2">'+currencyResultarray[amountOfCalculations][5] + ' (' + currencyResultarray[amountOfCalculations][1] + '/' + currencyResultarray[amountOfCalculations][2] + ')</div>';
			CurrencytableBody += '<div class="currencyResult2">'+currencyResultarray[amountOfCalculations][4] + ' ' + currencyResultarray[amountOfCalculations][2] +'</div>';
			
			CurrencytableFooter = '</li></ol></fieldset>';
			
			CurrencyOutputCode = CurrencytableHeader  + CurrencytableBody + CurrencytableFooter;
			
			
			
			
			document.getElementById("currencyResult").innerHTML = CurrencyOutputCode;
			
				
},

// return a number with decimaler amount of decimals
formatter: function(tal, decimaler, commafy){

 var self=calcCurrency;
 
 var fudge = 0.0001;
	 tal = parseFloat(tal+"");

	 tal = tal * Math.pow(10,decimaler);
	 tal = Math.round(tal);
	 tal = tal / Math.pow(10,decimaler);

	 tal = tal+fudge;

	var result = "";
 	var slutPotens = 0-decimaler;

 	var potens = Math.floor(Math.log(tal) / Math.log(10));
 
 if (potens < 0){potens = 0;}
 
 
 

 while (potens >= slutPotens) {
 ciffer = Math.floor(tal / Math.pow(10,potens));
 result = result + ciffer;
 if ((potens == 0) && (decimaler > 0)){ if (!commafy) {result = result + ",";} else {result = result + ".";}}
 else if ((potens/3 == Math.floor(potens/3)) && (potens > 0)){if (!commafy) {result = result + ".";} else {result = result + ",";}}
 tal = tal - ciffer*Math.pow(10,potens);
 potens = potens-1;
 }




return result;
},



handleDeleteCurrencies: function() { 

var self=calcCurrency;

	var deleteFromCurrencyList = new Array();
	
	for (var t=0; t<amountOfCalculations; t++) {
				
		if (document.getElementById('currencyLine'+t).checked) {
		//alert(t);
		deleteFromCurrencyList.push(t);
	
		}
			
	}


//alert(deleteFromCurrencyList);

for (var t=deleteFromCurrencyList.length-1; t>=0; t--) {
	//alert(t);
			currencyResultarray.splice(deleteFromCurrencyList[t],1);
		
			amountOfCalculations--;
}

self.outputFunctionExt();


},

IsNumericCheck: function(sText)
{
   var self=calcCurrency;
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
	  if (Char == "" || Char == " ") { IsNumber = false;}
	  else
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
	  
	
	
   return IsNumber;
   
   }






}


// end

DBcore.start(calcCurrency);




