/*
* function CopyHeight()
* description: iguala dois ou mais boxes pela altura do maior
* author: Renato Albano - renatoalbano [arroba] gmail [ponto] com
* date: 2006-01-01  10:00:00
*/
function CopyHeight() {
	var heights = [];
	for (var i = 0; i < arguments.length; i++) {
		document.getElementById(arguments[i]).style.height = '';
		heights.unshift(document.getElementById(arguments[i]).offsetHeight);
	}
	hT = heights.sort(function(a,b){ return a - b }).reverse()[0]; //ninja *[1]
	for (var i = 0; i < arguments.length; i++)
		document.getElementById(arguments[i]).style.height = hT+'px';
}

/*
* function: parseJson()
* description: Recebe um retorno AJAX, interpreta como JSON, exibe o status e chama as funcões de callback dependendo do resultado.
* optional parameters:  msgElem, msgOkElem,  msgErrorElem, fnSuccess, fnError, fnServerError, method
* author: Renato Rodrigues - renatorodrigues [arroba] gmail [ponto] com
* date: 2007-12-01 17:17:00
*/
function parseJson(url, data, opt) {
	/** Acerta os parâmetros opcionais */
	if (!opt) opt = {};
	if (opt['method']) opt['method'] = opt['method'].toUpperCase();
	if (opt['msgElem']) opt['msgOkElem'] = opt['msgErrorElem'] = opt['msgElem'];
	opt['contentType'] = ( (opt['method'] == 'POST') ? ('application/x-www-form-urlencoded') : (opt['contentType'] || ('text/plain')) );
	
	/** Dispara o Ajax */
	return jQuery.ajax({
		url: url,
		dataType: 'json',
		data: ( data || { } ),
		cache: ( opt['cache'] || true ),
		async: ( opt['async'] || true ),
		type: ( opt['method'] || 'GET' ),
		contentType: opt['contentType'],
		beforeSend: function(xhr) {
			xhr.setRequestHeader( "encoding", (opt['encoding'] || "ISO-8859-1") );
		},
		
		success: function(j){
			if (j.statusId === '0000') {
				/** Retorno com status OK, exibe a mensagem de sucesso, caso definida */
				if (opt['msgOkElem']) {
					showMsg(j.statusMessage, 'info', opt['msgOkElem']);
				/** Esconde alguma mensagem de erro que esteja sendo exibida */
				} else if (opt['msgErrorElem']) {
					$(opt['msgErrorElem']).addClass("hide");
				}
				/** Chama o Callback de sucesso, caso definido */
				if (opt['fnSuccess']) opt['fnSuccess'].call(this, j);
				
			} else if (j.statusId === '9996' || j.statusId === '9997' || j.statusId === '9998') {
				/** Retorno com Redirect, redireciona em caso de usuário não logado ou não autorizado a acessar o endereço requisitado */
				self.location.href = j.redirectURL+self.location.search;
				
			} else {
				/** Retorno com status de erro, exibe a(s) mensagem(ns) de erro retornada(s), caso definidas */
				if (opt['msgErrorElem']) {
					var errMsg = new String("");
					for (var id in j.statusMessage) {
						errMsg += j.statusMessage[id] + "<br />";
					}
					showMsg(errMsg, 'error', opt['msgErrorElem']);
				/** Esconde alguma mensagem de sucesso que esteja sendo exibida */
				} else if (opt['msgOkElem']) {
					$(opt['msgOkElem']).addClass("hide");
				}
				/** Chama o Callback de erro, caso definido */
				if (opt['fnError']) opt['fnError'].call(this, j);
			}
		},
			
		error: function (xhr) {
			/** Caso dê erro no retorno da resposta AJAX exibe a mensagem de erro no elemento definido  */
			if (opt['msgErrorElem']) {
				try {
					if (xhr.status == '200') {
						var errMsg = "Erro ao interpretar a resposta do servidor.<br />Resposta Inválida";
					} else { 
						var errMsg = "Erro ao comunicar-se com o servidor.<br />Status: " + xhr.status + ": " + unescape(xhr.statusText).replace(/\+/g," ");
					}
					showMsg(errMsg, (xhr.status == '200')?('alert'):('error'), opt['msgErrorElem']);
				} catch(e) {}
			/** Esconde alguma mensagem de sucesso que esteja sendo exibida */
			} else if (opt['msgOkElem']) {
				$(opt['msgOkElem']).addClass("hide");
			}
			/** Chama o Callback de erro de servidor, caso definido */
			if (opt['fnServerError']) opt['fnServerError'].call(this, xhr);
		}
	});
}

/*
* function: showMsg()
* description: Exibe a mensagem no elemento especificado
* type: info alert error
* author: Renato Rodrigues
* date: 2007-12-01 17:17:00
*/
function showMsg(msg, type, elem, anim) {
	$('#systemerror').hide();
	type = (type)?(type):('alert');
	elem = (elem)?(elem):('#resultbox');
	anim = (anim !== 'undefined')?(anim):(true);
	$(elem + " p").html(msg);
	$(elem).removeClass("alert error info hide").addClass(type).show();
	if (anim) var msgClose = window.setTimeout( function() { $(elem).fadeOut("slow"); },5000);
}


