(function($) {
		$.fn.customFadeTo = function(speed,to,callback) {
			return this.animate({opacity: to}, speed, function() {
				if (to == 1 && jQuery.browser.msie)
					this.style.removeAttribute('filter');
				if (jQuery.isFunction(callback))
					callback();
			});
		};
	})(jQuery);

function ShowLoading(_id) 
{ 
	/*document.getElementById( _id == undefined ? "bar-content-general" : _id).innerHTML = "<center><img src='content/images/loading.gif' border='0' title='Cargando...' alt='Carganado...' /></center>"; */
	_id = _id == undefined ? "bar-content-general" : _id;
	jQuery("#" + _id).customFadeTo("fast", 0.5);
	jQuery("#" + _id).append("<img id='_dynamic_loading' src='content/images/loading.gif' border='0' title='Cargando...' alt='Carganado...' style='position: absolute; left: 50%; top: 20%;' />");
}
function StopLoading(_id) { 
	
	_id = _id == undefined ? "bar-content-general" : _id;
	jQuery("#" + _id).customFadeTo("fast", 1);
	jQuery("#_dynamic_loading").remove();
}

jQuery(document).ready(function() {
  //LoadTicket();
  if(jQuery.trim(window.location.hash) != "") {
	  var _values = window.location.hash.substring(1).split('/');
	  Change(document.getElementById("_" + _values[0]), _values.length > 1 ? _values[1] : null);
  }
  else Change(document.getElementById("_nacional"));
});

function LoadTicket() {
	jQuery.post('minutoaminuto.php', 
		function(data) {
			if(document.getElementById('mod_ticket') != undefined)
				document.getElementById('mod_ticket').innerHTML = data;
		}
	);	
}


String.prototype.startsWith = function (str) { return (this.match("^" + str) == str) }

function ChangeTab( tab, name_dept ) {
	name_dept = name_dept || null;
		
	jQuery.ajax({
		type: "POST",
		url: tab + '.php',
		cache: false,
		beforeSend: function () {
            ShowLoading();
        },
		success: function(data) {
			document.getElementById('bar-content-general').innerHTML = data;
			StopLoading();
			if(tab == "nacional") {
				if(document.getElementById("_script_graph") != undefined)
					   eval(document.getElementById("_script_graph").value);
				if(document.getElementById("_value_informado") != undefined) {
					jQuery("#_value_d_informado").html(document.getElementById("_value_informado").value + "%");
					jQuery("#_value_d_boletin").html("#" + document.getElementById("_value_report").value);
				}
			}
			else if(tab == "ciudad") {
				jQuery("#_c_result_filtro").buttonset();
				ShowCity(name_dept != null ? name_dept : "BOGOTA, D.C.");				
			}else if(tab == "historico") {
				
				if(document.getElementById("_script_tlg") != undefined) {
					eval(document.getElementById("_script_tlg").value);
				}
				LoadChartHash();
			}
			else if(tab == "regional") {
				InitFunctionsMaps(function () { ShowPie(name_dept != null ? name_dept : "Antioquia"); });
				
			}
			
		},
        error: function (a, b, c) {
            StopLoading();
            jQuery("#bar-content-general").html(a.responseText);
        }
	});
	
	
}
function Change(seleccionado, name_dept) {
	name_dept = name_dept || null;
	if(seleccionado != null) {
		if(seleccionado.id.substring(1) != "historico" || window.location.hash.substring(1).split('/').length < 6) {
			window.location.hash = seleccionado.id.substring(1);
		}
		pageTracker._trackEvent("Tabs", seleccionado.id);
		
		jQuery(".pestanas ul li").removeClass();
		jQuery("#" + seleccionado.id).addClass("selected");

		ChangeTab(seleccionado.id.substr(1), name_dept);
	}
}

var _percents = new Array();
var _ids_inte = new Array();
var _a_index = 0;

function ChangePercent(id, percent, votes) {
	
	document.getElementById("_value" + id.toString().substr(id.indexOf('n') + 1)).innerHTML = addCommas(votes);	
	_percents[_a_index] = 0;
	_ids_inte[_a_index] = setInterval("ChangePercentEffect(\"" + id + "\", " + _a_index + ", " + percent + ")", 1);
	_a_index++;
}

function ChangePercentEffect(id_elem, inde, _max) {
	percent = _percents[inde];
	if(document.getElementById(id_elem) != undefined) {
		document.getElementById(id_elem).style.width = percent + "%";
	
		_percents[inde] = percent + 1;
		if(percent >= _max) {
			clearInterval(_ids_inte[inde]);
		}
	}
	else {
		clearInterval(_ids_inte[inde]);
	}
}

