// ********************************************************************************************************
// Coleccion de funciones para comprobar que una imagen de un campo de tipo file es correcta.
// ********************************************************************************************************
	// Sobresuponemos que va bien
	var imagenFueErronea=false;

	// Carga la imagen en un img oculto que DEBE existir en el formulario
	function compruebaImagen(imgSrc,imgTag)
	{
		testImage = new Image();
		testImage.src = imgSrc;
		imgTag.src=testImage.src;
	}
	// En el img oculto ponemos esta funcion en el evento onError ya que de esta manera sabemos 
	// que la imagen no se cargó.
	function imagenErronea()
	{
		alert("El archivo cargado no es una imágen");
		imagenFueErronea=true;
	}
	// En el img oculto ponemos esta funcion en el evento onLoad ya que de esta manera sabemos 
	// que la imagen se cargó correctamente.
	function imagenCorrecta()
	{
		imagenFueErronea=false;
	}

	// Si Tenemos un botón "ver imagen" podemos regula su funcionamiento desde aquí.
	function verImagen(imagen)
	{
		if(!imagenFueErronea && imagen!="")
		{			
			mostrarImagen(imagen);
		}
		else
		{
			alert("No hay una imagen válida cargada");
		}
	}

	//FUNCION QUE MUESTRA UNA IMAGEN
	function mostrarImagen(imagen)
	{
		
		// Creem una imatge a partir de la ruta i del parámetre
		var img = new Image();
		img.src= imagen;
		
		img.onLoad = (ven_imagen=window.open("","ventana","width=400,height=400,resizable")); //abrir_ventana_imagen(img);
		ven_imagen.document.write("<html><body style=\"margin:0px\"><img id=\"imag\" src=\""+imagen+"\"></body></html>");
		ven_imagen.window.resizeTo(img.width+10,img.height+53);
		
	}
	
	function abrir_ventana_imagen(imagen)
	{		
		var rutaImg = imagen.src.replace("file:///","");		
		alert(imagen.height);
		// Obrim una finestra, li fiquema la imatge al body (sense marges)
		// i li canviem la mida a la finestra a partir de la mida de la imatge.		
		ven_imagen=window.open(rutaImg,"ventana","resizable,width=400,height=400;");		
		//ven_imagen.document.write("<html><body style=\"margin:0px\"><img id=\"imag\" src="+url+"></body></html>");		
		ven_imagen.window.resizeTo(imagen.width+10,imagen.height+53);
		ven_imagen.focus();		
	}

	function recuperarIndiceOpcion(input)
	{
		for(i=0;i<input.length;i++)
		{
			if(input[i].checked)
			{
				return i;
			}
		}
		return -1;
	}


// ********************************************************************************************************
// Coleccion de funciones genéricas
// ********************************************************************************************************
function trim(sString)
{
	sString = leftTrim(sString);
	sString = rightTrim(sString);
	return sString;
}

function leftTrim(sString)
{
	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}
	return sString;
}

function rightTrim(sString)
{
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}


function canviaVis(id)
{
	
	itm = extrauControl(id);
	

	if (!itm) 
	{
	  // do nothing
	}
	else if (itm.style) 
	{
		if (itm.style.display == "none") 
		{
			itm.style.display = ""; 
		}
		else 
		{ 
			itm.style.display = "none"; 
		}
	}
	else 
	{ 
		itm.visibility = "show"; 
	}
}

function posaVis(id,vis)
{
	itm = extrauControl(id);

	if (!itm) 
	{
	  // do nothing
	}
	else if (itm.style) 
	{
		itm.style.display = vis; 
	}
	else 
	{ 
		itm.visibility = "show"; 
	}
}
function extrauControl(id)
{
	var itm = null;
	if (document.getElementById) 
	{
		itm = document.getElementById(id);
	}
	else if (document.all)
	{
		itm = document.all[id];
	}
	else if (document.layers)
	{
		itm = document.layers[id];
	}

	return itm;
}

