/*
	Created by: Ritesh Tendulkar
	Needs jquery library to be loaded before this
*/

/*
	Represents a fee object
*/	
function Fee(xml){
	// name of the fee
	this.name = $("name",xml).text();
	// base amount on which the fee is applied
	this.amount = parseFloatLocalised($("amount",xml).text());
	// fee amount applicable
	this.feeAmount = parseFloatLocalised($("feeAmount",xml).text());
	// base amount + fee amount
	this.totalAmount = parseFloatLocalised($("totalAmount",xml).text());
}

/*
	type: string : type of fee to query
	amount: string : base amount to apply fee on
	successFunction: function: function to execute when the query is complete
*/
function getFee(type,amount,successFunction,programmeInstance){
		var dataString = 'name='+ type +'&amount='+ amount + '&programmeInstance=' + programmeInstance ;
	$.ajax({
	type: "POST",
	url: "fees.htm",
	data: dataString,
	success: function(msg){
		if(jQuery.isFunction(successFunction)){
			successFunction.call(this,new Fee(msg));
		}
	}});
}

/*
	provider: string : type of provider to query
	cashCurrency: string : requested cash currency	
*/
function getDenomination(provider, cashCurrency, amount, successFunction){

	var dataString = 'provider='+ provider +'&currency='+ cashCurrency  + '&amount=' + amount;
	
	$.ajax({
		type: "POST",
		url: "denomination.htm",
		data: dataString,
		success: function(msg){
		if(jQuery.isFunction(successFunction)){
			successFunction.call(this,msg);
		}
	}});
}


/*
	Represents a fx rate object
*/
function Rate(offer,fromCurrency,toCurrency,rate){
	this.offer = offer;
	this.fromCurrency = fromCurrency;
	this.toCurrency = toCurrency;
	this.rate = rate;
}


/*
	Represents a fx rate provider object
*/
var allRates = null;
function Provider(xml){
	this.name = $("name",xml).text();
	allRates = new Array();
	this.allRates = allRates;

	$("rate",xml).each(function(index, rate){
							allRates[index] = new Rate(
													$("offer",rate).text(),
													$("fromCurrency",rate).text(),
													$("toCurrency",rate).text(),
													$("value",rate).text()
													);
												});
}

/*
	Represents all fx rate providers in the system
*/
var providers = null;
function Rates(xml){
	this.lastUpdated = $("lastUpdated",xml).text();
	this.locale = $("locale",xml).text();
	providers = new Array();
	this.providers = providers;

	$("provider",xml).each(function(index, provider){
						   		providers[index] = new Provider(provider);
						   	});
}


// Mew comparison objects
function ComparisonItem(xml){
	this.providerId = $("provider_id",xml).text();
	this.providerName = $("name",xml).text();
	this.ownData = $("own_data",xml).text();
	this.rate = $("rate",xml).text();
	this.fxUplift = $("fx_uplift",xml).text();

	this.atmPercent = $("atm_percent",xml).text();
	this.atmMin = $("atm_min",xml).text();
	this.atmMax = $("atm_max",xml).text();

	this.posPercent = $("pos_percent",xml).text();
	this.posMin = $("pos_min",xml).text();
	this.posMax = $("pos_max",xml).text();
}


var comparisonItems = null;
function Comparison(xml){
	this.type = $("type",xml).text();
	this.fromCurrency = $("from_currency",xml).text();
	this.toCurrency = $("to_currency",xml).text();

	this.lastUpdated = $("last_updated",xml).text();
	this.locale = $("locale",xml).text();
	comparisonItems = new Array();
	$("item",xml).each(function(index, item_xml){
							comparisonItems[index] = new ComparisonItem(item_xml);
					   });
					   
	this.items = comparisonItems;
}



// utility function to get querystring parameters
function getQueryParameter(paramName){
	var queryString =  location.search.substring(1);
	var varPairs = queryString.split("&");
	for(var i=0;i<varPairs.length;i++){
		var data = varPairs[i].split("=");
		var argName =  data[0];
		var argValue =  data[1];
	
		// check if we have refcode
		if(argName == paramName){
			return argValue;
		}
	}
}

// document upload related functions

// handle for the upload document child window
var docUploadWindow;

var textUploadDocument;
var textUploadAnotherDocument;
var textRemoveDocument;

/**
	opens a window for uploading a document
*/
function addDocument(){
	docUploadWindow=window.open ("upload_document.htm", "docUploadWindow","location=0,status=0,scrollbars=0,width=475,height=350");
	if (docUploadWindow.opener == null) {
		docUploadWindow.opener = self;
    }
	
	fixUploadText();

	return false;
}

