/**
 * SUBMODAL v1.6
 * Used for displaying DHTML only popups instead of using buggy modal windows.
 *
 * By Subimage LLC
 * http://www.subimage.com
 *
 * Contributions by:
 * 	Eric Angel - tab index code
 * 	Scott - hiding/showing selects for IE users
 *	Todd Huss - inserting modal dynamically and anchor classes
 *
 * Up to date code can be found at http://submodal.googlecode.com
 */

// Popup code
var gPopupMask = null;
var gPopupContainer = null;
var gPopFrame = null;
var gDivIframe = null;
var gReturnFunc;
var gPopupIsShown = false;
var gDefaultPage = 'about:blank';
var gHideSelects = false;
var gReturnVal = null;
var gTabIndexes = new Array();
var gPopupWidth = null;
var gPopupHeight = null;
var TimeToFade = 200.0;
// Pre-defined list of tags we want to disable/enable tabbing into
var gTabbableTags = new Array("A","BUTTON","TEXTAREA","INPUT","IFRAME");	

//document.onkeypress = function (e) { keyDownHandler(e);}

function eliminarObjeto(objeto){

	if(document.getElementById(objeto)){
		var divEliminar = document.getElementById(objeto);
		divEliminar.parentNode.removeChild(divEliminar);
	}

}

function fade(acc){

	if(gPopupContainer == null)	return;

	if(gPopupContainer.FadeState == null){
		gPopupContainer.FadeState = -2;
	}

	if(gPopupContainer.FadeState == 1 || gPopupContainer.FadeState == -1){
		gPopupContainer.FadeState = gPopupContainer.FadeState == 1 ? -1 : 1;
		gPopupContainer.FadeTimeLeft = TimeToFade - gPopupContainer.FadeTimeLeft;
	}else{
		gPopupContainer.FadeState = gPopupContainer.FadeState == 2 ? -1 : 1;
		gPopupContainer.FadeTimeLeft = TimeToFade;
		setTimeout("animateFade(" + new Date().getTime() + ",'" + 'popupContainer' + "')", 33);
		setTimeout("mostrar_ocultar_div('" + acc + "')", TimeToFade);
	}

}

function mostrar_ocultar_div(acc){

	gPopupContainer.style.display = acc;

}

function animateFade(lastTick){

	var curTick = new Date().getTime();
	var elapsedTicks = curTick - lastTick;

	if(gPopupContainer.FadeTimeLeft <= elapsedTicks){
		gPopupContainer.style.opacity = gPopupContainer.FadeState == 1 ? '1' : '0';
		gPopupContainer.style.filter = 'alpha(opacity = '+ (gPopupContainer.FadeState == 1 ? '100' : '0') + ')';
		gPopupContainer.FadeState = gPopupContainer.FadeState == 1 ? 2 : -2;
		return;
	}
	gPopupContainer.FadeTimeLeft -= elapsedTicks;
	var newOpVal = gPopupContainer.FadeTimeLeft/TimeToFade;
	if(gPopupContainer.FadeState == 1){
		newOpVal = 1 - newOpVal;
	}
	gPopupContainer.style.opacity = newOpVal;
	gPopupContainer.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';
	setTimeout("animateFade(" + curTick	+ ",'" + 'popupContainer' + "')", 33);

}

/**
 * Initializes popup code on load.	
 */
function initPopUp() {

	gPopupMask = null;
	gPopupContainer = null;
	gPopFrame = null;
	gDivIframe = null;
	gDefaultPage = 'about:blank';
	eliminarObjeto('popupMask');
	eliminarObjeto('popupContainer');
	var theBody = document.getElementsByTagName('body').item(0);
	var popmask = document.createElement('div');
	popmask.id = 'popupMask';
	var popcont = document.createElement('div');
	popcont.id = 'popupContainer';
	popcont.innerHTML = 
		'<div id="popupInner">' +
			'<div id="popupDivIframe"><iframe src="'+ gDefaultPage +'" style="background-color:transparent;" scrolling="auto" frameborder="0" allowtransparency="true" id="popupFrame" name="popupFrame"></iframe></div>' +
			'<div id="popupTitleBar">' +
				'<span class="linktoolbar"><a href="#" onclick="hidePopWin(false); return false;">Aceptar</a></span>' +
			'</div>' +
		'</div>';

	theBody.appendChild(popmask);
	theBody.appendChild(popcont);

	gPopupMask = document.getElementById('popupMask');
	gPopupContainer = document.getElementById('popupContainer');
	gPopFrame = document.getElementById('popupFrame');	
	gDivIframe = document.getElementById('popupDivIframe');	
	gPopupMask.onclick = function () { hidePopWin(false); return false; }

	// check to see if this is IE version 6 or lower. hide select boxes if so
	// maybe they'll fix this in version 7?
	var brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10);
	if (brsVersion <= 6 && window.navigator.userAgent.indexOf("MSIE") > -1) {
		gHideSelects = true;
	}
	
	// Add onclick handlers to 'a' elements of class submodal or submodal-width-height
	/*var elms = document.getElementsByTagName('a');
	for (i = 0; i < elms.length; i++) {
		if (elms[i].className.indexOf("submodal") == 0) { 
			// var onclick = 'function (){showPopWin(\''+elms[i].href+'\','+width+', '+height+', null);return false;};';
			// elms[i].onclick = eval(onclick);
			elms[i].onclick = function(){
				// default width and height
				var width = 400;
				var height = 200;
				// Parse out optional width and height from className
				params = this.className.split('-');
				if (params.length == 3) {
					width = parseInt(params[1]);
					height = parseInt(params[2]);
				}
				showPopWin(this.href,width,height,null); return false;
			}
		}
	}*/
}

