﻿var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

function $() {
  var elements = new Array();
  for (var i = 0; i < arguments.length; i++) {
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);

    if (arguments.length == 1)
      return element;

    elements.push(element);
  }
  return elements;
}

document.getElementsByClassName = function(className, parentElement, nodeType) {
	var search_elements;
	
	if(nodeType)
		search_elements = $NL(($(parentElement) || document.body).getElementsByTagName(nodeType));
	else if(document.all)
		search_elements = $NL(($(parentElement) || document.body).all);
	else
		search_elements = $NL(($(parentElement) || document.body).getElementsByTagName("*"));

	className = className.toUpperCase();
 
  return search_elements.inject([], function(elements, child) {
  	var classElements = $A(child.className.toUpperCase().split(' '));
  	classElements.each(function(classElement) {
		if (classElement == className) {
	    		elements.push(child);
		}
  	});
  	return elements;
  });
}


var Prototype = 
{
	Version: '1.4.0',
	ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',
  emptyFunction: function() {},
  K: function(x) {return x}
}

var Class = 
{
  create: function() 
  {
  	return function() 
  	{
    	this.initialize.apply(this, arguments);
    }
  }
}

var Abstract = new Object();

Object.extend = function(destination, source) 
{
	for (property in source) 
	{
		destination[property] = source[property];
	}
  return destination;
}

Object.inspect = function(object) 
{
	try 
	{
  	if (object == undefined) return 'undefined';
    if (object == null) return 'null';
    return object.inspect ? object.inspect() : (object.toString ? object.toString() : typeof object);
  } 
  catch (e) 
  {
    if (e instanceof RangeError) return '...';
    throw e;
  }
}

Function.prototype.bind = function() 
{
	var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
}

Function.prototype.bindAsEventListener = function(object) 
{
  var __method = this;
  return function(event) 
  {
    return __method.call(object, event || window.event);
  }
}

Object.extend(Number.prototype, {
  toColorPart: function() {
    var digits = this.toString(16);
    if (this < 16) return '0' + digits;
    return digits;
  },

  succ: function() {
    return this + 1;
  },

  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  }
});

var Try = {
  these: function() {
    var returnValue;

    for (var i = 0; i < arguments.length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }

    return returnValue;
  }
}


var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0; i < iterable.length; i++)
      results.push(iterable[i]);
    return results;
  }
}
var $break    = new Object();
var $continue = new Object();

var Enumerable = {
  each: function(iterator) {
    var index = 0;
    try {
      this._each(function(value) {
        try {
          iterator(value, index++);
        } catch (e) {
          if (e != $continue) throw e;
        }
      });
    } catch (e) {
      if (e != $break) throw e;
    }
  },

  all: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      result = result && !!(iterator || Prototype.K)(value, index);
      if (!result) throw $break;
    });
    return result;
  },

  any: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      if (result = !!(iterator || Prototype.K)(value, index))
        throw $break;
    });
    return result;
  },

  collect: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      results.push(iterator(value, index));
    });
    return results;
  },

  detect: function (iterator) {
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },

  findAll: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },

  grep: function(pattern, iterator) {
    var results = [];
    this.each(function(value, index) {
      var stringValue = value.toString();
      if (stringValue.match(pattern))
        results.push((iterator || Prototype.K)(value, index));
    })
    return results;
  },

  include: function(object) {
    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },

  inject: function(memo, iterator) {
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },

  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.collect(function(value) {
      return value[method].apply(value, args);
    });
  },

  max: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (value >= (result || value))
        result = value;
    });
    return result;
  },

  min: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (value <= (result || value))
        result = value;
    });
    return result;
  },

  partition: function(iterator) {
    var trues = [], falses = [];
    this.each(function(value, index) {
      ((iterator || Prototype.K)(value, index) ?
        trues : falses).push(value);
    });
    return [trues, falses];
  },

  pluck: function(property) {
    var results = [];
    this.each(function(value, index) {
      results.push(value[property]);
    });
    return results;
  },

  reject: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },

  sortBy: function(iterator) {
    return this.collect(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },

  toArray: function() {
    return this.collect(Prototype.K);
  },

  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (typeof args.last() == 'function')
      iterator = args.pop();

    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      iterator(value = collections.pluck(index));
      return value;
    });
  },

  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
  },
  
	unique: function(){
		return this.inject([], function(results, item){
			if(results.indexOf(item) < 0)
				results.push(item);
			return results;
		});
	}
}

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray
});

Object.extend(String.prototype, {
	templateReplace: function(search_string, replace_string){
		//var regEx = new RegExp('~' + search_string + '~', 'g')
		var output = this.replace('~' + search_string + '~', replace_string);
		return output;
	}
});

Object.extend(Array.prototype, Enumerable);
Object.extend(String.prototype, Enumerable);

Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0; i < this.length; i++)
      iterator(this[i]);
  },

  clear: function() {
    this.length = 0;
    return this;
  },

  first: function() {
    return this[0];
  },

  last: function() {
    return this[this.length - 1];
  },

  compact: function() {
    return this.select(function(value) {
      return value != undefined || value != null;
    });
  },

  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(value.constructor == Array ?
        value.flatten() : [value]);
    });
  },

  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },

  indexOf: function(object) {
    for (var i = 0; i < this.length; i++)
      if (this[i] == object) return i;
    return -1;
  },

  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },

  shift: function() {
    var result = this[0];
    for (var i = 0; i < this.length - 1; i++)
      this[i] = this[i + 1];
    this.length--;
    return result;
  },

  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  }
});


function swapOver(img, suffix) 
{
	if(!suffix) { suffix = 'Over'; }
	var img = $(img);
	if(img.src.indexOf(suffix) > -1 || img.src == img.getAttribute('hover_src')) 	{
		if(img.getAttribute('nohover_src'))
			img.src = img.getAttribute('nohover_src');
		else
			img.src = img.src.replace(suffix, '');
	}
	else 
	{
		if(img.getAttribute('hover_src')){
			img.setAttribute('nohover_src', img.src);
			img.src = img.getAttribute('hover_src');
		}
		else{
			var array = img.src.split('.');
			var src = "";		
			// Loop through all but the last
			for(var i=0; i<(array.length - 1); i++) {
				if(i!=0)
				 src += '.';
				src += array[i];
			}
			img.src = src + suffix + '.' + array[array.length-1];
		}
	}
}

function swapOn(img, suffix) 
{
	if(!suffix) { suffix = 'Over'; }
	var img = $(img);
	if(img.src.indexOf(suffix) > -1) {
		// Do nothing.
	}
	else if(img.getAttribute('hover_src')){
		img.src = img.getAttribute('hover_src');
	}
	else {
		var array = img.src.split('.');
		var src = "";		
		// Loop through all but the last
		for(var i=0; i<(array.length - 1); i++) {
			if(i!=0)
			 src += '.';
			src += array[i];
		}
		img.src = src + suffix + '.' + array[array.length-1];
	}
}

function swapOut(img, suffix) {
	if(!suffix) { suffix = 'Over'; }
	var img = $(img);
	if(img.src.indexOf(suffix) > -1 || img.src == img.getAttribute('hover_src')) {
		if(img.getAttribute('nohover_src'))
			img.src = img.getAttribute('nohover_src');
		else
			img.src = img.src.replace(suffix, '');
	}
}

function swapOut_click(event, img, suffix){
	if(!suffix) { suffix = 'Over'; }
	var img = $(img);
	if(img.src.indexOf(suffix) > -1) {
		if(!Dom.isInBounds(img, Event.pointerX(event), Event.pointerY(event))){
			img.src = img.src.replace(suffix, '');
		}
	}

}

var isFlashHidden = false;


function hideAllFlashInSafari() {
	if (!isFlashHidden && isMacBrowser()){
		var flashObjs = $A(document.getElementsByTagName('OBJECT'));
		
		flashObjs.each(function(flashObj) {
			flashObj.parentNode.style.visibility   = 'hidden';	
		})
		isFlashHidden = true;		
	}
}
function showAllFlashInSafari() {
	
	if (isFlashHidden){
		var flashObjs = $A(document.getElementsByTagName('OBJECT'));
		
		flashObjs.each(function(flashObj) {
			flashObj.parentNode.style.visibility = 'visible';		
		})		
		isFlashHidden = false;		
	}
}


function isMacBrowser() {
	if(navigator.userAgent.toLowerCase().indexOf('mac') > -1) {
		return true;	
	}
	return false;
}

var isSelectHidden = false;
var selectsFound;
function disableAllSelectElementsInIE() {
	if (!isSelectHidden && hideSelectElements()){
		
		if(!selectsFound) {
			var selectObjs = document.getElementsByTagName('SELECT');
			selectsFound = new Array();
			
			for(var i=0; i<selectObjs.length; i++) {
				selectsFound.push(selectObjs[i]);
			}
		}
		for(var i=0; i<selectsFound.length; i++) {
			selectsFound[i].style.visibility = 'hidden';
		}
		isSelectHidden = true;		
	}
}
function enableAllSelectElementsInIE() {
	
	if (isSelectHidden && selectsFound){
		for(var i=0; i<selectsFound.length; i++) {
				selectsFound[i].style.visibility = 'visible';	
		}
		isSelectHidden = false;
	}
		
}
function hideSelectElements() {
	if(document.all) {
		return true;	
	}
	return false;
}



function showElementsForOverlays() {
	showAllFlashInSafari();
	enableAllSelectElementsInIE();
}

function hideElementsForOverlays() {
	hideAllFlashInSafari();
	disableAllSelectElementsInIE();
}

function Node() {}

Node.ELEMENT_NODE = 1;
Node.ATTRIBUTE_NODE = 2;
Node.TEXT_NODE = 3;
Node.CDATA_SECTION_NODE = 4;
Node.ENTITY_REFERENCE_NODE = 5;
Node.ENTITY_NODE = 6;
Node.PROCESSING_INSTRUCTION_NODE = 7;
Node.COMMENT_NODE = 8;
Node.DOCUMENT_NODE = 9;
Node.DOCUMENT_TYPE_NODE = 10;
Node.DOCUMENT_FRAGMENT_NODE = 11;
Node.NOTATION_NODE = 12;

/**
 * This section extends (or create in IE) the NodeList object
 * to allow for enumeration of read-only node lists (element.childNodes, etc)
 * A NodeList differs from an Array in a couple ways.
 * - It is specifically designed to hold Nodes (XML nodes or HTML elements)
 * - It is read only
 * - It is often "live" meaning that if the DOM changes, this list will often change
 *   without warning.
 * - It's much faster
 */
function IENodeList(node_list){
	var _real_node_list;
	this._real_node_list = node_list;
};

NodeList_Extensions = {
	elements:	function() {
					return this.inject([], function(elementNodes, element) {
					  if(element.nodeType == Node.ELEMENT_NODE)
						elementNodes.push(element);
					  return elementNodes;
					})
				},
	firstElement:	function(){
					return this.elements().first();
				},
	lastElement:	function(){
					return this.elements().last();
				},
	inspect:	Array.prototype.inspect				
};


Object.extend(IENodeList.prototype, Enumerable);
Object.extend(IENodeList.prototype, {
	_each:	function(iterator) {
		for (var i = 0; i < this._real_node_list.length; i++)
			iterator(this._real_node_list[i]);
	},
	first:		function(){ return this._real_node_list[0] },
	last:		function(){ return this._real_node_list[this._real_node_list.length - 1] },
	indexOf:	function(object) {
				for (var i = 0; i < this._real_node_list.length; i++)
					if (this._real_node_list[i] == object) return i;
				return -1;
			}
});
Object.extend(IENodeList.prototype, NodeList_Extensions);

if(typeof NodeList != 'undefined'){
	Object.extend(NodeList.prototype, Enumerable);	
	Object.extend(NodeList.prototype, {
		_each:		Array.prototype._each,
		first:		Array.prototype.first,
		last:		Array.prototype.last,
		indexOf:	Array.prototype.indexOf
	});
	Object.extend(NodeList.prototype, NodeList_Extensions);
}

/**
 * Build a browser independent NodeList object from a node list.
 * This does nothing in FireFox, but supplies a bunch of fixes in IE.
 */
function $NL(node_list){

	if(typeof IENodeList != 'undefined' || typeof node_list != 'NodeList'){
		return new IENodeList(node_list);
	}
	else{
		return node_list;
	}

}


if (!window.Event) {
  var Event = new Object();
}

Object.extend(Event, {
  KEY_BACKSPACE: 8,
  KEY_TAB:       9,
  KEY_RETURN:   13,
  KEY_ESC:      27,
  KEY_LEFT:     37,
  KEY_UP:       38,
  KEY_RIGHT:    39,
  KEY_DOWN:     40,
  KEY_DELETE:   46,

  element: function(event) {
    return event.target || event.srcElement;
  },

  isLeftClick: function(event) {
    return (((event.which) && (event.which == 1)) ||
            ((event.button) && (event.button == 1)));
  },

  pointerX: function(event) {
    return event.pageX || (event.clientX +
      (document.documentElement.scrollLeft || document.body.scrollLeft));
  },

  pointerY: function(event) {
    return event.pageY || (event.clientY +
      (document.documentElement.scrollTop || document.body.scrollTop));
  },

  stop: function(event) {
    if (event.preventDefault) {
      event.preventDefault();
      event.stopPropagation();
    } else {
      event.returnValue = false;
      event.cancelBubble = true;
    }
  },

  // find the first node with the given tagName, starting from the
  // node the event was triggered on; traverses the DOM upwards
  findElement: function(event, tagName) {
    var element = Event.element(event);
    while (element.parentNode && (!element.tagName ||
        (element.tagName.toUpperCase() != tagName.toUpperCase())))
      element = element.parentNode;
    return element;
  },

  observers: false,

  _observeAndCache: function(element, name, observer, useCapture) {
    if (!this.observers) this.observers = [];
    if (element.addEventListener) {
      this.observers.push([element, name, observer, useCapture]);
      element.addEventListener(name, observer, useCapture);
    } else if (element.attachEvent) {
      this.observers.push([element, name, observer, useCapture]);
      element.attachEvent('on' + name, observer);
    }
    return this.observers[this.observers.length-1];
  },

  unloadCache: function() {
    if (!Event.observers) return;
    for (var i = 0; i < Event.observers.length; i++) {
      Event.stopObserving.apply(this, Event.observers[i]);
      Event.observers[i][0] = null;
    }
    Event.observers = false;
  },

  observe: function(element, name, observer, useCapture) {
    var element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.attachEvent))
      name = 'keydown';

    return this._observeAndCache(element, name, observer, useCapture);
  },
  
  stopObserving: function(element, name, observer, useCapture) {

    if(arguments.length == 1){
    	name = element[1];
    	observer = element[2];
    	useCapture = element[3];
    	element = element[0];
    }
    
    var element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.detachEvent))
      name = 'keydown';

    if (element.removeEventListener) {
      element.removeEventListener(name, observer, useCapture);
    } else if (element.detachEvent) {
      element.detachEvent('on' + name, observer);
    }
  }
});


