// JavaScript Document
document.writeln('<script language="javascript" type="text/javascript" src="js/flashobject.js"></script>');
document.writeln('<script language="javascript" type="text/javascript" src="../js/jquery/jquery.js"></script>');
document.writeln('<script language="javascript" type="text/javascript" src="../js/jquery/jquery.ajaxfileupload.js"></script>');
document.writeln('<script language="javascript" type="text/javascript" src="../js/jquery/jquery.blockUI.js"></script>');
document.writeln('<script language="javascript" type="text/javascript" src="../js/jquery/jquery.color.js"></script>');
document.writeln('<script language="javascript" type="text/javascript" src="../js/jquery/jquery.maskedinput.js"></script>');
document.writeln('<script language="javascript" type="text/javascript" src="../js/jquery/jquery.validate.js"></script>');
document.writeln('<script language="javascript" type="text/javascript" src="../js/jquery/jquery.tooltip.js"></script>');
document.writeln('<script language="javascript" type="text/javascript" src="../js/ajax.js"></script>');

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

String.prototype.isEmail = function() {
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	return emailPattern.test(this);
}

String.PAD_LEFT  = 0;
String.PAD_RIGHT = 1;
String.PAD_BOTH  = 2;

String.prototype.pad = function(size, pad, side) {
  var str = this, append = "", size = (size - str.length);
  var pad = ((pad != null) ? pad : " ");
  if ((typeof size != "number") || ((typeof pad != "string") || (pad == ""))) {
    throw new Error("Wrong parameters for String.pad() method.");
  }
  if (side == String.PAD_BOTH) {
    str = str.pad((Math.floor(size / 2) + str.length), pad, String.PAD_LEFT);
    return str.pad((Math.ceil(size / 2) + str.length), pad, String.PAD_RIGHT);
  }
  while ((size -= pad.length) > 0) {
    append += pad;
  }
  append += pad.substr(0, (size + pad.length));
  return ((side == String.PAD_LEFT) ? append.concat(str) : str.concat(append));
}

Number.prototype.format = function(d_len, d_pt, t_pt) {
  var d_len = d_len || 0;
  var d_pt = d_pt || ",";
  var t_pt = t_pt || "";
  if ((typeof d_len != "number")
    || (typeof d_pt != "string")
    || (typeof t_pt != "string")) {
    throw new Error("wrong parameters for method 'String.pad()'.");
  }
  var integer = "", decimal = "";
  var n = new String(this).split(/\./); i_len = n[0].length; i = 0;
  if (d_len > 0) {
    n[1] = (typeof n[1] != "undefined") ? n[1].substr(0, d_len) : "";
    decimal = d_pt.concat(n[1].pad(d_len, "0", String.PAD_RIGHT));
  }
  while (i_len > 0) {
    if ((++i % 3 == 1) && (i_len != n[0].length)) {
      integer = t_pt.concat(integer);
    }
    integer = n[0].substr(--i_len, 1).concat(integer);
  }
  return (integer + decimal);
}

String.prototype.isCNPJ = function() {
		var CNPJ = this;
		
		if (CNPJ.length > 18) CNPJ = CNPJ.substr(1, 19);
		
    erro = new String;
    if (CNPJ.length < 18) erro += "É necessário preencher corretamente o CNPJ!\n\n";
    if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")) {
        if (erro.length == 0) erro += "É necessário preencher corretamente o CNPJ!\n\n";
    }
    //substituir os caracteres que nao sao numeros
    if (document.layers && parseInt(navigator.appVersion) == 4) {
        x = CNPJ.substring(0,2);
        x += CNPJ.substring(3,6);
        x += CNPJ.substring(7,10);
        x += CNPJ.substring(11,15);
        x += CNPJ.substring(16,18);
        CNPJ = x;   
    } else {
        CNPJ = CNPJ.replace(".","");
        CNPJ = CNPJ.replace(".","");
        CNPJ = CNPJ.replace("-","");
        CNPJ = CNPJ.replace("/","");
    }
    var nonNumbers = /\D/;
    if (nonNumbers.test(CNPJ)) erro += "A verificação do CNPJ suporta apenas números!\n\n";
    var a = [];
    var b = new Number;
    var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
    for (i=0; i<12; i++) {
        a[i] = CNPJ.charAt(i);
        b += a[i] * c[i+1];
    }
    if ((x = b % 11) < 2) {
        a[12] = 0
    } else {
        a[12] = 11-x
    }
    b = 0;
    for (y=0; y<13; y++) {
        b += (a[y] * c[y]); 
    }
    if ((x = b % 11) < 2) {
        a[13] = 0;
    } else {
        a[13] = 11-x;
    }
    if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])) {
        erro +="Dígito verificador inválido!";
    }
    if (erro.length > 0) {
        //alert(erro);
        return false;
    }
    return true;
}