//addEvent(window, "load", initPopUp);
//addEvent(window, "load", initPopUp);

//window.onload = initPopUp;

function showPopWin(url_msg, width, height, returnFunc, es_txt) {
//document.documentElement.style.overflow = "hidden";

	initPopUp();
	
	if (typeof document.body.style.maxHeight === "undefined"){
		scrollFixIE6('hidden');
	}

	gPopupIsShown = true;
	disableTabIndexes();

	gPopupWidth = width;
	gPopupHeight = height;
	
	centerPopWin();
	gPopupMask.style.display = "block";
	//gPopupContainer.style.display = "block";
	fade('block');

	//setMaskSize();

	if(es_txt){
		gDivIframe.innerHTML = url_msg;
		gDivIframe.style.margin = '4px';
	}else{
		gPopFrame.src = url_msg;
	}
	
	//alert(typeof document.getElementsByTagName('body').style.maxHeight);
	var titleBarHeight = parseInt(document.getElementById("popupTitleBar").offsetHeight, 10);
	//gDivIframe.style.width = (parseInt(document.getElementById("popupTitleBar").width, 10)-10) + "px";
	gDivIframe.style.height = (height) + "px";
	gPopupContainer.style.width = width + "px";
	gPopupContainer.style.height = parseInt(document.getElementById('popupInner').offsetHeight) + parseInt(titleBarHeight) + "px";

	//document.getElementById("popupTitleBar").style.top = (height + 1) + "px";


	gReturnFunc = returnFunc;
	if (gHideSelects == true) {
		hideSelectBoxes();
	}

}

//var gi = 0;
function centerPopWin() {
	if (gPopupIsShown == true) {
		

		

		var fullHeight = obtenerViewPort().alto;
		var fullWidth = obtenerViewPort().ancho;
		//var scLeft,scTop;
		//scLeft = obtenerScroll().left;
		//scTop = obtenerScroll().top;
		//gPopupMask.style.height = (fullHeight) + "px";
		//gPopupMask.style.width = fullWidth + "px";
		//gPopupMask.style.top = scTop + "px";
		//gPopupMask.style.left = scLeft + "px";
		//window.status = gPopupMask.style.top + " " + gPopupMask.style.left + " " + gi++;
		

	/*$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(typeof document.body.style.maxHeight === "undefined")) { // take away IE6
		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}*/

		var topMargin = ((fullHeight - (gPopupHeight + 20)) / 2);
		topMargin = (topMargin < 0) ? 0 : topMargin;
		gPopupContainer.style.top = topMargin + "px";
		gPopupContainer.style.left =  ((fullWidth - gPopupWidth) / 2) + "px";	
	}
}

window.onresize = centerPopWin;
window.onscroll = centerPopWin;

/*function obtener_scroll(tipo_scroll) {
	var h = 0, v = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		v = window.pageYOffset;
		h = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		v = document.body.scrollTop;
		h = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		v = document.documentElement.scrollTop;
		h = document.documentElement.scrollLeft;
	}
	
	if(tipo_scroll == 'v'){
		return v;
	}else{
		return h;
	}
}

/**
 * Sets the size of the popup mask.
 

function setMaskSize() {	 
var theBody = document.getElementsByTagName("body").item(0); 
	 
var fullHeight = obtenerViewPort().alto;
var fullWidth = obtenerViewPort().ancho;	 
	 
// Determine what's bigger, scrollHeight or fullHeight / width	 
if (fullHeight > theBody.scrollHeight) {	 
popHeight = fullHeight;	 
} else {	 
popHeight = theBody.scrollHeight;	 
}	 
	 
if (fullWidth > theBody.scrollWidth) {	 
popWidth = fullWidth;	 
} else {	 
popWidth = theBody.scrollWidth;	 
}	 
	 
//gPopupMask.style.height = fullHeight + "px";	 
//gPopupMask.style.width = popWidth + "px";	 
}

/**
 * @argument callReturnFunc - bool - determines if we call the return function specified
 * @argument returnVal - anything - return value 
 */