function ClearIntervals() {
	for(i = 0; i < _ids_inte.length; i++) {
		clearInterval(_ids_inte[i]);
	}
}
function ShowCity(city) {
	try { pageTracker._trackEvent("Ciudad", name_dept); }catch(err) { }
	ClearIntervals();
	if(jQuery.trim(window.location.hash) != "") {	
		var _values = window.location.hash.substring(1).split('/');	
		window.location.hash = _values[0] + "/" + city;
	}
	else {
		window.location.hash = "_ciudad/" + city;
	}
	ShowLoading("_results_city");
	jQuery.post("functions.php", 
		   { _nf: "content/data/ciudad/" + city + ".xml" }, 
		   function(_result) {
			   
			   document.getElementById("_results_city").innerHTML = _result;
			   jQuery("#_c_text_city").html("");
			   
			   if(document.getElementById("_script_graph") != undefined)
				   eval(document.getElementById("_script_graph").value);
						   
			   if( document.getElementById("_value_informado") != undefined) {	
			   	   jQuery("#_d_boletin").css("visibility", "visible");
				   jQuery("#_d_boletin").css("display", "inline");
				   jQuery("#_d_informado").css("visibility", "visible");
				   jQuery("#_d_informado").css("display", "inline");
				   jQuery("#_d_chart").css("visibility", "visible");
				   jQuery("#_d_chart").css("display", "inline");
				   jQuery("#_c_text_city").css("visibility", "visible");
				   jQuery("#_c_text_city").css("display", "inline");
				   
				   
				   jQuery("#_value_d_informado").html(document.getElementById("_value_informado").value + "%");
				   jQuery("#_value_d_boletin").html("#" + document.getElementById("_value_report").value);
				   jQuery("#_c_text_city").html( city == "BOGOTA" ? "BOGOT&Aacute; D.C." : (city == "MEDELLIN" ? "MEDELL&Iacute;N" : (city == "CUCUTA" ? "C&Uacute;CUTA" : city.replace('_', ' '))) );
				   
				   
				   jQuery("#_d_chart").click(function () { window.location.hash = "historico/ciudad/" + city.toLowerCase() + "/-1/1/1/1/1/1/1/1/1/1"; Change(document.getElementById("_historico")); });
			   }
			   else {
				   try {
					   jQuery("#_d_boletin").css("visibility", "hidden");
					   jQuery("#_d_boletin").css("display", "none");
					   jQuery("#_d_informado").css("visibility", "hidden");
					   jQuery("#_d_informado").css("display", "display");
					   jQuery("#_d_chart").css("visibility", "hidden");
				   	   jQuery("#_d_chart").css("display", "none");
					   jQuery("#_c_text_city").css("visibility", "hidden");
					   jQuery("#_c_text_city").css("display", "display");
				   }catch(e){}
			   }
			   StopLoading("_results_city");
		   }
	);
}

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;
}
var _colors = [];
function ShowChart() {
	
	var _type_value_chart = jQuery("#_type_search").val();
	
	if(_type_value_chart != "ciudad") { 
		document.getElementById("_city_search").value = "-1";
		document.getElementById("_city_tr_fitler").style.visibility = "hidden"; 
		document.getElementById("_city_tr_fitler").style.display = "none";
	}
	if(_type_value_chart != "regional") { 
		document.getElementById("_dept_chart").value = "-1";
		document.getElementById("_dept_tr_fitler").style.visibility = "hidden"; 
		document.getElementById("_dept_tr_fitler").style.display = "none";
	}
	if(_type_value_chart == "-1") { 
		_type_value_chart = document.getElementById("_type_search").value = "nacional";
	}
	window.parent.location.hash = "historico/" + 
			_type_value_chart + "/" + 
			document.getElementById("_city_search").value + "/" +
			document.getElementById("_dept_chart").value + "/" +
			jQuery("#_mockus:checked").length + "/" +
			jQuery("#_santos:checked").length;
	
	
	_colors = [];
	if(document.getElementById("_mockus").checked) {
		_colors.push("#ff7800");
	}
	if(document.getElementById("_santos").checked) {
		_colors.push("#259d00"); 
	}
	
	if(_type_value_chart == "nacional") {

		jQuery.ajax({
			type: "POST",
			url: "functions.php",
			data: { 
		   		_chart_nal: true, 
				dont_show_ana: true,
				is_ie: jQuery.browser.msie != undefined,
				mockus: jQuery("#_mockus:checked").length == 1,
				santos: jQuery("#_santos:checked").length == 1
			},
			beforeSend: function() {
				ShowLoading("chart_div");
			},
			success: function(_result) {
				eval(_result);		
			},
			error: function (a, b, c) {
				jQuery("#chart_div").html(a.responseText);
			}
		});
	}
	else if(_type_value_chart == "ciudad") {
		if(document.getElementById("_city_tr_fitler").style.visibility == "hidden") {
			document.getElementById("_city_tr_fitler").style.visibility = "visible";
			document.getElementById("_city_tr_fitler").style.display = "table-row";
		}else {
			if(document.getElementById("_city_search").value == "-1") return;
			ShowLoading("chart_div");
			jQuery.post("functions.php", 
			   { 
					_chart_ciu: true,
					city_filter: document.getElementById("_city_search").value,
					dont_show_ana: true,
				    is_ie: jQuery.browser.msie != undefined,
					mockus: jQuery("#_mockus:checked").length == 1,
					santos: jQuery("#_santos:checked").length == 1
				}, 
			   function(_result) {
				   eval(_result);
			   }
			);
		}
	}
	else if(_type_value_chart == "regional") {

		if(document.getElementById("_dept_tr_fitler").style.visibility == "hidden") {
			document.getElementById("_dept_tr_fitler").style.visibility = "visible";
			document.getElementById("_dept_tr_fitler").style.display = "table-row";
		}else {
			
			if(document.getElementById("_dept_chart").value == "-1") return;
			
			ShowLoading("chart_div");
			jQuery.post("functions.php", 
			   { 
					_chart_dept: true,
					city_filter: document.getElementById("_dept_chart").value,
					dont_show_ana: true,
				    is_ie: jQuery.browser.msie != undefined,
					mockus: jQuery("#_mockus:checked").length == 1,
					santos: jQuery("#_santos:checked").length == 1
				}, 
			   function(_result) {
				   eval(_result);
			   }
			);
		}
	}
	
}
function LoadChartHash() {
	var _type_value_chart = -1, _city_search = -1, _dept_chart = -1, _mockus = 1, _santos = 1;
	
	if(jQuery.trim(window.parent.location.hash) != "") {
		
		var _values = window.parent.location.hash.split('/');
		
		_type_value_chart = _values.length > 1 ? _values[1] : -1;
		_city_search = _values.length > 2 ? _values[2] : -1;
		_dept_chart = _values.length > 3 ? _values[3] : -1;
		
		_mockus = _values.length > 4 ? _values[4] : 1;
		_santos = _values.length > 5 ? _values[5] : 1;	
		
	}

	document.getElementById("_type_search").value = _type_value_chart;
	document.getElementById("_city_search").value = _city_search;
	document.getElementById("_dept_chart").value = _dept_chart;
	
	document.getElementById("_mockus").checked = _mockus == 1;
	document.getElementById("_santos").checked = _santos == 1;
	
		
	if(_type_value_chart == "ciudad") { 
		document.getElementById("_city_tr_fitler").style.visibility = "visible"; 
		document.getElementById("_city_tr_fitler").style.display = "table-row";
	}
	if(_type_value_chart == "regional") { 
		document.getElementById("_dept_tr_fitler").style.visibility = "visible"; 
		document.getElementById("_dept_tr_fitler").style.display = "table-row";
	}
	
	setTimeout("ShowChart()", 500);
}

