/*
/ PACK DE FUNÇÕES PARA INFUTURO
/
*/

//Detector de MSIExplorer
function isIE(){
	var detect = navigator.userAgent.toLowerCase();
	if(detect.indexOf('msie') + 1) {
		return true;
	} else {
		return false;
	}
}

//Detector de Firefox
function isFox(){
	var detect = navigator.userAgent.toLowerCase();
	if(detect.indexOf('irefox') + 1) {
		return true;
	} else {
		return false;
	}
}

//Detector de Chrome
function isChrome(){
	var detect = navigator.userAgent.toLowerCase();
	if(detect.indexOf('hrom') + 1) {
		return true;
	} else {
		return false;
	}
}

//tamanho total da janela
function getWindowWidth() {
	var windowWidth = 0;
	if (typeof(window.innerWidth) == 'number') {
		windowWidth = window.innerWidth;
	}
	else {
		if (document.documentElement && document.documentElement.clientWidth) {
			windowWidth = document.documentElement.clientWidth;
		}
		else {
			if (document.body && document.body.clientWidth) {
				windowWidth = document.body.clientWidth;
			}
		}
	}
	return windowWidth;
}

function getWindowHeight() {
	var windowWidth = 0;
	if (typeof(window.innerHeight) == 'number') {
		windowHeight = window.innerHeight;
	}
	else {
		if (document.documentElement && document.documentElement.clientHeight) {
			windowHeight = document.documentElement.clientHeight;
		}
		else {
			if (document.body && document.body.clientHeight) {
				windowHeight = document.body.clientHeight;
			}
		}
	}
	return windowHeight;
}

/* updateOrientation  */
function updateOrientation()
{
	/*window.orientation returns a value that indicates it */
/*	var orientation=window.orientation;
	switch(orientation){
		case 0:
			alert("Portrait!");
			break;	
		case 90:
			alert("Left Landscape!");
			break;
		case -90:	
			alert("Right Landscape!");
			break;
	}*/
}

//inicializador da página
function ready() {

	// checar orientação de tela
	window.onorientationchange=updateOrientation;

	var win_width = getWindowWidth();
	var win_height = getWindowHeight();
	var offset_fix = (win_width-1024)/2;

	//Mobile
	if (offset_fix < 0) { offset_fix = 0; }

	var offset_fix_plus = (win_width-1024);

	//Mobile
	if (offset_fix_plus < 0) { offset_fix_plus = 0; }

	var new_width_footer = (offset_fix_plus+4096);

	//teste de navegador
	if (isIE()) {
		var new_height_footer = (win_height-570); //590 = page height
	} else {
		if (isFox()) {
			var new_height_footer = (win_height-590); //590 + 17px
		} else {
			var new_height_footer = (win_height-590); //590 = page height
		}
	}

	var new_width = 1024+offset_fix;

	//document.getElementById("footer").style.height=new_height_footer+'px';

	if (!isIE()) {
		document.getElementById('footer').style.height = (new_height_footer-22)+'px';
	} else {
		document.getElementById('footer').style.height = new_height_footer+'px';
	}

	document.getElementById("footer").style.top='595px';

	bubbles();
}

//Inicia a captura de eventos do Keydown
$(function () {
  $(document).keydown(function (evt) {

    var pos = parseInt(document.getElementById('pos').innerHTML,10);

    if (evt.keyCode == 37) { // left
        if (pos > 0) {
		pos = pos-1;
		document.getElementById('pos').innerHTML = pos;
		evt.preventDefault();
		var win_width = getWindowWidth();
		var offset_fix = (win_width-1024)/2;

		//Mobile
		if (offset_fix < 0) { offset_fix = 0; }

		$.scrollTo( $('div .page:eq('+pos+')'), 2000, {axis:'x', offset: {left:-offset_fix}} );
		$('#footerBranco').animate({ left: '+=100px'}, 2000, function() { });
		$('#footerRoxo').animate({ left: '+=50px'}, 650, function() { });
		$('#footerLaranja').animate({ left: '+=150px'}, 1365, function() { });
	} else {
		evt.preventDefault();
	}
    } else if (evt.keyCode == 39) { // right
	if (pos < 3) {
		pos = pos+1;
		document.getElementById('pos').innerHTML = pos;
		evt.preventDefault();
		var win_width = getWindowWidth();
		var offset_fix = (win_width-1024)/2;

		//Mobile
		if (offset_fix < 0) { offset_fix = 0; }

		$.scrollTo( $('div .page:eq('+pos+')'), 2000, {axis:'x', offset: {left:-offset_fix}} );
		$('#footerBranco').animate({ left: '-=100px'}, 1350, function() { });
		$('#footerRoxo').animate({ left: '-=50px'}, 2000, function() { });
		$('#footerLaranja').animate({ left: '-=150px'}, 650, function() { });
	} else {
		evt.preventDefault();
	}
    }
  });
});

