function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function xmlhttpPost(strURL, strSubmit, strResultFunc) {

       var xmlHttpReq = false;
       
       // Mozilla/Safari
       if (window.XMLHttpRequest) {
               xmlHttpReq = new XMLHttpRequest();
               if(xmlHttpReq.overrideMimeType) {
                   xmlHttpReq.overrideMimeType('text/html');
               }
       }
       // IE
       else if (window.ActiveXObject) {
               xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
       }

    xmlHttpReq.open('POST', strURL, true);
    xmlHttpReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xmlHttpReq.onreadystatechange = function() {
            if (xmlHttpReq.readyState == 4) {
                    eval(strResultFunc + '(xmlHttpReq.responseText);');
            }
    }

    xmlHttpReq.send(strSubmit);
}

function open_abstract(link){
	var largura = 332;
	var altura = 539;
	var w = largura;
	var h = altura;
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',title=Sociedade Portuguesa de Reumatologia,status=no,toolbar=no,menubar=no,scrollbars=yes,resizable=no';
	win = window.open(link, 'SPMFR', winprops);
	if (parseInt(navigator.appVersion) >= 4) win.window.focus();
}
function lunchboxOpen(lunchID) {
	document.getElementById('cartao_footer_' + lunchID).style.display = "block";
	document.getElementById('cartao_top_setaId_' + lunchID).innerHTML="<a href=\"javascript:lunchboxClose('" + lunchID + "');\"><img src=\"/ficheiro/interface/icone_menos.jpg\" border=\"0\"></a>";
}
function lunchboxClose(lunchID) {
	document.getElementById('cartao_footer_' + lunchID).style.display = "none";
	document.getElementById('cartao_top_setaId_' + lunchID).innerHTML="<a href=\"javascript:lunchboxOpen('" + lunchID + "');\"><img src=\"/ficheiro/interface/icone_mais.jpg\" border=\"0\"></a>";
}

function ver_imagem(path, titulo,imgwidth,imgheight){
	var w = imgwidth;
	var h = imgheight;
	var largura = w;
	var altura = h;
	var screenX = screen.width;
	var screenY = screen.height;
	var winl;
	var wint;

	if (w > screenX){
		largura = screenX;
		if (h > screenY){
			altura = screenY;
			largura = (w * screenY) / (h);
		} else {
			altura = (h * screenX) / (w);
		}
	} else {
		largura = w;
		if (h > screenY){
			altura = screenY;
			largura = (w * screenY) / (h);
		} else {
			altura = h;
		}
	}

	winl = (screenX - largura) / 2;
	wint = (screenY - altura) / 2;

	winprops = 'height='+altura+',width='+largura+',top='+wint+',left='+winl+',status=no,toolbar=no,menubar=no,scrollbars=no,resizable=no,directories=no';
	win = window.open('imagem.php?titulo='+titulo+'&imagem='+path+'&width='+largura+'&height='+altura,'', winprops);
	if (parseInt(navigator.appVersion) >= 4) win.window.focus();
}

function ver_imagem_keyword(raiz,path, titulo,imgwidth,imgheight){

	var w = imgwidth;
	var h = imgheight;
	var largura = w;
	var altura = h;
	var screenX = screen.width;
	var screenY = screen.height;
	var winl;
	var wint;

	if (w > screenX){
		largura = screenX;
		if (h > screenY){
			altura = screenY;
			largura = (w * screenY) / (h);
		} else {
			altura = (h * screenX) / (w);
		}
	} else {
		largura = w;
		if (h > screenY){
			altura = screenY;
			largura = (w * screenY) / (h);
		} else {
			altura = h;
		}
	}

	winl = (screenX - largura) / 2;
	wint = (screenY - altura) / 2;

	winprops = 'height='+altura+',width='+largura+',top='+wint+',left='+winl+',status=no,toolbar=no,menubar=no,scrollbars=no,resizable=no,directories=no';
	win = window.open(raiz+'imagem.php?titulo='+titulo+'&imagem='+path+'&width='+largura+'&height='+altura,'', winprops);
	if (parseInt(navigator.appVersion) >= 4) win.window.focus();
}

//esta funcao serve para alterar a cor do texto de press_realeases ao passar o rato
function changeStyleById(id, color){
	if (document.getElementById){
		var nodeObj = document.getElementById(id);
		nodeObj.style.color = color;
	}
}

function open_calendario(url, form, campo, dataEntrada)
 {
	urlFinal = url + "?form=" + form + "&campo=" + campo;
			if(!dataEntrada == "") {
				urlFinal += "&data_entrada=" + dataEntrada;
			}
			var newWindow;
	newWindow = window.open(urlFinal,'','height=250,width=255,toolbar=no,minimize=no,status=no,menubar=no,location=no,scrollbars=no');
}

function nltobr (str){
	var str=new String(str);
	var primeira_pos=str.search(/<[ ]*table/g);
	var temp_pos;
	var inicio=1;

	var ma_array=str.match(/<[ ]*\/[ ]*table/g);
	if (ma_array) {
			ultima_pos=str.lastIndexOf(ma_array[ma_array.length-1]);
	}
	if (primeira_pos!=-1) {
			var new_str=(str.slice(0,primeira_pos)).replace(/\n/g,"<br>");
			new_str+=(str.slice(primeira_pos,ultima_pos));
			new_str+=(str.slice(ultima_pos)).replace(/\n/g,"<br>");
	}
	else {
			var new_str=str.replace(/\n/g,"<br>");
	}
	return new_str;
}

function mostra_imagem(strFile,file_dir) {
	var file_dir = file_dir || '/';
	if (strFile != '')
			preview3(file_dir+strFile, 600, 400);

}

function checkEnterPage(nform, evt)
{
	evt = (evt) ? evt : event
	var charCode = (evt.wich) ? evt.wich : evt.keyCode
	if (charCode == 13)
	{
		 nform.submit();
		 return false
	}
	return true
}

function sub_caract_esq(str)
{
	var str_sub=String(str);
	var regexp=/€/g;
	str_sub=str_sub.replace(regexp,'&euro;');
	regexp=/[”“]/g;
	str_sub=str_sub.replace(regexp,'"');
	regexp=/…/g;
	str_sub=str_sub.replace(regexp,'...');
	regexp=/–/g;
	str_sub=str_sub.replace(regexp,'-');
	return str_sub;
}

function IsNumeric(sText)
{
    var re = /^[0-9]+$/;
	var test = re.test(sText);
	var valida = true;
	if (test)
	  valida = false;
	//alert(valida);
	return valida;   
}


