﻿/**
 * Variaveis globais
 */
 
// variaveis utilizadas na persistencia temporaria do formulario de criação de novo utilizador
var tmpUser = "";
var tmpPass = "";
var tmpPass2 = "";
var tmpNome = "";
var tmpSexo = "m";
var tmpMail = "";	
var tmpHidemail = "yes";
var tmpContact = "";
var tmpAddress = "";
var tmpLanguage = "";
var tmpDia = "";
var tmpMes = "";
var tmpAno = "";
var tmpLatitude = 0;
var tmpLongitude = 0;

var originalimgsname = new Array(0);
var originaldocname = new Array(0);
var newimgname = new Array(0);
var newdoc = new Array(0);
var uploadpost = "";
var uploadpostdoc = "";
var docsuploadended = false;
var imagesuploadended = false;
var iteminserted = false;

var myVideoData = "";
var myPhotosNames = "";
var myDocumentData = "";

var maxcontentswidthpx = 850;	// largura máxima da area de conteúdos
var sidebarwidthpx = 0;	// largura da barra lateral de categorias (200 + 10)
var itemcardwidthpx = 250 + 10;	// largura de cada cartão dos items

var numLinhasConteudos = 8;		// definição do numero de linhas da zona de conteúdos (default=8) (BD)
var numColunasConteudos = 4;	// definição do numero de colunas da zona de conteúdos (default=4 --> calculado para ocupar o maximo do ecrã do utilizador!)

var paginaActual = 0;			// numereo da página actualmente mostrada [1, ...]

var admingroupid = 2;			// ID do grupo de administradores (BD)

var userlangid = 1;				// lingua actualmente utilizada (por defeito 1 = PT)
var internationalid = 999;		// palavras não traduziveis/internacionais

var userItemVotes = new Array(0);	// guarda os items em que o utilizador já votou

var currentDispTypeList = 0;
var lastlastval = "ND";


/**
 * Executa uma função 'myfunction' por cada elemento de 'myarray' e devolve o array resultado.
 * (Igual ao map(), mas este não está definido no IE...)
 */
function maping(myarray, myfunction) {
	var res = new Array(myarray.length);
	
	for (i=0; i<myarray.length; i++) {
		res[i] = myfunction(myarray[i]);
	}
	
	return res;
}


/*********************** PHP GET ENCODE **************************/

/**
 * Encode a string as the PHP 'urlencode()'.
 */
function urlencode(str) {
    // URL-encodes string  
    // 
    // version: 904.317
    // discuss at: http://phpjs.org/functions/urlencode
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %          note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
                             
    var histogram = {};
    var ret = (str+'').toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urldecode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    histogram['\u20AC'] = '%80';
    histogram['\u0081'] = '%81';
    histogram['\u201A'] = '%82';
    histogram['\u0192'] = '%83';
    histogram['\u201E'] = '%84';
    histogram['\u2026'] = '%85';
    histogram['\u2020'] = '%86';
    histogram['\u2021'] = '%87';
    histogram['\u02C6'] = '%88';
    histogram['\u2030'] = '%89';
    histogram['\u0160'] = '%8A';
    histogram['\u2039'] = '%8B';
    histogram['\u0152'] = '%8C';
    histogram['\u008D'] = '%8D';
    histogram['\u017D'] = '%8E';
    histogram['\u008F'] = '%8F';
    histogram['\u0090'] = '%90';
    histogram['\u2018'] = '%91';
    histogram['\u2019'] = '%92';
    histogram['\u201C'] = '%93';
    histogram['\u201D'] = '%94';
    histogram['\u2022'] = '%95';
    histogram['\u2013'] = '%96';
    histogram['\u2014'] = '%97';
    histogram['\u02DC'] = '%98';
    histogram['\u2122'] = '%99';
    histogram['\u0161'] = '%9A';
    histogram['\u203A'] = '%9B';
    histogram['\u0153'] = '%9C';
    histogram['\u009D'] = '%9D';
    histogram['\u017E'] = '%9E';
    histogram['\u0178'] = '%9F';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret); // Custom replace. No regexing
    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    //return ret;
}

/*****************************************************************/



/************************ Google maps ****************************/

/**
 * Show Google Map for get/show GPS posotion in a overlayer window by thickbox.
 * editable = 1 --> true; editable = 0 --> false
 */
function showGMapsBox(editable, lat, lng, returnFunction) {
	var myphpfile = "php/googleMapsBox.php?height=530&width=840&editable=" + editable + '&startlat=' + lat + '&startlng=' + lng + '&startaddress=ND&startzoomlevel=6&returnfunc=' + returnFunction;
	
	tb_show('Mapa Global:', myphpfile, null);
}

/**
 * Show Google Map for get/show GPS posotion in a overlayer window by thickbox.
 * editable = 1 --> true; editable = 0 --> false
 */
function showGMapsBox2(editable, address, returnFunction) {
	address = urlencode(address);
	var myphpfile = "php/googleMapsBox.php?height=530&width=840&editable=" + editable + '&startlat=39.402244&startlng=-7.954101&startaddress=' + address + '&startzoomlevel=6&returnfunc=' + returnFunction;
	
	tb_show('Mapa Global:', myphpfile, null);
}


/**
 * Mostrar o mapa do google maps caso lat e long existem ou address existe.
 */
function showMapPoint(lat, long, address) {
	if (lat !== 0 && long !== 0) {
		showGMapsBox(0, lat, long, '');
	} else {
		if (address !=="") {
			showGMapsBox2(0, address, '');
		}
	}
}

/*****************************************************************/




/******************* LOADS e RELOAD da PAGINA *********************/

/**
 * Recarregar a página principal
 */
function reloadPage() {
	//document.location = "";
	//$("#container").load("main.php");	
	
	tmpUser = "";
	tmpPass = "";
	tmpPass2 = "";
	tmpNome = "";
	tmpSexo = "m";
	tmpMail = "";
	tmpHidemail = "yes";
	tmpContact = "";
	tmpAddress = "";
	tmpLanguage = "";
	tmpDia = "";
	tmpMes = "";
	tmpAno = "";
	tmpLatitude = 0;
	tmpLongitude = 0;

	originalimgsname = new Array(0);
	originaldocname = new Array(0);
	newimgname = new Array(0);
	newdoc = new Array(0);
	uploadpost = "";
	uploadpostdoc = "";
	docsuploadended = false;
	imagesuploadended = false;
	iteminserted = false;

	myVideoData = "";
	myPhotosNames = "";
	myDocumentData = "";
	
	paginaActual = 0;

	currentDispTypeList = 0;
	lastlastval = "ND";
	
	
	// executar inicializações
	loadAllThings();
}