function LoadSriptGoogle() {
   var head= document.getElementsByTagName('head')[0];
   var script= document.createElement('script');
   script.type= 'text/javascript';
   script.src= 'http://www.google.com/jsapi';
   head.appendChild(script);

}
function LoadSript(path) {
   var head= document.getElementsByTagName('head')[0];
   var script= document.createElement('script');
   script.type= 'text/javascript';
   script.src= path;
   head.appendChild(script);

}

LoadSriptGoogle();

if(window.google) {
	try {
	google.load("visualization", "1", {packages:["corechart"]});	
	google.load("visualization", "1", {packages:["imagelinechart"]});
	}catch(e) {}
}

function showTooltip(x, y, contents) {
	jQuery('<div id="tooltip" >' + contents + '</div>').css( {
		position: 'absolute',
		display: 'none',
		top: y + 5,
		left: x + 5,
		border: '1px solid #000',
		padding: '2px',
		'font-size': '12px',
		color: 'white',
		'font-family': 'Arial',
		'background-color': '#000',
		opacity: 0.80
	}).appendTo("body").fadeIn(200);
}

var ___records_chart_line = null;
var options = null;
function LoadG() {
	if(___records_chart_line == null) { alert("No hay datos para mostrar"); return }
	
	var options = {
					legend: 
					{ 
						show: true, 
						noColumns: 2, 
						backgroundColor: null,
						container: document.getElementById("cont_legend")
					},
					series: {
						lines: 
						{ 
							show: true,
							lineWidth: 1,
							fill: 0.02
						},
						points:
						{ 
							show: true
						}
					},
					grid: { 
						hoverable: true, 
						color: '#aaa', 
						borderWidth: 1,
						tickColor: '#f1f1f1'
					},
					selection: { mode: "xy", color: "#477e9e" },
					colors: _colors.length > 0 ? _colors : ["#259d00", "#ff7800"]
				};
	
	var plot = jQuery.plot(
					jQuery("#placeholder"), 
					___records_chart_line, 
					options);
	jQuery("#placeholder").bind("plothover", function (event, pos, item) {

		if (item) {
			if (previousPoint != item.datapoint) {
				previousPoint = item.datapoint;
				
				jQuery("#tooltip").remove();
				var x = item.datapoint[0].toFixed(2),
					y = item.datapoint[1].toFixed(2);

				showTooltip(item.pageX, item.pageY, "<b>" + item.series.label + "</b> | Bolet&iacute;n #<b>" + parseInt(x) + "</b> Total votos: <b>" + addCommas(parseInt(y)) + "</b>");
			}
		}
		else {
			jQuery("#tooltip").remove();			
			previousPoint = null;            
		}

    });
	
    var overview = jQuery.plot(jQuery("#overview"), ___records_chart_line, {
        legend: { show: false },
        series: {
            lines: { show: true, lineWidth: 1 },
            shadowSize: 0
        },
        xaxis: { ticks: 4 },
        yaxis: { ticks: 3, min: 0 },
        grid: { color: "#999" },
        selection: { mode: "xy", color: "#477e9e"  },
		colors: _colors.length > 0 ? _colors : ["#259d00", "#ff7800"]
    });    
    jQuery("#placeholder").bind("plotselected", function (event, ranges) {
        if (ranges.xaxis.to - ranges.xaxis.from < 0.00001)
            ranges.xaxis.to = ranges.xaxis.from + 0.00001;
        if (ranges.yaxis.to - ranges.yaxis.from < 0.00001)
            ranges.yaxis.to = ranges.yaxis.from + 0.00001;
        
        plot = jQuery.plot(jQuery("#placeholder"), ___records_chart_line,
                      jQuery.extend(true, {}, options, {
                          xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to },
                          yaxis: { min: ranges.yaxis.from, max: ranges.yaxis.to }
                      }));
        
        overview.setSelection(ranges, true);
    });
    jQuery("#overview").bind("plotselected", function (event, ranges) {
        plot.setSelection(ranges);
    });
}