/**
	updates the list of uploaded documents
*/
function updateDocumentList(docId, docFileName){
	var docIdsField = document.getElementById("docIds");
	if (docIdsField.value == ""){
		docIdsField.value =docId;
	}else {
		docIdsField.value = docIdsField.value + ','+ docId;
	}

	for (i = 0 ; i < 5; i ++ ){
		var docElement = document.getElementById("lidoc" + i);
		if (docElement.innerHTML.replace(/^\s+|\s+$/g, '') == ""){
			// the element may be removed, re-add it
			docElement.innerHTML = docFileName + "&nbsp;&nbsp;" 
								+ "<a href=\"#\" onclick=\"return removeDocument('doc" + i + "'," + docId + ");\">" + textRemoveDocument + "</a>";
		}

		if (docElement.style.display == "none"){
			// the element was hidden, so show it
			docElement.style.display = "block";
			break;
		}
	}
	
	fixUploadText();
}

/* Updates the list of uploaded documents so that the document is marked for removal. The actual removal will
happen when the form is submitted.
*/
function removeDocument(id,docId){

	var docIdsField = document.getElementById("docIds");
	// -ve representing document to be removed
	var allIds =  docIdsField.value.split(",");
	for (j = 0 ; j < allIds.length; j++){
		if (allIds[j] == docId){
			allIds[j] = '-' +docId;
			break;
		}
	}

	docIdsField.value = allIds.join();

	var liDocElement = document.getElementById("li" + id);
	liDocElement.innerHTML = "";
	liDocElement.style.display = "none";

	fixUploadText();

	return false;
}

/**
	Updates the upload text to correctly refelct the current state
*/
function fixUploadText() {
	var noOfDocsShown = 0;

	var atLeastOneDoc = false;
	for (i = 0 ; i < 5; i ++ ){
		var docElement = document.getElementById("lidoc" + i);
		if (docElement.style.display != "none"){
			noOfDocsShown++;
		}
	}

	var textToShow = "";
	if (noOfDocsShown == 0) {
		textToShow = textUploadDocument;
	}else if (noOfDocsShown > 0  && noOfDocsShown < 5) {
		textToShow = textUploadAnotherDocument;
	} else {
		// no text to display
	}

	document.getElementById("upload_doc_cmd").innerHTML = textToShow;
}

// locale aware handling
var currentLocale;
function Locale(identifier){
	this.id = identifier;
	
	var locales = {
					"en": [".",","],
					"de": [",","."],
					"fr": ["."," "]
				  };
	
	this.decimalSeparator = locales[identifier][0];
	this.thousandSeparator = locales[identifier][1];
}

function setLocale(identifier){
	// expect identifieer to be just language identifier
	currentLocale = new Locale(identifier);
} 

Number.prototype.toFixedLocalised = function(precision){
	var retVal = this.toFixed(precision);
	if (!currentLocale){
		return retVal;
	}
	
	// if currentLocale is defined, replace . with decimal placeholder
	// and 
	retVal = retVal.replace(".","<decimal>");
	retVal = retVal.replace(",","<thousand>");
	retVal = retVal.replace("<decimal>",currentLocale.decimalSeparator);
	retVal = retVal.replace("<thousand>",currentLocale.thousandSeparator);

	return retVal;
}

/**
 * Adds thousand separators. toFixedLocalised will only format the decimal part
 * of a number.
 */
Number.prototype.toFixedFullyLocalised = function(precision){
	var retVal = this.toFixed(precision);
	if (!currentLocale){
		return retVal;
	}
	retVal = addCommas(retVal);
	retVal = retVal.replace(".","<decimal>");
	retVal = retVal.replace(",","<thousand>");
	retVal = retVal.replace("<decimal>",currentLocale.decimalSeparator);
	retVal = retVal.replace("<thousand>",currentLocale.thousandSeparator);

	return retVal;
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

/*
	Parses string to float keeping in mind different thousand separator 
	on the current locale. If the current locale is not selected it will
	only use global parseFloat(String), in which case resulting number may be
	a NaN.
*/
function parseFloatLocalised(string2Parse){
	
	if (currentLocale){
		//remove thousandSeparator
		var retValStr = string2Parse.replace(currentLocale.thousandSeparator,'');
		// replace decimal placeholder with.
		retValStr = retValStr.replace(currentLocale.decimalSeparator,"<decimal>");
		retValStr = retValStr.replace("<decimal>",".");
		
		string2Parse = retValStr;
	}
	
	return parseFloat(string2Parse);
}


function getCurrencySymbol(currencyCode){

	if(currencyCode == "GBP")
		return '&pound;'
	else if(currencyCode == "USD")
		return '&#36;';
	else if(currencyCode == "EUR")
		return '&euro;'
}



//from quirksmode.org
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toUTCString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


function init()
{
	$("form input, form select").live('keypress', function (e) {
				if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
						submitForm();
						return false;
					} else {
						return true;
				}
			});				
}				

function submitForm()
{
}				

