/* STRING FUNCTIONS *****************************************/
/* TRIM();
 * Strip whitespace from the beginning and end of a string.
 * Usage: var str = "  abc  ".trim();
 */
String.prototype.trim = function(){
	return this.replace(/^ +| +$/g,"");
}


/* ARRAY FUNCTIONS ******************************************/
/* LAST();
 * Return the last element of an array.
 * Usage: var arr = ['a','b','c','d'].last();
 */
Array.prototype.last = function(){
	return this.reverse()[0];
}


/* MISC FUNCTIONS *******************************************/
/* $();
 * Return a reference to the element
 * Usage: var el = $('id');
 */
function $(w){
		return document.getElementById(w);
}
/* _s();
 * Change the inline style of an element
 * Usage: _s($('id'),'color','#f00');
 */
function _s(obj,p,v){
	obj.style[p] = v;
}

/* printThis();
 * Print the selected Element
 * Usage: printThis(this.id);
 */
function printThis(w){
		var s = document.createElement('link');
			s.setAttribute('type', 'text/css');
			s.setAttribute('media','print');
			s.setAttribute('rel','stylesheet');
			s.setAttribute('id','printThis');
			s.setAttribute('href',APATH+'styles/pic-print.css');
		
		$('img-printer').src = w.src;
		document.getElementsByTagName('head')[0].appendChild(s);
		window.print();
		setTimeout(function(){
			var el = document.getElementsByTagName('head')[0];
				el.removeChild(el.lastChild);
			},3000
		);
}

/* download();
 * Create a direct link to an image
 * Usage: download(this,'revestimento','catalogo');
 */
function download(w,c,d){
	var n  = APATH;
		n += 'download.php?cat=';
		n += c;
		n += '&dir=';
		n += d;
		n += '&pic=';
		n += w.parentNode.previousSibling.src.split('/').last();
	
	w.href = n;
}

/* addVideo();
 * Add a new Video in the Container
 * Usage: addVideo('revestimento','video.flv','preview.jpg');
 */
function addVideo(rawLink,videoFlv,videoImg){
	var s1 = new SWFObject(APATH+"flash/player.swf","mpl","320","224","7");
	s1.addParam("allowfullscreen","true");
	s1.addVariable("file",APATH+"produtos/"+rawLink+"/videos/"+videoFlv);
	s1.addVariable("image",APATH+"produtos/"+rawLink+"/videos/"+videoImg);
	s1.addVariable("width","320");
	s1.addVariable("height","224");
	s1.addVariable("volume","50");
	s1.write("videoContainer");
}

/* changeTab();
 * Change the clicked Tab
 * Usage: changeTab(this);
 */
function changeTab(w){
	var el = document.getElementById('opts');
	var li = el.getElementsByTagName('li');
	var dv = ['Fotos','Catálogo','Downloads','Videos','Indicar'];
	for(var x=0,y=li.length;x<y;x++){
		if(li[x].className!='no')
		li[x].className = '';
	}
	for(var x=0, y=dv.length; x<y; x++){
		$(dv[x]).style.display = 'none';
	}
	w.parentNode.className = 'hi';
	document.getElementById(w.innerHTML).style.display = 'block';
	document.getElementById(w.innerHTML).focus();
}
	
/* STYLE *****************************************************/
/* getStyle();
 * Return an external css property
 * Usage: getStyle($('id'),'height');
 */
function getStyle(oNode, sProperty) {
    if(document.defaultView) {
        return document.defaultView.getComputedStyle(oNode, null).getPropertyValue(sProperty);
    } else if(oNode.currentStyle) {
        for(
			var reExp = /-([a-z])/;
			reExp.test(sProperty);
			sProperty = sProperty.replace(reExp, RegExp.$1.toUpperCase())
			);
        return oNode.currentStyle[sProperty];
    }
  
    return null;
}


/* FORM VALIDATION FUNCTION *********************************/
/* valida_contato();
 * Check the contact form
 * Usage: onsubmit="return valida_contato(this)";
 */