function ComandoSelected(nome,accao)
{
	document.forms[nome].action=accao;
	document.forms[nome].submit();
}

function preview_nome(accao,w,h,nome)
{
	window.open('<?=$_SERVER[HTTPS]==on?$base:$URL?>'+accao,nome,toolbar=no,width='+w+',height='+h+',directories=no,status=no,scrollbars=yes,resizable=no,menubar=no,location=no);
}

function preview(accao,w,h)
{
	window.open('<?=$_SERVER[HTTPS]==on?$base:$URL?>'+accao,'<?=$LOGIN_USER?>',toolbar=no,width='+w+',height='+h+',directories=no,status=no,scrollbars=yes,resizable=no,menubar=no,location=no);
}

function nova(accao,w,h)
{
	window.open('<?=$_SERVER[HTTPS]==on?$base:$URL?>'+accao,'<?=$LOGIN_USER?>',toolbar=no,width='+w+',height='+h+',directories=no,status=no,scrollbars=no,resizable=no,menubar=no,location=no);
}

function preview2(accao,w,h)
{
	window.open('<?=$_SERVER[HTTPS]==on?$base:$URL?>'+accao,'Imagem_<?=$LOGIN_USER?>',toolbar=no,width='+w+',height='+h+',directories=no,status=no,resizable=yes,menubar=yes,location=no);

}

function preview3(accao,w,h)
{
	window.open(accao,'Imagem_<?=$LOGIN_USER?>',toolbar=no,width='+w+',height='+h+',directories=no,status=no,resizable=yes,menubar=yes,location=no);

}

function ver_header(id_ficheiro, w, h){

	var largura = w;
	var altura = h;
	var screenX = screen.width;
	var screenY = screen.height;
	var winl;
	var wint;

	if (w > screenX){
		largura = screenX;
		if (h > screenY){
			altura = screenY;
			largura = (w * screenY) / (h);
		} else {
			altura = (h * screenX) / (w);
		}
	} else {
		largura = w;
		if (h > screenY){
			altura = screenY;
			largura = (w * screenY) / (h);
		} else {
			altura = h;
		}
	}

	winl = (screenX - largura) / 2;
	wint = (screenY - altura) / 2;

	winprops = 'height='+altura+',width='+largura+',top='+wint+',left='+winl+',status=no,toolbar=no,menubar=no,scrollbars=no,resizable=no,directories=no';
	win = window.open('imagem.php?imagem='+id_ficheiro+'&width='+w+'&height='+h,'', winprops);
	if (parseInt(navigator.appVersion) >= 4) win.window.focus();
}

function MultiSelector( list_target){
	this.list_target = list_target;
	this.count = 0;
	this.id = 0;
	this.addElement = function( element ){
		if( element.tagName == 'INPUT' && element.type == 'file' ){
			element.name = 'file[]';
			element.className= 'select_normal';
			element.multi_selector = this;element.onchange = function(){
				var new_element = document.createElement( 'input' );
				new_element.type = 'file';
				this.parentNode.insertBefore( new_element, this );
				this.multi_selector.addElement( new_element );
				this.multi_selector.addListRow( this );
				this.style.position = 'absolute';
				this.style.left = '-1000px';
			};
			this.count++;
			this.current_element = element;
		} else {
			alert( 'Error: not a file input element' );
		};
	};
	this.addListRow = function( element ){
		var new_row = document.createElement( 'div' );
		var new_row_button = document.createElement( 'input' );
		new_row_button.type = 'button';
		new_row_button.value = 'remover';
		new_row_button.className = 'botao_normal';
		new_row.element = element;
		new_row_button.onclick= function(){
			this.parentNode.element.parentNode.removeChild(
			this.parentNode.element );
			this.parentNode.parentNode.removeChild( this.parentNode );
			this.parentNode.element.multi_selector.count--;
			this.parentNode.element.multi_selector.current_element.disabled = false;
			return false;
		};
		new_row.innerHTML = '<b>' + element.value + '</b>  ';
		new_row.appendChild( new_row_button );
		this.list_target.appendChild( new_row );
	};
};

function MultiSelector_( list_target){
	this.list_target = list_target;
	this.count = 0;
	this.id = 0;
	this.addElement = function( element ){
		if( element.tagName == 'INPUT' && element.type == 'file' ){
			element.name = 'file[]';
			element.className= 'select_normal';
			element.multi_selector = this;element.onchange = function(){
				var new_element = document.createElement( 'input' );
				new_element.type = 'file';
				this.parentNode.insertBefore( new_element, this );
				this.multi_selector.addElement( new_element );
				this.multi_selector.addListRow( this );
				this.style.position = 'absolute';
				this.style.left = '-1000px';
			};
			this.count++;
			this.current_element = element;
		} else {
			alert( 'Error: not a file input element' );
		};
	};
	this.addListRow = function( element ){
		var new_row = document.createElement( 'div' );
		
		var new_desc = document.createElement( 'span' ) ;
		new_desc.innerHTML = "&nbsp;&nbsp;";
		
		var new_inp = document.createElement('input');
		new_inp.name = "descricao[]";
		new_inp.type = "text";
		new_inp.className = 'input_normal';
		new_inp.value = 'legenda ';
		
		new_desc.appendChild( new_inp ) ;
		
		var new_row_button = document.createElement( 'input' );
		new_row_button.type = 'button';
		new_row_button.value = 'remover';
		new_row_button.className = 'botao_normal';
		new_row.element = element;
		new_row_button.onclick= function(){
			this.parentNode.element.parentNode.removeChild(
			this.parentNode.element );
			this.parentNode.parentNode.removeChild( this.parentNode );
			this.parentNode.element.multi_selector.count--;
			this.parentNode.element.multi_selector.current_element.disabled = false;
			return false;
		};
		new_row.innerHTML = '<b>' + element.value + '</b>  ';
		new_row.appendChild ( new_desc ) ;
		new_row.appendChild( new_row_button );
		this.list_target.appendChild( new_row );
	};
};
function MultiSelector2(list_target){
	this.list_target = list_target;
	this.count = 0;
	this.id = 0;
	
	this.addElement = function( element ){
		if( element.tagName == 'INPUT' && element.type == 'file' ){
			element.name = 'file[]';
			element.className= 'select_normal';
			element.multi_selector = this;element.onchange = function(){
				var new_element = document.createElement( 'input' );
				new_element.type = 'file';
				this.parentNode.insertBefore( new_element, this );
				this.multi_selector.addElement( new_element );
				this.multi_selector.addListRow( this );
				this.style.position = 'absolute';
				this.style.left = '-1000px';
			};
			this.count++;
			this.current_element = element;
		} else {
			alert( 'Error: not a file input element' );
		};
	};
	
	this.addListRow = function( element ){
		var textBoxLegenda = document.createElement( 'input' );
		var new_row = document.createElement( 'div' );
		var new_row_button = document.createElement( 'input' );
		//cria botao remover
		new_row_button.type = 'button';
		new_row_button.value = 'remover';
		new_row_button.className = 'botao_normal';
		//cria o tipo ficheiro
		new_row.element = element;
		//cria a caixa de texto legenda
		textBoxLegenda.type = 'text';
		textBoxLegenda.name = 'legenda[]';
		textBoxLegenda.id = 'legenda[]';
		textBoxLegenda.className = 'input_normal';
		
		
		
		new_row_button.onclick= function(){
			this.parentNode.element.parentNode.removeChild(
			this.parentNode.element );
			this.parentNode.parentNode.removeChild( this.parentNode );
			this.parentNode.element.multi_selector.count--;
			this.parentNode.element.multi_selector.current_element.disabled = false;
			return false;
		};
		
		//adiciona ficheiro e botao
		new_row.innerHTML = '<br/><b> imagem '+(this.count-1)+':</b> ' + element.value+'  ';
		
		//adiciona legenda
		new_row.innerHTML += '<br/><b>Legenda da imagem '+(this.count-1)+':</b><font color=\"#FF0000\">*</font><br/>';
		new_row.appendChild( textBoxLegenda );
		new_row.appendChild( new_row_button );
		
		this.list_target.appendChild( new_row );
		//this.list_target.appendChild( rowLegenda );
		//this.list_target.appendChild( textBoxLegenda );
	};
};


