/********* DATE PICKER *************
$("#startDate,#endDate").datepicker({     beforeShow: $.datepicker.customRange,     showOn: "both",     buttonImage: "/imagenes/calendar.gif",     buttonImageOnly: true });


$("#i18n").datepicker($.extend({}, 
$.datepicker.regional["es"], { 
    showStatus: true, 
    showOn: "both", 
    buttonImage: "/imagenes/calendar.gif", 
    buttonImageOnly: true 
}));

/*


/***********************************************
* Contractible Headers script- © Dynamic Drive (www.dynamicdrive.com)
* This notice must stay intact for legal use. Last updated Oct 21st, 2003.
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/

var enablepersist="off" //Enable saving state of content structure using session cookies? (on/off)
var collapseprevious="no" //Collapse previously open content when opening present? (yes/no)

if (document.getElementById){
document.write('<style type="text/css">')
document.write('.switchcontent{display:none;}')
document.write('</style>')
}

function getElementbyClass(classname){
ccollect=new Array()
var inc=0
var alltags=document.all? document.all : document.getElementsByTagName("*")
for (i=0; i<alltags.length; i++){
if (alltags[i].className==classname)
ccollect[inc++]=alltags[i]
}
}

function contractcontent(omit){
var inc=0
while (ccollect[inc]){
if (ccollect[inc].id!=omit)
ccollect[inc].style.display="none"
inc++
}
}

function expandcontent(cid){
if (!existeObjeto(cid)) return;
if (typeof ccollect!="undefined"){
if (collapseprevious=="yes")
contractcontent(cid)
document.getElementById(cid).style.display=(document.getElementById(cid).style.display!="block")? "block" : "none"
}
}

function do_onload(){
getElementbyClass("switchcontent")
if (enablepersist=="on" && typeof ccollect!="undefined")
revivecontent()
}

if (window.addEventListener)
window.addEventListener("load", do_onload, false)
else if (window.attachEvent)
window.attachEvent("onload", do_onload)
else if (document.getElementById)
window.onload=do_onload

// ------------------------------
// Obtención del objeto para AJAX
// ------------------------------

//--- http://jibbering.com/2002/4/httprequest.html ---//
var xmlhttp;
var ajaxResult;
/*@cc_on
@if (@_jscript_version >= 5)
  try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
      xmlhttp = false;
    }
  }
@else
xmlhttp = false;
@end @*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
{
  try
  {
    xmlhttp = new XMLHttpRequest();
  } catch (e)
  {
    xmlhttp = false;
  }
}

// -----------------------------
// Funciones de utilidad general
// -----------------------------

function initTinyMCE(controles)
{
      tinyMCE.init({
        mode : "exact",
        theme : "advanced",
	    elements : controles,
	    theme_advanced_buttons1 : "bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright, justifyfull,bullist,numlist,undo,redo",
	    theme_advanced_buttons2 : "",
	    theme_advanced_buttons3 : "",
	    theme_advanced_toolbar_location : "top",
	    theme_advanced_toolbar_align : "left",
        force_br_newlines : true,
        force_p_newlines : false
      });
}

// Obtiene un objeto DOM a partir de su id
function obtenerObjeto(idObjeto)
{
  if (document.getElementById)
    return document.getElementById(idObjeto);
  else if (document.all)
    return document.all[idObjeto];
}

function existeObjeto(idObjeto)
{
  return (obtenerObjeto(idObjeto) != undefined);
}

// Muestra un elemento
function mostrar(idObjeto)
{
  var objeto = obtenerObjeto(idObjeto);
  objeto.style.visibility = "visible";
  objeto.style.display = "block";
}

// Oculta un elemento
function ocultar(idObjeto)
{
  var objeto = obtenerObjeto(idObjeto);
  objeto.style.visibility = "hidden";
  objeto.style.display = "none";
}

// Obtiene el valor del elemento seleccionado en un desplegable
function obtenerValorSeleccionado(idDesplegable)
{
  var desplegable = obtenerObjeto(idDesplegable);
  if (desplegable.options.length == 0)
    return -1
  else
    return desplegable.options[desplegable.selectedIndex].value;
}

// selecciona un valor en un desplegable
function seleccionarValor(idDesplegable, valor)
{
  var desplegable = obtenerObjeto(idDesplegable);
  for (var i = 0; i < desplegable.options.length; i++)
    if (desplegable.options[i].value == valor)
    {
      desplegable.options[i].selected = true;
      return;
    }
}

// vacía un desplegable
function vaciarDesplegable(idDesplegable)
{
  var desplegable = obtenerObjeto(idDesplegable);
  // vaciar el desplegable
  while (desplegable.options.length > 0)
    desplegable.options[0] = null;
  //desplegable.options[desplegable.length] = new Option("------------------------", "-1");
}

// Actualiza el texto del primer elemento de un desplegable
function actualizarTitularDesplegable(idDesplegable, titular)
{
  var desplegable = obtenerObjeto(idDesplegable);
  if (desplegable.options.length > 0)
    desplegable.options[0].text = titular;
}

// actualiza un desplegable con una lista de códigos-descripciones
function actualizarDesplegable(idDesplegable, codigos, descripciones)
{
  var desplegable = obtenerObjeto(idDesplegable);
  // vaciar el desplegable
  while (desplegable.options.length > 0)
    desplegable.options[0] = null;
  // rellenar el desplegable
  for (i = 0; i < codigos.length; i++)
  {
    if (i == 0)
      desplegable.options[desplegable.length] = new Option("------------------------", "-1", true);
    desplegable.options[desplegable.length] = new Option(descripciones[i], codigos[i]);
  }
  ordenarDesplegable(desplegable);
}

// obtiene el índice que ocupa un objeto en un array
function indexOf(array, objeto)
{
  var i = 0;
  var encontrado = false;
  while (i < array.length && !encontrado)
    if (array[i] == objeto)
      encontrado = true;
    else
      i++;
  if (encontrado)
    return i;
  else
    return -1;
}

// ordena un desplegable
function ordenarDesplegable(lb)
{
  if (lb.options.length == 0)
    return;
  var arrTexts = new Array();
  var el;
  var oldValue = lb.options[lb.selectedIndex].value;
  for (i = 0; i < lb.length; i++)
    arrTexts[i] = lb.options[i].text.toLowerCase() + ':' + lb.options[i].text + ':' + lb.options[i].value;
  arrTexts.sort();
  for (i = 0; i < lb.length; i++)
  {
    el = arrTexts[i].split(':');
    lb.options[i].text = el[1];
    lb.options[i].value = el[2];
    if (oldValue == lb.options[i].value)
      lb.options[i].selected = true;
    else
      lb.options[i].selected = false;
  }
}

// funciones de transformación binario <-> hexadecimal
var binarios = ["0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"];
var hexadecimales = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];

function hexToBin(hexDigit)
{
  var idx = indexOf(hexadecimales, hexDigit);
  return binarios[idx];
}

function binToHex(binaryValue)
{
  var idx = indexOf(binarios, binaryValue);
  return hexadecimales[idx];
}

function binaryToHex(binaryString)
{
  var result = "";
  var i = binaryString.length - 4;
  while (i > 0)
  {
      result = binToHex(binaryString.substr(i, 4)) + result;
      i -= 4;
  }
  var lastBin = binaryString.substr(0, i + 4);
  while (lastBin.length < 4)
    lastBin = "0" + lastBin;
  result = binToHex(lastBin) + result;
  return result;
}

function hexToBinary(hexString)
{
  var result = "";
  for (var i = 0; i < hexString.length; i++)
  {
      result = result + hexToBin(hexString[i]);
  }
  return result;
}

function hexToBinary(hexString, maxLength)
{
  var result = hexToBinary(hexString);
  while (result.length < maxLength)
    result = '0' + result;
  if (result.length > maxLength)
    result = result.substr(result.length - maxLength);
  return result;
}

function normalizarFecha(fecha, formatoInicial)
{
  var time = getDateFromFormat(fecha, formatoInicial);
  var dResult = new Date();
  dResult.setTime(time);
  return formatDate(dResult, "ddMMyyyy");
}

function desnormalizarFecha(fecha, formatoFinal)
{
  if (fecha == "")
    return "";
  var time = getDateFromFormat(fecha, "ddMMyyyy");
  var dResult = new Date();
  dResult.setTime(time);
  return formatDate(dResult, formatoFinal);
}

//function binaryToHex(binaryString)
//{
//  var result = parseInt(binaryString, 2).toString(16);
//  return result;
//}

//function hexToBinary(hexString, maxLength)
//{
//  var result = parseInt(hexString, 16).toString(2);
//  while (result.length < maxLength)
//    result = "0" + result;
//  return result;
//}

// cambia el idioma de la página
function quitarIdioma(url)
{
  var newUrl;
  var index = url.lastIndexOf("lang=");
  if (index == -1)
  {
    newUrl = url;
  }
  else
  {
      var headUrl = url.substring(0, index);
      var tailUrl = url.substring(index + 7, url.length);
      newUrl = headUrl + "lang=" + idioma + tailUrl;
  }
  return newUrl;
}

function sustituirIdioma(url, idioma)
{
    var newUrl;
    var index = url.lastIndexOf("lang=");
    if (index == -1)
    {
      index = url.lastIndexOf("?");
      if (index == -1)
        newUrl = url + "?lang=" + idioma;
      else
        newUrl = url + "&lang=" + idioma;
    }
    else
    {
      var headUrl = url.substring(0, index);
      var tailUrl = url.substring(index + 7, url.length);
      newUrl = headUrl + "lang=" + idioma + tailUrl;
    }
    return newUrl;
}

function cambiarIdioma(idioma)
{
    showModalWindow();
    var newUrl = sustituirIdioma(location.href, idioma);    
    location.replace(newUrl);
}

// volver a la página anterior teniendo en cuenta los cambios de idioma
function volver(idioma)
{
  netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
  var currentUrl = quitarIdioma(location.href);
  // buscar la url actual en el histórico hasta encontrarlo
  var encontrado = false;
  var i = history.length - 1;
  while (i > 0 && !encontrado)
  {
    var tmpUrl = quitarIdioma(history[i]);
    if (tmpUrl == currentUrl)
      encontrado = true;
  }
  if (i > 0)
  {
    var previousUrl = sustituirIdioma(history[i - 1], idioma);
    location.href = previousUrl;
  }
}

function cargarUrl(url)
{
  if (xmlhttp)
  {
    ajaxResult = null;
    xmlhttp.open("GET", url, false);
    xmlhttp.onReadyStateChange = respuesta_CargarUrl;
    xmlhttp.send(null);
    if (ajaxResult == null)
      respuesta_CargarUrl();
    return ajaxResult;
  }
}

function respuesta_CargarUrl()
{
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
  {
    ajaxResult = xmlhttp.responseText;
  }
}

// ----------------------------------------
// Funciones de acceso a datos del servidor
// ----------------------------------------

function servidor_obtenerSubzonas(id_padre, idioma)
{
  if (xmlhttp)
  {
    showModalWindow();
    ajaxResult = null;
    var url = "AjaxDataProviders/Subzonas.aspx?id_padre=" + id_padre + "&lang=" + idioma;
    xmlhttp.open("GET", url, false);
    xmlhttp.onReadyStateChange = respuesta_obtenerSubzonas;
    xmlhttp.send(null);
    closeModalWindow();
    if (ajaxResult == null)
      respuesta_obtenerSubzonas();
    return ajaxResult;
  }
}

function respuesta_obtenerSubzonas()
{
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
  {
    var resultadoXml = xmlhttp.responseXML;
    var objNodeList = resultadoXml.getElementsByTagName("zona");
    var codigos = new Array(objNodeList.length);
    var descripciones = new Array(objNodeList.length);
    for (var i = 0; i < objNodeList.length; i++)
    {
      codigos[i] = objNodeList.item(i).attributes.getNamedItem("valor").value;      
      if (window.ActiveXObject)
        descripciones[i] = objNodeList.item(i).text;
      else if (window.XMLHttpRequest)
        descripciones[i] = objNodeList.item(i).textContent;
    }
    ajaxResult = new Array(2);
    ajaxResult[0] = codigos;
    ajaxResult[1] = descripciones;
  }
}

function servidor_obtenerSubservicios(id_padre, idioma)
{
  if (xmlhttp)
  {
    showModalWindow();
    ajaxResult = null;
    var url = "AjaxDataProviders/Subservicios.aspx?id_padre=" + id_padre + "&lang=" + idioma;
    xmlhttp.open("GET", url, false);
    xmlhttp.onreadystatechange = respuesta_obtenerSubservicios;
    xmlhttp.send(null);
    closeModalWindow();
    if (ajaxResult == null)
      respuesta_obtenerSubservicios();
    return ajaxResult;
  }
}

function respuesta_obtenerSubservicios()
{
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
  {
    var resultadoXml = xmlhttp.responseXML;
    var objNodeList = resultadoXml.getElementsByTagName("servicio");
    var codigos = new Array(objNodeList.length);
    var descripciones = new Array(objNodeList.length);
    for (var i = 0; i < objNodeList.length; i++)
    {
      codigos[i] = objNodeList.item(i).attributes.getNamedItem("valor").value;      
      if (window.ActiveXObject)
        descripciones[i] = objNodeList.item(i).text;
      else if (window.XMLHttpRequest)
        descripciones[i] = objNodeList.item(i).textContent;
    }
    ajaxResult = new Array(2);
    ajaxResult[0] = codigos;
    ajaxResult[1] = descripciones;
  }
}

function servidor_login(usu, pwd)
{
  if (xmlhttp)
  {
    showModalWindow();
    ajaxResult = null;
    var url = "AjaxDataProviders/Login.aspx?usu=" + usu + "&pwd=" + pwd;
    xmlhttp.open("GET", url, false);
    xmlhttp.onreadystatechange = respuesta_login;
    xmlhttp.send(null);
    closeModalWindow();
    if (ajaxResult == null)
      respuesta_login();
    return ajaxResult;
  }
}

function respuesta_login()
{
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
  {
    var resultadoXml = xmlhttp.responseXML;
    var objNodeList = resultadoXml.getElementsByTagName("usuario");
    var tipos = new Array(objNodeList.length);
    for (var i = 0; i < objNodeList.length; i++)
    {
      tipos[i] = objNodeList.item(i).attributes.getNamedItem("valor").value;
    }      
    ajaxResult = tipos;
  }
}

function servidor_logout()
{
  if (xmlhttp)
  {
    showModalWindow();
    ajaxResult = null;
    var url = "AjaxDataProviders/Logout.aspx";
    xmlhttp.open("GET", url, false);
    xmlhttp.onreadystatechange = respuesta_logout;
    xmlhttp.send(null);
    closeModalWindow();
    if (ajaxResult == null)
      respuesta_logout();
    return ajaxResult;
  }
}

function respuesta_logout()
{
  ajaxResult = "ok";
}

//TABS

function tabSwitch(new_tab, new_content) {
	
	document.getElementById('content_1').style.display = 'none';
	document.getElementById('content_2').style.display = 'none';
	document.getElementById('content_3').style.display = 'none';
	document.getElementById('content_4').style.display = 'none';	
	document.getElementById(new_content).style.display = 'block';	
	
	document.getElementById('tab_1').className = '';
	document.getElementById('tab_2').className = '';
	document.getElementById('tab_3').className = '';
	document.getElementById('tab_4').className = '';
	document.getElementById(new_tab).className = 'active';		

}

// Ties a set of tabs and content id's together, and switches between them
// <div id='tab_1'> and <div id="content_1"> for example
// Usage: tabswitch(1, 4, 'tab', 'panel') would switch on tab_1 and panel_1

function tabSwitch_2(active, number, tab_prefix, content_prefix) {
	
	for (var i=1; i < number+1; i++) {
	  document.getElementById(content_prefix+i).style.display = 'none';
	  document.getElementById(tab_prefix+i).className = '';
	}
	document.getElementById(content_prefix+active).style.display = 'block';
	document.getElementById(tab_prefix+active).className = 'active';	
	
}
