var inThickB = false;
var medPopup = false;
var bRegister = false;
var popOn = false;

var bShadowboxInit = false;

var strAttention = "Aten&ccedil;&atilde;o!"; 
var strInsertUser = "Tens que escrever o teu nome de utilizador!";
var strInsertPass = "Tens que escrever a tua palavra chave!";
var strInsertEmail = "Tens que escrever o teu email!";
var strInsertMSISDN = "Tens que escrever o teu n&uacute;mero de telem&oacute;vel!";
var strInsertName = "Tens que escrever o teu nome!";
var strAuthError = "Ocorreu um problema na autentica&ccedil;&atilde;o por favor tenta outra vez.";
var strActivated = "A tua conta ainda n&atilde;o foi activada. Por favor verifica o teu email.";
var strNeedAuth = "Para poderes enviar um shout precisas de fazer login!";
var strError = "Ocorreu um erro, por favor tenta de novo!";
var strValidEmail = "Tens que escrever um email v&aacute;lido!";
var strInsertSubject = "Tens que escrever o assunto da mensagem!";
var strInsertMsg = "Tens que escrever o texto da mensagem!";
var strSentEmail = "Email enviado, obrigado pelo teu contacto!";
var strAlreadyRegistered = "Esse endere&ccedil;o de email j&aacute; est&aacute; registado!";
var strMSISDNAlreadyRegistered = "Esse n&uacute;mero de telem&acute;vel j&aacute; est&aacute; registado!";
var strConfirmEmail = "Tens que confirmar o teu email!";
var strDateBirth = "Tens que seleccionar a tua data de nascimento!";
var strDayBirth = "Tens que seleccionar o teu dia de nascimento!";
var strMonthBirth = "Tens que seleccionar o teu m&ecirc;s de nascimento!";
var strYearBirth = "Tens que seleccionar o teu ano de nascimento!";
var strCaptcha = "Tens que inserir o c&oacute;digo de valida&ccedil;&atilde;o!";
var strRules = "Tens que ler e aceitar as regras de utiliza&ccedil;&atilde;o da TAG!";
var strRegisterOk = "Foste registado com sucesso, j&aacute; podes usar &agrave; vontade!";
var strConfirmPass = "Tens de confirmar a palavra-chave!";
var strPassNoMatch = "As palavras-chave n&atilde;o coincidem!";
var strPassNoMinChars = "A tua palavra-chave tem que ter pelo menos 5 caracteres!";
var strInsertSex = "Tens que indicar o teu sexo!";
var strChooseUser = "Tens que escolher o teu nome de utilizador!";
var strUserNoMinChars = "O teu nome de utilizador deve ter entre 3 e 14 caracteres!";
var strLettersNumbers = "O teu nome de utilizador tem de incluir letras ou n&uacute;meros!";
var strEmailSentTo = "Email enviado para"; 
var strIlegalChars = "O nome de utilizador tem os seguintes caracteres inv&aacute;lidos:";
var strActivate = "Foi-te enviado um email que necessita de confirma&ccedil;&atilde;o para poderes entrar na tua &aacute;rea myTAG.";
var strCongratulations = "Parab&eacute;ns";
var strGamesAuth = "Para poderes jogar precisas de fazer login";
var invalidAuth = "Utilizador ou palavra-chave inv&aacute;lidos!"
var bannedAuth = "A tua conta encontra-se desactivada!"

function open_youtube_video(code){
  popup = window.open('/youtubePopUp.jsp?code=' + code , 'youtubeVideo', 'width=465,height=384,titlebar=no,menubar=no,toolbar=no,status=no,location=no,scrollbars=no,resize=no,directories=no,hotkeys=no');
  popup.focus();
  return;
}

function check_flash(username, sessionid){
	var version = swfobject.getFlashPlayerVersion();

	// For HTML Pages
	if(username != undefined && sessionid != undefined){
		if(version.major >= 9){
			displayTopBar(username, sessionid);
		}
	}
	// For TAG and MyTAG
	else {	
		if(version.major < 9){
			window.location = "/flash_install.html"
			return false;
		}	
		else {
			return true;
		}
	}

	return true;
}
		
