
/**
* funcions per manetjar el DOM, quasi totes adaptades de
* http://www.howtocreate.co.uk/tutorials/javascript/elementcontents
*/

//var besDOM = new Object();

var error_navegador="The browser doesn''t accept this cahracteristic. El navegador no acepta esta característica.";


/**
* llista el nom del elements d'una ficha
*/
function listaElementosForm(_form) {
	var lista, element;
	for (var i = 0; i < document.forms[_form].elements.length; i++) {
    	element = document.forms[_form].elements[i];

		lista=lista+' '+element.name;
	}

	alert(lista);
}


/**
* cross browser per tornar una referència a un id
*/
function getRefToDiv(divID,oDoc) {
  if( document.getElementById ) {
    return document.getElementById(divID); }
  if( document.all ) {
    return document.all[divID]; }
  if( !oDoc ) { oDoc = document; }
  if( document.layers ) {
    if( oDoc.layers[divID] ) { return oDoc.layers[divID]; } else {
      //repeatedly run through all child layers
      for( var x = 0, y; !y && x < oDoc.layers.length; x++ ) {
        //on success, return that layer, else return nothing
        y = getRefToDiv(divID,oDoc.layers[x].document); }
    return y; } }
  return false;
}


/**
* mostra un div per Id, és inline, per fer-ho per block, utilitzar showDivBlock
*/
function showDiv(divID_as_a_string) {
  //get a reference as above ...
  myReference = getRefToDiv(divID_as_a_string);
  if( !myReference ) {
    window.alert(error_navegador);
    return; //don't go any further
  }
  //now we have a reference to it
  if( myReference.style ) {
    //DOM & proprietary DOM
    myReference.style.visibility = 'visible';
  } else {
    //layers syntax
    myReference.visibility = 'show';
  }
}

/**
* oculta un div per Id
*/
function hideDiv(divID_as_a_string) {
  //get a reference as above ...
  myReference = getRefToDiv(divID_as_a_string);
  if( !myReference ) {
    window.alert(error_navegador);
    return; //don't go any further
  }
  //now we have a reference to it
  if( myReference.style ) {
    //DOM & proprietary DOM
    myReference.style.visibility = 'hidden';
  } else {
    //layers syntax
    myReference.visibility = 'hide';
  }
}


/**
* canvia la forma de display a nivell de block
* pot ser '' (default)  'inline' 'block'  'none'
*/
function changeDisplay( elementId, setTo ) {
   var theElement;
  if( document.getElementById ) {
    //DOM
    theElement = document.getElementById( elementId );
  } else if( document.all ) {
    //Proprietary DOM
    theElement = document.all[ elementId ];
  }
  if( !theElement ) {
    /* The page has not loaded, or the browser claims to
    support document.getElementById or document.all but
    cannot actually use either */
    return;
  }
  //Reference the style ...
  if( theElement.style ) { theElement = theElement.style; }
  if( typeof( theElement.display ) == 'undefined' ) {
    //The browser does not allow us to change the display style
    //Alert something sensible (not what I have here ...)
    window.alert( error_navegador );
    return;
  }
  //Change the display style
  theElement.display = setTo;
}



/**
* Canvia els colors d'un element
*/
function setBackgroundcolor( divID_as_a_string, color, bcolor, bgcolor ) {
    myReference = getRefToDiv(divID_as_a_string);
    if( !myReference ) {
      window.alert(error_navegador);
      return; //don't go any further
    }

	if( myReference.style ) { myReference = myReference.style; }
	myReference.bgColor = color;//'#00ff00';
	myReference.background = bcolor;//'#00ff00';
	myReference.backgroundColor = bgcolor;//'#00ff00';
}

/**
* canvia el tamany del div
*/
function setSize(divID_as_a_string, newWidth, newHeight) {
    myReference = getRefToDiv(divID_as_a_string);
    if( !myReference ) {
      window.alert(error_navegador);
      return; //don't go any further
    }

	if( myReference.style ) { myReference = myReference.style; }
	if( myReference.resizeTo ) {
		  myReference.resizeTo( newWidth, newHeight );
	}
	var noPx = document.childNodes ? 'px' : 0;
	myReference.width = newWidth + noPx;
	myReference.pixelWidth = newWidth;
	myReference.height = newHeight + noPx;
	myReference.pixelHeight = newHeight;
}

