/*
 * common routines
 * org.notariado.inti.bcn.MaxNoe 20040517
 */

/*
 * The starting routine is attached to the
 * page including the script.
 */

window.onload = startUp;

/*
 * this function is called at body.onLoad, so
 * if there is a function that needs to be
 * executed everytime a page is loaded, it
 * should be called here.
 */

/*var delayb4scroll=1000 ;//Specify initial delay before marquee starts to scroll on page (2000=2 seconds)
var marqueespeed=1 ;//Specify marquee scroll speed (larger is faster 1-10)
var pauseit=1 ;//Pause marquee onMousever (0=no. 1=yes)?

var copyspeed=marqueespeed;
var pausespeed=(pauseit==0)? copyspeed: 0;
var actualheight='';
function scrollmarquee(){
	if (parseInt(cross_marquee.style.top)>(actualheight*(-1)+8))
		cross_marquee.style.top=parseInt(cross_marquee.style.top)-copyspeed+"px"
	else
		cross_marquee.style.top=parseInt(marqueeheight)+8+"px"
	}

function initializemarquee(){
	cross_marquee=document.getElementById("vmarquee");
	if (cross_marquee) {
		cross_marquee.style.top = 0;
		marqueeheight = document.getElementById("marqueecontainer").offsetHeight;
		actualheight = cross_marquee.offsetHeight;
		if (window.opera || navigator.userAgent.indexOf("Netscape/7") != -1) { //if Opera or Netscape 7x, add scrollbars to scroll and exit
			cross_marquee.style.height = marqueeheight + "px";
			cross_marquee.style.overflow = "scroll";
			return;
		}
		setTimeout('lefttime=setInterval("scrollmarquee()",30)', delayb4scroll);
	}else
		return;
	
}

*/
function startUp() {
	correctExternalLinks();
	correctFormElementsNames();
	setFocus();
	enableEnter();
    applicationDate();
    escapeEuro();
	//initializemarquee();
	return true;
}

/*
 * forces the external links to open in a new
 * window, in a manner that validates against
 * XHTML Strict. This last one does not allow
 * 'target="_blank"' anymore, but the DOM does.
 */
function correctExternalLinks() {
	// run through every a tag in the document	
	var serverSplit = window.location.hostname.split(".");
	//colegio.notariado.org
	var serverName = serverSplit[serverSplit.length-3] + "." + serverSplit[serverSplit.length-2] + "." + serverSplit[serverSplit.length-1];

	for (var index = 0; index <= (document.links.length - 1); index++) {
		if(document.links[index].parentNode.id!='banner_andalucia'){
			var URL = document.links[index].href;
			// any links not containing the current server name are outbound.
			if ((URL.indexOf(serverName) < 0) && (URL.indexOf('javascript') != 0)) {
				document.links[index].target = "_blank";
			} else {
				document.links[index].target = "";
			}
		}
	}

	return true;
}

/*
 * Ensures that each element in a form
 * has a name, copying it from the id,
 * if none found. This yields future
 * compatibility with XHTML1.1.
 */
function correctFormElementsNames() {
	for (var index = 0; index < document.forms.length; index++) {
		var currentForm = document.forms[index];
		for (var elementIndex = 0; index < currentForm.elements.length; elementIndex++) {
			var formElement = currentForm.elements[elementIndex];
			if (formElement) {
				if ((formElement.name == "") && (formElement.id != "")) {
					formElement.name = formElement.id;
				}
			} else {
				// If formElement is undefined, somehow the loop
				// restarts and enters an infinite loop.
				break;
			}
		}
	}

	return true;
}

/*
 * sets the focus at the first form field.
 */
function setFocus() {
	if (document.forms[0]) {
		var editableTypes = {checkbox:"", "select-one":"", text:"", textarea:"", radio:""};
		var formElements = document.forms[0].elements;
		for (var index = 0; index < formElements.length; index++) {
			if ((formElements[index].type in editableTypes) && (!formElements[index].disabled)) {
				formElements[index].focus();
				break;
			}
		}
	}

	return true;
}

function openWindow(strUrl, strWindowName, strWindowFeatures){
    windowName = strWindowName;
    if (windowName == null)
       windowName = '';

    if (strWindowFeatures != null){
       window.window.open(strUrl, windowName, strWindowFeatures);

    } else {
      window.window.open(strUrl, windowName, 'location=0,menubar=1,resizable=1,scrollbars=1,status=1,toolbar=1,fullscreen=0,width=600,height=450');
    }
}