function ver_cartao(membro){

	var largura = 250;
	var altura = 420;
	var screenX = screen.width;
	var screenY = screen.height;
	
	winl = (screenX - largura) / 2;
	wint = (screenY - altura) / 2;

	winprops = 'height='+altura+',width='+largura+',top='+wint+',left='+winl+',status=no,toolbar=no,menubar=no,scrollbars=no,resizable=no,directories=no';
	window.open('cartao.php?id_membro='+membro,'Cartão', winprops);
	
}
function ver_cartao_pesquisado(membro){
	
	var largura = 250;
	var altura = 420;
	var screenX = screen.width;
	var screenY = screen.height;
	
	winl = (screenX - largura) / 2;
	wint = (screenY - altura) / 2;
	
	winprops = 'height='+altura+',width='+largura+',top='+wint+',left='+winl+',status=no,toolbar=no,menubar=no,scrollbars=no,resizable=no,directories=no';
	window.open('cartao.php?id_membro='+membro,'Cartão', winprops);

}

function displayWindow(theURL,winName,width,height,features) {

	var window_width = width;
    var window_height = height;
    var newfeatures= features;
    var window_top = (screen.height-window_height)/2;
    var window_left = (screen.width-window_width)/2;
    newWindow=window.open(''+ theURL + '',''+ winName + '','width=' + window_width + ',height=' + window_height + ',top=' + window_top + ',left=' + window_left + ',features=' + newfeatures + ',status=no,toolbar=no,menubar=no,scrollbars=no,resizable=no,directories=no');
    newWindow.focus();
}

function ver_comentario(id_coment){

	var screenX = screen.width;
	var screenY = screen.height;

	winl = (screenX - 500) / 2;
	wint = (screenY - 260) / 2;

	winprops = 'height=260,width=500,top='+wint+',left='+winl+',status=no,toolbar=no,menubar=no,scrollbars=no,resizable=no,directories=no';
	win = window.open('coment.php?coment='+id_coment,'', winprops);
	if (parseInt(navigator.appVersion) >= 4) win.window.focus();
}

function fillSelectFromArray(selectCtrl, itemArray, defaultItem, goodPrompt, badPrompt) {
	var i, j;
	var prompt;
		
	// empty existing items
	for (i = selectCtrl.options.length; i >= 0; i--) {
		selectCtrl.options[i] = null;
	}
	prompt = (itemArray != null) ? goodPrompt : badPrompt;
	if (prompt == null) {
		j = 0;
	}
	else {
		selectCtrl.options[0] = new Option(prompt);
		j = 1;
	}
	if (itemArray != null) {
		// add new items
		for (i = 0; i < itemArray.length; i++) {
			selectCtrl.options[j] = new Option(itemArray[i][0]);
			if (itemArray[i][1] != null) {
				selectCtrl.options[j].value = itemArray[i][1];
			}
			if(itemArray[i][1] == defaultItem && defaultItem != null){
				selectCtrl.options[j].selected = true;
			}
			j++;
		}
		// select first item (prompt) for sub list

	 }
}

/*
 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
 * in FIPS PUB 180-1
 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for details.
 */

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_sha1(s){return binb2hex(core_sha1(str2binb(s),s.length * chrsz));}
function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * chrsz));}
function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length * chrsz));}
function hex_hmac_sha1(key, data){ return binb2hex(core_hmac_sha1(key, data));}
function b64_hmac_sha1(key, data){ return binb2b64(core_hmac_sha1(key, data));}
function str_hmac_sha1(key, data){ return binb2str(core_hmac_sha1(key, data));}

/*
 * Perform a simple self-test to see if the VM is working
 */
function sha1_vm_test()
{
  return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
}

/*
 * Calculate the SHA-1 of an array of big-endian words, and a bit length
 */
function core_sha1(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << (24 - len % 32);
  x[((len + 64 >> 9) << 4) + 15] = len;

  var w = Array(80);
  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;
  var e = -1009589776;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;
    var olde = e;

    for(var j = 0; j < 80; j++)
    {
      if(j < 16) w[j] = x[i + j];
      else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
      var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
                       safe_add(safe_add(e, w[j]), sha1_kt(j)));
      e = d;
      d = c;
      c = rol(b, 30);
      b = a;
      a = t;
    }

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
    e = safe_add(e, olde);
  }
  return Array(a, b, c, d, e);

}

/*
 * Perform the appropriate triplet combination function for the current
 * iteration
 */
function sha1_ft(t, b, c, d)
{
  if(t < 20) return (b & c) | ((~b) & d);
  if(t < 40) return b ^ c ^ d;
  if(t < 60) return (b & c) | (b & d) | (c & d);
  return b ^ c ^ d;
}