//FORM!!! --------------------------------------------------------------------------------------------------

//testa se o valor é numérico
function IsNumeric(sText)

{
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
}

//valida um objeto e seus campos
function validar(o, t) {
	
    if (t == 'contatopt') {
	var obrigatorios = new Array(['nome','Nome'],['email','e-mail'],['mensagem','Mensagem']);

	var msgErr = '';
	var inicioErr = '';
	for(i=0; i<obrigatorios.length; i++) {
		var el = obrigatorios[i][0];
		if (o.elements[el].value == '' || o.elements[el].selectedIndex==0) {
			inicioErr = 'Os seguintes campos são de preenchimento obrigatório:\n\n';
			msgErr += obrigatorios[i][1]+"\n";
		}
	}

	// checagem do email válido
	var temp = emailChecker(o.email.value,'pt');
	msgErr +=temp;
	if(msgErr!=''){
		alert(inicioErr+msgErr);
		return false;
	}else{
		o.submit();
		return true;
	}
    } else if (t == 'contatoen') {
	var obrigatorios = new Array(['nome','Name'],['email','E-mail'],['mensagem','Message']);

	var msgErr = '';
	var inicioErr = '';
	for(i=0; i<obrigatorios.length; i++) {
		var el = obrigatorios[i][0];
		if (o.elements[el].value == '' || o.elements[el].selectedIndex==0) {
			inicioErr = 'The following fields are mandatory:\n\n';
			msgErr += obrigatorios[i][1]+"\n";
		}
	}

	// checagem do email válido
	var temp = emailChecker(o.email.value,'en');
	msgErr +=temp;
	if(msgErr!=''){
		alert(inicioErr+msgErr);
		return false;
	}else{
		o.submit();
		return true;
	}
   } else { 
	return false;
   }		
}

//testa padroes de email
function emailChecker(emailStr,kind){
	if(emailStr!='' && emailStr!='e-mail'){
		var emailPat=/^(.+)@(.+)$/;
		var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
		var validChars="\[^\\s" + specialChars + "\]";
		var quotedUser="(\"[^\"]*\")";
		var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
		var atom=validChars + '+';
		var word="(" + atom + "|" + quotedUser + ")";
		var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
		var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
		var returnMsg = new Object();
		//
		var matchArray=emailStr.match(emailPat)
		if (matchArray==null) {
			if (kind == 'pt') { returnMsg= "\nPadrão de e-mail incorreto (verifique @ e '.').\n"; } else { returnMsg= "\nIncorrect email address (verify @ and '.').\n"; }
			return returnMsg;
		}
		//
		var user=matchArray[1]
		var domain=matchArray[2]
		//
		// See if "user" is valid 
		//
		if (user.match(userPat)==null) {
			// user is not valid
			if (kind == 'pt') { returnMsg="\nO nome de usuário do e-mail é inválido!\n"; } else { returnMsg="\nInvalid email username.\n"; }
			return returnMsg;
		}
		//
		var IPArray=domain.match(ipDomainPat);
		if (IPArray!=null) {
		// this is an IP address
			for (var i=1;i<=4;i++) {
				if (IPArray[i]>255) {
					if (kind == 'pt') { returnMsg="\nIP inválido!\n"; } else { returnMsg="\nInvalid IP.\n"; }
					return returnMsg;
				}
			}
		return true
		}
		// Domain is symbolic name
		var domainArray=domain.match(domainPat);
		if (domainArray==null) {
			if (kind == 'pt') { returnMsg="\nNome de domínio inválido!\n"; } else { returnMsg="\nInvalid domain name.\n"; }
			return returnMsg;
		}
		//
		var atomPat=new RegExp(atom,"g")
		var domArr=domain.match(atomPat)
		var len=domArr.length
		if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3) {
			if (kind == 'pt') { returnMsg="\nO endereço de e-mail deve terminar no padrão \".xxx\"(Ex: .com ) ou \".xx\"(Ex: .br ).\n"; } else { returnMsg="\nThe email address must end in a three-letter domain or a two-letter country code.\n"; }
			return returnMsg;
		}
		// Make sure there's a host name preceding the domain.
		if (len<2) {
			if (kind == 'pt') { returnMsg="\nE-mail sem nome de usuário.\n"; } else { returnMsg="\nAddress without a hostname.\n"; }
			return returnMsg;
		}
		// If we've gotten this far, everything's valid!
		return "";
	}else{
		return "";
	}
}