/**
 * Recarregar zona principal (zona dos items).
 */
function reloadMainDiv() {
	//document.location.href = document.location.href;
	loadMyItems("ND");
	paginaActual = 0;
}


/**
 * Recarregar a pagina toda.
 */
/*function reloadInitialPage() {
	document.location.href = document.location.href;
	paginaActual = 0;
}*/



/**
 * Carregar os dados iniciais para a zona de dados da página principal.
 */
function loadInitialContents() {
	$("#myContents").load("php/showItemsList.php", function() {loadMyItems("ND");} );	
}



/**
 * Carregar tudo 'onload' (dados para o contentor principal da página, etc.).
 */
function loadAllThings() {
	
	$(document).ready(function() {		
		// put all your jQuery goodness in here.
							   
		//alert('Width: ' + screen.width + ' Height: ' + screen.height);
		maxcontentswidthpx = screen.width - sidebarwidthpx;
		numColunasConteudos = parseInt(maxcontentswidthpx / itemcardwidthpx);
		
		maximizeWindow();
		
		$("#container").load("main.php", {langid: userlangid}, function(){loadInitialContents();} );
		
	});
}


/**
 * Carregar os últimos items de um utilizador autenticado na zona de destaques da página principal. Se for administrador, carrega os items por validar. Caso não esteja nenhum autenticado, carrega os últimos items adicionados.
 */
function loadMyItems(lastval) {
	document.getElementById("busySendMainPage").className = "";
	
	if (document.getElementById("lastval")) {
		lastval = document.getElementById("lastval").value;
	}
	$("#itemsToDisplay").load("php/itemsToDisplay.php?lastval=" + lastval + "&langid="+userlangid + "&type=40&searchtype=0&querytxt=0&categorygroup=0&categoryid=0&outputlimit=" + (numColunasConteudos*numLinhasConteudos) + "&maxcolumns=" + numColunasConteudos,
									function(){document.getElementById("busySendMainPage").className = "escondida";});
}

/**
 * Carregar 'ultimos items' na zona de destaques da página principal.
 */
function loadLastItems(lastval) {
	document.getElementById("busySendMainPage").className = "";
	
	if (document.getElementById("lastval")) {
		lastval = document.getElementById("lastval").value;
	}
	$("#itemsToDisplay").load("php/itemsToDisplay.php?lastval=" + lastval + "&langid="+userlangid + "&type=1&searchtype=0&querytxt=0&categorygroup=0&categoryid=0&outputlimit=" + (numColunasConteudos*numLinhasConteudos) + "&maxcolumns=" + numColunasConteudos,
									function(){document.getElementById("busySendMainPage").className = "escondida";});
}

/**
 * Carregar 'items mais vistos' na zona de destaques da página principal.
 */
function loadMoreViwedItems(lastval) {
	document.getElementById("busySendMainPage").className = "";
	
	if (document.getElementById("lastval")) {
		lastval = document.getElementById("lastval").value;
	}
	$("#itemsToDisplay").load("php/itemsToDisplay.php?lastval=" + lastval + "&langid="+userlangid + "&type=2&searchtype=0&querytxt=0&categorygroup=0&categoryid=0&outputlimit=" + (numColunasConteudos*numLinhasConteudos) + "&maxcolumns=" + numColunasConteudos,
									function(){document.getElementById("busySendMainPage").className = "escondida";});
}


/**
 * Carregar 'items mais votados' na zona de destaques da página principal.
 */
function loadMoreVotedItems(lastval) {
	document.getElementById("busySendMainPage").className = "";
	
	if (document.getElementById("lastval")) {
		lastval = document.getElementById("lastval").value;
	}
	$("#itemsToDisplay").load("php/itemsToDisplay.php?lastval=" + lastval + "&langid="+userlangid + "&type=3&searchtype=0&querytxt=0&categorygroup=0&categoryid=0&outputlimit=" + (numColunasConteudos*numLinhasConteudos) + "&maxcolumns=" + numColunasConteudos,
									function(){document.getElementById("busySendMainPage").className = "escondida";});
}

/**
 * Carregar 'items preferidos' na zona de destaques da página principal.
 */
function loadPreferedItems(lastval) {
	document.getElementById("busySendMainPage").className = "";
	
	if (document.getElementById("lastval")) {
		lastval = document.getElementById("lastval").value;
	}
	$("#itemsToDisplay").load("php/itemsToDisplay.php?lastval=" + lastval + "&langid="+userlangid + "&type=4&searchtype=0&querytxt=0&categorygroup=0&categoryid=0&outputlimit=" + (numColunasConteudos*numLinhasConteudos) + "&maxcolumns=" + numColunasConteudos,
									function(){document.getElementById("busySendMainPage").className = "escondida";});
}

/**
 * Carregar todos os items na zona de destaques da página principal.
 */
function loadAll() {
	var lastval = "ND";
	
	document.getElementById("busySendMainPage").className = "";
	
	if (document.getElementById("lastval")) {
		lastval = document.getElementById("lastval").value;
	}
	$("#itemsToDisplay").load("php/itemsToDisplay.php?lastval=" + lastval + "&langid="+userlangid + "&type=1&searchtype=0&querytxt=0&categorygroup=0&categoryid=0&outputlimit=" + (numColunasConteudos*numLinhasConteudos) + "&maxcolumns=" + numColunasConteudos,
									function(){document.getElementById("busySendMainPage").className = "escondida";});
}



/**
 * Carregar items da categoria 'category' (id original da categoria + 10) na zona de destaques da página principal.
 */
/*function loadCategory(category) {
	var lastval = "ND";
	
	document.getElementById("busySendMainPage").className = "";
	
	if (document.getElementById("lastval")) {
		lastval = document.getElementById("lastval").value;
	}
	$("#itemsToDisplay").load("php/itemsToDisplay.php?lastval=" + lastval + "&langid="+userlangid + "&searchtype=0&querytxt=0&type=" + category + "&outputlimit=" + (numColunasConteudos*numLinhasConteudos) + "&maxcolumns=" + numColunasConteudos,
									function(){document.getElementById("busySendMainPage").className = "escondida";});
}*/


/**
 * Carregar items da categoria com ID 'categoryid' na zona de destaques da página principal.
 */
function loadCategoryById(categoryid) {
	var lastval = "ND";
	
	document.getElementById("busySendMainPage").className = "";
	
	if (document.getElementById("lastval")) {
		lastval = document.getElementById("lastval").value;
	}
	$("#itemsToDisplay").load("php/itemsToDisplay.php?lastval=" + lastval + "&langid="+userlangid + "&type=10&searchtype=0&querytxt=0&categorygroup=0&categoryid=" + categoryid  + "&outputlimit=" + (numColunasConteudos*numLinhasConteudos) + "&maxcolumns=" + numColunasConteudos, function(){document.getElementById("busySendMainPage").className = "escondida";});
}