function valida_contato(f){

	var countError 		= 0;
	var msgsError 		= new Array();
	var textoPattern 	= new RegExp('^[\\w\\s\\n\\t\\r!?,\.:;áàãâÁÀÂÃéèêÈEÊíìîÍÌÎóòôõÓÒÔÕúùûÚÙÛçÇ@_ -]+$');
	var numeroPattern 	= new RegExp('^[\\d]+$');
	
	var frml = document.forms[f.name];
	var cont = frml.elements['contato'];
	var tDDD = frml.elements['DDD'];
	var fone = frml.elements['telefone'];
	var unfe = frml.elements['estado'];
	var city = frml.elements['cidade'];
	var mail = frml.elements['email'];
	var subj = frml.elements['assunto'];

	var texto 	= [cont,mail];
	var numero 	= [tDDD,fone];
	var escolha = [unfe,city,subj];
	if(!frml.elements['empresa'].disabled){
		var empr = frml.elements['empresa'];
		texto.push(empr);
	}
	
	for(x=0,y=texto.length;x<y;x++){
		if(!textoPattern.test(texto[x].value)){
			msgsError[countError] = '- Preencha o campo '+String(texto[x].name).toUpperCase();
			++countError;
		}
	}
	
	for(x=0,y=numero.length;x<y;x++){
		if(!numeroPattern.test(numero[x].value.replace(/[^.-_ ]+/gi,""))){
			msgsError[countError] = '- Preencha o campo '+String(numero[x].name).toUpperCase();
			++countError;
		}
	}
	
	for(x=0,y=escolha.length;x<y;x++){
		if(escolha[x].value=='none'){
			msgsError[countError] = '- Escolha uma opção no campo '+String(escolha[x].name).toUpperCase();
			++countError;
		}
	}
	
	var str = msgsError.join('|');
	if(countError != 0){
		alertar('Erro no Preenchimento',str.replace(/[\|]+/gi,'<br />'),true);
	}
	return (countError != 0) ? false : true;
}

/* NEW WINDOW FUNCTION **************************************/
/* abrirJanela();
 * Open a new window with a Picture
 * Usage: abrirJanela('pic.jpg');
 */
var janela;
function abrirJanela(){
	janela = window.open("http://www.maxtelas.com.br/prod_popup.php?picID="+arguments[0],
	"",
	 "width=375,height=375,menubar=no,location=no,resizable=no,scrollbars=no,status=no");
}

/* OVERLAY CLASS ********************************************/
/* overlay{};
 * Create a transparent overlay in the page
 * Usage: overlay.add(); or overlay.remove();
 */
overlay = {
	
	add : function(){
		var c = overlay.getSize();
		var o = document.createElement("div");
			o.setAttribute("id", "overlay");
			/*o.setAttribute("onclick", "overlay.remove()");
			if(o.attachEvent){
				o.attachEvent(("onclick"), function(){ overlay.remove(); });
			}*/
	
		document.body.appendChild(o);
	
		var el = document.getElementsByTagName('select');
		for(x=0,y=el.length;x<y;x++){
			_s(el[x],'visibility','hidden');
		}
	
		var el = $('overlay');
			el.className = "overlay";
			el.style.height = c.b+'px';	
	},
	
	remove : function(){
		$('tt').innerHTML  = '';
		$('msg').innerHTML = '';
		document.body.removeChild($('overlay'));
		var el = document.getElementsByTagName('select');
		for(x=0,y=el.length;x<y;x++){
			_s(el[x],'visibility','visible');
		}
	},
	
	getSize : function(){
		var w = document.body.clientWidth || innerWidth;
		var h = document.body.clientHeight || innerHeight;
		var a = window.scrollMaxX || 0;
		var b = window.scrollMaxY || 0;
		return {a:w,b:h+b}
	}	
}

/* AJAX FUNCTIONS *******************************************/
/* Async();
 * Create a XMLHttp Object
 * Usage: Async();
 */
