var wndp, conteudo, html2print;
var aOp = new Array();
		
//MODELO NOVO ==================================================================================================================================================
function fImprime_v2(id) {
  var mlkGPTB, opID, temp, i;
	
	document.getElementById('FolhaPrint').contentWindow.location.href = 'about:blank';
	//if (wndp) wndp.close();
	//wndp = window.open("about:blank", 'wndImp', 'width=640, height=480, resizable=no, scrollbars=no; menubar=no');
	//wndp.document.body.style.backgroundColor = '#c0c0c0';
	//wndp.document.body.style.fontFamily = 'arial';
	//wndp.document.body.style.fontSize = '10pt';
	//wndp.document.body.innerHTML = "A preparar a impressão, aguarde um momento, por favor...";
	//wndp.focus();
  if (document.getElementById(id)) {
    conteudo = document.getElementById(id).innerHTML;
  } else {
    conteudo = document.body.innerHTML;
  }
  //Passo 1. 
  //Identifica e substitui a TAG iframe dos blocos operação por uma TAG div
  temp = conteudo.split("<!--MLKMPOPS");
  conteudo = temp[0]
  for (i = 1; i < temp.length; i++) {
		opID = temp[i].split("-->")[0]
		conteudo += "<div id='mpOp" + opID + "'>" + opID + "</div>" + temp[i].split('<!--MLKMPOPE' + opID + '-->')[1];
		aOp[aOp.length] = new Object();
		aOp[aOp.length - 1].id = 'mpOp' + opID;
		aOp[aOp.length - 1].html = '';
		aOp[aOp.length - 1].impressaoTipo = 0;
		aOp[aOp.length - 1].completo = false;
  }
  //Passo 2. 
  //Percorre o array aOp e vai buscar o HTML dos campos OPERACAO e coloca em aOp[x].html
  //Como o carregamento do HTML dos campos operação é assincrono, inicia aqui o trabalho 
  //e que é terminado em fImprimeNotifica_v2()
	if (aOp.length == 0) {
		fImprimeVerificaCompleto_v2();
	} else {
		for (i = 0; i < aOp.length; i++) {
			mlkGPTB = document.getElementById(aOp[i].id).contentWindow.mlkGPTB;
			aOp[i].impressaoTipo = mlkGPTB.impressaoTipo;
			mlkGPTB.impressaoTipo = 1;
			mlkGPTB.DoAccaoImprimir(fImprimeNotifica_v2, i);
		}
	}
}  

function fImprimeNotifica_v2(hwdHTML, szID) {
	//Esta função é invocada pelos blocos OPERACAO (proc_operacao.aspx) quando o 
	//HTML para impressão do bloco está pronto para o efeito
	var i = parseInt(szID, 10);
	aOp[i].html = hwdHTML.document.body.innerHTML;
	aOp[i].completo = true;
	document.getElementById(aOp[i].id).contentWindow.mlkGPTB.impressaoTipo = aOp[i].impressaoTipo;
	//O bloco OPERACAO cujo id é szID está concluido. Chama a função fImprimeVerificaCompleto_v2()
	//que vai verificar se todos os blocos OPERACAO também já estão concluidos
	fImprimeVerificaCompleto_v2();
}
  
function fImprimeVerificaCompleto_v2() {
  //Passo 3. 
  //Caso todos os blocos OPERACAO tenham concluido e notificado via fImprimeNotifica_v2
  //que concluiram o seu processo, então invoca o mlkImprimir.aspx que há-de vir a esta 
  //página buscar o html completo para impressão
  var i, completo = true;
  for (i = 0; i < aOp.length; i++) {
		if (aOp[i].completo == false) {
			completo = false;
			break;
		}
	}
	if (completo == true) {
		html2print = fImprimeCSS(fImprimeRetiraScripts(fImprimeIFRAME2DIV_v2(conteudo)));
		document.getElementById('FolhaPrint').contentWindow.location.href = mlkSessURL + '/wwwbase/raiz/mlkImprimir_v2.aspx?codigoms=' + mlkReqCodigoMS;
		//wndp.location.href = mlkSessURL + '/wwwbase/raiz/mlkImprimir.aspx?codigoms=' + mlkReqCodigoMS
		//wndp.focus();
	}
}

function fImprimeIFRAME2DIV_v2(sz) {
	//Se for uma página Externa/Redireccionada o elemento mlkFrame é uma IFRAME com uma aplicação 
	//lá dentro, logo substitui o IFRAME por um DIV com o respctivo conteúdo dessa aplicação.
	if (document.getElementById('mlkFrame') && document.getElementById('mlkFrame').tagName.toUpperCase() == 'IFRAME') {
		try {
			var iframeHTML = document.getElementById('mlkFrame').contentWindow.document.body.innerHTML;
			if (sz.indexOf('id="mlkFrame') != -1)
				var aTemp = sz.split('id="mlkFrame');
			else
				var aTemp = sz.split('id=mlkFrame');
			aTemp[0] = aTemp[0].substr(0, aTemp[0].lastIndexOf('<'));
			aTemp[0] += '<div style="width:100%; overflow:visible;">';
			aTemp[1] = aTemp[1].substr(aTemp[1].replace(/<\/iframe>/gi, '</IFRAME>').indexOf('</IFRAME>') + 9);
			aTemp[1] = iframeHTML + '</div>' + aTemp[1];
			return aTemp.join('');
		} catch (e) {
			return sz;
		}
	} else {
		return sz;
	}
}

