﻿/**************************************
 * PRODUCT PAGE
 **************************************/
/**
	ProductNavigation. Create and apply the product navigation funcionality.
	
	@author Marcelo Miranda Carneiro
	@version 0.1 15:00 7/1/2008
	@example
		<code>
			var test = new ProductNavigation({
				imgPath:'../Imagens/produtos/id1/', <% //onde as imagens deste produto ficarão hospedadas %>
				fileList:{
					prefix: 'fake',
					small:'_tmb_', <% // nome do sufixo da imagem pequena %>
					big:'_big_', <% // nome do sufixo da imagem grande %>
					zoom:'_zoom_' <% // nome do sufixo da imagem para zoom %>
					<%
						// padrão de nomenclatura para todas as fotos
						// o nome do arquivo será concatenado na seguinte ordem:
						//
						// prefix+colorId+(small || big || zoom)+quantity:
						// "fake_bam_fvd_tmb_1.jpg"
					%>
				},
				photos:[{
					colorId:'bam_fvd',
					allSizes:[38,39,40,41], <% // tamanhos disponíveis %>
					photoQuantity:3, <% // número de fotos %>
					fileList:{ <% // caso necessário, é possível colocar um padrão de nomenclatura específico para um id de cor (usa a mesma lógica do geral). %>
						prefix: 'fake_custom',
						small:'_tmb_', <% // nome do sufixo da imagem pequena %>
						big:'_big_', <% // nome do sufixo da imagem grande %>
						zoom:'_zoom_' <% // nome do sufixo da imagem para zoom %>
					}
				},{
					colorId:'bbr_fvd',
					allSizes:[40,41,42,43],
					photoQuantity:3
				},{
					colorId:'bbr_fvm',
					allSizes:[28,29,30,35,38,39,42,45],
					photoQuantity:3
				}]			
			});
		</code>
*/
//{
var ProductNavigation = function($obj){
	
	if(typeof($obj) != 'object'){
		alert('ProductNavigation Error: \n $obj is not defined or isn´t an object');
		return false;
	}
	
	var _this = this;
	try{
		this._loaderImgObj = (typeof($obj.elements.loaderImgObj) == 'object') ? $obj.elements.loaderImgObj : null;
		this._unavailablePhoto = (typeof($obj.elements.unavailablePhoto) == 'object') ? $obj.elements.unavailablePhoto : null;
		this._photos = $obj.photos;
		
		$obj.elements = $obj.elements || {};
		this._colorUl = $obj.elements.colorUl;
		this._sizesUl = $obj.elements.sizesUl;
		this._toZoomUl = $obj.elements.toZoomUl;
		this._videoList = $obj.elements.videoList;
		this._videoContainer = $obj.elements.videoContainer;
		this._bigImageCont = $obj.elements.bigImageCont;
		this._bigImage = gTag('img',$obj.elements.bigImageCont)[0];
		this._hideIfNoPhoto = $obj.elements.hideIfNoPhoto;
		this._photoToZoomObj = $obj.elements.photoToZoomObj;
		this._txtSizeElm = $obj.elements.txtSize;
		this._txtColorElm = $obj.elements.txtColor;
		this._txtRefElm = $obj.elements.txtRef;
		this._htmlPromoElm = $obj.elements.htmlPromo;
		this._htmlDivisaoElm = $obj.elements.htmlDivisao;
		this._selosCont = $obj.elements.selosCont;
		this._productNameElm = $obj.elements.productName;
		this._form = $obj.elements.form;
		
		this._btEnviaAmigo = $obj.elements.btEnviaAmigo || null;
		
		this._imgPath = $obj.imgPath;
		this._fileList = $obj.fileList;
		
	}catch(e){
		return alert('ERROR: FF: '+e+' | IE: '+e.description);
	}
	
	this._toZoomLi = 
	this._videoListLi =
	this._liSizesModel = 
	this._alternateColors = 
	this._alternateSizes = 
	this._buyButton = 
	this._reminderButton = 
	this.reminderBoxNode = 
	this.indiqueBoxNode = null;
	
	this._spacer = new LoadImage(url_global+'img/px.png');
	
	//{ ************ APPLY FUNCTIONS ************
	/**
		ProductNavigation._applyFunctions. Apply functions to object nodes.
		@return Boolean.
	*/
	this._applyFunctions = function(){
		_this._applyColorFunction();
	};
	/**
		ProductNavigation._applyColorFunction. Apply functions, related to colors, to object nodes.
		@return Boolean.
	*/
	var colorCarret = 0;
	var maxColorCarret = 0;
	this._applyColorFunction = function(){
		var links = gTag('a',_this._colorUl);
		var altColorNodes = gTag('li',_this._colorUl);
		maxColorCarret = links.length-1;
		var selectedOption = null;
		var applyFunction = function($node){
			var parent = $node.parentNode.parentNode;
			$node.href = 'javascript:;';
			EventUtil.clear($node,'click');
			EventUtil.add($node,'mouseover',function(e){
				if(parent.className.indexOf("sel") < 0){
					parent.className += " sel";
				}else{
					selectedOption = parent;
				}
			});
			EventUtil.add($node,'mouseout',function(e){
				if(selectedOption != parent){
					parent.className = parent.className.replace(/sel/, "");
				}
			});
			EventUtil.add($node,'click',function(e){
				selectedOption = parent;
				_this._alternateColors.on(parent);
			});
		};
		// create alternate colors instance
		_this._alternateColors = new AlternateItens({
			onFunction:function($item){
				var linkElm = gTag('a', $item)[0];
				var photoObj = _this.getPhotoInfoByColorId($item.id);

				// write details by color
				_this._writeProductDetail(photoObj,function($obj){
					_this._txtColorElm.innerHTML = '('+linkElm.innerHTML.trim()+')';
					_this._txtSizeElm.innerHTML = '';
				});
				// refresh hidden values by color
				_this._refreshHiddens(photoObj.inputHiddens);
				
				_this._getSizes(_this.verifyId($item.id));
				_this._getAvailPhotos(_this.verifyId($item.id));
				_this._getAvailVideos(_this.verifyId($item.id));
				
				// select color input
				$item.className += ' sel';
				var inputs = gTag('input',_this._colorUl);
				for(var i=0; i< inputs.length; i++){
					inputs[i].checked = false;
				}
				gTag('input',$item)[0].checked = true;
			},
			offFunction:function($item){
				$item.className = $item.className.replace(/sel/,'');
			},
			itens:altColorNodes
		});
		//verify sizes quantities
		var sizes = null;
		var photosObjs = [];
		var noQuantItens = 0;
		var withoutProd = [];
		for(var i=0; i < altColorNodes.length; i++){
			if(_this.verifyId(altColorNodes[i].id)){
				
				sizes = _this.getPhotoInfoByColorId(_this.verifyId(altColorNodes[i].id)).sizes;
				for(var j=0; j<sizes.length; j++){
					if(sizes[j].quant == 0)
						noQuantItens++;
				}
				if(sizes.length == noQuantItens){
					if(_this._reminderButton){
						altColorNodes[i].style.opacity = .5;
						altColorNodes[i].style.filter = 'Alpha(Opacity=50)';
					}else{
						hDiv(altColorNodes[i]);
					}
					withoutProd[i] = true;
				}else{
					withoutProd[i] = false;
				}
				noQuantItens = 0;
			}
		}
		// apply functions
		var verifyOnce = false;
		var firstColor = 0;
		for(var i=0; i<altColorNodes.length; i++){
			// console.info("_this.verifyId: "+_this.verifyId(links[i].parentNode.parentNode.id));
			if(_this.verifyId(altColorNodes[i].id)){
				applyFunction(links[i]);
				if(!withoutProd[i]){
					if(!verifyOnce){
						verifyOnce = true;
						firstColor = i;
					}
				}
			}else{
				hDiv(altColorNodes[i]);
			}
		}
		// run function for the first element.
		_this._alternateColors.on(firstColor);
		return true;
	};
	/**
		ProductNavigation._getSizes. Construct sizes list.
		@param $id:String. Color Id.
		@return Boolean.
	*/
	var sizesErrorMsgElm = null;
	this._getSizes = function($id){
		var sizes = _this.getPhotoInfoByColorId($id).sizes;
		// var availSizes = _this.getPhotoInfoByColorId($id).availSizes;
		var tempLi = null;
		if(!_this._liSizesModel)
			_this._liSizesModel = _this._clearUl(_this._sizesUl);
		var li = _this._liSizesModel;
		var writeData = function($node,$sizeObj){
			
			// delete error message
			if(sizesErrorMsgElm){
				delElm(sizesErrorMsgElm);
				sizesErrorMsgElm = null;
			}
			
			// select option
			_this._alternateSizes.on($node);
			
			// refresh hidden values by size
			_this._refreshHiddens($sizeObj.inputHiddens);
			gTag('input',$node)[0].checked = true;
			
			// write product detail
			_this._writeProductDetail($sizeObj,function($obj){
				_this._txtSizeElm.innerHTML = '('+gTag('label',$node)[0].innerHTML.trim()+')';
			}, _this.getPhotoInfoByColorId($id));
			
		};
		// var value = null;
		var applyFunction = function($node,$sizeObj,$disp){
			$disp = !($disp === false); // by default is true, only is false if "false" (instead of falsy value) is passed;
			var actClassName = '';
			var overArea;
			if($node.overArea == null){
				$node.style.position = 'relative';
				$node.overArea = document.createElement('span');
				overArea = $node.overArea;
				overArea.className = 'overarea';
				overArea.style.position = 'absolute';
				overArea.style.zIndex = 2;
				overArea.style.top = overArea.style.left = 0;
				overArea.style.backgroundColor = 'red';
				overArea.style.opacity = 0;
				overArea.style.filter = 'Alpha(Opacity=0)';
				overArea.style.width = '1px';
				overArea.style.height = '27px';
				overArea.style.overflow = 'hidden';
				$node.appendChild(overArea);
			}else{
				overArea = $node.overArea;
			}
			
			$node.onmouseover = function(){
				$node.onmouseover = null;
				overArea.style.width = $node.offsetWidth+'px';
				overArea.style.height = '27px';
			};
			overArea.onmouseover = function(){
				if(actClassName.match(/sel/) != null){
					actClassName = $node.className;
				}
				$node.className = actClassName.replace(/sel/,'')+' over';
			};
			overArea.onmouseout = function(){
				if($node.className.match(/sel/) != null){
					actClassName = $node.className.replace(/over/,'');
				}
				$node.className = actClassName;
			};
			if($disp){
				overArea.onclick = function(){
					writeData($node,$sizeObj);
					_this.showBuyButton();
					actClassName = $node.className;
				};
			}else{
				overArea.onclick = function(){
					writeData($node,$sizeObj);
					_this.showReminderButton();
				};
			}
		};
		_this._clearUl(_this._sizesUl);
		// create new LIs
		var firstAvailableItem = 0;
		var runonce = true;
		for(var i=0; i<sizes.length; i++){
			gTag('input',li)[0].id = 'nm'+sizes[i].val;
			gTag('label',li)[0].attributes['for'].value = ''; //'nm'+sizes[i].val;
			gTag('label',li)[0].innerHTML = sizes[i].val;
			tempLi = _this._sizesUl.appendChild(li.cloneNode(true));
			if(sizes[i].quant < 1){
				applyFunction(tempLi,sizes[i],false);
				if(_this._reminderButton){
					gTag('label',tempLi)[0].className = 'indisponivel';
				}else{
					hDiv(tempLi);
				}
			}else{
				if(runonce){
					runonce = false;
					firstAvailableItem = i;
				}
				applyFunction(tempLi,sizes[i]);
			}
		}
		_this._alternateSizes = new AlternateItens({
			onFunction:function($item){
				$item.className += ' sel';
			},
			offFunction:function($item){
				$item.className = $item.className.replace(/sel/,'');
			},
			itens:gTag('li',_this._sizesUl)
		});
		
		//seleciona caso exista apenas 1 item disponível
		if(sizes.length == 1){
			gClass('overarea', '*', gTag('li',_this._sizesUl)[firstAvailableItem])[0].onclick();
		}else{
			_this.showBuyButton();
		}
		
		if(_this._form){
			var oldSubmit = _this._form.onsubmit;
			var returnVal = null;
			_this._form.onsubmit = function(){
				var inputs = gTag('input',_this._sizesUl);

				if(!validateRadio(inputs)){
					if(!sizesErrorMsgElm){
						sizesErrorMsgElm = createElm(_this._buyButton.parentNode,[
							'div',{'class':'feedLogin'},[
								'p',{style:'margin:0;'},'Por favor, selecione Cor e Tamanho para comprar.'
							]
						]);
					}
					//scrollToElm(_this._txtSizeElm.parentNode);
					return false;
				}
				if(typeof(oldSubmit) == 'function'){
					returnVal = oldSubmit();
					return returnVal;
				}
			};
		}
		return false;
	};
	this._writeProductDetail = function($sizeObj,$otherCustomization,$parentSizeObj){
		
		_this._productNameElm.innerHTML = $sizeObj.name || ($parentSizeObj ? $parentSizeObj.name : '');
		_this._txtRefElm.innerHTML = 'Ref.: '+$sizeObj.ref;
		
		// write or hide promo text
		if(_this._htmlPromoElm){
			if($sizeObj.pCode != null || ($parentSizeObj && $parentSizeObj.pCode != null)){
				if($sizeObj.pCode != null){
					_this._htmlPromoElm.innerHTML = $sizeObj.pCode;
				}else if ($parentSizeObj.pCode != null){
					_this._htmlPromoElm.innerHTML = $parentSizeObj.pCode;
				}else{
					_this._htmlPromoElm.innerHTML = '';
					hDiv(_this._htmlPromoElm);
				}
				sDiv(_this._htmlPromoElm);
			}else{
				hDiv(_this._htmlPromoElm);
			}
		}
		
		// write or hide division text
		if(_this._htmlDivisaoElm){
			if($sizeObj.dCode != null || ($parentSizeObj && $parentSizeObj.dCode != null)){
				if($sizeObj.dCode != null){
					_this._htmlDivisaoElm.innerHTML = $sizeObj.dCode;
				}else if ($parentSizeObj.dCode != null){
					_this._htmlDivisaoElm.innerHTML = $parentSizeObj.dCode;
				}else{
					_this._htmlDivisaoElm.innerHTML = '';
					hDiv(_this._htmlDivisaoElm);
				}
				sDiv(_this._htmlDivisaoElm);
			}
		}
		if(typeof($otherCustomization) == 'function'){
			$otherCustomization($sizeObj);
		}
		_this._writeSelos($sizeObj.selosPath || ($parentSizeObj ? $parentSizeObj.selosPath : null));
	};
	this._writeSelos = function($selos){
		if(_this._selosCont == null){
			return;
		}
		
		var cont = _this._selosCont;
		var actElm = null;
		cont.innerHTML = '';
		
		if(typeof($selos) != 'object' || $selos == null){
			hDiv(cont);
			return false;
		}else{
			if(typeof($selos.length) != 'number'){
				hDiv(cont);
				return false;
			}
		}
		
		sDiv(cont);
		/*
			array $selos agora é uma matriz Nx2, sendo que pra cada linha, a primeira coluna é o src da imagem, e a segunda é o texto alternativo da imagem
			ex: $selos[i][0] = '../Imagens/px.gif';
				$selos[i][1] = 'Alt e title da imagem';
		*/
		for(var i=0; i<$selos.length; i++){
			actElm = createElm(cont,[
				'img',{
					alt:$selos[i][1],
					title:$selos[i][1],
					src:$selos[i][0]
				}
			]);
		}
	};
	
	/**
	 * refresh hidden values with specific product values
	 * @param $hiddens:Object Object 
	 * @return nothing
	 */
	this._refreshHiddens = function($hiddens){
		// apply input type hidden values
		var hiddens = $hiddens;
		var currHiddenElm = null;
		
		// HERE!
		if(hiddens != null){
			for(var name in hiddens){
				currHiddenElm = $(name);
				if(currHiddenElm != null){
					currHiddenElm.value = hiddens[name];
				}
			}
		}
	}
	this._createReminderButton = function($imageSrc){
		this._reminderButton = createElm(this._buyButton.parentNode,[
			//'a',{href:'javascript:;',onclick:this.openReminderBox, style:'display:none;'},[
				'img',{src:$imageSrc,alt:'',title:'', style:'display:none'}
			// ]
		]);
	};
	this.showReminderButton = function(){
		if(this._reminderButton && this._buyButton){
			sDiv(this._reminderButton);
			hDiv(this._buyButton);
		}
	};
	this.showBuyButton = function(){
		if(this._reminderButton && this._buyButton){
			hDiv(this._reminderButton);
			sDiv(this._buyButton);
		}
	};
	this.getProductData = function(){
		var name = gTag('h2',_this._colorUl.parentNode)[0].innerHTML.trim();
		var ref = gTag('small',_this._colorUl.parentNode)[0].innerHTML.trim();
		var color = {
			name:null,
			hexa:null
		};
		var size = null;
		var colorLis = gTag('li',_this._colorUl);
		var sizesLis = gTag('li',_this._sizesUl);
		for(var i=0; i<colorLis.length; i++){
			if(colorLis[i].className.trim() == 'sel'){
				color.hexa = gTag('label',colorLis[i])[0].style.backgroundImage;
				color.name = _this._txtColorElm.innerHTML.trim();
				color.name = color.name.slice(1,color.name.length-1);
			}
		}
		size = _this._txtSizeElm.innerHTML.trim();
		size = size.slice(1,size.length-1);
		
		return {name:name,ref:ref,color:color,size:size};
	};
	this.openReminderBox = function(){
		var populateBox = function(){
			var data = _this.getProductData();
			
			$('titlePopAviseme').innerHTML = data.name;
			$('refPopAviseme').innerHTML = data.ref;
			$('productColorTxtPopAviseme').innerHTML = '('+data.color.name+')';
			$('productColorPopAviseme').style.backgroundImage = data.color.hexa;
			$('productSizeTxtPopAviseme1').innerHTML = '('+data.size+')';
			$('productSizeTxtPopAviseme2').innerHTML = data.size;
			gTag('img',$('productSizeTxtPopAviseme1').parentNode)[0].src = gTag('img',_this._txtSizeElm.parentNode)[0].src;
			gTag('img',$('productSizeTxtPopAviseme1').parentNode)[0].alt = gTag('img',_this._txtSizeElm.parentNode)[0].alt;
			
			eval(gTag('script',_this.reminderBoxNode.box)[0].innerHTML.trim());
		};
		Box.fetchHtml('../produto/aviseme.aspx',{
			contStyle:'width:450px;',
			callback:function(e){
				_this.reminderBoxNode = e;
				populateBox();
			}
		});
	};
	this.openIndicaAmigo = function(){
		var populateBox = function(){
			var data = _this.getProductData();
			
			$('titlePopIndicaAmigo').innerHTML = data.name;
			$('refPopIndicaAmigo').innerHTML = data.ref;

		};
		Box.fetchHtml('../produto/indiqueamigo.aspx',{
			contStyle:'width:450px;',
			callback:function(e){
				_this.indiqueBoxNode = e;
				populateBox();
			}
		});
		eval(gTag('script',_this.indiqueBoxNode.box)[0].innerHTML.trim());
	};
	
	/**
		ProductNavigation._getAvailVideos. Construct videos list.
		
		@param $id:String. Color Id.
		@param $initNum:Number. Initial number.
		@return Boolean.
	*/
	
	this._overThumb = function($node){
		var tempLis = [];
		var lis = [];
		var i;
		
		tempLis = gTag('li', _this._toZoomUl);
		for(i=0; i< tempLis.length; i++){
			tempLis[i].style.borderColor = '';
			lis[lis.length] = tempLis[i];
		}
		
		tempLis = gTag('li', _this._videoList);
		for(i=0; i< tempLis.length; i++){
			tempLis[i].style.borderColor = '';
			lis[lis.length] = tempLis[i];
		}
		
		$node.style.borderColor = "#000000";
	};
	
	this._getAvailVideos = function($id, $initNum){
		
		hDiv(this._videoContainer);
		
		var videoQuantity = (_this.getPhotoInfoByColorId($id).videos != null) ? _this.getPhotoInfoByColorId($id).videos.length : 0;
		var tempLis = [];
		var applyFunction = function($node, $index){
			
			var img = gTag('img',$node)[0];
			var videoObject = _this.getPhotoInfoByColorId($id).videos[$index];
			var fo;
			var videoURL;
			
			if(videoObject.thumb && img){
				img.src = videoObject.thumb;
				img.width = 
				img.height = 50;
			}
			if(videoObject.url != null){
				var videoURL = videoObject.url.match(/\?v=(.[^&$]*)(&|$)/);
				if(videoURL != null){
					if(videoURL[1] != null){
						fo = new FlashObject('http://www.youtube.com/v/'+videoURL[1].replace(/(^\s+|\s+$)/g, '')+'&rel=0&hl=pt-br&fs=1', 'embedVideo', 410, 410, false, 8);
						fo.addParam('wmode', 'transparent');
					}
				}
			}
			
			addEvent($node, 'click', function(){
				if(fo){
					_this._photoToZoomObj._zoomObj.link.style.visibility = 'hidden';
					if(_this._videoContainer.style.display != 'block'){
						sDiv(_this._videoContainer);
					}
					fo.write(_this._videoContainer.id);
				}else{
					throw new Error('[ProductNavigation._getAvailVideos]: O link do youtube não está no formato certo. Formato esperado: http://www.youtube.com/watch?v=ID_DO_VIDEO" ou "http://www.youtube.com/watch?v=ID_DO_VIDEO&f...."');
				}
			});

			$node.onmouseover = function(e){
				_this._overThumb($node);
			};
		};
		
		_this._clearUl(_this._videoList);
		
		if(videoQuantity > 0){
			sDiv(_this._videoList.parentNode);
			for(var i=0; i<videoQuantity; i++){
				tempLis[tempLis.length] = _this._videoList.appendChild(_this._videoListLi.cloneNode(true));
				applyFunction(tempLis[tempLis.length-1], i);
			}
		}else{
			hDiv(_this._videoList.parentNode);
		}
		
	};
	/**
		ProductNavigation._getAvailPhotos. Construct photos list.
		
		@param $id:String. Color Id.
		@param $initNum:Number. Initial number.
		@return Boolean.
	*/
	this._getAvailPhotos = function($id, $initNum){
		$initNum = $initNum || 1;
		var isLoaded = false;
		var photoQuantity = _this.getPhotoInfoByColorId($id).photoQuantity;
		_this._clearUl(_this._toZoomUl);
		var tempLis = [];
		var imgsToLoad = [];
		//_this._openBigPhoto($id,$initNum);
		var applyFunction = function($node, $cont){
			var img = gTag('img',$node)[0];
			
			img.src = _this._spacer.getImage().src;
			img.width = 
			img.height = 50;
			imgsToLoad[imgsToLoad.length] = new LoadImage(_this.getPhotoPath($id,'small',$cont),{
				onStart:function(){
					// console.info('começou a carregar');
				},
				onError:function(){
					hDiv($node);
					// console.info('erro ao carregar');
				},
				onComplete:function($img){
					// console.info('carregou com sucesso');
					isLoaded = true;
					img.src = $img.src;
					img.alt = img.title = '';
				}
			});
			
			$node.onmouseover = function(e){
				_this._photoToZoomObj.load(_this.getPhotoPath($id,'big',$cont));
				_this._overThumb($node);
			};
			$node.onclick = function(e){
				_this._photoToZoomObj._zoomObj.link.style.visibility = 'visible';
				if(_this._videoContainer.style.display == 'block'){
					hDiv(_this._videoContainer);
					_this._videoContainer.innerHTML = '';
				}
			}

		};
		_this._bigImage.style.visibility = 'visible';
		if(photoQuantity > 0){
			sDiv(_this._toZoomUl.parentNode);
			for(var i=0; i<photoQuantity; i++){
				tempLis[tempLis.length] = _this._toZoomUl.appendChild(_this._toZoomLi.cloneNode(true));
				applyFunction(tempLis[tempLis.length-1],(i+1));
				_this._photoToZoomObj.load(_this.getPhotoPath($id,'big',i+1), null, false);
			}
			_this._photoToZoomObj.load(_this.getPhotoPath($id,'big',$initNum));
			tempLis[$initNum-1].style.borderColor = "#000000";

			if(photoQuantity > 1){
				sDiv(_this._hideIfNoPhoto);
			}else{
				hDiv(_this._hideIfNoPhoto);
			}
		}else{
			hDiv(_this._hideIfNoPhoto);
			_this._photoToZoomObj.getZoomObj().stop();
			_this._photoToZoomObj.unload();
			try{
				_this._bigImage.src = _this._unavailablePhoto.getImage().src;
			}catch(e){
				_this._bigImage.style.visibility = 'hidden';
			}
		}
	};
	/**
		ProductNavigation._centerSizeList. Center avaliable sizes horizontally.
		
		@return Boolean.
	*/
	this._centerSizeList = function(){
		_this._sizesUl.style.left = '50%';
		_this._sizesUl.style.marginLeft = '-'+(_this._sizesUl.offsetWidth/2)+'px';
		return true;
	};
	//}
	//{ ************ UTIL STUFF ************
	/**
		ProductNavigation.getPhotoPath. Get the path name of a photograph based in values defined on the constructor.
		
		@param $colorId:String - color id.
		@param $size:String - Get image with the defined size. Valid values: "small", "big", "zoom".
		@param $number:Number - Number of the image.
		@return String - Generated path name or False for error.
	*/
	this.getPhotoPath = function($colorId, $size, $number){
		var photoObj = this.getPhotoInfoByColorId($colorId);
		var photoQuantity = $number > photoObj.photoQuantity ? photoObj.photoQuantity : $number;
		switch($size){
			case 'small':
			case 'big':
			case 'zoom':
				return this._imgPath + (photoObj.colorPath+'/' || '') + (photoObj.produtoPath+'/'+photoObj.produtoPath || '') + (this._fileList[$size] || '') + (photoQuantity || '') + '.jpg';
				break;
			default:
				return false;
				break;
		}
	};
	/**
		ProductNavigation.getPhotoInfoByColorId. Get photo object based on the colorId.
		
		@param $colorId:String - color id.
		@return Object or false in case of an uknown $colorId.
	*/
	this.getPhotoInfoByColorId = function($colorId){
		var photos = _this._photos;
		for(var i=0; i<photos.length; i++){
			if(photos[i].colorId == $colorId)
				return photos[i];
		}
		return false;
	};
	this.verifyId = function($id){
		var photos = _this._photos;
		for(var i=0; i<photos.length; i++){
			if(photos[i].colorId == $id){
				//console.info($id+': '+photos[i].colorId);
				return photos[i].colorId;
			}
		}
		return false;
	};

	/**
		ProductNavigation._clearUl. Clear UL Node and returns the first li.
		
		@param $node:Node - UL Node.
		@return Node or False for error.
	*/
	this._clearUl = function($node){
		var arr = [];
		var li = null;
		
		// copy LI nodes to an array;
		for(var i=0; i<gTag('li',$node).length; i++) arr[arr.length] = gTag('li',$node)[i];
		// clone first LI;
		if(arr.length >= 1)li = arr[0].cloneNode(true);
		// clear ul;
		for(var i=0; i<arr.length; i++)delElm(arr[i]);
		// return first LI;
		return li;		
	};
	/**
		ProductNavigation.getFileList. Get file list.
		
		@return Object. File list.
	*/
	this.getFileList = function(){
		return this._fileList;
	};
	//}
	//{ ************ INIT ************
	/**
		ProductNavigation.init. Initialize the class.
		
		@param $obj:Object - Elements that will be part of the product pages funcionality: colorUl:Node (ul); sizesUl:Node (ul); toZoomUl:Node (ul); bigImageCont:Node; imgToZoomSize:Object{width:Number, height:Number};
		@return Boolean.
	*/
	this._toZoomLi = this._clearUl(this._toZoomUl);
	this._videoListLi = this._clearUl(this._videoList);
	if(typeof($obj.imgToZoomSize) != 'object') $obj.imgToZoomSize = {width:50,height:50};
	var img = gTag('img',this._toZoomLi)[0];
	img.width = $obj.imgToZoomSize.width;
	img.height = $obj.imgToZoomSize.height;
	img.src = url_global+'img/px.png';
	
	try{
		this._buyButton = $obj.elements.buyButton;
		this._createReminderButton($obj.elements.availButton.getImage().src);
	}catch(e){
		// do nothing
	}
	this._applyFunctions();
	
	if(this._btEnviaAmigo)
		this._btEnviaAmigo.onclick = this.openIndicaAmigo;
	
	// monta listas
	if(this._colorUl)this._colorUl.className = 'colorList';
	if(this._sizesUl)this._sizesUl.className = 'sizeList';
	//}
};
//}
/**
	CustomShirt. Custom shirt class
	@autor Marcelo Miranda Carneiro
	@version 0.1
	@requires main.js v10+
	@example
		<code>
			
		</code>	
*/
//{
var CustomShirt = function($obj){
	var _this = this;
	
	$obj = Type.object($obj);
	$obj.form = Type.node($obj.form);
	$obj.nodePrice = Type.node($obj.nodePrice);
	$obj.name = Type.object($obj.name);
	$obj.number = Type.object($obj.number);
	
	var name = $obj.name ? {
		node: $obj.name.node,
		initText: $obj.name.initText || '',
		maxLength: $obj.name.maxLength || 12,
		nodePrice: $obj.name.nodePrice,
		unityPrice: $obj.name.unityPrice
	} : null;
	
	var number = $obj.number ? {
		node: $obj.number.node,
		maxLength: $obj.number.maxLength || 2,
		nodePrice: $obj.number.nodePrice,
		unityPrice: $obj.number.unityPrice
	} : null;
	
	this.applyFunctions = function(){
		if(name){
			this.applyNameFunction();
			name.node.onkeyup();
			name.node.blur();
			name.node.maxLength = name.initText.length;
			name.node.value = name.initText;
		}
		if(number){
			this.applyNumberFunction();
			number.node.blur();
		}
	};

	this.applyNameFunction = function(){
		name.node.onkeypress = function($e){
			$e = $e || window.event;
			return only('restrict','àáãâéêèìíîóõôòúûùÁÃÂÀÉÊÈÌÍÎÓÕÔÒÙÚÛñÑ. ',$e);
		};
		name.node.onkeyup = function(){
			_this.writeContent();
			name.node.value = name.node.value.toUpperCase();
		}
		name.node.onfocus = function(){
			if(name.node.value == name.initText || name.node.value.indexOf(name.initText) == 0){
				name.node.value = '';
				name.node.maxLength = name.maxLength;
				name.maxLength
			}
		};
		name.node.onblur = function(){
			if(!_this.hasText(name.node.value)){
				name.node.maxLength = name.initText.length;
				name.node.value = name.initText;
			}else{
				name.node.value = name.node.value.trim();
			}
		};

	};
	this.applyNumberFunction = function(){
		number.node.maxLength = number.maxLength;
		number.node.onkeyup = _this.writeContent;
		number.node.onkeypress = function($e){
			$e = $e || window.event;
			return only('num',false,$e);
		};
	};
	this.enableFields = function(){
		number.node.disabled = false;
		name.node.disabled = false;
		number.node.style.backgroundColor = 
		name.node.style.backgroundColor = '';
	};
	this.disableFields = function(){
		number.node.disabled = true;
		name.node.disabled = true;
		number.node.style.backgroundColor = 
		name.node.style.backgroundColor = '#E1E1E1';
	};
	this.writeContent = function(){
		if($obj.nodePrice){
			var currentPrice = 0;
			if(name && name.node.value.indexOf(name.initText) < 0 && _this.hasText(name.node.value)){
				currentPrice += name.unityPrice;
			}
			if(number && _this.hasText(number.node.value)){
				currentPrice += number.unityPrice;
			}
			if(currentPrice <= 0){
				$obj.nodePrice.innerHTML = '';
			}else{
				$obj.nodePrice.innerHTML = '+ R$ ' + _this.writePrice(currentPrice);
			}
		}else{
			if(name && name.node){
				if(name.node.value.indexOf(name.initText) == 0 || !_this.hasText(name.node.value)){
					name.nodePrice.innerHTML = '+ R$ ' + _this.writePrice(0);
				}else{
					name.nodePrice.innerHTML = '+ R$ ' + _this.writePrice(name.unityPrice);
				}
			}
			if(name && number.node){
				if(!_this.hasText(number.node.value)){
					number.nodePrice.innerHTML = '+ R$ ' + _this.writePrice(0);
				}else{
					number.nodePrice.innerHTML = '+ R$ ' + _this.writePrice(number.unityPrice);
				}
			}
		}
	};
	this.writePrice = function($price){
		var price = (Math.round($price*1000)/1000).toString().replace(/\./,',');
		price = price.split(',').length > 1 ? (price.split(',')[1].length == 1 ? price+'0' : price) : price+',00';
		return price;
	};
	this.hasText = function($txt){
		return $txt.match(/^(?:\s+)?$/) == null;
	};

	// init
	this.applyFunctions();
	if($obj.form){
		var oldSubmit = $obj.form.onsubmit;
		$obj.form.onsubmit = function(){
			if(name.node.value.indexOf(name.initText) >= 0 ){
				name.node.value = '';
			}
			if(typeof(oldSubmit) == 'function'){
				return oldSubmit();
			}
		};
	}
};
//}
/**
	Detail Window
	@autor Marcelo Miranda Carneiro
	@version 0.1 12:17 4/1/2008
	@requires UrlUtil class, AlternateItens class , Main.js v10+
 */
