
window.onerror = function(){
	return true;

}

if(document.getElementById){

//Selected option from contextual menu
var rightMenuActive;
//Requested url
var LINK;
//Current page
var REFERER;
//Dummy objects used for showing and hiding of content
var DUMMY;
//Dummy functions used to initialize IE < 7 code
var initIE6 = initIE6Page = null;
//Used to store references to loaded scripts
var SCRIPTS = new Array();
//Object used to manage the multimedia widget
var AUDIOVISUALWIDGET;
//Array of objects used to manage highlight widgets
var HIGHLIGHTS;
var LOADING;

var PA_IE6 = false;

//We have Javascript, so we add the style sheet
var interactivecss = document.createElement('link');
interactivecss.setAttribute('type', 'text/css');
interactivecss.setAttribute('rel', 'stylesheet');
interactivecss.setAttribute('href', '/css/interactivity.css');

document.getElementsByTagName('head')[0].appendChild(interactivecss);

/***************************
  FLASH
***************************/

var _VERSIONREQUIRED = 7;

var installedVersion = deconcept.SWFObjectUtil.getPlayerVersion();

var isFlashEnabled = installedVersion.versionIsValid({major: _VERSIONREQUIRED, minor: 0});

var flashTimer;

function enableFlash(){
  clearTimeout(flashTimer);

  var found = false;

  var container = document.getElementById('multimediaContainer');
  //Wait untill container and object are created

  if(container){
    var obj = container.getElementsByTagName('object');

	//Save content of highlights since we are going to rewrite the content of the container
	var highlight = document.getElementById('homeHighlights');
	var newHighlight;
	if(highlight){
		newHighlight = highlight.cloneNode(true);
	}

	//Save existence of multimedia open button since we are going to rewrite the content of the container
	var button = document.getElementById('contenedorMultimediaEnlace');

    if(obj.length > 0){
		rewriteObjectHTML(obj[0]);


/*
      var params = obj[0].getElementsByTagName('param');

      //IE looses the content of the "param" tags when getting the innerHTML, so we get them by brute force
      var paramsString = '';
      for (var i = 0; i < params.length; i++){
        paramsString += '<param name="'+params[i].getAttribute('name')+'" value="'+params[i].getAttribute('value')+'" />';
      }

      var text = container.innerHTML;
      text = text.substring(0, text.indexOf('  '));

      text += paramsString+'</object>';

      container.innerHTML = text;
*/
	  //Add highlights if necessary
	  if(newHighlight){
//	  	container.appendChild(newHighlight);
		initHighlights();
	  }

	  //Add button if necessary
	  if(button){
	  	addMultimediaButton();
	  }
		/*
		obj = container.getElementsByTagName('object')[0];
		obj.style.display = 'block';
		*/
	  enableMultimedia();
      found = true;
    }
  }

  //We haven't found the container, so ask again
  if(!found){
    flashTimer = setTimeout('enableFlash()', 100);
  }
}

function rewriteObjectHTML(node){

	//Get parameters and save them into a string

	//IE seems to get ALL 'param' tags (as if doing document.getElementsByTagName) when invoking node.getElementsByTagName
	//var params = node.getElementsByTagName('param');







	var childs = node.childNodes;
	var params = new Array();

	for (var i = 0; i < childs.length; i++){
		if(childs[i].tagName && childs[i].tagName.toLowerCase() == 'param'){
			params[params.length] = childs[i];
		}
	}

    var paramsString = '';
    for (var i = 0; i < params.length; i++){
    	paramsString += '<param name="'+params[i].getAttribute('name')+'" value="'+params[i].getAttribute('value')+'" />';
    }

	var text = node.parentNode.innerHTML;

	//Create a test string in lowercase to avoid capitalization
	var testText = text.toLowerCase();

	//TODO: This maybe could be done with a RegExp...
	var start = testText.indexOf('<object');
	//Get rid of this part.
	testText = testText.substring(start);
	//Now the first '>' is the closing of '<object'
	var end = testText.indexOf('>') + 1;
	//Add start to end since we have substringed testText
	end += start;

	//Now we have stored everything untill closing 'object'
	var newText = text.substring(0, end);

	//Add params
	newText += paramsString;

	//Get the rest of the string
	end = testText.indexOf('</object>');
	//Again, add start to end
	end += start;

	newText += text.substring(end);

	node.parentNode.innerHTML = newText;

}

function getObjectHTML(node){
	//Get parameters and save them into a string

	//IE seems to get ALL 'param' tags (as if doing document.getElementsByTagName) when invoking node.getElementsByTagName
	//var params = node.getElementsByTagName('param');

	var childs = node.childNodes;
	var params = new Array();

	for (var i = 0; i < childs.length; i++){
		if(childs[i].tagName && childs[i].tagName.toLowerCase() == 'param'){
			params[params.length] = childs[i];
		}
	}

    var paramsString = '';
    for (var i = 0; i < params.length; i++){
    	paramsString += '<param name="'+params[i].getAttribute('name')+'" value="'+params[i].getAttribute('value')+'" />';
    }

	var text = node.parentNode.innerHTML;

	//Create a test string in lowercase to avoid capitalization
	var testText = text.toLowerCase();

	//TODO: This maybe could be done with a RegExp...
	var start = testText.indexOf('<object');
	//Get rid of this part.
	testText = testText.substring(start);
	//Now the first '>' is the closing of '<object'
	var end = testText.indexOf('>') + 1;
	//Add start to end since we have substringed testText
	end += start;

	//Now store untill closing 'object'
	var newText = text.substring(start, end);

	//Add params
	newText += paramsString;

	//Get the rest of the string
	end = testText.indexOf('</object>');
	//Again, add start to end
	end += start;

	newText += text.substring(end, end + new String('</object>').length);

	return newText;

}

function disableFlash(){
  clearTimeout(flashTimer);

  var found = false;

  var container = document.getElementById('multimediaContainer');
  //Wait untill container and object are created
  if(container){

	//Save content of highlights since we are going to rewrite the content of the container
	var highlight = document.getElementById('homeHighlights');
	var newHighlight;
	if(highlight){
		newHighlight = highlight.cloneNode(true);
	}

	//Save existence of multimedia open button since we are going to rewrite the content of the container
	var button = document.getElementById('contenedorMultimediaEnlace');

	var obj = container.getElementsByTagName('object');

    var img = obj[0].getElementsByTagName('img');
    //IE doesn't detect the "img" tag inside the "object" tag

    if(img.length > 0){
      var node = img[0].cloneNode(false);

      while(container.firstChild){
        container.removeChild(container.firstChild);
      }

      container.appendChild(node);

      found = true;
    }
    else{
      var text = container.innerHTML;

      var img = text.substring(text.lastIndexOf('<img'), text.lastIndexOf('/>') + 2);

      container.innerHTML = img;

	  //Add highlights if necessary
	  if(newHighlight){
	  	container.appendChild(newHighlight);
		initHighlights();
	  }

	  //Add button if necessary
	  if(button){
	  	addMultimediaButton();
	  }

      found = true;
    }
  }

  //We haven't found the container, so ask again
  if(!found){
    flashTimer = setTimeout('disableFlash()', 100);
  }
}

function killCSSRuleOnSheet(sheet, selector){
	var searchPattern = new RegExp('(^|\s)' + selector + '([,]|$)', 'i');

	if(sheet.cssRules){
		cssRules = sheet.cssRules;
	}
	else{
		cssRules = sheet.rules;
	}

	for(var i = 0; i < cssRules.length; i++){
		if(searchPattern.test(cssRules[i].selectorText)){
             if (sheet.cssRules) {
                styleSheet.deleteRule(i);
             } else {
                sheet.removeRule(i);
             }
		}
	}


}

function enableMultimedia(){

	var sheets = document.styleSheets;
	for(var i = 0; i < sheets.length; i++){
		if(sheets[i].href.lastIndexOf('interactivity') > -1){
//			killCSSRuleOnSheet(sheets[i], '#multimediaContainer object')
			var rules = getRulesBySelector(sheets[i], '#multimediaContainer object');

			rules[0].style.display = 'block'
		}
	}

	$('.highlightContent a').click(_linkPressed);
}



if(isFlashEnabled){
  //Rewrite Flash content only in IE to avoid "Press here to activate this control"
  if(document.all){
    enableFlash();

  }
}
else{
  disableFlash();
}

var navAgent = navigator.userAgent.toLowerCase();

if(navAgent.lastIndexOf('linux') > -1){
	disableFlash();
}

/***************************
  INICIALIZACI�N
***************************/

$().ready(function() {
  init();

  if(initIE6){
    initIE6();
  }
})

function init(){

//	_saveScripts();

	if(!document.all){
		enableMultimedia();
	}

  REFERER = document.location+'';

  createHeaderCalendar();

  createHeaderSelects();

  initBotonera();

  initRightMenu();

  initLogo();

  initUtils();

  initFooter();

  initSearchForm();

  initContent();

  setBlur();

	//Remove CSS rules for multimedia widgets :hover
  killCSSRule('#audiovisual:hover .out');
  killCSSRule('#audiovisual:hover .over');

	//See if multimedia container is opened
	var container = document.getElementById('multimediaContainer');
	var obj = container.getElementsByTagName('object');
	//If there is no flash, there is no need to open the container
	if(obj.length > 0){
		var obj = obj[0];
		var clip = DY.Dom.getClip(obj);
		var height = DY.Dom.getHeight(obj);
		var visible = clip[2] - clip[0];


		var isMultimediaClosed = (visible < height);
		//TODO Explorer doesn't get height right
		if(height == 0){
			if(visible < 100){
				isMultimediaClosed = true;
			}
		}

		//Multimedia container is closed. Add button to open it.
		if(isMultimediaClosed){
			addMultimediaButton();
		}
		//Multimedia container is opened (so we are at the homepage).
		else{
			initHighlights();
		}


	}


  //Create a new StyleSheet to take care of multimedia container when getting back to it
  createMultimediaStyleSheet();
}

function initSearchForm(){
	$('#searchForm').bind('submit', checkSearchForm);
}

function checkSearchForm(){
	var search = document.getElementById('search');
	if(search){
		var value = search.value;

		if(value.length > 0){
			var url = $(this).attr('action')+'?text='+value;
			//Encapsulate in an object since 'sendLink' expects an object with an 'href' property
			sendLink({href: url});
		}
	}

	return false;
}

function createHeaderCalendar(){
  $('#selectHotelDate').datePicker({firstDayOfWeek:1});
}

function createHeaderSelects(){
  var selects = $('#header select');

  for (var i = 0; i< selects.length; i++){
    $(selects[i]).selectBox({css:'select', holder:selects[i].parentNode, id: 'select'+i});
  }
}

function initLogo(){

	//Bind only if flash is available
	if(isFlashEnabled){
		$('#headerLogo').bind('click', function(){
			showMultimedia();
			return false;
		});
	}
	else{
		var logo = document.getElementById('headerLogo');
		logo.removeAttribute('href');
//		$('#headerLogo').css('cursor', 'default');
	}
}

function initUtils(){

	$('#utils .imprimir').bind('click', doPrint);
	$('#utils .sendto').bind('click', showSendToAFriend);

    var options = {
        beforeSubmit:  	checkForm,  // pre-submit callback
        success:       	catchSendAFriendFormResponse  // post-submit callback

    };

	$('#enviarAmigoform').ajaxForm(options);

}

function doPrint(){
	window.print();
	return false;
}

function showSendToAFriend(){
	var h1 = document.getElementsByTagName('h1');
	if(h1.length > 0){
		var color = DY.Dom.getStyle(h1[0], 'color');
		$('#utils .sendto').css('color', color);
		document.getElementById('enviarAmigoform').getElementsByTagName('legend')[0].style.color = color;
	}

	document.getElementById('enviarAmigoform').style.display = 'block';
	$('#article').addClass('sendToAFriend');
	return false;
}

function hideSendToAFriend(){
	var enviar = document.getElementById('enviarAmigoform');
	if (enviar){
		enviar.style.display = 'none';
		$('#article').removeClass('sendToAFriend');
		$('#utils .sendto').css('color', '#000');
	}
}

function catchSendAFriendFormResponse(xml){
	var fields = xml.getElementsByTagName('form');
	var p;
	var message;
	for(var i = 0; i < fields.length; i++){
		p = fields[i].getElementsByTagName('p');

		for(var j = 0; j < p.length; j++){
			if(p[j].getAttribute('class') == 'error'){
				message = p[j];
				break;
			}
		}
	}

	var messageText = message.firstChild.xml || message.firstChild.nodeValue;

	var currentform = document.getElementById('enviarAmigoform');
	hideFormLoading(currentform);
	setError(currentform, null, messageText);
	enableInputs();
}

/***************************
  CONTENIDO
***************************/
function initContent(){
  //Bind events to a named function so we can unbind them if necessary
  $('#article a').click(_linkPressed);

  //Bind highlights

  $('.highlightContent a').click(_linkPressed);

  //Bind path links
  $('#path a').click(_linkPressed);

  //Init audiovisuals
  initAudiovisual();

  synchronizePath();


	if(LINK){
		//If we are asking for sitemap, reconfigure page
		var page = LINK.substring(LINK.lastIndexOf('/') + 1).toLowerCase();
		if ((page.lastIndexOf('sitemap.') > -1) || (page.lastIndexOf('404.') > -1) || (page.lastIndexOf('mapa_del_web.') > -1) || (page.lastIndexOf('plan_du_site.') > -1)){
			$('#pageContent').addClass('sitemapHolder');
		}
		else{
			$('#pageContent').removeClass('sitemapHolder');
		}
	}

	$('#article').removeClass('gallery');

	if(initIE6Page){
		initIE6Page();
	}


	//See if multimedia container is opened = we are at the homepage
	var container = document.getElementById('multimediaContainer');
	var obj = container.getElementsByTagName('object');

	if(obj.length == 0){
		obj = container.getElementsByTagName('img');
	}

	if(obj.length > 0){
		var obj = obj[0];
		var clip = DY.Dom.getClip(obj);
		var height = DY.Dom.getHeight(obj);
		var visible = clip[2] - clip[0];


		var isMultimediaClosed = (visible < height);
		//TODO Explorer doesn't get height right
		if(height == 0){
			if(visible < 100){
				isMultimediaClosed = true;
			}
		}

		//Multimedia container is closed. We are not at the homepage.
		if(isMultimediaClosed){
			initHighlights();
		}
	}

  //Init highlights
  //initHighlights();
}

function setBlur(){
	$('a').bind('click', blurLink);
	$('#idiomas a').unbind('click');
}

function blurLink(){
	this.blur();
	return false;
}

function _linkPressed(){
  sendLink(this);
  return false;
}

function synchronizePath(){

	var path = document.getElementById('path');

	var a = path.getElementsByTagName('a');

	if(a.length < 1){
		//We are on a special page like "sitemap". Remove all marks and do nothing more
		deselectBotoneraItems();
		return false;
	}

	//Try to guess section
	var section = a[0].innerHTML.toLowerCase();

	var botonera = document.getElementById('botonera');
	var span = botonera.getElementsByTagName('span');

	var text;
	var sectionItem = null;

	for(var i = 0; i < span.length; i++){
		text = span[i].innerHTML.toLowerCase();
		if(text == section){
			sectionItem = span[i];
			break;
		}
	}

	if(sectionItem == null){
		//We haven't found the section so it's better to not touch anything
		return false;
	}

	//Let's try to find subsection
	var subsection = null;
	if(a.length > 1){
		subsection = a[1].innerHTML.toLowerCase();
	}
	else{
		var strong = path.getElementsByTagName('strong');
		if(strong.length > 0){
			subsection = strong[0].innerHTML.toLowerCase();
		}
	}

	if(subsection == null){
		//We haven't found the subsection so it's better to not touch anything
		return false;
	}

	//Access parent node of span which contains the ul submenu
	sectionItem = sectionItem.parentNode;
	var subsectionLinks = sectionItem.getElementsByTagName('a');

	if(subsectionLinks.length == 0){
		//No possible match, touch nothing
		return false;
	}

	var subsectionItem = null;
	for(var i = 0; i < subsectionLinks.length; i++){
		text = subsectionLinks[i].innerHTML.toLowerCase();
		if(text == subsection){
			subsectionItem = subsectionLinks[i];
			break;
		}
	}

	if(subsectionItem == null){
		//We haven't found the subsection item so it's better to not touch anything
		return false;
	}

	//Send the item to be marked
	setBotoneraSubItemSelected(subsectionItem);

}

/***************************
  MENÚS PIE
***************************/
function initFooter(){
  //Bind events to a named function so we can unbind them if necessary
  $('#submenu a').click(_linkPressed);
  $('#foot a').click(_linkPressed);
}

/***************************
  BOTONERA SUPERIOR
***************************/

function initBotonera(){

  var elms = $('#botonera').children('li');

  //Bind events to a named function so we can unbind them if necessary

  for (var i = 0; i < elms.length; i++){
    //If element doesn't have a nested list, add event to the link
    if($(elms[i]).children('ul').length == 0){
      //li a
      $(elms[i]).children('a').click(_botoneraItemPressed);

    }
    //Add event to every link on the nested list
    else{
      //li ul li a
      $(elms[i]).children('ul').children('li').children('a').click(_botoneraSubItemPressed);

    }
  }

}

function _botoneraItemPressed(){
  setBotoneraItemSelected(this);
  sendLink(this);
  return false;
}

function _botoneraSubItemPressed(){
	//if ( $.browser.safari ) {
	   document.location = this;
	/*}
	else {
		setBotoneraSubItemSelected(this);
		sendLink(this);
		return false;
	}*/
}

function setBotoneraItemSelected(elm){
  deselectBotoneraItems();
  //Mark parent list
  // -li (parent)
  //		-a (elm)
  _setBotoneraItemSelected($(elm).parent());
}

function setBotoneraSubItemSelected(elm){
  //Send to the previous function to mark the subnode
  setBotoneraItemSelected(elm);
  //Also mark the parent li of the nested list
  // -li (parent)
  //		-ul (parent)
  //			-li (parent)
  //				-a (elm)
  _setBotoneraItemSelected($(elm).parent().parent().parent());
}

function _setBotoneraItemSelected(elm){
  $(elm).addClass('selected');
}

function deselectBotoneraItems(){
  $('#botonera').children('li').removeClass('selected');
  $('#botonera').children('li').children('ul').children('li').removeClass('selected');
}

/***************************
  BOTONERA CONTEXTUAL
***************************/

function initRightMenu(){
  //Bind events to named functions so we can unbind them if necessary

  //Add event to links
  $('#rightmenu li a').click(rightMenuLinkClicked);
  //Add event to "span" (they link to the current page, so they doesn't have link)
  $('#rightmenu li span').click(rightMenuSpanClicked);
}

function rightMenuLinkClicked(){

  var length = $(this).parent().children('ul').length;

  //If the parent doesn't have a nested list, ask for url
  if (length == 0){
    sendLink(this);
  }
  //Else, show submenu
  else{
    showSubMenu(this);
  }

  return false;
}

function showSubMenu(elm){
  if (rightMenuActive){
    $(rightMenuActive).removeClass("active");
    $("ul", rightMenuActive).Fold(500);
  }

  rightMenuActive = elm.parentNode;

  $(rightMenuActive).addClass("active");
  $("ul", rightMenuActive).UnFold(500);
}

function rightMenuSpanClicked(){
  if ($(this).parent().children('ul').length > 0){
    showSubMenu(this);
  }
}

/***************************
  CARGA DE CONTENIDO
***************************/

function sendLink(a){

	if(a.className){
		if(a.className == 'popupAgencias'){
			if ( FILTERS['birthdate'].test( $('input#IDfecha').val() ) && $('#IDaconpanates').val()!= "" ) openPopup(a.href,595,773);
			else alert( $('input#IDmsgError').val() )
			return false;
		}

		if(a.className == 'popup'){
			openPopup(a.href);
			return false;
		}

		if(a.className == 'external'){
			var win = window.open(a.href);
			return false;
		}
		if(a.className == 'weboramaHighlight'){
			$(a).parents('.highlightContent').next().submit();
			return false;
		}
	}

	if(a.getAttribute){
		if(a.getAttribute('class') == 'popup'){
			openPopup(a.href);
			return false;
		}

		if(a.getAttribute('rel') == 'external' || a.getAttribute('class') == 'external' || a.getAttribute('target') == '_blank'){
			var win = window.open(a.href);
			return false;
		}
	}



	hideSendToAFriend();

	if(LINK){
		REFERER = LINK;
	}

	LINK = a.href;

	document.location = LINK;
	return;

  try{
  	//TODO: Check if this is necessary
    if(LINK == window.location+''){
      LINK += '?r='+Math.random();
    }

    //Access multimedia content
    var container = document.getElementById('multimediaContainer');

    var obj = container.getElementsByTagName('object');

    if(!obj || obj.length == 0){
      obj = container.getElementsByTagName('img');
    }

    var clip = DY.Dom.getClip(obj[0]);
    var h = DY.Dom.getHeight(obj[0]);

    //Is the multimedia content clipped?
    var multimediaOpened = (clip[0] == 0 && clip[2] == h);

    //There is page content?
    var hasContent = ($('#article').children().length > 0);

    if(multimediaOpened){
      //If there is no content, we'll request the url when the multimedia container finishes hiding
      hideMultimedia(!hasContent);
    }

    if(hasContent){
      hideContent();
    }
  }
  catch(e){
    handleError(e);
  }
}



function _sendLink(){

  if(DUMMY){
    document.getElementById('page').removeChild(DUMMY);
    DUMMY = null;
    }

    //TODO: This shouldn't have to be necessary in the future
    LINK = LINK.replace('.xml', '.html');

  //Request content
  $.get(LINK, REFERER, catchData, 'xml');
}



function catchData(data){

  try{
//		createDummyContent();

	//Check if there is a redirect

	var redirect = checkRedirect(data);

	if(redirect){
		LINK = redirect;
		_sendLink();
		return false;
	}

    _writeContent(data);
    hideLoading();
    weboRequest(LINK);

  }
  catch(e){
    handleError(e);
  }

}

function checkRedirect(data){

	try{

		var _metas = data.getElementsByTagName('meta');

		var _meta, attribute;
		var attributesearch = 'http-equiv';
		var ret = null;

		for (var i = 0; i < _metas.length; i++){
			var _meta = _metas[i];

			if ( _metas[i].attributes["http-equiv"] )
			{
				attribute = _getMetaAttribute(_meta, attributesearch);

				if(attribute){
					attribute = attribute.toLowerCase();

					if(attribute == 'refresh'){
						ret = _getMetaAttribute(_meta, 'content');

						//Remove time from value
						var index = ret.indexOf('url=');
						if(index < 0){
							index = ret.indexOf('URL=');
						}
						ret = ret.substring(index + 4);

						break;
					}
				}
			}
		}

		return ret;
	}
	catch(e){
		throw e;
	}

}

function _getMetaAttribute(node, attributesearch){
	var attribute = null;

	//TODO: Check this. IE seems to not be able to use this node as an XML node?
	if(node.xml){
		var str = node.xml+'';
		var index = str.indexOf(attributesearch);
		if(index < 0){
			return null;
		}

		//Add the length of the searc pattern and 2 more for ="
		index += attributesearch.length + 2;
		str = str.substring(index);

		//Get rid of everything from the closing "
		attribute = str.substring(0, str.indexOf('"'));

	}
	else{
		if(node.getAttribute){
			attribute = node.getAttribute(attributesearch);
		}

		if(!attribute){
			attribute = node.attributes[attributesearch];

			if(attribute.nodeValue){
				attribute = attribute.nodeValue;
			}
			else if(attribute.value){
				attribute = attribute.value;
			}
			else{
				attribute = null;
			}

		}
	}

	return attribute;
}

function createDummyContent(){
  DUMMY = document.createElement('div');
  DUMMY.innerHTML = document.getElementById('pageContent').innerHTML;
  var pos = DY.Dom.getAbsolutePosition('pageContent');

  DY.Dom.setStyle(DUMMY, 'position', 'absolute');
  DY.Dom.moveTo(DUMMY, pos.x, pos.y);
  DUMMY.className = 'dummyContent';
  document.getElementById('page').appendChild(DUMMY);
  DUMMY.style.visibility = 'visible';
}

function _writeContent(xmldata){
    //TODO: Fix this for Opera
    var divs = xmldata.getElementsByTagName('div');

    var articleData;
	var columnData;
	var pathData;

    for (var i = 0; i < divs.length; i++){
      if(divs[i].getAttribute('id') == 'article'){
        articleData = divs[i];
      }

      if(divs[i].getAttribute('id') == 'column'){
        columnData = divs[i];
      }

      if(divs[i].getAttribute('id') == 'path'){
        pathData = divs[i];
      }
    }

    var articleDiv = document.getElementById('article');
    var columnDiv = document.getElementById('column');
    var pathDiv = document.getElementById('path');

	removeContent();

	if(articleData.childNodes.length == 0){
		throw new Error('Malformed page');
	}

	if(articleData && articleData.childNodes.length > 0){

	    var childs = articleData.childNodes;

		//IE will loose "param" tags when retrieving innerHTML, so instead of writing it sequentially
		//we are going to store content in a string and flush it at the end
		var articleString = '';

	    for (var i = 0; i < childs.length; i++){
	      if(childs[i].nodeType == 1){
	          if(childs[i].xml){
					articleString += childs[i].xml;
	          }
	          else{
	          articleDiv.appendChild(childs[i])
	          }
	        }
	    }

		//Just for IE
		if(articleString.length > 0){
			articleDiv.innerHTML = articleString;

			var obj = articleDiv.getElementsByTagName('object');

			for (var i = 0; i < obj.length; i++){
				rewriteObjectHTML(obj[i]);
			}
		}
	}

	if(columnData && columnData.childNodes.length > 0){
	    childs = columnData.childNodes;

	    for (var i = 0; i < childs.length; i++){
	      if(childs[i].nodeType == 1){
	          if(childs[i].xml){
	          columnDiv.innerHTML += childs[i].xml;
	          }
	          else{
	          columnDiv.appendChild(childs[i])
	        }
	      }
	    }
	}

	if(pathData && pathData.childNodes.length > 0){
	    childs = pathData.childNodes;

	    for (var i = 0; i < childs.length; i++){

	      if(childs[i].nodeType == 1){
	          if(childs[i].xml){
	          pathDiv.innerHTML += childs[i].xml;
	          }
	          else{
	          pathDiv.appendChild(childs[i])
	        }
	      }
	    }
	}



    //Initialize content now so specific scripts can overwrite event bindings
    initContent();

    //Get every script of the loaded page
    var neededscripts = xmldata.getElementsByTagName('script');
    _loadScripts(neededscripts);

	initRightMenu();

	setBlur();

	//Set action and value for "send to a friend" form
	var frm = document.getElementById('enviarAmigoform');
	if(frm){
		frm.setAttribute('action', LINK);

		var hidden = document.getElementById('pagina');
		if(hidden){
			hidden.setAttribute('value', LINK);
		}
	}

}


function removeContent(){
    var articleDiv = document.getElementById('article');
    var columnDiv = document.getElementById('column');
    var pathDiv = document.getElementById('path');

    while(articleDiv.firstChild){
      articleDiv.removeChild(articleDiv.firstChild);
    }

    while(columnDiv.firstChild){
      columnDiv.removeChild(columnDiv.firstChild);
    }

    while(pathDiv.firstChild){
      pathDiv.removeChild(pathDiv.firstChild);
    }
}

//var animationCount = 0;

function sendAnimation(){
	this.elm = DY.getElement('loading_Text');

	this.count = 0;
	this.obj = 'sendAnimationObj';//+animationCount++;
	eval(this.obj+'=this');

	this.loop = function(){
		var str = '';
		for (var i = 0; i < this.count; i++){
			str+='.';
		}

		this.elm.innerHTML = "cargando" + str;

		if (this.count++ > 3) {
			this.count = 1;
		}
	}

	this.stop = function(){
		clearInterval(this.timer);
	}

	this.timer = setInterval(this.obj+'.loop()', 200);
}

function showLoading(){

  if(!LOADING){

	LOADING = document.getElementById('loading');
	var p = LOADING.getElementsByTagName('p')[0];
	var texto = p.innerHTML;

	var index = texto.lastIndexOf('.');
	if(index > -1){
		texto = texto.substring(0, index);
	}
	p.innerHTML = texto;
/*    LOADING = document.createElement('div');
    LOADING.id = 'loading';

    LOADING.appendChild(document.createElement('div'));
    var img = document.createElement('img');
    img.setAttribute('src', '/media/img/common/loading.png');
	img.setAttribute('alt', 'Loading');
    LOADING.appendChild(img);
    */

	/* TXUS INTERACTIVO :P */
	/*
	LOADING = document.createElement('div');
    LOADING.id = 'loading';

	var myDiv = document.createElement('div');
	myDiv.id = 'loadingBack';

	var myP = document.createElement('p');
	myP.id = 'loading_Text';
	//myP.innerHTML = 'Cargando...';

    LOADING.appendChild(myDiv);
	LOADING.appendChild(myP);

	document.getElementsByTagName('body')[0].appendChild(LOADING);


	var sendAnim = new sendAnimation();
	*/
	/* END TXUS */

//    document.getElementById('page').appendChild(LOADING);
//	document.getElementsByTagName('body')[0].appendChild(LOADING);
  }

	var pos = DY.Dom.getAbsolutePosition('content');
	window.scroll(0, 0);
	var height = Math.max(DY.Dom.getHeight('content'), DY.Dom.getDocumentHeight());


	LOADING.style.height = height+'px';
	LOADING.style.top = pos.y+'px';

  LOADING.style.display = 'block';

  _sendLink();

/*
  var loading = document.getElementById('loading');
  loading.style.display = 'block'
  var pos = DY.Dom.getAbsolutePosition(loading);
  DY.Dom.setStyle(loading, 'position', 'absolute');
  DY.Dom.moveTo(loading, pos.x, pos.y);
  DY.Dom.setClip(loading, 0, null, 0, 0);
  var h = DY.Dom.getHeight(loading);
  var w = DY.Dom.getWidth(loading);

  var y;

  //There's no visible content
  if(DY.Dom.getAbsolutePosition('submenu').y == 0){
    y = DY.Dom.getAbsolutePosition('content').y + DY.Dom.getAbsolutePosition('foot').y + DY.Dom.getHeight('foot') + 10;
  }
  else{
    y = DY.Dom.getAbsolutePosition('multimediaContainer').y + DY.Dom.getHeight('multimediaContainer') + 10;
  }

  var x = (DY.Dom.getDocumentWidth() - DY.Dom.getWidth('loading')) / 2;

  DY.Dom.moveTo(loading, x, y);

  var wiper = DY.Dom.wipeFrenadoTo(loading, 0, w, h, 0, 5, 5);

  wiper.onWipeFrenadoEnd = function(){
    _sendLink();
  }
*/
}

function hideLoading(){
  showContent();
  /*
  var wiper = DY.Dom.wipeFrenadoTo('loading', 0, null, 0, 0, 5, 5);

  wiper.onWipeFrenadoEnd = function(){
    DY.Dom.setStyle(this.el, 'display', 'none');
    showContent();
  }
  */

}

function showContent(){
  LOADING.style.display = 'none';
  endLoad();
/*
  document.getElementById('loading').style.display = 'none';

  var articleDiv = document.getElementById('article');
  var columnDiv = document.getElementById('column');

  //Disable home style sheet
  if(!document.getElementById('homeStyle').disabled){
    document.getElementById('homeStyle').disabled = true;
  }

  DY.Dom.setVisible('pageContent', false);

  DUMMY = document.createElement('div');
//	DUMMY.style.height = '0px';
  DUMMY.innerHTML = document.getElementById('pageContent').innerHTML;
  var pos = DY.Dom.getAbsolutePosition('pageContent');

  DY.Dom.setStyle(DUMMY, 'position', 'absolute');
  DY.Dom.moveTo(DUMMY, pos.x, pos.y);
  DUMMY.className = 'dummyContent';
  document.getElementById('page').appendChild(DUMMY);
  DUMMY.style.visibility = 'visible';
  $(DUMMY).slideDown(500, endLoad);
*/
}

function hideContent(){
  //Stop the audiovisual
  if(AUDIOVISUALWIDGET){
    AUDIOVISUALWIDGET.stop();
    AUDIOVISUALWIDGET = null;
  }
  showLoading();

/*
  //Create a dummy content and fill it
  DUMMY = document.createElement('div');
  DUMMY.innerHTML = document.getElementById('pageContent').innerHTML;

  //Set dummy content at the same position that the real one
  var pos = DY.Dom.getAbsolutePosition('pageContent');

  DY.Dom.setStyle(DUMMY, 'position', 'absolute');
  DY.Dom.moveTo(DUMMY, pos.x, pos.y);
  DUMMY.className = 'dummyContent';
  document.getElementById('page').appendChild(DUMMY);

  //Hide original contnet (it still pushes its containers)
  DY.Dom.setVisible('pageContent', false);


  $(DUMMY).slideUp(500, showLoading);
*/
}



function showMultimedia(){
  var container = document.getElementById('multimediaContainer');

  var obj = container.getElementsByTagName('object');

  var wiper = DY.Dom.wipeFrenadoTo(obj[0], 0, 1023, DY.Dom.getHeight(obj[0]), 0, 1, 5);



  wiper.onWipeFrenado = function(){
    var clip = DY.Dom.getClip(this.el);
    DY.Dom.setY(this.el, -1 * clip[0]);
    DY.Dom.setHeight(this.el.parentNode, clip[2] - clip[0]);
  }

  wiper.onWipeFrenadoEnd = function(){
    quitMultimediaButton();
    setMultimediaCloser();
	obj[0].SetVariable('_root.changePlay', 'true');
  }

  removeContent();

  //Enable the style sheet we created to hide content
 	var sheet = document.getElementById('multimediaContainerStyle');
	sheet.disabled = false;

}

function hideMultimedia(askForContent){

  var container = document.getElementById('multimediaContainer');
  var obj = container.getElementsByTagName('object');

	//We will create the multimedia opener only if we have flash
	var isMultimedia = true;

	if(!obj || obj.length == 0){
		obj = container.getElementsByTagName('img');
		isMultimedia = false;
	}

	//Get contents CSS to read the clip values
	var sheet = document.getElementById('contentStyle');
	var value = getSelectorValue(sheet, '#multimediaContainer object', 'clip');

	//Get first element from the returned array
	value = value[0];
	//Remove not needed characters
	value = value.substring(value.indexOf('(') + 1, value.indexOf(')'));

	//Split values into an array. First look if the return uses a comma as a separator
	var separator = (value.lastIndexOf(',') > -1) ? ',' : ' ';
	value = value.split(separator);

	//Turn them into numbers
	for (var i = 0; i < value.length; i++){
		value[i] = parseInt(value[i], 10);
	}

  var wiper = DY.Dom.wipeFrenadoTo(obj[0], value[0], value[1], value[2], value[3], 1, 5);

  wiper.onWipeFrenado = function(){
    var clip = DY.Dom.getClip(this.el);
    DY.Dom.setY(this.el, -1 * clip[0]);
    DY.Dom.setHeight(this.el.parentNode, clip[2] - clip[0]);
  }

  var getContent = askForContent;

  wiper.onWipeFrenadoEnd = function(){
    if(getContent){
      showLoading();
    }

	if(isMultimedia){
    	addMultimediaButton();
	}
  }

	//Stop multimedia
	if(isMultimedia){
		obj[0].SetVariable('_root.changePlay', 'false');
	}

	//Remove home highlights if necessary
	var highlight = document.getElementById('homeHighlights');

	if(highlight){
		//TODO: Check why IE6 doesn't remove it
		highlight.style.display = 'none';
		destroyNode(highlight);
		while(highlight.firstChild){
			highlight.removeChild(highlight.firstChild);
		}

//		highlight.parentNode.removeChild(highlight);
	}

  removeMultimediaCloser();
}

function destroyNode(node){
	var nodes = node.childNodes;

	for (var i = 0; i < nodes.length; i++){
		destroyNode(nodes[i]);
	}

	node.parentNode.removeChild(node);
}

function addMultimediaButton(){
  var button = document.getElementById('contenedorMultimediaEnlace');


  if (!button){
    var container = document.getElementById('multimediaContainer');
    var obj = container.getElementsByTagName('object');
    //Only create button if there is flash content
    if(obj && obj.length > 0){
      button = document.createElement('div');
      button.id = 'contenedorMultimediaEnlace';

      var clip = DY.Dom.getClip(obj[0]);
      button.style.height = (clip[2] - clip[0])+'px';

      container.appendChild(button);
    }
  }

  //If button exists, give it behavior and show it
  if(button){
    $(button).click(function(){
      showMultimedia();
    })

    button.style.visibility = 'visible';
  }
}

function quitMultimediaButton(){
  var button = document.getElementById('contenedorMultimediaEnlace');
  if(button){
    button.style.visibility = 'hidden';
  }

}

function setMultimediaCloser(){
/*
  $('body').bind('click', function(){
    hideMultimedia(false);
  })
*/
}

function doHideHomeWidgets(){
	var widgetsContainer = document.getElementById('homeHighlights');
	
	if(widgetsContainer){
		widgetsContainer.style.display = 'none';
	}
}

function removeMultimediaCloser(){
  //Clear all associated events
  $('body').unbind('click');
}

function endLoad(){
  //DY.Dom.setVisible('pageContent', true);

  //Disable home style sheet
  var homeStyle = document.getElementById('homeStyle');
  if(!homeStyle.disabled){
    homeStyle.disabled = true;
  }

	var ie6HomeStyle = document.getElementById('IEhomeStyle');
	if(ie6HomeStyle){
		ie6HomeStyle.disabled = true;
	}


  //Disable the style sheet we created to hide content
	var sheet = document.getElementById('multimediaContainerStyle');
	sheet.disabled = true;

  if(DUMMY){
    DUMMY.parentNode.removeChild(DUMMY);
    DUMMY = null;
  }

}


/***************************
  AUDIOVISUALS
***************************/
function initAudiovisual(){
  var node = document.getElementById('audiovisual');

  if(node){
	var contentDisplay = document.getElementById('content').style.display;
	var pageContentDisplay = document.getElementById('pageContent').style.display;

	document.getElementById('content').style.display = 'block';
	document.getElementById('pageContent').style.display = 'block';
    AUDIOVISUALWIDGET = new PAmultimediaWidget(node);
	document.getElementById('content').style.display = contentDisplay;
	document.getElementById('pageContent').style.display = pageContentDisplay;
  }
}

/***************************
  HIGHLIGHTS
***************************/
function initHighlights(){

  killCSSRule('.highlightContent:hover');
  killCSSRule('.highlightContent:hover img.out');
  killCSSRule('.highlightContent:hover img.over');
  killCSSRule('.highlightContent.over');

  var _highlights = $('.highlightContent');

  if(_highlights.length > 0){
	HIGHLIGHTS = new Array();

	for(var i = 0; i < _highlights.length; i++){
		HIGHLIGHTS[i] = new PAhighlightWidget(i, _highlights[i], HIGHLIGHTS);
	}
  }
}

/***************************
  SCRIPT MANAGEMENT
***************************/

function _saveScripts(){
  var loadedscripts = $('head').children('script');
  var src;

  for(var i = 0; i < loadedscripts.length; i++){
    src = loadedscripts[i].getAttribute('src');
    _addScript(src);
  }
}

function _addScript(src){
  SCRIPTS[SCRIPTS.length] = src;
}

function _loadScripts(needed){
  var toload = new Array();

  for(var i = 0; i < needed.length; i++){
    var id = needed[i].getAttribute('id');
    if(!id){
      continue;
    }

    if(id.lastIndexOf('externalscript') > -1){
      toload[toload.length] = needed[i];
    }
  }

	var src;

  for (var i = 0; i < toload.length; i++){
  	src = toload[i].getAttribute('src');

    $.getScript(src);
  }

	setBlur();

/*
  var neededsrc;
  var found;

  for (var i = 0; i < needed.length; i++){
    neededsrc = needed[i].getAttribute('src');
    found = false;
    for (var j = 0; j < SCRIPTS.length; j++){
      if (neededsrc == SCRIPTS[j]){
        found = true;
      }
    }

    if(!found){
      toload[toload.length] = neededsrc;
    }
  }

  for (var i = 0; i < toload.length; i++){
    $.getScript(toload[i]);
    _addScript(toload[i]);
  }
*/
}

/***************************
  CSS MANAGEMENT
***************************/

function getCSSRule(ruleName, deleteFlag) {
	var ruleName = ruleName.toLowerCase();
   if (document.styleSheets) {
      for (var i=0; i<document.styleSheets.length; i++) {
         var styleSheet=document.styleSheets[i];
         var ii=0;
         var cssRule=false;
         do {
            if (styleSheet.cssRules) {
               cssRule = styleSheet.cssRules[ii];
            } else {
               cssRule = styleSheet.rules[ii];
            }
            if (cssRule)  {
               if (cssRule.selectorText.toLowerCase() == ruleName) {
                  if (deleteFlag=='delete') {
                     if (styleSheet.cssRules) {
                        styleSheet.deleteRule(ii);
                     } else {
                        styleSheet.removeRule(ii);
                     }
                     return true;
                  } else {
                     return cssRule;
                  }
               }
            }
            ii++;
         } while (cssRule)
      }
   }
   return false;
}

function killCSSRule(ruleName) {
   return getCSSRule(ruleName,'delete');
}

function addCSSRule(ruleName) {
   if (document.styleSheets) {
      if (!getCSSRule(ruleName)) {
         if (document.styleSheets[0].addRule) {
            document.styleSheets[0].addRule(ruleName, null,0);
         } else {
            document.styleSheets[0].insertRule(ruleName+' { }', 0);
         }
      }
   }
   return getCSSRule(ruleName);
}

function createMultimediaStyleSheet(){

	//If we have entered by a page different than home, "content style" will be applied after "home style",
	//so just setting "home style" to enabled won't work.
	//Here we create a new style sheet and apply to it the rules needed to get the "back to home" effect.
	var s = document.createElement('style');
	s.setAttribute('type', 'text/css');
	s.setAttribute('id', 'multimediaContainerStyle');

	document.getElementsByTagName('head')[0].appendChild(s);

	//Access the new style sheet
	s = document.styleSheets[document.styleSheets.length - 1];
	//Disable it
	s.disabled = true;

	//Rules we need to copy
	var ruleNames = ['#content', '#path', '#pageContent', '#multimediaContainer'];

	//Get sheet by id
	var searchSheet = document.getElementById('homeStyle');
	//Get source of desired sheet
	var searchSheetSrc = searchSheet.getAttribute('href');
	//Get style sheet
	var sheet = getStyleSheetBySrc(searchSheetSrc);

	//Get rules for every selector and add them to the new styleSheet
	var rule;
	for (var i = 0; i < ruleNames.length; i++){
		rule = getRulesBySelector(sheet, ruleNames[i]);
		addRuleToStyleSheet(s, rule[0]);
	}

	//If there's an IE6 sheet for home save its selectors
	var ieHomeStyle = document.getElementById('IEhomeStyle');
	if(ieHomeStyle){
		//Rules we need to copy
		ruleNames = ['#content'];

		//Get source of desired sheet
		searchSheetSrc = ieHomeStyle.getAttribute('href');
		//Get style sheet
		sheet = getStyleSheetBySrc(searchSheetSrc);

		//Get rules for every selector and add them to the new styleSheet
		for (var i = 0; i < ruleNames.length; i++){
			rule = getRulesBySelector(sheet, ruleNames[i]);
			addRuleToStyleSheet(s, rule[0]);
		}
	}
}

//Will return an array of every occurrence of a selector with specified property
function getSelectorValue(searchSheet, selector, property){
	var cssRules;
	var cssSelector;
	var sheet;

	if(searchSheet.getAttribute){
		//Get source of desired sheet
		var searchSheetSrc = searchSheet.getAttribute('href');
		//Get style sheet
		sheet = getStyleSheetBySrc(searchSheetSrc);
	}
	else{
		sheet = searchSheet;
	}

	//Get selectors from this sheet
	var matches = getRulesBySelector(sheet, selector);

	if(matches.length == 0){
		return null;
	}

	var ret = new Array();

	for (var i = 0; i < matches.length; i++){

		if(matches[i].style[property]){
			ret[ret.length] = matches[i].style[property];
		}
	}

	return ret;
}

function getStyleSheetBySrc(src){
	//Get path from "css" folder
	var searchSheetSrc = src.substring(src.indexOf('/css'));

	var sheetSrc;
	var sheet;
	for (var i = 0; i < document.styleSheets.length; i++) {
		var sheet = document.styleSheets[i];
		sheetSrc = sheet.href;
		sheetSrc = sheetSrc.substring(sheetSrc.indexOf('/css'));

		if(sheetSrc == searchSheetSrc){
			return sheet;
			break;
		}
	}

	return null;

}

function getRulesBySelector(sheet, selector){
	var searchPattern = new RegExp('(^|\s)' + selector + '([,]|$)', 'i');

	var matches = new Array();

	if(sheet.cssRules){
		cssRules = sheet.cssRules;
	}
	else{
		cssRules = sheet.rules;
	}

	for(var i = 0; i < cssRules.length; i++){
		if(searchPattern.test(cssRules[i].selectorText)){
			matches[matches.length] = cssRules[i];
		}
	}


	return matches;

}

function addRuleToStyleSheet(sheet, rule){
	var selector = rule.selectorText;
	var ruleContent;

	if(sheet.insertRule){
		sheet.insertRule(rule.cssText, sheet.cssRules.length);
	}
	else{
		ruleContent = rule.style.cssText;
		sheet.addRule(selector, ruleContent, sheet.rules.length);
	}
}



function insertAfter(parent, node, referenceNode) {
	parent.insertBefore(node, referenceNode.nextSibling);
}

/***************************
  POPUP
***************************/

function openPopup(url, _width, _height, _useScroll){
	var width = _width || 536;
	var height = _height || 406;
	var x = (screen.width - width) / 2;
	var y = (screen.height - height) / 2;
	var useScroll = (_useScroll != null) ? _useScroll : 1;

	if(useScroll){
		width += 12;
	}

	var win = window.open(url, 'PA', 'resizable=0,scrollbars='+useScroll+',status=0,location=0,toolbar=0,menubar=0,width='+width+',height='+height+',screenX='+x+',screenY='+y+',left='+x+',top='+y+'');
}

/***************************
  RANDOM BACKGROUND
***************************/

function setRandomBackground(newimg){

	if(!newimg){
		//Background images
		var BGIMAGES = ['wood', 'polinesia', 'west', 'china'];

		var index = Math.floor(Math.random() * BGIMAGES.length);

		var newBGIMAGE = BGIMAGES[index];

		if(!newBGIMAGE){
			newBGIMAGE = BGIMAGES[1];
		}

		var globalcss = getStyleSheetBySrc('/css/globalj.css');

		var rule = getSelectorValue(globalcss, 'body', 'backgroundImage');
		rule += '';

		var path = rule.substring(rule.lastIndexOf('(') + 1);

		path = path.substring(0, path.lastIndexOf('/') + 1);
		newimg = path+newBGIMAGE+'.jpg';

		if(globalcss.insertRule){
			globalcss.insertRule('body{background-image:url('+newimg+')}', globalcss.cssRules.length);
		}
		else{
			globalcss.addRule('body', 'background-image:url('+newimg+')', globalcss.rules.length);
		}

	}
}

//setRandomBackground()

function handleError(e){
  //Something has gone wrong. Send user to the page.
  window.location.href = LINK;
  var s = '';
  for(var i in e) s += i+': '+e[i]+'\n';
  //alert('error \n'+s);
  //alert('Hola. Soy un error.\nPero no te asustes; lo más probable es que hayas intentado acceder a una página que todavía no existe.\nPor si las moscas, apúntate esta url:\n'+LINK+'\nCuando hayas acabado de revisarlo todo, envíales a Txus y Jose todos los enlaces que han fallado para que les peguen un ojo.\n\nGracias y buenos días.\n\nPD: Ahora se recargará la página.\n\n==============================\nERROR DATA:\n'+s)
  //window.location.href = window.location.href;
}
function weboRequest(CONTENT) {
	WRP_CONTENT = CONTENT;

	
	if (w_counter.nb_content > 0) w_counter.nb_content--;	
	w_counter.add_content(WRP_CONTENT);	
	w_counter.auto=1;
	w_counter.count();	

	$('a.external,a.popup').each(function() {
		var path_info = this.href.split("/media/pdf")[1];		
		var extension = this.href.substring(this.href.length-4,this.href.length);		
		if ( extension == '.pdf' || extension == '.PDF') {
			this.onclick = function() { weboRequest(path_info) }
		}		
	})
}


//Fin
}


function weboWESTORE(id){
	var url = ""
	$('form#'+id+' input').each(function(){
		url+= this.name+"="+this.value+'&';
	})
	var action = $('form#formTickets').attr('action')+'?'+url;
    $('form#formTickets').attr('action',action)
    $('form#formTickets').submit();
}