//<![CDATA[
/*
 Copyright (c) 2006 MexWebs Developer Team. All rights reserved.
 version 0.1.0
 Author: Caridy Patiño

 JS-YUI
 ==============
 Assumed Document Object Model described in:
 "Document Object Model (DOM) Level 2 Specification Version 1.0"
 (http://www.w3.org/TR/1999/CR-DOM-Level-2-19991210)
 Latest version: (http://www.w3.org/TR/DOM-Level-2)

 Successfully tested on:
  - Miscrosoft Internet Explorer 6.02
  - Mozilla Firefox 1.5
  - Opera 8.5
 All in platform Win32, Operating System Windows XP SP2.

 Description:
 ============
 Implementación de las principales funciones de YAHOO USER INTERFACE usadas en nuestros sitios...
*/
if (!YAHOO.CMS) YAHOO.namespace("CMS");  
YAHOO.namespace("tms.panel");
YAHOO.namespace("tms.simpledialog");
YAHOO.namespace("tms.animations");YAHOO.tms.animations = new Array();
YAHOO.namespace("tms.dimensions");YAHOO.tms.dimensions = new Array();
YAHOO.namespace("tms.vars");YAHOO.tms.vars = new Array();
YAHOO.namespace("tms.tooltips");YAHOO.tms.tooltips = new Array();

function downloadScripts ( s ) { // under production...
	// cut out all script tags, push them into scripts array
	var m = [], remoteScripts = Array(), localscripts = "", attr = false, self = this;
	while(m){
		m = s.match(/<script([^>]*)>([\s\S]*?)<\/script>/i);
		if(!m){ break; }
		if(m[1]){
		  attr = m[1].match(/src=(['"]?)([^"']*)\1/i);
		  if(attr)
			remoteScripts.push(attr[2]);
		}
		if(m[2]){
		  localscripts += m[2];
		}
	}

	try{
	  // initialize a new anonymous container for our script, dont make it part of this widgets scope chain
	  // instead send in a variable that points to this widget, usefull to connect events to onLoad, onUnLoad etc..
	  this.scriptScope = null;
	  this.scriptScope = new (new Function('_container_', localscripts+'; return this;'))(self);
	}catch(e){
  	  alert("Error running scripts from content:\n"+e);
	}
	return remoteScripts;
}