/**
* re-escriu el contingut del div
*/
function setInnerHTML(divID_as_a_string, contenido) {
    myReference = getRefToDiv(divID_as_a_string);
    if( !myReference ) {
      window.alert(error_navegador);
      return; //don't go any further
    }

	if( typeof( myReference.innerHTML ) != 'undefined' ) {
  		//used by all current browsers
  		myReference.innerHTML = contenido;
	} else if( myReference.document && myReference.document != window.document ) {
  		//used by layers browsers
  		myReference.document.open();
  		myReference.document.write(contenido);
  		myReference.document.close();
	}
}


/**
* crea un nou element, fill d'un altra donar les coordenades en px
*/
function createNewElement( divID_as_a_string, newName, left, top, width, contingut) {
    myReference = getRefToDiv(divID_as_a_string);
    if( !myReference ) {
      window.alert(error_navegador);
      return; //don't go any further
    }

	if( document.layers && window.Layer && document.classes ) {
  		//create a layer 350px wide
  		document.layers[newName] = new Layer( newName, myReference );
  		//write its content
		document.layers[newName].document.open();
		document.layers[newName].document.write('new content');
		document.layers[newName].document.close();
		//style it
		document.layers[newName].left = 0;
		document.layers[newName].top = 0;
		document.layers[newName].visibility = 'show';
	} else {
	    var theString = '<div style="position:absolute;left:'+laft+'px;top:'+top+'px;' +
		    'width:'+width+'px;">'+contingut+'</div>';
		if( myReference.insertAdjacentHTML ) {
		    myReference.insertAdjacentHTML( 'beforeEnd', theString );
		} else if( typeof( myReference.innerHTML ) != 'undefined' ) {
		    myReference.innerHTML += theString;
		} else {
		    //FAILURE, nothing works
		}
	}
}

/**
* canvia el bgcolor de tot el document
* #f6f6f6  #d2cbff  #777777   '' (returns to default) - not allowed by some old browse
*/
function setDocumentBackggroundColor( color ) {
	if( document.documentElement && document.documentElement.style ) {
    	document.documentElement.style.backgroundColor = color; }
	if( document.body && document.body.style ) {
    	document.body.style.backgroundColor = color; }
	document.bgColor = color;
}


function setFocus(oName) {
	findObj(oName).focus();
}

/**
* retorna una referencia a un objecte, vai el seu nom o id
* p.e. var theOb = findObj( NameOrId );
*/
function findObj( oName, oFrame, oDoc ) {
  /* if not working on a layer, document should be set to the
  document of the working frame
  if the working frame is not set, use the window object
  of the current document
  WARNING: - cross frame scripting will cause errors if
  your page is in a frameset from a different domain */
  if( !oDoc ) { if( oFrame ) { oDoc = oFrame.document; } else { oDoc = window.document; } }

  //check for images, forms, layers
  if( oDoc[oName] ) { return oDoc[oName]; }

  //check for pDOM layers
  if( oDoc.all && oDoc.all[oName] ) { return oDoc.all[oName]; }

  //check for DOM layers
  if( oDoc.getElementById && oDoc.getElementById(oName) ) {
    return oDoc.getElementById(oName); }

  //check for form elements
  for( var x = 0; x < oDoc.forms.length; x++ ) {
    if( oDoc.forms[x][oName] ) { return oDoc.forms[x][oName]; } }

  //check for anchor elements
  //NOTE: only anchor properties will be available,
  //NOT link properties (in layers browsers)
  for( var x = 0; x < oDoc.anchors.length; x++ ) {
    if( oDoc.anchors[x].name == oName ) {
      return oDoc.anchors[x]; } }

  //check for any of the above within a layer in layers browsers
  for( var x = 0; document.layers && x < oDoc.layers.length; x++ ) {
    var theOb = findObj( oName, null, oDoc.layers[x].document );
      if( theOb ) { return theOb; } }

  //check for frames, variables or functions
  if( !oFrame && window[oName] ) { return window[oName]; }
  if( oFrame && oFrame[oName] ) { return oFrame[oName]; }

  //if checking through frames, check for any of the above within
  //each child frame
  for( var x = 0; oFrame && oFrame.frames && x < oFrame.frames.length; x++ ) {
    var theOb = findObj( oName, oFrame.frames[x], oFrame.frames[x].document ); if( theOb ) { return theOb; } }

  return null;
}


/**
* torna les dimensions de la finestra
*/
function getWindowSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [myWidth, myHeight];
}


/**
* descomentar lo seguent
//first, tell the browsers to react to the event
//if( document.captureEvents && Event.KEYUP ) {
  //remove this part if you do not need Netscape 4 to work
  //document.captureEvents( Event.KEYUP );
//}
//document.onkeyup = alertkey;

/* this next line tells the browser to detect a keyup
event over the whole document and when it detects it,
it should run the event handler function 'alertkey' */