/**
 * Carregar items que correspondem a um criterio do tipo 'type' em 'querytxt' na zona de destaques da página principal.
 * 'searchtype' é um inteiro!!!
 */
function loadBySearch(searchtype, querytxt) {
	var lastval = "ND";
	var encodedquerytxt = urlencode(querytxt);
	
	document.getElementById("busySendMainPage").className = "";
	
	if (document.getElementById("lastval")) {
		lastval = document.getElementById("lastval").value;
	}
	$("#itemsToDisplay").load("php/itemsToDisplay.php?lastval=" + lastval + "&langid="+userlangid + "&type=20&categorygroup=0&categoryid=0&searchtype="+searchtype + "&querytxt="+encodedquerytxt  + "&outputlimit="+(numColunasConteudos*numLinhasConteudos) + "&maxcolumns="+numColunasConteudos, function(){document.getElementById("busySendMainPage").className = "escondida";});
}


/**
 * Carregar items da categoria do grupo 'categorygroup' na zona de destaques da página principal.
 */
function loadCategoryByGroup(categorygroup) {
	var lastval = "ND";
	
	document.getElementById("busySendMainPage").className = "";
	
	if (document.getElementById("lastval")) {
		lastval = document.getElementById("lastval").value;
	}
	$("#itemsToDisplay").load("php/itemsToDisplay.php?lastval=" + lastval + "&langid="+userlangid + "&type=11&searchtype=0&querytxt=0&categoryid=0&categorygroup=" + categorygroup + "&outputlimit=" + (numColunasConteudos*numLinhasConteudos) + "&maxcolumns=" + numColunasConteudos, function(){document.getElementById("busySendMainPage").className = "escondida";});
}



/**
 * Carregar items não validados (utilizador administrador) na zona de destaques da página principal.
 */
function loadNotValidated() {
	var lastval = "ND";
	
	document.getElementById("busySendMainPage").className = "";
	
	if (document.getElementById("lastval")) {
		lastval = document.getElementById("lastval").value;
	}
	$("#itemsToDisplay").load("php/itemsToDisplay.php?lastval=" + lastval + "&langid="+userlangid + "&type=30&categorygroup=0&categoryid=0&searchtype=0&querytxt=0&outputlimit="+(numColunasConteudos*numLinhasConteudos) + "&maxcolumns="+numColunasConteudos, function(){document.getElementById("busySendMainPage").className = "escondida";});
}


/**
 * Redimensionar a janela para ocupar todo o ecrã.
 */
function maximizeWindow() {
    window.moveTo(0,0)
    window.resizeTo(screen.availWidth, screen.availHeight)
}


/*****************************************************************/




/****************** ADICIONAR ITEMS e ALTERAR *********************/

/**
 * Inserir um novo item na base de dados.
 */
function insertItem() {
	window.scrollTo(0,0);
	
	document.getElementById("busySendMainPage").className = "";	
	
	var val = document.getElementById("category").value.split("-"); // $catid . '-' . $catgroup
	var categoryid = val[0];
	var categorygroup = val[1];	
	var title = document.getElementById("itemTitle").value;
	var description = document.getElementById("itemDescription").value;
	var price = document.getElementById("itemPrice").value;
	var hasfinancing = document.getElementById("hasFLink").value;	
	var itemlatitude = document.getElementById("itemLatitude").value;
	var itemlongitude = document.getElementById("itemLongitude").value;
	var itemaddress = document.getElementById("itemAddress").value;
	var obs = document.getElementById("itemObs").value;
	var videolink = document.getElementById("itemVideoLink").value;
	var videotitle = document.getElementById("itemVideoTitle").value;
	var documenttitle = document.getElementById("itemDocumentTitle").value;
	var documentdesc = document.getElementById("itemDocumentDesc").value;
	var secCode = document.getElementById("securityCodeNumber").value;
	
	var videoid = 0;  ////// inserir id a 0 (pode não ter video) e depois alterar id se tiver
	var documentid = 0;	//// inserir id a 0 (pode não ter documento) e depois alterar id se tiver
	var languageid = userlangid; // lingua actual
	
	
	
	// verificar se existem documentos ou imagens para fazer upload
	if (originaldocname.length <= 0) {
		docsuploadended = true;
	}	
	if (originalimgsname.length <= 0) {
		imagesuploadended = true;
	}
	
	iteminserted = false;
	
	
	// upload do video do youtube / verificação do link
	myVideoData = "";	
	if (videolink !== "") {
		myVideoData = videolink + "_" + videotitle;
	}
	
	
	// upload das imagens
	myPhotosNames = newimgname.join('_');	
	$('#imagesUpload').uploadifyUpload();	
	// clean images upload post buffer
	uploadpost = "";
	
		
	// upload do documento
	myDocumentData = "";
	if (newdoc !== null && newdoc.length >= 1) {
		myDocumentData = newdoc[0] + "_" + documenttitle + "_" + documentdesc;
	}
	$('#documentUpload').uploadifyUpload();	
	// clean document upload post buffer
	uploadpostdoc = "";
	
	
	///////////////
	
	
	switch(categorygroup){
		case '1': //vehicle
			insertVehicle(categoryid, categorygroup, title, description, price, hasfinancing, obs, itemlatitude, itemlongitude, itemaddress, videoid, documentid, languageid, secCode, myPhotosNames, myDocumentData, myVideoData);
			break;
			
		case '2': //property
			insertProperty(categoryid, categorygroup, title, description, price, hasfinancing, obs, itemlatitude, itemlongitude, itemaddress, videoid, documentid, languageid, secCode, myPhotosNames, myDocumentData, myVideoData);
			break;
			
		case '3': //business
			insertBusiness(categoryid, categorygroup, title, description, price, hasfinancing, obs, itemlatitude, itemlongitude, itemaddress, videoid, documentid, languageid, secCode, myPhotosNames, myDocumentData, myVideoData);
			break;
			
		case '4': //employment
			insertEmployment(categoryid, categorygroup, title, description, price, hasfinancing, obs, itemlatitude, itemlongitude, itemaddress, videoid, documentid, languageid, secCode, myPhotosNames, myDocumentData, myVideoData);
			break;
			
		default:
			insertDefault(categoryid, categorygroup, title, description, price, hasfinancing, obs, itemlatitude, itemlongitude, itemaddress, videoid, documentid, languageid, secCode, myPhotosNames, myDocumentData, myVideoData);
			break;
	}
	
}


