extensions.push('print');




//addExtensionHTML(printhtml);

function printBegin() {
	commands['printMap']='printMap';
	commands['printOpen']='printOpen';
	commands['printClose']='printClose';
	otherMapGui.push('printDiv');
	mapInfo.setProperty('currentSheet','A4');
	mapInfo.setProperty('currentOrientation','');
	
	eventListeners.attachToEvent('print','printWindowOpen');

	var popup=new Popup('stampa',document.getElementById('printDiv'),null,document.getElementById('legendChooseContainer'),document.getElementById('printTitle'));
	popups.addPopup(popup);

	
}

function printWindowOpen() {
	doCommand('queryParamsOpen','Print');
}

function setSheetOrientation(newOrientation) {
	mapInfo.setProperty('currentOrientation',newOrientation);
	updateSheet();
}

function changeSheetFormat() {
	var newSheet=document.getElementById('sheetFormat').options[document.getElementById('sheetFormat').selectedIndex].value;
	mapInfo.setProperty('currentSheet',newSheet);
	updateSheet();
}

function updateSheet() {
	updateFormat();
	var newSheet=mapInfo.getProperty('currentSheet')+mapInfo.getProperty('currentOrientation');
	var analysisList=mapInfo.getProperty('analysisList');
	var analysisCount=0;
	for(var name in analysisList) {
		document.getElementById('legendChoose'+name+'Check').checked=false;
		analysisCount++;
	}
	if(analysisCount>0) {
		
		mapInfo.setProperty('legendPositions',getLegendPositionsArray(newSheet));
		mapInfo.setProperty('legendSelected',null);
		updateLegendChoose();
		
	}
	
}

function printClose() {
	document.getElementById('printDiv').style.visibility='hidden';
	document.getElementById('legendChooseContainer').style.visibility='hidden';
	actionEnd();
}

function getLegendPositionHTML(sheet) {
	
	var html='<table cellspacing="0" cellpadding="0">';
	
	if(sheet=='A4' || sheet=='A4R') {
		var count=0;
		for(var row=0;row<2;row++) {
			html+='<tr>';
			for(var col=0;col<2;col++) {
				html+='<td id="legendPositionBox'+count+'" style="border: black solid 1px;background-color:white"><img src="images/spacer.gif"/ width="30" height="30"></td>';
				count++;
			}
			html+='</tr>';
		}
	}
	html+='</table>';
	return html;
}

function getFreeBox(name) {
	var positionsArr=mapInfo.getProperty('legendPositions');
	var pos=-1;
	for(var count=0;count<positionsArr.length && pos==-1;count++) {
		if(positionsArr[count]==null) {
			pos=count;
			positionsArr[count]=name;
		}
	}
	mapInfo.setProperty('legendPositions',positionsArr);
	return pos;
}

function getBoxPosition(name) {
	var positionsArr=mapInfo.getProperty('legendPositions');
	var pos=-1;
	for(var count=0;count<positionsArr.length && pos==-1;count++) {
		if(positionsArr[count]==name)
			pos=count;
	}
	return pos;
}

function selectLegend(name) {
	if(document.getElementById('legendChoose'+name+'Check').checked) {
		mapInfo.setProperty('legendSelected',name);
		updateLegendChoose();
	} else
		legendChooseOn(name);
}

function selectBox(pos) {
	releaseBox(mapInfo.getProperty('legendSelected'));
	var positionsArr=mapInfo.getProperty('legendPositions');
	positionsArr[pos]=mapInfo.getProperty('legendSelected');
	mapInfo.setProperty('legendPositions',positionsArr);
	updateLegendChoose();
}

function updateLegendChoose() {
	var analysisList=mapInfo.getProperty('analysisList');
	var selName=mapInfo.getProperty('legendSelected');
	for(var name in analysisList) {
		var label=document.getElementById('legendChoose'+name);
		var checked=document.getElementById('legendChoose'+name+'Check').checked;
		if(name==selName) {
			label.style.backgroundColor='#929191';
			label.style.color='white';
			label.style.cursor='default';
			label.onclick=null;
		} else {
			label.style.backgroundColor='';
			label.style.color='black';
			//if(checked) {
				label.style.cursor='hand';
				label.onclick=new Function('selectLegend(\''+name+'\')');
			/*} else {
				label.style.cursor='default';
				label.onclick=null;
			}*/
		}
		
	}
	var positionsArr=mapInfo.getProperty('legendPositions');
	for(var pos in positionsArr) {
		var name=positionsArr[pos];
		var box=document.getElementById('legendPositionBox'+pos);
		if(name==null) {
			box.style.borderColor='black';
			box.style.backgroundColor='white';
			if(selName!=null) {
				box.style.cursor='hand';
				box.onclick=new Function('selectBox(\''+pos+'\')');
			} else {
				box.style.cursor='default';
				box.onclick=null;
			}
		} else if(name==selName) {
			box.style.borderColor='yellow';
			box.style.backgroundColor='white';
			box.style.cursor='default';
			box.onclick=null;
		} else {
			box.style.borderColor='#929191';
			box.style.backgroundColor='';
			box.style.cursor='default';
			box.onclick=null;
		}
	}
}