function canviaDesplegable(id)
{
	img = extrauControl("img_" + id);
	
	if(img.src.match("/mas.gif")!=null)
	{
		img.src="/imagenes/iconos/menos.gif";
	}
	else
	{
		img.src="/imagenes/iconos/mas.gif";
	}
	
	canviaVis(id);
}


function cuentaLineas(txa,cont)
{
	itTxa = extrauControl(txa);
	itCont = extrauControl(cont);
	
	campo = itTxa.value;
	
	numLin = 1;
	numChars=0;
	for(i=0;i<campo.length;i++)
	{
		// Primero miramos is es un salto de linia
		if(campo.charCodeAt(i)==10 || numChars==40)
		{
			// sumamos una linia
			numLin++;
			// Reseteamos los caracteres
			numChars=0;
		}
		else
		{
			numChars++;
		}
	}
	
	itCont.value=numLin;
}

function aConsultar(id)
{
	itm = extrauControl(id);
	
	if(itm)
	{
		itm.value=-1;
	}
}


function captureMousePosition(e){
	xMousePos = window.event.x+document.body.scrollLeft;
	yMousePos = window.event.y+document.body.scrollTop;
	xMousePosMax = document.body.clientWidth+document.body.scrollLeft;
	yMousePosMax = document.body.clientHeight+document.body.scrollTop;
}

//FUNCIONES EFECTOS FILAS LISTA y COMENTARIOS
function activar_titulo(id,tipo)
{
	marcar_ruta(id,tipo);
}
function marcar_ruta(id_td,tipo)
{
	//tipo=1 es onmouseover
	//tipo=0 es onmouseout
	celda = extrauControl("td" + id_td);
	actual = celda.className;
	iluminada = "td-list-over > ";
	
	if (tipo==1)
	{
		clase = iluminada + actual;		
	}
	else
	{		
		clase = actual.replace(iluminada,"");
	}		
	
	celda.className = clase;
	delete celda;
}
function marcar_contacto(id_td,tipo)
{
	marcar_ruta(id_td,tipo);
}

function IrAPagina (Pagina)
{
	window.location.href=Pagina;
	return;
}
function AbrirPop(A,B,C)
{
	w_emergente = window.open(A,B,C);
	return false;
}
function abrir_ventana_general(A,B,C)
{
	w_emergente = window.open(A,B,C);
	return false;
}
function FechaDMYValida(Fecha, Mensaje) {
	  var blnEsValida=true;
	  var re = new RegExp("/");
	  var barra1 = Fecha.search(re);
	  if (barra1!=-1)
		  var barra2 = Fecha.substr(barra1+1).search(re);
	  else
		  var barra2 = -1;
	  if (barra1 >2 | barra1 <1   | barra2 >2 | barra2 <1 | Fecha.length < barra1 + barra2 + 4)
		{
		blnEsValida = false;
		}
	  else
		{
		var intDia = Fecha.substr(0,barra1);
		var intMes = Fecha.substr(barra1 + 1, barra2);
		var intAnio = Fecha.substr(barra1 + barra2 + 2, 4);
		var	FechaIngresada = intDia + '/' + intMes + '/' + intAnio;
		Fecha = FechaIngresada;
		var d = new Date(intAnio,intMes-1,intDia);
		intDiaEnFecha = d.getDate();
		intMesEnFecha = d.getMonth() + 1;
		intAnioEnFecha = d.getYear();
		if (intDiaEnFecha != intDia | intMesEnFecha !=intMes | intAnioEnFecha != intAnio)	
			blnEsValida = false;
		}
		if (!blnEsValida) 
			alert(Mensaje);
		return blnEsValida;
}
function esDigito (c)
{   return ((c >= "0") && (c <= "9"))
}

