var neededQuotes = ['eurusd', 'usdjpy', 'gbpusd', 'usdchf', 'gbpjpy', 'eurjpy', 'eurgbp', 'usdcad', 'audusd', 'eurchf', 'oil', 'gold', 'silver', 'wheat', 'sugar', 'soybeans', 'cotton', 'coffee', 'inx', 'dji', 'cac', 'dax', 'ftsemib', 'ibex', 'ndx', 'n225', 'ftse', 'apple', 'google', 'hsbc', 'ebay', 'bnp', 'sony', 'toyota', 'vivendi'];
var quotesValues = new Array();
var quotesFoundCounter = 0;
var current_titles;
var current_symbols;
var current_tab = '';


// start below, on document.ready
$(document).ready(function(){
    // manually call the updater before setting the alarm below
    quotesUpdater();

    // Check the refresh rate settings, the absolute min is 3 seconds, default 30 seconds
    var refresh_rate;
    if(settings.refresh_rate <= 3000) {
    	refresh_rate = settings.refresh_rate; 
    } else {
    	refresh_rate = 30000;
    }

    // Start the clock
    setInterval(quotesUpdater, refresh_rate);
    
    if ($.browser.msie && $.browser.version.substr(0,1)<7) {
    	var selectors = new Array('.top li', '.top li a');
    	DD_belatedPNG.fix(selectors.join(", "));
    }
    
    // Mess around with resizing various stuff..
    $(".tabbed-box").css({'height': settings.iframe_height + "px", 'width': settings.iframe_width  + "px"});
    var inner_height = settings.iframe_height - ((settings.brandless == false) ? 67 : 44);
    $(".tabbed-box .inner").css({'height': inner_height + "px", 'width': (settings.iframe_width - 2) + "px"});
    $(".forexfeed-msg").css('width', (settings.iframe_width - 22) + "px");
    
    // Start resizing and adding stuff for thin widget
    if(settings.iframe_width < 250) { 
    	$(".tabbed-box").css('font-size', '9px');
    	titles.fr.Commodities = "Matiéres"; 
    	titles.ru.Commodities = "Сырьё";
    }
    
    // fire up tab click-ability for tab focusing:            
    $(".tabbed-box .top ul li").click(function(e){
        e.preventDefault();
        
        try {
        	current_tab = $(this).attr('id').split('-');
        	current_tab = current_tab[1];
        } catch (e) {}
        
        var id = $(this).prevAll('li').size();
        $(this).parents(".tabbed-box").find(".current").removeClass("current");
        $(this).addClass("current");
        $(this).parents(".tabbed-box").find(".tab-content").hide();
        var content = $(this).parents(".tabbed-box").find(".tab-content")[id];
        $(content).addClass("current").show();

    });
    
    $(".tabbed-box").click(function (e) {
    	
    	var originalElement = e.srcElement;
        if(!originalElement){originalElement=e.originalTarget;}

    	if($(originalElement).parents(".top ul").size() > 0 || originalElement.tagName == 'a' || originalElement.tagName == 'A') {
    		return;
    	}
    	
    	var link = settings.link;
    	if(link == 'undefined' || link == '#' || !link || link == '') {
    		return;
    	}
    	
    	window.open(link, '_blank');
    	
    });
    
    // convert en-us, pt-br formats into 2 letter en, pt 
    if(settings.lang.length == 5) settings.lang = settings.lang.substr(0, 2);
    
    // Initiate Translations
    try {
    	current_titles = titles[settings.lang];
    	current_symbols = commodities[settings.lang];
    }
    catch (e) {
       	current_titles = titles['en'];
    	current_symbols = commodities['en'];
    }
	
	if(settings.lang == 'ar') {
		$('body').addClass('rtl');
	}
	if(settings.brandless == true) {
		$('body').addClass('brandless');
	}

	// Set up the current tab..
    try {
    	current_tab = $(".tabbed-box .top li.current").attr('id').split('-');
    	current_tab = current_tab[1];
    } catch (e) {}
    	
    // Handle Titles Translations
    translateTitles();
    
    $("table tr:odd, table td:odd").addClass('odd');
    
});

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

function translateTitles() {
	
	$(".top ul li a span, .forexfeed-table th").each(function (e) {
		for(x in current_titles) {
			if($(this).text().trim() == x) {
				$(this).text(current_titles[x]);
			}
		}
	});
	$(".forexfeed-msg").text(current_titles['QuotesDelayed']);

}

