function newWindow(mypage, myname, w, h, scroll) {
     var winLeft = (screen.width - w) / 2;
     var winTop = (screen.height - h) / 2;
     winProps = "height=" + h + ",width=" + w + ",top=" + winTop + ",left=" + winLeft + "," + scroll;
     win = window.open(mypage, myname, winProps);
     if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
     return win;
}

var posicX =0;
var posicY =0;

Event.observe(document, 'mousemove', get_mouse_xy);

function get_mouse_xy(e) {
	posicX = Event.pointerX(e) + 10;
	posicY = Event.pointerY(e) + 12;
	return true;
}

function showToolTip(text){
	idToolTip = "toolTip";
	w = Math.min((text.length * 5),250);
	//w = 300;
	if(!document.getElementById(idToolTip)){
		divholder = document.createElement("div");
		divholder.id = idToolTip;
		divholder.style.display = 'none';
		divholder.style.width = w + 'px';
		divholder.style.height = "auto";
		divholder.style.border = "1px solid #CCCCCC";
		divholder.style.backgroundColor = "#FCFCBD";
		divholder.style.position = "absolute";
		divholder.style.color = "#222222";
		divholder.style.padding = "2px";
		divholder.style.fontSize = "10px";
		divholder.style.zIndex = "200";
		document.body.appendChild(divholder);
	}else{
		divholder = document.getElementById(idToolTip);
		divholder.style.width = w + 'px';
	}
	x = posicX;
	y = posicY;
	if(document.body.offsetWidth < posicX+w+20){
		x = document.body.offsetWidth - (w+20);
	}

	divholder.style.left = x+"px";
	divholder.style.top = y+"px";
	document.getElementById(idToolTip).innerHTML = ""+text+"";
	document.getElementById(idToolTip).style.visibility = "visible";
	document.getElementById(idToolTip).style.display = "";
}


function hideToolTip(){
	document.getElementById("toolTip").style.visibility = "hidden";
}

function showDivDateChoose(form,campo){
	idDiv = "DateChoose";
	w = 300;
	if(!document.getElementById(idDiv)){
		divholder = document.createElement("div");
		divholder.id = idDiv;
		divholder.style.width = "auto";
		divholder.style.height = "auto";
		divholder.style.position = "absolute";
		divholder.style.zIndex = "200";
		document.body.appendChild(divholder);
	}else{
		divholder = document.getElementById(idDiv);
	}

	arr = Position.cumulativeOffset(document.f.elements[campo]);
	x = arr[0] + 110;
	y = arr[1] - 40;
	divholder.style.left = x+"px";
	divholder.style.top = y+"px";

	var texts = getTextsDateChooser();
 	content = 	"<div id='dateChooseContent'>";
 	content += 	"<ul>";
	content += 	"<li class='sigue hand'><a href='javascript:showCalendar(\""+form+"\",\""+campo+"\");javascript:hideDivDateChoose();'>"+texts[0]+"</a></li>";
	content += 	"<li class='sigue hand'><a href='javascript:hideDivDateChoose();'>"+texts[1]+"</a></li>";
	content += 	"</ul>";

	content += 	"<ul>";
	content += 	"<li class='sign'><a href='javascript:addDayToDate(-1,\""+form+"\",\""+campo+"\");'><b>-</b></a></li>";
	content += 	"<li><a href='javascript:calculateDate(0,\""+form+"\",\""+campo+"\");javascript:hideDivDateChoose();'>"+texts[2]+"</a></li>";
	content += 	"<li class='sign'><a href='javascript:addDayToDate(1,\""+form+"\",\""+campo+"\");'><b>+</b></a></li>";
	content += 	"</ul>";

	content += 	"<ul>";
	content += 	"<li class='sign'><a href='javascript:addDayToDate(-7,\""+form+"\",\""+campo+"\");'><b>-</b></a></li>";
	content += 	"<li class='semana'>"+texts[3]+"</li>";
	content += 	"<li class='sign'><a href='javascript:addDayToDate(7,\""+form+"\",\""+campo+"\");'><b>+</b></a></li>";
	content += 	"</ul>";
	content += 	"<div style='clear:both;'></div>";
	content += 	"</div>";
	content += 	"";
	document.getElementById(idDiv).innerHTML = ""+content+"";
	if(Effect){
		Effect.Appear(idDiv);
	}else{
		document.getElementById(idDiv).style.visibility = "visible";
	}
}