/**
 * Inserir um novo item da categoria veiculo na base de dados.
 */
function insertVehicle(categoryid, categorygroup, title, description, price, hasfinancing, obs, itemlatitude, itemlongitude, itemaddress, videoid, documentid, languageid, secCode, photosNames, documentData, videoData) {
	var km = document.getElementById("vehicleKm").value;
	var numReg = document.getElementById("vehicleNumReg").value;
	var brand = document.getElementById("vehicleBrand").value;
	var model = document.getElementById("vehicleModel").value;
	var version = document.getElementById("vehicleVersion").value;
	var fuelType = document.getElementById("vehicleFuelType").value;
	var gearboxType = document.getElementById("vehicleGearboxType").value;
	var horsePower = document.getElementById("vehicleHorsePower").value;
	var cc = document.getElementById("vehicleCC").value;
	var capacity = document.getElementById("vehicleCapacity").value;
	var portNumber = document.getElementById("vehiclePortNumber").value;
	var color = document.getElementById("vehicleColor").value;	
	var extras = document.getElementById("vehicleExtras").value;
	
	
	$("#hiddenDiv").load("php/insertItem.php", {categid: categoryid, categgroup: categorygroup, itemTitle: title, itemDescription: description, itemPrice: price, hasFLink: hasfinancing, itemObs: obs, itemLatitude: itemlatitude, itemLongitude: itemlongitude, itemAddress: itemaddress, itemVideoID: videoid, itemDocumentID: documentid, itemLanguageID: languageid, vehicleKm: km, vehicleNumReg: numReg, vehicleBrand: brand, vehicleModel: model, vehicleVersion: version, vehicleFuelType: fuelType, vehicleGearboxType: gearboxType, vehicleHorsePower: horsePower, vehicleCC: cc, vehicleCapacity: capacity, vehiclePortNumber: portNumber, vehicleColor: color, vehicleExtras: extras, securityCode: secCode},
						 function(){
							 // dispara quando o upload está completo
							 iteminserted = true;
							 finishAddItem(photosNames, documentData, videoData);
						 });
}


/**
 * Inserir um novo item da categoria propriedade na base de dados.
 */
function insertProperty(categoryid, categorygroup, title, description, price, hasfinancing, obs, itemlatitude, itemlongitude, itemaddress, videoid, documentid, languageid, secCode, photosNames, documentData, videoData) {
	var type = document.getElementById("propertyType").value;
	var totalArea = document.getElementById("propertyTotalArea").value;
	var usefulArea = document.getElementById("propertyUsefulArea").value;
	var topology = document.getElementById("propertyTopology").value;
	var year = document.getElementById("propertyYear").value;
	var extras = document.getElementById("propertyExtras").value;
	
	
	$("#hiddenDiv").load("php/insertItem.php", {categid: categoryid, categgroup: categorygroup, itemTitle: title, itemDescription: description, itemPrice: price, hasFLink: hasfinancing, itemObs: obs, itemLatitude: itemlatitude, itemLongitude: itemlongitude, itemAddress: itemaddress, itemVideoID: videoid, itemDocumentID: documentid, itemLanguageID: languageid, propertyType: type, propertyTotalArea: totalArea, propertyUsefulArea: usefulArea, propertyTopology: topology, propertyYear: year, propertyExtras: extras, securityCode: secCode},
						 function(){
							// dispara quando o upload está completo
							iteminserted = true;
							finishAddItem(photosNames, documentData, videoData);
						 });
}


/**
 * Inserir um novo item da categoria negocios na base de dados.
 */
function insertBusiness(categoryid, categorygroup, title, description, price, hasfinancing, obs, itemlatitude, itemlongitude, itemaddress, videoid, documentid, languageid, secCode, photosNames, documentData, videoData) {
	var name = document.getElementById("businessName").value;
	var bussfunction = document.getElementById("businessFunction").value;
	var area = document.getElementById("businessArea").value;
	var busdescription = document.getElementById("businessDescription").value;
	
	
	$("#hiddenDiv").load("php/insertItem.php", {categid: categoryid, categgroup: categorygroup, itemTitle: title, itemDescription: description, itemPrice: price, hasFLink: hasfinancing, itemObs: obs, itemLatitude: itemlatitude, itemLongitude: itemlongitude, itemAddress: itemaddress, itemVideoID: videoid, itemDocumentID: documentid, itemLanguageID: languageid, businessName: name, businessFunction: bussfunction, businessArea: area, businessDescription: busdescription, securityCode: secCode},
						 function(){
							// dispara quando o upload está completo
							iteminserted = true;
							finishAddItem(photosNames, documentData, videoData);
						 });
}


/**
 * Inserir um novo item da categoria emprego na base de dados.
 */
function insertEmployment(categoryid, categorygroup, title, description, price, hasfinancing, obs, itemlatitude, itemlongitude, itemaddress, videoid, documentid, languageid, secCode, photosNames, documentData, videoData) {
	var offerOrSearch = document.getElementById("employmentOffer").value;
	var employfunction = document.getElementById("employmentFunction").value;
	var area = document.getElementById("employmentArea").value;
	var employdescription = document.getElementById("employmentDescription").value;
	
	
	$("#hiddenDiv").load("php/insertItem.php", {categid: categoryid, categgroup: categorygroup, itemTitle: title, itemDescription: description, itemPrice: price, hasFLink: hasfinancing, itemObs: obs, itemLatitude: itemlatitude, itemLongitude: itemlongitude, itemAddress: itemaddress, itemVideoID: videoid, itemDocumentID: documentid, itemLanguageID: languageid, employmentOffer: offerOrSearch, employmentFunction: employfunction, employmentArea: area, employmentDescription: employdescription, securityCode: secCode},
						 function(){
							// dispara quando o upload está completo
							iteminserted = true;
							finishAddItem(photosNames, documentData, videoData);
						 });
}



/**
 * Inserir um novo item da categoria base (outros) na base de dados.
 */
function insertDefault(categoryid, categorygroup, title, description, price, hasfinancing, obs, itemlatitude, itemlongitude, itemaddress, videoid, documentid, languageid, secCode, photosNames, documentData, videoData) {
	
	$("#hiddenDiv").load("php/insertItem.php", {categid: categoryid, categgroup: categorygroup, itemTitle: title, itemDescription: description, itemPrice: price, hasFLink: hasfinancing, itemObs: obs, itemLatitude: itemlatitude, itemLongitude: itemlongitude, itemAddress: itemaddress, itemVideoID: videoid, itemDocumentID: documentid, itemLanguageID: languageid, securityCode: secCode},
						 function(respText, textStatus, xmlHttpRequest) {
							// dispara quando o upload está completo
							iteminserted = true;
							finishAddItem(photosNames, documentData, videoData);
						 });
}



