	var timer;
	var timer2;
	var timer3;
	var sec = 700;
	var loading_image_tag 	= '<img src="images/loading.gif"/>';
	var loading_image 		= 'images/loading.gif';
	var equal_image	  		= 'images/bg-converter-form.gif';
	var from_sign_id	  	= 'fr_sign';
	var to_sign_id	  		= 'to_sign';
	var from_amount_id	  	= 'fr_amount';
	var to_amount_id	  	= 'to_amount';
	var range_date_oanda	= '';
	
	Event.observe(window, 'load', function() {
		
		var currencyChoices = $$('div.currency-choices');
		var afrom = $$('div.convert-fr a');
		var ato = $$('div.convert-to a');
		var dp = $$('#input-calendar');
		var emdate = $$('#em-date');

		$$('div.currency-choices').invoke('hide');
		show_currency_list('Major');
		fetch_convertion(to_amount_id);
		fill_pocket_guide();
		
		new Ajax.AutocompleterCustom('fr_currency_type', "fr-currency-type-choices", "process/autocomplete.php", {paramName: "str", hdnAutoSuggest: "hdn_from_autoselect", minChars: 1,json: 'matches',afterUpdateElement:autocomplete_currency});
		new Ajax.AutocompleterCustom('to_currency_type', "to-currency-type-choices", "process/autocomplete.php", {paramName: "str", hdnAutoSuggest: "hdn_to_autoselect", minChars: 1,json: 'matches',afterUpdateElement:autocomplete_currency});
		

		$$('a.close').each(function (el) {
			$(el).observe('click', function(ev)
			{
				currencyChoices.invoke('hide').invoke('removeClassName','from').invoke('removeClassName','to');
				ato.invoke('addClassName','show-currencies');
				afrom.invoke('addClassName','show-currencies');
				ev.preventDefault();
				$('fd-but-dp-1').show();
			});
		});
		//FROM
		afrom.each(function (el) {
			$(el).observe('click', function(ev)
			{
				var elem = $(this);
				if ( elem.hasClassName('show-currencies') ) {
					elem.removeClassName('show-currencies');
					ato.invoke('addClassName', 'show-currencies').invoke('show');
					currencyChoices.invoke('removeClassName', 'to').invoke('addClassName', 'from').invoke('show');
					$('fd-but-dp-1').hide();
				} else {
					elem.addClassName('show-currencies');
					currencyChoices.invoke('hide').invoke('removeClassName','from');
					$('fd-but-dp-1').show();
				}
				ev.preventDefault();
			});
		});
		//TO
		ato.each(function (el) {
		  return $(el).observe('click', function(ev) 
		  {
			   var elem = $(this);
			   if ( elem.hasClassName('show-currencies') ) {
				elem.removeClassName('show-currencies');
				afrom.invoke('addClassName','show-currencies');
				currencyChoices.invoke('removeClassName','from').invoke('addClassName','to').invoke('show');
				$('fd-but-dp-1').hide();
			   } else {
				elem.addClassName('show-currencies');
				currencyChoices.invoke('hide').invoke('removeClassName','to');
				$('fd-but-dp-1').show();
			   }
				ev.preventDefault();
		  });
		 });

		 //HELP
		$$('div.c-help a').each(function (el) {
		  return $(el).observe('click', function(ev) {
		   var help = $$('div.c-help span');
		   var div = $$('div.tooltip');
			if (div.invoke('hasClassName','hidden')[0] == true ) {
				help.invoke('update','Hide Help using this Converter');
			} else {
				help.invoke('update','Show Help using this Converter');
			}
			div.invoke('toggleClassName','hidden');
			ev.preventDefault();
		  });
		 });

		//SELECT FROM CURRENCY
		 $$('div.cc-header li').each(function (el) {
		  return $(el).observe('click', function(ev) {
		   
			$('selected_currecy').innerHTML = '<div style="width:100%;text-align:center;">'+ loading_image_tag +'</div>';
			var findLetters = (ev.target.innerHTML != '') ? ev.target.innerHTML : 'Major';
			//remove active classname from previous and add active to selected/clicked
			$$('li.active').invoke('removeClassName','active');
			var elt = Event.findElement(ev, 'li');
			  if (elt != document)
				$(elt).addClassName('active');
				
				show_currency_list(findLetters);
				ev.preventDefault();
		  });
		 }); 
		 
		//ONKEYUP CONVERT
		$$('div.convert-fr .amnt').each(function (el) {
			$(el).observe('keyup', function(e) {
				var KeyCode = (e.keyCode) ? e.keyCode : e.which;
				this.value = this.value.split(' ').join('');
				
				if( KeyCode != 190 && KeyCode != 48 && this.value != "")
					this.value = parseFloat(this.value);
				
				if(this.value.indexOf('.') != this.value.lastIndexOf('.'))
					this.value = parseFloat(this.value);
				
				if(this.value != '')
				{	clearTimeout(timer);
					timer = window.setTimeout(function() { fetch_convertion(to_amount_id); }, sec);
				}
			});
		});
		//ONKEYUP AMOUT TO INPUTBOX
		$$('div.convert-to .amnt').each(function (el) {
			$(el).observe('keyup', function(e) {
				var KeyCode = (e.keyCode) ? e.keyCode : e.which;
				this.value = this.value.split(' ').join('');
				
				if( KeyCode != 190 && KeyCode != 48 && this.value != "")
					this.value = parseFloat(this.value);
				
				if(this.value.indexOf('.') != this.value.lastIndexOf('.'))
					this.value = parseFloat(this.value);
				
				if(this.value != '')
				{	clearTimeout(timer);
					timer = window.setTimeout(function() { fetch_convertion(from_amount_id); }, sec);
				}
			});
		});
		
		$('fr_currency_type').observe('focus', function(){
			$('fr_currency_type').select();
			clearTimeout(timer2);
		});
		$('to_currency_type').observe('focus', function(){
			$('to_currency_type').select();
			clearTimeout(timer3);
		});

		$('fr_currency_type').observe('blur',function(){
			timer2 = window.setTimeout(function(){ 
			var hdnFromAutoselect = $('hdn_from_autoselect');
			addBgColortoCurrency('fr_currency_type','0');
				if(hdnFromAutoselect.value == $('fr_currency_type').value){}
				else if(hdnFromAutoselect.value != '' && $('hdn_from_stats').value == '0'){	
					var val = autocomplete_currency('',hdnFromAutoselect.value);
					$('fr_currency_type').value = val;
					$('hdn_from_autoselect').value = val;
					addBgColortoCurrency('fr_currency_type','0');
					fill_pocket_guide();
					fetch_convertion(to_amount_id); 
				}
				else if($('hdn_from_stats').value == '1'){addBgColortoCurrency('fr_currency_type','1');}
				else{ addBgColortoCurrency('fr_currency_type','1');}
			},sec + 300);	
		});
		$('to_currency_type').observe('blur', function(){
			timer3 = window.setTimeout(function(){ 
				var hdnToAutoselect = $('hdn_to_autoselect');
				addBgColortoCurrency('to_currency_type','0');
				if(hdnToAutoselect.value == $('to_currency_type').value){}
				else if(hdnToAutoselect.value != '' && $('hdn_to_stats').value == '0'){	
					var val = autocomplete_currency('',hdnToAutoselect.value);
					$('to_currency_type').value = val;
					$('hdn_to_autoselect').value = val;
					addBgColortoCurrency('to_currency_type','0');
					fill_pocket_guide();
					fetch_convertion(to_amount_id); 
				}
				else if($('hdn_to_stats').value == '1'){ addBgColortoCurrency('to_currency_type','1');}
				else{ addBgColortoCurrency('to_currency_type','1');}
			},sec + 300);
		});
		
	});//END MAIN

	/**
	  *	Sends request to the provider
	  *	For convertion of the given amount according to the valid currencies selected 
	  *
	  *	param     string (element's id)
	  */
	function fetch_convertion(id)
	{	
		var fr_amount;
		var fr_cur_type;
		var to_cur_type;
		var sel_date = $('dp-1').value;
		var temp_fr_cur_type = $('fr_currency_type').value;
		var temp_to_cur_type = $('to_currency_type').value;
		//get the to_amount value
		if(id == from_amount_id)
		{	fr_amount = $(to_amount_id).value;
			fr_cur_type = temp_to_cur_type;
			to_cur_type = temp_fr_cur_type;
		}
		else
		{	fr_amount = $(from_amount_id).value;
			fr_cur_type = temp_fr_cur_type;
			to_cur_type = temp_to_cur_type;
		}
		
		if(id != '' && fr_amount != '' && fr_amount != 0 && fr_cur_type != '' && to_cur_type != '' )
		{
			fr_cur_type = stripCurrencyGetCode(fr_cur_type);
			to_cur_type = stripCurrencyGetCode(to_cur_type);
			addBgColortoCurrency('fr_currency_type','0');
			addBgColortoCurrency('to_currency_type','0');
			addBgColortoCurrency(from_amount_id,'0');
			addBgColortoCurrency(to_amount_id,'0');
			$$('div.converter-forms').invoke('setStyle','background-image:url('+ loading_image +');');
			var param = '?sel_date='+ sel_date + '&fr_amount=' + fr_amount + '&fr_cur_type=' + fr_cur_type + '&to_cur_type=' + to_cur_type;
			var url = 'process/convert_currency.php' + param;
				new Ajax.Request(url, {
				  method: 'get',
				  onSuccess: function(response) {
						var fr_sign;
						var to_sign;
						var data = response.responseText.evalJSON();
						if(data.error == 0)
						{
							$(id).value = data.ask;
							if(id == from_amount_id)
							{	
								$(from_sign_id).innerHTML = data.to_sign;
								$(to_sign_id).innerHTML = data.fr_sign;
								$('to_sign_desc').innerHTML = data.fr_cur_type.toUpperCase(); 
								$('fr_sign_desc').innerHTML = data.to_cur_type.toUpperCase();

							}
							else
							{	
								$(from_sign_id).innerHTML = data.fr_sign;
								$(to_sign_id).innerHTML = data.to_sign;
								$('fr_sign_desc').innerHTML = data.fr_cur_type.toUpperCase(); 
								$('to_sign_desc').innerHTML = data.to_cur_type.toUpperCase();
								$('to_amt_desc').innerHTML = data.ask_base;
								//fill_pocket_guide(data.fr_currency,data.to_currency,data.to_guide,data.from_guide)
							} 
						
							//FOR oanda current date
							if(range_date_oanda == '')
							{	$('show_date').innerHTML = data.formatted_date_oanda;
								$('pocket_guide_date').innerHTML = data.formatted_date_oanda;
								$('dp-1').value = data.formatted_date_oanda;
							}
						if(range_date_oanda == '' && data.range_date_oanda != '')
							range_date_oanda = data.range_date_oanda;
														
						}
						else if(data.error == 1)
						{
							addBgColortoCurrency('fr_currency_type','0');
							addBgColortoCurrency('to_currency_type','0');
							addBgColortoCurrency(from_amount_id,'0');
							addBgColortoCurrency(to_amount_id,'0');
							if(data.from == 1)
							{	addBgColortoCurrency('fr_currency_type','1'); }
							if(data.to == 1)
							{	addBgColortoCurrency('to_currency_type','1'); }
						}
						$$('div.converter-forms').invoke('setStyle','background-image:url('+ equal_image +');');
				  }
				});
		}
		else if(fr_amount == 0){
			if(id == from_amount_id){ 
				addBgColortoCurrency(to_amount_id,'1');
			}
			else if(id == to_amount_id){
				addBgColortoCurrency(from_amount_id,'1');
			}
			
		}
	}
	
	/**
	  *	Sends request to the provider
	  *	It is for placing contents on the pocket guide table
	  *
	  */
	function fill_pocket_guide()
	{
		$('pg_loading').removeClassName('hidden');
		$('pg_wrapper').addClassName('hidden');
		
		var sel_date 			= $('dp-1').value;
		var fr_currency_type	= $('fr_currency_type').value;
		var to_currency_type	= $('to_currency_type').value;
		$('pg_first_currency').innerHTML = fr_currency_type;
		$('pg_second_currency').innerHTML = to_currency_type;
		if(fr_currency_type != '' && to_currency_type != '')
		{	
			fr_currency_type = stripCurrencyGetCode(fr_currency_type);
			to_currency_type = stripCurrencyGetCode(to_currency_type);
			var param = '?sel_date='+ sel_date + '&fr_cur_type=' + fr_currency_type + '&to_cur_type=' + to_currency_type;
			var url = 'process/pocket_guide.php' + param;
				new Ajax.Request(url, {
				  method: 'get',
				  onSuccess: function(response) {

					var data = response.responseText.evalJSON();
					if(data.error == 0){
						
						addBgColortoCurrency('fr_currency_type','0');
						addBgColortoCurrency('to_currency_type','0');
						
						$('collection').value = response.responseText;
						var first_symbol 		= data.from_symbol;
						var second_symbol 		= data.to_symbol;
						for(x=0;x < 7; x++)
						{
							if(data.from_guide[x] != undefined)
							{
								$('pg_first['+x+']').innerHTML =  first_symbol + ' ' + data.from_guide[x].result;
								$('pg_first_val['+x+']').innerHTML = second_symbol + ' ' + data.from_guide[x].value;
							}
							else
							{
								$('pg_first['+x+']').innerHTML = first_symbol;
								$('pg_first_val['+x+']').innerHTML = second_symbol;
							}
							if(data.to_guide[x] != undefined)
							{
								$('pg_second['+x+']').innerHTML = second_symbol + ' ' + data.to_guide[x].result;
								$('pg_second_val['+x+']').innerHTML = first_symbol + ' ' + data.to_guide[x].value;
							}
							else
							{
								$('pg_second['+x+']').innerHTML = first_symbol;
								$('pg_second_val['+x+']').innerHTML = second_symbol;
							}
						}
						$('pg_loading').addClassName('hidden');
						$('pg_wrapper').removeClassName('hidden');
					}
					else{
						addBgColortoCurrency('fr_currency_type','0');
						addBgColortoCurrency('to_currency_type','0');
						addBgColortoCurrency(from_amount_id,'0');
						addBgColortoCurrency(to_amount_id,'0');
						$('pg_loading').addClassName('hidden');
						$('pg_wrapper').removeClassName('hidden');
						if(data.err_from == '1'){ addBgColortoCurrency('fr_currency_type','1');	}
						if(data.err_to == '1'){ addBgColortoCurrency('to_currency_type','1');	}
					}
				  }
				});
			
		}
	}
	/**
	 *	Add background color to currency type
	 *	params id (element id )
	 *	params type (0: success, 1: error)
	*/
	function addBgColortoCurrency(id,type)
	{
		if(type == 0)
		{
			$(id).removeClassName('error-field');
			$(id).addClassName('success-field');
		}
		else if(type == 1)
		{
			$(id).removeClassName('success-field');
			$(id).addClassName('error-field');
		}
	}

	/**
	  *	It is for making popup window when the link "Print" is clicked
	  */
	function print_pocket_guide(ev)
	{
		var url = 'guide.html';
		window.open(url,'popupWindow','toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=yes,copyhistory=no,width=550px,height=400px,screenX=350,screenY=150,top=150,left=250');
		if(ev.preventDefault) {
			ev.preventDefault();
		} else {
		 ev.returnValue = false; // IE branch
		}
	}
	
	/**
	  *	This is to set the highest date in the calendar
	  *	It gets the OANDA's most recent date
	  *
	  *	param     obj
	  */
	function modify_date_range(obj)
	{
		if(range_date_oanda != "")
			datePickerController.setRangeHigh(obj.id,range_date_oanda);
	}
	
	/**
	  *	Upon selecting a currency from the list (Major, A,B,D-f etc.)
	  *	It will automatically fill the currency input box (FROM and TO)
	  *	
	  *	param     string
	  */
	function select_currency_type(val,ev)
	{
		var currencyChoices = $$('div.currency-choices');
		var afrom 			= $$('div.convert-fr a');
		var ato 			= $$('div.convert-to a');
		var temp 			= val.split('-');
		var value			= temp[0];
		
		$('fr_currency_type').removeClassName('error-field');
		$('fr_currency_type').addClassName('success-field');
		$('to_currency_type').removeClassName('error-field');
		$('to_currency_type').addClassName('success-field');
		
	   if ( currencyChoices.invoke('hasClassName','from') == 'true') {
			$('fr_currency_type').value = value;
			$('hdn_from_autoselect').value = value;
			set_currency_sign(from_sign_id,val);
			
		}
	   else if ( currencyChoices.invoke('hasClassName','to') == 'true') {
			$('to_currency_type').value = value;
			$('hdn_to_autoselect').value = value;
			set_currency_sign(to_sign_id,val);
		}
		fetch_convertion(to_amount_id);
		fill_pocket_guide();
		currencyChoices.invoke('hide').invoke('removeClassName','from').invoke('removeClassName','to');
		ato.invoke('addClassName','show-currencies');
		afrom.invoke('addClassName','show-currencies');
		if(ev.preventDefault) {
			ev.preventDefault();
		} else {
		 ev.returnValue = false; // IE branch
		}
		$('fd-but-dp-1').show();
	}

	/**
	  *	Upon selecting a  currency from the list (Major, A,B,D-f etc.)
	  *	it automatically set the currency symbol 
	  *	If the symbol is not available, it will just take the currency code
	  *
	  *	param     string (element's id)
	  *	param     string (US Dollar (USD)-$) format
	  */
	function set_currency_sign(id,whole_currency)
	{	
		var signs = whole_currency.split('-');
		
		if(signs[1] == undefined || signs[1] == '')
		{
			var temp 	= whole_currency.split('(');
			temp 		= temp[1].split(')');
			sign		= temp[0];
		}
		else
		{	sign = signs[1];}
		
		$(id).innerHTML = sign;
	}
	/**
	  *	Split the "Currency (CODE)" format and return only the CODE
	  *
	  *	param     string
	  *	return    string
	  */
	function stripCurrencyGetCode(whole_currency)
	{
		var codes 	= whole_currency.split('(');
		if(codes.length > 2 && codes[2] != '')
		{	
			codes[1] = codes[2];
		}
	
		var code;
		var temp;
		if(codes[1] == undefined || codes[1] == '')
		{	
			code = codes[0];
		}
		else
		{	temp	= codes[1].split(')');
			code	= temp[0];
		}
	
		return code;
	}
	
	/**
	  *	Create a span element, used by calendar
	  *
	  *	param     obj
	  */
	function createSpanElement(argObj) {
		// Make sure the span doesn't exist already
		if($("EnglishDate")) return;

		// create the span node dynamically...
		var spn = document.createElement('span');
			p   = $(argObj.id).parentNode;
		
		spn.id = "EnglishDate";
		p.parentNode.appendChild(spn);
		
		// Remove the bottom margin on the input's wrapper paragraph
		p.style.marginBottom = "0";
		
		// Add a whitespace character to the span
		spn.appendChild(document.createTextNode(String.fromCharCode(160)));
	};
	/**
	  *	It is for displaying more readable date
	  *	 upon selecting a specific date from calendar
	  *	
	  *	param     obj
	  */
	function showEnglishDate(argObj) {
			// Grab the span & get a more English-ised version of the selected date
			var spn = $("show_date"),
				formattedDate = datePickerController.printFormattedDate(argObj.date, "d-sp-F-sp-Y", false);
			
			// Make sure the span exists before attempting to use it!
			if(!spn) {
					createSpanElement(argObj); 
					spn = $("show_date");
			};
			var pocketSpn = $("pocket_guide_date");
			// Note: The 3rd argument to printFormattedDate is a Boolean value that 
			// instructs the script to use the imported locale (true) or not (false)
			// when creating the dates. In this case, I'm not using the imported locale
			// as I've used the "S" format mask, which returns the English ordinal
			// suffix for a date e.g. "st", "nd", "rd" or "th" and using an
			// imported locale would look strange if an English suffix was included
			
			// Remove the current contents of the span
			while(spn.firstChild) spn.removeChild(spn.firstChild);
			while(pocketSpn.firstChild) pocketSpn.removeChild(pocketSpn.firstChild);
			
			// Add a new text node containing our formatted date
			spn.appendChild(document.createTextNode(formattedDate));
			pocketSpn.appendChild(document.createTextNode(formattedDate));
			fetch_convertion(to_amount_id);
			fill_pocket_guide();
	};
	
	/**
	  *	Currency that is selected from the autocomplete is then managed here
	  *	It formats the chosen value into this US Dollar (USD)
	  *	
	  *	param     string (element's id)
	  *	param     obj
	  */
	function autocomplete_currency(id,obj)
	{	
		var val = (id == '' ) ? obj : obj.childNodes[0].innerHTML;
		
		var result 	= val.split(':');
		
		if(result[1] == undefined)
		{	val = val;}
		else if(result[1] != '')
		{	val = result[1];}
		else{ val = result[0];}
		
		if(id == '') {
			return val; 
		} else{ 
			id.value = val;
			if(id.id == 'fr_currency_type')
				$('hdn_from_autoselect').value = val;
			else if(id.id == 'to_currency_type')
				$('hdn_to_autoselect').value = val;
		}
		
		fetch_convertion(to_amount_id);
		fill_pocket_guide();
	}
	/**
	  * 	Use to fetch currencies by letters
	*/
	 function show_currency_list(findLetters)
	 {
		var url = 'process/currencies_by_letters.php?letters='+findLetters;
		new Ajax.Request(url, {
		  method: 'get',
		  onSuccess: function(response) {
			var data 	= response.responseText.evalJSON();
			var temp;
			var ctr 	= 0;
			var value 	= ''
			var liStr 	= '<h3>'+ findLetters +'</h3><ol class="clearfix">';
			for(ctr=0; ctr < data.matches.length; ctr++)
			{
				value = data.matches[ctr].split('-');
				liStr 	+= '<li><a href="#" onclick=\'javascript:select_currency_type("'+ data.matches[ctr] + '",event);\'>' + value[0] + '</a></li>';
			}
			liStr 		+= '</ol>';
			$('selected_currecy').innerHTML = liStr;
		  }
		});
	} 