/*
 * Determine the appropriate additive constant for the current iteration
 */
function sha1_kt(t)
{
  return (t < 20) ?  1518500249 : (t < 40) ?  1859775393 :
         (t < 60) ? -1894007588 : -899497514;
}

/*
 * Calculate the HMAC-SHA1 of a key and some data
 */
function core_hmac_sha1(key, data)
{
  var bkey = str2binb(key);
  if(bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
  return core_sha1(opad.concat(hash), 512 + 160);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

/*
 * Convert an 8-bit or 16-bit string to an array of big-endian words
 * In 8-bit function, characters >255 have their hi-byte silently ignored.
 */
function str2binb(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - i%32);
  return bin;
}

/*
 * Convert an array of big-endian words to a string
 */
function binb2str(bin)
{
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (32 - chrsz - i%32)) & mask);
  return str;
}

/*
 * Convert an array of big-endian words to a hex string.
 */
function binb2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8  )) & 0xF);
  }
  return str;
}

/*
 * Convert an array of big-endian words to a base-64 string
 */
function binb2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * (3 -  i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}


function ccnum(form){
	x001 = form.num001.value;
	x002 = form.num002.value;
	x003 = form.num003.value;
	x004 = form.num004.value;
	x = x001+x002+x003+x004;
	form.C003.value = x;
	seg_par(form);
}

function valdat(form){
	x001 = form.val_ano.value;
	x002 = form.val_mes.value;
	x = x001+x002;
	form.C004.value = x;
	seg_par(form);
}

function codcvv(form){
	form.C005.value = form.cvv.value;
	seg_par(form);
}

function seg_par(form){
	x000 = form.cs.value;
	x001 = form.sp.value;
	x002 = form.C003.value;
	x003 = form.C004.value;
	x004 = form.C005.value;
	x005 = form.C012.value;
	x006 = x001+x002+x003+x004+x005;
	x007 = hex_hmac_sha1(x000, x006);
	form.C013.value = x007.toUpperCase();
}

function closeall(layer){
	document.getElementById('pagamento1').style.display = 'none';
	document.getElementById('pagamento2').style.display = 'none';
	document.getElementById('pagamento3').style.display = 'none';
	document.getElementById('pagamento4').style.display = 'none';
	document.getElementById('pagamento5').style.display = 'none';
	document.getElementById(layer).style.display = 'block';
}

