var indexes_urls			= new Object();
var indexes_rates			= new Object();
var indexes_current_id		= '';
var indexes_current_period	= '';
var indexes_limit_urls		= 4;
var indexes_limit_rates 	= 10;


function indexes_load_chart() {
	var html_periods = '';
	
	for (var i in indexes_urls[indexes_current_id]) {
		html_periods += ""
			+ "<div onclick=\"indexes_change_period('" + i + "');\" id=\"indexes_button_period" + i + "\" class=\"indexes_button\">" + i + "</div>";
	}
	
	document.getElementById("indexes_content").innerHTML = ""
		+ "<p class=\"label\">"
		+ "	" + indexes_current_id + ", "
		+ "	" + indexes_rates[indexes_current_id]['value'] + ", "
		+ "	" + indexes_rates[indexes_current_id][indexes_current_period]['change_percentage'] + "%, "
		+ "	" + indexes_rates[indexes_current_id][indexes_current_period]['change_value'] + "pkt"
		+ "</p>"
		+ "<div class=\"chart\">"
		+ "	<img src=\"" + indexes_urls[indexes_current_id][indexes_current_period] + "\" class=\"block\" alt=\"" + indexes_current_id + "\" />"
		+ "</div>"
		+ "<div id=\"indexes_periods_buttons\">"
		+ 	html_periods
		+ "</div>";
		
	$('div#indexes_periods_buttons div').removeClass('indexes_button_active');
	$('div#indexes_button_period' + indexes_current_period).addClass('indexes_button_active');
}

function indexes_change_id(x) {
	for (var i in indexes_urls[x]) {
		indexes_current_period = i;
		break;
	}
	
	indexes_current_id = x;
	indexes_load_chart();
	
	$('div#indexes_ids_buttons ul li').removeClass('active');
	$('li#indexes_button_id' + x).addClass('active');
}

function indexes_change_period(x) {
	indexes_current_period = x;
	indexes_load_chart();
}

function indexes_load_rates() {
	html = "<table>";
	for (var i in indexes_rates) {
		if (indexes_rates[i]['change_percentage'] > 0) {
			if (indexes_rates[i]['change_percentage'].substring(0,1) != '+') {
				indexes_rates[i]['change_percentage']	= '+' + indexes_rates[i]['change_percentage'];
				indexes_rates[i]['change_value']		= '+' + indexes_rates[i]['change_value'];
			}
			td_class = "positive";
		} else if (indexes_rates[i]['change_percentage'] < 0) {
			td_class = "negative";
		} else {
			td_class = "neutral";
		}
		html += "<tr>"
			+ "<td>" + i + "</td>"
			+ "<td class=\"align_right\">" + indexes_rates[i]['value'].toString().substring(0,indexes_rates[i]['value'].toString().indexOf('.')+3) + "</td>"
			+ "<td class=\"" + td_class +" align_right\">" + indexes_rates[i]['change_percentage'] + "%</td>"
			+ "<td class=\"align_right\">" + indexes_rates[i]['change_value'] + "pkt</td>"
			+ "<td class=\"" + td_class +" align_right chart_small\">" + indexes_rates[i]['chart_small'] + "</td>"
			+ "</tr>";
	}		
	html += "</table>";
	
	document.getElementById("indexes_content").innerHTML = html;
	
	$('div#indexes_ids_buttons ul li').removeClass('active');
	$('li#indexes_button_rates').addClass('active');
}

function indexes_load_ids_buttons() {
	var indexes_i = 0;
	var html = "";
	html += ""
		+ "<ul class=\"tabs_list\">"
			+ "<li class=\"tab\" id=\"indexes_button_rates\"><a href=\"javascript:indexes_load_rates();\" class=\"tab_link\">Indeksy</a></li>"
		//+ "<div onclick=\"indexes_load_rates();\" id=\"indexes_button_rates\" class=\"indexes_button\" >Indeksy</div>";
	
	for (var i in indexes_urls) {
		indexes_i++;
		if (indexes_i > indexes_limit_urls) {
			break;
		}
		html += ""
			//+ "<div onclick=\"indexes_change_id('" + i + "');\" id=\"indexes_button_id" + i + "\" class=\"indexes_button\">" + i + "</div>";
			+ "<li class=\"tab\" id=\"indexes_button_id" + i + "\"><a href=\"javascript:indexes_change_id('" + i + "');\" class=\"tab_link\">" + i + "</a></li>"
	}
	
	html += ""
		+ "</ul>";
		
	document.getElementById('indexes_ids_buttons').innerHTML = html;
}

