addEvent(window,"load",init);

var prevEl;


function init(){ 
	// Todos los links con class rollover
	var links = document.getElementsBySelector('a.rollover');
	var tmpImg = [];
	
	for (var i=0, t=links.length; i<t ;i++){
		// Asigna eventos de over y out
		addEvent(links[i], 'mouseover', rollOver);
		addEvent(links[i], 'mouseout', rollOut);
		
		// Preload de la imagen
		var img = links[i].getElementsByTagName('img')[0];
		tmpImg[i] = new Image(img.width, img.height);
		tmpImg[i].setAttribute('src', getImg(img, 'over'));
		
		
		/* 
		Va a buscar la imagen con el mismo nombre y sufijo "_selected"
		Dos opciones:
		1. Ponerle al link un class="selected"
		2. Ponerle al link un id="btn_nombreSeccion", donde nombreSeccion es el id del body.
		*/

		if (linkHasBodyId(links[i].id) || (links[i].className.indexOf('selected') != -1)){
			img.setAttribute('src', getImg(img, 'selected'));
		}		
		
		// Si quisiera hacer una barra de progreso, así detecto que cargó la imagen
		// addEvent(tmpImg[i], 'load', function(){alert(this.width);});
	}
	
	if (document.getElementsBySelector('#productos')[0] != null){
		var tds = document.getElementsBySelector('#prodList td');
		for (var i=0, t=tds.length; i<t ;i++){
			addEvent(tds[i], 'mouseup', tdMouseUp);		
		}
		
		var prodLinks = document.getElementsBySelector('#prodList td a');
		for (var i=0, t=prodLinks.length; i<t ;i++){
			prodLinks[i].className += ' jsOK';
			prodLinks[i].onclick = function(){return false;} // FIX usar addEvent
			//addEvent(prodLinks[i], 'click', function(){return false;});
		}	
		
		firstEl = document.getElementsBySelector('#prodList td.colCod a')[0];
		if (firstEl){
			firstEl = firstEl.parentNode
			firstEl.onmouseup = tdMouseUp;
			firstEl.onmouseup();
		}
		
		
		/*
		Marca como selected el link dentro de prodMenu 
		que coincide con el nombre del archivo actual
		*/
		fileName = getFileName(location.href);
		linksProdMenu = document.getElementsBySelector('#prodMenu a');

		for (var i=0, t=linksProdMenu.length; i<t; i++){
			if (fileName == getFileName(linksProdMenu[i].href)){
				linksProdMenu[i].className += 'selected';
			}
		}
		
	}
}


function getFileName(str){
	var arr = str.split("/");
	return arr[arr.length-1];
}



function rollOver(e){
	var img = this.getElementsByTagName('img')[0];
	img.src = getImg(img, 'over');
}

function rollOut(e){

	var img = this.getElementsByTagName('img')[0];	
	
	if (!linkHasBodyId(this.id) && this.className.indexOf('selected') == -1){
		var imgNormal = img.getAttribute('src').replace('_over.','.')
	} else {
		var imgNormal = img.getAttribute('src').replace('_over.','_selected.')	
	}
	img.src = imgNormal;
}

function getImg(img, status){
	return img.getAttribute('src').replace(/(_selected)?.(gif|jpg|png)/ig, '_' + status + '.$2')	
}

function linkHasBodyId(linkId){
	if (!linkId){return false;}
	bodyId = document.getElementsByTagName("BODY")[0].id;
	linkSection = linkId.split("_");
	if (linkSection.length == 2){linkSection = linkSection[1];} else {linkSection = false;}
	return (linkSection && linkSection == bodyId);
}



function tdMouseUp(e){

	if (prevEl){prevEl.className = prevEl.className.replace('selected','');}
	this.parentNode.className += ' selected';
	
	/* Por si hace click en el H2 */
	if (document.getElementsBySelector("#prodList tr.selected a").length == 0){
		this.parentNode.className = this.parentNode.className.replace('selected','')
		prevEl.className += ' selected';
		return false;
	}

	prevEl = this.parentNode;

	var imgUrl = document.getElementsBySelector("#prodList tr.selected a")[0].href;
	var cod = document.getElementsBySelector("#prodList tr.selected td.colCod a")[0].innerHTML;
	var modelo = document.getElementsBySelector("#prodList tr.selected td.colModelo")[0].innerHTML;
	var precio = document.getElementsBySelector("#prodList tr.selected td.colPrecio")[0].innerHTML;

	document.getElementsBySelector("#epigrafe a")[0].innerHTML = cod;
	
	var thumbUrl = imgUrl.replace('fotos_popup', 'fotos_chicas');
	document.getElementsBySelector("#productImgContainer img.thumb")[0].src = thumbUrl; 
	
	var links = document.getElementsBySelector("#productImgContainer a"); 
	for (var i=0, t=links.length; i<t; i++){
		links[i].href = '../popup.asp?imgUrl='+ escape(imgUrl)+ '&cod=' + escape(cod)
						+ '&modelo=' + escape(modelo) + '&precio=' + escape(precio);
		// eventSrc, finalWidth, finalHeight, duration, steps, considerScroll, startPlace, topStart, leftStart, topEnd, leftEnd
		links[i].onclick = function(){return newPopUp(this, 430, 305, 200, 10, true, 'sourceEl');}
	}
	
}