OnPageLoadEvents = Class.create();
Object.extend(OnPageLoadEvents.prototype, {
	initialize: function(){
		this.actions = new Array();
		Event.observe(window, 'load', function(){this._executeActions()}.bind(this), false);
	},
	addAction: function(func) {
		
		this.actions.push(func);
	}, 
	_executeActions: function() {
		for(var i=0; i<this.actions.length; i++) {
			var action = this.actions[i];
			action.apply(window,[]);
		}
	}	
});
var onPageLoadEvents = new OnPageLoadEvents();

//onPageLoadEvents.addAction(function() {debugOnloadEventTiming.startTime()});
onPageLoadEvents.addAction(function() {PAGE_LOAD = true;});

 var MODEL_ID = '';
 menuTimeout = 250;
 IMG_ROOT = '/images/';



/* Header navigation */

/* Global variables */
var hideMeDelay		= 250; // Submenu close time in miliseconds-->
var subMenuObj 		= "";
var currentButton = "";

/* Add dynamically onclick event to the header buttons */
onPageLoadEvents.addAction(addOnClickHandlers);
//vent.observe(window, 'load', addOnClickHandlers);
function addOnClickHandlers()
{
	var headerDiv = $('headernav_menu');
	var href = headerDiv.getElementsByTagName("a");
	//href[1].onmouseover = function(){swapOver('headernav_btnHOME')};
	//href[1].onmouseout  = function(){swapOver('headernav_btnHOME')};
	//href[2].onmouseover = function(){swapOver('headernav_btnLEGAL')};
	//href[2].onmouseout  = function(){swapOver('headernav_btnLEGAL')};
	//href[3].onmouseover = function(){swapOver('headernav_btnOTROS')};
	//href[3].onmouseout  = function(){swapOver('headernav_btnOTROS')};
	//href[4].onmouseover = function(){swapOver('headernav_btnMAIL')};
	//href[4].onmouseout  = function(){swapOver('headernav_btnMAIL')};
}
/* End add onclick */

function dropDownMenu(obj, thisButton, thisSub)
{
	navigationManager.hideNavigation();
	if (window.event)
	{ /* IE */
		event.cancelBubble=true; /* IE-Bubbling is disabled for this event, preventing the next event handler in the hierarchy from receiving the event*/
		clearHideSub();
		if (typeof subMenuObj!="undefined" && subMenuObj!=""){subMenuObj.style.visibility="hidden";} /* Hide last sub between button switch */
		if (currentButton!=""){ swapOver(currentButton); } /* Switch last button to normal state */
		subMenuObj=document.getElementById? document.getElementById(thisSub) : thisSub; /* Define new drop down menu object */
	}
	else
	{ /* w3c */
		clearHideSub();
		if (typeof subMenuObj!="undefined" && subMenuObj!=""){subMenuObj.style.visibility="hidden";}
		if (currentButton!=""){swapOver(currentButton);}
		subMenuObj=document.getElementById? document.getElementById(thisSub) : thisSub;
	}
	//alert(thisButton);
	showHideSub(subMenuObj.style, thisButton);

	return clickReturnValue();
}

function clearHideSub()
{ /* Clears the counter, hide any sub menus opened, and allows other sub menus to re-use it */
	if (typeof delayHide!="undefined"){clearTimeout(delayHide);}
}

function showHideSub(obj, thisButton)
{
	currentButton=thisButton; /* Assign the new current button globally */
	obj.visibility="visible"; /* Show the sub menu related to the current button */
	swapOver(thisButton);/*return setImage(thisButton,"hilite"); /* Hilite the onmouseovered menu button */
}

function clickReturnValue()
{ /* Fix older browser issues */
	return false;
}

function delayHideSub(btnRef)
{ /* Sets a delay for hiding both "on state" button and its sub */
	delayHide=setTimeout("hideSub('" + btnRef + "')",hideMeDelay);
}

function hideSub(btnRef)
{/* Hide current button and its related sub menu */
	if (typeof subMenuObj!="undefined" && subMenuObj!="")
	{
		currentButton = "";
		subMenuObj.style.visibility = "hidden";
		swapOver(btnRef); /*return setImage(btnRef,"normal");*/
	}
}

function initOnStates()
{/* Function that sets On State to the current section button */
	switch(MODEL_ID)
	{
		case 'About':
			$('headernav_btnABOUT').setAttribute('hover_src', $('headernav_btnABOUT').src.replace(new RegExp('(.*)(\.gif)', 'i'), '$1Over$2'));/* Sets the button name to hn_btnALOver */
			$('headernav_btnABOUT').src = $('headernav_btnABOUT').src.replace(new RegExp('(.*)(\.gif)', 'i'), '$1On$2');/* Sets the button name to hn_btnALOn */
			break;
		case 'Owners':
			$('headernav_btnOwn').setAttribute('hover_src', $('headernav_btnOwn').src.replace(new RegExp('(.*)(\.gif)', 'i'), '$1Over$2'));/* Sets the button name to hn_btnALOver */
			$('headernav_btnOwn').src = $('headernav_btnOwn').src.replace(new RegExp('(.*)(\.gif)', 'i'), '$1On$2');/* Sets the button name to hn_btnOwnOn */
			break;
		case 'CPO':
			$('hn_btnLEGAL').setAttribute('hover_src', $('hn_btnCPO').src.replace(new RegExp('(.*)(\.gif)', 'i'), '$1Over$2'));/* Sets the button name to hn_btnCPOOver */
			$('hn_btnCPO').src = $('hn_btnCPO').src.replace(new RegExp('(.*)(\.gif)', 'i'), '$1On$2');/* Sets the button name to hn_btnCPOOn */
			break;
		case 'Dealers':
			$('hn_FD').src = $('hn_FD').src.replace(new RegExp('(.*)(\.gif)', 'i'), '$1On$2');/* Sets the button name to hn_btnFDOn */
			break;
	}
}

onPageLoadEvents.addAction(initOnStates);
//vent.observe(window, 'load', initOnStates);
/* End Header Navigation */











































///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////   N  A  V  E  G  A  C  I  O  N  ///////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


var navigationManager = new CameraNavigationManager();


	/**
 * Class provides static methods to build and display the navigation onto the browser
 * @constructor
 */
