/*
********************************************************************************************
From : http://stuffledge.blogspot.com/2007/08/getelementsbyname-una-ms-la-lista.html

*/

function elementsByName(tag, name) 
{
     var elem = document.getElementsByTagName(tag);
     var arr = new Array();
     for(i = 0,iarr = 0; i < elem.length; i++)
     {          
        att = elem[i].getAttribute("name");
          if(att == name)
          {
               arr[iarr] = elem[i];
               iarr++;          
          }     
     }     
     return arr;
}

function elementsByClass(tag,name)
{
    var elem = document.getElementsByTagName(tag);
    var arr = new Array();
    var n = 0;
    for(i = 0,iarr = 0; i < elem.length; i++)
     {          
        if (elem[i].className.indexOf(name) > -1) 
        {
            arr[n++] = elem[i];
        }
     }     
     return arr;
}


/*
********************************************************************************************
From : 

*/

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); 
   //alert('r : on' + evType)
   return r; 
 } else { 
   return false; 
 } 
}

function removeEvent(obj, evType, fn){ 
 if (obj.removeEventListener){ 
   obj.removeEventListener(evType, fn, false); 
   return true; 
 } else if (obj.deattachEvent){ 
   var r = obj.deattachEvent("on"+evType, fn); 
   //alert('r : on' + evType)
   return r; 
 } else { 
   return false; 
 } 
}

/********************************************************************************************

*/
function mousePos(e)
{
    var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	// posx and posy contain the mouse position relative to the document
	// Do something with this information
	document.getElementById('luser').value = posx;    
	document.getElementById('lpass').value = posy;
	var pos = new Array(posx,posy);
	return pos;
}

function trackMouse()
{
    addEvent(document,'mousemove',mousePos);
}

function untrackMouse()
{
    removeEvent(document,'mousemove',mousePos);
}

/*
********************************************************************************************
INCLUDES

*/
// Function to allow one JavaScript file to be included by another.
// Copyright (C) 2006 www.cryer.co.uk
function include(jsFile)
{
  /*document.write('<script type="text/javascript" src="'
    + jsFile + '"></script>'); */
    var ojs = document.createElement('script');
    ojs.setAttribute('type','text/javascript');
    ojs.setAttribute('language','javascript');
    ojs.setAttribute('src',jsFile);
    
    var ahead = document.getElementsByTagName('head');
    ahead[0].appendChild(ojs);
    
}

//include('js/console.js');

//exemples
//addEvent(window, 'load', foo);
//addEvent(window, 'load', bar);

/*
************************************************************************************************
Pels DataInputs
*/

function any_traspas(any)
{
	if ((any % 4 == 0) && ((any % 100 != 0) || (any % 400 == 0)))
	{
		return true;
	}else{
		return false;
	}
}

function data_actualitza(id)
{
	var ot = document.getElementById(id);
	var oh = document.getElementById(id + '_h');
	var dia = document.getElementById(id + '_dia').value;
	var mes = document.getElementById(id + '_mes').value;
	var any = document.getElementById(id + '_any').value;

	//corregim dates impossibles
	var ams = [31,28,31,30,31,30,31,31,30,31,30,31];
	if (any_traspas(any))
	{
		ams[1] = 29;
	}
	if ( dia > ams[mes-1] )
	{
		dia = ams[mes-1];
	}
	
	ot.value = dia + '/' + mes + '/' + any;
	oh.value = dia + '/' + mes + '/' + any;
}

/*******************************************************************************************/
//només permet números als camps de text
function validarNum(e)
{
    tecla = (document.all) ? e.keyCode : e.which;
    if (tecla == 8) return true;
    patron = /\d/;
    te = String.fromCharCode(tecla);
    return patron.test(te);
}


/*****************************************************************************************
 ______       __     ______     __  __    
/\  __ \     /\ \   /\  __ \   /\_\_\_\   
\ \  __ \   _\_\ \  \ \  __ \  \/_/\_\/_  
 \ \_\ \_\ /\_____\  \ \_\ \_\   /\_\/\_\ 
  \/_/\/_/ \/_____/   \/_/\/_/   \/_/\/_/ 

******************************************************************************************/

/*************************************************

		AJAX

        Dani HeadMaster 2007 from empunyando.com

***************************************************/
		    //variable  clobal que conté l'objecte d'ajax
		    //var repReq = getAjaxObj();
            var repReq;
		    
		    //amb aixó montem la cadena de post amb el formulari
		    function getFormValues(fobj,valFunc)
		     {			
			var str = "";
			var valueArr = null;
			var val = "";
			var cmd = "";
			for(var i = 0;i < fobj.elements.length;i++)
			{
				switch(fobj.elements[i].type)
				{
				case "text":
					{
						//use single quotes for argument so that the value of			
						//fobj.elements[i].value is treated as a string not a literal			
						cmd = valFunc + "(" + 'fobj.elements[i].value' + ")";
						val = eval(cmd);
					}
			
					str += fobj.elements[i].name + "=" + escape(fobj.elements[i].value) + "&";
					break;
			
				case "select-one":
					str += fobj.elements[i].name + "=" + fobj.elements[i].options[fobj.elements[i].selectedIndex].value + "&";
					break;
				}
			}
			str = str.substr(0,(str.length - 1));
			return str;
			}	
		//capturar l'objecte
		
		//amb aixó escollim el component 
			function getObj()
			{
				var xh = null;
				try
				{
				//firefox, opera, KHTML
				xh =new XMLHttpRequest();	
				} catch(e)
					{
						//IE
						try
						{
						xh =new ActiveXObject("Msxml12.XMLHTTP");	
						}catch(e)
							{
								try{
									xh =new ActiveXObject("Microsoft.XMLHTTP")								
									}catch(e)
									{
										alert("El teu navegador no té suport per Ajax!");
										return false;	
									}
							}
					}
					
					return xh;		
					
			}
		
             function getAjaxObj()
             {
                if (window.XMLHttpRequest)
                {
                    return XMLHttpRequest; //NOT IE                    
                }else if (window.ActiveXObject)
                {
                    return new ActiveXObject("Microsoft.XMLHTTP");  //IE
                }else{
                    //navegadors que no suporten l'objecte
                    alert('El teu navegador no és compatible amb AJAX');
                    return false;
                }                
             }
             
             
      