/*
addEvent(element, type, handler)
  ej: addEvent(window, "load", init);
  Incluye removeEvent, preventDefault y stopPropagation.
  Fuente: http://therealcrisp.xs4all.nl/upload/addEvent_dean.html
*/
function addEvent(element, type, handler)
{
	if (element.addEventListener){
		element.addEventListener(type, handler, false);
	}else
	{
		if (!handler.$$guid) {handler.$$guid = addEvent.guid++;}
		if (!element.events) {element.events = {};}
		var handlers = element.events[type];
		if (!handlers)
		{
			handlers = element.events[type] = {};
			if (element['on' + type]){ handlers[0] = element['on' + type];}
			element['on' + type] = handleEvent;
		}
	
		handlers[handler.$$guid] = handler;
	}
}
addEvent.guid = 1;

function removeEvent(element, type, handler)
{
	if (element.removeEventListener){
		element.removeEventListener(type, handler, false);
	}else if (element.events && element.events[type] && handler.$$guid){
		delete element.events[type][handler.$$guid]; }

}

function handleEvent(event)
{
	event = event || fixEvent(window.event);
	var returnValue = true;
	var handlers = this.events[event.type];

	for (var i in handlers)
	{
		if (!Object.prototype[i])
		{
			this.$$handler = handlers[i];
			if (this.$$handler(event) === false){ returnValue = false;}
		}
	}

	if (this.$$handler) {this.$$handler = null;}

	return returnValue;
}

function fixEvent(event)
{
	event.preventDefault = fixEvent.preventDefault;
	event.stopPropagation = fixEvent.stopPropagation;
	return event;
}
fixEvent.preventDefault = function()
{
	this.returnValue = false;
}
fixEvent.stopPropagation = function()
{
	this.cancelBubble = true;
}

// This little snippet fixes the problem that the onload attribute on the body-element will overwrite
// previous attached events on the window object for the onload event
if (!window.addEventListener)
{
	document.onreadystatechange = function()
	{
		if (window.onload && window.onload != handleEvent)
		{
			addEvent(window, 'load', window.onload);
			window.onload = handleEvent;
		}
	}
}




/*
document.getElementsBySelector(selector) 
  ej: elements = document.getElementsBySelect('div#main p a.external')
  Fuente: http://simon.incutio.com/archive/2003/03/25/getElementsBySelector
  Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
  Opera 7 fails 
*/

function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (tagName && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words 
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }
    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}

/* That revolting regular expression explained 
/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
  \---/  \---/\-------------/    \-------/
    |      |         |               |
    |      |         |           The value
    |      |    ~,|,^,$,* or =
    |   Attribute 
   Tag
*/






















var iframe;

function newPopUp(eventSrc, finalWidth, finalHeight, duration, steps, considerScroll, startPlace, topStart, leftStart, topEnd, leftEnd){
	
	if (s>0) {
		closeIFrame(); 
	}
	pp = initPopUpDiv(eventSrc, finalWidth, finalHeight, duration, steps, considerScroll, startPlace, topStart, leftStart, topEnd, leftEnd);

	// HANDLE FORMS	
	if ((eventSrc.tagName == "INPUT") || (eventSrc.tagName == "BUTTON") || (eventSrc.tagName == "FORM")) { 
		while (eventSrc.tagName!="FORM")	{ 
			eventSrc=eventSrc.parentNode;
		}

		pp.targetLink = eventSrc.action;
		pp.targetData = buildQueryString(eventSrc.id);
	
	} 
	// HANDLE LINKS 
	else {
		pp.targetLink = eventSrc.href;
		pp.targetData = "";
	}

	if (!pp.iframe){
		pp.iframe = createIframe(pp.div.id, pp.finalWidth, pp.finalHeight); // target parent element, width, height
	}
	pp.iframe.doc.location.replace(pp.targetLink + pp.targetData);
	pp.iframe = null;
	return false;
}	