var __callback_map = null;

function InitFunctionsMaps(callback) {
	InitHover();
	document.onmousemove = getMouseCoordinates;
	ShowLoading("map");
	setTimeout("__LoadToolTips()", 500);
	__callback_map = callback;
}
function __LoadToolTips() {
	jQuery.ajax({
			type: "POST",
			url: "functions.php",
			data: { 
		   		___tooltips_map: true,
				dont_show_ana: true
			},
			beforeSend: function() {
				//ShowLoading("map");
			},
			success: function(_result) {
				eval(_result);
				jQuery("map#__maping area").each(
					function (i, e) { 
						var _obj = _tooltips_map.findElement(e.alt, function (element, alt) { return element.department.toLowerCase() == alt.toString().toLowerCase().removeTilde(); });
						if(_obj	!= undefined) {
							var _santos = null, _mockus = null;
							if(_obj.info[0].name == "Santos"){
								_santos = _obj.info[0];
								_mockus = _obj.info[1];
							}else {
								_santos = _obj.info[1];
								_mockus = _obj.info[0];
							}
							var _id_div = e.alt.toString().toLowerCase().removeTilde().replaceAll(" ", "-").replaceAll(".", "");
	
							if(parseInt(_santos.votes) > parseInt(_mockus.votes)) {
								jQuery("#" + _id_div).css("background-image", "url(content/images/map/" + _id_div + "-u.gif)");
							}
							else {
								jQuery("#" + _id_div).css("background-image", "url(content/images/map/" + _id_div + "-verde.gif)");
							}
							e.setAttribute("percentu", _santos.percent);
							e.setAttribute("votesu", addCommas(_santos.votes));
							e.setAttribute("percentverde", _mockus.percent);
							e.setAttribute("votesverde", addCommas(_mockus.votes));
							
							e.setAttribute("boletin", _obj.boletin);
							e.setAttribute("informado", _obj.informado);
							
							e.setAttribute("href", "javascript:void(0);");
							jQuery("map#__maping area[alt=" + e.alt + "]").click(function () { ShowPie(this);});
	//						e.setAttribute("onclick", "javascript:ShowPie(this);");
						}
					}
				);
				StopLoading("map");
				if(__callback_map != null) {
					__callback_map();
				}
			},
			error: function (a, b, c) {
				alert("error: " + a.responseText);
			}
		});
}
