/*
**************************************
* Funções Gerais                     *
* Author: Élison Gomes               *
* Contact: elison@fievel.com      *
**************************************
*/

function openWin(pUrl,pName,pWidth,pHeight) {
	var lLeft = (screen.width/2) - (pWidth/2);
	var lTop = (screen.height/2) - (pHeight/2) - 24;
	var lFeatures = (arguments.length > 4) ? ',' + arguments[4] : '';
	var lWin = window.open(pUrl,pName,"width="+pWidth+",height="+pHeight+",Top="+lTop+",Left="+lLeft+",status=no"+lFeatures);
	try {
		lWin.focus();
	} catch (ex) {}
	return lWin;
}

function goUrl(pUrl) {
	location.href = pUrl;
}


//Funções auxiliares
function splitDate(pDate) {
	lArrDate = pDate.split("/");
	lDay = 0;
	lMonth = 0;
	lYear = 0;
	if (lArrDate.length == 3) {
		lDay = parseFloat(lArrDate[0]);
		lMonth = parseFloat(lArrDate[1]);
		lYear = parseFloat(lArrDate[2]);
	}
	return {d:lDay, m:lMonth, y:lYear};
}

function isDate(pDate) {
	if (pDate.length < 6)  { return false; }
	if (pDate == '__/__/____') { return true; }
	lDate = splitDate(pDate);
	lDay = lDate.d;
	lMonth = lDate.m;
	lYear = lDate.y;
	if (lDay == 0 || lMonth ==0 || lYear == 0) { return false; }
	if (lYear < 1000) return false;
	if ((lMonth==2)&&(lDay>(lYear%4==0?29:28))) return false;
	else if ((lDay>30)&&((lMonth==4)||(lMonth==6)||(lMonth==9)||(lMonth==11))) return false;
	else if (lDay>31) return false;
	else if (lMonth>12) return false;
	if ((isNaN(lDay))||(isNaN(lMonth))||(isNaN(lYear))) return false;
	return true;
}

function validateDate() {
	lDate = (arguments.length > 0) ? arguments[0] : '';
	lObject = (arguments.length > 1) ? arguments[1] : null;
	if ( (lDate.length > 0) & (!isDate(lDate)) ) {
		alert('A data informada é inválida.');
		if (lObject != null) {
			lObject.value = '';
			lObject.focus();
		}
	}
}

//Prototype
String.prototype.trim = function () {
	var s = this.replaceall(/^\s*/, "");
	return s.replaceall(/\s*$/, "");
}

String.prototype.replaceall = function(pattern, replacement) {
	return this.split(pattern).join(replacement);
}

