//construct
function CurrencyRate( rootImgUrl )
{
	this.url = 'http://www.xforex.com/trade/RateEventServlet';
	this.ratesFromEventServlet = null;
	this.symbolIndex = 16;
	this.bidTime = 5
	this.askIndex = 0;
	this.bidIndex = 3;
	this.changeIndex = 18;
	this.lowIndex = 12;
	this.highIndex = 9;
	this.mainCurrencyRate = new Array('EURUSD','USDJPY',
			  						  'GBPUSD','USDCHF',
			  						  'AUDUSD','NZDUSD','USDCAD',
			  						  'XAUUSD','XAGUSD');
	
	this.crossCurrencies = new Array( 'EURJPY','EURGBP','EURCHF','EURAUD',
									  'EURCAD','EURSEK','EURNOK','EURZAR',
									  'GBPJPY','GBPCHF','GBPAUD','AUDNZD','AUDJPY','CHFJPY');
	this.rootImgUrl = rootImgUrl;
}

CurrencyRate.prototype.getRate = function(){
	var ajaxOptions = {
		type: "POST",
		async: false,
		url: this.url
	};
	this.ratesFromEventServlet = $.ajax(ajaxOptions).responseText;
	return this;
}, CurrencyRate.prototype.parseRates = function(){
	if (null !== this.ratesFromEventServlet) {
		var rateDetails = new Array();
		var rates = (this.ratesFromEventServlet).split("\n");
		var len = rates.length;
		for (var i = 0; i < len; i++) {
			rates[i] = rates[i].replace('rates#~', '');
			rateDetails = rates[i].split("~");
			if (!this.isMainCurrencyRate(rateDetails[this.symbolIndex])) {
				continue;
			}
			this.setTableRateCells(rateDetails[this.symbolIndex], rateDetails[this.askIndex], rateDetails[this.bidIndex], rateDetails[this.bidTime]);
		}
	}
	return this;
}, CurrencyRate.prototype.setTableRateCells = function(symbol, ask, bid, bidTime){
	symbol = symbol.replace('Symbol=', '');
	ask = ask.replace('Ask=', '');
	bid = bid.replace('Bid=', '');
	var prevBid = ($('#' + symbol + 'BID').html()) ? parseFloat($('#' + symbol + 'BID').html()) : 0;
	$('#' + symbol + 'BID').html(bid);
	this.setImgSrc(prevBid, bid, symbol);
	$('#' + symbol + 'ASK').html(ask);
	this.setBidTime(symbol, bidTime);
	return this;
},

CurrencyRate.prototype.setBidTime = function(symbol, bidTime){
	bidTime = $.trim(bidTime);
	var bidTimeArr = bidTime.split( ' ' );
	$('#' + symbol + 'BID_TIME').html(bidTimeArr[1]);
	return this;
},

CurrencyRate.prototype.setImgSrc = function( prevBid, bid, symbol ){
	if( prevBid ){
		bid = parseFloat( bid );
		var imgSrc = this.rootImgUrl;
		if( prevBid > bid ){
			imgSrc += 'down.gif';
		}else if( prevBid < bid){
			imgSrc += 'up.gif';
		}else{
			imgSrc = $('#'+symbol+'IMG').attr('src');
		}
		$('#'+symbol+'IMG').attr('src', imgSrc);
	}
},

CurrencyRate.prototype.isMainCurrencyRate = function( symbol ){
	var isMainPage = false;
	if(symbol != undefined){
		symbol = symbol.replace('Symbol=','');
		for(mainCurrencyIndex in this.mainCurrencyRate){
			if(this.mainCurrencyRate[mainCurrencyIndex] == symbol){
				isMainPage = true;
			}
		}
	}
	return isMainPage;
},