function getTextsDateChooser(){
	var lang = getCookie('lang');
	if (lang == '' || lang == undefined){
		lang = 'es';
	}
	if (lang == 'es'){
		texts = new Array('Elegir','Cerrar','Hoy','Semana');
	}else if (lang == 'eu'){
		texts = new Array('Aukeratu','Itxi','Gaur','Astea');
	}else if (lang == 'en'){
		texts = new Array('Choose','Close','Today','Week');
	}else {
		texts = new Array('Choose','Close','Today','Week');
	}
	return texts;
}


function hideDivDateChoose(){
	if(!$('DateChoose')) return;
	if(Effect){
		Effect.DropOut("DateChoose");
	}else{
		document.getElementById("DateChoose").style.visibility = "hidden";
	}
}

function calculateDate(dif,form,campo){
	MINUTE = 60 * 1000;
 	HOUR = MINUTE * 60;
 	DAY = HOUR * 24;


	today = (new Date()).getTime();
 	newFecha = new Date(today + (DAY * (dif)));
 	newFechaFormat = newFecha.getDate() + '-' + (newFecha.getMonth()+1) + '-' + (newFecha.getFullYear());

	setDate(form,campo,newFechaFormat);
}

function addDayToDate(dif,form,campo){
	MINUTE = 60 * 1000;
 	HOUR = MINUTE * 60;
 	DAY = HOUR * 24;

	elInputVal = eval("document." + form + "['" + campo + "'].value");
	if (elInputVal == ''){
		today = (new Date()).getTime();
	}else{
		fecha = elInputVal.split("-");
		d = fecha[0];
		m = fecha[1]-1;
		y = fecha[2];
		today = (new Date(y,m,d)).getTime();
	}
 	newFecha = new Date(today + (DAY * (dif)));
 	newFechaFormat = newFecha.getDate() + '-' + (newFecha.getMonth()+1) + '-' + (newFecha.getFullYear());

	setDate(form,campo,newFechaFormat);
}

function changeHeightTextArea(elName,inc)
{
	if(document.getElementById(elName +'___Frame')){
		var oEditor = FCKeditorAPI.GetInstance(elName).EditorWindow.parent;
		
		var actualHeight = oEditor.innerHeight;		
		
		document.getElementById(elName + '___Frame').style.height = actualHeight + inc +'px';
		return;
		
	}else{
		var tArea = document.getElementById(elName);
		var actualHeight = parseInt(tArea.getHeight());
	
		if(actualHeight <= 60 && inc < 0) return;
		if((actualHeight + inc) < 60) inc = 60 - actualHeight;
		if(Effect){
			// cual es el porcentaje de los pixeles a mover?
			var porcentaje = 100 + ((inc * 100) / (Math.max(50,actualHeight)));
			
			var test = new Effect.Scale(tArea, porcentaje, Object.extend({ scaleContent: false, scaleX: false, scaleMode: 'contents'}, {duration:0.2}));
		}else{
			tArea.style.height = actualHeight + inc +'px';
		}
	}
	
	
}

function setActiveStyleSheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
}

var detect = navigator.userAgent.toLowerCase();

function checkItDedolib(string)
{
	place = detect.indexOf(string) + 1;
	return place;
}

function clickDiaCalMini(idTd){
	s.ejecuta('agenda');
}
function clickDiaCalSearch(idTd){
	document.f.fechaCal.value = idTd;
	s.ejecuta('buscarPublic');
}


var idEnRoll = -1;
var classEnRoll = '';

function rollOverDiaCalMini(idTd){
	return;
}