function initShadowbox(){
		
	if(bShadowboxInit){
		return;
	}
	if(!Shadowbox){
		setTimeout("initShadowbox()",1000);
		return;
	}
	

	bShadowboxInit = true;

	var options = {
		overlayColor: '#EADDAA',
		overlayOpacity: 0.75,
		displayNAv: false,
		resizeDuration: 0.15,
		loadingImage: '/images/loading.gif',
		text: {
				cancel:     'Cancelar',
			 	loading:    'carregando',
				close:      '',
				next:       '<span class="shortcut">S</span>eguinte',
				prev:       '<span class="shortcut">A</span>nterior'
		    }
	}
	Shadowbox.init(options);
	
}

function goRegister(){
	window.location = "/Comunidade/registar.jsp";
}
		
function displayTopBar(username, sessionID) {
			var flashvars = {};
			flashvars.username = username;
			flashvars.sessionID = sessionID;
			var params = {};
			params.quality = "high";
			params.allowfullscreen = "false";
			params.allowscriptaccess = "always";
			params.base = "/clips";
			var attributes = {};
			attributes.id = "topbar";
			swfobject.embedSWF("/clips/topbar.swf", "topbar", "910", "27", "9.0.0", false, flashvars, params, attributes);
}

function displayMenu(strSiteArea, numTags){
			var flashvars = {};
			flashvars.tags = numTags;
			flashvars.area = strSiteArea;
			var params = {};
			params.quality = "high";
			params.wmode = "transparent";
			params.bgcolor = "#ffffff";
			params.allowfullscreen = "false";
			params.allowscriptaccess = "always";
			params.base = "/clips";
			var attributes = {};
			attributes.id = "menubar";
			swfobject.embedSWF("/clips/menu.swf?v=2", "menubar", "912", "31", "9.0.0", false, flashvars, params, attributes);
}

function showMessage(msg, title){
	Shadowbox.open({
		type: 'swf',
		content: '/clips/msgBox.swf?strHeader='+title+'&strText='+msg,
		width: '228',
		height: '131'
	});

}

function showDlgRating(username, sessionID, owner, app, itemid){
	if(username == "guest")
		showMessage("Para votar tens que estar autenticado!");
	else {
		Shadowbox.open({
			type: 'swf',
			content: '/clips/passatempos/Vote.swf?username='+username+'&sessionID='+sessionID+'&owner='+owner+'&app='+app+'&itemID='+itemid,
			width: '163',
			height: '111'
		});
	}
}

function sendMessage(msgTo){
	var user = getStoredCookie("TAG-User");
	var session = getStoredCookie("TAG-Session");
	
	if(user == null || user == "" || session == null || session == "")
		showMessage("Sessão expirada!", "Erro");
	else{
		Shadowbox.open({
			type: 'swf',
			content: '/clips/dlgComposeMsg.swf?username='+user+'&sessionID='+session+'&msgTo='+msgTo,
			width: '405',
			height: '290'
		});
	}
}

function search(keyword){
  	Shadowbox.open({
		type: 'iframe',
		content: '/pesquisa.jsp?keyword='+keyword,
		width: '370',
		height: '420'
	});

}


function redirect(url){

  	Shadowbox.open({
		type: 'img',
		content: '/images/redirect.jpg',
		width: '678',
		height: '307'
	});
	
	setTimeout("window.location='"+url+"'", 5000);

}

function recoverPass(){
  	Shadowbox.open({
		type: 'iframe',
		content: '/recuperar.jsp',
		width: '351',
		height: '179'		
	});

}

function closePopup() {

	Shadowbox.close();
		
}

function needAuth(){
	showMessage(strNeedAuth);
}

function showRules(){
  	Shadowbox.open({
		type: 'iframe',
		content: '/info/Regras_p.html',
		width: '912',
		height: '429'		
	});
}


function requestTagCard(){
/*
  	Shadowbox.open({
		type: 'iframe',
		content: 'http://www.optimus.pt/Particulares/Servicos/WebphoneTeens',
		width: '519',
		height: '248'
	});
*/
	window.location="/TagEsTu/Cartao.jsp";
}

function showLoader(){

//	hideLoader();
//	$("#loading").show();

	if(true) return;		
  	Shadowbox.open({
		type: 'img',
		content: '/images/loadingAnimation.gif',
		width: '208',
		height: '13'
	});
	
}

function hideLoader(){

	//$("#loading").hide();
	
}