CurrencyRate.prototype.init = function( ){
	if($ !== undefined){
		this.getRate().parseRates();
	}
},
CurrencyRate.prototype.setMainTableRateCells = function( rateDetails ){
	if(($ !== undefined) && (rateDetails[this.symbolIndex] != undefined)){
	
		rateDetails[this.symbolIndex] = rateDetails[this.symbolIndex].replace('Symbol=','');
		rateDetails[this.askIndex] = rateDetails[this.askIndex].replace('Ask=','');
		rateDetails[this.bidIndex] = rateDetails[this.bidIndex].replace('Bid=','');
		
		rateDetails[this.changeIndex] = rateDetails[this.changeIndex].replace('ChangePercent=','');
		rateDetails[this.lowIndex] = rateDetails[this.lowIndex].replace('Low=','');
		rateDetails[this.highIndex] = rateDetails[this.highIndex].replace('High=','');
		
		
		var prevBid = ( $('#'+rateDetails[this.symbolIndex]+'BID').html(  ) ) ?parseFloat( $('#'+rateDetails[this.symbolIndex]+'BID').html( ) ): 0;
		$('#'+rateDetails[this.symbolIndex]+'BID').html( rateDetails[this.bidIndex] );
		this.setImgSrc( prevBid, rateDetails[this.bidIndex], rateDetails[this.symbolIndex] );
		$('#'+rateDetails[this.symbolIndex]+'ASK').html( rateDetails[this.askIndex] );
		
		
		$('#'+rateDetails[this.symbolIndex]+'CHANGE').html( rateDetails[this.changeIndex] );
		$('#'+rateDetails[this.symbolIndex]+'HIGH').html( rateDetails[this.highIndex] );
		$('#'+rateDetails[this.symbolIndex]+'LOW').html( rateDetails[this.lowIndex] );
	}
	return this;
},

CurrencyRate.prototype.mainParseRates = function( ){
	if(null !== this.ratesFromEventServlet){
		var rateDetails = new Array();
		var rates = (this.ratesFromEventServlet).split("\n");
		var len = rates.length;
		for(var i = 0; i < len; i++){
			rates[i] = rates[i].replace('rates#~','');
			rateDetails = rates[i].split("~");
			this.setMainTableRateCells( rateDetails );
		}
	}
	return this;
},

CurrencyRate.prototype.main = function( ){
	this.getRate().mainParseRates();
};
//GLOBAL FUNCTION SHOULD REMOVE TO A DIFFRENT FILE
function customAjaxForm( formId,formMsgId ){
	var postData = $( formId ).serialize();
	$.post($( formId ).attr( 'action' ), postData, function(data){
		//$( formMsgId ).html( data );
	});
}

var newWin = null;
function popUp(strURL, strType, strHeight, strWidth) {
 if (newWin != null && !newWin.closed)
   newWin.close();
 var strOptions="";
 if (strType=="console")
   strOptions="resizable,height="+
     strHeight+",width="+strWidth;
 if (strType=="fixed")
   strOptions="status,height="+
     strHeight+",width="+strWidth;
 if (strType=="elastic")
   strOptions="toolbar,menubar,scrollbars,"+
     "resizable,location,height="+
     strHeight+",width="+strWidth;
 newWin = window.open(strURL, 'newWin', strOptions);
 newWin.focus();
}