function executeble(content) {
  if (!content) return true;
  if (!content.getElementsByTagName) return;
  var items = new Array(), localscripts = '', self = this;
  items.merge( content.getElementsByTagName("script") );
  
  for (var i=0; i<items.length; i++)
    localscripts += items[i].innerHTML;
	
  if (localscripts != '') {
	  try{
		// initialize a new anonymous container for our script, dont make it part of this widgets scope chain
		// instead send in a variable that points to this widget, usefull to connect events to onLoad, onUnLoad etc..
		this.scriptScope = null;
		this.scriptScope = new (new Function('_container_', localscripts+'; return this;'))(self);
	  } catch(e) {
		// alert("Error running scripts from content:\n"+e);
		return false;
	  }
  }
  return true;	
}
/**
* Este método muestra el contenido de una url externa dentro de un div...
* @public
* @param {string} t    title, el título del dialogo...
* @param {string} b    body, el contenido del dialogo... ;-)
* @param {string} w    width, el ancho del dialogo
* @param {string} d    dragable, si es o no dragable
* @return boolean
*/
function displayDialog( t, b, w, d, r ) {
	t = asset ( t, '' );
	b = asset ( b, '' );
	w = asset ( w, '' ); /* 50em */
	d = assetbool ( d, false );
	r = assetbool ( r, true );
	var dialogClass = YAHOO.widget.SimpleDialog;
	var handleCancel = function() {
		this.hide();
	}
	var handleOK = function() {
		this.hide();
	}
	try {YAHOO.tms.simpledialog.dlg.hide();} catch (e) {}
	if (r) dialogClass = YAHOO.widget.ResizePanel;
	YAHOO.tms.simpledialog.dlg = new dialogClass("dlg", 
	 							  { width:w,  
	 							    fixedcenter: true, 
	 							    constraintoviewport: true, 
	 							    underlay:"shadow", 
	 							    close:true, 
	 							    visible:false, 
	 							    draggable:d,
									iframe: true
	 							    } 
	 							   );
	YAHOO.tms.simpledialog.dlg.setHeader( t );
	YAHOO.tms.simpledialog.dlg.setBody( b );
	YAHOO.tms.simpledialog.dlg.cfg.queueProperty("buttons", [ { text:"Close", handler:handleCancel } ]);

    var listeners = new YAHOO.util.KeyListener(document, { keys : 27 }, {fn:handleCancel ,scope:YAHOO.tms.simpledialog.dlg, correctScope:true} );
	YAHOO.tms.simpledialog.dlg.cfg.queueProperty("keylisteners", listeners);

	YAHOO.tms.simpledialog.dlg.render(document.body);
	YAHOO.tms.simpledialog.dlg.show();
	return true;
}
/**
* Este método muestra el contenido de una url externa dentro de un div...
* @public
* @param {string} content_id    ID que identifica al DIV donde se debe mandar a cargar el contenido resultado de la navegación de url
* @param {string} url           URI de navegación
* @return boolean
*/
function displayLoading( m ) {
	YAHOO.CMS.Common.loading.show ();
}
/**
* Este metodo se encarga de aplicar los tooltips a todos los elementos que le correspondan...
* @public
* @param {object} obj Referencia al objeto que vamos a aplicarle el evento de tooltip
* @param {string} tt  DOM ID - estilo que se le va a aplicar a la caja del tooltip
* @param {real}   op  Opacity - Valor de la opacidad para la caja de estilo del tooltip
* @return void
*/
function applyToolTips() {
	if (YAHOO.tms.vars['tooltips-robot-handle'])
	  clearTimeout ( YAHOO.tms.vars['tooltips-robot-handle'] );
	YAHOO.tms.vars['tooltips-robot-handle'] = null;
	if (((typeof YAHOO.tms.tooltips == 'object') || (typeof YAHOO.tms.tooltips == 'array')) && (YAHOO.tms.tooltips.length > 0)) {
	  applyToolTip ( YAHOO.tms.tooltips.pop() );
      YAHOO.tms.vars['tooltips-robot-handle'] = window.setTimeout( 'applyToolTips()', 2 ); 
	}
}
/**
* Este metodo se encarga de asignarle al obj correspondiente los eventos de tooltip, asi como la conformación de la información que debe mostrar dicha caja
* @public
* @param {object} obj Referencia al objeto que vamos a aplicarle el evento de tooltip
* @param {string} tt  DOM ID - estilo que se le va a aplicar a la caja del tooltip
* @param {real}   op  Opacity - Valor de la opacidad para la caja de estilo del tooltip
* @return void
*/
function applyToolTip( obj, tt, op ) {
  if ((typeof obj == 'object') || (obj = document.getElementById( obj ))) {
	// Adicionando el evento para el tooltip sobre cada enlace...
	var ttid    = ( tt ? tt.toString() : "tt" );      // quoting value for DOM ID - the default id is #tt
	var opacity = ( op ? op.toString() : "0.9" );     // default value for DOM opacity attribute (semi-transparent)
	var host = location.hostname.toString();
	var txt  = new String ();
	var pattern = new RegExp("(http://?)"+host,"gi");
	var fullPath = obj.href.toString();
	var path = fullPath.replace(pattern,'');
	addy = (path.length > 30 ? path.toString().substring(0,30)+"..." : path);
	if ((addy.indexOf('/#') == 0) || (addy.indexOf('#') == 0) || (addy.indexOf('javascript:') == 0) || (addy == '/')) addy = ''; // remove the anchor links if it´s empty or null
	var access = ( obj.accessKey ? " ["+obj.accessKey+"]" : "" );
	// verifing if we really have text to display in the tooltip
	var tip = ( obj.getAttribute('title')? obj.getAttribute('title').toString() + '<br />' : "" );
	obj.removeAttribute('title');
	if (tip+access+addy != '') {
	    var ttb = new YAHOO.widget.Tooltip(ttid, { 
							  preventoverlap:true,
							  constraintoviewport:true,
							  zIndex: 10,
							  context:obj, 
							  hidedelay: 0,
							  autodismissdelay: 10000,
							  text: String(tip+'<em>'+access+'<em>'+addy) 
							  } );
		// Eliminando todos los ATL de las imagenes que estan dentro del Anchor
	    var childs = new Array();
		if (assetObj( obj ) && (childs = obj.getElementsByTagName("img"))) 
		  for (var i=0; i<childs.length; i++)
		    childs[i].alt = '';
	}
    // Defino el estilo para la caja de los tooltips, para que tenga un poco de transparencia.
    YAHOO.util.Dom.setStyle(ttid, 'opacity', opacity);
  }
  return true;
}
function slicing( el, h, onCompleteSlice ) {
  if ((typeof el != 'object') && !(el = document.getElementById( el ))) return false;
  YAHOO.util.Dom.setStyle(el, 'overflow', 'hidden');
  var id = YAHOO.util.Event.generateId (el) + '-slicing'; // stored height id

  if ((typeof YAHOO.tms.animations[id] == 'object') && (YAHOO.tms.animations[id].isAnimated())) { YAHOO.tms.animations[id].stop(); }
  YAHOO.tms.animations[id] = new YAHOO.util.Anim(el, { height: { to: storage( el, h, 'height') } }, 1.5, YAHOO.util.Easing.easeOutStrong);
  if(typeof onCompleteSlice == "function")
    YAHOO.tms.animations[id].onComplete.subscribe(onCompleteSlice);
  YAHOO.tms.animations[id].animate();
}
function expanding( el, w, onCompleteExpand ) {
  if ((typeof el != 'object') && !(el = document.getElementById( el ))) return false;
  YAHOO.util.Dom.setStyle(el, 'overflow', 'hidden');
  var id = YAHOO.util.Event.generateId (el) + '-expanding'; // stored height id
  
  if ((typeof YAHOO.tms.animations[id] == 'object') && (YAHOO.tms.animations[id].isAnimated())) { YAHOO.tms.animations[id].stop(); }
  YAHOO.tms.animations[id] = new YAHOO.util.Anim(el, { width: { to: storage( el, w, 'width') } }, 1.5, YAHOO.util.Easing.easeOutStrong);
  if(typeof onCompleteExpand == "function")
    YAHOO.tms.animations[id].onComplete.subscribe(onCompleteExpand);
  YAHOO.tms.animations[id].animate();
}
function storage( el, h, a) { // el, dimesion, attribute
  if ((typeof el != 'object') && !(el = document.getElementById( el ))) return false;
  var id = YAHOO.util.Event.generateId (el); // stored value id
  var hh = assetOffset(el, a); // current value
  var uaid = id + '-' + a;
  var usid = uaid + '-storage';
  var firsttime = false;
  if (isEmpty(YAHOO.tms.dimensions[uaid]))
	YAHOO.tms.dimensions[uaid] = hh;
  if (isEmpty(YAHOO.tms.dimensions[usid]) && (YAHOO.tms.dimensions[usid] != 0)) {
	YAHOO.tms.dimensions[usid] = hh; firsttime = true;
  }
  if (!isEmpty(h) || (h == 0))
    YAHOO.tms.dimensions[usid] = h;
  else if ((firsttime == false) && (Math.round(px2int(YAHOO.tms.dimensions[usid])) != Math.round(px2int(YAHOO.tms.dimensions[uaid]))))
    YAHOO.tms.dimensions[usid] = YAHOO.tms.dimensions[uaid];
  else
    YAHOO.tms.dimensions[usid] = 0;
  return YAHOO.tms.dimensions[usid];
}