String.prototype.isCPF = function() {
		var cpf = this;
		cpf = cpf.replace(".","");
		cpf = cpf.replace(".","");
		cpf = cpf.replace("-","");
		valor = true;
		erro = new String;
		if (cpf.length < 11) erro += "Sao necessarios 11 digitos para verificacao do CPF! \n\n"; 
		var nonNumbers = /\D/;
		if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! \n\n";	
		if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
			  erro += "Numero de CPF invalido!"
		}
		var a = [];
		var b = new Number;
		var c = 11;
		for (i=0; i<11; i++){
			a[i] = cpf.charAt(i);
			if (i < 9) b += (a[i] *  --c);
		}
		if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
		b = 0;
		c = 11;
		for (y=0; y<10; y++) b += (a[y] *  c--); 
		if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
		if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
			erro +="Digito verificador com problema!";
		}
		if (erro.length > 0){
			return false;
		}
		return true;
}

/* GENÉRICOS */
/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
 
var Base64 = {
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}

function currencyFormat(amount) {
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf(',') < 0) { s += ',00'; }
	if(s.indexOf(',') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}


function commaFormat(amount) {
	var delimiter = "."; // replace comma if desired
	var a = amount.split(',',2)
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d.length < 1) { amount = n; }
	else { amount = n + ',' + d; }
	amount = minus + amount;
	return amount;
}

function formatMoney(value) {
	//return parseInt(value).format(2, ",", ".");
	
	//if (value.indexOf('.') == (value.length - 3) || value.indexOf(',') == (value.length - 3)) value = value.substr(0, value.length - 3);
	
	value = value.replace(/(,|\.)(\d{1,2}|\d{4,99})$/g, "");
	value = value.replace(/,/g, "");
	value = value.replace(/\./g, "");
	
	return commaFormat(currencyFormat(value));
}

/* VARIÁVEIS BÁSICAS */
var defaultSpeed = 100;

var lastHideId = null;
var lastShowId = null;
var isLoadRestoring = false;
var loadTimeout = -1;

if (window.location.href.indexOf("imoveis") > 0) var PORTAL = "imoveis";
if (window.location.href.indexOf("servicos") > 0) var PORTAL = "servicos";
if (window.location.href.indexOf("carrosemotos") > 0) var PORTAL = "carrosemotos";
if (window.location.href.indexOf("compraevenda") > 0) var PORTAL = "compraevenda";

var URL = "http://www.superachei.com.br/";


/* FUNÇÕES BÁSICAS */
var SESSION_EXPIRE = 99;

function verifyCode(pErrorCode) {
	if (pErrorCode == SESSION_EXPIRE) {
		window.location.href = URL + PORTAL + "/?a=1";
		return false;
	}
	
	return true;
}


function enviaForm(pFormID) {
	if ($("#" + pFormID).length > 0) {
		$("#" + pFormID).submit();
	}
}

function setTooltip(pElement) {
	$(pElement).tooltip({
		track: true, 
    delay: 0, 
    showURL: false, 
    showBody: " - ", 
    fade: 250 
	});
}

function showLoading(pHideID, pShowID, pGetHeight) {
	pGetHeight = (typeof pGetHeight == "undefined") ? false : pGetHeight;
	
	lastHideId = pHideID;
	lastShowId = pShowID;
	
	if (pGetHeight) {
		var newHeight = $("#" + pHideID).height();
		$("#" + pShowID).css("backgroundPosition", "50% " + ((newHeight / 2) - 30) + "px");
		$("#" + pShowID).css("height", ((newHeight / 2) - 10));
		$("#" + pShowID).css("paddingTop", ((newHeight / 2) + 10));
	}
	
	loadTimeout = setTimeout(showLoadingNow, 100);
}

function showLoadingNow() {
	$("#" + lastHideId).fadeOut(defaultSpeed, function() {
		if (!isLoadRestoring) {
			$("#" + lastShowId).fadeIn(defaultSpeed);
		}
	});
}

function restoreLoading() {
	clearTimeout(loadTimeout);
	isLoadRestoring = true;
	
	$("#" + lastShowId).fadeOut(defaultSpeed, function() {
		$("#" + lastHideId).fadeIn(defaultSpeed, function() {
			isLoadRestoring = false;
		});
		
		lastHideId = null;
		lastShowId = null;
	});
}

var lastQuickLoading = null;

function showQuickLoading(pTarget, pMessage, pGetHeight) {
	pMessage = (typeof pMessage == "undefined") ? "aguarde" : pMessage;
	pGetHeight = (typeof pGetHeight == "undefined") ? false : pGetHeight;
	
	var boxQuickLoading = $('<div id="boxQuickLoading" class="hidden boxLoading">' + pMessage + '</div>');
	
	if (pGetHeight) {
		var newHeight = $(pTarget).parent().height();
		$(boxQuickLoading).css("backgroundPosition", "50% " + ((newHeight / 2) - 30) + "px");
		$(boxQuickLoading).css("height", ((newHeight / 2) - 10));
		$(boxQuickLoading).css("paddingTop", ((newHeight / 2) + 10));
	}
	
	$(pTarget).parent().after(boxQuickLoading);
	
	$(pTarget).parent().hide();
	$(boxQuickLoading).show();
	
	lastQuickLoading = $(pTarget).parent();
}

function hideQuickLoading() {
	$("#boxQuickLoading").hide().remove();
	$(lastQuickLoading).show();
	
	lastQuickLoading = null;
}

function getScroll() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  }
	else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  }
	else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

function goBack(pUrl) {
	if (pUrl) {
		window.location.href = pUrl;
	}
	else if (aQueryUrl) {
		window.location.href = aQueryUrl;
	}
	else {
		window.location.href = "./";
	}
}