/* Modified to support Opera */
function bookmarksite(title,url){
	if (window.sidebar) // firefox
		window.sidebar.addPanel(title, url, "");
	else if(window.opera && window.print){ // opera
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	}
	else if(document.all)// ie
		window.external.AddFavorite(url, title);
}

/*
 * Enables the keypress of Enter as
 * a means to submit a form.
 */
function enableEnter() {
	// TODO: Attach Enter keypress event to all input/text.
}

function applicationDate() {
    var elem = document.getElementById('application_date');
    if (elem) {
	    var currentDate = new Date().toLocaleDateString();
	    currentDate = currentDate.substr(0,1).toUpperCase() + currentDate.substr(1);
        elem.innerHTML = currentDate;
    }
}

function wprinter(section, option) {
    var params = "toolbar=no,location=no, status=no,menubar=no,scrollbars=yes, resizable=no, titlebar=no, left=1,top=1";
//	width
	var content = document.getElementById('content');
	if (content) {
		if (content.style.width == '') 
			var ancho = content.innerWidth+20;
		else 
			var ancho = content.style.width+20;
			
		params = params + ",width=" + ancho;
		document.body.style.width = "auto";
	}
    printerpage = window.open('?do=' + section + '&option=' + option + '&mode=wvpr', 'Printer', params);
}


function openColegioMap(Code, Title) {
    var wWin = (screen.width - 500) / 2;
    var hWin = (screen.height - 565) / 2;
    var url = "http://www.viamichelin.com/b2b2c/esp/dyn/controller/dlPoiAccess?productId=82081&name=" + Title + "&id=" + Code + "&typeZoom=400";
    var params = "toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no,titlebar=no,width=500,height=565,left="+wWin+",top="+hWin;
    window.open(url,"mapaBilbao",params);
}



function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function compareDates(){

	var today = new Date();
	var todayDay = today.getDate();
	var todayMonth = today.getMonth()+1;
	var todayYear = today.getYear();

	dayLapsing = document.getElementById('dayLapsing').value;
	monthLapsing = document.getElementById('monthLapsing').value;
	yearLapsing = document.getElementById('yearLapsing').value;
	dayPublish = document.getElementById('dayPublish').value;
	monthPublish = document.getElementById('monthPublish').value;
	yearPublish = document.getElementById('yearPublish').value;

	var lapsingDate=new Date(yearLapsing,(monthLapsing-1),dayLapsing);
	var publishDate=new Date(yearPublish,(monthPublish-1),dayPublish);

	if (lapsingDate < today ){
		alert('La fecha de caducidad debe ser superior a ' +todayDay+'/'+todayMonth+'/'+todayYear+".");
		return false;
	}else if (lapsingDate < publishDate) {
		alert('La fecha de caducidad debe ser mayor a la fecha de publicación.');
		return false;
	}else{
		return true;
	}
}

function addEvent(obj, evType, fn){
	if (typeof(Event) != "undefined" && typeof(Event.observe) != "undefined") { // con prototype.js
		Event.observe(obj, evType, fn);
	} else { // sin prototype.js
		if (obj.addEventListener){
		   obj.addEventListener(evType, fn, true);
		   return true;
		} else if (obj.attachEvent){
		   var r = obj.attachEvent("on"+evType, fn);
		   return r;
		} else {
		   return false;
		}
	}
}

function newCheckUrl(){
	var selected = document.forms[0].option_type.selectedIndex;
	if(document.forms[0].option_type.options[selected].value == 'database'){
		document.getElementById('urldiv').style.display = 'none';
		document.getElementById('contentdiv').style.display = 'inline';		
	} else if(document.forms[0].option_type.options[selected].value == 'link') {
		document.getElementById('urldiv').style.display = 'inline';
		document.getElementById('contentdiv').style.display = 'none';	
	} else {
		document.getElementById('contentdiv').style.display = 'none';	
		document.getElementById('urldiv').style.display = 'none';
	}
	
}
function checkUrl() {
	if (document.forms[0].option_type.selectedIndex == 1) {
		document.getElementById('urldiv').style.display = 'inline';
		document.getElementById('contentdiv').style.display = 'none';
	} else {
		document.getElementById('urldiv').style.display = 'none';
		document.getElementById('contentdiv').style.display = 'inline';
	}
}

/*
 * Unless url all the arguments are optionals
 */