/**
* Este metodo se encarga de asignarle un menu contextual sobre un enlace o elemento cualquiera 
* @public
* @param {string} obj_id   DOM ID - Referencia o ID del elemento al que se le va a enlazar el menu contextual
* @param {string} menu_id  DOM ID - Referencia o ID del elemento que representa en menu
* @return void
*/
function init_contextual_menu ( el, menu_id, single ) {
  if ((typeof el == 'object') || (el = document.getElementById( el ))) 
	YAHOO.widget.MyContextMenu ( el,	{ 
									  context:el,
									  menu:menu_id,
									  opacity:0.9
									}
							 );
}
// Render de un menu a partir de la estructura en xhtml
function initMenuBar( el, single, op ) {
  if ((typeof el == 'object') || (el = document.getElementById( el ))) 
	YAHOO.widget.MyMenuBar( el, { opacity:op } );
}

function initYUI () {
  YAHOO.util.Event.addListener( document, "mousedown", onDocumentMouseDown );
}

// "mousedown" handler for the document
YAHOO.tms.panel.OverlayManager = new YAHOO.widget.OverlayManager();
function onDocumentMouseDown(p_oEvent) {
	YAHOO.tms.panel.OverlayManager.hideAll();
}

/* Array prototype, matches value in array: returns bool */
Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++)
 	  if (this[i] === value)
		return true;
	return false;
};

