// @+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@ \\
// ARQUIVO DE FUNCÍES GENERICAS EM JS
// BY: OBJECT@
// AT: 18/11/2010
// AUTHOR: ACELMAR
// @+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@+@ \\

function Get_Cookie( check_name ) {
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false;
	var i = '';
	for ( i = 0; i < a_all_cookies.length; i++ ){
		a_temp_cookie = a_all_cookies[i].split( '=' );
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		if ( cookie_name == check_name ){
			b_cookie_found = true;
			if ( a_temp_cookie.length > 1 ){
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ){ return null; }
}

function Set_Cookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ){ expires = expires * 1000 * 60 * 60 * 24; }
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function carregaCidades(form, estado, cidade){
	$('#selectCidade').html('AGUARDE...');
	$('#selectCidade').load(
		rootSite + 'system/_ajax_.php',
		{ 'acaoAjax' : 'carregarCidades', 'Estado' : getSelected(form, 'Estado'), 'Cidade' : cidade }
	);
}

function verifyEmail(Form, Campo, Id_Usuario){
	var Email = document[Form][Campo].value;
	$("#checarEmail").html("");
	if(Email.length > 0){
		$("#checarEmail").load(rootSite + "system/_ajax_.php", { "acaoAjax" : "checarEmail", "Form" : Form, "Campo" : Campo, "Email" : Email, "Id_Usuario" : Id_Usuario }, function(){
			if($("#checarEmail").html() != ""){ $("#checarEmail").show(); }
		});
	}
}

function verifyUsuario(Form, Campo, Id_Usuario){
	var Usuario = document[Form][Campo].value;
	$("#checarUsuario").html("");
	if(Usuario.length > 0){
		$("#checarUsuario").load(rootSite + "system/_ajax_.php", { "acaoAjax" : "checarUsuario", "Form" : Form, "Campo" : Campo, "Usuario" : Usuario, "Id_Usuario" : Id_Usuario }, function(){
			if($("#checarUsuario").html() != ""){ $("#checarUsuario").show(); }
		});
	}
}

function verifyValorBD(Form, Campo, Table, Id, ValorId){
	var ValorCampo = document[Form][Campo].value;
	$("#checar"+Campo).html("");
	if(ValorCampo.length > 0){
		$("#checar"+Campo).load(rootSite + "system/_ajax_.php", { "acaoAjax" : "checarValorBD", "Form" : Form, "Table" : Table, "Campo" : Campo, "ValorCampo" : ValorCampo, "Id" : Id, "ValorId" : ValorId }, function(){
			if($("#checar"+Campo).html() != ""){ $("#checar"+Campo).show(); }
		});
	}
}

function processPermalink(elVal){
	var charn = new Array(225,224,227,229,226,233,234,237,243,244,245,250,252,231,193,192,195,194,201,202,205,211,212,213,218,220,199,732,241,232);
	var chars = new Array("a","a","a","a","a","e","e","i","o","o","o","u","u","c","a","a","a","a","e","e","i","o","o","o","u","u","c","_","n","e");
	var valSplit = elVal.toLowerCase().split('');
	var valNChar = new Array();
	var newch = "";
	var t = valSplit.length;
	for(t in valSplit){
		var tString = valSplit[t].toString();
		if(tString.length == 1){
			var tC = tString.charCodeAt();
			newch = valSplit[t];
			if(valSplit[t] == " "){ newch = "-"; }
			if(valSplit[t] == "/"){ newch = "_slash_"; }
			for(n in charn){
				if(charn[n] == tC){
					newch = chars[n];
				}
			}
			valNChar.push(newch);
		}
	}
	val = valNChar.join('');
	val = val.replace(/[^a-zA-Z0-9_-]/g, function(c) { return ''; });
	val = val.replace(/-$/g, function(c) { return ''; });
	val = val.replace(/-$/g, function(c) { return ''; });
	val = val.replace(/-$/g, function(c) { return ''; });
	val = val.replace(/-$/g, function(c) { return ''; });
	val = val.replace("_slash_","/");
	return val;
}
function completePermalink(form, fieldFrom, fieldTo){
	var elFrom = eval("document."+form+"."+fieldFrom);
	if(eval("document."+form+"."+fieldTo)){
		var elTo = eval("document."+form+"."+fieldTo);
		if(elTo.value.length == 0){
			elTo.value = processPermalink(elFrom.value);
		}
	}
}

function completePermalinkProc(form, fieldFrom, fieldTo, maxSize){
	var elFrom = eval("document."+form+"."+fieldFrom);
	var elTo = eval("document."+form+"."+fieldTo);
	if(elTo.value.length < maxSize){
		elTo.value = processPermalink(elFrom.value);
	}
}

function clearPermalink(form, fieldVal){
	var elVal = eval("document."+form+"."+fieldVal);
	if(elVal.value.length > 0){
		elVal.value = processPermalink(elVal.value);
	}
}

function checkKey(){
	alert("you hit " + window.event.keyCode);
	if (window.event.keyCode == 13){
	}
}

function lettersonly(e){
	var unicode=e.charCode? e.charCode : e.keyCode
	if (unicode!=8){
		if((unicode > 64 && unicode < 91) || (unicode > 96 && unicode < 123) || (unicode == 95) || (unicode == 45)){ return true; } else { return false; }
	}
}

function numericOnly() {
    var key_code = window.event.keyCode;
    var oElement = window.event.srcElement;
    if (!window.event.shiftKey && !window.event.ctrlKey && !window.event.altKey) {
        if ((key_code > 47 && key_code < 58) ||
            (key_code > 95 && key_code < 106)) {

            if (key_code > 95)
                 key_code -= (95-47);
            oElement.value = oElement.value;
        } else if(key_code == 8) {
            oElement.value = oElement.value;
        } else if(key_code != 9) {
            event.returnValue = false;
        }
    }
}

function elementFocusBlur(el, inival){
	if(eval(el).value == inival){
		eval(el).value = "";
	}
	el.style.backgroundColor = "#FFFFFF";
	$(el).bind("blur", function(){
		if(el.value == ""){ el.value = inival; }
	});
}

function getSelected(form, field){
	var elForm = eval("document."+form+"."+field);
	return elForm.options[elForm.options.selectedIndex].value;
}

function camposForm(form, keys){
	var nfail = 0;
	$.each(keys, function(){
		var vk = this;
		var campoV = vk[0];
		var valorV = vk[1];
		var alertV = vk[2];
		if(campoV != undefined){
			if(eval("document."+form+"."+campoV)){
				var elForm = eval("document."+form+"."+campoV);
				var corFail = "#fffbeb";
				var cor = "#FFFFFF";
				var setCor = 0;
				if(vk[1] == "select"){
					if(parseInt(elForm.options[elForm.options.selectedIndex].value) == 0){ setCor = 1; }
					if(elForm.options[elForm.options.selectedIndex].value == ""){ setCor = 1; }
				} else if(vk[1] == "number"){ if(elForm.value == 0){ setCor = 1; }
				} else if(valorV == "check"){ if(elForm.checked === false){ setCor = 1; }
				} else if(valorV.toString().match("^!")){ if(elForm.value == valorV.substr(1)){ setCor = 1; }
				} else { if(elForm.value.length < parseInt(vk[1])){ setCor = 1; }
				}
				if(setCor == 1){ cor = corFail; nfail++; }
				elForm.style.backgroundColor = cor;
			}
		}
	});
	if(nfail > 0){ return false; } else { return true; }
}

function verificaForm(form, keys, minimo){
	var recadoForm  = "";
	var numValores = 0;
	$.each(keys, function(){
		var vk = this;
		var campoV = vk[0];
		var valorV = vk[1];
		var alertV = vk[2];
		if(campoV != undefined){
			if(eval("document."+form+"."+campoV)){
				var elForm = eval("document."+form+"."+campoV);
				var corFail = "#FFEEE9";
				var cor = "#FFFFFF";
				var setCor = 0;
				if(valorV == "select"){
					if(parseInt(elForm.options[elForm.options.selectedIndex].value) == 0){ setCor = 1; }
					if(elForm.options[elForm.options.selectedIndex].value == ""){ setCor = 1; }
				} else if(valorV == "number"){ if(elForm.value == 0){ setCor = 1; }
				} else if(valorV == "check"){ if(elForm.checked === false){ setCor = 1; }
				} else if(valorV.toString().match("^!")){ if(elForm.value == valorV.substr(1)){ setCor = 1; }
				} else { if(elForm.value.length < parseInt(valorV)){ setCor = 1; }
				}
				if(minimo > 0){
					if(setCor == 0) numValores++;
				} else {
					if(setCor == 1){ cor = corFail; recadoForm += "\n" + alertV; }
					elForm.style.backgroundColor = cor;
				}
			}
		}
	});
	if(minimo > 0){
		if(numValores < minimo){
			alert("Favor preencher no minimo " + minimo + " informa" + (minimo>1?"oes":"ao"));
			return false;
		} else {
			return true;
		}
	} else {
		if(recadoForm.length > 0){
			alert("Preencha corretamente o campos:\n" + recadoForm);
			return false;
		} else {
			return true;
		}
	}
}

function getFlashMovieObject(movieName){
	var ret;
	if (window.document[movieName]){
		return window.document[movieName];
	}
	if (navigator.appName.indexOf("Microsoft")==-1){
		if (document.embeds && document.embeds[movieName]){
			return document.embeds[movieName];
		}
	}
	return document.getElementById(movieName);
}


function getFlashMovieObjectA(movieName) { 
  var isIE = navigator.appName.indexOf("Microsoft") != -1; 
  return (isIE) ? window[movieName] : document[movieName]; 
}

function flash(ID, arquivo, w, h) {
	document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" id="' + ID + '" width="' + w + '" height="' + h + '">');
	document.write('<param name="movie" value="' + arquivo + '">');
	document.write('<param name="allowFullScreen" value="true">');
	document.write('<param name="allowScriptAccess" value="always">');
	document.write('<param name="quality" value="high">');
	document.write('<param name="wmode" value="transparent">');
	document.write('<embed src="' + arquivo + '" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="' + w + '" height="' + h + '" WMODE="transparent" NAME=' + ID + ' swLiveConnect=true></embed>');
	document.write('</object>');
}

function flashFLV(ID, arquivo, w, h) {
	document.write("<object width='"+w+"' height='"+h+"' id='"+ID+"'>");
	document.write("<param name='allowFullScreen' value='true'>");
	document.write("<param name='allowScriptAccess' value='always'>");
	document.write("<param name='movie' value='"+arquivo+"'>");
	document.write('<param name="wmode" value="transparent">');
	document.write("<embed src='"+arquivo+"' width='"+w+"' height='"+h+"' allowFullScreen='true' type='application/x-shockwave-flash' WMODE='transparent' NAME='" + ID + "' allowScriptAccess='always'>");
	document.write("</object>");
}



function makeWindow(vURL,nameW,w,h){
	if(w == 0 && h == 0){
		var vScreenWidth = window.screen.availWidth;
		var vScreenHeight = window.screen.availHeight;
		var lf = 0;
		var tp = 0;
		var vFeatures = "fullscreen=yes, toolbar=no, status=no, menubar=no, scrollbars=yes, resizable=yes, directories=no, location=no, left="+lf+", top="+tp+", width="+vScreenWidth+", height="+ vScreenHeight;
	} else {
		var vScreenWidth = w;
		var vScreenHeight = h;
		var lf = (window.screen.availWidth - w)/2;
		var tp = (window.screen.availHeight - h)/2;
		var vFeatures = "toolbar=no, status=yes, menubar=no, scrollbars=yes, resizable=yes, directories=no, location=no, left="+lf+", top="+tp+", width="+vScreenWidth+", height="+ vScreenHeight;
	}
	window.open(vURL,nameW,vFeatures);
}

function Browser() {
	var ua, s, i;
	this.isIE    = false;
	this.isNS    = false;
	this.version = null;
	ua = navigator.userAgent;
	s = "MSIE";
	if ((i = ua.indexOf(s)) >= 0) {
		this.isIE = true;
		this.version = parseFloat(ua.substr(i + s.length));
		return;
	}
	s = "Netscape6/";
	if ((i = ua.indexOf(s)) >= 0) {
		this.isNS = true;
		this.version = parseFloat(ua.substr(i + s.length));
		return;
	}
	// Treat any other "Gecko" browser as NS 6.1.
	s = "Gecko";
	if ((i = ua.indexOf(s)) >= 0) {
		this.isNS = true;
		this.version = 6.1;
		return;
	}
}
var browser = new Browser();
// Global object to hold drag information.
var dragObj = new Object();
dragObj.zIndex = 1800;
function dragStart(event, id) {
	var el;
	var x, y;
	// If an element id was given, find it. Otherwise use the element being
	// clicked on.
	if (id){
		dragObj.elNode = document.getElementById(id);
	} else {
		if (browser.isIE) dragObj.elNode = window.event.srcElement;
		if (browser.isNS) dragObj.elNode = event.target;
		// If this is a text node, use its parent element.
		if (dragObj.elNode.nodeType == 3) dragObj.elNode = dragObj.elNode.parentNode;
	}
	// Get cursor position with respect to the page.
	if (browser.isIE) {
		x = window.event.clientX + document.documentElement.scrollLeft
			+ document.body.scrollLeft;
		y = window.event.clientY + document.documentElement.scrollTop
			+ document.body.scrollTop;
	}
	if (browser.isNS) {
		x = event.clientX + window.scrollX;
		y = event.clientY + window.scrollY;
	}
	// Save starting positions of cursor and element.
	dragObj.cursorStartX = x;
	dragObj.cursorStartY = y;
	dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);
	dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,  10);
	if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
	if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 0;
	// Update element's z-index.
	dragObj.elNode.style.zIndex = ++dragObj.zIndex;
	// Capture mousemove and mouseup events on the page.
	if (browser.isIE) {
		document.attachEvent("onmousemove", dragGo);
		document.attachEvent("onmouseup",   dragStop);
		window.event.cancelBubble = true;
		window.event.returnValue = false;
	}
	if (browser.isNS) {
		document.addEventListener("mousemove", dragGo,   true);
		document.addEventListener("mouseup",   dragStop, true);
		event.preventDefault();
	}
}
function dragGo(event) {
	var x, y;
	// Get cursor position with respect to the page.
	if (browser.isIE) {
		x = window.event.clientX + document.documentElement.scrollLeft
			+ document.body.scrollLeft;
		y = window.event.clientY + document.documentElement.scrollTop
			+ document.body.scrollTop;
	}
	if (browser.isNS) {
		x = event.clientX + window.scrollX;
		y = event.clientY + window.scrollY;
	}
	// Move drag element by the same amount the cursor has moved.
	dragObj.elNode.style.left = (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px";
	dragObj.elNode.style.top  = (dragObj.elStartTop  + y - dragObj.cursorStartY) + "px";
	
	if (browser.isIE) {
		window.event.cancelBubble = true;
		window.event.returnValue = false;
	}
	if (browser.isNS) event.preventDefault();
}

function dragStop(event) {
	// Stop capturing mousemove and mouseup events.
	if (browser.isIE) {
		document.detachEvent("onmousemove", dragGo);
		document.detachEvent("onmouseup",   dragStop);
	}
	if (browser.isNS) {
		document.removeEventListener("mousemove", dragGo,   true);
		document.removeEventListener("mouseup",   dragStop, true);
	}
}

jQuery.preloadImages = function(){
	for(var i = 0; i<arguments.length; i++){
		jQuery("<img>").attr("src", arguments[i]);
	}
}