function esEntero (s)
{   var i;

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if( i != 0 ) {
            if (!esDigito(c)) return false;
        } else { 
            if (!esDigito(c) && (c != "-") || (c == "+")) return false;
        }
    }
    return true;
}
function LimitarTextArea(txt, theForm, longitudMaxima)
{
	var longitudTexto;

	longitudTexto = theForm[txt].value.length;
	
	if (longitudTexto > longitudMaxima)
	{
		theForm[txt].value = theForm[txt].value.substring(0,longitudMaxima);
	}
}

function quitarParametroUrl(url,param)
{
	// Partimos la url en 2, la dirección propiamente dicha y los parámetros
	urlD = url.split("?");
	
	// Empezamos a crear la nueva url usando la dirección y le ponemos el ? para separarla de los futuros parámetros
	newUrl=urlD[0] + "?";
	
	// Partimos los parámetros usando el caracter & que nos permite distinguirlos
	parametros = urlD[1].split("&");	
	for(i=0;i<parametros.length;i++)
	{					
		// Separamos el parámetro de su valor a partir del =
		parametro = parametros[i].split("=");
		// Miramos si es el parámetro a quitar, y si no lo es, agregamos la información del parámetro a la nueva url
		if(parametro[0]!=param)
		{
			newUrl += parametros[i] + "&";
		}
	}
	// Por último, quitamos el último carácter. Si hay parámetros este sera un & de más, y sino hay, quitaremos el ? que no hace falta
	newUrl = newUrl.substr(0,newUrl.length-1);
	
	return newUrl;
}

function gestionMarca(elem,estado){
	var check;
	
	arr = elem.split(",");
	for(var i=0;i<arr.length;i++){
		check = extrauControl("eliminarReg_" + arr[i])
		check.checked = estado;
	}
}

/**
*
*  Scrollable HTML table
*  http://www.webtoolkit.info/
*
**/
 
function ScrollableTable (tableEl, tableHeight, tableWidth) {
 
	this.initIEengine = function () {
 
		this.containerEl.style.overflowY = 'auto';
		if (this.tableEl.parentElement.clientHeight - this.tableEl.offsetHeight < 0) {
			this.tableEl.style.width = this.newWidth - this.scrollWidth +'px';
		} else {
			this.containerEl.style.overflowY = 'hidden';
			this.tableEl.style.width = this.newWidth +'px';
		}
 
		if (this.thead) {
			var trs = this.thead.getElementsByTagName('tr');
			for (x=0; x<trs.length; x++) {
				trs[x].style.position ='relative';
				trs[x].style.setExpression("top",  "this.parentElement.parentElement.parentElement.scrollTop + 'px'");
			}
		}
 
		if (this.tfoot) {
			var trs = this.tfoot.getElementsByTagName('tr');
			for (x=0; x<trs.length; x++) {
				trs[x].style.position ='relative';
				trs[x].style.setExpression("bottom",  "(this.parentElement.parentElement.offsetHeight - this.parentElement.parentElement.parentElement.clientHeight - this.parentElement.parentElement.parentElement.scrollTop) + 'px'");
			}
		}
 
		eval("window.attachEvent('onresize', function () { document.getElementById('" + this.tableEl.id + "').style.visibility = 'hidden'; document.getElementById('" + this.tableEl.id + "').style.visibility = 'visible'; } )");
	};
 
 
	this.initFFengine = function () {
		this.containerEl.style.overflow = 'hidden';
		this.tableEl.style.width = this.newWidth + 'px';
 
		var headHeight = (this.thead) ? this.thead.clientHeight : 0;
		var footHeight = (this.tfoot) ? this.tfoot.clientHeight : 0;
		var bodyHeight = this.tbody.clientHeight;
		var trs = this.tbody.getElementsByTagName('tr');
		if (bodyHeight >= (this.newHeight - (headHeight + footHeight))) {
			this.tbody.style.overflow = '-moz-scrollbars-vertical';
			for (x=0; x<trs.length; x++) {
				var tds = trs[x].getElementsByTagName('td');
				tds[tds.length-1].style.paddingRight += this.scrollWidth + 'px';
			}
		} else {
			this.tbody.style.overflow = '-moz-scrollbars-none';
		}
 
		var cellSpacing = (this.tableEl.offsetHeight - (this.tbody.clientHeight + headHeight + footHeight)) / 4;
		this.tbody.style.height = (this.newHeight - (headHeight + cellSpacing * 2) - (footHeight + cellSpacing * 2)) + 'px';
 
	};
 
	this.tableEl = tableEl;
	this.scrollWidth = 16;
 
	this.originalHeight = this.tableEl.clientHeight;
	this.originalWidth = this.tableEl.clientWidth;
 
	this.newHeight = parseInt(tableHeight);
	this.newWidth = tableWidth ? parseInt(tableWidth) : this.originalWidth;
 
	this.tableEl.style.height = 'auto';
	this.tableEl.removeAttribute('height');
	
	this.containerEl = this.tableEl.parentNode.insertBefore(document.createElement('div'), this.tableEl);
	this.containerEl.appendChild(this.tableEl);
	this.containerEl.style.height = this.newHeight + 'px';
	this.containerEl.style.width = this.newWidth + 'px';
 
 
	var thead = this.tableEl.getElementsByTagName('thead');
	this.thead = (thead[0]) ? thead[0] : null;
 
	var tfoot = this.tableEl.getElementsByTagName('tfoot');
	this.tfoot = (tfoot[0]) ? tfoot[0] : null;
 
	var tbody = this.tableEl.getElementsByTagName('tbody');
	this.tbody = (tbody[0]) ? tbody[0] : null;
 
	if (!this.tbody) return;
 
	if (document.all && document.getElementById && !window.opera) this.initIEengine();
	if (!document.all && document.getElementById && !window.opera) this.initFFengine();
 
 
}
	