function Async(){
	if(window.XMLHttpRequest){
		return new XMLHttpRequest();
	}
	else if(window.ActiveXObject){
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
	else{
		alert('Houve um problema com a requisição');
	}
}

function post(f){
	
	var ld = document.getElementById('load');
		ld.style.display = 'block;'
		
		document.getElementById('sendMsg').style.visibility='hidden';
	
	var url = APATH+"indicar.php";
	var params  = "nome="+f.elements['nome'].value;
		params += "&email="+f.elements['email'].value
		params += "&to="+f.elements['to'].value;
		params += "&page="+window.location.href.replace(/([\/]?)([a-zA-Z=&?])*$/,'').split('/').last();
		
	http = Async();
	
	http.open("POST", url, true);
	
	//Send the proper header information along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");
	
	http.onreadystatechange = function() {//Call a function when the state changes.
		if(http.readyState == 4 && http.status == 200) {
			if(http.responseText=='sucesso'){
				document.getElementById('sendMsg').style.visibility='visible';
				f.reset();
			}else{
				alert(http.responseText);
			}
			ld.style.display = 'none';
			
		}
		
	}
	http.send(params);	
}
/* get();
 * Sends a request
 * Usage: get('value');
 */
function get(valor){
	if(valor != 'none'){
		http = Async();
		http.open('GET',APATH+'cidades.php?uf='+valor,true);
		http.onreadystatechange = handler;
		http.send(null);
	}else{
		var el = document.forms[0].elements['cidade'];
			el.options.length = 0;
			el.options[0] = new Option('-- Selecione o Estado --','none');
	}
}

/* handler();
 * Manage data received
 * Usage: handler();
 */
function handler(){
	var campo = document.getElementById('cidade');
	
	if(http.readyState==4){
		var xml = http.responseXML;
		var nodes = xml.getElementsByTagName('cidade');
		
		campo.options.length = 0;
		campo.options[0] = new Option('-- Selecione a Cidade --','none');
		
		for(x=0;x<nodes.length;x++){
			var v = nodes[x].firstChild.nodeValue;
			campo.options[x] = new Option( v, v );
		}		
	}
}

/* GALLERY FUNCTIONS *******************************************/
/* pic();
 * Change gallery picture
 * Usage: pic.load('target','new-image.jpg[,30]');
 */
pic = {

	// Main Variables
	'i' 		: null,
	'el'		: null,
	'_name'		: 'pic',
	'eTime'		: 40,
	
	// Main Function
	'load'		: function(e,t){
	
		// Main Element
		this['el'] = $(e);
		
		// Change the Time
		if(typeof(arguments[2])=='number'){
			this['eTime'] = arguments[2];
		}
	
		// Start the Process
		this['fadeOut'](100,t);
	},

	'fadeOut' 	: function(v,t){

		if(v>=-1){
		var _c = this;
			// Change the Opacity
			this['el'].style.opacity = v/100;
			this['el'].style.filter  = 'alpha(opacity='+v+');'
			
			// Loop
			this['i'] = setTimeout(
				function(){
					_c['fadeOut'](v-20,t);
				},this['eTime']
			);
			
		}else{
			// Chain Other Functions
			this['changePic'](t);
		}
	}, // fadeOut End

	'fadeIn'	: function (v){

		if(v<101){
			
			var _c = this;
			// Change The Opacity
			this['el'].style.opacity = v/100;
			this['el'].style.filter  = 'alpha(opacity='+v+');'
			
			this['i'] = setTimeout(
				function(){
					_c['fadeIn'](v+20);
				},this['eTime']
			);
		}
	}, // fadeIn End
	
	'changePic'	: function(t){

		var _c = this;
		
		// Preload the Image
		var image = new Image();
			image.onload = function(){
				_c['fadeIn'](0);	
			}
			image.src = t;
		// Change the Pic
		this['el'].src = image.src;
	}
} // Pic Class End

/* markSelected();
 * Mark the clicked picture
 * Usage: markSelected(this);
 */
function markSelected(w){
	var cont = $('prod-pic-thumbs');
	var pics = cont.getElementsByTagName('a');
	
	for(var x=0, y=pics.length; x<y; x++){
		if(pics[x].className!='none'){
			pics[x].className = ''
		}
	}
	w.className = 'selected';
}

/* Animation();
 * Fade between slides
 */
function Animation(obj,from,to,steps,callback,pic){
	this.obj 		= obj;
	this.to 		= to;
	this.steps 		= steps || 6;
	this.from 		= from;
	this.curr 		= from;
	this.callback 	= callback || false;
	this.pic		= APATH+'images/slides/'+pic;
	this.intVal;
	
	this.fade();
}

Animation.prototype.fade = function(){
	var self = this;
	
	this.curr =  this.curr + ((this.to-this.from)/this.steps);
   	this.obj.style.opacity = ( this.curr / 100 );
    this.obj.style.filter  = 'alpha(opacity=' + Number( this.curr ) + ')';
	
    if(Math.round(this.curr) != this.to){
        this.intVal = setTimeout( function(){ self.fade(); }, 40 );
    }else{
		this.callback.call(this,this);
	}
}

Animation.prototype.remove = function(){
	clearInterval(this.intVal);
	
	delete this.obj;
	delete this.callback;
	delete this.fade;
	delete this.from;
	delete this.to;
}


/* cal();
 * Generate a calendar
 */
function cal(){
	// Date object
	var dates = {
		dayActual   : new Date().getDate(),
		monthActual : new Date().getMonth(),
		yearActual  : new Date().getFullYear(),
		monthName	: [	"January","February","March","April",
						"May","June","July","August",
						"September","October","November","December"],
		monthI18n   : [	"Janeiro","Fevereiro","Março","Abril",
						"Maio","Junho","Julho","Agosto",
						"Setembro","Outrubro","Novembro","Dezembro"],
		monthEndDay : [31,(this.yearActual%4==0)?29:28,31,30,31,30,31,31,30,31,30,31],
		weekDays	: ['&nbsp;&nbsp;Dom','Seg','Ter','Qua','Qui','Sex','Sab']
	}
	
	var c = new Array();
		c.push('<table class="calendar" cellpadding="0" cellspacing="0" border="0">');
	
		c.push('<thead><tr class="caption">');
		c.push('<th colspan="7">'+dates.monthI18n[dates.monthActual]+',&nbsp;'+dates.yearActual+'</th>');
		c.push('</tr><tr>');
		for(var x=0, y=dates.weekDays.length;x<y;x++){
			c.push('<th>');
			c.push(dates.weekDays[x]);
			c.push('</th>');
		}
		c.push('</tr></thead>');
	
		c.push('<tfoot><tr><td colspan="7"></td></tr></tfoot>');
	
		c.push('<tbody>');
		for(var x=0,y=1,d=1,z=dates.monthEndDay[dates.monthActual];x<6;x++){
			c.push('<tr>');
			for(var a=0,b=7;a<b;a++){
				if((x*b)+a>=startAt && y <= z){
					if(y==dates.dayActual){
						c.push('<td class="today">');
					}else{
						c.push('<td>');
					}
					c.push(y);
					y++;
				}else{
					if(y<=z){
						c.push('<td class="not-month">');
						c.push(dates.monthEndDay[dates.monthActual]-(startAt-a))
					}else{
						c.push('<td class="not-month">');
						c.push(d);
						d++;
					}
				}
				c.push('</td>');
			}
			c.push('</tr>');
		}
		
		c.push('</tr>');
		c.push('</tbody>');
		c.push('</table>');
	
	$('calendario').innerHTML = c.join('');
}

/* swapPic();
 * Change Pics
 */
function swapPic(){
	var self = this;
	
	// Preload the Image
	var image = new Image();
		image.onload = function(){
			self.fade();	
		}
	image.src = this.pic;

	this.obj.src = this.pic;

	this.callback = self.remove;
	this.to 	= 100;
	this.from 	= 0;
	this.curr	= this.from;
	
}

/* changeSlide();
 * Change actual slide item
 */
function changeSlide(e){
	var tg;
	
	if (!e) var e = window.event;
	if (e.target) tg = e.target;
	else if (e.srcElement) tg = e.srcElement;
	
	var pics = $('dest-pics').getElementsByTagName('a');
	
	for(var x=0, y=pics.length;x<y;x++){
		pics[x].className = '';
	}
	tg.className = 'hi';
	
	new Animation($('pic'),100,0,null,swapPic,tg.id);
}

/* addEventSlimple();
 * Add event to elements
 */
function addEventSimple(obj,evt,fn) {
	if (obj.addEventListener)
		obj.addEventListener(evt,fn,false);
	else if (obj.attachEvent)
		obj.attachEvent('on'+evt,fn);
}

window.onload = function(){
	if($('dest-pics')){
		var b = $('dest-pics').getElementsByTagName('a');
		
		for(var x=0, y=b.length; x<y; x++){
			addEventSimple(b[x],'click',changeSlide);	
		}
	}
	
	if($('calendario')){
		cal();
	}
	if($('mapa')){
		load();	
	}

	swfobject.embedSWF(
		APATH+"flash/logo.swf",
		"logo",
		"280",
		"78",
		"8.0.0",
		null,
		false,
		params,
		false);
		
	swfobject.embedSWF(
		APATH+"flash/"+movie+".swf",
		"anim",
		"570",
		"78",
		"8.0.0",
		null,
		false,
		params,
		false);
		
	swfobject.embedSWF(
		APATH+"flash/telefone.swf",
		"telefone",
		"243",
		"30",
		"8.0.0",
		null,
		false,
		params,
		false);

	}