/* Array prototype, marge a new array to the current array: returns bool */
Array.prototype.merge = function ( items ) {
	var i;
	for (i=0; i < items.length; i++)
      this.push(items[i]);
};
/**
* Este método muestra el contenido de una url externa dentro de un div...
* @public
* @param {string} content_id    ID que identifica al DIV donde se debe mandar a cargar el contenido resultado de la navegación de url
* @param {string} url           URI de navegación
* @return boolean
*/
function ajaxLoadContent( content, url, aHandleSuccess, aHandleFailure ) {
  return YAHOO.CMS.Common.ajaxLoadContent ( content, url, aHandleSuccess, aHandleFailure );
}
/**
* Este método muestra el contenido de una url externa dentro de un div...
* @public
* @param {Object} el    ID que identifica al Elemento donde se debe mandar a cargar el contenido
* @param {string} c     Content que debe ser colocado como hijo...
* @return boolean
*/
function safeInnerHTML( el, c ) {
  return YAHOO.CMS.Common.safeInnerHTML( el, c );
}
/**
* Este método asegura que las variables esten definidas
* @public
* @param {object} variable    
* @param {object} valor por defecto    
* @return integer
*/
function asset( v, d ) {
  return YAHOO.CMS.Common.asset( v, d );
}
function isEmpty( v ) {
  return YAHOO.CMS.Common.isEmpty( v );
}
function assetbool( v, d ) {
  return YAHOO.CMS.Common.assetbool( v, d );
}
function assetObj( o, d ) {
  return YAHOO.CMS.Common.assetObj( o, d );
}
function assetOffset ( o, a ) {
  return YAHOO.CMS.Common.assetOffset ( o, a );
}
/**
* Este método elimina el px de las dimensiones...
* @public
* @param {string} dimension    ej. (102px) y esta funcion devuelve el numero 102
* @return integer
*/
function px2int( d ) {
  return YAHOO.CMS.Common.px2int( d );
}

/**
* Este método hace un parsing de una url, completa sus parametros sobrescribiendo parametros que se pasan como m a la funcion
* @public
* @param {string} url URI de navegación
* @param {string} m   MoreParams representa una cadena de parametros con el siguiente formato ( param1=value1&param2=value2 )
* @return string
*/
function url_completion ( url, m ) {
  return YAHOO.CMS.Common.url_completion( url, m );
}
/**
* Este metodo hace un fadeOut, luego sustituye el contendio actual del elemento por el nuevo contenido y hace un fadeIn
* @public
* @param {object}   el    			Referencia al objeto que vamos a aplicarle el pase magico
* @param {string}   text  			Nuevo contenido para el innerHTML del objeto
* @param {function} onCompleteFade	Function que se ejecutará al finalizar la animación...
* @return void
*/
function applyMagicFade ( el, userconfig ) {
  return YAHOO.CMS.Common.applyMagicFade ( el, userconfig );
}
	function magicFade ( el, newtext, onCompleteFade ) {
	  return YAHOO.CMS.Common.applyMagicFade ( el, {text: newtext, onComplete: onCompleteFade } );
	}
function resetAccordion ( m, id )  {
  return YAHOO.CMS.Common.resetAccordion ( m, id );
}
function accordion ( el ) {
  return YAHOO.CMS.Common.accordion ( el );
}
/**
* Este metodo se encarga de asignarle una nueva clase a un elemento
* @public
* @param {string} el  DOM ID    - Referencia o ID del elemento al que se le va a enlazar el menu contextual
* @param {string} c1  ClassName
* @param {string} c2  ClassName
* @return void
*/
function swapClass( el, c1, c2 ) { // caridy: v1.0
  return YAHOO.CMS.Common.swapClass( el, c1, c2 );
}
// Dustin Diaz Functions...   pending to be check it...
/* grab Elements from the DOM by className */
function getElementsByClass(searchClass,node,tag) {
	return YAHOO.util.Dom.getElementsByClassName(searchClass,tag,node);
}
/* toggle an element's display */
function toggle(obj) {
  return YAHOO.CMS.Common.toggle(obj);
}
/* insert an element after a particular node */
function insertAfter(parent, node, referenceNode) {
  return YAHOO.CMS.Common.insertAfter(parent, node, referenceNode);
}
/* get, set, and delete cookies */
function getCookie( name ) {
  return YAHOO.CMS.Common.getCookie( name );
}
function setCookie( name, value, expires, path, domain, secure ) {
  return YAHOO.CMS.Common.setCookie( name, value, expires, path, domain, secure );
}
function deleteCookie( name, path, domain ) {
  return YAHOO.CMS.Common.deleteCookie( name, path, domain );
}

//]]>