/**
*
*  Sortable HTML table
*  http://www.webtoolkit.info/
*
**/
 
function SortableTable (tableEl) {
 
	this.tbody = tableEl.getElementsByTagName('tbody');
	this.thead = tableEl.getElementsByTagName('thead');
	this.tfoot = tableEl.getElementsByTagName('tfoot');
 
	this.getInnerText = function (el) {
		if (typeof(el.textContent) != 'undefined') return el.textContent;
		if (typeof(el.innerText) != 'undefined') return el.innerText;
		if (typeof(el.innerHTML) == 'string') return el.innerHTML.replace(/<[^<>]+>/g,'');
	}
 
	this.getParent = function (el, pTagName) {
		if (el == null) return null;
		else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())
			return el;
		else
			return this.getParent(el.parentNode, pTagName);
	}
 
	this.sort = function (cell) {
 
	    var column = cell.cellIndex;
	    var itm = this.getInnerText(this.tbody[0].rows[1].cells[column]);
		var sortfn = this.sortCaseInsensitive;
 
		if (itm.match(/\d\d[-]+\d\d[-]+\d\d\d\d/)) sortfn = this.sortDate; // date format mm-dd-yyyy
		if (itm.replace(/^\s+|\s+$/g,"").match(/^[\d\.]+$/)) sortfn = this.sortNumeric;
 
		this.sortColumnIndex = column;
 
	    var newRows = new Array();
	    for (j = 0; j < this.tbody[0].rows.length; j++) {
			newRows[j] = this.tbody[0].rows[j];
		}
 
		newRows.sort(sortfn);
 
		if (cell.getAttribute("sortdir") == 'down') {
			newRows.reverse();
			cell.setAttribute('sortdir','up');
		} else {
			cell.setAttribute('sortdir','down');
		}
 
		for (i=0;i<newRows.length;i++) {
			this.tbody[0].appendChild(newRows[i]);
		}
 
	}
 
	this.sortCaseInsensitive = function(a,b) {
		aa = thisObject.getInnerText(a.cells[thisObject.sortColumnIndex]).toLowerCase();
		bb = thisObject.getInnerText(b.cells[thisObject.sortColumnIndex]).toLowerCase();
		if (aa==bb) return 0;
		if (aa<bb) return -1;
		return 1;
	}
 
	this.sortDate = function(a,b) {
		aa = thisObject.getInnerText(a.cells[thisObject.sortColumnIndex]);
		bb = thisObject.getInnerText(b.cells[thisObject.sortColumnIndex]);
		date1 = aa.substr(6,4)+aa.substr(3,2)+aa.substr(0,2);
		date2 = bb.substr(6,4)+bb.substr(3,2)+bb.substr(0,2);
		if (date1==date2) return 0;
		if (date1<date2) return -1;
		return 1;
	}
 
	this.sortNumeric = function(a,b) {
		aa = parseFloat(thisObject.getInnerText(a.cells[thisObject.sortColumnIndex]));
		if (isNaN(aa)) aa = 0;
		bb = parseFloat(thisObject.getInnerText(b.cells[thisObject.sortColumnIndex]));
		if (isNaN(bb)) bb = 0;
		return aa-bb;
	}
 
	// define variables
	var thisObject = this;
	var sortSection = this.thead;
 
	// constructor actions
	if (!(this.tbody && this.tbody[0].rows && this.tbody[0].rows.length > 0)) return;
 
	if (sortSection && sortSection[0].rows && sortSection[0].rows.length > 0) {
		var sortRow = sortSection[0].rows[0];
	} else {
		return;
	}
 
	for (var i=0; i<sortRow.cells.length; i++) {
		sortRow.cells[i].sTable = this;
		sortRow.cells[i].onclick = function () {
			this.sTable.sort(this);
			return false;
		}
	}
}