function openframe(url, name, width, height, scrollbars, resizable) {

	if (!width) width = parseInt((screen.width*97)/100);
	if (!height) height = parseInt((screen.height*97)/100);

	if (!scrollbars) scrollbars = 1;
	if (!resizable) resizable = 1;

	var w = width;
	var h = height;
	var posx = (screen.width-w)/2;
	var posy = (screen.height-(h))/2;

	// alert(screen.width + ',' + screen.height);
	// alert(w + ',' + h + ':' + posx + ',' + posy);

  	var settings  ='height='+(h-150)+',';
    	settings +='width='+w+',';
      	settings +='top='+posy+',';
      	settings +='left='+posx+',';
      	settings +='location=0,';
      	settings +='menubar=0,';
      	settings +='directories=0,';
      	settings +='scrollbars='+scrollbars+',';
      	settings +='status=1,';
      	settings +='resizable='+resizable+'';

	var backoffice = window.open(url, name, settings);

	if (parseInt(navigator.appVersion) >= 4) {
		backoffice.window.focus();
	}

	// Make parent window not to load url
	return backoffice;
}
function checkProtocolForm(resetCuv, castellano){
	if(resetCuv==true)
		document.forms[0].cuv.value = null;
	
	var checked = true;
	var message = '';
	var nombre = document.forms[0].nombre.value;
	var apellidos = document.forms[0].apellidos.value;
	var fechaBusqueda = document.forms[0].fecha.value;
	if ((nombre.replace(/^\s*|\s*$/g,"")=="" && apellidos.replace(/^\s*|\s*$/g,"")=="" && fechaBusqueda.replace(/^\s*|\s*$/g,"")=="") 
		|| 
		((nombre.replace(/^\s*|\s*$/g,"")=="" && apellidos.replace(/^\s*|\s*$/g,"")!='') || (nombre.replace(/^\s*|\s*$/g,"")!='' && apellidos.replace(/^\s*|\s*$/g,"")=='')) 
		|| 
		(nombre.replace(/^\s*|\s*$/g,"")=="" && apellidos.replace(/^\s*|\s*$/g,"")=="")
		||
		(fechaBusqueda == '' )) {
			
		checked = false;
		message = 'Por favor, introduzca los campos de búsqueda solicitados.';
	}
	if (document.forms[0].fecha.value == '') {
		checked = false;
		message = 'Por favor, introduzca los campos de búsqueda solicitados.';
	} else {
		if(castellano==true){
			if (!esFechaValida(document.forms[0].fecha)) {
				checked = false;
				message = 'La fecha introducida no es correcta.';
			}
		} else {
			if (!esFechaValidaEuskera(document.forms[0].fecha)) {
				checked = false;
				message = 'La fecha introducida no es correcta.';
			}
		}
	}
	if(checked)
		document.forms[0].submit();
	else
		alert(message);
	
}


function checkDateFormat(fecha){	
	var tempDate = fecha.split('/');
	if(tempDate.length==3){
		if(tempDate[0]<10 && tempDate[0].indexOf(0)==-1){
			tempDate[0] = "0"+ tempDate[0];
		}
		if (tempDate[1] < 10 && tempDate[1].indexOf(0) == -1) {
			tempDate[1] = "0"+ tempDate[1];
		}
		
		document.forms[0].fecha.value	 = tempDate.join("/");
		return true;
	}else{
		return false;
	}	
}
function esFechaValida(fecha){
	if (fecha != undefined && fecha.value != "" && checkDateFormat(fecha.value)){
		if (!/^\d{2}\/\d{2}\/\d{4}$/.test(fecha.value)){
			//alert("formato de fecha no válido (dd/mm/aaaa)");
			return false;
		}
		var dia  =  parseInt(fecha.value.substring(0,2),10);
		var mes  =  parseInt(fecha.value.substring(3,5),10);
		var anio =  parseInt(fecha.value.substring(6),10);
	switch(mes){
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			numDias=31;
			break;
		case 4: case 6: case 9: case 11:
			numDias=30;
			break;
		case 2:
			if (comprobarSiBisisesto(anio)){ numDias=29 }else{ numDias=28};
			break;
		default:
			return false;
	}
		if (dia>numDias || dia==0){
			return false;
		}
		var actualDate = new Date();
		if(parseInt(actualDate.getFullYear(),10)< parseInt(anio,10)){
			return false;
		}
		
		return true;
	}
}