function CameraNavigationView() 
{
	this.ROOT_IMG = '/images/menu/';
	this.MODEL_REPLACE = 'model';
	this.MODEL_CODE_REPLACE = 'model-code';
	this.CATEGORY_REPLACE = 'category';
	this.IMG_GALLERY = this.ROOT_IMG + 'modelo_~' + this.MODEL_REPLACE + '~Pg.gif';
	this.IMG_HEAD = this.ROOT_IMG + 'modelo_~'  + this.MODEL_REPLACE + '~Head.gif';
	this.IMG_PHOTO = this.ROOT_IMG + 'modelo_~'  + this.MODEL_REPLACE + '~Photo.gif';
	this.CAT_OVERLAY = this.ROOT_IMG + 'categoria_~' + this.CATEGORY_REPLACE + '~On.gif'
	                                                                         
	/**
	 * Method will control the operatations to build and show a Cateogry Navigation.
	 * Will return true if the Model navigation is displayed
	 * @param category ProductCategory
	 * @type boolean
	 * @member CameraNavigationView
	 */
	this.showCategoryNavigation = function(category) 
	{
		var wrapper = $('wrapper');
		
		this.buildCategoryOverlay(category);
		this.buildCategoryNavigation(category);
	
		// If we could not build, return, nothing else to do
		if(!category.domOverlay)
		  return;
	
		// Make sure we have the Model class NOT category
	    wrapper.appendChild(category.domOverlay);
	    category.domOverlay.style.top = Dom.getTopYAsPx(category.domHotSpot,wrapper);
	    category.domOverlay.style.left = Dom.getLeftXAsPx(category.domHotSpot,wrapper);
	    category.domOverlay.style.display = 'block';
			
		if(!category.domNavigation)
		  return
		category.domNavigation.style.top = Dom.getBottomYAsPx('mvContainer',wrapper);
	
		/*
		 * Need to calculate the position of category div
		 * This will take into consideration the total size of the
		 * category menu and compare with the total size of the navigation bar.
		 * This is to make sure we do NOT position past the right most point of
		 * the navigation bar.
		 */
		var catTotalSize = 1; // we start with one because the category div has to make up one extra right px
		var navTotalSizeRight = 0;
		var catTotalSizeRight = 0;
	
	    /* 
	     * Calculate the total width based on how many models we are showing
	     * also adds the left position of the dom hot spot (category image)
	     */
		for(var i=0; i<category.models.length; i++) {
			catTotalSize += 234;
			if(i>0) {
				catTotalSize += 1;
			}
		}
		catTotalRight = catTotalSize + Dom.getLeftX(category.domHotSpot,wrapper) - 5;
	
	    // calculate the total size and left position of Navigation bar.
	    var mvBoundry = Dom.getBoundries('mvContainer',wrapper);
	    
	    navTotalSize = mvBoundry.width + mvBoundry.leftX
	    /* 
	     * If are category div is larger than the navigation bar then we will 
	     * line it up on the right corner
	     */
		if(catTotalRight  >  navTotalSize) {
		  category.domNavigation.style.left = (mvBoundry.rightX - catTotalSize) + 'px';
		}
		/*
		 * Else position the menu at the left edge of the triggering category image
		 */
		else {
		  category.domNavigation.style.left = (Dom.getLeftX(category.domHotSpot,wrapper) - 5) + 'px';
		}
		wrapper.appendChild(category.domNavigation);
		category.domNavigation.style.display = 'block';
	    
	}
	/**
	 * Method will control the operatations to build and show a Model Navigation.
	 * Will return true if the Model navigation is displayed
	 * @param model ProductModel
	 * @type boolean
	 * @member CameraNavigationView
	 */
	this.showModelNavigation = function(model,modelHref) 
	{
		var wrapper = $('wrapper');
		this.buildModelNavigation(model,modelHref);
	
		// if we could not build, return, nothing else to do
		if(!model.domNavigation)
		  return

      // show and position navigation menu	
		wrapper.appendChild(model.domNavigation);	
		
		model.domNavigation.style.top = Dom.getBottomYAsPx('mvContainer',wrapper);
		model.domNavigation.style.left = (Dom.getLeftX(model.domHotSpot,wrapper) - 8) + 'px';
	   model.domNavigation.style.display = 'block';
	    
	    
		this.buildModelOverlay(model);
		
		// if we could not build, return, nothing else to do
		if(!model.domOverlay)
		  return
		
		wrapper.appendChild(model.domOverlay);
		model.domOverlay.style.top = Dom.getTopYAsPx(model.domHotSpot,wrapper);
		// We move the image 4 px left because the image has 3px on each side more of space
		model.domOverlay.style.left = (Dom.getLeftX(model.domHotSpot,wrapper) - 4) + 'px';
		
		model.domOverlay.style.display = 'block';
	    
		return true;
	}
	/**
	 * Method will build the DIV Object Navigation representing a specific Model.
	 * @param model ProductModel
	 * @type void
	 * @member CameraNavigationView
	 */
	this.buildModelNavigation = function(model,modelHref) {
	    if(model.domNavigation)
		  return
		
		var nav = $('mvNavigationModel_Template').cloneNode(true);
	    var links = nav.getElementsByTagName('a');
	    var imgs = nav.getElementsByTagName('IMG');
	
	//Set all Links
	   for(var i=0; i<links.length; i++) {
	   	 var link = links[i];
	   	 var linkImg = link.firstChild;
	   	 //enlace = link.getAttribute('link');
	   	 //alert(enlace);
	   	 link.href = this._replaceModelLink2(link.href, model.id, model.code,modelHref);	   	
	   
		 if(link.parentNode.className == 'mvNavigationLink') {
		 	//Debug.debug('', linkImg);
 		 	Event.observe(linkImg, 'mouseover', function() {swapOver(this)}.bind(linkImg) );   	
 		 	Event.observe(linkImg, 'mouseout', function() {swapOut(this)}.bind(linkImg) );
		 }
	   }
	   
	// Set all images
		for(var i=0; i<imgs.length; i++) {
			var img = imgs[i];
			var pieces = img.src.split('#');
			img.src = this._replaceModel(pieces[pieces.length - 1], model.id);	 
	   	img.alt = this._replaceModel(img.alt, model.name);		   	
		}

		nav.id = 'mvNav_' + model.categoryId + "_" + model.id;
    
	//Build Features
		var containerDivs = nav.getElementsByTagName('DIV');
		var topChildrenDivs = containerDivs[0].getElementsByTagName('DIV');
		var featuresDiv = topChildrenDivs[topChildrenDivs.length - 1];
		var startingPrice = topChildrenDivs[topChildrenDivs.length - 2];
		
		for(var i=0; i<model.features.length; i++) {
			var featureDiv = document.createElement('DIV');
			featureDiv.className = 'mvNavigationFeature';
			featureDiv.innerHTML = model.features[i];
			
			/*
			var disclaimers = featureDiv.getElementsByTagName('A');
			
			for(var x=0; x<disclaimers.length; x++) {
				var disclaimer = disclaimers[x];
				
				disclaimer.href = 'javascript:void(0);'
				
				disclaimer.onclick = function() {navigationManager.launchDisclaimer(this);}.bind(model.name);
			}
			*/
			featuresDiv.appendChild(featureDiv);		
		}
		
		
	//Build Staring Price
		//startingPrice.innerHTML = model.getPriceAsString();
		
		
		
    //Add Events
		if(document.all)
		  Event.observe(nav, 'mouseout', function() {event.cancelBubble = true;navigationManager.hideNavigationWithTimeOut(event)})
		else
		  Event.observe(nav, 'mouseout', function(event) {event.cancelBubble = true;navigationManager.hideNavigationWithTimeOut(event)})
		
		Event.observe(nav, 'mouseover', function() {navigationManager.clearTimeOut()})

		model.domNavigation = nav;
		
		//this._addLegalDisclaimerEvents(model.name,model.domNavigation);
		$('mvContainer').appendChild(model.domNavigation);
	}
	/**
	 * Method will build the DIV Object for the Model Overlay representing a specific Model.
	 * @param model ProductModel
	 * @type void
	 * @member CameraNavigationView
	 */
	this.buildModelOverlay = function(model) {
		if(model.domOverlay)
		  return

		var overlayDiv = document.createElement('DIV');
		var overlayHref = document.createElement('A');
		var overlayImg = document.createElement('IMG');
	
		overlayDiv.className = 'mvOverLay';
	
		// browser conflict
		if(document.all)	
		  overlayDiv.onmouseout = function() { event.cancelBubble = true;navigationManager.hideNavigationWithTimeOut(event)};
		else
		  overlayDiv.onmouseout = function(event) {event.cancelBubble = true;navigationManager.hideNavigationWithTimeOut(event)};
	
		overlayDiv.onmouseover = function() {navigationManager.clearTimeOut()};

		overlayHref.href = model.domHotSpot.parentNode.href;
	   overlayHref.target = model.domHotSpot.parentNode.getAttribute('TARGET');

	   var imagepath = model.domHotSpot.src.split('cameraNav');
		overlayImg.src =  rootFolder  + 'images/menu/modelo_' + model.id + "Over.gif";
		
		overlayImg.style.display = "block";
		//overlayImg.width = "";

		//alert(overlayImg.src+" "+overlayImg.width);
		overlayImg.alt = model.name;
		
		overlayHref.appendChild(overlayImg);
		overlayDiv.appendChild(overlayHref);
	
		model.domOverlay = overlayDiv;
		$('mvContainer').appendChild(model.domOverlay);  
	}
	/**
	 * Method will build the DIV Object Navigation representing a specific Model.
	 * @param model ProductModel
	 * @type void
	 * @member CameraNavigationView
	 */
	this.buildCategoryNavigation = function(category) {
		if(category.domNavigation)
		  return
	   
		var categoryDiv = document.createElement('DIV');
		categoryDiv.id = 'mvCat_' + category.name;
		categoryDiv.className = 'mvNavigationCategory';
	    
	    for(var i=0; i<category.models.length; i++) {    	
	  	// Build Model Navigation if needed
		  	if(!category.models[i].domNavigation) {
		  	  this.buildModelNavigation(category.models[i],category.models[i].href);
		  	  
		  	}
		
		  	var cloneDiv = category.models[i].domNavigation.cloneNode(true);
		  	
		  	cloneDiv.id = category.name + '_' + cloneDiv.id;
		  	cloneDiv.className = 'mvNavigationModelForCategory';
		  	cloneDiv.style.display = 'block';
		
			//this._addLegalDisclaimerEvents(category.models[i].name,cloneDiv);

		  	if(i>0) {
		        var catDivider = document.createElement('DIV');
		        var catDividerImg = document.createElement('IMG');
		        
		      catDivider.className = 'mvNavigationCategoryDivider';	        
		      catDividerImg.src = IMG_ROOT + 'spacer.gif'
		        
		  	  catDivider.appendChild(catDividerImg);
		  	  categoryDiv.appendChild(catDivider)
		  	}
		  	categoryDiv.appendChild(cloneDiv);
	  }
	  category.domNavigation = categoryDiv;
	  $('mvContainer').appendChild(categoryDiv);
	}
	/**
	 * Method will build the DIV Object for the Model Overlay representing a specific Model.
	 * @param model ProductModel
	 * @type void
	 * @member CameraNavigationView
	 */
	this.buildCategoryOverlay = function(category) {
	  if(category.domOverlay)
	    return

	  var overlayDiv = $('mvCategoryOverLay_Template').cloneNode(true);
	  var divs = overlayDiv.getElementsByTagName('DIV');
	  var topDiv = divs[0];
	  
	
	  overlayDiv.id = 'overlayDiv' + category.id;
	
	  // Create Category Overlay Image Example: 'cn_ESOn.gif'
	  var imgTopDiv = ($NL(topDiv.childNodes)).firstElement();
	  var pieces = imgTopDiv.src.split('#');
	  imgTopDiv.src = this._replaceCategory(pieces[pieces.length - 1], category.id);
     imgTopDiv.alt = category.name;
	  //Need to calc cached images width;
	  var imgWidth = new Image();
	  imgWidth.src = imgTopDiv.src;
	  // Have to set a width in IE
	  if(document.all)
			overlayDiv.style.width = imgWidth.width;
	  	
	    
	    
	  category.domOverlay = overlayDiv;
	  $('mvContainer').appendChild(category.domOverlay);
	}
	this._addLegalDisclaimerEvents = function(modelId, div) {
		var featureDivs = document.getElementsByClassName('mvNavigationFeatures', div, 'DIV');
		var priceDiv = document.getElementsByClassName('mvNavigationPrice', div, 'DIV')[0];
		
		for(var x=0; x<featureDivs.length; x++) {
			var featureDiv  = featureDivs[x];
			
			var disclaimers = featureDiv.getElementsByTagName('A');
			
			for(var x=0; x<disclaimers.length; x++) {
				var disclaimer = disclaimers[x];
				
				disclaimer.href = 'javascript:void(0);'
				
				// If we are on a vendor site
				if(window.LEXUS_ROOT_URL) {
					disclaimer.onclick = function() {navigationManager.launchDisclaimerPopup(this);}.bind(modelId);
				}
				// else we must be on www.lexus.com
				else {
					disclaimer.onclick = function() {navigationManager.launchDisclaimer(this);}.bind(modelId);
				}
			}
		}
		
		var hrefs = priceDiv.getElementsByTagName('A'); 
		var disclaimer;
		if(hrefs.length > 0) {
			disclaimer = hrefs[0];
		}
		else {
			disclaimer = document.createElement('A');
			disclaimer.href = '#_1';
			disclaimer.className = 'link_disclaim';
			disclaimer.innerHTML = '[1]';
			priceDiv.appendChild(disclaimer);
		}		
		// Add diclaimer about price 
		// If we are on a vendor site
		if(window.LEXUS_ROOT_URL) {
			disclaimer.onclick = function() {navigationManager.launchDisclaimerPopup(this);}.bind(modelId);
		}
		// else we must be on www.lexus.com
		else {
			disclaimer.onclick = function() {navigationManager.launchDisclaimer(this);}.bind(modelId);
		} 		
		
	}
	/**
	 * Method replaces all ~model~ wildcards with actual model name
	 */
	this._replaceModel = function(str, name) {
	  return str.templateReplace(this.MODEL_REPLACE, name);	
	}
	this._replaceModelCode = function(str, name) {
		return str.templateReplace(this.MODEL_CODE_REPLACE, name);	
	}
	this._replaceModelLink = function(str, name, code) {
	  str = str.replace('about:blank','');
	  str = str.replace('javascript:void(0);', '');
	  str = this._replaceModel(str, name);
	  //str = this._replaceModelCode(str, code);
	  return str;
	}
	this._replaceModelLink2 = function(str, name, code, modelHref) {
		str = str.replace('about:blank','');
	  str = str.replace('javascript:void(0);', '');
	  str = modelHref;
	  //str = this._replaceModelCode(str, code);
	  return str;
	}
	/**
	 * Method replaces all ~category~ wildcards with actual category name
	 */
	this._replaceCategory = function(str, cat) {
	  return str.templateReplace(this.CATEGORY_REPLACE, cat);	
	}
}


var Dom = function() {
	
	
};
/**
  * Static Method finds the left most X-axis coordinate of the given object.
  * @param {Object} Object or String id of the DOM desired
  * @param topNode Object or String id to declare the top node to traverse too.
  * measurment will include the topNode
  * @return int - X-axis coordinate
  * @member Dom
  */  
Dom.getLeftX = function(id, topNode) {
	var obj = $(id);
	topNode = (topNode) ? $(topNode) : topNode;
  var curleft = 0;
  
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
			if(topNode && obj == topNode)
			  break;
		}
	} else if (obj.x)
		curleft += obj.x;
	return curleft;
}
Dom.getLeftXAsPx = function(id, topNode) {
	return Dom.getLeftX(id, topNode) + "px";
}
/**
 * Static Method finds the right most X-axis coordinate of the given object.
 * @param {Object} id Object or Id of the DOM desired
 * @param topNode Object or String id to declare the top node to traverse too.
 * measurment will include the topNode
 * @return int - X-axis coordinate
 * @member Dom
 */
Dom.getRightX = function(id, topNode) {
	var obj = $(id);
  
  return Dom.getLeftX(obj, topNode) + obj.offsetWidth;
}
Dom.getRightXAsPx = function(id,topNode) {
	return Dom.getRightX(id,topNode) + "px";
}
 /**
 * Static Method finds the bottom most Y-axis coordinate of the given object.
 * @param {Object} Object or String id of the DOM desired
 * @param topNode Object or String id to declare the top node to traverse too.
 * measurment will include the topNode
 * @return int - Y-axis coordinate
 * @member Dom
 */ 
Dom.getBottomY = function(id,topNode) {
	var obj = $(id);
	  
	return Dom.getTopY(obj,topNode) + obj.offsetHeight;
}
Dom.getBottomYAsPx = function(id,topNode) {
	return Dom.getBottomY(id,topNode) + "px";
}
 /**
 * Static Method finds the top most Y-axis coordinate of the given object.
 * @param {Object} Object or String id of the DOM desired
 * @param topNode Object or String id to declare the top node to traverse too.
 * measurment will include the topNode
 * @return int - Y-axis coordinate
 * @member Dom
 */ 
Dom.getTopY = function(id,topNode) {
	var obj = $(id);
	topNode = $(topNode)
	var curtop = 0;
	var index = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			index++;
			curtop += obj.offsetTop		  
			obj = obj.offsetParent;
			if(topNode && obj == topNode)
			  break;
		}
	} else if (obj.y)
	curtop += obj.y;
	return curtop;
}
Dom.getTopYAsPx = function(id,topNode) {
	return Dom.getTopY(id,topNode) + "px";
}
/**
 * Static Method finds the Left, Right, Top, Bottom positions of a certain object
 * and returns an object with 4 properties: <br />
 * .leftX <br />
 * .rightX <br />
 * .topY <br />
 * .bottomY <br />
 * @param {Object} id Object or String id of the DOM desired
 * @param topNode Object or String id to declare the top node to traverse too.
 * measurment will include the topNode
 * @return Object - with 4 properties .leftX, .rightX, .topY, bottomY
 * @member Dom
 */
Dom.getBoundries = function(id,topNode) {

	 var boundries = {
		leftX:   Dom.getLeftX(id,topNode),
		rightX:  Dom.getRightX(id,topNode),
		topY:    Dom.getTopY(id,topNode),
		bottomY: Dom.getBottomY(id,topNode),
		width: Dom.getRightX(id,topNode) - Dom.getLeftX(id,topNode),
		height: Dom.getBottomY(id,topNode) - Dom.getTopY(id,topNode)		
	}
	return boundries;	
}
Dom.isInBounds = function(id, x, y) {
	var rectangle = Dom.getBoundries(id);
	
	if(x<=rectangle.leftX || x>=rectangle.rightX)
	  return false;
	if(y<=rectangle.topY || y>=rectangle.bottomY)
	  return false;
	
	return true;
}


/**
 * Class acts as the controller to handle all interaction of the navigation bar<br/>
 * @constructor
 */