/**
 * Verificar se o upload de todos os elementos está concluído, mostrar informação e recarregar zona central da página.
 */
function finishAddItem(theitemfotos, theitemdoc, thevideodata) {
	
	if (docsuploadended && imagesuploadended && iteminserted) {
		var mynewitemid = document.getElementById("hiddenDiv").innerHTML;
		
		docsuploadended = false;
		imagesuploadended = false;
		iteminserted = false;
		
		$("#hiddenDiv").load("php/insertPicturesAndDoc.php", {newitemid: mynewitemid, itemfotos: theitemfotos, itemdoc: theitemdoc, itemvideo: thevideodata},
						 function() {
							// dispara quando o upload está completo
							alert('Anúncio inserido com sucesso - ID='+mynewitemid);
							originalimgsname = new Array(0);
							originaldocname = new Array(0);
							newimgname = new Array(0);
							newdoc = new Array(0);
							//if () {
								// if user isn't registered, show register form
								//showRegister();
							//}
							reloadPage();
						 });
	}
}


/**
 * Submeter posição GPS do novo item.
 */
function gMapSubmitPosNewItem(lat, lng, mapaddress) {
	document.getElementById("itemLatitude").value = lat;
	document.getElementById("itemLongitude").value = lng;
	document.getElementById("itemAddress").value = mapaddress;
	//document.getElementById("outputdiv").innerHTML = "(" + lat + ", " + lng + ")";
	
	GUnload();
	tb_remove();
}


/**
 * Mostrar mapa do google maps para selecção da localização de um novo item.
 */
function showMapSelectPointNewItem(strload) {
	
	//tb_remove();
	
	showGMapsBox(1, 39.402244, -7.954101, 'gMapSubmitPosNewItem');
	
	//$("#hiddenDiv").load(strload);
}


/**
 * Mostrar caixa de upload de videos.
 */
function showVideoUploadBox(strload) {
	document.getElementById("busySendMainPage").className = "";
	
	alert('Upload de videos ainda não implementado! Desculpe.');
	
	document.getElementById("busySendMainPage").className = "escondida";
}


/**
 * Mostrar caixa de upload de documentos.
 */
function showDocumentUploadBox(strload) {
	document.getElementById("busySendMainPage").className = "";
	
	alert('Upload de documentos ainda não implementado! Desculpe.');
	
	document.getElementById("busySendMainPage").className = "escondida";
}


/**
 * Salvar voto no item 'itemid' na BD.
 */
function setItemVote(itemid, itemvote) {
	document.getElementById("busySendMainPage").className = "";
	
	if (userItemVotes.indexOf(itemid) >= 0) {
		alert("Não Pode votar duas vezes consecutivas no mesmo item!");
	} else {
		userItemVotes.push(itemid);
		alert("Voto no item " + itemid + " com " + itemvote + " estrelas registado! Obrigado!");	
		$("#hiddenDiv").load("php/setItemVote.php", {id: itemid, vote:itemvote}, function(){viewItem(itemid);});		
	}
	
	document.getElementById("busySendMainPage").className = "escondida";
	
}

/*****************************************************************/




/*************************** VER ITEMS ***************************/


/**
 * Mostrar caixa de gestão de anuncios.
 */
function showUserItems() {
	document.getElementById("busySendMainPage").className = "";
	
	$("#myContents").load("php/showItemsList.php", function() {loadMyItems("ND");});

	window.scrollTo(0,0);
}

/** TODO
 * Mostrar mensagens do utilizador autenticado (todas (privadas/não privadas) e novas (privadas/não privadas) separadamente.
 */
function showMessages() {
	document.getElementById("busySendMainPage").className = "";
	
	alert("'Mensagens do utilizador autenticado' indisponivel de momento...");
	
	document.getElementById("busySendMainPage").className = "escondida";
}

/** TODO
 * Ver items favoritos do utilizador ligado.
 */
function showFavoriteItems() {
	document.getElementById("busySendMainPage").className = "";
	
	alert("'Favoritos do utilizador autenticado' indisponivel de momento...");
	
	document.getElementById("busySendMainPage").className = "escondida";
}

/**
 * Ver todos as informações de um item.
 */
function viewItem(id) {
	document.getElementById("busySendMainPage").className = "";
	
	$("#myContents").load("php/viewItem.php", {id: id}, function() {showItemComments(id);});	
	
	window.scrollTo(0, 0);
}


/** TODO
 * Mostrar todos os comentários (não privados) de um item CASO O UTILIZADOR ACTUAL ESTEJA LOGADO!
 */
function showItemComments(myitemid) {
	document.getElementById("busySendMainPage").className = "";
	
	$("#itemcommentsdiv").load("php/viewItemComments.php", {id: myitemid}, function() {document.getElementById("busySendMainPage").className = "escondida";});	
}



/** TODO
 * Actualizar a lista de versoes e modelos dos veículos referentes à marca seleccionada.
 */
function updateModelAndVersion() {
	alert("update model and version lists!!!");
}

/** TODO
 * Actualizar a lista de versoes dos veículos relativas ao modelo (e marca) seleccionada.
 */
function updateVersion() {
	alert("update version list!!!");
}


/** TODO
 * Actualizar a lista de topologias dos imóveis após selecção do tipo de imóvel.
 * (Caso não se aplique, colocar opção unica "Não aplicável".)
 */
function updateTopology() {
	alert("update topology list!!!");
}



/**
 * Mostrar o formulario apropriado de introdução de um novo item da categoria veiculo.
 */
function showVehicleForm() {
	document.getElementById("vehicle").className = "itemForm";
	document.getElementById("property").className = "escondida";
	document.getElementById("employment").className = "escondida";
	document.getElementById("business").className = "escondida";
}


/**
 * Mostrar o formulario apropriado de introdução de um novo item da categoria propriedade.
 */
function showPropertyForm() {
	document.getElementById("property").className = "itemForm";
	document.getElementById("vehicle").className = "escondida";
	document.getElementById("employment").className = "escondida";
	document.getElementById("business").className = "escondida";
}


/**
 * Mostrar o formulario apropriado de introdução de um novo item da categoria negocio.
 */
function showBusinessForm() {
	document.getElementById("business").className = "itemForm";
	document.getElementById("property").className = "escondida";
	document.getElementById("vehicle").className = "escondida";
	document.getElementById("employment").className = "escondida";
}


/**
 * Mostrar o formulario apropriado de introdução de um novo item da categoria emprego.
 */
function showEmploymentForm() {
	document.getElementById("employment").className = "itemForm";
	document.getElementById("property").className = "escondida";
	document.getElementById("vehicle").className = "escondida";
	document.getElementById("business").className = "escondida";
}