function esFechaValidaEuskera(fecha){
	if (fecha != undefined && fecha.value != "" && checkDateFormat(fecha.value)){
		if (!/^\d{4}\/\d{2}\/\d{2}$/.test(fecha.value)){
			//alert("formato de fecha no válido (uuuu/hh/ee)");
			return false;
		}
		var anio =  parseInt(fecha.value.substring(0,4),10);
		var mes  =  parseInt(fecha.value.substring(5,7),10);
		var dia  =  parseInt(fecha.value.substring(8),10);
		
	switch(mes){
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			numDias=31;
			break;
		case 4: case 6: case 9: case 11:
			numDias=30;
			break;
		case 2:
			if (comprobarSiBisisesto(anio)){ numDias=29 }else{ numDias=28};
			break;
		default:
			return false;
	}
		if (dia>numDias || dia==0){
			return false;
		}
		var actualDate = new Date();
		if(parseInt(actualDate.getFullYear(),10)< parseInt(anio,10)){
			return false;
		}
		
		return true;
	}
}

function comprobarSiBisisesto(anio){
	if ( ( anio % 100 != 0) && ((anio % 4 == 0) || (anio % 400 == 0))) {
		return true;
		}
	else {
		return false;
		}
}
function setSearch(cuv){
	document.forms[0].cuv.value = cuv;
	checkProtocolForm(false);
}
/*function setSearch(apellidos, nombre){
	document.forms[0].nombre.value = nombre.replace("+"," ");
	document.forms[0].apellidos.value = apellidos.replace("+"," ");
}*/
function openGmap(dominio, titulo, cc, infoData){
	var url = dominio + '&title=' + escape(titulo) + '&codigo_catastro=' + cc + '&direccion=' + escape(infoData);
	var widthWindow = 500;
	var heightWindow = 300;
	var leftWindow = (screen.width - widthWindow) / 2;
	var topWindow = (screen.height - heightWindow) / 2;
	var params = "toolbar=no,location=no, status=no,menubar=no,scrollbars=no, resizable=no, titlebar=no, width=" + widthWindow + ", height=" + heightWindow + ", left=" + leftWindow + ",top=" + topWindow;
	openWindow(url, "gMap", params);
}
function openWindow(strUrl, strWindowName, strWindowFeatures){
	windowName = strWindowName;
	if (windowName == null)
		windowName = '';
	if (strWindowFeatures != null){
		window.window.open(strUrl, windowName, strWindowFeatures);
	} else {
		window.window.open(strUrl, windowName, 'location=0,menubar=1,resizable=1,scrollbars=1,status=1,toolbar=1,fullscreen=0,width=600,height=450');
	}
}


                      
function fixImprimir(){
	//funcion para arreglar en caso de que fuera necesario
	//javascript:wprinter('contenidos','ficheros');
	var url = parent.document.location.href;
	var section;
	var option = "";
	//var a_imprimir = document.getElementById('a_printer');
	//if(a_imprimir){
		url = url.split('?');
		url = url[1];
		section = url.split('&');
		section = section[0];
		section = section.split("=");
		section = section[1];
		url = url.split('&');
		for(i=1;i<=(url.length-1);i++){
			var tempOption = '';
			if(url[i].indexOf("option")!=-1){
					url[i] = url[i].split("=");
					url[i] = url[i][1];
			}
			if(option=='')
				option = url[i];
			else	
				option = option + "&" + url[i];
		}
		//a_imprimir.href = "javascript:wprinter('"+section+"','"+option+"')";
	//}
	var toPrint = '';
	toPrint = "?do=" + section;
	if(option!='')
		toPrint = toPrint + "&option=" + option;
	toPrint = toPrint + "&mode=wvpr";
	setTimeout(setLocation(toPrint), 0);
}


function aweRedirect(url){
	url = "?do=awe.redirect&url="+escape(url);
	setLocation(url);
}
function setLocation(url){
	window.location = url;
}

function escapeEuro()
{
	if (!document.getElementsByTagName) 
		return false; 
	var elementsA = document.getElementsByTagName('a'); 
	for (var i = 0; i < elementsA.length; i++) {
		if(elementsA[i].title)
			elementsA[i].title=html_entity_decode(elementsA[i].title.replace(/&euro;/gi,"&#8364;"));
	} 
}



function html_entity_decode(str) {
    var ta = document.createElement("textarea");
	ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
    toReturn = ta.value;
    ta = null;
      return toReturn

 }