//Criador de DIV's
function creatediv(param, id, html, width, height, left, top) {

	var newdiv = document.createElement('div');
	newdiv.setAttribute('id', id);
	if (width) {
		newdiv.style.width = 10;
	}
	if (height) {
		newdiv.style.height = 10;
	}
	if ((left || top) || (left && top)) {
		newdiv.style.position = "absolute";
		if (left) {
			newdiv.style.left = left;
		}
		if (top) {
			newdiv.style.top = top;
		}
	}

	if (html) {
		newdiv.innerHTML = "<img src=\""+html+".png\">";
	} else {
		newdiv.innerHTML = "nothing";
	}

	document.getElementById(param).appendChild(newdiv);
}

//Bolhas borbulhantes na DIV footer
function bubbles() {

	var currHeight = document.getElementById('footer').style.height;
	currHeight=currHeight.substr(0,currHeight.indexOf('px'));

	if (currHeight < 150) { currHeight = 150; }
	//	
	//if (currHeight > 174) { currHeight = 174; }
	var letters = new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
	var maxDiam = new Array();
	maxDiam=[0,150,100,70,60,30];
	var numBalls = Math.round(getWindowHeight()*(25/900))

	for (var cycle=1;cycle<=5;cycle++) {

		for (var w=0;w<numBalls;w++){
			var randX = Math.floor(Math.random()*(4096-maxDiam[cycle]))+"px";
			var randY = (Math.floor(Math.random()*(currHeight-maxDiam[cycle])))+"px";

			//random limiter
			var randguard = 0;

			//test cycle
			switch (cycle) {
				case 4:
					randguard = 12;
					break;
				case 5:
					randguard = 15;
					break;
				default:
					randguard = 9;
					break;
			}
	
			//indice is a random number between 1 and randguard
			var indice = (Math.floor(Math.random()*(randguard-1)+1))-1;

			//gets the letter associated to index
			var theletter = letters[indice];
			
			var theName = "b"+cycle+"_"+w;

			creatediv('footer', theName, '/shared/bolha_'+cycle+theletter, maxDiam[cycle], maxDiam[cycle], randX, randY);
		}

	}

}

function redraw(){

	var d = document.getElementById('principal');
	var olddiv = document.getElementById('footer');
	d.removeChild(olddiv);

	var newdiv = document.createElement('div');
	newdiv.setAttribute('id', 'footer');
	d.appendChild(newdiv);

	//teste de navegador
	if (isIE()) {
		var height_fix = 570; //590 = page height
	} else {
		if (isFox()) {
			var new_height_footer = (win_height-590); //ffox
		} else {
			var new_height_footer = (win_height-590); //chrome
		}
	}
	
	if (!isIE()) {
		document.getElementById('footer').style.height = (getWindowHeight()-(height_fix + 22))+'px';
	} else {
		document.getElementById('footer').style.height = (getWindowHeight()-height_fix)+'px';
	}

	bubbles();
}

window.onresize = redraw;