function handleIframeLoad(){ // loaded iframe must call this funk 
		parent.document.getElementById("popUp").style.display = "block";
		parent.document.getElementById("popUp").style.visibility = 'visible';
		popUpDiv("popUp");
}


function closeIFrame(){
		document.getElementById("funkIframe").style.display = "none";
		document.getElementById("popUp").style.display = "none";
		document.getElementsByTagName('BODY')[0].removeChild(document.getElementById("popUp")); // For the latest IE6 patches		
		IFrameObj = null;
		s=0;
		return false;
}



function initPopUpDiv(eventSrc, finalWidth, finalHeight, duration, steps, considerScroll, startPlace, topStart, leftStart, topEnd, leftEnd){
	// some defaults
	
	// Size
	this.finalWidth = finalWidth || 330;
	this.finalHeight = finalHeight || 350;

	// Animation
	this.duration = duration || 100;
	this.steps = steps || 8;

	// steps cannot be larger than (smallest size / 2)
	if (this.steps > ( (this.finalWidth /2) || this.finalHeight /2)){
		if (this.finalWidth < this.finalHeight){
			this.steps = this.finalWidth /2;
		} else {
			this.steps = this.finalHeight /2;	
		}	
	}

	this.considerScroll = considerScroll || true;
	if (startPlace == "sourceEl") {
		var elPos = getPos(eventSrc);
		this.topStart = elPos.top;
		this.leftStart = elPos.left+10;
	} else if (startPlace == "custom") {
		this.topStart = topStart;
		this.leftStart = leftStart;
	} 

	var client = getClientSize();
	var cliendMidX = client.width / 2;
	var cliendMidY = client.height / 2;

	if (!topStart && !startPlace){
		this.topStart = cliendMidY;
		this.leftStart = cliendMidX;
		var topStartWasUndefined = true ;
	}
	if (!topEnd){
		this.topEnd = cliendMidY;
		this.leftEnd = cliendMidX;
	}	

	var currentScroll = getScroll();
	if (this.considerScroll && topStartWasUndefined){
		this.topStart += currentScroll.top;
		this.leftStart += currentScroll.left;
	}
	if (this.considerScroll){
		this.topEnd += currentScroll.top;
		this.leftEnd += currentScroll.left;
	}

	this.stepMoveY = (this.topEnd - this.topStart) / this.steps;
	this.stepMoveX = (this.leftEnd - this.leftStart) / this.steps;

	this.stepDuration = this.duration / this.steps;
	this.stepWidth = this.finalWidth / this.steps;
	this.stepHeight = this.finalHeight / this.steps;

	// CREATE THE CONTAINING DIV	
	var XHTMLNS = "http://www.w3.org/1999/xhtml";
    // add namespace methods to HTML DOM; this makes the script work in both HTML and XML contexts.
    if(!document.createElementNS) {
        document.createElementNS = function(ns,elt) {
            return document.createElement(elt);
        };
    }
	
	this.popId = "popUp";
	if (!document.getElementById(this.popId)) {
		this.div = document.createElementNS(XHTMLNS,"div");
		div.id = this.popId;
		document.getElementsByTagName("BODY")[0].appendChild(div);	
	} else {
		this.div = document.getElementById(this.popId);
	}

	// CONFIG DIV
	div.style.top = this.topStart + "px";
	div.style.left = this.leftStart + "px";


	/* set required properties */
	div.style.display = 'block'; 
	div.style.visibility = 'hidden';
	div.style.overflow = 'hidden';	
	div.style.position = 'absolute';
	div.style.width = 0 + "px";
	div.style.height = 0 + "px";

	return this;
}


var s=0;
var pp;
function popUpDiv(divId){
	/*if (s===0){
		pp = initPopUpDiv(divId);
	} */
	if (pp){
		pp.div.style.width 	=  parseInt(pp.div.style.width.substring(0,pp.div.style.width.length-2)) + pp.stepWidth + "px";
		pp.div.style.height	= parseInt(pp.div.style.height.substring(0,pp.div.style.height.length-2)) + pp.stepHeight + "px";
		pp.div.style.left	= (parseInt(pp.div.style.left.substring(0,pp.div.style.left.length-2)) - pp.stepWidth/2) + pp.stepMoveX + "px";
		pp.div.style.top 	= (parseInt(pp.div.style.top.substring(0,pp.div.style.top.length-2)) - pp.stepHeight/2) + pp.stepMoveY + "px";

		if (s < pp.steps-1){
			var move = setTimeout('popUpDiv()',parseInt(pp.stepDuration));
			s++;
		} else {
			document.getElementById("funkIframe").style.display = "block";
			pp = null;			
		}
	}
	return false;
}