Rater	=	{
					/* First array is for all pages and second (bigger array) is for financial calendar (thease are currency id) */
	list		:	[[27,28,29,30,37,38,25,26,39],[27,28,29,30,37,38,25,26,39,31,32,33,41,45,/*40,52,18,*/34,35,63,43,44,35,36]] ,
	calendar	:	false,
	first		:	true,
	direction	:	true,
	url			:	"/trade/services/rates",
	request		:	{},
	saved		:	{},
	date		:	{},
	start		:	0,
	frame		:	false,
	pop_list	:	function(mainCurr,crossCur){
		//Get Values from xml file
		//Erase the list var and make new one with data taken from xml file. 
		Rater.list = new Array();
		Rater.list[0] = new Array();
		Rater.list[1] = new Array();
		$.each(mainCurr, function(k, rateInfo) {
			Rater.list[0].push(parseInt(rateInfo.id));
		});
		$.each(crossCur, function(k, rateInfo) {
			Rater.list[1].push(parseInt(rateInfo.id));			
		});		
	},
	init		:	function() {
		/*
			1. Determine the type of the page (any page, or currency rates page)
			2. Preapre the list of currencies to parse
			3. Make first call
		*/
		
		this.where().prepare().go();
	} ,
	where		:	function() {
		this.calendar	=	/currency-rates/i.test(document.location.href);
		this.frame		=	/iframeRates/i.test(document.location.href);
		return this;
	} ,
	get_list	:	function() {
		if(this.calendar)
		{
			return this.list[0].concat(this.list[1]);
		}
		else
		{
			return this.list[0];
		}
		//return this.list[this.calendar ? 1 : 0];
	},
	prepare		:	function() {
		this.request.query	=	this.get_list().join(",");

		return this;
	}  ,
	go			:	function() {
	
		Rater.start	=	new Date().getTime();
		
		$.ajax ({
			url				:	Rater.url , 
			data 			: 	{ "p" : Rater.request.query } ,
			dataType		:	"json" ,
			success			:	Rater.success 	,
			error			:	Rater.error ,
			cache			:	false
		});
	} , 
	error		:	function() {
		Rater.over("5000");
	} ,
	success		:	function(res) {

		$(res.symbols).each(function(index, value) {
			Rater.rate(value);
		});
		if(Rater.first)	Rater.first	=	false;
		
		if(!res.tradeEnabled) { 
			Rater.over(20000); 
		}
		else { 
			Rater.over(); 
		}
	},
	
	over		:	function(time) {
	
		timeout	=	!time ? 15000 : time;
		var Elapsed	 = new Date().getTime() - Rater.start;

		if(Elapsed > timeout) {
			Rater.go();
		} else {
			setTimeout(Rater.go , timeout - Elapsed);
		}
	} ,
	rate		:	function(rate) {
		// Checking if curent rate is in the list of rates that we are working with.
		if(!this.valid(rate.id)) return;
		
		// Checking if current rate has changed from previous time. If not - so we are not doing nothing (only removing previous classes that describes directions)
		if(!this.changed(rate.id, rate.ask))	return;

		this.show(rate);
	} ,
	show		:	function(rate) {
		$("#cur-"+rate.id+" .cur-ask").html(rate.ask);
		$("#cur-"+rate.id+" .cur-bid").html(rate.bid);
		
		if(this.calendar) {
			$("#cur-"+rate.id+" .cur-change").html(rate.perc);
			$("#cur-"+rate.id+" .cur-high").html(rate.max);
			$("#cur-"+rate.id+" .cur-low").html(rate.min);
		}
		
		if(this.frame){
			
			$("#cur-"+rate.id+" .cur-change").html(rate.perc);
		}
		
		if(!this.first) {
			$("#cur-"+rate.id).toggleClass(this.getDirection()).removeClass(this.getDirection(true));
		}
	} ,
	valid		:	function(id) {
		return $.inArray(parseInt(id), this.get_list()) == -1 ? 0 : 1;
	} ,
	save		:	function(id, ask) {
		this.saved[id]	=	ask;
		return true;
	} ,
	changed		:	function(id, ask) {
		if(this.first)	return this.save(id, ask);
		
		if(this.saved[id]	<	ask) {
			this.direction	=	true; //this mean that direction is positive
			return this.save(id, ask);
		} else if(this.saved[id]	>	ask) {
			this.direction	=	false; //this mean that direction is negative
			return this.save(id, ask);
		}
		else {
			//No activity - so lets remove all the classes
			$("#cur-"+id).removeClass("cur-possitive").removeClass("cur-negative");
			return false;
		}
	} , 
	getDirection		:	function(opposite) {
		if(opposite) {
			return !this.direction ? "cur-possitive" : "cur-negative";
		} else {
			return this.direction ? "cur-possitive" : "cur-negative";
		}
	}
}



$(document).ready(function(){

	//Check the mainRatesList and crossRatesList created in currencyrate.php file.
	if(typeof(mainRatesList) !== "undefined" && typeof(crossRatesList) !== "undefined") Rater.pop_list(mainRatesList,crossRatesList);
	Rater.init();
	//console.log(Rater.list);
	$siteMap = $( '.site-map ul' );
	$siteMap.find( 'li' ).each(function(){
		$(this).find( 'a' ).each(function(i){
			if(i == 1){
				$(this).parent().remove();
				$(this).remove();
			}
		});
	});
	$( '.site-map ul' ).removeClass().addClass( 'site-map-parent' );
	$( '.site-map a' ).removeClass();
	$( '.site-map li' ).removeClass().addClass('site-map-child');
	$( '.site-map li ul' ).each(function(i){
		$(this).parent().removeClass().addClass('site-map-parent');
	});
});