function legendChooseOn(name) {
	var pos=getFreeBox(name);
	if(pos==-1) {
		document.getElementById('legendChoose'+name+'Check').checked=false;
		alert('Tutte le posizioni per le legende sono già occupate');
	}
	else {
		if(!document.getElementById('legendChoose'+name+'Check').checked)
			document.getElementById('legendChoose'+name+'Check').checked=true;
		mapInfo.setProperty('legendSelected',name);
		updateLegendChoose();
	}

}

function releaseBox(name) {
	var positionsArr=mapInfo.getProperty('legendPositions');
	
	for(var count=0;count<positionsArr.length;count++) {
		if(positionsArr[count]==name)
			positionsArr[count]=null;
		
	}
	mapInfo.setProperty('legendPositions',positionsArr);
}

function legendChooseOff(name) {
	releaseBox(name);
	if(mapInfo.getProperty('legendSelected')==name)
		mapInfo.setProperty('legendSelected',null);
	updateLegendChoose();
}

function legendChooseClick(name) {
	if(document.getElementById('legendChoose'+name+'Check').checked)
		legendChooseOn(name);
	else
		legendChooseOff(name);
}

function getLegendPositionsArray(sheet) {
	if(sheet=='A4' || sheet=='A4R')
		return new Array(null,null,null,null);
}

function updateFormat() {
	var orientation=mapInfo.getProperty('currentOrientation');
	if(orientation=='') {
		document.getElementById('orientationPortrait').style.border='red solid 2px';
		document.getElementById('orientationLandscape').style.border='';
	} else {
		document.getElementById('orientationPortrait').style.border='';
		document.getElementById('orientationLandscape').style.border='red solid 2px';
	}
}

function printOpen() {
	
	mapInfo.setProperty('legendPositions',getLegendPositionsArray(mapInfo.getProperty('currentSheet')+mapInfo.getProperty('currentOrientation')));
	document.getElementById('printDiv').style.visibility='visible';
	
	var analysisList=mapInfo.getProperty('analysisList');
	var html='<table><tr><td valign="top" colspan="2"><span class="label">Legende: </span></td></tr>';
	var anaCount=0;
	for(var name in analysisList) {
		anaCount++;
		var analysis=analysisList[name];
		if(analysis.opacity>0)
			html += '<tr><td width="10"><input type="checkbox" id="legendChoose'+name+'Check" onClick="legendChooseClick(\''+name+'\')"/></td><td width="150" style="cursor:hand" onClick="selectLegend(\''+name+'\')" id="legendChoose'+name+'">'+analysis.description+'</td></tr>';
	}
	html+='</table>';
	if(anaCount>0) {
		
		document.getElementById('legendChoose').innerHTML=html;
	
		
		document.getElementById('legendChoosePosition').innerHTML=getLegendPositionHTML(mapInfo.getProperty('currentSheet')+mapInfo.getProperty('currentOrientation'));
		
		InitialiseScroll('legendChooseContainer','legendChooseContent','scrollbarLegendChoose',95);
		document.getElementById('legendChooseContainer').style.visibility='visible';		
	} else {
		document.getElementById('legendChoose').innerHTML='';
		document.getElementById('legendChoosePosition').innerHTML='';
	}
	updateFormat();
	actionEnd();
}



function printMap()
{
	document.getElementById('printDiv').style.visibility='hidden';
	automa=new Automa('PrintMap',3,'automa','actionEnd()');
	automa.interval=500;
	var titolo=document.getElementById('printTitle').value;
	if(!titolo)
		titolo='NO-TITLE';
	automa.setProperty('title',titolo);
	automa.setProperty('texts',document.getElementById('testiCheck').checked);
	if(document.getElementById('qualityLow').checked)
		automa.setProperty('quality','low');
	else
		automa.setProperty('quality','high');
		
	
	
	automa.start();
	
}