String.prototype.isCPF = function(){
	var c = this;
	if((c = c.replace(/[^\d]/g,"").split("")).length != 11) return false;
	if(new RegExp("^" + c[0] + "{11}$").test(c.join(""))) return false;
	for(var s = 10, n = 0, i = 0; s >= 2; n += c[i++] * s--);
	if(c[9] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
	for(var s = 11, n = 0, i = 0; s >= 2; n += c[i++] * s--);
	if(c[10] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
	return true;
};

String.prototype.isCNPJ = function(){
	var b = [6,5,4,3,2,9,8,7,6,5,4,3,2], c = this;
	if((c = c.replace(/[^\d]/g,"").split("")).length != 14) return false;
	for(var i = 0, n = 0; i < 12; n += c[i] * b[++i]);
	if(c[12] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
	for(var i = 0, n = 0; i <= 12; n += c[i] * b[i++]);
	if(c[13] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
	return true;
};

//Eventos
addEvent = function(o, e, f, s){
	var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
	r[r.length] = [f, s || o], o[e] = function(e){
		try{
			(e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
			e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
			e.target || (e.target = e.srcElement || null);
			e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
		}catch(f){}
		for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
		return e = null, !!d;
    }
};

removeEvent = function(o, e, f, s){
	for(var i = (e = o["_on" + e] || []).length; i;)
		if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
			return delete e[i];
	return false;
};

function printVersion() {
	var lConteudo = $('#rightcol').html();
	var lWin = openWin('about:blank', '_blank', 700,500,'resizable=yes,scrollbars=yes,toolbar=yes');
	lWin.document.open();
	lWin.document.writeln('<html><head><title>Versão para Impressão</title>');
	lWin.document.writeln('<link rel="stylesheet" type="text/css" href="/themes/default/css/printversion.css" /> ');
	lWin.document.writeln('</head> ');
	lWin.document.writeln('<body>');
	lWin.document.writeln(lConteudo);
	lWin.document.writeln('<div class="url"><b>Link:</b> '+gURI+'</div>');
	lWin.document.writeln('<div class="siteap">Copyright © Compet PM — Gerenciamento de Projetos</div>');
	lWin.document.writeln('<script> self.print(); </script>');
	lWin.document.writeln('</body></html> ');
	lWin.document.close();
}

function vEnquete(pCd) {
	var lQtdResp = document.enquete.enqresp.length;
	var lVotos = 0;
	var lvt = '';
	for (i = 0; i < lQtdResp; i++) {
		if (document.enquete.enqresp[i].checked) {
			if (lvt.length > 0) {
				lvt += ',';
			}
			lvt += document.enquete.enqresp[i].value;
			lVotos++;
		}
	}
	if (lVotos == 0) {
		alert('Selecione uma opçao antes de votar.');
	} else {
		$.post("/enquete", { op: 'votar', cd: pCd, vt: lvt  },
				  function(data){
					  alert(data);
					  $("#lnkEnqresp").click();
				  }
				);
	}
}

function afterSubmit_NEWSLETTER() {
	var lnome = $('#nome').val();
	var lemail = $('#email').val();
	
	if (lnome == 'Informe seu nome') {
		alert('Informe seu nome.');
		$('#nome').focus();
		return false;
	}

	$.post("/newsletter", { nome: lnome, email: lemail  },
			  function(data){
				  alert(data);
				  $('#nome').val('');
				  $('#email').val('');
			  }
			);
	return false;
}

//gallery
function lg(cd,div) {
	$.getJSON("/load_gal?op=lg&cd="+cd+"",
		function(data){
		  var ldata = '';
		  var j = 0;
		  $.each(data.items, function(i,item){
			ldata = ldata + '<span class="gallery_common2"><a href="'+item.img+'" class="fancybox" rel="group" title="'+item.legend+'"><img src="'+item.img_tb+'" /><span class="pic_desc">'+item.legend+'</span></a></span>';
			j++;
			if (j > 3) {
				ldata = ldata + '<div class="clear"></div>';
				j=0;
			}
		  });
		  $('#'+div+'').html(ldata);
		  var target_offset = $('#'+div+'').offset();
		  var target_top = target_offset.top;
		  $('html, body').animate({scrollTop:target_top}, 500);
		  $(".fancybox").fancybox({ 'hideOnContentClick': false });
		});	
}

function doLogin() {
	var email = $('[name="l_email"]').val().trim();
	var senha = $('[name="l_senha"]').val().trim();
	if (email.length == 0 || senha.length == 0) {
		alert('Informe seu e-mail e senha!');
	} else {
		$('#_ll').html(gLOADER);
		$.post('/login', { op: 'login', _email: email, _senha: senha },
				function(data){
					$('#_ll').html('');
					if (data.msg == 'success') {
						if (typeof data.url != 'undefined') {
							goUrl(data.url);
						} else {
							goUrl(gURI);
						}
					} else {
						$('[name="l_email"]').val('');
						$('[name="l_senha"]').val('');
						alert(data.msg);
					}
				}, "json"
			);
	}
}

function doLogout() {
	$.post('/login', { op: 'logout'},
			function(data){
				if (data.msg == 'success') {
					goUrl(gURI);
				} else {
					alert(data.msg);
				}
			}, "json"
		);
}