var isExplorer=checkItDedolib('msie');
function validaMouseOut(elem){
		if(isExplorer){
			if (!e) var e = window.event;
			if (e.target) tg = e.target;
			else if (e.srcElement) tg = e.srcElement;
			var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
			if(!reltg) return false;
			while (reltg.className != elem.className && reltg.nodeName != 'BODY'){
					if(reltg.parentNode==null) return false;
					reltg= reltg.parentNode;
			}
			if (reltg.className == elem.className) return false;
		}
		return true;
}

///////////////////////////////////////////////////////////////////////////
// MOVESELECTBOX
///////////////////////////////////////////////////////////////////////////
function moveFromTo(fbox,tbox){
	for(var i=0; i<fbox.options.length; i++) {
		if(fbox.options[i].selected && fbox.options[i].value != "") {
			var no = new Option();
			no.value = fbox.options[i].value;
			no.text = fbox.options[i].text;
			tbox.options[tbox.options.length] = no;
			fbox.options[i] = null;
      		i--;
   		}
	}
	SortD(tbox);
	if(fbox.name.substr(fbox.name.length-5,100) == 'Out[]'){
		changed(tbox);
	}else{
		changed(fbox);
	}
}


function SortD(box)  {
	var temp_opts = new Array();
	var temp = new Object();
	for(var i=0; i<box.options.length; i++)  {
		temp_opts[i] = box.options[i];
	}
	
	temp_opts.sort(function (a,b) {
				if((a.text.toUpperCase()) < (b.text.toUpperCase())){
					return -1;
				}
				if((a.text.toUpperCase()) > (b.text.toUpperCase())){
					return 1;
				}
				return 0;
		});
	
	box.options.length = 0;
	for(var i=0; i<temp_opts.length; i++)  {
		box.options[i] = temp_opts[i];
	}
}

///////////////////////////////////////////////////////////////////////////
// END MOVESELECTBOX
///////////////////////////////////////////////////////////////////////////


function showDialog(texto)
{
	Dialog.alert(texto,{windowParameters: {className:'alphacube',showEffectOptions:{duration:0.2},width:300, height:100}, okLabel: 'OK',ok:function(win) { return true;}});
}


/* PROTOTYPE EXTENDS */

Object.extend(Ajax.Autocompleter.prototype, {
  initialize: function(element, update, url, options) {
    this.baseInitialize(element, update, options);
    this.options.asynchronous  = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
    this.url                   = url;
  	this.options.onNoresults = this.options.onNoresults || function(element, update){ return; };
  },

  onObserverEvent: function() {
    this.changed = false;

    if(this.getToken().length>=this.options.minChars) {
      this.startIndicator();
      this.getUpdatedChoices();
    } else {
      //this.options.onNoResults(this.element,this.update);
      this.active = false;
      this.hide();
    }
  },

  updateChoices: function(choices) {
    if(!choices || choices == '' || choices.indexOf('no_results') != -1) this.options.onNoresults(this.element,this.update);
  	if(!this.changed && this.hasFocus) {
      this.update.innerHTML = choices;
      Element.cleanWhitespace(this.update);
      Element.cleanWhitespace(this.update.firstChild);

      if(this.update.firstChild && this.update.firstChild.childNodes) {
        this.entryCount =
          this.update.firstChild.childNodes.length;
        for (var i = 0; i < this.entryCount; i++) {
          var entry = this.getEntry(i);
          entry.autocompleteIndex = i;
          this.addObservers(entry);
        }
      } else {
        this.entryCount = 0;
      }


      this.stopIndicator();

      this.index = 0;
      this.render();
    }
  },
  onBlur: function(event) {
    // needed to make click events working
    setTimeout(this.hide.bind(this), 250);
    this.hasFocus = false;
    this.active = false;
    if(this.element.value == ''){
    	this.options.onNoresults(this.element,this.update);
    }
  },
  onComplete: function(request) {
    //alert(request.responseText);
    this.updateChoices(request.responseText);
  }
});