function toggleCheck(id){
	extrauControl(id).checked=!extrauControl(id).checked;
}

var MONTH_NAMES=new Array('Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre','Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic');

Array.prototype.indexOf = function(s) {
	for (var x=0;x<this.length;x++) if(this[x] == s) return x;
	return -1;
}


function lanzarPopupPOST(id,action,data){
	var i;
	
	frm = $("#"+id);
	
	if(frm){
		frm.remove();
	}
	
	// Creamos el formulario y lo configuramos
		frm = $("<form />");
		frm.attr("id",id);
		frm.attr("action",action);
		frm.attr("target","_blank");
		frm.attr("method","post");
	
	// Partimos data y creamos un input por cada para campo=valor
	aData = data.split("&");
	for(i=0 ; i<aData.length ; i++){
		fields = aData[i].split("=");
		fieldName = fields[0];
		fieldVal = fields[1];
		
		inp = $("<input />");
		inp.attr("type","hidden");
		inp.attr("name",fieldName);
		inp.val(fieldVal);
		
		frm.append(inp);
	}
	
	$("body").append(frm);
	frm.submit();
}

function recuperarTipos(bloque,packs){
	var data = jQuery.parseJSON($.ajax({
		url: '/area_restringida/ajax.asp',
		type: 'Post',
		dataType: 'json',
		async: false,
		data: 'funcion=recuperarDatosApartamentosJson&idIdioma=1&idBloque=' + bloque + '&cargarPacks=' + packs,
		success: function(data){			
			return data;
		},
		error: function(){
			return false
		}
	}).responseText);
	
	return data;
}

function compareOptionText(a,b) {
	/*
	  * return >0 if a>b
	  * 0 if a=b
	  * <0 if a<b
	  */
	// textual comparison
	return a.value!=b.value ? a.value<b.value ? -1 : 1 : 0;
	// numerical comparison
	// return a.text - b.text;				 
}

function sortOptions(list) {
	var items = list.options.length;
	// create array and make copies of options in list
	var tmpArray = new Array(items);
	for ( i=0; i<items; i++ )
	tmpArray[i] = new
	Option(list.options[i].text,list.options[i].value);
	// sort options using given function
	tmpArray.sort(compareOptionText);
	// make copies of sorted options back to list
	for ( i=0; i<items; i++ )
	list.options[i] = new Option(tmpArray[i].text,tmpArray[i].value);
	 
}