//now create the event handler function to process the event
function alertkey(e) {
  if( !e ) {
    //if the browser did not pass the event information to the
    //function, we will have to obtain it from the event register
    if( window.event ) {
      //Internet Explorer
      e = window.event;
    } else {
      //total failure, we have no way of referencing the event
      return;
    }
  }
  if( typeof( e.keyCode ) == 'number'  ) {
    //DOM
    e = e.keyCode;
  } else if( typeof( e.which ) == 'number' ) {
    //NS 4 compatible
    e = e.which;
  } else if( typeof( e.charCode ) == 'number'  ) {
    //also NS 6+, Mozilla 0.9+
    e = e.charCode;
  } else {
    //total failure, we have no way of obtaining the key code
    return;
  }
  window.alert('The key pressed has keycode ' + e +
    ' and is key ' + String.fromCharCode( e ) );
}

/**
* coordenades del ratolí
*/
/*
if( document.captureEvents && Event.KEYUP ) {
  //remove this part if you do not need Netscape 4 to work
  document.captureEvents( Event.KEYUP );
}
myReference.onmousemove = alertCoord;
*/

function getMousePosition(event) {
 if (typeof event == "undefined")
  {
    event = window.event;
  }

  var scrollingPosition = getScrollingPosition();
  var cursorPosition = [0, 0];

  if (typeof event.pageX != "undefined" && typeof event.x != "undefined")
  {
    cursorPosition[0] = event.pageX;
    cursorPosition[1] = event.pageY;
  }
  else
  {
    cursorPosition[0] = event.clientX + scrollingPosition[0];
    cursorPosition[1] = event.clientY + scrollingPosition[1];
  }

  var coords = [cursorPosition[0],cursorPosition[1]];

  window.status='Mouse coordinates are ('+cursorPosition[0]+','+cursorPosition[1]+')';
  return coords;

//  var paragraph = document.getElementsByTagName("p")[0];

//  paragraph.replaceChild(document.createTextNode("Your mouse is currently located at: " + cursorPosition[0] + "," + cursorPosition[1]), paragraph.firstChild);

//  return true;


}

/**
* afegeix un listener al carregador de pàgina, de forma que podem afegir-li tots els loadListeners
* que vuigem
*
*/
function addLoadListener(fn) {

	if (typeof window.addEventListener!= 'undefined')
	{
		window.addEventListener('load', fn, false);
	}
	else if (typeof document.addEventListener != 'undefined')
	{
			document.addEventListener('load', fn, false);
	}
	else if (typeof window.attachEvent!= 'undefined')
	{
		window.attachEvent('onload', fn);
	}
	else
	{
		var oldfn=window.onload;
		if (typeof window.onload!='function')
		{
			window.onload=fn;
		}
		else
		{
			window.onload=function()
			{
				oldfn();
				fn();
			};
		}
	}
}

/**
* torna un array amb tots els elements amb atribut=value
* p.e. tots els de la clase algo: "class", "algo"
* "type", "checkbox"
*/
function getElementsByAttribute(attribute, attributeValue)
{
  var elementArray = new Array();
  var matchedArray = new Array();

  if (document.all)
  {
    elementArray = document.all;
  }
  else
  {
    elementArray = document.getElementsByTagName("*");
  }

  for (var i = 0; i < elementArray.length; i++)
  {
    if (attribute == "class")
    {
      var pattern = new RegExp("(^| )" + attributeValue + "( |$)");

      if (pattern.test(elementArray[i].className))
      {
        matchedArray[matchedArray.length] = elementArray[i];
      }
    }
    else if (attribute == "for")
    {
      if (elementArray[i].getAttribute("htmlFor") || elementArray[i].getAttribute("for"))
      {
        if (elementArray[i].htmlFor == attributeValue)
        {
          matchedArray[matchedArray.length] = elementArray[i];
        }
      }
    }
    else if (elementArray[i].getAttribute(attribute) == attributeValue)
    {
      matchedArray[matchedArray.length] = elementArray[i];
    }
  }

  return matchedArray;
}