function drawAvatar(divID, owner, width, height, avatar, content){
					var flashvars = {};
					flashvars.owner = owner;
					flashvars.username = getStoredCookie(cookieTAG_User);
					flashvars.sessionID = getStoredCookie(cookieTAG_Session);
					flashvars.avatar = avatar;
					flashvars.content = content;
					flashvars.size = width;
					
					var params = {};
					params.quality = "high";
					params.bgcolor = "#ffffff";
					params.allowfullscreen = "false";
					params.allowscriptaccess = "always";
					params.base = "/clips";
					params.wmode = "transparent";
					var attributes = {};
					attributes.id = divID;
					swfobject.embedSWF("/clips/single_avatar.swf", divID, width, height, "9.0.0", false, flashvars, params, attributes);
}

/**
 *
 * LOGIN FUNCTIONS - START
 *
 */
  function doLogin(hashpass){
	
	var user = document.getElementById('login-user').value;
	if(user == ""){
		showMessage(strInsertUser);
		return;
	}
	
	var loginpass = document.getElementById('login-pass').value;
	var cookiepass = getStoredCookie("TAG-Hash");
	
	if(loginpass == ""){
		showMessage(strInsertPass);
		return;
	}
	
	var pass_md5 = (loginpass != cookiepass) ? hex_md5(loginpass) : cookiepass;
	var url = '/utils.jsp';
	var params = 'action=loginUser&username='+user+'&password='+pass_md5 +
				'&rcode='+Math.random();
	
	$.ajax({
		url: url,
		type: 'GET',
		dataType: 'html',
		data: params,
  		error: showFailedLogin,
		success: showLoginResult
	});
	
    showLoader();

  }
  function showFailedLogin(){
	showMessage(strAuthError);
  }
  
  function showLoginResult(resultStr){
	var resultStr = trim(resultStr);
	
	
	if(resultStr.substring(0,5) == "ERROR"){
		var msg = trim(resultStr.substring(7));
		
		if(msg == "INACTIVE") {
			showMessage(invalidAuth,"",false);
			//document.location = "/Comunidade/activar.jsp";
		}
		else if(msg == "BANNED"){
			showMessage(bannedAuth, "", false);
		}
		else {
			showMessage(resultStr.substring(7),"",false);
		}
	}
	else{
		if(resultStr.length< 50){
			var cb = document.getElementById('login-remember');
			var loginpass = document.getElementById('login-pass').value;
			var cookiepass = getStoredCookie('TAG-Hash');
			
			if(cb && cb.checked){
				if(cookiepass == null || cookiepass == "" || 
					(cookiepass != loginpass && loginpass != "" && loginpass != null))
					saveUserData(document.getElementById('login-user').value, hex_md5(loginpass));
				else
					saveUserData(document.getElementById('login-user').value, cookiepass);
			}
			else
				clearUserData();
				
			var theUsername = document.getElementById('login-user').value;
			storeCookie(cookieTAG_User, theUsername, 720, '/', '', '');
			storeCookie(cookieTAG_Session, resultStr, 1, '/', '', '');
				
			// window.location.reload(true);
			window.location = "/Comunidade/mytag.jsp";

		}
		else {
			showMessage(strError,"",false);
		}
	}
  }
  
function loginEnter(myfield,e)
{
	if(popOn!=true) {
		var keycode;
		if (window.event) keycode = window.event.keyCode;
		else if (e) keycode = e.which;
			else return true;
		
		if (keycode == 13)
		{
			doLogin();
			return false;
		}
		else
		   return true;
	}
}
function logout_flash(username, sessionID)
{
	
	var url = '/utils.jsp';
	var params = 'action=logout&username='+username+'&sessionID='+sessionID + '&rcode='+Math.random();
	
	$.ajax({
		url: url,
		type: 'GET',
		dataType: 'html',
		data: params,
  		error: logout_flashResult,
		success: logout_flashResult
	});
	
  }
  function logout_flashResult(){
  	
	clearCookie(cookieTAG_Session);
	clearCookie(cookieTAG_User);
	clearCookie(cookieTAG_Pass);
	clearCookie(cookieTAG_Hash);
	
	window.location.reload(true);
	
  }
 
function logout(username, sessionID)
{
	
	var url = '/utils.jsp';
	var params = 'action=logout&username='+username+'&sessionID='+sessionID + '&rcode='+Math.random();
	
	$.ajax({
		url: url,
		type: 'GET',
		dataType: 'html',
		data: params,
  		error: logoutResult,
		success: logoutResult
	});
	
    showLoader();

  }
  function logoutResult(){
	$("#TB_load").remove();
	
	clearCookie(cookieTAG_Session);
	clearCookie(cookieTAG_User);
	clearCookie(cookieTAG_Pass);
	clearCookie(cookieTAG_Hash);
	
	window.location.reload(true);
	
  }