function soma_numero() { 
	 var _num001 = document.getElementById("3DSECURE").num001.value; 
	 var _num002 = document.getElementById("3DSECURE").num002.value; 
	 var _num003 = document.getElementById("3DSECURE").num003.value; 
	 var _num004 = document.getElementById("3DSECURE").num004.value; 
	 var numero_cc = _num001 + _num002 + _num003 + _num004;
	 checkCard(numero_cc);
	 document.getElementById("3DSECURE").C003.value  = numero_cc;  
	// alert(numero_cc);
} 

 function soma_validade() { 
	 var _val_mes = document.getElementById("3DSECURE").val_mes.value; 
	 var _val_ano = document.getElementById("3DSECURE").val_ano.value;
	 var validade = _val_ano + _val_mes;	
	 document.getElementById("3DSECURE").C004.value  = validade; 
	 //alert(validade);
}
 


  function validate_form_cheque()
	{
	document.getElementById("erro_letra").innerHTML = "";
	document.getElementById("erro_letra").style.display = 'none';
	
	
    valid = true;
	if(document.getElementById("3DSECURE").metodo[1].checked == true)
	{		
		if(document.getElementById("3DSECURE").agencia.value.length <= '1'){
			valid = false;
			document.getElementById("erro_letra").innerHTML += "Introduza o nome da sua agência.<br>"; 
		}
		else if(document.getElementById("3DSECURE").cheque.value.length<=1){
			valid = false;
			document.getElementById("erro_letra").innerHTML += "Introduza o número de cheque.<br>"; 
		}
		else if(IsNumeric(document.getElementById("3DSECURE").cheque.value)==true){
			valid = false;
			document.getElementById("erro_letra").innerHTML += "Apenas são aceites números.<br>"; 
		}	
	}
    if(valid==false){
    	document.getElementById("erro_letra").style.display = 'block';
		 return valid;
    }
    if(valid==true){
    	document.getElementById("erro_letra").style.display = 'none';
		 return valid;
    }
  }
  
   function validate_form_vale()
	{
	document.getElementById("erro_letra").innerHTML = "";
	document.getElementById("erro_letra").style.display = 'none';
	
	
    valid = true;
	if(document.getElementById("3DSECURE").metodo[4].checked == true)
	{		
		if(document.getElementById("3DSECURE").numero_vale.value.length<=1){
			valid = false;
			document.getElementById("erro_letra").innerHTML += "Introduza o número de cheque.<br>"; 
		}
		else if(IsNumeric(document.getElementById("3DSECURE").numero_vale.value)==true){
			valid = false;
			document.getElementById("erro_letra").innerHTML += "Apenas são aceites números.<br>"; 
		}	
	}
    if(valid==false){
    	document.getElementById("erro_letra").style.display = 'block';
		 return valid;
    }
    if(valid==true){
    	document.getElementById("erro_letra").style.display = 'none';
		 return valid;
    }
  }
 
 function validate_form()
{
	document.getElementById("erro_letra").innerHTML = "";
	document.getElementById("erro_letra").style.display = 'none';
	
	
    valid = true;
     var _num001 = document.getElementById("3DSECURE").num001.value; 
	 var _num002 = document.getElementById("3DSECURE").num002.value; 
	 var _num003 = document.getElementById("3DSECURE").num003.value; 
	 var _num004 = document.getElementById("3DSECURE").num004.value; 
	 var numero_cc = _num001 + _num002 + _num003 + _num004;
	if(document.getElementById("3DSECURE").metodo[0].checked == true)
	{
		if(document.getElementById("3DSECURE").num001.value.length != '4'){
			valid = false;
			document.getElementById("erro_letra").innerHTML += "Introduza os 4 números da 1ª parcela.<br>"; 
		}	
		else if(IsNumeric(document.getElementById("3DSECURE").num001.value)==true){
			valid = false;
			document.getElementById("erro_letra").innerHTML += "Apenas são aceites números.<br>"; 
		}
		else if(document.getElementById("3DSECURE").num002.value.length!=4){
			valid = false;
			document.getElementById("erro_letra").innerHTML += "Introduza os 4 números da 2ª parcela.<br>"; 
		}
		else if(IsNumeric(document.getElementById("3DSECURE").num002.value)==true){
			valid = false;
			document.getElementById("erro_letra").innerHTML += "Apenas são aceites números.<br>"; 	
		}
		else if(document.getElementById("3DSECURE").num003.value.length!=4){
			valid = false;
			document.getElementById("erro_letra").innerHTML += "Introduza os 4 números da 3ª parcela.<br>"; 
		}	
		else if(IsNumeric(document.getElementById("3DSECURE").num003.value)==true){
			valid = false;
			document.getElementById("erro_letra").innerHTML += "Apenas são aceites números.<br>"; 
		}
		else if(document.getElementById("3DSECURE").num004.value.length!=4){
			valid = false;
			document.getElementById("erro_letra").innerHTML += "Introduza os 4 últimos números na 4ª parcela.<br>"; 
		}
		else if(IsNumeric(document.getElementById("3DSECURE").num004.value)==true){
			valid = false;
			document.getElementById("erro_letra").innerHTML += "Apenas são aceites números.<br>"; 	
		}else if(checkCard(numero_cc)==false){
			valid = false;
			document.getElementById("erro_letra").innerHTML += "O número do cartão é inválido.<br>Por favor, verifique se o introduziu correctamente.<br>"; 
		}else if(IsNumeric(document.getElementById("3DSECURE").val_mes.value)==true){
			valid = false;
			
			document.getElementById("erro_letra").innerHTML += "Apenas são aceites números na validade do mês do seu cartão (mm).<br>"; 
		}	
		else if(document.getElementById("3DSECURE").val_mes.value.length!=2){
			
			valid = false;
			document.getElementById("erro_letra").innerHTML += "Introduza o mês de validade do seu cartão (mm).<br>"; 			
		}	
		if(document.getElementById("3DSECURE").val_mes.value.length==2 && IsNumeric(document.getElementById("3DSECURE").val_mes.value)==false){
			var avancar=0;
			
			switch (document.getElementById("3DSECURE").val_mes.value){
					case "01": 
					case "02": 
					case "03": 
					case "04": 
					case "05": 
					case "06": 
					case "07": 
					case "08": 
					case "09": 
					case "10": 
					case "11": 
					case "12": 						
						avancar=1;						
						break;					
					default : 
						valid = false;	
						document.getElementById("erro_letra").innerHTML += "Os números do mês de validade do seu cartão têm de estar entre os valores 01 e 12.<br>"; 
						avancar=0;		
						break;	
						
				}
		}
		if(avancar=='1'){		
			if(document.getElementById("3DSECURE").val_ano.value.length != '4'){
				valid = false;
				document.getElementById("erro_letra").innerHTML += "Introduza o ano de validade do seu cartão (aaaa).<br>"; 
			}		
			else if(IsNumeric(document.getElementById("3DSECURE").val_ano.value)==true){
				valid = false;
				document.getElementById("erro_letra").innerHTML += "Apenas são aceites números no ano de validade do seu cartão (aaaa)."; 
			}	
			else if(Number(document.getElementById("3DSECURE").val_ano.value) < 2007 || Number(document.getElementById("3DSECURE").val_ano.value) > 2020){
				valid = false;
				document.getElementById("erro_letra").innerHTML += "O ano de validade do seu cartão tem de ser superior ao ano actual e inferior a 2020.<br>"; 
			}	
			else if(IsNumeric(document.getElementById("3DSECURE").cvv.value)==true){
				valid = false;
				document.getElementById("erro_letra").innerHTML += "Apenas são aceites números no CVV.<br>"; 
			}		
			else if(document.getElementById("3DSECURE").cvv.value.length!=3){
				valid = false;	
				document.getElementById("erro_letra").innerHTML += "Necessita de introduzir os 3 números do seu CVV.<br>"; 
			}	
			else  {
				
			}
		}
	}
    if(valid==false){
    	document.getElementById("erro_letra").style.display = 'block';    		 
    }
    if(valid==true){
    	document.getElementById("erro_letra").style.display = 'none';
    	soma_numero();
    	soma_validade(); 
    	 document.getElementById("3DSECURE").C005.value  = document.getElementById("3DSECURE").cvv.value;    	
    	//soma_tudo();    
    	ajaxFunction();    		   	
    }
    return valid;
  }
 
  
  
  
function isCreditCard( CC )
{
	if (CC.length > 19)
		return (false);
	
	sum = 0; 
	mul = 1; 
	l = CC.length;
	for (i = 0; i < l; i++)
	{
		digit = CC.substring(l-i-1,l-i);
		tproduct = parseInt(digit ,10)*mul;
		if (tproduct >= 10)
			sum += (tproduct % 10) + 1;
		else
			sum += tproduct;
		if (mul == 1)
			mul++;
		else
			mul--;
	}
	if ((sum % 10) == 0)
		return (true);
	else
		return (false);
}

function isVisa( cc )
{
	if( (cc.substring(0,1) == 4) && (cc.length == 16) || (cc.length == 13) )
	{
		return isCreditCard( cc );
	}
	return (false);
}

function isMC( cc )
{
	if( (cc.length == 16) && (cc.substring(0,2) == 51)	|| (cc.substring(0,2) == 52) || (cc.substring(0,2) == 53) || (cc.substring(0,2) == 54) || (cc.substring(0,2) == 55) )
	{
		return isCreditCard( cc );
	}
	return (false);
}

function checkCard(cc){
	
	var ccredito=false;
	var validar=false;
	if(!isCreditCard( cc )) { 
		ccredito=true;		
	}
	if(isMC( cc )) { 
		validar = true;
	}	
	if(isVisa( cc )) {
		validar = true;
	}	
	return validar;
}