function CameraNavigationManager() 
{
	this.categories = $A();
	this.navState = new CameraNavigationState();
	this.navView = new CameraNavigationView();
	this.timeOutId;
	this.timeOutSet = false;
	this.ajaxQueue;
	this.imageCache = new Array();
	
	this.backdrop;	

	/**
	 * Method will be called on instantiation of this class.
	 * Exact features are TBD
	 * @member CameraNavigationManager
	 */
	this.init = function() 
	{
		this._setOnState();	
		// Add onload event
	 	onPageLoadEvents.addAction(this.init_onload.bindAsEventListener(this));
	 	Event.observe(window, 'unload', Event.unloadCache);
	}
	
	this.init_onload = function() 
	{
		this._setupNavigation();
		this._cacheMenuImages();
		this._preLoadMenus();  
	}
	/**
   * Method adds a Category Object to an array.   
   * @param model - Category Category Object representing a Lexus Category
   * @type void
   * @member CameraNavigationManager
   */
	this.addCategory = function(category) 
	{
		this.categories.push(category);
	}
  /**
   * Method returns a Category Object from the current array.
   * @param model - Category Category Object representing a Lexus Category
   * @type void
   * @member CameraNavigationManager
   */
	this.getCategory = function(key) 
	{
		return this.categories.find(function(category)
  		{
  			if(category.id == null)return;
			if(category.id.indexOf(key.toUpperCase()) >= 0) 
  			{
  				return category;
  			}
  		}
  		)
	}	
  /**
   * Function will control the action of showing a Model or Category Vehicle Navigation Item
   * @param domObject Dom Element
   * @param categoryId String 
   * @param modelId String
   * @type void
   * @member CameraNavigationManager
   */
	
	this.showNavigation = function (domObject, categoryId, modelId, modelHref) 
	{
		//alert(categoryId);
		
		var dataObject = this._getDataObject(categoryId, modelId);
		
		if(dataObject == null)return;
		if(this.timeoutSet) 
		{
  			clearTimeout(this.timeoutId);
  			this.timeoutSet = false;
  		}
		this.closeDisclaimer();
	
		// attach Dom Hot Spot if not already done.
		if(!dataObject.domHotSpot)dataObject.domHotSpot = domObject;

  	  	if(this.navState.isNavShowing()) 
  	  	{
			if(this.navState.getCurrentActive() == dataObject)return;
  	  		else this.hideNavigation();
  		}
  		// Hide all flash objects in safari
  		hideElementsForOverlays();
  		if(dataObject.type == ProductCategory.type) 
  		{
  			this._showCategoryNavigation(dataObject);
  		}
  		else 
  		{
	  		/*
	  		 * IE needs to have an expliced hide on the body to make sure
	  		 * the navigation actually hides when you roll off the menu
	  		 */
	  		if(document.all)
			Event.observe(document.body, 'mouseout', ieBodyhideNavigation, true);
			this._showModelNavigation(dataObject,modelHref);
  		}
  	}
  /**
   * Method will control the action to hide a Model or Category Vehicle Navigation Item.
   * @param eventObject Event
   * @type void
   * @member CameraNavigationManager
   */

	this.hideNavigation = function (eventObject) 
	{
  		var currentActive = this.navState.getCurrentActive();
	  	// Only Hide if its ok
  		if(!this._shouldWeHideNavigation(eventObject))return;
    
    	var wrapper = $('wrapper');
    
		// Hide Navigation
		currentActive.domNavigation.style.display = 'none';
		currentActive.domOverlay.style.display = 'none';
    
		/* 
		* Removed from the actual DOM because IE has issues displaying if we dont remove,
		* since these elements could be cloned.
		*/
		wrapper.removeChild(currentActive.domNavigation);
		wrapper.removeChild(currentActive.domOverlay);    
		/*
		* Removed IE specific body event
		* 
		*/
		if(document.all)
			Event.stopObserving(document.body, 'mouseout', ieBodyhideNavigation, true);
		this.navState.setNavShowing(false);
		
		// Show all flash objects in safari
		showElementsForOverlays();
	}
	/**
	* Method will activate a timer and execute hideNavigation().
	* @member CameraNavigationManager
	*/
	this.hideNavigationWithTimeOut = function(eventObject) 
	{
		if(this.timeoutSet)return;
		// Only Hide if its ok
		if(!this._shouldWeHideNavigation(eventObject))return;
	
		this.timeoutId = setTimeout("navigationManager.hideNavigation()",menuTimeout);
		this.timeoutSet = true;
	}
	/**
	* Method will figure out wether or not to hide the current openned navigation
	* @member CameraNavigationManager
	*/
	this._shouldWeHideNavigation = function (eventObject) 
	{
		var currentActive = this.navState.getCurrentActive();
	
		// Nothing to do if we dont have a nav showing
		if(!currentActive || !currentActive.domNavigation || !currentActive.domOverlay)return false; 	
		// If in bounds, do nothing
		if(this.isEventInBounds(currentActive.domOverlay, eventObject) || this.isEventInBounds(currentActive.domNavigation, eventObject))return false;
		return true;
	}
	/**
	* Method clears the current hideNavigation timeout setting if there is one.
	* @member CameraNavigationManager
	*/
	this.clearTimeOut = function() 
	{
		if(this.timeoutSet) 
		{
			clearTimeout(this.timeoutId);
			this.timeoutSet = false;
		}
	}
	/**
	* Method will handle the specific task to show a Category Navigation Item
	* @param category ProductCategory
	* @type void 
	* @member CameraNavigationManager
	*/
	this._showCategoryNavigation = function(category) 
	{
		var status = this.navView.showCategoryNavigation(category);
		this.navState.setCurrentActive(category);
	}
	/**
	* Method will handle the specific task to show a Model Navigation Item
	* @param category ProductCategory
	* @type void 
	* @member CameraNavigationManager
	*/
	this._showModelNavigation = function(model,modelHref) 
	{
		var status = this.navView.showModelNavigation(model,modelHref);
		this.navState.setCurrentActive(model);
	}
	/**
	* Method figures out if the cursor of the given Event is within the given DOM Element
	* @param domObject DOMElement 
	* @param eventObject Event
	* @type void 
	* @member CameraNavigationManager
	*/
	this.isEventInBounds = function(domObject, eventObject) 
	{	
		if(!eventObject)
		return false;
		return Dom.isInBounds(domObject,Event.pointerX(eventObject), Event.pointerY(eventObject));
	}
	/**
	* Method pre caches all menu images
	* @type void 
	* @member CameraNavigationManager
	*/  
	this._cacheMenuImages = function() 
	{
		for(var x=0; x<this.categories.length; x++) 
		{
			var category = this.categories[x];
			// Cache Model Navigation Images
			for(var i=0; i<category.models.length; i++) 
			{
				var model = category.models[i];
				this._cacheModelNavigationImages(model.id);	  
			}
		}
	}
	/**
	* Method returns either a Category or a Model object based on if a model is passed in.
	* @param category String
	* @param model String (optional)
	* @type ProductCategory/ProductModel
	* @member CameraNavigationManager
	*/
	this._getDataObject = function(category, model) 
	{
		var dataObject;
		if(!model)
			dataObject = this._getCategoryObject(category);
		else
			dataObject = this._getModelObject(category, model);
		return dataObject;
	}
	/**
	* Method returns either a Category object based on the id passed in
	* @param categoryId String
	* @type ProductCategory
	* @member CameraNavigationManager
	*/
	this._getCategoryObject = function(categoryId) 
	{ 
		return this.getCategory(categoryId);
	}
	/**
	* Method returns either a Model object based on the id passed in
	* @param modelId String
	* @type Model
	* @member CameraNavigationManager
	*/
	this._getModelObject = function(categoryId, modelId) 
	{
		var category = this.getCategory(categoryId);
		return category.getModel(modelId);
	}
	
	this._setOnState = function() 
	{
		if(typeof( window[ 'MODEL_ID' ] ) != "undefined") 
		{      
			var onStateImg;
			// Check if the current page we are on is a model
			for(var i=0; i<this.categories.length; i++) 
			{
				var category = this.categories[i];
				for(var x=0; x<category.models.length; x++) 
				{
					var model = category.models[x];
					// Determine if we are on this current Model, change image to 'On' state, and cache image
					if(MODEL_ID.toLowerCase() == model.id.toLowerCase()) 
					{
	 					onStateImg = $( [model.categoryId.toLowerCase(), '_' , model.id.toLowerCase()].join('') );
						break;
					}
				}
			}
	
			// If we are not on a Model, look if we are on a misc Link
			if(!onStateImg) 
			{
					onStateImg = $( ['mv', MODEL_ID].join('') );
			}
			if(onStateImg) 
			{
				onStateImg.src = onStateImg.src.replace('.gif', 'On.gif');
				this._cacheImage(onStateImg.src);
			}
		}
	}
	/**
	* Method executes the preliminary setup of the navigation bar. 
	* Including: caching of all images and rollovers, and all needed
	* events.
	* @member CameraNavigationManager
	*/
	this._setupNavigation = function() 
	{  
		var mvCategoryContainers = document.getElementsByClassName('mvCategoryContainer');
		var mvMiscLinkContainers = document.getElementsByClassName('mvMiscLinkContainer');
	
		// Category and Model: Add Events and cache all images
		for(var i=0; i<mvCategoryContainers.length; i++) 
		{
			var mvCategoryContainer = mvCategoryContainers[i];
		
			var mvCategory = $A(document.getElementsByClassName('mvCategory',mvCategoryContainer));
			var mvModels = $A(document.getElementsByClassName('mvModels',mvCategoryContainer));
	
			if(mvCategory != '') 
			{
				this._setupCategory(mvCategory[0]);
			}
			if(mvModels != '') 
			{
				this._setupModels(mvModels[0]);
			}
		}
	
		// Misc Links: Add Events and cache all images
		for(var i=0; i<mvMiscLinkContainers.length; i++) 
		{
			var miscDivs = ($NL(mvMiscLinkContainers[i].childNodes)).elements();
	
			for(var x=0; x<miscDivs.length; x++) 
			{
				var miscDiv = miscDivs[x];
				var href = ($NL(miscDiv.childNodes)).firstElement();
				var img = ($NL(href.childNodes)).firstElement();
	
				this._cacheOnOverImages(img.src);
				// Cache Images
				//this._cacheImage(img.src);
				
				// Cache Over State
				var overImgSrc = img.src.replace('On.gif', '.gif');
				this._cacheImage(overImgSrc.replace('.gif', 'Over.gif'));
				// Events
				if(img.src.indexOf('On.gif') == -1) 
				{
					Event.observe(img, 'mouseout', function() {swapOver(this);}.bind(img), false);
					Event.observe(img, 'mouseover', function() {swapOver(this);}.bind(img), false);
				}
			}
		}
	}
	/**
	* Method prebuild category overlays.
	* @member CameraNavigationManager
	*/
	this._preLoadMenus = function() 
	{  	
		this.categories.each(function(category)
		{ 
			this.navView.buildCategoryOverlay(category); 	  
		}.bind(this));
	}
	/**
	* Method managers the caching of all navigation category images and
	* adds swapOver and showNavigation events to the category position of the 
	* Navigtaion bar.
	* @member CameraNavigationManager
	*/
	this._setupCategory = function(mvCategory) 
	{ 
		// Find Category Image and Cache
		if(mvCategory.parentNode.childNodes.length == 1)return;
		var categoryImg = ($NL(mvCategory.childNodes)).firstElement();
	
		if(categoryImg.tagName == "A")
			categoryImg = categoryImg.firstChild;
		
		this._cacheOverImage(categoryImg.src);
	
		// Add Events to Category
		Event.observe(categoryImg, 'mouseover', function() {swapOver(categoryImg);this.hideNavigation()}.bindAsEventListener(this), false);
		Event.observe(categoryImg, 'mouseout', function() {swapOut(categoryImg);}, false);
		Event.observe(categoryImg, 'click', function() {swapOut(categoryImg);this.showNavigation(categoryImg, categoryImg.id)}.bindAsEventListener(this), false);   
	}
	
	this._cacheOverImage = function(src) 
	{
		var overImgSrc = src.replace('On.gif', '.gif');
		this._cacheImage(overImgSrc.replace('.gif', 'Over.gif'));
	}

	this._cacheOnOverImages = function(src) 
	{
		this._cacheImage(src);
		this._cacheOverImage(src)        
	}
	/**
	* Method caches image in browser.
	* @member CameraNavigationManager
	*/
	this._cacheImage = function(src) 
	{
		// Check if we are a third party navigation and we dont have a full url
		var newImage = new Image();
		var d = new Date();
		var url = src //+ "?" + d.getTime();

		newImage.src = src;
				
		//alert(url+" "+newImage.width);
		this.imageCache.push(newImage);
		//alert(this.imageCache[this.imageCache.length-1].src+"\n"+this.imageCache[this.imageCache.length-1].width);
		
	}
	/**
	* Method handels the setup of all Navigation model images and
	* addes showNavigation to a mouseover event on each model.
	* @member CameraNavigationManager
	*/
	this._setupModels = function(mvModel) 
	{
		var modelLinks = ($NL(mvModel.childNodes)).elements();
	
		// Loop through each Model, cache and apply needed events
		modelLinks.each(function(modelLink) 
		{
			var modelImg = modelLink.firstChild;
			var ids = modelImg.id.split('_');
			var catId = ids[0];
			var modId = ids[1];

			// Cache Model Image and Overlay
			//alert(modelImg.src);
			this._cacheOverImage(modelImg.src);
	
			// Add Events to Model
			Event.observe(modelImg, 'mouseover', function() {this.showNavigation(modelImg, catId, modId, modelLink.href)}.bindAsEventListener(this), false);
		}.bind(this)); 	 
	}
	/**
	* Method controls the caching of all Navigation Menu Model images.
	* @member CameraNavigationManager
	*/
	this._cacheModelNavigationImages = function(modelName) 
	{
		this._cacheImage(this.navView._replaceModel(this.navView.IMG_HEAD,modelName));
		this._cacheImage(this.navView._replaceModel(this.navView.IMG_PHOTO,modelName));
	}
	this.launchDisclaimer = function(modelName) 
	{
		this.hideNavigation();
		this.closeDisclaimer();
	
		hideElementsForOverlays();
		this.showDisclaimerWrap();
	
		this.ajaxQueue = new Ajax.Queue(Ajax.Queue.FIFO, true);
		this.ajaxQueue.addAction(new Ajax.Updater(document.body,	GalleryUtils.buildAjaxUrl(['/camaras-compartido/includes/models/legal_disclaimers_template.incl']),
			{
	    		method: 'get',
	     		insertion: Insertion.Bottom,
	     		onComplete: function() {this.prepareContent()}.bind(this),
	 			wait: true
			}))
		this.ajaxQueue.addAction(new Ajax.Updater('legalDisclaimerHolder',GalleryUtils.buildAjaxUrl(['/camaras-compartido/includes/models/legal_disclaimers_' + modelName + '.incl']),
			{
	    		method: 'get',
	     		insertion: Insertion.Bottom,
	     		onComplete: this.setupLegalDisclaimerScroll,
	 			wait: true
			}))
		this.ajaxQueue.start();
	}
	
	this.launchDisclaimerPopup = function(modelName) 
	{
		this.hideNavigation();
	
		var windowWidth = (document.all) ? document.body.offsetWidth : window.innerWidth;
		var windowHeight = (document.all) ? document.body.offsetHeight : window.innerHeight;
	
		var left = Math.round( (windowWidth - 804) / 2 );
		var top =  Math.round( (windowHeight - 620) / 2 );
	
		this.closeDisclaimer();
	
		legalDisclaimerWindow  = window.open(LEXUS_ROOT_URL + '/camaras-compartido/includes/models/legal_disclaimer_vendor.html?model='+modelName,'legalDisclaimerWindow','width=' 
													+ 774 + ',height=' + 425
													+ ',menubar=no,location=no,resizable=no,scrollbars=no,status=no,left=' + left + 'px,top=' + top + 'px');
		legalDisclaimerWindow.focus();	
	
		// We have to add these events without prototype, since prototype might not
		// be loaded at this point
		if (window.addEventListener) 
		{
			window.addEventListener('unload', this.closeDisclaimer.bind(this), null);
		} 
		else if (window.attachEvent) 
		{
			window.attachEvent('on' + 'unload', this.closeDisclaimer.bind(this));
		}
	}
	
	this.prepareContent = function() 
	{
		$('legalClose').onclick = function() {this.closeDisclaimer()}.bind(this);
	
	}
	
	this.closeDisclaimer = function() 
	{
		if($('legalDisclaimerContainer')) 
		{
			$('legalDisclaimerContainer').parentNode.removeChild($('legalDisclaimerContainer'));
			this.hideDisclaimerWrap();
			showElementsForOverlays();
		}
		else if(window.legalDisclaimerWindow && !window.legalDisclaimerWindow.closed) 
		{
			legalDisclaimerWindow.close();
			legalDisclaimerWindow = null;
		}
	}
	
	this.setupLegalDisclaimerScroll = function() 
	{
		var scrollObj = new dw_scrollObj('legalClippingLayer', 'legalDisclaimerHolder', null);
	
		// arguments: dragBar id, track id, axis ("v" or "h"), x offset, y offset
		// (x/y offsets of dragBar in track)
		scrollObj.setUpScrollbar("legalDragBar", "legalTrack", "v", 0, 0);
	}
	
	this.showDisclaimerWrap = function() 
	{
		if(!this.backdrop) 
		{
			this.backdrop = new Backdrop('disclaimerWrap','galleryWrap');
			this.backdrop.observe('click', this.closeDisclaimer.bind(this), false);
		}
		this.backdrop.enable();
	}
	
	this.hideDisclaimerWrap = function() 
	{
		if(this.backdrop) 
		{
			this.backdrop.disable();
		}
	}
}