/**
* atacha un event a un target
* target - element al que atacham l'event
* eventType - tipus d'event sense l'on devant
* functionRef - callback de l'event
* capture - consumir l'event
*
* p.e
* var mylink = document.getElementById("mylink");
*
*  attachEventListener(mylink, "click", engage, false);
*/
function attachEventListener(target, eventType, functionRef, capture)
{
  if (typeof target.addEventListener != "undefined")
  {
    target.addEventListener(eventType, functionRef, capture);
  }
  else if (typeof target.attachEvent != "undefined")
  {
    var functionString = eventType + functionRef;
    target["e" + functionString] = functionRef;

    target[functionString] = function(event)
    {
      if(typeof event == "undefined"){event = window.event}; target["e" + functionString](event);
    };

    target.attachEvent("on" + eventType, target[functionString]);
  }
  else
  {
    eventType = "on" + eventType;

    if (typeof target[eventType] == "function")
    {
      var oldListener = target[eventType];

      target[eventType] = function()
      {
        oldListener();

        return functionRef();
      }
    }
    else
    {
      target[eventType] = functionRef;
    }
  }

  return true;
}

/**
* detacham l'event de l'element
*/
function detachEventListener(target, eventType, functionRef, capture)
{
  if (typeof target.removeEventListener != "undefined")
  {
    target.removeEventListener(eventType, functionRef, capture)
  }
  else if (typeof target.detachEvent != "undefined")
  {
    var functionString = eventType + functionRef;

    target.detachEvent("on" + eventType, target[functionString]);

    target["e" + functionString] = null;
    target[functionString] = null;
  }
  else
  {
    target["on" + eventType] = null;
  }

  return true;
}


/**
* atacha un callback d'event a un grup d'elements
p.e.
	//assignam el callback showTip quant el ratolí passi per damunt una imatge
	//de clase azar_empresa_fotillo
	attachEventToElements( "class", "azar_empresa_fotillo",
							"mouseover", showTip, false );
*/
function attachEventToElements( attribute, attributeValue, eventType, functionRef, capture) {
	var elems=getElementsByAttribute(attribute, attributeValue);

	for (var i=0; i<elems.length; i++) {
		attachEventListener( elems[i], eventType, functionRef, capture);
	}

	return true;
}


/**
* mostra un tip
*/
function showTip(event)
{
  if (typeof event == "undefined")
  {
    event = window.event;
  }

  var target = getEventTarget(event);

  while (target.className == null || !/(^| )hastooltip( |$)/.test(target.className))
  {
    target = target.parentNode;
  }

  var tip = document.createElement("div");
  var content = target.getAttribute("title");

  target.tooltip = tip;
  target.setAttribute("title", "");

  if (target.getAttribute("id") != "")
  {
    tip.setAttribute("id", target.getAttribute("id") + "tooltip");
  }

  tip.className = "tooltip";
  tip.appendChild(document.createTextNode(content));

  var scrollingPosition = getScrollingPosition();
  var cursorPosition = [0, 0];

  if (typeof event.pageX != "undefined" && typeof event.x != "undefined")
  {
    cursorPosition[0] = event.pageX;
    cursorPosition[1] = event.pageY;
  }
  else
  {
    cursorPosition[0] = event.clientX + scrollingPosition[0];
    cursorPosition[1] = event.clientY + scrollingPosition[1];
  }

  tip.style.position = "absolute";
  tip.style.left = cursorPosition[0] + 10 + "px";
  tip.style.top = cursorPosition[1] + 10 + "px";
  tip.style.visibility = "hidden";

  document.getElementsByTagName("body")[0].appendChild(tip);

  var viewportSize = getViewportSize();

  if (cursorPosition[0] - scrollingPosition[0] + 10 + tip.offsetWidth > viewportSize[0] - 25)
  {
    tip.style.left = scrollingPosition[0] + viewportSize[0] - 25 - tip.offsetWidth + "px";
  }
  else
  {
    tip.style.left = cursorPosition[0] + 10 + "px";
  }

  if (cursorPosition[1] - scrollingPosition[1] + 10 + tip.offsetHeight > viewportSize[1] - 25)
  {
    if (event.clientX > (viewportSize[0] - 25 - tip.offsetWidth))
    {
      tip.style.top = cursorPosition[1] - tip.offsetHeight - 10 + "px";
    }
    else
    {
      tip.style.top = scrollingPosition[1] + viewportSize[1] - 25 - tip.offsetHeight + "px";
    }
  }
  else
  {
    tip.style.top = cursorPosition[1] + 10 + "px";
  }

  tip.style.visibility = "visible";

  return true;
}