function hidePopWin(callReturnFunc) {
	gPopupIsShown = false;
	restoreTabIndexes();
	if (gPopupMask == null) {
		return;
	}
	gPopupMask.style.display = "none";
	fade('none');
	//gPopupContainer.style.display = "none";
	if (callReturnFunc == true && gReturnFunc != null) {
		gReturnFunc(window.frames["popupFrame"].returnVal);
	}
	//gPopFrame.src = gLoading;
	// display all select boxes
	
	if (typeof document.body.style.maxHeight === "undefined"){
		scrollFixIE6('');
	}
	
	
	if (gHideSelects == true) {
		displaySelectBoxes();
	}
}

/**
 * Sets the popup title based on the title of the html document it contains.
 * Uses a timeout to keep checking until the title is valid.
 
function setPopTitle() {
	return;
	if (window.frames["popupFrame"].document.title == null) {
		window.setTimeout("setPopTitle();", 10);
	} else {
		document.getElementById("popupTitle").innerHTML = window.frames["popupFrame"].document.title;
	}
}


function keyDownHandler(e){

	var event = (e) ? e : window.event;
	var keyID = event.keyCode;

	if(gPopupIsShown){
	
		switch(keyID){
			case 9:
				return false;
			break;
			case 13:
				hidePopWin(false);
				return false;
			break;
			case 27:
				hidePopWin(false);
				return false;
			break;
		
		}
	
	}

}*/

// For IE.  Go through predefined tags and disable tabbing into them.
function disableTabIndexes() {
	if (document.all) {
		var i = 0;
		for (var j = 0; j < gTabbableTags.length; j++) {
			var tagElements = document.getElementsByTagName(gTabbableTags[j]);
			for (var k = 0 ; k < tagElements.length; k++) {
				gTabIndexes[i] = tagElements[k].tabIndex;
				tagElements[k].tabIndex="-1";
				i++;
			}
		}
	}
}

function scrollFixIE6(modo){
	if (typeof document.body.style.maxHeight === "undefined"){
		try{
			document.getElementsByTagName('html').item(0).style.overflow = modo;
		}catch(e){
			document.getElementsByTagName('body').item(0).style.overflow = modo;
		}
	}
}

// For IE. Restore tab-indexes.
function restoreTabIndexes() {
	if (document.all) {
		var i = 0;
		for (var j = 0; j < gTabbableTags.length; j++) {
			var tagElements = document.getElementsByTagName(gTabbableTags[j]);
			for (var k = 0 ; k < tagElements.length; k++) {
				tagElements[k].tabIndex = gTabIndexes[i];
				tagElements[k].tabEnabled = true;
				i++;
			}
		}
	}
}


/**
 * Hides all drop down form select boxes on the screen so they do not appear above the mask layer.
 * IE has a problem with wanted select form tags to always be the topmost z-index or layer
 *
 * Thanks for the code Scott!
 */
function hideSelectBoxes() {
  var x = document.getElementsByTagName("select");

  for (i=0;x && i < x.length; i++) {
    x[i].style.visibility = "hidden";
  }
}

/*function addEvent(obj, evType, fn){
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, false);
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else {
		return false;
	}
}*/

/**
 * Makes all drop down form select boxes on the screen visible so they do not 
 * reappear after the dialog is closed.
 * 
 * IE has a problem with wanting select form tags to always be the 
 * topmost z-index or layer.
 */
function displaySelectBoxes() {
  var x = document.getElementsByTagName("select");

  for (i=0;x && i < x.length; i++){
    x[i].style.visibility = "visible";
  }
}

/*function getViewportHeight() {
	if (window.innerHeight!=window.undefined) return window.innerHeight;
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientHeight;
	if (document.body) return document.body.clientHeight; 
	return window.undefined; 
}

function getViewportWidth() {
	if (window.innerWidth!=window.undefined) return window.innerWidth; 
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientWidth; 
	if (document.body) return document.body.clientWidth; 
	return window.undefined; 
}

	function getScrollBarWidth () {
		var inner = document.createElement('p');
		inner.style.width = "100%";
		inner.style.height = "200px";
		var outer = document.createElement('div');
		outer.style.position = "absolute";
		outer.style.top = "0px";
		outer.style.left = "0px";
		outer.style.visibility = "hidden";
		outer.style.width = "200px";
		outer.style.height = "150px";
		outer.style.overflow = "hidden";
		outer.appendChild (inner);
		document.body.appendChild (outer);
		var w1 = inner.offsetWidth;
		outer.style.overflow = 'scroll';
		var w2 = inner.offsetWidth;
		if (w1 == w2) w2 = outer.clientWidth;
		document.body.removeChild (outer);
		return (w1 - w2);
	};*/
	
	function obtenerScroll(){
		return{
			top : Math.max(self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop),
			left : Math.max(self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft)
		}
	}
	
	function obtenerViewPort() {
		return {
			alto : Math.max(window.innerHeight || document.documentElement.clientHeight || document.getElementsByTagName('body').item(0).clientHeight),
			ancho : Math.max(window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body').item(0).clientWidth)
		}
	}