/**
 * Mostrar o formulario apropriado de introdução de um novo item da categoria base.
 */
function showDefaultForm() {
	document.getElementById("vehicle").className = "escondida";
	document.getElementById("property").className = "escondida";
	document.getElementById("employment").className = "escondida";
	document.getElementById("business").className = "escondida";
}


/**
 * Mudar a lista de sub-categorias em conformudade com a categoria seleccionada.
 */
function changeSubCatsList() {
	document.getElementById("busySendMainPage").className = "";
	var val = document.getElementById("category").value.split("-"); // $catid . '-' . $catgroup
	var maincatid = val[0];
	//var catgroup = val[1];
	
	showAppropriateForm();
	
	$("#subcatsdynamiclist").load("php/subcatsdynamiclist.php", {languageid: userlangid, internationalid: internationalid, mymaincatid: maincatid}, function() {document.getElementById("busySendMainPage").className = "escondida";});	
}

/**
 * Mostrar o formulario apropriado de introdução de um novo item, consoante a sua categoria.
 */
function showAppropriateForm() {
	var val = document.getElementById("category").value.split("-"); // $catid . '-' . $catgroup
	var catid = val[0];
	var catgroup = val[1];
	
	switch(catgroup) {
		case '1': //'vehicle':
			showVehicleForm();
			break;
			
		case '2': //'property':
			showPropertyForm();
			break;
			
		case '3': //'business':
			showBusinessForm();
			break;
			
		case '4': //'employment':
			showEmploymentForm();
			break;
			
		default: // outros-> artigos diversos - mostrar so os dados base
			showDefaultForm();
			break;
		
	}
}

/*****************************************************************/




/********************* USER REGISTER e LOGIN **********************/

/**
 * Mostrar o formulario de registo de um novo utilizador.
 */
function showRegister() {
	var myLink = "php/newUser.php?height=390&width=320";
	tb_show("Novo Utilizador", myLink, null);
}


/**
 * Verificar se a password e a sua confirmação são iguais e validas.
 */
function isValidPass(pass1, pass2){
	if(pass1 == pass2){
		return true;
	}	
	alert("A password e a sua confirmação são diferentes! Tente novamente.");
	return false;
}


/**
 * Verificar se o endereço de email é valido.
 */
function isValidEmail(str) {
		var at="@";
		var dot=".";
		var lat = str.indexOf(at);
		var lstr = str.length;
		var ldot = str.indexOf(dot);
		
		if (lat == -1){
		   alert("Invalid Email.");
		   return false;
		}

		if (lat == -1 || lat === 0 || lat == lstr) {
		   alert("Invalid Email.");
		   return false;
		}

		if (ldot == -1 || ldot === 0 || ldot == lstr) {
		    alert("Invalid Email.");
		    return false;
		}

		 if (str.indexOf(at,(lat+1))!=-1) {
		    alert("Invalid Email.");
		    return false;
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) {
		    alert("Invalid Email.");
		    return false;
		 }

		 if (str.indexOf(dot,(lat+2))==-1) {
		    alert("Invalid Email.");
		    return false;
		 }
		
		 if (str.indexOf(" ")!=-1) {
		    alert("Invalid Email.");
		    return false;
		 }

 		 return true;	 
}


/**
 * Inserir um novo utilizador.
 */
function novoUser() {
	document.getElementById("busySendUserRegister").className = "";
	
	var userphoto = 0; ////////// ADICIONAR CAMPO DE UPLOAD 1 FOTO AO FORMULÀRIO!
	var username = document.getElementById("fUser").value;
	var password = document.getElementById("fPass").value;
	var password2 = document.getElementById("fPass2").value;
	var nomecompleto = document.getElementById("fNome").value;
	var usersexo = document.getElementById("fSexo").value;
	var usermail = document.getElementById("fMail").value;
	var userhidemail = document.getElementById("fHidemail").value;
	var usercontacto = document.getElementById("fContact").value;
	var userendereco = document.getElementById("fAddress").value;
	var userlatitude = document.getElementById("fLatitude").value;
	var userlongitude = document.getElementById("fLongitude").value;
	var userlingua = document.getElementById("fLanguage").value;	
	var userdia = document.getElementById("fDia").value;
	var usermes = document.getElementById("fMes").value;
	var userano = document.getElementById("fAno").value;
	
	//nome = urlencode(nome);
	//endereco = urlencode(endereco);
	
	if(isValidPass(password, password2) && isValidEmail(usermail)) {	
		
		//tb_show("Novo Utilizador", myLink, null);
		$("#hiddenDiv").load("php/insertUser.php", {user: username, pass: password, photo: userphoto, nome: nomecompleto, sexo: usersexo, mail: usermail, hidemail: userhidemail, contact: usercontacto, address: userendereco, latitude: userlatitude, longitude: userlongitude, lang: userlingua, dia: userdia, mes: usermes, ano: userano}, function(){document.getElementById("busySendUserRegister").className="escondida";});
	} else {
		document.getElementById("busySendUserRegister").className = "escondida";
	}
	
}


/**
 * Mostrar janela de login.
 */
function showLogin() {
	var myLink = "php/loginForm.php?height=120&width=200";	
	tb_show("Login", myLink, null);
}


/**
 * Fazer login.
 */
function doLogin(){
	document.getElementById("busySendLogin").className = "";
	
	var username = document.getElementById("username").value;
	var password = document.getElementById("password").value;
		
	$("#hiddenDiv").load("php/doLogin.php", {user: username, pass: password, admingroup: admingroupid}, function(){document.getElementById("busySendLogin").className = "escondida";});	
}


/**
 * Fazer logout.
 */
function doLogout(){
	document.getElementById("busySendMainPage").className = "";
	
	$("#myContents").load("php/doLogout.php", function(){reloadPage();});
}


/** TODO
 * Mostrar caixa de dialogo para recuperação de password.
 */
function passRecovery() {
	document.getElementById("busySendLogin").className = "";
	
	alert("'Recuperar Password' indisponivel de momento...");
	
	document.getElementById("busySendLogin").className = "escondida";
}


/**
 * Mostrar mapa do google maps para selecção da morada aquando a criação de um novo utilizador.
 */