/**
 *
 * LOGIN FUNCTIONS - END
 *
 */
 
/**
 * 
 * TAG UTILS
 *
 */
var cookieTAG_User="TAG-User";
var cookieTAG_Pass="TAG-Pass";
var cookieTAG_Hash="TAG-Hash";
var cookieTAG_Session="TAG-Session";

function setSessionCookie(user, session){
	var date = new Date();
	date.setTime(date.getTime()+(60*60*1000));
	var expires = "; expires="+date.toGMTString();
	document.cookie = cookieTAG_User+"="+user+expires+"; path=/";
	document.cookie = cookieTAG_Session+"="+session+expires+"; path=/";
}
function saveUserData(user, pass){
	var date = new Date();
	date.setTime(date.getTime()+(720*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
	document.cookie = cookieTAG_User+"="+user+expires+"; path=/";
	document.cookie = cookieTAG_Hash+"="+pass+expires+"; path=/";
}	    
function clearUserData()
{
	var date = new Date();
	date.setTime(date.getTime()-(365*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
	clearCookie(cookieTAG_User);
	clearCookie(cookieTAG_Pass);
}
function clearCookie(name)
{
	var date = new Date();
	date.setTime(date.getTime()-(365*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
	document.cookie = name+"="+expires+"; path=/";
}
function storeCookie( name, value, expires, path, domain, secure)
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	if ( expires ) // hours
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function getStoredCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) &&
	( name != document.cookie.substring( 0, name.length ) ) )
	{
	return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function getVarsFromCookies(){
	var theVars = "";
	var tmp = "";
	tmp = getStoredCookie(cookieTAG_User);
	var tmp2 = "";
	tmp2 = getStoredCookie(cookieTAG_Hash);
	thisMovie("flashcontent").setVars(tmp,tmp2); 
}

function thisMovie(movieName) {
    var isIE = navigator.appName.indexOf("Microsoft") != -1;
     return (isIE) ? window[movieName] : document[movieName];
}


function getCookie(c_name) {
	if (document.cookie.length>0) {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
	    { 
	    c_start=c_start + c_name.length+1; 
	    c_end=document.cookie.indexOf(";",c_start);
	    
		if (c_end==-1) 
			c_end=document.cookie.length;
		
		c_start_pwd = document.cookie.indexOf("TAG-Pass=");
		c_start_pwd = c_start_pwd + c_name.length+1; 


		thisMovie("Stage").getCookie(unescape(document.cookie.substring(c_start,c_end)),unescape(document.cookie.substring(c_start_pwd,document.cookie.length)));
	    } 
	  } else {
			thisMovie("Stage").getCookie("");
	  }

}

function echeck(str) {

	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	
	if (str.indexOf(at)==-1){
	   //alert("Invalid E-mail ID")
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   //alert("Invalid E-mail ID")
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		//alert("Invalid E-mail ID")
		return false
	}

	if (str.indexOf(at,(lat+1))!=-1){
		//alert("Invalid E-mail ID")
		return false
	 }

	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		//alert("Invalid E-mail ID")
		return false
	 }

	if (str.indexOf(dot,(lat+2))==-1){
		//alert("Invalid E-mail ID")
		return false
	}

	if (str.indexOf(" ")!=-1){
		//alert("Invalid E-mail ID")
		return false
	}

	return true					
}


/**
 * 
 * GENERAL UTILS
 *
 */
 // Removes leading whitespaces
function LTrim( value ) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {
	
	return LTrim(RTrim(value));
	
}

function urlencode(str) {
	str = escape(str);
	str = str.replace('+', '%2B');
	str = str.replace('%20', '+');
	str = str.replace('*', '%2A');
	str = str.replace('/', '%2F');
	str = str.replace('@', '%40');
	
	alert(str);
	
	return str;
}

function urldecode(str) {
	str = str.replace('+', ' ');
	str = unescape(str);
	return str;
}

/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {

    // public method for url encoding
    encode : function (string) {
   	
        //return escape(this._utf8_encode(string));
        
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // 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;
    }

}