function automaPrintMapPhase1() {
	var extraParams='';
	var analysisList=mapInfo.getProperty('analysisList');
	for(var analysisName in analysisList) {
		var analysis=analysisList[analysisName];
		var legend=false;
		var legendPosition=getBoxPosition(analysisName);
		if(document.getElementById('legendChoose'+analysisName+'Check').checked)
			legend=true;

		if(analysis.opacity>0)
			extraParams+=';'+analysis.analysisName+','+analysis.layer+','+analysis.opacity+','+legend+','+legendPosition+','+analysis.params;
		
		
		
	
	}
	if(extraParams.length>0)
		extraParams=extraParams.substring(1);
	//alert(extraParams);
		
	engine.sendMsg("printMap",null,'returnPrintMap',map.mapName,mapInfo.getProperty('currentConfiguration'),automa.getProperty('quality'),map.realRange.minX,map.realRange.maxX,map.realRange.minY,map.realRange.maxY,automa.getProperty('title'),automa.getProperty('texts'),mapInfo.getProperty('currentSheet')+mapInfo.getProperty('currentOrientation'),extraParams);
	//}
	//actionEnd();
}

function returnPrintMap(retrow) {
	//automa.end();
	automa.goOn();	
}

function automaPrintMapPhase2() {
	engine.sendMsg("waitPrintMap",null,'returnWaitPrintMap');
}

function returnWaitPrintMap(retrow) {
	//alert(retrow);
	if(retrow=='OK')
		automa.goOn();
	else
		automa.repeatPhase()
}

function automaPrintMapPhase3() {
	automa.end();
}

//--------------- PDF PRINT -----------------------------------------------------------------------------------------

function genericMapPdf() {
//	deselectCurrentFunction();
//	var queryDesc=mapInfo.getProperty('queries')[mapInfo.getProperty('queryName')];

//	var title=queryDesc.getInput('titleInput');
//	var scale=queryDesc.getInput('scaleInput');
	var title=document.getElementById('titoloInput').value;
	var scale=document.getElementById('scalaInput').value;
	var scaleInt=parseInt(scale);

	var minx=map.realRange.minX;
	var miny=map.realRange.minY;
	var maxx=map.realRange.maxX;
	var maxy=map.realRange.maxY;
	var currScale;
	if (scaleInt>0)
	{
		
		var xcenter = (minx+maxx)/2;
		var ycenter = (miny+maxy)/2;
		var rangex=scaleInt*2.54*mapWidth/7200;
		var rangey=scaleInt*2.54*mapHeight/7200;
		
		minx=xcenter-rangex/2;
		maxx=xcenter+rangex/2;
		miny=ycenter-rangey/2;
		maxy=ycenter+rangey/2;
		var newRange=new Range(minx,maxx,miny,maxy);
		currScale=newRange.getScale(map.maxRealRange);
	} else {
		currScale=map.getScale();
		var rangex = maxx-minx;
		scaleInt=rangex/(2.54*mapWidth/7200);
		scaleInt=Math.ceil(scaleInt);
		scale=String(scaleInt);
	}

//	var title=mapInfo.getProperty('pdfTitle');
//	var scale=mapInfo.getProperty('pdfScale');

	document.getElementById('queryParamsDiv').style.visibility='hidden';

	var pdfWin=window.open('report.html','print','WIDTH=660,HEIGHT=620,RESIZABLE=YES,SCROLLBARS=YES,STATUS=YES');
	pdfWin.focus();
	mapInfo.setProperty('pdfWindow',pdfWin);
	
	var layers='';
	var priority;

	var printDenied=mapInfo.getProperty('printDenied');

	for(var layerName in map.layers) {
		
		var layer=map.getLayer(layerName);
		if(layer.visible && layer.visibleInScale(currScale)) {
			priority=layer.priority;
			if(layer.features && layer.features.length>0) {
				for(var pos in layer.features) {
					var feature=layer.features[pos];
					if(!printDenied || !arrayContains(printDenied,layer.name+'.'+feature)) {
						var renderingManager=layer.renderingManagers[feature];
						if(renderingManager.getProperty('visibility') && layer.visibleInScale(currScale,feature))
							//layers+=','+priority+';'+feature.replace(/\*/g,',');
							
							layers+=','+priority+';'+feature;
					}
				}
			} else {
				if(!printDenied || !arrayContains(printDenied,layer.name))
					//layers+=','+priority+';'+layer.name.replace(/\*/g,',');
					if(layer.name.indexOf('analysis')!==0)
						layers+=','+priority+';'+layer.name;
			}
		}
	}
	
	
	if(layers.length>0) {
		layers=layers.substring(1);
		
	
		var lyrs=layers.split(',');
		var tmp='';
		var i,j;
		
		for(i=0;i<lyrs.length-1;i++)
			for(j=i+1;j<lyrs.length;j++)
			{
				var xa=lyrs[i].split(';');
				var xb=lyrs[j].split(';');
				if (Number(xa[0])>Number(xb[0]))
				{
					tmp=lyrs[i];
					lyrs[i]=lyrs[j];
					lyrs[j]=tmp;
				}
			}
		
		layers='';
		for(i=0;i<lyrs.length;i++)
		{
			var x=lyrs[i].split(';');
			layers+=','+x[1].replace(/\*/g,',');
		}
		
		layers=layers.replace(',TooltipLayer','');
		if(layers.length>0)
			layers=layers.substring(1);

		var args='\''+layers+'\',\''+minx+','+miny+','+maxx+','+maxy+'\',\'550,430\',\''+title+'\',\'1:'+scale+'\'';
		
		eval('engine.sendMsg(\'printPdf\',this,\'returngenericMapPdf\','+args+')');
	} else
		pdfWin.close();
	actionEnd();
}