function showMapSelectPointNewUser(strload) {
	tmpUser = document.getElementById("fUser").value;
	tmpPass = document.getElementById("fPass").value;
	tmpPass2 = document.getElementById("fPass2").value;
	tmpNome = document.getElementById("fNome").value;
	tmpSexo = document.getElementById("fSexo").value;
	tmpMail = document.getElementById("fMail").value;	
	tmpHidemail = document.getElementById("fHidemail").value;
	tmpContact = document.getElementById("fContact").value;
	tmpAddress = document.getElementById("fAddress").value;
	tmpLanguage = document.getElementById("fLanguage").value;
	tmpDia = document.getElementById("fDia").value;
	tmpMes = document.getElementById("fMes").value;
	tmpAno = document.getElementById("fAno").value;
	
	//tb_remove();
	
	showGMapsBox(1, 39.402244, -7.954101, 'gMapSubmitPosNewUser');
	
	//$("#hiddenDiv").load(strload);
}


/**
 * Carregar valores para o formulario de introdução de novo utilizador.
 */
function loadNewUserFormData() {		
	document.getElementById("fUser").value = tmpUser;
	document.getElementById("fPass").value = tmpPass;
	document.getElementById("fPass2").value = tmpPass2;
	document.getElementById("fNome").value = tmpNome;
	document.getElementById("fSexo").value = tmpSexo;
	document.getElementById("fMail").value = tmpMail;	
	document.getElementById("fHidemail").value = tmpHidemail;
	document.getElementById("fContact").value = tmpContact;
	document.getElementById("fAddress").value = tmpAddress;
	document.getElementById("fLanguage").value = tmpLanguage;
	document.getElementById("fDia").value = tmpDia;
	document.getElementById("fMes").value = tmpMes;
	document.getElementById("fAno").value = tmpAno;
	document.getElementById("fLatitude").value = tmpLatitude;
	document.getElementById("fLongitude").value = tmpLongitude;
}

/**
 * Submeter posição GPS no novo utilizador.
 */
function gMapSubmitPosNewUser(lat, lng, mapaddress) {
	tmpLatitude = lat;
	tmpLongitude = lng;
	tmpAddress = mapaddress;
	//document.getElementById("outputdiv").innerHTML = "(" + lat + ", " + lng + ")";
	
	GUnload();
	//tb_remove();
	
	showRegister();
}

/*****************************************************************/




/************************* USER ADMIN ****************************/

/**
 * Validar um novo item previamente adicionado.
 */
function approveItem(id){
	document.getElementById("busySendMainPage").className = "";
	
	$("#myContents").load("php/approveItem.php", {id: id}, function(){reloadPage();});
	
	window.scrollTo(0,0);
}

/**
 * Apagar um item previamente adicionado.
 */
function deleteItem(id){
	document.getElementById("busySendMainPage").className = "";
	
	$("#myContents").load("php/deleteItem.php", {id: id}, function(){reloadPage();});
	
	window.scrollTo(0,0);
}


/**
 * Mostrar items não validados.
 */
function showNotValidatedItems() {	
	document.getElementById("busySendMainPage").className = "";

	$("#myContents").load("php/showItemsList.php", function() {loadNotValidated();});

	tb_remove();
	window.scrollTo(0,0);
}

/*****************************************************************/




/*********************** BARRA DO FUNDO **************************/

/** TODO
 * Mostrar ajuda da página.
 */
function showHelp() {
	document.getElementById("busySendMainPage").className = "";
	
	alert("'Ajuda' indisponivel de momento...");
	
	document.getElementById("busySendMainPage").className = "escondida";
}


/** TODO
 * Mostrar os termos e condições do serviço.
 */
function showConditions() {
	document.getElementById("busySendMainPage").className = "";
	
	alert("'Termos e Condições' indisponivel de momento...");
	
	document.getElementById("busySendMainPage").className = "escondida";
}


/** TODO
 * Mostrar o suporte da página (browsers suportados e etc).
 */
function showSuport() {
	document.getElementById("busySendMainPage").className = "";
	
	alert("'Suporte Técnico' indisponivel de momento...");
	
	document.getElementById("busySendMainPage").className = "escondida";
}

/** TODO
 * Mostar formulário de critícas, opiniões e sugestões dos utilizadores.
 */
function showSuggestionsForm() {
	document.getElementById("busySendMainPage").className = "";
	
	alert("Formulario 'Sugestões' indisponivel de momento...");
	
	document.getElementById("busySendMainPage").className = "escondida";
}

/*****************************************************************/




/********************* OPÇÕES MENU LATERAL ***********************/

/**
 * Mostrar items mais recentes.
 */
function showMoreRecent() {
	document.getElementById("busySendMainPage").className = "";
	
	currentDispTypeList = 1;
	if (document.getElementById("lastval")) {
		document.getElementById("lastval").value = "ND";
	}
	$("#myContents").load("php/showItemsList.php", function() {loadLastItems("ND");} );
	
	tb_remove();
	window.scrollTo(0,0);
}

/**
 * Mostrar items mais vistos.
 */
function showMoreViwed() {
	document.getElementById("busySendMainPage").className = "";
	
	currentDispTypeList = 2;
	if (document.getElementById("lastval")) {
		document.getElementById("lastval").value = "ND";
	}
	$("#myContents").load("php/showItemsList.php", function() {loadMoreViwedItems("ND");} );
	
	tb_remove();
	window.scrollTo(0,0);
}

/**
 * Mostrar items mais votados.
 */
function showMoreVoted() {
	document.getElementById("busySendMainPage").className = "";
	
	currentDispTypeList = 3;
	if (document.getElementById("lastval")) {
		document.getElementById("lastval").value = "ND";
	}
	$("#myContents").load("php/showItemsList.php", function() {loadMoreVotedItems("ND");} );
	
	
	tb_remove();
	window.scrollTo(0,0);
}

/**
 * Mostrar items preferidos.
 */
function showPrefered() {
	document.getElementById("busySendMainPage").className = "";
	
	currentDispTypeList = 4;
	if (document.getElementById("lastval")) {
		document.getElementById("lastval").value = "ND";
	}
	$("#myContents").load("php/showItemsList.php", function() {loadPreferedItems("ND");} );
	
	tb_remove();
	window.scrollTo(0,0);
}

/**
 * Mostrar todos os items.
 */
function showAll() {
	document.getElementById("busySendMainPage").className = "";
	
	currentDispTypeList = 1;
	if (document.getElementById("lastval")) {
		document.getElementById("lastval").value = "ND";
	}
	$("#myContents").load("php/showItemsList.php", function() {loadAll();} );
	
	tb_remove();
	window.scrollTo(0,0);
}



/**
 * Mostrar items de uma categoria pelo seu id e/ou pelo seu grupo.
 */
function showCat(catid, catgroup) {
	document.getElementById("busySendMainPage").className = "";
	
	currentDispTypeList = catid + 11;
	if (document.getElementById("lastval")) {
		document.getElementById("lastval").value = "ND";
	}
	$("#myContents").load("php/showItemsList.php", function() {loadCategoryById(catid);});

	tb_remove();
	window.scrollTo(0,0);
}