/**************************** 
FIND POSITION OF AN HTML ELEMENT
basado en http://www.xs4all.nl/~ppk/js/findpos.html
****************************/
function getPos(obj){
	var curleft = 0, curtop = 0;
	if (obj.offsetParent){
		while (obj.offsetParent){
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;			
			obj = obj.offsetParent;
		}
	}
	return {	top: curtop,
				left: curleft };
}

/*****************************
get size of the browser canvas
ref: http://www.howtocreate.co.uk/tutorials/index.php?tut=0&part=16
*****************************/
function getClientSize() {  
	var myWidth = 0, myHeight = 0;
	if (typeof(window.innerWidth) == 'number') { //NS
    	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 {	width: myWidth,
				height: myHeight };
}

function getScroll() {
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else {
		if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
		} else {
			if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
				//IE6 standards compliant mode
				scrOfY = document.documentElement.scrollTop;
				scrOfX = document.documentElement.scrollLeft;
			}
		}
	}
	return { 	top: scrOfY,
  				left: scrOfX };		
}


/* IFRAME ************************
	iframe ref	COSTELLO@APPLE:	http://developer.apple.com/internet/javascript/iframe.html 
				COSTELLO: http://glish.com/articles/apple/rs_with_iframe.html
******************************* */
var IFrameObj;

function createIframe(parentElm, alertWidth, alertHeight){	
	alertHeight = 500; // FIX !!!iframe object is not being reinitiated, try newsletter then amigo w/o this
	if (!IFrameObj) {
		var parentEl = document.getElementById(parentElm);	
		var IFrameDoc;
		try {
			var tempIFrame=document.createElement('iframe');
			tempIFrame.setAttribute('id','funkIframe');
			tempIFrame.setAttribute('name','funkIframe');
			tempIFrame.setAttribute('frameborder','0');
			tempIFrame.style.border='0px';
			tempIFrame.style.width= alertWidth + 'px';
			tempIFrame.style.height= alertHeight + 'px';
			tempIFrame.style.position = 'absolute';
			IFrameObj = parentEl.appendChild(tempIFrame);
			if (document.frames) {
				IFrameObj = document.frames['funkIframe'];
			}
		} catch(exception) { // para IE5Win
			var iframeHTML='\<iframe id="funkIframe" style="';
			iframeHTML+='border:0px none #000000;';
			iframeHTML+='width:' + alertWidth + 'px;';
			iframeHTML+='height:' + alertHeight + 'px;';
			iframeHTML+='"><\/iframe>';
			parentEl.innerHTML+=iframeHTML;
			IFrameObj = new Object();
			IFrameObj.document = new Object();
			IFrameObj.document.location = new Object();
			IFrameObj.document.location.iframe = document.getElementById('funkIframe');
			IFrameObj.document.location.replace = function(location) {
				this.iframe.src = location;
			};
		}
	}
	if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {
		setTimeout('createIframe()',10); // give NS6 a sec to recognize the new IFrame
		return false;
	}

	if (IFrameObj.contentDocument) {
		// For NS6
		IFrameDoc = IFrameObj.contentDocument; 
	} else if (IFrameObj.contentWindow) {
		// For IE5.5 and IE6
		IFrameDoc = IFrameObj.contentWindow.document;
	} else if (IFrameObj.document) {
		// For IE5
		IFrameDoc = IFrameObj.document;
	} else {
		return true;
	}
	parentEl.firstChild.frameborder="0";
	return {	doc: IFrameDoc,
	 			obj: IFrameObj };
}

function buildQueryString(theFormName) { 
	var theForm = document.forms[theFormName];
	var qs = '';
	for (var e=0;e<theForm.elements.length;e++) {
		if (theForm.elements[e].name!=='' && !(theForm.elements[e].type=='radio' || theForm.elements[e].type=='checkbox')) {
			qs+=(qs==='')?'?':'&';
			qs+=theForm.elements[e].name+'='+escape(theForm.elements[e].value);
		} else if (theForm.elements[e].name!=='' && (theForm.elements[e].type=='radio' || theForm.elements[e].type=='checkbox') && theForm.elements[e].checked === true){
			qs+=(qs==='')?'?':'&';
			qs+=theForm.elements[e].name+'='+escape(theForm.elements[e].value);
		}
	}
	return qs;
}