function CameraNavigationState () {
	this._navShowing = false;
	this._categoryShowing = false;
	this._modelShowing = false;
	this._currentActive = null;

	/**
	 * @member CameraNavigationState
	 * Method sets the current state of the navigation.
	 * If false, method will also update categoryShowing and modelShowing attributes
	 * @param boolean - state True/False 
	 */
	this.setNavShowing = function (state) {
		this._navShowing = state;
		
		// update dependencies if false
		if(!state) {
			this.setCategoryShowing(false);
			this.setModelShowing(false);
			this.setCurrentActive(null);
		}
	}
	/**
	 * 
	 * Method sets categoryShowing attribute, to indicate if a Category Navigation is current visible.
	 * If True, will also set _navShowing to true and will set _modelShowing to false, since only a
	 * model or category can be shown at any point.
	 * @param boolean - state True/False 
	 * @member CameraNavigationState
	 */
	this.setCategoryShowing = function (state) {
		this._categoryShowing = state;
		
		// update dependencies if true
		if(state) {
			this.setNavShowing(true);
			this.setModelShowing(false);
		}
	}
	/**
	 * Method sets modelShowing attribute, to indicate if a Model Navigation is current visible.
	 * If True, will also set _navShowing to true and will set _categoryShowing to false, since only a
	 * model or category can be shown at any point.
	 * @param boolean - state True/False 
	 * @member CameraNavigationState
	 */
	this.setModelShowing = function (state) {
		this._modelShowing = state;
		
		// update dependencies if true
		if(state) {
			this.setNavShowing(true);
			this.setCategoryShowing(false);
		}
	}
  /**
	 * Method sets the current object that is active on the vehicle navigation
	 * @param object - Category or Model Object
	 * @member CameraNavigationState
	 */
	this.setCurrentActive = function(object) {
		this._currentActive = object;
		
		if(!object)
		  return;
	  if(object.type == ProductCategory.type) {
	  	this.setCategoryShowing(true);	  	
	  }
	  else {
	  	this.setModelShowing(true);	  	
	  }
	}
  /**
	 * Method gets the current object that is active on the vehicle navigation
	 * @type object - Category or Model Object
	 * @member CameraNavigationState
	 */
	this.getCurrentActive = function() {
		return this._currentActive;		
	}
	/**
	 * Method returns true/false depending on if a vehicle navigation is current showing
	 * @type boolean
	 * @member CameraNavigationState
	 */
	this.isNavShowing = function() {
		return this._navShowing;
	}
	/**
	 * Method returns true/false depending on if a vehicle Category navigation is current showing
	 * @type boolean
	 * @member CameraNavigationState
	 */
	this.isCategoryShowing = function() {
		return this._categoryShowing;
	}
	/**
	 * Method returns true/false depending on if a vehicle model navigation is current showing
	 * @type boolean
	 * @member CameraNavigationState
	 */
	this.isModelShowing = function() {
		return this._modelShowing;
	}
}
/*******************************************************************************/

function ieBodyhideNavigation() {	
	navigationManager.hideNavigationWithTimeOut();
}

function ProductCategory(id, name) {
	this.id = id;
	this.name = name;
	this.models = $A();
	this.domHotSpot = null;
	this.domNavigation = null;
	this.domOverlay = null;

  /**
   * Method adds a ProductModel Object to an array.   
   * @param model ProductModel Model Object representing a Lexus Model
   * @type void
   * @member ProductCategory
   */
  this.addModel = function(model) {
  	  model.categoryId = this.id;
    	this.models.push(model);
  }
   /**
   * Method returns a ProductModel Object from the current array. 
   * @param model ProductModel Model Object representing a Lexus Model
   * @type ProductModel
   * @member ProductCategory
   */
  this.getModel = function(key) {
  	return this.models.find(function(model){
  		if(model.id.indexOf(key) >= 0)
  		  return model;
  	})
  }
}
ProductCategory.prototype.toString = function() {
	return "Category (Object)";
}
/** Type Declarations Class/Instance **/
ProductCategory.type = 'Category';
ProductCategory.prototype.type = 'Category';

function ProductModel(id, name, href, endingPrice,code) {
	this.id = id.toLowerCase();
	this.name = name;
	this.href = href;
	this.endingPrice = endingPrice;
	this.code = code;
	this.categoryId = 0;
	this.features = $A();
	this.domHotSpot = null;
	this.domNavigation = null;
	this.domOverlay = null;
	
	/**
   * Method adds a VehicleFeature Object to an array.
   * @param feature VehicleFeature VehicleFeature Object representing a Lexus Model Feature
   * @type void
   * @member ProductModel
   */
	this.addFeature = function(feature) {
		this.features.push(feature);
	}
	/**
	 * Method returns a string representing the price of the Lexus Model
	 * @type String
	 * @member ProductModel
	 */
	this.getPriceAsString = function() {
		return "Starting at " + this.startingPrice + 
		       ((this.endingPrice) ? " - " + this.endingPrice : "" ) + ' ';
	}
}

ProductModel.prototype.toString = function() {
	return "Model (Object)";
}
/** Type Declarations Class/Instance **/
ProductModel.type = 'Model';
ProductModel.prototype.type = 'Model';

var xmlhttp;
var hasImages = false;
var hasVideos = false;

function CameraModelManager()
{
	this.modelo = null;
	this.xml = null;
	this.xmlFile = null;
	this.rootPath = null;
	this.menuselect = null;
	
	this.init = function()
	{
		var arg = this.init.arguments;
		this.rootPath = (arg[1] != undefined ? arg[1] : './');
		this.xmlFile = (arg[0] != undefined ? arg[0] : 'xml/home.xml');
		this.getModeloXML();
	}
	
	this.getModeloXML = function ()
	{
		getTransporte();
		url = this.rootPath+this.xmlFile;
		if (xmlhttp!=null)
		{
			xmlhttp.open("GET",url,true);
			xmlhttp.onreadystatechange = this.state_change;
			xmlhttp.send(null);
		}
		else
		{
			alert("Your browser does not support XMLHTTP.")
		}
	}
	
	this.state_change = function()
	{
		if (xmlhttp.readyState == 4) 
		{
			if (xmlhttp.status == 200)
			{
				modelManager.xml = xmlhttp.responseXML;
				modelManager.buildModelo();
			}
			else
			{
				alert(xmlhttp.status);
			}
		}
	}
	
	this.buildModelo = function()
	{
		this.buildMenu();
		this.buildItem();
	}
	
	this.buildItem = function()
	{
		var caracteristicas = this.xml.getElementsByTagName('caracteristicas').item(0);
		for(var i = 0; i < caracteristicas.childNodes.length; i++)
		{
			var nodo = caracteristicas.childNodes[i];
			switch (nodo.tagName)
			{
				case 'background_image':
					background[0] = nodo.firstChild.nodeValue;
					var vcArea = $("vcArea");
					vcArea.style.background = '#495677 no-repeat url('+ nodo.firstChild.nodeValue+')';
					break;
				case 'content':
					var content_caracteristicas = $("content_caracteristicas_html");
					content_caracteristicas.innerHTML = nodo.firstChild.nodeValue;
			}
		}
		var imagenesvideos = this.xml.getElementsByTagName('imagenesvideos').item(0);
		for(var i = 0; i < imagenesvideos.childNodes.length; i++)
		{
			var nodo = imagenesvideos.childNodes[i];
			switch (nodo.tagName)
			{
				case 'background_image':
					background[1] = nodo.firstChild.nodeValue;
					break;
				case 'content':
					var content_imagenesvideos = $("content_imagenesvideos_html");
					content_imagenesvideos.innerHTML = nodo.firstChild.nodeValue;
				case 'imagenes':
					hasImages = true;
					break;
				case 'videos':
					hasVideos = true;
					break;
				case 'gallery_header_image':
					var gallery_header_image = $("gallery_header_image");
					gallery_header_image.src = nodo.firstChild.nodeValue;
					gallery_header_image.align = "left";
					break;
			}
		}
		var pdf = this.xml.getElementsByTagName('pdf').item(0);
		for(var i = 0; i < pdf.childNodes.length; i++)
		{
			var nodo = pdf.childNodes[i];
			switch (nodo.tagName)
			{
				case 'background_image':
					background[2] = nodo.firstChild.nodeValue;
					break;
				case 'content':
					var content_pdf = $("content_pdf_html");
					content_pdf.innerHTML = nodo.firstChild.nodeValue;
					break;
				case 'pdf_header_image':
					var pdf_header_image = $("pdf_header_image");
					pdf_header_image.src = nodo.firstChild.nodeValue;
					pdf_header_image.align = "left";
					break;

			}
		}
		var aplicaciones = this.xml.getElementsByTagName('aplicaciones').item(0);
		for(var i = 0; i < aplicaciones.childNodes.length; i++)
		{
			var nodo = aplicaciones.childNodes[i];
			switch (nodo.tagName)
			{
				case 'background_image':
					background[3] = nodo.firstChild.nodeValue;
					break;
				case 'content':
					var content_aplicaciones = $("content_aplicaciones_html");
					content_aplicaciones.innerHTML = nodo.firstChild.nodeValue;
			}
		}
		var relacionados = this.xml.getElementsByTagName('relacionados').item(0);
		for(var i = 0; i < relacionados.childNodes.length; i++)
		{
			var nodo = relacionados.childNodes[i];
			switch (nodo.tagName)
			{
				case 'background_image':
					background[4] = nodo.firstChild.nodeValue;
					break;
				case 'content':
					var content_relacionados = $("content_relacionados_html");
					content_relacionados.innerHTML = nodo.firstChild.nodeValue;
					break;
			}
		}

	}
	
	
	this.buildMenu = function()
	{
		var menu = this.xml.getElementsByTagName('menu').item(0);
		for(var i = 0; i < menu.childNodes.length; i++)
		{
			var ancho = null;
			var alto = null;
			var texto = null;
			var enlace = null;
			var fuente = null;
			var nodo = menu.childNodes[i];
			var elementos = nodo.childNodes;
			if(elementos.length)
			{
				var contenedor = null;
				for(var j = 0; j < elementos.length; j++)
				{
					var elemento = elementos[j];
					if(elemento.attributes)
					{
						ancho = (elemento.attributes.getNamedItem("width") ? elemento.attributes.getNamedItem("width").value : null);
						alto = (elemento.attributes.getNamedItem("height") ? elemento.attributes.getNamedItem("height").value : null);
						texto = (elemento.attributes.getNamedItem("alt") ? elemento.attributes.getNamedItem("alt").value : null);
						enlace = (elemento.attributes.getNamedItem("href") ? elemento.attributes.getNamedItem("href").value : null);
						fuente = (elemento.attributes.getNamedItem("src") ? elemento.attributes.getNamedItem("src").value : null);
					}
					else
					{
						continue;
					}
					switch (nodo.tagName)
					{
						case 'menu_caracteristicas':
							contenedor = $("menuItems0");
							break;
						case 'menu_imagenesvideos':
							contenedor = $("menuItems1");
							break;
						case 'menu_pdf':
							contenedor = $("menuItems2");
							break;
						case 'menu_aplicaciones':
							contenedor = $("menuItems3");
							break;
						case 'menu_relacionados':
							contenedor = $("menuItems4");
							break;
						case 'header':
							contenedor = $("menu_header");
							break;
						case 'bottom':
							contenedor = $("menu_bottom");
							break;
					}
					contenedor.style.display="block";
					var divObj = document.createElement("DIV");
					var contenido = null;
					if(fuente)
					{
						var contenido = document.createElement("IMG");
						contenido.width = ancho;
						contenido.height = alto;
						contenido.alt = texto;
						contenido.src = fuente;
					}
					else
					{
						divObj.className = "elementos_menuright";
						contenido = document.createElement("SPAN");
						contenido.innerHTML = elemento.firstChild.nodeValue;
					}
					
					if(enlace)
					{
						var aObj = document.createElement("A");
						aObj.href = enlace;
						aObj.appendChild(contenido);
						divObj.appendChild(aObj);
					}
					else
					{
						divObj.appendChild(contenido);
					}
					contenedor.appendChild(divObj);
				}
			}
		}	
		var x=0;
		var item = null;
		var imgs = null;
		var img = null;
		while(item = document.getElementById("menu"+x))
		{
			imgs = item.getElementsByTagName("IMG");
			imgs[0].setAttribute("number",x);
			imgs[0].onmouseover = function () {
				var imgsrc = this.src;
				var imgsrc_over = imgsrc.replace(".png","_ov.png");
				this.src = imgsrc_over;
			}
			imgs[0].onmouseout = function () {
				var imgsrc = this.src;
				var imgsrc_over = imgsrc.replace("_ov.png",".png");
				this.src = imgsrc_over;
			}
			imgs[0].onclick = function() {
				swaptab(this);
			}
			x++;
		}
		x=0;
		while(item = document.getElementById("menutab"+x))
		{
			item.setAttribute("number",x);
			item.onclick = function () {
				swaptab(this);
			}
			imgs = item.getElementsByTagName("IMG");
			if(imgs.length)
			{
				imgs[0].setAttribute("number",x);
				imgs[0].onmouseover = function () {
					var imgsrc = this.src;
					var imgsrc_over = imgsrc.replace(".png","_ov.png");
					this.src = imgsrc_over;
				}
				imgs[0].onmouseout = function () {
					var imgsrc = this.src;
					var imgsrc_over = imgsrc.replace("_ov.png",".png");
					this.src = imgsrc_over;
				}
				imgs[0].onclick = function() {
					swaptab(this);
				}
			}
			x++;
		}
		
	}
}