//FUNCOES COMUNS AO MODELO ANTIGO E NOVO ================================================================================================================================
function fImprimeCSS(html) {
	//Desactiva os CSS
  return html.replace(/\.css/gi, '.nouse');
}

function fImprimeRetiraScripts(html) {
	//Retira todos os scripts da página
	var i, aTemp = html.replace(/<script/gi, '<SCRIPT').split('<SCRIPT');
	for (i = 1; i < aTemp.length; i++) {
		aTemp[i] = aTemp[i].replace(/<\/script>/gi, '</SCRIPT>').split('</SCRIPT>')[1];
	}
	return aTemp.join('');
}

//MODELO ANTIGO ==========================================================================================================================================================
function fImprime() {
  var conteudo;
  if (document.getElementById('ctAreaConteudo')) {
    conteudo = document.getElementById('ctAreaConteudo').innerHTML;
  } else {
    conteudo = document.body.innerHTML;
  }
	html2print = fImprimeCSS(fImprimeRetiraScripts(fImprimeIFRAME2DIV(conteudo)));
	if (wndp) wndp.close();
	wndp = window.open(mlkSessURL + '/wwwbase/raiz/mlkImprimir.aspx?codigoms=' + mlkReqCodigoMS, 'wndImp', 'width=600, height=480, resizable=yes, scrollbars=no; menubar=no');
	wndp.focus();
}

function fImprimeIFRAME2DIV(sz) {
	if (document.getElementById('mlkFrame') && document.getElementById('mlkFrame').tagName.toUpperCase() == 'IFRAME') {
		try {
			var iframeHTML = document.getElementById('mlkFrame').contentWindow.document.body.innerHTML;
			if (sz.indexOf('id="mlkFrame') != -1)
				var aTemp = sz.split('id="mlkFrame');
			else
				var aTemp = sz.split('id=mlkFrame');
			aTemp[0] = aTemp[0].substr(0, aTemp[0].lastIndexOf('<'));
			aTemp[0] += '<div style="width:100%; overflow:visible;">';
			aTemp[1] = aTemp[1].substr(aTemp[1].replace(/<\/iframe>/gi, '</IFRAME>').indexOf('</IFRAME>') + 9);
			aTemp[1] = iframeHTML + '</div>' + aTemp[1];
			return aTemp.join('');
		} catch (e) {
			return sz;
		}
	} else {
		return fImprimeIFRAMEGP(sz);
	}
}

function fImprimeIFRAMEGP(html) {
  //Verificar se há IFRAMES do GP (blocos Operação, Formulário ou Formulário pesquisa)
  var i, htmlOP;
  var rgBlocoGP = /^mpOp\d+$/, rgIF;
  var cll = document.getElementsByTagName('IFRAME');
  var lstIF = new Array();
  for (i = 0; i < cll.length; i++) {
    if (rgBlocoGP.test(cll[i].id) == true) {
      lstIF[lstIF.length] = cll[i].id;
    }
  }
  for (i = 0; i < lstIF.length; i++) {
    var aux = "<iframe id=['\"]?" + lstIF[i] + "['\"]?.+name=['\"]?" + lstIF[i] + "['\"]?[^>]+><\/iframe>";
    rgIF = new RegExp(aux, "i");
    //Obter HTML da operação
    var mlkGPTB = document.getElementById(lstIF[i]).contentWindow.mlkGPTB;
    htmlOP = fObtemHTMLOperacao(mlkGPTB);
    html = html.replace(rgIF, htmlOP);
  }
  return html;
}

function fObtemHTMLOperacao(mlkGPTB) {
  htmlOP = 'Em desenvolvimento.';
  if (mlkGPTB.modoActivo == 1) {
    //Listagem
    var rgAlvo = /alvo.((fMlkGPLRSelecciona)|(fMlkGPLRDuploClique)|(fMlkGPLRIlumina))\(\d+\)/gi;
    htmlOP = 
      "<table border=0 cellspacing=0 cellpadding=0>" +
      "<tr><td>" + mlkGPTB.document.getElementById('Toolbar').innerHTML + "</td></tr>" +
      "<tr><td>" + mlkGPTB.document.getElementById('Listagem').contentWindow.document.getElementById('dvLst').innerHTML.replace(rgAlvo, '') + "</td></tr>" +
      "<tr><td>" + mlkGPTB.document.getElementById('Listagem').contentWindow.document.getElementById('tdNavegacao').innerHTML + "</td></tr>" +
      "</table>";
  } else {
    //Registo
    var rowIndex = 0;
    try { rowIndex = mlkGPTB.document.getElementById('aac').offsetParent.parentNode.rowIndex; } catch(e) {}
    if (rowIndex == 0) {
      htmlOP = 
        "<table border=0 cellspacing=0 cellpadding=0>" +
        "<tr><td>" + mlkGPTB.document.getElementById('Toolbar').innerHTML + "</td></tr>" +
        "<tr><td>" + mlkGPTB.document.getElementById('Registo').contentWindow.document.body.innerHTML + "</td></tr>" +
        "</table>";
    } else {
      htmlOP = 
        "<table border=0 cellspacing=0 cellpadding=0>" +
        "<tr><td>" + mlkGPTB.document.getElementById('Registo').contentWindow.document.body.innerHTML + "</td></tr>" +
        "<tr><td>" + mlkGPTB.document.getElementById('Toolbar').innerHTML + "</td></tr>" +
        "</table>";
    }
  }
  return htmlOP;
}