document.getElementsByAttribute = function(attribute, value, tagName, parentElement) {
	var children = ($(parentElement) || document.body).getElementsByTagName((tagName || '*'));
	return $A(children).inject([], function(elements, child) {
		var attributeValue = child.getAttribute(attribute);
		if(attributeValue != null) {
			if(!value || attributeValue == value) {
				elements.push(child);
			}
		}
		return elements;
	});
}

function procesaAccesibleValuesForm()
{
	var els = $$('.accesibleVal');
	els.each(function(value, index) {
      var element = els[index];
      
      element.startValue = element.value;
      Element.addClassName(element,'accesibleValFocus');
		element.onfocus = function(){
			if (element.value == element.startValue){
				element.value = "";
				//element.style.color='#000000';
				Element.removeClassName(element,'accesibleValFocus');
			}
		};
		element.onblur = function(){
			if (element.value == ''){
				element.value = element.startValue;
				//element.style.color='#747373';
				Element.addClassName(element,'accesibleValFocus');
			}
		};
    });
}

function initMap(lat, lon, dirOverlay, mapId,showScala,showTipoMapa)
{
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById(mapId));
	
		map.setCenter(new GLatLng(lat, lon), 14);
		if(showScala){
			map.addControl(new GLargeMapControl());
		}else{
			map.addControl(new GSmallMapControl());
		}
		if(showTipoMapa){
			map.addControl(new GMapTypeControl());
		}
		
		var point = new GLatLng(lat, lon);
	
		var marker = new GMarker(point);
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(dirOverlay);
		});
		map.addOverlay(marker);
		marker.openInfoWindowHtml(dirOverlay);
	}
}


var ZebraTable = {
	bgcolor: '',
	classname: '',
	stripe: function(el) {
		if (!$(el)) return;
		
		var rows = $(el).getElementsByTagName('tr');
		for (var i=1,len=rows.length;i<len;i++) {
			rows[i].className = 'impar';
			if (i % 2 == 0) rows[i].className = 'par';
			Event.observe(rows[i], 'mouseover', function() { ZebraTable.mouseover(this); });
			Event.observe(rows[i], 'mouseout', function() { ZebraTable.mouseout(this); });
		}
	},
	mouseover: function(row) {
		this.bgcolor = row.style.backgroundColor;
		this.classname = row.className;
		row.addClassName('ruled');
	},
	mouseout: function(row) {
		row.removeClassName('ruled');
		row.addClassName(row,this.classname);
		row.style.backgroundColor = this.bgcolor;
	}
}

Event.observe(window, 'load', function() { procesaAccesibleValuesForm();});


var myrulesInit = {
		'#checkAllJS' : function(element){
			element.onclick = function(){
				var els = $$('.checkJS');
				els.each(function(value, index) {
      				var chkBox = els[index];
      				chkBox.checked = true;
				});
				return false;
			}
		},
		'#uncheckAllJS' : function(element){
			element.onclick = function(){
				var els = $$('.checkJS');
				els.each(function(value, index) {
      				var chkBox = els[index];
      				chkBox.checked = false;
				});
				return false;
			}
		},
		'#multiAccion' : function(element){
			element.onclick = function(){
				var selEl = $('multiActionSel');
				var index = selEl.selectedIndex;
    			if(index == 0){
    				alert('Seleccione una acción a realizar');
    				return false;
    			}
    			var optSelText = selEl.options[index].text;
				var msg = 'Confirme que desea <strong style="color:red;">' + optSelText + '</strong> los elementos seleccionados.';
				var accion = $F(selEl);
				var id = -1;
				Dialog.confirm(msg, 
				{windowParameters: {className:"alphacube",width:300}, okLabel: "OK", 
				buttonClass: "myButtonClass",
				id: "msgAlert",
				showEffectOptions:{duration:0.2},
				cancel:function(win) {return false;},
				ok:function(win) {
					if (accion.substr(0,5) == "print") {
						s.ejecutaInNewWindow(accion, id);
					}else{
						s.ejecuta(accion, id);
					}
					return true;
					}
				});
				return false;
			}
		},
		'.inputText' : function(element){
			$(element).setAttribute("autocomplete", "off"); 
		}
		
	};
	
Behaviour.register(myrulesInit);

