// JavaScript Document

var toggled = 0;
var recentHash = '';
var contenedor = '';

/*** Load Google Map ***/
//http://maps.google.es/maps?f=q&source=s_q&hl=es&geocode=&q=ferraz+100,+madrid&sll=40.396764,-3.713379&sspn=12.676975,19.6875&ie=UTF8&ll=40.431155,-3.722219&spn=0.012381,0.019226&z=16&iwloc=r2
function loadMap() {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("googlemap"));
		map.setCenter(new GLatLng(40.431155, -3.722219), 15);
		map.addControl(new GSmallMapControl());
		tipos = map.getMapTypes();
		map.setMapType(tipos[0]);
		
		var baseIcon = new GIcon();
		baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		baseIcon.iconSize = new GSize(20, 34);
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		baseIcon.infoShadowAnchor = new GPoint(18, 25);
		
		var marca = new GMarker(new GLatLng(40.431155, -3.722219));
		info = '<table><tr><td><image src="imgs/colpolsoc_mini.jpg" /></td<td><strong>Ilustre Colegio de<br />Doctores y Licenciados<br />en Ciencias Pol&iacute;ticas<br />y Sociolog&iacute;a</strong><br />C/ Ferraz, 100<br /></td</tr></table>';
		GEvent.addListener(marca, "click",
		function() {
			marca.openInfoWindowHtml(info);
		});
		
		map.addOverlay(marca);
	}
}

function showLoading(msg,target) {
	if (!target) elem_target = 'mainBody';
	else elem_target = target;
	
	if (!msg || msg == '') info = 'Cargando contenido';
	else info = msg;
	
	var elem = document.getElementById(elem_target);
	// Copiamos el contenido del contenedor y lo cambiamos por el de carga
	prev_content = elem.innerHTML;
	elem.innerHTML = '';
	// Creamos el div con el loading
	loadDiv = document.createElement('div');
	if (target == 'resultados') { loadDiv.id = 'loading_results'; }
	else if (target == 'grupos_td') { loadDiv.id = 'load_grupos'; }
	else { loadDiv.id = 'loading'; }
	
	loadDiv.innerHTML = '<img src="./imgs/ajax-loader.gif" /><br /><br />'+info+'...';
	elem.appendChild(loadDiv);
}

function confirmBox(target,params,values,msg) {
	$.prompt(msg,{            
        buttons:{Si:true,No:false},
		prefix:'impr_alert',
        callback: function(v) {
            if (v) {
				if(target == 'submit') document.del.submit();
				else callProcess(target,params,values);
            }
        }
    });
}

function showAlert(msg,target) {
	$.prompt(msg,{            
		prefix:'impr_alert',
        callback: function() {
			if (target == 'reload') window.location.reload();
			else callSection(target);
        }
    });
}

/****** Funciones de llamada Ajax ******/
function callProcess(current,params,values) {
	var query_string = '';
	var paramArray = params.split(",");
	var valueArray = values.split(",");
	for (var i=0; i<paramArray.length; i++) { 
		if (i==0) { 
			if (paramArray[i] == 'sugerencia') query_string += paramArray[i] + '=' + valueArray[i]; 
			else query_string += paramArray[i] + '=' + encodeURI(valueArray[i]); 
		}
		else { 
			if (paramArray[i] == 'sugerencia') query_string += '&' + paramArray[i] + '=' + valueArray[i]; 
			else query_string += '&' + paramArray[i] + '=' + encodeURI(valueArray[i]); 
		}
	}
	
	$.ajax({
		type: "POST",
		url: "./redirect.php",
		data: query_string,
		error: function(){
			alert('Error al procesar');
			callSection(current);
		},
		success: function(msg){
			/*$.prompt(msg,{
				prefix:'impr_alert'
			});
			callSection(current);*/
			showAlert(msg,current);
		}
	});
}

