/**
 * 	Common routines
 * 	@author org.notariado.inti.bcn.MaxNoe 20040517
 *	@package Soporte
 *	@subpackage JavaScript
 *	@version ST060101
 */

window.onload = startUp;
var blankReplacement = "/resources/images/res.gif";

/**
 * This function is called at body.onLoad, so
 * if there is a function that needs to be
 * executed everytime a page is loaded, it
 * should be called here.
 */
function startUp() {

    if (typeof(window.frames[0]) != 'undefined') {
        window.frames['0'].focus();
    }
    // loadHomeflash();
	correctExternalLinks();
	correctFormElementsNames();
	initHighlight("input");
	initHighlight("textarea");
	// alphaBackground(); // para logo pc
	// setFormSubmitEvent();
	// fixPNGs();
	// setFocus();
	/*
	if (document.getElementById('sections')) {
		var mySlider = new Fx.Slide('sections', {duration: 800}).hide();
		mySlider.slideIn(); //toggle the slider up and down.
		$('sections').style.visibility = 'visible';
	}*/
	if (document.getElementById('accordion')) {
		var accordion = new Accordion('h4.atStart', 'div.atStart', {
			opacity: false,
			onActive: function(toggler, element){
				toggler.setStyle('color', '#ff3300');
			},

			onBackground: function(toggler, element){
				toggler.setStyle('color', '#222');
			}
		}, $('accordion'));
	}
	if (document.getElementById('sections')) {
		var accordionsection = new Accordion('li.expsection', 'div.expoption', {
			opacity: false, start: true,
			onActive: function(toggler, element){
				toggler.setStyle('color', '#ff3300');
			},
			onBackground: function(toggler, element){
				toggler.setStyle('color', '#222');
			}
		}, $('sections'));
		indexToShow = -1;
		stretchers = $$('li.expsection');
	    stretchers.each(function(item, i){
			//Encontrar la opción seleccionada
			if (item.getElementsByClassName("accsel").length > 0) {
				indexToShow = i; //Desplegar la sección que contenga la opción activa
			}
	    });
		if (indexToShow > -1)
		    accordionsection.showThisHideOpen(indexToShow);

	}
//	$('sections').effect('height').start(0,1000);
//	$('head').effect('height').start(0,302);
//	$('head').effect('height', {duration: 1000, transition: Fx.Transitions.linear});

	return true;
}

function alphaBackground(){
	var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
	var itsAllGood = (rslt != null && Number(rslt[1]) >= 5.5 && Number(rslt[1]) < 7);
	var bg = document.getElementById('artwork');
	if (itsAllGood && bg) {
		alert('ie5');
    	bg.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='data/media/images/logos/lpct_morado.png', sizingMethod='scale')";
    	bg.style.backgroundImage = "url('')";
	}
}

function initSlider(divname) {
	return new Fx.Slide(divname, {duration: 800})
}

function makeToglee(divname, elemSlider) {
	if (document.getElementById(divname)) {
		if ($(divname).style.visibility == 'hidden') {
			elemSlider.hide();
			elemSlider.slideIn(); // toggle the slider up and down.
			$(divname).style.visibility = 'visible';
		} else {
			elemSlider.toggle(); // toggle the slider up and down.
		}
	}
}


function loadHomeflash() {
	// Original 640x180  //
	return;
	if (document.getElementById('flashwork')) {
	    var so = new SWFObject("data/media/flash/layout/abs15.swf", "titulo", "760px", "215px", "6.0.0", "#FFFFFF");
	    so.addParam("quality", "high");
	    so.addParam("allowScriptAccess", "sameDomain");
	    so.addParam("wmode", "transparent");
	    so.write("flashwork");
	}
}

function setFormSubmitEvent() {
	var forms = document.getElementsByTagName('form');
	if (forms.length > 0) {
		alert('hay formulario, activando evento onsubmit');
		if (forms[0].addEventListener) {
			alert('añadiendo listener');
			forms[0].addEventListener('submit', function() {return activeOperationSign()}, false);
		} else {
			alert('añadiendo evento');
			forms[0].onsubmit = function() {return activeOperationSign()};
		}
	}
/*
	var form = document.forms[0];
	if (form)
		form.addEventListener('submit',function(e) {
			activeOperationSign();
		},true);
*/
}


/**
 * Make form field emphasized when has
 * onfocus event
 */
function initHighlight(tagnames) {
    if (!document.getElementsByTagName) { return; }
    var allfields = document.getElementsByTagName(tagnames);

    // loop through all input tags and add events
    for (var i=0; i<allfields.length; i++) {
        var field = allfields[i];
        if ((field.getAttribute("type") == "text") || (field.getAttribute("type") == "password") || tagnames == "textarea") {
            field.onfocus = function () {
				this.style.border = '1px solid #ff0e0e';
				this.style.borderLeft = '1px solid #ff0e0e';
			}
            field.onblur = function () {
            	this.style.border = '1px solid #284279';
            }
        }
    }
}