function addquot (str){
	var str=new String(str);
	var new_str=str.replace(/["]/g,"&quot;");
	return new_str;
}

function limitInput(limitField, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	}
}

function altera_href_link(document,campo){
	for(i=37;i<=63;i++){
		document.links[i].href+='&campo='+campo;
	}
}


function direita(id){
	var el = document.getElementById(id);
	el.scrollLeft  += 150;
}

function ddireita(id){
	tempo = window.setInterval(function(){ direita(id); }, 100);
}

function esquerda(id){
	var el = document.getElementById(id);
	el.scrollLeft  -= 150;
}

function sesquerda(id){
	tempo = window.setInterval(function(){ esquerda(id); }, 100);
}

function parar(){
	window.clearInterval(tempo);
}

function centra_e_mostra_div(div,width){
	
	BrowserDetect.init();
	
	switch ( BrowserDetect.browser ) {
		case "Netscape":
		case "Safari":
		case "Opera":
		case "Firefox":
				winW = window.innerWidth;
		  		winH = window.innerHeight;				
			break;
		case "Explorer":
			  	winW = document.body.offsetWidth;
			  	winH = document.body.offsetHeight;		
			break;
	}
	
	div = document.getElementById(div);
	div.style.left = (winW/2)-(width/2)+"px";
	div.style.visibility = 'visible';
}

function mostra_div(div){
	
	div = document.getElementById(div);
	div.style.visibility = 'visible';
	
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "browser desconhecido";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "versão desconhecida";
		this.OS = this.searchString(this.dataOS) || "OS desconhecido";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

function my_function(id) {
	if ( id == 18 ) {
		document.getElementById("texto_table").style.display ='block';
	} else {
		document.getElementById("texto_table").style.display ='none';	
	}
}

function attachNewFile() {
	var targetDiv = document.getElementById('files_to_attach') ;
	anotherInputFile = document.createElement("input");
	anotherInputFile.setAttribute("type","file");
	anotherInputFile.setAttribute("class","texto_normal");
	anotherInputFile.setAttribute("name","filesToAttach[]");
	
	anotherSpace = document.createTextNode(" ");
	
	anotherInputText = document.createElement("input");
	anotherInputText.setAttribute("type","text");
	anotherInputText.setAttribute("class","texto_normal");
	anotherInputText.setAttribute("name","filesToAttachDescrition[]");
	
	
	targetDiv.appendChild( anotherInputFile ) ;
	targetDiv.appendChild( anotherSpace ) ;
	targetDiv.appendChild( anotherInputText ) ;
}


function diseaseFileHide(var_g) {
	alert('lol');
}


function MultiSelectorCasos(list_target){
	this.list_target = list_target;
	this.count = 0;
	this.id = 0;
	this.addElement = function( element ){
		if( element.tagName == 'INPUT' && element.type == 'file' ){
			element.name = 'file[]';
			element.className= 'input_100';
			element.multi_selector = this;
			element.onchange = function(){
				var new_element = document.createElement( 'input' );
				new_element.type = 'file';
				this.parentNode.insertBefore( new_element, this );
				this.multi_selector.addElement( new_element );
				this.multi_selector.addListRow( this );
				this.style.position = 'absolute';
				this.style.left = '-1000px';
			};
			this.count++;
			this.current_element = element;
		} else {
			alert( 'Error: not a file input element' );
		};
	};
	
	this.addListRow = function(element){
		//cria tabela
		var new_row_table = document.createElement( 'table' );
		new_row_table.border=0;
		new_row_table.cellSpacing=0;
		new_row_table.cellPadding=0;
		new_row_table.align='left';
		
		 	//cria row para a imagem e o ficheiro
			var new_row_imagem = document.createElement( 'tr' );
			new_row_imagem.element = element;
			var s = element.value.split("\\");
			var z = s[s.length-1];	
			
				var new_col_imagem = document.createElement( 'td' );
				new_col_imagem.className = 'fundo_cinza';
				new_col_imagem.width = "5";
			new_row_imagem.appendChild(new_col_imagem);
				
				var new_col_imagem = document.createElement( 'td' );
				new_col_imagem.innerHTML = '<b> imagem:</b>';
				new_col_imagem.className = 'fundo_cinza';		
				new_col_imagem.height = "19";
				new_col_imagem.width = "145";
				new_col_imagem.align = 'left';
			new_row_imagem.appendChild(new_col_imagem);
				
				var new_col_imagem = document.createElement( 'td' );
				new_col_imagem.innerHTML = '&nbsp;';
				new_col_imagem.className = 'navegador_branco';
				new_col_imagem.width = "8";
			new_row_imagem.appendChild(new_col_imagem);
				
				var new_col_imagem = document.createElement( 'td' );
				new_col_imagem.innerHTML = '&nbsp;';
				new_col_imagem.className = 'fundo_cinza';
				new_col_imagem.width = "5";
			new_row_imagem.appendChild(new_col_imagem);
				
				var new_col_imagem = document.createElement( 'td' );
				new_col_imagem.innerHTML = z
				new_col_imagem.className = 'fundo_cinza';
				new_col_imagem.width = "407";
				
			new_row_imagem.appendChild(new_col_imagem);
			
		new_row_table.appendChild( new_row_imagem );
		
		//cria espaço entre rows
			var new_row_espaco = document.createElement( 'tr' );
				var new_col_espaco = document.createElement( 'td' );
				new_col_espaco.className = 'navegador_branco';
				new_col_espaco.height = "5";
				new_col_espaco.colspan = "5";
			new_row_espaco.appendChild(new_col_espaco);
		new_row_table.appendChild(new_row_espaco);
			
			//cria o row da legenda
			var new_row_legenda = document.createElement( 'tr' );
				var new_col_legenda = document.createElement( 'td' );
				new_col_legenda.innerHTML = '&nbsp;';
				new_col_legenda.className = 'fundo_cinza';
				new_col_legenda.width = "5";
				new_col_legenda.height = "19";
			new_row_legenda.appendChild(new_col_legenda);
			
				var new_col_legenda = document.createElement( 'td' );
				new_col_legenda.className = 'fundo_cinza';
				new_col_legenda.width = "145";
				new_col_legenda.innerHTML = '<b>legenda da imagem:</b><font color=\"#FF0000\">*</font>';
			new_row_legenda.appendChild(new_col_legenda);
			
				var new_col_legenda = document.createElement( 'td' );
				new_col_legenda.innerHTML = '&nbsp;';
				new_col_legenda.className = 'navegador_branco';
				new_col_legenda.width = "8";
			new_row_legenda.appendChild(new_col_legenda);
			
				var new_col_legenda = document.createElement( 'td' );
				new_col_legenda.innerHTML = '&nbsp;';
				new_col_legenda.className = 'fundo_cinza';
				new_col_legenda.width = "5";
			new_row_legenda.appendChild(new_col_legenda);
			
				var new_col_legenda = document.createElement( 'td' );
				new_col_legenda.className = 'fundo_cinza';
				new_col_legenda.width = "407";
			
				//cria caixa de texto e botao remover 
				var textBoxLegenda = document.createElement( 'input' );	
				var new_row_button = document.createElement( 'input' );
			
				new_row_button.type = 'button';
				new_row_button.value = 'remover';
				new_row_button.className = 'texto';
	
				textBoxLegenda.type = 'text';
				textBoxLegenda.name = 'legenda[]';
				textBoxLegenda.id = 'legenda[]';
				textBoxLegenda.className = 'textoinputlegendas';
				
				new_row_button.onclick= function(){
					this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.previousSibling.previousSibling);
					this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.previousSibling);
					this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
					//this.parentNode.parentNode.parentNode.element.multi_selector.count--;
					//this.parentNode.element.parentNode.element.multi_selector.current_element.disabled = false;
					return false;
				};	
				
				new_col_legenda.appendChild( textBoxLegenda );
				new_col_legenda.appendChild( new_row_button );
				
			new_row_legenda.appendChild(new_col_legenda);
		new_row_table.appendChild( new_row_legenda );

			var new_row_imagem = document.createElement( 'tr' );
				var new_col_imagem = document.createElement( 'td' );
				new_col_imagem.className = 'navegador_branco';
				new_col_imagem.height = "5";
				new_row_imagem.appendChild(new_col_imagem);
			new_row_table.appendChild(new_row_imagem);

		this.list_target.appendChild(new_row_table);
			
		
	};
}