function translateSymbols() {
	
	$(".forexfeed-table td.abbr").each(function (e) {
		for(x in current_symbols) {
			if($(this).text().trim() == x) {
				$(this).text(current_symbols[x]);
			}
		}
	});
	
}


function number_format(number, decimals, dec_point, thousands_sep) {
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

function parseresponse(data){

    var quotesFullData = data;
    //console.log(data);
    quotesFoundCounter = 0;
    $(neededQuotes).each(function(index, quoteName){
        // parse data from server:
        try {
            if ('name' in quotesFullData[quoteName]) {
                // got one needed quote. save its data
                quotesValues[quoteName] = quotesFullData[quoteName];
                quotesFoundCounter++;
            }
        }
        catch (e){}
    // else - nothing, quote is not needed.
    });
    // now update DOM with quotesValues, if anything inside
    if (quotesFoundCounter > 0) {
        //$.quotesValues.each(function(symbol, feed){
        for (instrument in quotesValues) {
            instrument = quotesValues[instrument];
            var myRow = $('#forexfeed-' + instrument.id);

            if (typeof document.savedData == 'undefined') {
                document.savedData = {};
            }
            data = document.savedData;
            cha = '';

            var oldBuy = parseFloat($('.buy', myRow).text());
            var newBuy = parseFloat(instrument.buy);

            if (oldBuy !== newBuy) { // There has been change
                $('#forexfeed-' + instrument.id + ' .abbr').text(instrument.name);
                $('#forexfeed-' + instrument.id + ' .sell').text(instrument.sell);
                $('#forexfeed-' + instrument.id + ' .buy').text(instrument.buy);
                $('#forexfeed-' + instrument.id + ' .change').text(number_format(instrument.change,2) + ' % ');
                if (oldBuy > newBuy) {
                    cha = 'neg';
                }
                else
                if (oldBuy < newBuy) {
                    cha = 'pos';
                }
            }
            else { // no change
            }

            if (cha !== '') {
                myRow.removeClass('pos neg').addClass(cha);
            }
            else {
                myRow.removeClass('pos neg');
            }
            instrument = "";

            // Handle Symbols Translations
            translateSymbols();
        }
    }

}

/**
 * Fetches data and updates quotes in DOM
 */

var id_ajax;
function quotesUpdater(){
	
	var category = current_tab == '' ? '' : "&q=" + current_tab;
	
    id_ajax = $.ajax({
        url: "http://" + settings.apiserver + "/quotes?key=" + settings.key + category,
        cache: true,
        dataType: "jsonp",
        jsonpCallback: "parseresponse",
        success: function(data){
        }
    });
}

$('document').unload(function(){
    id_ajax.abort();
});

//Define Translations
//Titles

var titles = {
"ar" : {
 "Forex": "فوركس",
 "Commodities": "السلع",
 "Indices": "مؤشرات",
 "Stocks": "الاسهم",
 "Instrument" : "السند",
 "Bid": "عرض",
 "Ask": "طلب",
 "Change": "التغيير",
 "QuotesDelayed": "* الاسعار متأخره"
},
"es" : {
 "Forex": "Forex",
 "Commodities": "Materias Primas",
 "Indices": "Índices",
 "Stocks": "Acciones",
 "Instrument" : "Instrumento",
 "Bid": "Compra",
 "Ask": "Venta",
 "Change": "Variación",
 "QuotesDelayed": "* Cotizaciones diferidas"
},
"tr" : {
 "Forex": "Forex",
 "Commodities": "Emtialar",
 "Indices": "Endeksler",
 "Stocks": "Senetlerinde",
 "Instrument" : "Enstrüman",
 "Bid": "Alış",
 "Ask": "Satış",
 "Change": "Değiştir",
 "QuotesDelayed": "* Fiyatlar gecikmelidir"
},
"en" : {
 "Forex": "Forex",
 "Commodities": "Commodities",
 "Indices": "Indices",
 "Stocks": "Stocks",
 "Instrument" : "Instrument",
 "Bid": "Bid",
 "Ask": "Ask",
 "Change": "Change",
 "QuotesDelayed": "* Quotes are delayed"
},
"nl" : {
 "Forex": "Forex",
 "Commodities": "Grondstoffen",
 "Indices": "Indices",
 "Stocks": "Aandelen",
 "Instrument" : "Instrument",
 "Bid": "Bid",
 "Ask": "Ask",
 "Change": "Verandering",
 "QuotesDelayed": "* Noteringen zijn vertraagd"
},
"de" : {
 "Forex": "Forex",
 "Commodities": "Rohstoffe",
 "Indices": "Indizes",
 "Stocks": "Wertpapiere",
 "Instrument" : "Instrument",
 "Bid": "Bid",
 "Ask": "Ask",
 "Change": "Veränderung",
 "QuotesDelayed": "* Kursnotierungen sind zeitverzögert"
},
"ru" : {
 "Forex": "Форекс",
 "Commodities": "Сырьевые товары",
 "Indices": "Индексы",
 "Stocks": "Акции",
 "Instrument" : "Инструмент",
 "Bid": "Bid",
 "Ask": "Ask",
 "Change": "Изменение",
 "QuotesDelayed": "* Котировки с задержкой"
},
"pt" : {
 "Forex": "Forex",
 "Commodities": "Mercadorias",
 "Indices": "Índices",
 "Stocks": "Acções",
 "Instrument" : "Instrumento",
 "Bid": "Bid",
 "Ask": "Ask",
 "Change": "Câmbio",
 "QuotesDelayed": "* As cotações estão atrasadas"
},
"fr" : {
 "Forex": "Forex",
 "Commodities": "Matiéres Premières",
 "Indices": "Indices",
 "Stocks": "Actions",
 "Instrument" : "Instrument",
 "Bid": "Bid",
 "Ask": "Ask",
 "Change": "Changer",
 "QuotesDelayed": "* Les cotations sont différées"
},
"it" : {
 "Forex": "Forex",
 "Commodities": "Materie Prime",
 "Indices": "Indici",
 "Stocks": "Azioni",
 "Instrument" : "Strumento",
 "Bid": "Offerta",
 "Ask": "Richiesta",
 "Change": "Modifica",
 "QuotesDelayed": "* Quotazioni non in tempo reale"
},
"pl" : {
 "Forex": "Waluty",
 "Commodities": "Towary",
 "Indices": "Indeksy",
 "Stocks": "Akcje",
 "Instrument" : "Instrument",
 "Bid": "Bid",
 "Ask": "Ask",
 "Change": "Zmiana",
 "QuotesDelayed": "* Notowania są opóźnione"
},
"sv" : {
 "Forex": "Forex",
 "Commodities": "Råvaror",
 "Indices": "Index",
 "Stocks": "Aktier",
 "Instrument" : "Instrument",
 "Bid": "Sälj",
 "Ask": "Köp",
 "Change": "Ändring",
 "QuotesDelayed": "* Noteringarna är fördröjda"
},
"ro" : {
 "Forex": "Forex",
 "Commodities": "Mărfuri",
 "Indices": "Indici",
 "Stocks": "Acţiuni",
 "Instrument" : "Instrumentul",
 "Bid": "Bid",
 "Ask": "Ask",
 "Change": "Schimbare",
 "QuotesDelayed": "* Cotaţiile sunt în întârziere"
},
"ja" : {
 "Forex": "Forex",
 "Commodities": "商品",
 "Indices": "株式指数",
 "Stocks": "株式",
 "Instrument" : "商品",
 "Bid": "ビッド ",
 "Ask": "アスク",
 "Change": "変更",
 "QuotesDelayed": "* 相場の表示に遅れが生じております"
},
"zh-hans" :{
 "Forex": "外汇",
 "Commodities": "商品",
 "Indices": "指数",
 "Stocks": "股票",
 "Instrument" : "﻿金融产品",
 "Bid": "买入价",
 "Ask": "卖出价",
 "Change": "涨跌",
 "QuotesDelayed": "*报价延迟"
},
"cs" :{
 "Forex": "Forex",
 "Commodities": "Komodity",
 "Indices": "Indexy",
 "Stocks": "Akcie",
 "Instrument" : "NÁSTROJ",
 "Bid": "BID",
 "Ask": "ASK",
 "Change": "ZMĚNA",
 "QuotesDelayed": "* Ceny jsou zpožděné"
},
"nb" :{
 "Forex": "Forex",
 "Commodities": "Råvarer",
 "Indices": "Indekser",
 "Stocks": "Aksjer",
 "Instrument" : "INSTRUMENT",
 "Bid": "TILBUD",
 "Ask": "ETTERSPØRSEL",
 "Change": "ENDRE",
 "QuotesDelayed": "* Noteringer er forsinket"
},
"sr" :{
 "Forex": "Devizna sredstva",
 "Commodities": "Roba",
 "Indices": "Indeksi",
 "Stocks": "Akcije",
 "Instrument" : "INSTRUMENT",
 "Bid": "PONUDA",
 "Ask": "POTRAŽNJA",
 "Change": "PROMENA",
 "QuotesDelayed": "* Kvote kasne"
},
"sk" :{
 "Forex": "Forex",
 "Commodities": "Komodity",
 "Indices": "Indexy",
 "Stocks": "Akcie",
 "Instrument" : "NÁSTROJ",
 "Bid": "Ponuka",
 "Ask": "Dopyt",
 "Change": "ZMENA",
 "QuotesDelayed": "* Ceny sú oneskorené"
},
"hu" :{
 "Forex": "Forex",
 "Commodities": "Árutőzsde",
 "Indices": "Index",
 "Stocks": "Részvények",
 "Instrument" : "INSTRUMENTUM",
 "Bid": "Eladás",
 "Ask": "Vétel",
 "Change": "VÁLTÁS",
 "QuotesDelayed": "* A kereskedés szüneteltetése"
},
"el" :{
 "Forex": "Forex",
 "Commodities": "Εμπορεύματα",
 "Indices": "Δείκτες",
 "Stocks": "Μετοχές",
 "Instrument" : "ΤΙΤΛΟΣ",
 "Bid": "ΠΡΟΣΦΟΡΑ",
 "Ask": "ΖΗΤΗΣΗ",
 "Change": "ΑΛΛΑΓΗ",
 "QuotesDelayed": "* Η προσφορά των τιμών καθυστερεί"
},
"sl" :{
 "Forex": "Forex trg",
 "Commodities": "Produkti",
 "Indices": "Indeksi",
 "Stocks": "Delnice",
 "Instrument" : "ORODJE",
 "Bid": "BID",
 "Ask": "ASK",
 "Change": "SPREMEMBA",
 "QuotesDelayed": "Cene so zadržane *"   
},
"bg" :{
 "Forex": "Forex пазар",
 "Commodities": "Стоки",
 "Indices": "Индекси",
 "Stocks": "Акции",
 "Instrument" : "ИНСТРУМЕНТ",
 "Bid": "BID",
 "Ask": "ASK",
 "Change": "ПРОМЯНА",
 "QuotesDelayed": "* Цените са забавени"   
}

};

//Commodities
var commodities = {
"en" : {
 "Oil": "Oil",
 "Gold": "Gold",
 "Silver" : "Silver",
 "Wheat": "Wheat",
 "Sugar": "Sugar no.11",
 "Soybeans": "Soybeans",
 "Cotton": "Cotton no.2",
 "Coffee": "Coffee" 
},
"fr" : {
 "Oil": "Pétrole",
 "Gold": "Or",
 "Silver" : "Argent",
 "Wheat": "Blé",
 "Sugar": "Sucre n°11",
 "Soybeans": "Soja",
 "Cotton": "Coton n°2",
 "Coffee": "Café C" 
},
"ar" : {
 "Oil": "النفط",
 "Gold": "الذهب",
 "Silver" : "الفضه",
 "Wheat": "الحنطه",
 "Sugar": "السكر",
 "Soybeans": "فول الصويا",
 "Cotton": "القطن",
 "Coffee": "البن" 
},
"it" : {
 "Oil": "Petrolio",
 "Gold": "Oro",
 "Silver" : "Argento",
 "Wheat": "Granturco",
 "Sugar": "Zucchero N°11",
 "Soybeans": "Soia",
 "Cotton": "Cotone N°2",
 "Coffee": "Caffè C" 
} ,
"es" : {
 "Oil": "Petróleo",
 "Gold": "Oro",
 "Silver" : "Plata",
 "Wheat": "Trigo",
 "Sugar": "Azúcar nº 11",
 "Soybeans": "Soja",
 "Cotton": "Algodón nº 2",
 "Coffee": "Café" 
},
"tr" : {
 "Oil": "Petrol",
 "Gold": "Altin",
 "Silver" : "Gümüş",
 "Wheat": "Buğday",
 "Sugar": "11 no’lu Şeker",
 "Soybeans": "Soya Fasulyesi",
 "Cotton": "2 no’lu Pamuk",
 "Coffee": "Kahve Arabika" 
},
"nl" : {
 "Oil": "Ruwe olie",
 "Gold": "Goud",
 "Silver" : "Zilver",
 "Wheat": "Tarwe",
 "Sugar": "Suiker nr. 11",
 "Soybeans": "Sojabonen",
 "Cotton": "Katoen nr. 2",
 "Coffee": "Koffie C" 
},
"de" : {
 "Oil": "Rohöl",
 "Gold": "Gold",
 "Silver" : "Silber",
 "Wheat": "Weizen",
 "Sugar": "Zucker Nr.11",
 "Soybeans": "Sojabohnen",
 "Cotton": "Baumwolle Nr.2",
 "Coffee": "Kaffee C" 
},
"ru" : {
 "Oil": "Нефть",
 "Gold": "Золото",
 "Silver" : "Серебро",
 "Wheat": "Пшеница",
 "Sugar": "Сахар №11",
 "Soybeans": "Соя",
 "Cotton": "Хлопок №2",
 "Coffee": "Кофе C" 
},
"pt" : {
 "Oil": "Petróleo",
 "Gold": "Ouro",
 "Silver" : "Prata",
 "Wheat": "Trigo",
 "Sugar": "Açúcar nº.11",
 "Soybeans": "Soja",
 "Cotton": "Algodão nº.2",
 "Coffee": "Café C" 
},
"pl" : {
 "Oil": "Ropa",
 "Gold": "Złoto",
 "Silver" : "Srebro",
 "Wheat": "Pszenica",
 "Sugar": "Cukier nr 11",
 "Soybeans": "Soja",
 "Cotton": "Bawełna nr 2",
 "Coffee": "Kawa C" 
},
"sv" : {
 "Oil": "Olja",
 "Gold": "Guld",
 "Silver" : "Silver",
 "Wheat": "Vete",
 "Sugar": "Socker nr 11",
 "Soybeans": "Sojabönor",
 "Cotton": "Bomull nr 2",
 "Coffee": "Kaffe C" 
},
"ja" : {
 "Oil": "原油",
 "Gold": "金",
 "Silver" : "銀",
 "Wheat": "小麦",
 "Sugar": "砂糖",
 "Soybeans": "大豆",
 "Cotton": "綿花",
 "Coffee": "コーヒー"
},
"zh-hans" : {
 "Oil": "原油",
 "Gold": "黄金",
 "Silver" : "白银",
 "Wheat": "小麦",
 "Sugar": "糖",
 "Soybeans": "黄豆",
 "Cotton": "棉花",
 "Coffee": "咖啡"
},
"cs" : {
 "Oil": "Ropa",
 "Gold": "Zlato",
 "Silver" : "Stříbro",
 "Wheat": "Pšenice",
 "Sugar": "Cukr",
 "Soybeans": "Sójové boby",
 "Cotton": "Bavlna",
 "Coffee": "Káva"
},
"nb" : {
 "Oil": "Olje",
 "Gold": "Gull",
 "Silver" : "Sølv",
 "Wheat": "Hvete",
 "Sugar": "Sukker",
 "Soybeans": "Soyabønner",
 "Cotton": "Bomull",
 "Coffee": "Kaffe"
},
"sr" : {
 "Oil": "Nafta",
 "Gold": "Zlato",
 "Silver" : "Srebro",
 "Wheat": "Pšenica",
 "Sugar": "Šećer",
 "Soybeans": "Zrno soje",
 "Cotton": "Pamuk",
 "Coffee": "Kafa"
},
"sk" : {
 "Oil": "Ropa",
 "Gold": "Zlato",
 "Silver" : "Striebro",
 "Wheat": "Pšenica",
 "Sugar": "Cukor",
 "Soybeans": "Sójové bôby",
 "Cotton": "Bavlna",
 "Coffee": "Káva"
},
"hu" : {
 "Oil": "Olaj",
 "Gold": "Arany",
 "Silver" : "Ezüst",
 "Wheat": "Gabona",
 "Sugar": "Cukor",
 "Soybeans": "Szójabab",
 "Cotton": "Gyapot",
 "Coffee": "Kávé"
},
"el" : {
 "Oil": "Πετρέλαιο",
 "Gold": "Χρυσός",
 "Silver" : "Άργυρος",
 "Wheat": "Σιτάρι",
 "Sugar": "Ζάχαρη",
 "Soybeans": "Σόγια",
 "Cotton": "Βαμβάκι",
 "Coffee": "Καφές"
},
"sl" :{
 "Oil": "Nafta",
 "Gold": "Zlato",
 "Silver" : "Srebro",
 "Wheat": "Pšenica",
 "Sugar": "Sladkor",
 "Soybeans": "Sojina zrna",
 "Cotton": "Bombaž",
 "Coffee": "Kava"  
},
"bg" :{
 "Oil": "Петрол",
 "Gold": "Злато",
 "Silver" : "Сребро",
 "Wheat": "Пшеница",
 "Sugar": "Захар",
 "Soybeans": "Соеви зърна",
 "Cotton": "Памук",
 "Coffee": "Кафе"  
}

};