function returngenericMapPdf(retrow) {
	
	actionEnd();
}

function PDFEngine_clearCommunication() {
	pdfcommunication.document.write('<html><head></head><body><form id="pdfform" name="pdfform" method="POST" action="http://mauro/qweb/proxy/PDFPrint.aspx"><input type="hidden" name="meth" value="SOAP"/><input type="hidden" name="data" value=""/><input type="hidden" name="layer" value=""/><input type="hidden" name="titolo" value=""/><input type="hidden" name="scala" value=""/></form></body></html>');
}
/*
 * Invia una richiesta al motore java. Il metodo è asincrono. Ciò significa che
 * non viene attesa la risposta. Tale risposta verrà inviata alla funzione <responseHandler>,
 * oppure al metodo <responseHandler> di <responseHandlerObject>.
 * Il tipo di richiesta viene indicata dal parametro <msgAction>. Ogni tipo di richiesta 
 * può prevedere una serie di parametri aggiuntivi.
 */

function PDFEngine_handleMsg(msgAction,otherArgs) {
	var layerNames=otherArgs[0];
	var range=otherArgs[1];
	var size=otherArgs[2];
	var titolo=otherArgs[3];
	var scala=otherArgs[4];

	var ranges=range.split(',');
	var minX=parseFloat(ranges[0]);
	var minY=parseFloat(ranges[1]);
	var maxX=parseFloat(ranges[2]);
	var maxY=parseFloat(ranges[3]);
	
	var sizes=size.split(',');
	var mapWidth=parseInt(sizes[0]);
	var mapHeight=parseInt(sizes[1]);

	var pdfWin=mapInfo.getProperty('pdfWindow');
	pdfWin.document.write('<html><head></head><body><form id="pdfform" name="pdfform" method="POST" action="'+this.url+'"><input type="hidden" name="meth" value="SOAP"/><input type="hidden" name="data" value=""/><input type="hidden" name="layer" value=""/><input type="hidden" name="titolo" value=""/><input type="hidden" name="scala" value=""/><input type="hidden" name="application" value=""/></form></body></html>');
	
	var wmsquery='<BoundingBox dimensions="2"><LowerCorner>'+minX+' '+minY+'</LowerCorner><UpperCorner>'+maxX+' '+maxY+'</UpperCorner></BoundingBox><Output><Format>image/png</Format><Transparent>false</Transparent><Size><Width>'+(mapWidth*10)+'</Width><Height>'+(mapHeight*10)+'</Height></Size></Output><Exceptions>XML</Exceptions></GetMap>';

	var url=this.url;		
		
	var encodedRequest=wmsquery;
	var ogcform=pdfWin.document.getElementById('pdfform');
	ogcform.layer.value=layerNames;
	ogcform.data.value=encodedRequest;
	ogcform.titolo.value=titolo;
	ogcform.scala.value=scala;
	ogcform.application.value=mapInfo.getProperty('applicationName');
	ogcform.submit();
	
	return null;
}

/**
 * Costruttore. Viene passato come parametro la <DIV> usata per la comunicazione con il motore.
 */
function PDFEngine(url) {
	this.url=url;
	this.clearCommunication();
}


PDFEngine.prototype.handleMsg=PDFEngine_handleMsg;
PDFEngine.prototype.clearCommunication=PDFEngine_clearCommunication;