/**
* amaga el tip
*/
function hideTip(event)
{
  if (typeof event == "undefined")
  {
    event = window.event;
  }

  var target = getEventTarget(event);

  while (target.className == null || !target.className.match(/(^| )hastooltip( |$)/))
  {
    target = target.parentNode;
  }

  if (target.tooltip != null)
  {
    target.setAttribute("title", target.tooltip.childNodes[0].nodeValue);
    target.tooltip.parentNode.removeChild(target.tooltip);
  }

  return false;
}

/**
* torna el target d'un evetn
*/
function getEventTarget(event)
{
  var targetElement = null;

  if (typeof event.target != "undefined")
  {
    targetElement = event.target;
  }
  else
  {
    targetElement = event.srcElement;
  }

  while (targetElement.nodeType == 3 && targetElement.parentNode != null)
  {
    targetElement = targetElement.parentNode;
  }

  return targetElement;
}

/**
* torna el tamany del viewport
*/
function getViewportSize()
{
  var size = [0,0];

  if (typeof window.innerWidth != 'undefined')
  {
    size = [
        window.innerWidth,
        window.innerHeight
    ];
  }
  else if (typeof document.documentElement != 'undefined'
      && typeof document.documentElement.clientWidth != 'undefined'
      && document.documentElement.clientWidth != 0)
  {
    size = [
        document.documentElement.clientWidth,
        document.documentElement.clientHeight
    ];
  }
  else
  {
    size = [
        document.getElementsByTagName('body')[0].clientWidth,
        document.getElementsByTagName('body')[0].clientHeight
    ];
  }

  return size;
}

/**
* torna els offsets dels scrolls
*/
function getScrollingPosition()
{
  //array for X and Y scroll position
  var position = [0, 0];

  //if the window.pageYOffset property is supported
  if(typeof window.pageYOffset != 'undefined')
  {
    //store position values
    position = [
        window.pageXOffset,
        window.pageYOffset
    ];
  }

  //if the documentElement.scrollTop property is supported
  //and the value is greater than zero
  if(typeof document.documentElement.scrollTop != 'undefined'
    && document.documentElement.scrollTop > 0)
  {
    //store position values
    position = [
        document.documentElement.scrollLeft,
        document.documentElement.scrollTop
    ];
  }

  //if the body.scrollTop property is supported
  else if(typeof document.body.scrollTop != 'undefined')
  {
    //store position values
    position = [
        document.body.scrollLeft,
        document.body.scrollTop
    ];
  }

  //return the array
  return position;
}


/**
* torna la posició d'un element
*/
function getElementPosition(theElement)
{
  var positionX = 0;
  var positionY = 0;

  while (theElement != null)
  {
    positionX += theElement.offsetLeft;
    positionY += theElement.offsetTop;
    theElement = theElement.offsetParent;
  }


  return [positionX, positionY];
}

/**
* crea i mostra una finestra de popup
*/
function makePopup(url, width, height, overflow)
{
  if (width > 640) { width = 640; }
  if (height > 480) { height = 480; }

  if (overflow == '' || !/^(scroll|resize|both)$/.test(overflow))
  {
    overflow = 'both';
  }

  var win = window.open(url, '',
      'width=' + width + ',height=' + height
      + ',scrollbars=' + (/^(scroll|both)$/.test(overflow) ? 'yes' : 'no')
      + ',resizable=' + (/^(resize|both)$/.test(overflow) ? 'yes' : 'no')
      + ',status=yes,toolbar=no,menubar=no,location=no'
  );

  return win;
}

/*
* detecció de quin botó s'ha clickat
*/

/*
<script type="text/javascript">

//link and form elements do not need to be told to capture.
//Using the JavaScript syntax, we have to wait for the relevant
//part of the page to load before telling it to detect the event
//This is easiest done with a load event listener
window.onload = function () { document.links[0].onmousedown=alertBut; }

function alertBut( e, evElement ) {
  if( !e ) {
    if( window.event ) {
      //Internet Explorer
      e = window.event;
    } else {
      //total failure, we have no way of referencing the event
      return;
    }
  }
  if( typeof( e.which ) == 'number' ) {
    //Netscape compatible
    e = e.which;
  } else if( typeof( e.button ) == 'number' ) {
    //DOM
    e = e.button;
  } else {
    //total failure, we have no way of obtaining the button
    return;
  }
  if( !evElement ) { evElement = this; }
  // 'this' will exist if I have used object.onEventName = alertBut;
  //If I have passed evElement from the onmouseup attribute,
  //'this' will refer to window
  window.alert( evElement + ' was clicked with button ' + e );
}

</script>

<a onmouseup="alertBut(arguments[0],this)" href="whatever">

*/