/***********************************************************************************************/	
            var rDiv = '';
            //gestiona la resposta
             function handleReq()
             {
             	//alert('hem rebut');
                //comprobem que la connexió ha acabat
                if ( repReq.readyState == 4 )
                {
                    //posem el contingut a l'span
                    //alert(repReq.responseText);
                    document.getElementById(rDiv).innerHTML = repReq.responseText;
		            document.getElementById(rDiv).style.visibility = 'visible';	
                    //document.meuform.resposta.value = repReq.responseText;   
                    
                    //per si ha saltat el loading
                    no_loading();                                    
                }
                
             }

	
		    //amb aquesta crido un script asp i poso la resposta en una div 'situacio'
		    function cridaiposa(pagina,situacio)
		    {
		        rDiv = situacio;
		        repReq = getObj();
		        //alert();
                if ( repReq.readyState == 4 || repReq.readyState == 0 )
                {
                    //configurem la funció que gestiona l'enllaç quan canvia
                    repReq.onreadystatechange = handleReq;                	
                    //configurem la connexió com un  GET
					//el "true" expecifica que es asíncrona ( opció per defecte)
                    repReq.open('GET',pagina,true);
                    //repReq.open('POST','temps.php',true);
                    //fem el request al servidor
                    repReq.send(null);                    
                }
		    }
		    
		    function cridaiposa_post(pagina,situacio,qstring)
		    {
		        rDiv = situacio;
		        repReq = getObj();
             	//alert();
                if ( repReq.readyState == 4 || repReq.readyState == 0 )
                {
                	//configurem la funció que gestiona l'enllaç quan canvia
                    repReq.onreadystatechange = handleReq;                	
                    //configurem la connexió com un  GET
					//el "true" expecifica que es asíncrona ( opció per defecte)
                    repReq.open('POST',pagina,true);
                    repReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    //alert(qstring);
		            repReq.send(qstring);
                }
		    }
		    
		    
		    		    
		    
		    function cridaiposa_post2(pagina,situacio,qstring)
		    {
		        rDiv = situacio;
		        repReq = getObj();
             	//alert();
             	if( repReq.readyState == 4 || repReq.readyState == 0 )
                {
                	//configurem la funció que gestiona l'enllaç quan canvia
                    repReq.onreadystatechange = handleReq;                	
                    //configurem la connexió com un  GET
					//el "true" expecifica que es asíncrona ( opció per defecte)
                    repReq.open('POST',pagina,true);
                    repReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    //alert(qstring);
		            repReq.send(qstring);
                }
		    }
		    
/*
************************************************************************************
*/

       if (!TextCtrl) 
       {
            var TextCtrl = {};
       }
       
       //TextCtrl.textctrl = function(o1,o2)
       TextCtrl.textctrl = function(obj,cobj,l)
       //function TextCtrl(o1,o2)
       {
            var primerCop = true;
            var n;
                        
            addEvent(obj,'focus',neteja);
            addEvent(obj,'keyup',conta);
                        
            function neteja()
            {
                if (primerCop)
                {
                    //obj.value='';
                    n = obj.value.length;
                    primerCop = false;
                }
            }
            
            function conta()
            {
                n = obj.value.length;
                
                if ( n > l )
                {
                    n = l;
                    obj.value = obj.value.substr(0,n);                    
                }
                if ( cobj.tagName.toLowerCase() == 'input' )
                {
                    cobj.value = n;
                }
                
                if ( cobj.tagName.toLowerCase() == 'div' )
                {
                    cobj.innerHTML = n;                    
                }
            }
            
            this.mostra = function()
            {
                alert(n);
            }           
            
       }
       
/*
*************************************************************************************
*/

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
// From LightBox --> http://www.huddletogether.com/projects/lightbox/ ( thanks guy !! ;) )
function getPageSize(){
	
	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;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// 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;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}


//fem precache de la imatge loading
var cache = new Image();
cache.src = '/images/loading_02.gif';


function loading()
{
    var ob = document.body;
    
    var whxy = getPageSize();
        
    var img = document.createElement('img');
    img.src = '/images/loading_02.gif';
    img.style.position = 'relative';
    img.style.top = '30%';
    
    var d2 = document.createElement('div');
    d2.style.position = 'absolute';
    d2.style.height = whxy[1];
    d2.style.width = whxy[0];
    d2.style.top = '0';
    d2.style.left = '0';
    d2.style.textAlign = 'center';
    d2.verticalAlign = 'middle';
    d2.appendChild(img);
    d2.id = 'trans2';
    
    var d1 = document.createElement('div');
    d1.style.position = 'absolute';
    d1.style.height = whxy[1];
    d1.style.width = whxy[0];
    d1.style.top = '0';
    d1.style.left = '0';
    d1.style.backgroundColor = '#000000';
    d1.className = 'div_transparent';
    d1.id = 'trans1';
    
    ob.appendChild(d1);    
    ob.appendChild(d2);    
}

function no_loading()
{
    var o = document.body;
    if ( document.getElementById('trans1') )  
    {
        o.removeChild(document.getElementById('trans1'));
    }
    if ( document.getElementById('trans2') )  
    {
        o.removeChild(document.getElementById('trans2'));
    }
}