var background = new Array()

function getTransporte()
{
	try 
	{
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} 
	catch (e) 
	{
		try 
		{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch (E) 
		{
			xmlhttp = false;
		}
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') 
	{
		try 
		{
			xmlhttp = new XMLHttpRequest();
		} 
		catch (e) 
		{
			xmlhttp=false;
		}
	}
	if (!xmlhttp && window.createRequest) 
	{
		try 
		{
			xmlhttp = window.createRequest();
		} 
		catch (e) 
		{
			xmlhttp=false;
		}
	}
}

function SwapImagesVideos()
{
	var img = $('pgMainPhotosGrid');
	var vid = $('pgMainVideosGrid');
	var buttonImages = $('pg_photo');
	var buttonVideos = $('pg_video');
	if(img.style.display == 'block')
	{
		img.style.display = 'none';
		vid.style.display = 'block';
		buttonImages.src = rootFolder+'images/g_tbPhto.gif';
		buttonVideos.src = rootFolder+'images/g_tbVidOn.gif';
	}
	else
	{
		img.style.display = 'block';
		vid.style.display = 'none';
		buttonImages.src = rootFolder+'images/g_tbPhtoOn.gif';
		buttonVideos.src = rootFolder+'images/g_tbVid.gif';
	}
}
	
function swaptab(obj)
{
	var n=0;
	var number = obj.getAttribute("number");
	var vcArea = $("vcArea");
	vcArea.style.background = '#495677 no-repeat url('+ background[number] +')';
	var galleryWrap;
	var galleryContainer;
	while(tab = document.getElementById("content_tab"+n))
	{
		if(number == n)
		{
			tab.style.display = "block";
			if(galleryWrap = document.getElementById("galleryWrap"+n))
			{
				galleryWrap.style.display = "block";
				createGallery();
			}
		}
		else
		{
			tab.style.display = "none";
		}
		n++;
	}
}

function Resize()
{
	if (BrowserDetect.version<7 && BrowserDetect.browser == "Explorer")
	{
		$('galleryWrap1').className="galleryWrapIE";
		$('pdfWrap').className="pdfWrapIE";
	}
	$('galleryWrap1').style.width = document.body.offsetWidth+"px";
	$('pdfWrap').style.width = document.body.offsetWidth+"px";
	$('galleryContainer1').style.margin = "0px 0px 0px "+(document.body.offsetWidth-800)/2+"px";
	$('pdfContainer').style.margin = "0px 0px 0px "+(document.body.offsetWidth-700)/2+"px";
}

function createGallery()
{
	window.onresize = Resize;
	var backdrop_loader = $('backdrop_loader');
	Resize();
	if(!hasImages && !hasVideos)
	{
		backdrop_loader.innerHTML = "EN ESTOS MOMENTOS NO HAY DISPONIBLE CONTENIDO MULTIMEDIA PARA ESTE PRODUCTO";
		setTimeout("cerrarGaleria()",2000);
		return;
	}
	/* Creamos las pestañas si hay galerias de imgenes y videos */
	
	var pestanias = $('pgTabContainer');
	var ulObj = document.createElement("UL");
	
	if(hasImages)
	{
		var liObj = document.createElement("LI");
		var tab = document.createElement("IMG");
		tab.src = rootFolder+"images/g_tbPhtoOn.gif";
		tab.className = "pgTabsOn";
		tab.id = "pg_photo";
		tab.alt = "Fotografias";
		if(hasVideos)
		{
			tab.onclick = function()
			{
				SwapImagesVideos();
			}
		}
		liObj.appendChild(tab);
		ulObj.appendChild(liObj);
	}
	if(hasVideos)
	{
		var liObj = document.createElement("LI");
		var tab = document.createElement("IMG");
		if(hasImages)
		{
			tab.className = "pgTabs";
			tab.src = rootFolder+"images/g_tbVid.gif";
			tab.onclick = function()
			{
				SwapImagesVideos();
			}
		}
		else
		{
			tab.src = rootFolder+"images/g_tbVidOn.gif";
			tab.className = "pgTabsOn";
		}
		tab.id = "pg_video";
		tab.alt = "Videos";
		liObj.appendChild(tab);
		ulObj.appendChild(liObj);
	}
	pestanias.appendChild(ulObj);
	
	var contenido = $('pgMainBodyContainer');
	if(hasImages)
	{
		var divContent = document.createElement("DIV");
		divContent.className = "pgMainPhotos";
		divContent.id = "pgMainPhotosGrid";
		divContent.style.display = "block";
		
		var divBody = document.createElement("DIV");
		divBody.className = "pgBodyGrid";
		divBody.id = "pgBodyGridExt";
		divBody.style.display = "block";
		divBody.style.margin = "5px 0px 0px 0px";
		
		var FlashHTML = AC_FL_RunContent(
  			"codebase" ,"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0",
			"width", "800px", 
			"height", "500px",
			"align", "middle",
			"allowScriptAccess" ,"sameDomain",
			"movie", rootFolder+"galeria?xmlfile="+xmlMain+"&rootFolder="+rootFolder,
			"bgcolor", "#000000",
			"src", rootFolder+"galeria?xmlfile="+xmlMain+"&rootFolder="+rootFolder,
			"quality", "high",
			"allowScriptAccess", "sameDomain",
			"type", "application/x-shockwave-flash" ,
			"pluginspage", "http://www.macromedia.com/go/getflashplayer");

		
		divBody.innerHTML = FlashHTML;
				
		divContent.appendChild(divBody);
		contenido.appendChild(divContent);
	}
	
	if(hasVideos)
	{
		var divContent = document.createElement("DIV");
		divContent.style.width ='780px';
		divContent.className = "pgMainVideos";
		divContent.id = "pgMainVideosGrid";
		if(hasImages)
		{
			divContent.style.display = "none";
		}
		else
		{
			divContent.style.display = "block";
		}
		var divBody = document.createElement("DIV");
		divBody.className = "pgBodyGrid";
		divBody.id = "pgBodyGridExt";
		divBody.style.display = "block";
		divBody.style.margin = "5px 0px 0px 0px";
		
		var myTable = document.createElement("TABLE");
		myTable.width="100%";
		var myTableBody = document.createElement("TBODY");
	  	var row = document.createElement("TR");
     	var cell_1 = document.createElement("TD");
     	cell_1.valign="top";
     	var cell_2 = document.createElement("TD");
     	cell_1.valign="top";
		
		var spanLoader = document.createElement("DIV");
		
	
		
		var FlashHTML = AC_FL_RunContent(
  			"codebase" ,"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0",
			"width", "150px", 
			"height", "450px",
			"align", "middle",
			"allowScriptAccess" ,"sameDomain",
			"movie", rootFolder+"galeriaVideos?xmlfile="+xmlMain+"&rootFolder="+rootFolder,
			"bgcolor", "#000000",
			"src", rootFolder+"galeriaVideos?xmlfile="+xmlMain+"&rootFolder="+rootFolder,
			"quality", "high",
			"allowScriptAccess", "sameDomain",
			"type", "application/x-shockwave-flash" ,
			"pluginspage", "http://www.macromedia.com/go/getflashplayer");
		spanLoader.innerHTML = FlashHTML;
		cell_1.appendChild(spanLoader);
    	row.appendChild(cell_1);
	
		var spanPlayer = document.createElement("DIV");
		
		FlashHTML = AC_FL_RunContent(
  			"codebase" ,"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0",
			"width", "450px", 
			"height", "370px",
			"align", "middle",
			"allowScriptAccess" ,"sameDomain",
			"name","playflv",
			"id","playflv",
			"movie", rootFolder+"playflv",
			"bgcolor", "#000000",
			"src", rootFolder+"playflv",
			"quality", "high",
			"allowScriptAccess", "sameDomain",
			"type", "application/x-shockwave-flash" ,
			"pluginspage", "http://www.macromedia.com/go/getflashplayer");
		
		spanPlayer.innerHTML = FlashHTML;
		cell_2.appendChild(spanPlayer);
    	row.appendChild(cell_2);
		
    	myTableBody.appendChild(row);
		myTable.appendChild(myTableBody);
		divBody.appendChild(myTable);
		

		divContent.appendChild(divBody);
		contenido.appendChild(divContent);
	}
	
	$("galleryContainer1").style.display="block";
	
}
function cambiarVideo(video)
{
	var reproductor = $("playflv");
	reproductor.SetVariable("video", video);
}

function cerrarGaleria()
{
	$('galleryContainer1').style.display='none';
	$('galleryWrap1').style.display='none';
	$('pgTabContainer').innerHTML="";
	$('pgMainBodyContainer').innerHTML="";
}

function cerrarPDF()
{
	$('pdfContainer').style.display='none';
	$('pdfWrap').style.display='none';
	//$('pgTabContainer').innerHTML="";
	$('pdfMainBodyContainer').innerHTML="";
}

function CameraHomeTemplate()
{
	this.fondo = null;
	this.flash = new Array();
	this.numFlash = 0;
	this.texto = new Array();
	this.numTexto = 0;
	this.imagen = new Array();
	this.numImagen = 0;
	this.iframe = new Array();
	this.numIframe = 0;
}

function CameraHomeImagen()
{
	this.href = null;
	this.src = null;
	this.top = null;
	this.left = null;
	this.target = "_self";
}

function CameraHomeFlash()
{
	this.src = null;
	this.top = null;
	this.left = null;
	this.width = null;
	this.height = null;
}

function CameraHomeTexto()
{
	this.href = null;
	this.texto = null;
	this.width = null;
	this.top = null;
	this.left = null;
	this.clase = null;
}

function CameraHomeIframe()
{
	this.src = null;
	this.top = null;
	this.left = null;
	this.width = null;
	this.height = null;
	this.scrolling = null;
	this.position = null;
}

function CameraHomeBuilder()
{
	this.xml = null;
	this.homeXML = null;
	this.contenedor = null;
	this.rootPath =null;
	this.imageCache = Array();
	this.numTemaSiguiente = 0;
	
	this._cacheImage = function(src) 
	{
		// Check if we are a third party navigation and we dont have a full url
		var newImage = new Image();
		var d = new Date();
		var url = src //+ "?" + d.getTime();

		newImage.src = src;
				
		//alert(url+" "+newImage.width);
		this.imageCache.push(newImage);
		//alert(this.imageCache[this.imageCache.length-1].src+"\n"+this.imageCache[this.imageCache.length-1].width);
		
	}

	this.init = function()
	{
		var arg = this.init.arguments;
		this.rootPath = (arg[1] != undefined ? arg[1] : './');
		this.homeXML = (arg[0] != undefined ? arg[0] : 'xml/home.xml');
		this.contenedor = document.getElementById("vcArea");
		this.getModeloXML();
	}
	
	this.getModeloXML = function ()
	{
		getTransporte();
		if (xmlhttp!=null)
		{
			xmlhttp.open("GET",this.rootPath+this.homeXML,false);
			xmlhttp.onreadystatechange = this.state_change;
			xmlhttp.send(null);
		}
		else
		{
			alert("Your browser does not support XMLHTTP.")
		}
	}
	
	this.state_change = function()
	{
		if (xmlhttp.readyState == 4) 
		{
			if (xmlhttp.status == 200)
			{
				homeBuilder.xml = xmlhttp.responseXML;
				homeBuilder.buildHome();
			}
			else
			{
				alert(xmlhttp.status);
			}
		}
	}
	
	this.parseTema = function()
	{
		var arg = this.parseTema.arguments;
		var item = arg[0];
		var tema = new CameraHomeTemplate();
		var atributo = null;
		for(var i = 0; i < item.childNodes.length; i++)
		{
			atributo = item.childNodes.item(i);
			switch(atributo.tagName)
			{
				case 'fondo':
					tema.fondo = atributo.textContent;
					if(tema.fondo == undefined)
					{
						tema.fondo = atributo.firstChild.text;
					}
					break;
				case 'flash':
					var n = tema.numFlash;
					tema.numFlash++;
					tema.flash[n] = new CameraHomeFlash();
					tema.flash[n].src = atributo.textContent;
					if(tema.flash[n].src == undefined)
					{
						tema.flash[n].src = atributo.firstChild.text;
					}
					for(j=0; j < atributo.attributes.length; j++)
					{
						switch(atributo.attributes[j].nodeName)
						{
							case 'top':
								tema.flash[n].top = atributo.attributes[j].nodeValue;
								break;
							case 'left':
								tema.flash[n].left = atributo.attributes[j].nodeValue;
								break;
							case 'width':
								tema.flash[n].width = atributo.attributes[j].nodeValue;
								break;
							case 'height':
								tema.flash[n].height = atributo.attributes[j].nodeValue;
								break;
						}
					}
					break;
				case 'iframe':
					var n = tema.numIframe;
					tema.numIframe++;
					tema.iframe[n] = new CameraHomeIframe();
					for(j=0; j < atributo.attributes.length; j++)
					{
						switch(atributo.attributes[j].nodeName)
						{
							case 'href':
								tema.iframe[n].href = atributo.attributes[j].nodeValue;
								break;
							case 'top':
								tema.iframe[n].top = atributo.attributes[j].nodeValue;
								break;
							case 'left':
								tema.iframe[n].left = atributo.attributes[j].nodeValue;
								break;
							case 'width':
								tema.iframe[n].width = atributo.attributes[j].nodeValue;
								break;
							case 'height':
								tema.iframe[n].height = atributo.attributes[j].nodeValue;
								break;
							case 'position':
								tema.iframe[n].position = atributo.attributes[j].nodeValue;
								break;
							case 'scrolling':
								tema.iframe[n].scrolling = atributo.attributes[j].nodeValue;
								break;
						}
					}
					break;
				case 'imagen':
					var n = tema.numImagen;
					tema.numImagen++;
					tema.imagen[n] = new CameraHomeImagen();

					tema.imagen[n].src = atributo.textContent;
					if(tema.imagen[n].src == undefined)
					{
						tema.imagen[n].src = atributo.firstChild.text;
					}
					for(j=0; j < atributo.attributes.length; j++)
					{
						switch(atributo.attributes[j].nodeName)
						{
							case 'href':
								tema.imagen[n].href = atributo.attributes[j].nodeValue;
								break;
							case 'top':
								tema.imagen[n].top = atributo.attributes[j].nodeValue;
								break;
							case 'left':
								tema.imagen[n].left = atributo.attributes[j].nodeValue;
								break;
							case 'target':
								tema.imagen[n].target = atributo.attributes[j].nodeValue;
								break;
						}
					}
					break;
				case 'texto':
					var n = tema.numTexto;
					tema.numTexto++;
					tema.texto[n] = new CameraHomeTexto();

					tema.texto[n].texto = atributo.textContent;
					if(tema.texto[n].texto == undefined)
					{
						tema.texto[n].texto = atributo.firstChild.text;
					}
					for(j=0; j < atributo.attributes.length; j++)
					{
						switch(atributo.attributes[j].nodeName)
						{
							case 'target':
								tema.texto[n].target = atributo.attributes[j].nodeValue;
								break;
							case 'href':
								tema.texto[n].href = atributo.attributes[j].nodeValue;
								break;
							case 'top':
								tema.texto[n].top = atributo.attributes[j].nodeValue;
								break;
							case 'width':
								tema.texto[n].width = atributo.attributes[j].nodeValue;
								break;
							case 'left':
								tema.texto[n].left = atributo.attributes[j].nodeValue;
								break;
							case 'class':
								tema.texto[n].clase = atributo.attributes[j].nodeValue;
								break;
						}
					}
					break;
					
			}
		}
		return tema;
	}
	
	this.detectImagenesVideos = function ()
	{
		var arg = this.detectImagenesVideos.arguments;
		var item = arg[0];
		for(var i = 0; i < item.childNodes.length; i++)
		{
			atributo = item.childNodes.item(i);
			switch(atributo.tagName)
			{
				case 'imagenes':
					hasImages = 1;
					break;
				case 'videos':
					hasVideos = 1;
					break;	
			}
		}
			
	}
	
	this.buildHome = function()
	{
		var home = this.xml.getElementsByTagName('root').item(0);
		
		var numTemas = temas.length;
		if(!numTemas)
		{
			for(var i = 0; i < home.childNodes.length; i++)
			{
				var item = home.childNodes.item(i);
				if(item.tagName == "tema")
				{
					temas[numTemas] = this.parseTema(item);
					numTemas++;
				}
				if(item.tagName == "imagenesvideos")
				{
					this.detectImagenesVideos(item);
				}
			}
		}
		if(this.contenedor==null)return;
		
		var numTemaSeleccionado = this.numTemaSiguiente;
		
		var temaSeleccionado = temas[numTemaSeleccionado];

		this.numTemaSiguiente = parseInt(Math.floor(Math.random ( ) * numTemas));
		var temaSiguiente = temas[this.numTemaSiguiente];
		
		this._cacheImage(temaSiguiente.fondo);
		
				
		var backImage = "url("+temaSeleccionado.fondo+") no-repeat"
		this.contenedor.innerHTML="";
		this.contenedor.style.background = backImage;
		for(i=0;i<temaSeleccionado.iframe.length;i++)
		{
			var iframe = document.createElement("iframe");
			iframe.className = "iframe";
			iframe.src = temaSeleccionado.iframe[i].href;
			iframe.width = temaSeleccionado.iframe[i].width;
			iframe.height = temaSeleccionado.iframe[i].height;
			iframe.style.position = temaSeleccionado.iframe[i].position;
			iframe.scrolling = temaSeleccionado.iframe[i].scrolling;
			iframe.frameBorder = 0;
			
			iframe.style.top = temaSeleccionado.iframe[i].top;
			iframe.style.left = temaSeleccionado.iframe[i].left;
			this.contenedor.appendChild(iframe);
		}
		for(i=0;i<temaSeleccionado.flash.length;i++)
		{
			var FlashHTML = AC_FL_RunContent(
	  			"codebase" ,"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0",
				"width", temaSeleccionado.flash[i].width+"px", 
				"height", temaSeleccionado.flash[i].height+"px", 
				"align", "middle",
				"allowScriptAccess" ,"sameDomain",
				"movie", rootFolder+temaSeleccionado.flash[i].src, 
				"bgcolor", "#000000",
				"src", rootFolder+temaSeleccionado.flash[i].src, 
				"quality", "high",
				'wmode', 'transparent',
				"allowScriptAccess", "sameDomain",
				"type", "application/x-shockwave-flash" ,
				"pluginspage", "http://www.macromedia.com/go/getflashplayer");

			var divObj = document.createElement("DIV");
			divObj.innerHTML = FlashHTML;
			divObj.style.position = "absolute";
			divObj.style.display = "block";
			divObj.style.width = temaSeleccionado.flash[i].width+"px";
			divObj.style.height = temaSeleccionado.flash[i].height+"px";
			divObj.style.top = temaSeleccionado.flash[i].top+"px"; 
			divObj.style.left = temaSeleccionado.flash[i].left+"px"; 
			
			this.contenedor.appendChild(divObj);
		}
		for(i=0;i<temaSeleccionado.imagen.length;i++)
		{
			var imagen = new Image();
			imagen.src = rootFolder+temaSeleccionado.imagen[i].src;
			imagen.style.cursor = "pointer";
			if(temaSeleccionado.imagen[i].href != null)
			{
				var link = document.createElement("A");
				link.href = temaSeleccionado.imagen[i].href;
				link.target = temaSeleccionado.imagen[i].target;
				link.appendChild(imagen);
				var divObj = document.createElement("DIV");
				divObj.appendChild(link);
			}
			else
			{
				var divObj = document.createElement("DIV");
				divObj.appendChild(imagen);
			}
			divObj.style.position = "absolute";
			divObj.style.display = "block";
			divObj.style.width = imagen.width+"px";
			divObj.style.height = imagen.height+"px";
			divObj.style.top = temaSeleccionado.imagen[i].top+"px"; 
			divObj.style.left = temaSeleccionado.imagen[i].left+"px"; 
			
			this.contenedor.appendChild(divObj);
		}
		for(i=0;i<temaSeleccionado.texto.length;i++)
		{
			var texto = document.createElement("DIV");
			texto.innerHTML = temaSeleccionado.texto[i].texto;
			if(temaSeleccionado.texto[i].width != null)
				texto.style.width = temaSeleccionado.texto[i].width;
			if(temaSeleccionado.texto[i].clase != null)
				texto.className = temaSeleccionado.texto[i].clase;
			if(temaSeleccionado.texto[i].href != null)
			{
				texto.style.cursor = "pointer";
				var link = document.createElement("A");
				link.href = temaSeleccionado.texto[i].href;
				link.target = (temaSeleccionado.texto[i].target != undefined ? temaSeleccionado.texto[i].target : '_self');
				link.appendChild(texto);
				var divObj = document.createElement("DIV");
				divObj.appendChild(link);
			}
			else
			{
				var divObj = document.createElement("DIV");
				divObj.appendChild(texto);
			}
			divObj.style.position = "absolute";
			divObj.style.display = "block";
			divObj.style.top = temaSeleccionado.texto[i].top+"px"; 
			divObj.style.left = temaSeleccionado.texto[i].left+"px"; 
			
			this.contenedor.appendChild(divObj);
		}
		
	
	}	
}

function CameraMenuBuilder()
{
	this.menuXML = null;
	this.xml = null;
	this.path = null;
	this.contenedor = null;
	this.modelo = null;
	
	this.init = function()
	{
		var arg = this.init.arguments;
		this.rootPath = (arg[1] != undefined ? arg[1] : './');
		this.menuXML = (arg[0] != undefined ? arg[0] : 'xml/menu.xml');
		this.contenedor = document.getElementById("mvNavigation");
		this.getModeloXML();
	}
	
	this.getModeloXML = function ()
	{
		getTransporte();
		if (xmlhttp!=null)
		{
			xmlhttp.open("GET",this.rootPath+this.menuXML,false);
			xmlhttp.onreadystatechange = this.state_change;
			xmlhttp.send(null);
		}
		else
		{
			alert("Your browser does not support XMLHTTP.")
		}
	}
	
	this.state_change = function()
	{
		if (xmlhttp.readyState == 4) 
		{
			if (xmlhttp.status == 200)
			{
				menuBuilder.xml = xmlhttp.responseXML;
				menuBuilder.buildMenu();
			}
			else
			{
				alert(xmlhttp.status);
			}
		}
	}
	
	this.buildMenu = function()
	{
		var menu = this.xml.getElementsByTagName('root').item(0);
		for(var i = 0; i < menu.childNodes.length; i++)
		{
			var nodo = menu.childNodes[i];
			
			switch (nodo.tagName)
			{
				case 'category':
					this.buildCategory(nodo);
					break;
				case 'headernav':
					this.buildHeaderNav(nodo);
					break;
			}
		}
	}
	
	this.buildHeaderNav = function()
	{
		var arg = this.buildHeaderNav.arguments;
		var nodo = arg[0];
		var width = null;
		var height = null;
		var texto = null;
		var href = null;
		var src = null;
		var alt = null;
		var mouseover = null;
		var mouseout = null;
		var identificador = null;
		var nombre = null;
		var classname = null;
		if(nodo.attributes)
		{
			width = (nodo.attributes.getNamedItem("width") ? nodo.attributes.getNamedItem("width").value : null);
			height = (nodo.attributes.getNamedItem("height") ? nodo.attributes.getNamedItem("height").value : null);
			alt = (nodo.attributes.getNamedItem("alt") ? nodo.attributes.getNamedItem("alt").value : null);
			texto = (nodo.attributes.getNamedItem("texto") ? nodo.attributes.getNamedItem("texto").value : null);
			href = (nodo.attributes.getNamedItem("href") ? nodo.attributes.getNamedItem("href").value : null);
			src = (nodo.attributes.getNamedItem("src") ? nodo.attributes.getNamedItem("src").value : null);
			mouseover = (nodo.attributes.getNamedItem("onmouseover") ? nodo.attributes.getNamedItem("onmouseover").value : null);
			mouseout = (nodo.attributes.getNamedItem("onmouseout") ? nodo.attributes.getNamedItem("onmouseout").value : null);
			identificador = (nodo.attributes.getNamedItem("id") ? nodo.attributes.getNamedItem("id").value : null);
			nombre = (nodo.attributes.getNamedItem("name") ? nodo.attributes.getNamedItem("name").value : identificador);
			classname = (nodo.attributes.getNamedItem("classname") ? nodo.attributes.getNamedItem("classname").value : null);
		}
		var contenedor = document.getElementById("headernav_menu");
		var divObj = document.createElement("div");
		if(classname)divObj.className = classname;
		if(src)
		{
			var imgObj = document.createElement("img");
			imgObj.src = src;
			imgObj.border=0;
			imgObj.hspace=0;
			imgObj.vspace=0;
			if(width)imgObj.width = width;
			if(height)imgObj.height = height;
			if(alt)imgObj.alt = alt;
			if(identificador)
			{
				imgObj.id = identificador;
				imgObj.onmouseover = function(){swapOver(identificador)};
				imgObj.onmouseout = function(){swapOver(identificador)};
			}
			if(nombre)imgObj.name = nombre;
			
		}
		else if(!texto)
		{
			return false;
		}
		if(href)
		{
			var aObj = document.createElement("a");
			aObj.href=href;
			if(src)aObj.appendChild(imgObj);
			else aObj.innerHTML = texto;
			divObj.appendChild(aObj);
		}
		else if(src)
		{
			divObj.appendChild(imgObj);
		}
		else
		{
			divObj.innerHTML = texto;
		}
		contenedor.appendChild(divObj);
	}
	
	this.buildCategory = function()
	{
		var arg = this.buildCategory.arguments;
		var nodo = arg[0];
		var width = null;
		var height = null;
		var alt = null;
		var href = null;
		var src = null;
		var id = null;
		var name = null;
		if(nodo.attributes)
		{
			width = (nodo.attributes.getNamedItem("width") ? nodo.attributes.getNamedItem("width").value : null);
			height = (nodo.attributes.getNamedItem("height") ? nodo.attributes.getNamedItem("height").value : null);
			alt = (nodo.attributes.getNamedItem("alt") ? nodo.attributes.getNamedItem("alt").value : null);
			href = (nodo.attributes.getNamedItem("href") ? nodo.attributes.getNamedItem("href").value : null);
			catname = (nodo.attributes.getNamedItem("nombre") ? nodo.attributes.getNamedItem("nombre").value : null);
			if(catname == null)return false;
			id = catname.toUpperCase();
			name = catname.toLowerCase();
			src = rootFolder + 'images/menu/categoria_'+id+".gif";
		}
		var contenedor = document.getElementById("mvNavigation");
		var divObj1 = document.createElement("div");
		var divObj2 = document.createElement("div");
		var divObj3 = document.createElement("div");
		var divObj4 = document.createElement("div");
		divObj1.className="mvCategoryContainer";
		divObj2.className="mvCategory";
		divObj3.className="mvModels";
		divObj4.className="mvCategoryDivider";
		if(href)
		{
			var aObj = document.createElement("a");
			aObj.href = href;
			//alert(enlace);
			var imgObj = document.createElement("img");
			imgObj.width = width;
			imgObj.height = height;
			imgObj.src = src;
			imgObj.alt = alt;
			imgObj.id = id;
			aObj.appendChild(imgObj);
			divObj2.appendChild(aObj);
		}
		else
		{
			var imgObj = document.createElement("img");
			imgObj.width = width;
			imgObj.height = height;
			imgObj.src = src;
			imgObj.alt = alt;
			imgObj.id = id;
			divObj2.appendChild(imgObj);
		}
		divObj1.appendChild(divObj2);
		
		var category = new ProductCategory(id, alt);
		
		if(nodo.childNodes.length)
		{
			for(i = 0; i < nodo.childNodes.length; i++)
			{
				//alert(nodo.childNodes.item(i));
				var item = nodo.childNodes.item(i);
				if(item.attributes != undefined)
				{
					var modelo = this.getModel(nodo.childNodes.item(i),id);
					var model = new ProductModel(modelo.name, modelo.alt, modelo.href,'','');
					if(item.childNodes.length)
					{
						for(j = 0; j < item.childNodes.length; j++)
						{
							var featureNode = item.childNodes.item(j);
							if(featureNode.nodeName=="feature")
							{
								model.addFeature(featureNode.firstChild.nodeValue);
							}
						}
					}
					category.addModel(model);
					divObj3.appendChild(modelo);
				}
			}
			divObj1.appendChild(divObj3);
		}
		navigationManager.addCategory(category);
		
		this.contenedor.appendChild(divObj1);
		var imgObj = document.createElement("img");
		
		imgObj.src = "/images/spacer.gif";
		imgObj.height = 45;
		imgObj.width = 1;
		divObj4.appendChild(imgObj);
		this.contenedor.appendChild(divObj4);
	}
	
	this.getModel = function()
	{
		var arg = this.getModel.arguments;
		var nodo = arg[0];
		var enlace = nodo.attributes.getNamedItem("href").value;
		var categoryId = arg[1];
		var nombre = nodo.attributes.getNamedItem("nombre").value
		var modelId = categoryId+"_"+nombre;
		//var modelId = nodo.attributes.getNamedItem("nombre").value;
		var aObj = document.createElement("a");
		var imgObj = document.createElement("img");
		//alert(nodo.href);
		aObj.href = (nodo.attributes.getNamedItem("href") ? nodo.attributes.getNamedItem("href").value : null);
		//aObj.link = (nodo.attributes.getNamedItem("href") ? nodo.attributes.getNamedItem("href").value : null);
		imgObj.src = rootFolder+"images/menu/modelo_"+nombre+".gif";
		imgObj.width = (nodo.attributes.getNamedItem("width") ? nodo.attributes.getNamedItem("width").value : null);
		imgObj.height = (nodo.attributes.getNamedItem("height") ? nodo.attributes.getNamedItem("height").value : null);
		imgObj.alt = (nodo.attributes.getNamedItem("alt") ? nodo.attributes.getNamedItem("alt").value : null);
		aObj.name = (nodo.attributes.getNamedItem("nombre") ? nodo.attributes.getNamedItem("nombre").value : null);
		aObj.alt = (nodo.attributes.getNamedItem("alt") ? nodo.attributes.getNamedItem("alt").value : null);
		imgObj.id = modelId;
		aObj.appendChild(imgObj);
		return aObj;
	}
}

var modelManager = new CameraModelManager();
var menuBuilder = new CameraMenuBuilder();
var homeBuilder = new CameraHomeBuilder();
var temas = new Array();
//v1.0
//Copyright 2006 Adobe Systems, Inc. All rights reserved.
function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '<object ';
  for (var i in objAttrs)
  {
    str += i + '="' + objAttrs[i] + '" ';
  }
  str += '>';
  for (var i in params)
  {
    str += '<param name="' + i + '" value="' + params[i] + '" /> ';
  }
  str += '<embed ';
  for (var i in embedAttrs)
  {
    str += i + '="' + embedAttrs[i] + '" ';
  }
  str += ' ></embed></object>';

  return str;
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  return AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "id":
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "name":
      case "type":
      case "codebase":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}


function DescargarPDF(doc)
{
	window.onresize = Resize;
	var backdrop_loader = $('backdrop_loader2');
	var pdf_wrap = $('pdfWrap');
	pdf_wrap.style.display = "block";
	Resize();
	$("pdfContainer").style.display="block";
	var contenido = $("pdfMainBodyContainer");
	
	var pdfHeader = document.createElement("DIV");
	var pdfHeader2 = document.createElement("DIV");
	var pdfTab = document.createElement("DIV");
	var pdfDivider = document.createElement("DIV");

	
	var imgHeader = document.createElement("IMG");
	
	pdfTab.className = "pgTabContainer";
	var imgTab = document.createElement("IMG");
	imgTab.src=rootFolder+"images/g_tbPdfOn.gif";
	imgTab.style.width = "160px";
	var ulTab = document.createElement("UL");
	var liTab = document.createElement("LI");
	liTab.appendChild(imgTab);
	ulTab.appendChild(liTab);
	pdfTab.appendChild(ulTab);
	
	imgDivider = document.createElement("IMG");
	imgDivider.src = rootFolder+"images/spacer.gif";
	pdfDivider.className = "pgTabDivider";
	pdfDivider.appendChild(imgDivider);
	
	
	pdfHeader.align = "left";
	imgHeader.src= rootFolder+"images/logopdfgris.png";
	imgHeader.hspace= "30";
	imgHeader.vspace= "10";
	pdfHeader.appendChild(imgHeader);
	pdfHeader2.align = "center";
	pdfHeader2.innerHTML = "Descargando el documento <strong>"+doc+"</strong>";
	pdfHeader2.className = "related_docs";
	contenido.appendChild(pdfTab);
	contenido.appendChild(pdfDivider);
	contenido.appendChild(pdfHeader);
	contenido.appendChild(pdfHeader2);

		//pdfHeader2.innerHTML = "IMPORTANTE: Para poder visualizar documentos PDF es necesario tener instalado el programa Adobe Acrobat Reader. Puede descargar gratuitamente este programa haciendo click <A href='http://www.adobe.com/products/acrobat/readstep2.html' target=_blank>aquí</A>"

	var before =  document.createElement("DIV");
	before.id =  "before";
	
	var processing =  document.createElement("DIV");
	processing.id = "processing";
	processing.style.display = "none";
	 
	var download =  document.createElement("DIV");
	download.id = "download";
	download.style.display = "none";
	
	before.innerHTML = "<div class='related_docs' align='center'>Para completar la descarga le rogamos nos facilite su dirección de correo electrónico</div><br /><br /><br />"
	before.innerHTML += "<div class='related_docs_form' align='center'>Email: <input type='text' class='related_docs_form' size='35' name='subscriber_email' id='subscriber_email' value='"+leerCookie('subscriber_email')+"'></div><br />";
	before.innerHTML += "<input type='hidden' name='subscriber_document' id='subscriber_document' value='"+doc+"'>";
	before.innerHTML += "<div style='padding:25px' align='center'><input type='image' src='"+rootFolder+"images/send.png' width='111' height='22' value='ENVIAR' onclick='SendData()'></div><br />";
	
	processing.innerHTML = "<br /><br /><br /><div class='related_docs' align='center'>P R O C E S A N D O</div><br /><br /><br /><br />";
	processing.innerHTML += "<div class='related_docs' align='center'><img src='"+rootFolder+"images/download_loader.gif'></div><br /><br /><br /><br />";
	processing.innerHTML += "<div class='related_docs' align='center'>POR FAVOR ESPERE</div>";
	
	download.innerHTML += "<br /><br /><br /><div class='related_docs' align='center'>Hemos enviado un email a la dirección de correo que nos ha facilitado con las instrucciones para la descarga del documento.</div><br /><br />";
	download.innerHTML += "<br /><br /><br /><div class='related_docs' align='center'>GRACIAS POR SU INTERES</div><br /><br /><br />";
	//download.innerHTML += "<div class='related_docs' align='center'><a class='related_docs_link' href='"+rootFolder+"images/pdf/"+doc+"' target='_blank' onclick='OcultarDocumento()'>CLICK AQUI PARA DESCARGAR</a></div>";
	download.innerHTML += "<br /><br /><br /><br /><br /><br /><br /><br /><br /><br />";
	download.innerHTML += "<div class='related_docs_small' align='center'>IMPORTANTE: Para poder visualizar documentos PDF es necesario tener instalado el programa Adobe Acrobat Reader. Puede descargar gratuitamente este programa haciendo click <A href='http://www.adobe.com/products/acrobat/readstep2.html' target=_blank class='related_docs_small'>aquí</A></div>";
	
	
	contenido.appendChild(before);
	contenido.appendChild(processing);
	contenido.appendChild(download);
	
}

function SendData()
{
	var email = $("subscriber_email");
	var documento = $("subscriber_document");
	
	if(!Validar())
	{
		return false;
	}
	
	$("processing").style.display = "block";
	$("before").style.display = "none";
	
	escribirCookie('subscriber_email',email.value);

	loadXMLDoc(rootFolder+'mail.php?email='+email.value+'&document='+documento.value);
	
	
}

function ValidarEmail(theElement)
{
	var s = theElement.value;
	var filter=/^[A-Za-z][A-Za-z0-9_.]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;
	if (s.length == 0 ) return false;
	if (filter.test(s))
	{
		return true;
	}
	else
	{
		return false;
	}
}

function ValidarTexto(theElement,min,max)
{
	var s = theElement.value;
	if(s.length > max || s.length < min)
	{
		return false;
	}
	return true;
}


function Validar()
{
	var email = $("subscriber_email");
	if(!ValidarEmail(email))
	{
		alert('Debe introducir una direccion de Email valida para descargar el documento');
		email.focus();
		return false;		
	}
	return true;	
}
var xmlhttp;

function loadXMLDoc(url)
{
	xmlhttp=null;
	// code for Mozilla, etc.
	if (window.XMLHttpRequest)
  	{
  		xmlhttp=new XMLHttpRequest()
  	}
  	// code for IE
	else if (window.ActiveXObject)
  	{
  		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
  	}
	if (xmlhttp!=null)
  	{
  		xmlhttp.onreadystatechange=state_Change
  		xmlhttp.open("GET",url,true)
  		xmlhttp.send(null)
  	}
	else
  	{
  		alert("Your browser does not support XMLHTTP.")
  	}
}

function state_Change()
{
	// if xmlhttp shows "loaded"
	if (xmlhttp.readyState==4)
  	{// if "OK"
  		if (xmlhttp.status==200)
    	{
    		if(xmlhttp.responseText == "ok")
    			showDownloadLink();
    		else
    			alert(xmlhttp.responseText);// ...some code here...
    	}
  		else
    	{
    		alert("Problem retrieving data")
    	}
  	}
}

function showDownloadLink()
{
	$("processing").style.display = "none";
	$("download").style.display =  "block";
}



var interval = null;
function desactivar()
{
	clearInterval(interval)
	//alert("desactivado");
}

function activar()
{
	//alert("activado");
	interval = setInterval("OcultarPresentacion()",30000);
}

function escribirCookie(sName, sValue)
{
  date = new Date();
  document.cookie = sName + "=" + escape(sValue) + ";path=/; expires=Fri, 31 Dec 2099 23:59:59 GMT;";
}

function leerCookie(sName)
{
  // cookies are separated by semicolons
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    // a name/value pair (a crumb) is separated by an equal sign
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0]) 
      return unescape(aCrumb[1]);
  }

  // a cookie with the requested name does not exist
  return '';
}


function abrirCategoria(name)
{
	var imagenCategoria = $(name.toUpperCase());
	var mvCategory = imagenCategoria.parentNode;
	
	var categoryImg = ($NL(mvCategory.childNodes)).firstElement();
	
	if(categoryImg.tagName == "A")
			categoryImg = categoryImg.firstChild;
	swapOut(categoryImg);
	navigationManager.showNavigation(categoryImg, categoryImg.id);
}

function abrirGaleriaGeneral()
{
	var arg = this.abrirGaleriaGeneral.arguments;
	var inicio = arg[0];

	var galleryWrap = $("galleryWrap1");
	galleryWrap.style.display = "block";
	createGallery();
	$('gallery_header_image').src = "/images/transparent.gif";
	if(inicio == 'videos')
		SwapImagesVideos();
}

function renovarTema(){
	homeBuilder.buildHome();
	setTimeout("renovarTema()",recargarTema*1000);
}