function indexes_parseXml(xml)
{
	var json = $.xml2json(xml);
	
	var id;
	var period;
	
	var indexes_i = 0;
	$.each(json.index, function() {
		indexes_i++;
		if (indexes_i > indexes_limit_rates) {
			return;
		}
		
		id					= this.id;
		indexes_rates[id]			= new Object();
		indexes_rates[id]['change_percentage']	= parseFloat(this.change_percentage.replace(',','.')).toString().substr(0,this.change_percentage.indexOf(',')+3);
		indexes_rates[id]['change_value']	= myRound(parseFloat(this.change_value.replace(',','.')),0);
		indexes_rates[id]['value']		= this.rates[1].rate[0].value.replace(',','.');
		
		indexes_urls[id]			= new Object();
		
		var first_rates = true;
		
		$.each(this.rates, function() {
			period						= this.period;
			
			indexes_rates[id][period]			= new Object();
			indexes_rates[id][period]['change_percentage']	= myRound(parseFloat(this.change_percentage.replace(',','.')),2);
			indexes_rates[id][period]['change_value']	= myRound(parseFloat(this.change_value.replace(',','.')),0);
			
			if (indexes_i > indexes_limit_rates) {
				return;
			}
			
			indexes_urls[id][period]			= new Object();
			
			var factor_min	= 1;
			var factor_max	= 1;
			
			var width	= 270;
			var height	= 190;
			
			var precision	= 2;
			
			var min 	= 0;
			var max 	= 0;
			var top 	= 0;
			var bottom 	= 0;
			var range	= 0;
			var floor	= 0;
			var bottom	= 0;
			var sum 	= 0;
			var avg		= 0;
			var count	= 0;
			
			var chl		= '';
			var chd		= '';
			var chd_min	= '';
			var chd_max	= '';
			var chd_avg	= '';
			var url		= '';
			
			$.each(this.rate, function() {
				value	= parseFloat(this.value.replace(',','.'));
				date	= this.date;
				sum	+= value;
				count++;
				
				if (count == 1) {
					max = value;
					min = value;
					if (period =='5d') {
						value_1st = value;
					}
				} else {
					if (period =='5d' && count == 2) {
						value_2nd = value;
					}
					if (value > max) max = value;
					if (value < min) min = value;
				}
				
				chd = value + "," + chd;
				
				if (period == '1d') {
					chl = date.substr(11,5) + '|' + chl;
				} else if (period == "1m" || period == "5d") {
					chl = date.substr(8,2) + '.' + date.substr(5,2)/* + '.' + date.substr(2,2)*/ + '|' + chl;
				} else {
					chl = /*date.substr(8,2) + '.' + */date.substr(5,2) + '.' + date.substr(2,2) + 'r.|' + chl;
				}
			});
			
			chl = chl.substr(0, chl.length-1);
			
			top	= myRound(factor_max * max, precision);
			bottom	= myRound(factor_min * min, precision);
			
			avg	= myRound(sum / count, 4);
			floor	= Math.floor((factor_min * min) * Math.pow(10, precision)) / Math.pow(10, precision);
			ceil	= Math.ceil((factor_max * max) * Math.pow(10, precision)) / Math.pow(10, precision);
			range	= myRound(ceil - floor, precision) * Math.pow(10,precision);
			//if (id == 'SWIG80' && period == '1d') alert('P:' + precision + ' R:' + range + ' ' + 'F: ' + floor + 'C: ' + ceil);
			
			if (first_rates) {
				small_chd = chd.substring(0,chd.length-1);
				indexes_rates[id]['chart_small'] =	"<img src='" +
					"http://chart.apis.google.com/chart"
					+ "?chs=" + "52" + "x" + "22"	// wymiary
					+ "&cht=lc"				// typ wykresu
					+ "&chd=t:" + small_chd			// dane
					+ "&chma=0,0,0,0|0,0"	// marginesy
					+ "&chds=" + floor + "," + ceil
					//+ "&chxr=0," + floor + "," + ceil + "," + (1 / Math.pow(10, precision))	// zasięg osi
					+ "&chf=c,lg,90,EFB168,0,FAFAF6,0.6"	// wypełnienie - gradient
					//+ "&chls=3,0,0|2,3,3|2,3,3|2,3,3"	// style linii
					//+ "&chm=b,FFE2BF,0,1,0|o,F8981D,0,-1,7,0"	// wypełnienia
					//+ "&chco=F8981D,F8981D,EF2C2C,0CCF4B"	// kolory linii
					+ "' />";
					//alert(currencies_rates[id]['chart_small']);
			}	
			if (first_rates) {
				first_rates = false;
			}
			
			if (indexes_i > indexes_limit_urls) {
				return;
			}
			
			while (range > 9) {
				precision--;
				floor	= Math.floor((factor_min * min) * Math.pow(10, precision)) / Math.pow(10, precision);
				ceil	= Math.ceil((factor_max * max) * Math.pow(10, precision)) / Math.pow(10, precision);
				range	= myRound(ceil - floor, precision) * Math.pow(10,precision);
			}
			if (range < 2) {
				precision++;
				floor	= Math.floor((factor_min * min) * Math.pow(10, precision)) / Math.pow(10, precision);
				ceil	= Math.ceil((factor_max * max) * Math.pow(10, precision)) / Math.pow(10, precision);
				range	= myRound(ceil - floor, precision) * Math.pow(10,precision);
			}
			
			for (i = 0; i < count; i++) {
				chd_avg = avg + "," + chd_avg;
				chd_min = min + "," + chd_min;
				chd_max = max + "," + chd_max;
			}		
			
			chd =	chd.substr(0, chd.length - 1) + '|' +
				chd_avg.substr(0, chd_avg.length - 1) + '|' +
				chd_min.substr(0, chd_min.length - 1) + '|' +
				chd_max.substr(0, chd_max.length - 1);

					
			url = 	"http://chart.apis.google.com/chart"
				+ "?chs=" + width + "x" + height	// wymiary
				+ "&cht=lc"				// typ wykresu
				+ "&chd=t:" + chd			// dane
				+ "&chds=" + floor + "," + ceil + "," + floor + "," + ceil + "," + floor + "," + ceil + "," + floor + "," + ceil	// skala
				+ "&chl=" + chl				// etykiety
				+ "&chxt=y,r" 				// osie
				//+ "&chxl=1:|" + myRound(min, precision + 1) + "|" + myRound(avg, precision + 1) + "|" + myRound(max, precision + 1)	// labele na osi r
				+ "&chxl=1:|min|avg|max"	// labele na osi r
				+ "&chxp=1," + ((min - floor) * (100 / (ceil - floor))) + "," + ((avg - floor) * (100 / (ceil - floor))) + "," + ((max - floor) * (100 / (ceil - floor))) // pozycje na osi r
				+ "&chxr=0," + floor + "," + ceil + "," + (1 / Math.pow(10, precision))	// zasięg osi
				+ "&chf=c,lg,90,EFB168,0,F6F6F6,0.6"	// wypełnienie - gradient
				+ "&chg=" + myRound(100 / (count - 1),0 ) + "," + (100 / ((ceil - floor) * Math.pow(10, precision))) + ",1,0"	// siatka
				+ "&chls=3,0,0|2,3,3|2,3,3|2,3,3"	// style linii
				+ "&chm=b,FFE2BF,0,1,0|o,F8981D,0,-1,7,0"	// wypełnienia
				+ "&chco=F8981D,F8981D,EF2C2C,0CCF4B";	// kolory linii
				
			indexes_urls[id][period] = url;
		});
	});
	indexes_load_ids_buttons();
	indexes_load_rates();
	$('div#indexes_button_rates').addClass('indexes_button_active');
}

function indexes_load_data(url) {
	if (!url) {
		url = "http://www.portfel.pl/pl/index/ajaxproxy/url/indexes";
	}
	$.ajax({
		type: "GET",
		url: url,
		dataType: "xml",
		beforeSend : function() {
			document.getElementById("indexes_content").innerHTML = "<br />&nbsp;&nbsp;&nbsp;Ładowanie danych...";
		},
		success: indexes_parseXml
	});
}