//{
var DetailWindow = function($menuElms, $contElms){
	var _this = this;
	var _alternate = null;
	var _menuElms = typeof($menuElms) != 'string' ? $menuElms : [];
	var _contElms = typeof($contElms) != 'string' ? $contElms : [];
	
	var _alternateInit = function(){
		_alternateMenu = new AlternateItens({
			onFunction:function($item){
				$item.className = 'on';
				gTag('img',$item)[0].src = gTag('img',$item)[0].src.replace(/_off/,'_on');
			},
			offFunction:function($item){
				$item.className = 'off';
				gTag('img',$item)[0].src = gTag('img',$item)[0].src.replace(/_on/,'_off');
			},
			itens:_menuElms
		});
		_alternateCont = new AlternateItens({
			onFunction:function($item){
				sDiv($item);
			},
			offFunction:function($item){
				hDiv($item);
			},
			itens:_contElms
		});
	};
	var _applyEvents = function(){
		_alternateMenu.clear();
		_alternateCont.clear();
		var apply = function(i){
			var a = gTag('a',_menuElms[i])[0];
			EventUtil.add(a,'click',function(){
				_this.select(i);
			});
		};
		for(var i=0; i<_menuElms.length; i++){
			apply(i);
			_contElms[i].id += '_noMoreAnchor';
		}
		_this.select();
	};
	this.select = function($num){
		if(typeof($num) != 'number'){
			$num = 0;
			for(var i=0; i<_menuElms.length; i++){
				if(UrlUtil.anchor(gTag('a',_menuElms[i])[0].href) == UrlUtil.anchor()){
					$num = i;
					break;
				}
			}
		}
		_alternateMenu.on($num);
		_alternateCont.on($num);
	};
	_alternateInit();
	_applyEvents();
	this.select();
};
//}
/**
	Load Image
	@autor Marcelo Miranda Carneiro
	@version 0.2 15:00 7/1/2008
	@example
		<code>
			var teste = new LoadImage('http://www.google.com.br/intl/pt-BR_br/images/logo.gif',{
				onStart:function(IMAGE_OBJECT){
					CODE
				},
				onError:function(IMAGE_OBJECT){
					CODE
				},
				onComplete:function(IMAGE_OBJECT){
					CODE
				}
			})
		</code>
*/
//{ 
var LoadImage = function($url,$obj){
	
	if(!$url)return alert('LoadImage ERROR: Image source is not defined.');
	
	var _obj = $obj || {};
	var loaded = false;

	var _img = document.createElement('img');
	_img.onerror = function(){
		if(typeof(_obj.onError) == 'function'){
			_obj.onError(_img);
		}else{
			alert('Erro ao carregar a imagem:\n'+_img.src);
		}
	};
	_img.onload = function(){
		loaded = true;
		if(typeof(_obj.onComplete) == 'function'){
			_obj.onComplete(_img);
		}
	};
	if(typeof(_obj.onStart) == 'function')
		_obj.onStart(_img);
	_img.src = $url;

	/**
		LoadImage.getImage. Get Image Object.
		
		@return Image.
	*/
	this.getImage = function(){
		return _img;
	};
	/**
		LoadImage.removeObj. Remove instance of this class.
		
		@return nothing.
	*/
	this.removeObj = function(){
		delete this;
	};
	/**
		LoadImage.isLoaded. Verify if the image is loaded.
		
		@return Boolean.
	*/
	this.isLoaded = function(){
		return loaded;
	};
};
//}
/**
	Alternate Itens.
	@autor Marcelo Miranda Carneiro
	@version 0.1 15:19 9/1/2008
	@requires
	@example
		<code>
			var teste = new AlternateItens({
				onFunction:function($item){
					$item.style.border = '1px solid red';
				},
				offFunction:function($item){
					$item.style.border = '1px solid blue';
				},
				itens:gTag('li',$('wdwCategoryLst'))
			});
			teste.on(gTag('li',$('wdwCategoryLst'))[0])
			teste.clear();
		</code>	
*/
//{
var AlternateItens = function($obj){
	
	var _this = this;
	var _allItens = [];
	var _onFunction = [];
	var _offFunction = [];
	
	/**
		addFunction - Private. Record ON and OFF functions in private variables.
		
		@param $fnc:Function. ON or OFF function.
		@param $type:String. Identification of the function. Valid values: "on", "off".
		@return nothing.
	*/
	this.addFunction = function($fnc, $type){
		if(!$fnc)return;
		if(typeof($fnc) != 'function'){
			throw 'AlternateItens.setOnFunction ERROR: Parameter MUST be a function!\n$fnc: '+$fnc+' - '+typeof($fnc);
			return;
		}
		switch($type){
			case 'on':
				_onFunction[_onFunction.length] = $fnc;
				break;
			case 'off':
				_offFunction[_offFunction.length] = $fnc;
				break;
		}
	};
	
	/**
		_onoffFunction - Private. Run ON or OFF function.
		
		@param $which:Object or Number. Object that will be changed with the function.
		@param $clear:Boolean. If "clear" Function will be executed before ON or OFF Function.
		@param $type:String. Identification of the function. Valid values: "on", "off".
		@return nothing.
	*/
	var _onoffFunction = function($which,$clear,$type){
		var fnc = [];
		switch($type){
			case 'on':
				fnc = _onFunction;
				break;
			case 'off':
				fnc = _offFunction;
				break;
			default:
				return;
		}
		
		if($clear !== false){
			_this.clear();
		}
		
		if(typeof($which) == 'number'){
			if(_allItens[$which]){
				for(var i=0; i<fnc.length; i++){
					fnc[i](_allItens[$which]);
				}
			}else{
				throw new Error('AlternateItens ERROR: item doesn\'t exists!\nItem number: '+$which+'. Maximum item: '+(_allItens.length-1));
				return;
			}
		}else if(typeof($which) == 'object'){
			for(var i=0; i<_allItens.length; i++){
				if($which == _allItens[i]){
					for(var j=0; j<fnc.length; j++){
						fnc[j]($which);
					}
					return;
				}
			}
			throw new Error('AlternateItens ERROR: item doesn\'t exists in the array!\nItem passed: '+$which+" / total items: "+_allItens);
			return;
		}
	};
	/**
		AlternateItens.clear. Executes off functions in all itens "_allItens" Array.
		@param Nothing.
		@return Nothing.
	*/
	this.clear = function(){
		for(var i=0; i<_allItens.length; i++){
			for(var j=0; j<_offFunction.length; j++){
				_offFunction[j](_allItens[i]);
			}
		}
	};
	/**
		AlternateItens.on. Executes on function.
		@param $which:Object or Number. Object that will be changed with the function.
		@param $clear:Boolean. If "clear" Function will be executed before ON or OFF Function.
		@return nothing.
	*/
	this.on = function($which,$clear){
		_onoffFunction($which,$clear,'on');
	};
	/**
		AlternateItens.off. Executes off function.
		@param $which:Object or Number. Object that will be changed with the function.
		@param $clear:Boolean. If "clear" Function will be executed before ON or OFF Function.
		@return nothing.
	*/
	this.off = function($which,$clear){
		_onoffFunction($which,$clear,'off');
	};
	/**
		AlternateItens.setItens. Set the itens.
		@param $arr:Array or Object. List of itens.
		@return nothing.
	*/
	this.setItens = function($arr){
		if(typeof($arr) == 'string'){
			throw new Error('AlternateItens.setItens ERROR: Parameter MUST be an array!\n$arr: '+$arr);
			return;
		}
		_allItens = $arr;
	};
	/**
		AlternateItens.getItens. Get the itens.
		@param nothing
		@return $arr:Array or Object.
	*/
	this.getItens = function(){
		return _allItens;
	};

	/* INIT */
	this.addFunction($obj.onFunction,'on');
	this.addFunction($obj.offFunction,'off');
	if($obj.itens)
		this.setItens($obj.itens);
};
//}

var multipleNodeActions = function($elms,$func){
	if(typeof($func) != 'function')
		return false;
	
	for(var i=0; i<$elms.length; i++){
		if(NodeUtil.getNode($elms[i]))
			$func(NodeUtil.getNode($elms[i]));
	}
	return true;
};