/**
 * Forces the external links to open in a new
 * window, in a manner that validates against
 * XHTML Strict. This last one does not allow
 * 'target="_blank"' anymore, but the DOM does.
 */
function correctExternalLinks() {

	// run through every a tag in the document
	var serverName = window.location.hostname;
	var outBound;
	for (var index = 0; index <= (document.links.length - 1); index++) {
		var linkElement = document.links[index];

		// any links not containing the current server name are outbound.
		outBound = ((linkElement.href.indexOf(serverName) < 0) && (linkElement.href.indexOf('javascript') != 0)) ||
				   linkElement.className.indexOf('newwindow') >= 0;
		if (outBound) {
			linkElement.target = "_blank";
		} else {
			linkElement.target = "";
		}

	}

	return true;
}

/**
 * Sets the focus at the first form's first field.
 */
function setFocus() {
	if (document.forms[0]) {
		var editableTypes = {checkbox:"", "select-one":"", text:"", textarea:"", radio:""};
		var formElements = document.forms[0].elements;
		for (var index = 0; index < formElements.length; index++) {
			if ((formElements[index].type in editableTypes) && (!formElements[index].disabled)) {
				formElements[index].focus();
				break;
			}
		}
	}

	return true;
}

/**
 * Prints the current page.
 */
function printPage() {
	if (window.print) {
		window.print();
	} else {
		alert("Su navegador no permite imprimir esta página.");
	}
}

/**
 * Do an action
 */
function doAction(action) {
	window.location.href = '?do=' + action;
}

function doWebAction(action) {
	window.location.href = '?do=' + action;
}



function doConfirmActionForm(action, msg, required) {
	if (confirm(msg)) {
		document.forms[0].action = '?do=' + action;
		validateAndSubmit(required);
	} else
		return void(0);
}

/**
 *   Events page
 */
function doEventAction(id, month, page) {
	if (id) document.forms[0].id.value=id;
	if (month) document.forms[0].month.value=month;
	if (page) document.forms[0].page=page;
	document.forms[0].submit();
}

/**
 *   Open a new window
 */
function openWindow(url) {

	var top = 0;
	var left = 0;
	if(navigator.appVersion.indexOf("MSIE")!=-1){
		top  = window.screenTop + 20;
		left = window.screenLeft + 20;
	}else{
	 	top  = window.screen.top + 40;
    	left = window.screen.left + 40;
    }
    var widthWindow = 640;
	var heightWindow = 290;
   	params = "toolbar=yes,location=no, status=yes,menubar=no,scrollbars=yes, width=708,height=580, left = " + left + ", top = " + top + ", resizable=yes";
	myWindow  =  window.open(url,'App',params);
}

/*
 * Routine to correct IE's PNGs transparency.
 */
function fixPNGs() {
	if ((navigator.userAgent.match(/MSIE/).length > 0) && navigator.platform == "Win32") {
		for (var index = 0; index < document.images.length; index++) {
			element = document.images[index];

			// get src
			var src = element.src;

			// If the image is still unprocessed...
			if (src != blankReplacement) {
				// ... check if it is a PNG...
				if ( /\.png$/.test(src.toLowerCase())) {
					// ... take note of the size...
					var width = element.width;
					var height = element.height;
					// ... replace image with a blank one...
					element.src = blankReplacement;
					// ... set its size...
					element.width = width;
					element.height = height;
					// ... and, finally, show the filtered image.
					element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" +
					src + "',sizingMethod='none')";
				}
			}

		}
	}
}

/*
 * Ensures that each element in a form
 * has a name, copying it from the id,
 * if none found. This yields future
 * compatibility with XHTML1.1.
 */
function correctFormElementsNames() {

    forms = document.forms;
	for (var index = 0; index < forms.length; index++) {
		var currentForm = forms[index];
		for (var elementIndex = 0; index < currentForm.elements.length; elementIndex++) {
			var formElement = currentForm.elements[elementIndex];
			if (formElement) {
				if ((formElement.name == "") && (formElement.id != "")) {
					formElement.name = formElement.id;
				} else if ((formElement.name != "") && (formElement.id == "")) {
					formElement.id = formElement.name;
				}
			} else {
				// If formElement is undefined, somehow the loop
				// restarts and enters an infinite loop.
				break;
			}
		}
	}

	return true;
}