function MultiSelectorCasosBackoffice(list_target){

	this.list_target = list_target;
	this.count = 0;
	this.id = 0;
	
	this.addElement = function( element ){
		if( element.tagName == 'INPUT' && element.type == 'file' ){
			element.name = 'file[]';
			element.className= 'input_100';
			element.multi_selector = this;
			element.onchange = function(){
				var new_element = document.createElement( 'input' );
				new_element.type = 'file';
				this.parentNode.insertBefore( new_element, this );
				this.multi_selector.addElement( new_element );
				this.multi_selector.addListRow( this );
				this.style.position = 'absolute';
				this.style.left = '-1000px';
			};
			this.count++;
			this.current_element = element;
		} else {
			alert( 'Error: not a file input element' );
		};
	};
	
	this.addListRow = function(element){
		//cria tabela
		var new_row_table = document.createElement( 'table' );
		new_row_table.border=0;
		new_row_table.width="100%";
		new_row_table.cellSpacing=0;
		new_row_table.cellPadding=0;
		new_row_table.align='left';
		
			var new_row_imagem = document.createElement( 'tr' );
				var new_col_imagem = document.createElement( 'td' );
				new_col_imagem.className = 'navegador_branco';
				new_col_imagem.height = "5";
				new_row_imagem.appendChild(new_col_imagem);
				
			new_row_table.appendChild(new_row_imagem);
		
		 	//cria row para a imagem e o ficheiro
			var new_row_imagem = document.createElement( 'tr' );
			new_row_imagem.element = element;
			var s = element.value.split("\\");
			var z = s[s.length-1];	
			
				var new_col_imagem = document.createElement( 'td' );
				new_col_imagem.className = 'fundo_cinza';
				new_col_imagem.width = "5";
			new_row_imagem.appendChild(new_col_imagem);
				
				var new_col_imagem = document.createElement( 'td' );
				new_col_imagem.innerHTML = '<b> imagem:</b>&nbsp;&nbsp;'+z;
				new_col_imagem.className = 'fundo_cinza';		
				new_col_imagem.height = "19";
				new_col_imagem.width = "100%";
				new_col_imagem.align = 'left';
			new_row_imagem.appendChild(new_col_imagem);
			
		new_row_table.appendChild( new_row_imagem );
		
			//cria o row da legenda
			var new_row_legenda = document.createElement( 'tr' );
				var new_col_legenda = document.createElement( 'td' );
				new_col_legenda.innerHTML = '&nbsp;';
				new_col_legenda.className = 'fundo_cinza';
				new_col_legenda.width = "5";
				new_col_legenda.height = "19";
			new_row_legenda.appendChild(new_col_legenda);
			
				var new_col_legenda = document.createElement( 'td' );
				new_col_legenda.className = 'fundo_cinza';
				new_col_legenda.width = "100%";
				new_col_legenda.innerHTML = '<b>legenda da imagem:</b>&nbsp;<font color=\"#FF0000\">*</font>&nbsp;&nbsp;';
						
			//cria caixa de texto e botao remover 
				var textBoxLegenda = document.createElement( 'input' );	
				var new_row_button = document.createElement( 'input' );
			
				new_row_button.type = 'button';
				new_row_button.value = 'remover';
				new_row_button.className = 'texto';
	
				textBoxLegenda.type = 'text';
				textBoxLegenda.name = 'legenda[]';
				textBoxLegenda.id = 'legenda[]';
				textBoxLegenda.width="100%";
				textBoxLegenda.className = 'textoinputlegendas';

				new_row_button.onclick= function(){
					
					this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.previousSibling.previousSibling);
					this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.previousSibling);
					this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
					
					//this.parentNode.parentNode.parentNode.element.multi_selector.count--;
					//this.parentNode.element.parentNode.element.multi_selector.current_element.disabled = false;
					return false;
				};	
				
				new_col_legenda.appendChild( textBoxLegenda );
				new_col_legenda.appendChild( new_row_button );
				
			new_row_legenda.appendChild(new_col_legenda);
		new_row_table.appendChild( new_row_legenda );

		this.list_target.appendChild(new_row_table);
			
		
	};
}

//Funções para os casos clínicos
function addField(area,field,limit,nRespExistentes) {
		
	if(!document.getElementById) 
		return;
		
	var field_area = document.getElementById(area);
	
	var all_inputs = field_area.getElementsByTagName("input");
	var last_item = all_inputs.length - 1;
	var last = all_inputs[last_item].id;
	var count = Number(last.split("_")[1]) + 1;

	if(count > limit && limit > 0) 
		return;
 	
	if(document.createElement) {
		
		field_area.innerHTML +="<tr><td colspan=\"4\" height=\"19\" class=\"fundo_cinza\"><table width=\"100%\" height=\"19\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"texto\"><tr><td width=\"10\" align=\"left\"><b>"+(String.fromCharCode(count+nRespExistentes-1+94))+")</b></td><td align=\"left\"><input type=\"text\" name="+field+count+" id="+field+count+" class=\"texto_normal\" onchange=\"contaRespostas(true)\"></td></tr></table></td></tr><tr><td height=\"5\" class=\"navegador_branco\" colspan=\"4\"></td></tr>";
	
	} else {
		alert('Nao podes apagar');
		field_area.innerHTML += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<li>&nbsp;&nbsp;&nbsp;<input name='"+(field+count)+"' id='"+(field+count)+"' type='text'  maxlength='255'/></li>";
	}
}