/*
* function: mask()
* description: recebe um objeto e uma função que é executada de tempos em tempos
* author: Élcio Ferreira / Leonardo Souza (adptação jQuery);
* date: 2007-12-02 19:33:00
*/
function mask(o,f){
	v_obj=o;
	v_fun=f;
	setTimeout("execmask()",1);
}

/*
* function: execmask()
* description: retorna no value do objeto o resultado da regex 
* author: Élcio Ferreira / Leonardo Souza (adptação jQuery);
* date: 2007-12-02 19:33:00
*/
function execmask(){
	v_obj.value=v_fun(v_obj.value);
}

/*
* function: re_num()
* description: regular expression para validação de  números
* author: Élcio Ferreira / Leonardo Souza (adptação jQuery);
* date: 2007-12-02 19:33:00
*/
function re_num(v){
	v=v.replace(/\D/g,"");
	return v;
}

/*
* function:re_email()
* description: regular expression para validação de email
* author: Leonardo Souza
* date: 2008-04-26 18:53:00
*/
function re_email(v) {
	v=v.match(/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$/g,"");
	isValid(v);
	return v;
}

/*
* function:re_cep()
* description: regular expression para validação de cep
* author: Leonardo Souza
* date: 2008-04-26 18:53:00
*/
function re_cep(v){
	v=v.replace(/\D/g,"");
	v=v.replace(/^(\d)(\d)/g,"$1$2");
	v=v.replace(/(\d{5})(\d)/,"$1-$2"); 
	return v;
}

/*
* function:re_data()
* description: regular expression para validação de  telefone
* author: Leonardo Souza
* date: 2007-12-02 20:31:00
*/	
function re_data(v){
	v=v.replace(/\D/g,"");
	v=v.replace(/^(\d{2})(\d{2})/g,"$1/$2");
	v=v.replace(/(\d{2})(\d)/,"$1/$2"); 
	return v;
}

/*
* function:re_tel()
* description: regular expression para validação de  telefone
* author: Élcio Ferreira / Leonardo Souza (adptação jQuery);
* date: 2007-12-02 19:33:00
*/			
function re_tel(v){
	v=v.replace(/\D/g,"");
	v=v.replace(/^(\d\d)(\d)/g,"($1) $2");
	v=v.replace(/(\d{4})(\d)/,"$1-$2"); 
	return v;
}



function isValid(v) {
	if(v == null) {
		$('.valid').addClass('hide');
		$('.invalid').removeClass('hide');
	} else {
		$('.invalid').addClass('hide'); 
		$('.valid').removeClass('hide');
	}
}

/*
* function addActionsMenu()
* description: adiciona as funcionalidades básicas de menu para todo o site
* author: Leonardo Souza - leonardodisouza [arroba] gmail [ponto] com
* date: 2008-06-28  14:16:00
*/
function addActionsMenu() {
	$('.level2 dl dt a').toggle(
	    function() {
	        $(this).parent().parent().find('dd').show();
			CopyHeight('sidebarleft','main','sidebarright');
	        return false;
	    },
	    function() {
	        $(this).parent().parent().find('dd').hide();
			CopyHeight('sidebarleft','main','sidebarright');
	        return false;
	    }
	);


	$('.products .level1 a').toggle(
	    function() {
	        $(this).parent().next().show();
			CopyHeight('sidebarleft','main','sidebarright');
	        return false;
	    },
	    function() {
	        $(this).parent().next().hide();
			CopyHeight('sidebarleft','main','sidebarright');
	        return false;
	    }
	);
	
	$(window).scroll(function () { 
		CopyHeight('sidebarleft','main','sidebarright');
	});
	
	
	$('#nome').add('#email')
	.click(
		function() {
			$(this).val('');
		}
	)
	.blur(
		function() {
			if($(this).val() == '') {
				if($(this).attr('id') == 'nome') {
					$(this).val('digite seu nome');
				} else {
					$(this).val('digite seu email');
				}
			}
		}
	)
	
	// callback function
	var newsletter = {
		Error: function(j) {
			showMsg(j.statusMessage, 'null', '#msgnews');
			$('#nome').val('digite seu nome');
			$('#email').val('digite seu email');
		},
		Success: function(j) {
			showMsg(j.statusMessage, 'null', '#msgnews');
			$('#nome').add('#email').val('');
		}
	};
	
	
	$('.news .btok').click(
		function() {
			if($('#nome').val() != 'digite seu nome' && $('#email').val() != 'digite seu email') {
				parseJson(
					'../ajax-actions/add_newsletter.php',
					{ name: $('#nome').val(), mail: $('#email').val() }, 
					{ 
					fnError: newsletter.Error, 
					fnSuccess: newsletter.Success,
					method: 'POST'
					}
				);
			}
		}
	);
	
	
	
}


function selectMenuItem(idsubcategory) {
	$('.level2 a').each(
	    function() {
	        if($(this).attr('rel') == idsubcategory) {
	            $('.products dt.level1 a').click();
	            $(this).parent().parent().children().children().click()
	            $(this).addClass('selected');
	        }
	    }
	);
}