function setOperationSign(mode) {
	var ajaxOperationSign = document.getElementById('ajax-operation');
	if (ajaxOperationSign) {
		var transparentLayer = document.getElementById('transparent-layer');
		if (transparentLayer) {
			var sizeWin = WindowUtilities.getPageSize();
			transparentLayer.style.left = (0 + (sizeWin.scrollWidth))  + 'px';
	    	transparentLayer.style.top  = (0 + (sizeWin.scrollHeight)) + 'px';
			transparentLayer.style.width   = sizeWin.windowWidth  + 'px';
			transparentLayer.style.height  = sizeWin.windowHeight + 'px';
			transparentLayer.style.display = mode;
			ajaxOperationSign.style.left = ((sizeWin.windowWidth  / 2) - 134 + (sizeWin.scrollWidth))  + 'px';
	    	ajaxOperationSign.style.top  = ((sizeWin.windowHeight / 2) - 100 + (sizeWin.scrollHeight)) + 'px';
			ajaxOperationSign.style.display = mode;
		}
	}
}

function activeOperationSign() {
	setOperationSign('block');
}

function deactiveOperationSign() {
	setOperationSign('none');
}

/***********************************************
* Bookmark site script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

/* Modified to support Opera */
function bookmarksite(title,url){
	if (window.sidebar) // firefox
		window.sidebar.addPanel(title, url, "");
	else if(window.opera && window.print){ // opera
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	}
	else if(document.all)// ie
		window.external.AddFavorite(url, title);
}


// Se utilizaba cuando se abría el mapa desde la ficha notarial
function showFrame(url, name, param) {
	var wWin = 480;
	var hWin = 570;
	var leftW = (screen.width - wWin) / 2;
	var topW  = (screen.height - hWin) / 2;
	var params = "toolbar=no,location=no, status=no,menubar=no,scrollbars=yes, resizable=no, titlebar=no, width=" + wWin + ", height=" + hWin + ", left=" + leftW + ",top=" + topW;
	if (param) url = url + '&param=' + param;
    window.open(url, name, params);
}


var WindowUtilities = {
  // From script.aculo.us
  getWindowScroll: function() {
    var w = window;
      var T, L, W, H;
      with (w.document) {
        if (w.document.documentElement && documentElement.scrollTop) {
          T = documentElement.scrollTop;
          L = documentElement.scrollLeft;
        } else if (w.document.body) {
          T = body.scrollTop;
          L = body.scrollLeft;
        }
        if (w.innerWidth) {
          W = w.innerWidth;
          H = w.innerHeight;
        } else if (w.document.documentElement && documentElement.clientWidth) {
          W = documentElement.clientWidth;
          H = documentElement.clientHeight;
        } else {
          W = body.offsetWidth;
          H = body.offsetHeight
        }
      }
      return { top: T, left: L, width: W, height: H };

  },
  //
  // getPageSize()
  // Returns array with page width, height and window width, height
  // Core code from - quirksmode.org
  // Edit for Firefox by pHaez
  //
  getPageSize: function(){
  	var xScroll, yScroll;

  	if (window.innerHeight && window.scrollMaxY) {
  		xScroll = document.body.scrollWidth;
  		yScroll = window.innerHeight + window.scrollMaxY;
  	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
  		xScroll = document.body.scrollWidth;
  		yScroll = document.body.scrollHeight;
  	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
  		xScroll = document.body.offsetWidth;
  		yScroll = document.body.offsetHeight;
  	}

  	var windowWidth, windowHeight;

  	if (self.innerHeight) {	// all except Explorer
  		windowWidth = self.innerWidth;
  		windowHeight = self.innerHeight;
        scrollX = window.pageXOffset;
        scrollY = window.pageYOffset;
  	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
  		windowWidth = document.documentElement.clientWidth;
  		windowHeight = document.documentElement.clientHeight;
        scrollX = document.documentElement.scrollLeft;
        scrollY = document.documentElement.scrollTop;
  	} else if (document.body) { // other Explorers
  		windowWidth = document.body.clientWidth;
  		windowHeight = document.body.clientHeight;
        scrollX = window.pageXOffset;
        scrollY = window.pageYOffset;
  	}
  	var pageHeight, pageWidth;

  	// for small pages with total height less then height of the viewport
  	if(yScroll < windowHeight){
  		pageHeight = windowHeight;
  	} else {
  		pageHeight = yScroll;
  	}

  	// for small pages with total width less then width of the viewport
  	if(xScroll < windowWidth){
  		pageWidth = windowWidth;
  	} else {
  		pageWidth = xScroll;
  	}

  	return {
        pageWidth: pageWidth ,
        pageHeight: pageHeight ,
        windowWidth: windowWidth,
        windowHeight: windowHeight,
        scrollWidth: scrollX,
        scrollHeight: scrollY

    };
  }

}