/**
 * Procurar item por texto.
 */
function simpleSearch() {
	document.getElementById("busySendMainPage").className = "";
	
	var inputtxt = document.getElementById("txtProcura").value;
	var searchtype = getCheckedValue(document.getElementsByName("simplesearchtype"));

	
	$("#myContents").load("php/showItemsList.php", function() {loadBySearch(searchtype, inputtxt);});

	tb_remove();
	window.scrollTo(0,0);
}


/** TODO
 * Detectar a categoria selecionada.
 */
function catSelected(cat) {
	alert("Categoria seleccionada: " + cat);
}


/** TODO
 * Detectar a sub-categoria selecionada
 */
function subCatSelected(subcat) {
	alert("Sub-categoria seleccionada: " + subcat);
}


/**************************************************************/


/**************** OPÇÕES BARRAS DE TOPO ***********************/

/**
 * Carregar formulario de adição de novos items.
 */
function addItem() {
	document.getElementById("busySendMainPage").className = "";
	
	$('#documentUpload').uploadifyClearQueue();
	$('#imagesUpload').uploadifyClearQueue();
	$("#myContents").load("php/addItem.php?langid="+userlangid + "&internationalid="+internationalid, function(){showAppropriateForm(); document.getElementById("busySendMainPage").className = "escondida";});
}

/**
 * Mostrar formulário de pesquisa simples.
 */
function showSimpleSearch() {
	var myLink = "php/simpleSearchForm.php?height=100&width=210";
	
	tb_show("Pesquisa básica", myLink, null);
}


/** TODO
 * Mostrar pesquisa avançada.
 */
function showAdvancedSearch() {
	var myLink = "php/advancedSearchForm.php?height=300&width=300";
	
	tb_show("Pesquisa avançada", myLink, null);
}


/** TODO
 * Mostrar estatisticas do site.
 */
function showStats() {
	var myLink = "php/systemStatsForm.php?height=400&width=300";
	
	tb_show("Estatisticas do site", myLink, null);
}


/**
 * Mostrar janela de mudança de lingua.
 */
function showChangeLanguage() {
	var myLink = "php/languagesForm.php?height=280&width=280";
	
	tb_show("Change language", myLink, null);
}


/**
 * Mudar idioma do sistema.
 */
function changeLanguage(langid) {
	userlangid = langid;
	reloadPage();
	tb_remove();
}

/** TODO
 * Mostrar propriedades da conta do utilizador.
 */
function accountProperties() {
	var myLink = "php/personaliseAccountForm.php?height=400&width=300";
	
	tb_show("Personalisar conta", myLink, null);
}


/**
 * Mostrar lista de categorias.
 */
function showCatList(langid) {
	var myLink = "php/showCatsList.php?height=500&width=300&langid=" + langid;
	
	tb_show("Lista de Categorias", myLink, null);
}


/**
 * Mostrar lista de destaques.
 */
function showHighlightsList(langid) {
	var myLink = "php/showHighlightsList.php?height=50&width=300&langid=" + langid;
	
	tb_show("Lista de Destaques", myLink, null);
}

/*****************************************************************/



/********************* NAVEGAÇÃO nas PAGINAS e ITEMS ***********************/

/** TODO
 * Mostrar a próxima página do conteúdo em 1º plano.
 */
function goToNextPage(type) {
	/*lastval = "ND";
	if (document.getElementById("lastval")) {
		lastval = document.getElementById("lastval").value;
	}
	lastlastval = lastval;
	switch(type) {
		case 1:
			loadLastItems(lastval);
		break;
		
		case 2:
			loadMoreViwedItems(lastval);
		break;
		
		case 3:
			loadMoreVotedItems(lastval);
		break;
		
		case 4:
			loadPreferedItems(lastval);
		break;
	}
	
	if (type > 10) {
		loadCategoryById(type-11);
	}*/
	
	document.getElementById("busySendMainPage").className = "";
	alert("Inactivo de momento. Pedimos desculpa pelo incomodo.");
	document.getElementById("busySendMainPage").className = "escondida";
			
	//alert("type=" + type + " lastval=" + lastval);	
}

/** TODO
 * Mostrar a página anterior do conteúdo em 1º plano.
 */
function goToPrevPage(type) {
	/*lastval = "ND";
	if (document.getElementById("lastval")) {
		lastval = document.getElementById("lastval").value;
	}
	switch(type) {
		case 1:
			loadLastItems(lastlastval);
		break;
		
		case 2:
			loadMoreViwedItems(lastlastval);
		break;
		
		case 3:
			loadMoreVotedItems(lastlastval);
		break;
		
		case 4:
			loadPreferedItems(lastlastval);
		break
	}
	
	if (type > 10) {
		loadCategoryById(type-11);
	}*/
	
	document.getElementById("busySendMainPage").className = "";
	alert("Inactivo de momento. Pedimos desculpa pelo incomodo.");
	document.getElementById("busySendMainPage").className = "escondida";
	
	//alert("type=" + type + " lastval=" + lastval+ " lastlastval=" + lastlastval);
}


/** TODO
 * Ir para o proximo item (depende da vista actual!).
 */
function goToNextItem() {
	document.getElementById("busySendMainPage").className = "";
	alert("Inactivo de momento. Pedimos desculpa pelo incomodo.");
	document.getElementById("busySendMainPage").className = "escondida";
}

/** TODO
 * Ir para o item anterior (depende da vista actual!).
 */
function goToPreviousItem() {
	document.getElementById("busySendMainPage").className = "";
	alert("Inactivo de momento. Pedimos desculpa pelo incomodo.");
	document.getElementById("busySendMainPage").className = "escondida";
}

/*****************************************************************/


/*** KEY PRESS ****/

/**
 * Executa a função 'mytask' se primido um 'enter'.
 */
function onEnter(evt, mytask) {
	var keynum = 0;
	
	if(window.event) { // IE
	  keynum = evt.keyCode;
	}
	else if(evt.which) { // Netscape/Firefox/Opera
	  keynum = evt.which;
	}
		
	if (keynum == 13 || keynum == '\n') {
		mytask();
	}
}




/**
 * Devolve true se a tecla primida não corresponde a um numero, falso caso contrario.
 */
function noNumbers(e) {
	var keynum;
	var keychar;
	var numcheck;

	if(window.event) { // IE
	  keynum = e.keyCode;
	}
	else if(e.which) { // Netscape/Firefox/Opera
	  keynum = e.which;
	}
	keychar = String.fromCharCode(keynum);
	numcheck = /\d/;
	
	return !numcheck.test(keychar);
}




// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}