var dBug_ini;
var dBug_dif;
function startDebug(){
	dBug_ini = new Date();
	dBug_dif = new Date();
	$("#debug").html('');
}
function debugInfo(str){
	var now = new Date();
	var timestamp = now.getTime() - dBug_ini.getTime();
	var diff = now.getTime() - dBug_dif.getTime();
	timestamp = timestamp/1000;
	diff = diff/1000;
	
	$("#debug").append(timestamp + " (" + diff + ")" + ": " + str + "<br />");
	dBug_dif = new Date();
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

$(document).ready(function(){	
	var hoy = new Date();
	var ayer = new Date();
	ayer.setDate(ayer.getDate()-1);
	var manyana = new Date();
	manyana.setDate(manyana.getDate()+1);
	
	$('.datePicker_de').datepicker({
		showOn: "both",
		buttonImage: "/imagenes/calendar.gif",
		buttonImageOnly: true,
		changeMonth: true,
		dateFormat: 'dd/mm/yy',
		numberOfMonths: 1,
		minDate: hoy,
		onSelect: function( selectedDate ) {			
			var option = "minDate";
			var instance = $( this ).data( "datepicker" );				
				
			date = $.datepicker.parseDate(
				instance.settings.dateFormat ||
				$.datepicker._defaults.dateFormat,
				selectedDate, instance.settings );
				
			// Nos aseguramos que no puede seleccionar el mismo día
			date.setDate(date.getDate()+1);
				
			// La fecha mínima siempre será como máximo hoy
			if (date.getTime() < hoy.getTime()){
				date = hoy;
			}
			
			otherPicker = $(this).parent().parent().parent().find('td .datePicker_hasta');
			
			// Seteamos el max date
			otherPicker.datepicker( "option", option, date );
			
			// Si no hay fecha, le asignamos el día siguiente o anterior en función de en que picker estamos
			if ( otherPicker.val()=="" ){
				otherPicker.datepicker( "setDate", date );
			}
		}
	});
	
	$('.datePicker_hasta').datepicker({		
		showOn: "both",
		buttonImage: "/imagenes/calendar.gif",
		buttonImageOnly: true,
		changeMonth: true,
		dateFormat: 'dd/mm/yy',
		numberOfMonths: 1,
		minDate: manyana,
		onSelect: function( selectedDate ) {			
			var option = "maxDate";
			var instance = $( this ).data( "datepicker" );				
				
			date = $.datepicker.parseDate(
				instance.settings.dateFormat ||
				$.datepicker._defaults.dateFormat,
				selectedDate, instance.settings );
				
			// Nos aseguramos que no puede seleccionar el mismo día
			date.setDate(date.getDate()-1);
				
			// La fecha mínima siempre será como máximo hoy
			/*
			if (date.getDate() < hoy.getDate()){
				date = hoy;
			}
			*/
			
			otherPicker = $(this).parent().parent().parent().find('td .datePicker_de');
			
			// Seteamos el max date
			otherPicker.datepicker( "option", option, date );
			
			// Si no hay fecha, le asignamos el día siguiente o anterior en función de en que picker estamos
			if ( otherPicker.val()=="" ){
				otherPicker.datepicker( "setDate", date );
			}
		}
	});	
	
	$('.datepicker').datepicker({
		changeMonth: true,
		changeYear: true,
		dateFormat: 'dd/mm/yy',
		showButtonPanel: false,
		numberOfMonths: 1
	});	
	
	$('.aValidar').each(function(){
		$(this).validate({
			errorPlacement: function(error, element) {			
			},
			showErrors: function(errorMap, errorList) {					
				this.defaultShowErrors();
			}
		});
	});
	
	$('.btnMostrarPrecios').click(function(){		
		$('#seleccionarFechas_' + $(this).attr('idBloque')).fadeIn();
		$(this).remove();
	});
	
	$('.button').button();	
	$('.tabs').tabs();	
	$('.accordion').accordion();
});