//funções para o banco de imagens
var ie=document.all
var ns6=document.getElementById&&!document.all

function ietruebody(){
	return (document.compatMode && document.compatMode!="BackCompat" && !window.opera)? document.documentElement : document.body
}

function closepreview(){
	crossobj.style.visibility="hidden"
}


function enlarge(which, e, position,topo, esquerda, imgwidth, imgheight, legenda, cor){

	if (ie||ns6){
		crossobj=document.getElementById? document.getElementById("showimage") : document.all.showimage
		if (position=="spot"){
			pgyoffset=ns6? parseInt(pageYOffset) : parseInt(ietruebody().scrollTop)
			horzpos=ns6? pageXOffset+743: ietruebody().scrollLeft+737
			vertpos=ns6? pgyoffset+156 : pgyoffset+156
			if (window.opera && window.innerHeight) //compensate for Opera toolbar
				vertpos=pgyoffset+155
			vertpos=Math.max(pgyoffset, vertpos)
		}
		else{
			var horzpos=ns6? pageXOffset+e.clientX : ietruebody().scrollLeft+event.clientX
			var vertpos=ns6? pageYOffset+e.clientY : ietruebody().scrollTop+event.clientY
		}
		if(((document.body.offsetWidth-956)/2)<0){
			margemH=0
		}else{
			margemH=((document.body.offsetWidth-956)/2)
		}
		crossobj.style.left=margemH+esquerda+"px"
		crossobj.style.top=topo+"px"

		if(legenda){
			legendaHTML='<div align="left" id="dragbar" class="barra_'+cor+'" style="width:'+imgwidth/2+'; height:15"><div id="legenda" class="legenda_'+cor+'" style="width:'+imgwidth/2+'; height:15">&nbsp;'+legenda+'</div></div>'
		}else{
			legendaHTML='';
		}
		crossobj.innerHTML='<div align="right" id="dragbar_close" style="width:0px;height:14px"><span id="closetext" onClick="closepreview()" class="close_'+cor+'" style="width:0px;height:19px;">&nbsp;Fechar</span></div><img src="'+which+'" width="'+imgwidth+'" height="'+imgheight+'">'+legendaHTML
		crossobj.style.visibility="visible"
		return false;		
	}
	else //if NOT IE 4+ or NS 6+, simply display image in full browser window
		return true
}

function submitPoll(resp,perg,caso){
	url = "/caso_problema/_sabichao.php";
	new Ajax.Request(url, {
		method: 'get', parameters: 'resposta='+resp+'&pergunta='+perg+'&caso='+caso,
		onSuccess: function(value){
			if (value.responseText == "N") {
				// lets find the position
				$('id_erro').style.display='';				
				$('id_erro').style.visibility='visible';
				$('id_erro').setStyle("top:"+(document.documentElement.scrollTop+100)+"px;");				
				new Effect.Fade('id_erro',{duration:0.5,from:0,to:0.90});				
			}
			else {
				$('responder').submit();
			}
		}
	});
}


function showComment(){
	$('id_comment').style.display='';				
	$('id_comment').style.visibility='visible';
	$('id_comment').setStyle("top:"+(document.documentElement.scrollTop+100)+"px;");				
	new Effect.Fade('id_comment',{duration:0.5,from:0,to:0.95});
}

function resetCommentBoxStyles(){
	new Effect.Morph('id_comment', {
		style: {
			height:'229px'
		}
	});	
	$('name_name').setStyle("border:1px solid black");
	$('comment').setStyle("border:1px solid black");
	$('comment_controlbar').setStyle("height:0px;");
	$('comment_controlbar').innerHTML = '';
}

function submitComment(){
	// lets validate data first //
	// putting the fields border to normal //
	$('name_name').setStyle("border:1px solid black");
	$('comment').setStyle("border:1px solid black");	
	
	erro = '';
	erro_header = 'Foram encontrados os seguintes erros:<ul>';
	if ($F('name_name') == '') {
		$('name_name').setStyle("border:1px solid red");
		if ( erro == '' ) erro = erro_header ;
		erro += "<li>O nome tem que estar preenchido";
	}
	if ($F('comment') == '') {
		$('comment').setStyle("border:1px solid red");
		if ( erro == '' ) erro = erro_header ;
		erro += "<li>O comentário tem que estar preenchido";
	}
	if ( erro != "" ) {
		if ($('id_comment').style.height == '285px') {
			$('comment_controlbar').innerHTML = erro;
			new Effect.Highlight('comment_controlbar', {});		
		}
		else {
			new Effect.Morph('id_comment', {
				style: {
					height: '285px'
				},
				duration: 0.5,
				afterFinish: function(){
					$('comment_controlbar').setStyle("height:50px");
					$('comment_controlbar').innerHTML = erro;
					new Effect.Highlight('comment_controlbar', {});
				}
			});
		}		
		return false ;
	}
	
	url = "/caso_problema/_recebe_comment.php";
	new Ajax.Request(url, {
		method: 'post',
		parameters: 'idPergunta='+$F('id_pergunta')+'&comment='+$F('comment')+'&idCaso='+$F('id_caso')+'&name='+$F('name_name'),
		onComplete: function(){
			if ($('id_comment').style.height != "285px") {
				new Effect.Morph('id_comment', {
					style: {
						height: '285px'
					},
					duration: 0.5,
					afterFinish: function(){
						$('comment_controlbar').setStyle("height:50px");
						$('comment_controlbar').innerHTML = "O seu comentário foi registado com sucesso.<br>Fica pendente até aprovação do administrador.";
						new Effect.Highlight('comment_controlbar', {});
						window.setTimeout('hideControlBar()', 3000 );
					}
				});
			} else {
				$('comment_controlbar').setStyle("height:50px");
				$('comment_controlbar').innerHTML = "O seu comentário foi registado com sucesso.<br>Fica pendente até aprovação do administrador.";
				new Effect.Highlight('comment_controlbar', {});
				window.setTimeout('hideControlBar()', 3000 );
			}
		}
	});
}

function hideControlBar(){
	new Effect.Fade('id_comment',{duration:1,from:0.95,to:0.0});
	if($F('is_logged_in')=='0'){$('name_name').value='';}
	$('comment').value='';
	resetCommentBoxStyles();
}