function callSection(section,target,msg) {	
	// Objeto contenedor donde se mostrara el resultado
	if (target) {
		var contenedor = document.getElementById(target);
		load_target = target;
	}
	else {
		var contenedor = document.getElementById('mainBody');
		load_target = 'mainBody';
	}
	
	if (!msg) showLoading('',load_target);
	else showLoading(msg,load_target);
	
	
	// Llamda Ajax
	$.ajax({
		type: "GET",
		url: "./redirect.php?section="+section,
		error: function(){
			contenedor.innerHTML = "Contenido no disponible";
		},
		success: function(msg){
			contenedor.innerHTML = msg;
			replaceEmails();
			if ((section == 'portada') || (section == 'noticias') || (section == 'enlaces_boletines') || (section == 'enlaces_organismos') || (section == 'enlaces_profesionales') || (section == 'agenda') || (section.match("portada&page=") == "portada&page=")) {
				toggled = 0;
				$(".togglerTitle").click(function () {
					toggler_id = $(this).attr("id");
					num = toggler_id.substr(toggler_id.lastIndexOf("_")+1,toggler_id.length-1);
					
					if ((toggled > 0) && (toggled != num)) 
						$("#elementContent_"+toggled).hide("slow", function () {
							$("#elementContent_"+num).show("slow");
						});
					else {
						if ($("#elementContent_"+num).css("display") == "none") $("#elementContent_"+num).show("slow");
						else $("#elementContent_"+num).hide("slow");
					}
					toggled = num;
				});
			}
			if (document.getElementById('campoFecha')) {
				$('#campoFecha').DatePicker({
					format:'d/m/Y',
					date: $('#campoFecha').val(),
					current: $('#campoFecha').val(),
					starts: 1,
					position: 'right',
					onBeforeShow: function(){
						$('#campoFecha').DatePickerSetDate($('#campoFecha').val(), true);
					},
					onChange: function(formated, dates){
						$('#campoFecha').val(formated);
					}
				});
			}
			$("a[@rel='history']").click(function(){
				var hash = this.href;
				hash = hash.replace(/^.*#/, '');
				changeItem(hash);
				return false;
			});
			if (section == 'contacto_colegio') { loadMap(); }
		}
	});
}
/****** Final de Funciones Ajax ******/

function changeItem(section) {
	ExpReg = /^[a-z_]+$/i;
	valid = ExpReg.test(section);
	if (!valid) section = 'portada';
	window.location.hash = section;
	
	document.title = "Colegio de Politólogos y Sociólogos de Madrid";
	/************ Google Analytics tracker ************/
	pageTracker._trackPageview(section); 
	/**************************************************/	
	callSection(section);
	return true;
}

function bbCode(bbcode, textarea, formulario)
{
	if (bbcode != 'url') {
		if (bbcode == 'b') msg = "en negrita";
		else if (bbcode == 'i') msg = "en cursiva";
		else if (bbcode == 'u') msg = "subrayado";
		var txt = prompt("Escribe el texto "+msg+":", "");
		eval("document."+formulario+"."+textarea+".value += '["+bbcode+"]"+txt+"[/"+bbcode+"]'");
	}
	else if (bbcode == 'url') {
		var url = prompt("Escribe la url de la web:", "http://");
		var n_url = prompt("Escribe el nombre de la web:", "");
		if (url != null) {
			if (n_url != null) {
				if (n_url == "") {
					n_url = url;
				}
		
				eval("document."+formulario+"."+textarea+".value += '["+bbcode+"="+url+"]"+n_url+"[/"+bbcode+"]'");
			}
		}
	}
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function bisiesto(ano) 
{
	if ((ano % 4 == 0) && ((ano % 100 != 0) || (ano % 400 == 0))) { return 29; }
	else { return 28; }
}	

function populateDias(total, formulario)
{
	if (formulario == 1) { diaList = document.getElementById('dia'); }
	else { diaList = document.getElementById('dia2'); }
	if(!diaList){return;}
	diaList.options.length = 0;
	diaList.options.length = total;
	for(var i=0;i<total;i++)
	{
		diaList.options[i].text=i+1;
		diaList.options[i].value=i+1;
	}
}

function changeDias(o, formulario) 
{
	mes = o.options[o.selectedIndex].value;
	if (formulario == 1) { diasEnero = bisiesto(document.getElementById('anio').value); }
	else { diasEnero = bisiesto(document.getElementById('anio2').value); }				
	if ((mes == 1) || (mes == 3) || (mes == 5) || (mes == 7) || (mes == 8) || (mes == 10) || (mes == 12)) { populateDias(31, formulario); }
	else if ((mes == 4) || (mes == 6) || (mes == 9) || (mes == 11)) { populateDias(30, formulario); }
	else { populateDias(diasEnero, formulario); }
}

function populate(o, formulario)
{
	if (formulario == 1) { mesList=document.getElementById('mes'); }
	else { mesList=document.getElementById('mes2'); }
	if(!mesList){return;}
	mesList.options.selectedIndex = 0;		
	populateDias(31, formulario);
}

function reload_page() {
	window.location.href = unescape(window.location.pathname);
}

function Abrir_ventana (pagina) {
	var opciones="toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, width=500, height=450, top=center, left=center";
	window.open(pagina,"",opciones);
}

/** Esconde los correos para evitar bots de spam **/
function replaceEmails() {
	if (!document.getElementsByTagName && !document.createElement &&
		!document.createTextNode) return;
	var nodes = document.getElementsByTagName("span");
	for(var i=nodes.length-1;i>=0;i--) {
		if (nodes[i].className=="change") {
			var at = / at /;
			var dot = / dot /g;
			var node = document.createElement("a");
			var address = nodes[i].firstChild.nodeValue;

			address = address.replace(at, "@");
			address = address.replace(dot, ".");

			address = address.replace(at, "@");
			address = address.replace(dot, ".");
			node.className = nodes[i].title;
			node.setAttribute("href", "mailto:"+address);
			node.appendChild(document.createTextNode(address));
			
			var prnt = nodes[i].parentNode;
			for(var j=0;j<prnt.childNodes.length;j++)
				if (prnt.childNodes[j] == nodes[i]) {
					if (!prnt.replaceChild) return;
					prnt.replaceChild(node, prnt.childNodes[j]);
					break;
				}
		}
	}
}