/**************************************************************************
Copyright : 2008 - GEOSIGNAL - www.geosignal.fr - contact@geosignal.fr
Projet : Communauté de commune Pic saint loup
***************************************************************************
Date  : 16/03/2009 par Dina
Objet : Fonctions javascript de l'interface de paramètrage de l'impression 
       
************************************************************************        
**Modifications le jj/mm/aaa par xxxxxx
Objet :

**********************************************************************************/

var Impression = {
	winPop : false , 
	comboEchellePrint : null ,
	store : null ,
	openWin : function(){
		if(Impression.winPop != false)Impression.winPop.close();	
		var visu = Ext.get(CMap.map.div) ;
  		var leftWin = visu.getLeft()+visu.getWidth()-345 ;
  	
	  Impression.winPop = new Ext.Window({
	    title: 'Impression',
	    width: 335,
	    html : "Chargement...",
	    height: 330,
	    collapsible: true,
	    plain: true,
	    resizable : false,
	    autoScroll: false,
	    id: 'id_couche_gestion',
	    x : leftWin,
	    y : visu.getTop()+10,
	    close: function() {
	    	if(typeof(Visualiser) == 'object'){
	    		Visualiser.effacer();	
	    	}
	    	this.destroy();
	    }
	  });
	  Impression.winPop.show(this);
		Ext.Ajax.request({
		   url: 'fonctionnalites/print/fiche.print.php',
		   success: function(response){
		   	Impression.winPop.body.update(response.responseText);
		   	Impression.writeButton() ;
		   	Impression.initScale() ;
		   },
		   failure: Impression.errorCallBack,
		   params: { 
		   		act: 'loadform'
		   }
		});
	},
	writeButton : function(){
		var btn2 = new Ext.Button({
			text: 'Imprimer',
			id: 'id_impression_launch',
			renderTo: 'pslprintbtn',
			handler: function(){
				Impression.launchprint(false) ;
			}
		});
	},
	errorCallBack : function(response){
    Ext.MessageBox.show({
       title: 'Erreur sur modifaction',
       msg: response.responseText,
       buttons: Ext.MessageBox.OK,
       icon: 'ext-mb-error'
   });
	},
	launchprint : function(param){
		if(!param){
			this.saveDessinVectorInMap() ;
			return true ;
		}
		var params = this.loadParamsToPrint() ;
		$('imp_id_attente').style.display = 'block' ;
  	new Ajax('print/printmap.php',{
			evalScripts: true,
			postBody: params,
			onComplete: function(originalResponse){
		  	try{
					eval('var res = ' + originalResponse );
					switch(res.format){
						case 'html':	
							window.open("../tmp/"+res.file) ;
						break ;
						case 'word':	
							$('impr_redirect').src = "print/word.php?file="+res.file ;
						break ;
						case 'pdf':	
							var urlPdf = "html2pdf/demo/html2ps.php?process_mode=single&URL=BEGINURL"+res.file+"ENDURL";
							urlPdf += "&media="+res.dimension ;
							if(res.miseenpage == 'paysage'){
								urlPdf += "&landscape=1" ;
							}
							window.open(urlPdf) ;
						break ;
						case 'zip':	
							$('imp_iframe_dowload').src = "fonctionnalites/print/chargement.php?format=zip&fichier="+res.file ;
						break ;
					}
		  	}catch(e){}
				$('imp_id_attente').style.display = 'none' ;
				removeCadre('imp_id_attente');
		}
	}).request(); 
	},
	
	getScaleDisponible : function(){
		var aScale = Array() ;
		if(typeof(CMap.scale) == 'object'){
			for(var i=0; i < CMap.scale.length;i++){
				var intScale = parseInt(CMap.scale[i].substr(2,CMap.scale[i].length-1));
				aScale.push([intScale, CMap.scale[i]]) ;
			}	
			return 	aScale ;	
		}
		else{
			return [[3000, '1/1000'],
							[10000, '1/10000'],
							[25000, '1/25000'],
							[50000, '1/50000'],
							[100000, '1/100000'],
							[125000, '1/125000']
						 ];	
		}
	},
	getScaleMapCurrent : function(){
		return (parseInt(CMap.map.getScale()) > 200000)?200000 : parseInt(CMap.map.getScale()) ;
	},
	verifInScaleDispo : function(aEchelle, echelleCur){
		if(typeof(aEchelle) != "object")return false ; 
		var bfind = false ;
		for(var i=0; i < aEchelle.length ; i++){
			if(aEchelle[i][0] == echelleCur){
				bfind = true ;
			}
		}
		return bfind ;
	},
	initScale : function(){
		var aEchelle = Impression.getScaleDisponible() ;
		var echelleCur = Impression.getScaleMapCurrent() ;
		if(!this.verifInScaleDispo(aEchelle, echelleCur)){
			aEchelle.push([echelleCur, '1/'+echelleCur]) ;
		}
		Impression.store = new Ext.data.SimpleStore({
		    fields: ['valechelle', 'libechelle'],
		    data : aEchelle
		});
		Impression.store.sort('valechelle', 'ASC') ;
		Impression.comboEchellePrint = new Ext.form.ComboBox({
		    store: Impression.store,
		    displayField:'libechelle',
		    valueField: 'valechelle' ,
		    typeAhead: true,
		    mode: 'local',
		    triggerAction: 'all',
		    emptyText:'...',
		    selectOnFocus:true,
		    editable:false,
		    width: 130,
		    listWidth: 130,
		    maxHeight: 100 ,
		    renderTo: 'imp_echelle',
		    listeners : {
		    	select : function(combo, record, indexRec ){
		    		Impression.redrawVisu();
		    	},
		    	render : function(combo){
		    		combo.setValue(echelleCur) ;
		    	}	
		    }
		});
	},
	
	saveDessinVectorInMap : function (){
		if(typeof(dessinPanel) == 'undefined' || typeof(dessinPanel.layer) == 'undefined'){
			this.launchprint(true) ;
			return false;
		}
		if(dessinPanel.layer.features.length == 0){
			this.launchprint(true) ;
			return true;
		}
		else{
			Ext.Ajax.request({
			   url: 'fonctionnalites/print/buildSession.php',
			   success: Impression.saveChange,
			   params: { 
			   		act: 'new', 
			   		nomCalque: 'capture',
			   		compteur : dessinPanel.layer.features.length
			   	}
			});
		}
	},

	saveChange : function (response){
		try{
			var res = eval("("+response.responseText+")");	
			if(res.error){
				Impression.launchprint(true) ;
	     	return false ;
			}
			if(res.nextFeatures){
				var feature = dessinPanel.layer.features[res.nextFeatures] ;
		    var options = {};
		    if (CMap.map && !dessinPanel.layer.projection.equals(CMap.map.getProjectionObject())) {
		        options.externalProjection = dessinPanel.layer.projection;
		        options.internalProjection = CMap.map.getProjectionObject();
		    }
		    var writerJson = new OpenLayers.Format.GeoJSON(options, this);
		    eval('var data = '+writerJson.write(feature));
		    var styleFeature = "";
		    if(data.geometry.type == 'Point'){
		    	if(typeof(feature.style.label) == 'undefined'){
		    		styleFeature = 	"{fillColor : '"+feature.style.fillColor+"',strokeColor: '"+feature.style.strokeColor+"',pointRadius: '"+feature.style.pointRadius+"',fillOpacity: '"+feature.style.fillOpacity+"',strokeWidth: '"+feature.style.strokeWidth+"'}";
		    	}
		    	else{
		    		styleFeature = 	"{label : \""+feature.style.label+"\",fillColor : '"+feature.style.fontColor+"',fontFamily: '"+feature.style.fontFamily+"',strokeWidth: '"+feature.style.fontSize+"'}";	
		    	}
		    }else if(data.geometry.type == 'LineString'){
		    	styleFeature = 	"{fillColor : '"+feature.style.fillColor+"',strokeColor: '"+feature.style.strokeColor+"',pointRadius: '"+feature.style.pointRadius+"',fillOpacity: '"+feature.style.fillOpacity+"',strokeWidth: '"+feature.style.strokeWidth+"'}";
		    }else if(data.geometry.type == 'Polygon'){      
		    	styleFeature = 	"{fillColor:'"+feature.style.fillColor+"',strokeColor:'"+feature.style.strokeColor+"',hoverStrokeColor:'"+feature.style.hoverStrokeColor+"',strokeOpacity: '"+feature.style.strokeOpacity+"',strokeWidth: '"+feature.style.strokeWidth+"',fillOpacity: '"+feature.style.fillOpacity+"'}";
		    } 
		    
				Ext.Ajax.request({
				   url: 'fonctionnalites/print/buildSession.php',
				   success: Impression.saveChange,
				   params: { 
	            id:data.id,
	        		geometrytype : data.geometry.type,
	        		the_geom : data.geometry.coordinates.join(","),
	        		crs : data.crs.properties.code,
	        		style : styleFeature,
		      		etape : parseInt(res.nextFeatures)+1
				   }
				});
			}
			if(res.fin){
				Impression.launchprint(true) ;
				return true;
			}
		}
		catch(e){
			Impression.launchprint(true) ;
		}
	},
	loadParamsToPrint : function(){
		var params = "format="+$('format').value ;
		var val_loc = ($('imp_localisation_oui').checked)?'oui':'non' ;
		params += "&localisation="+val_loc ;
		var val_leg = ($('imp_legende_oui').checked)?'oui':'non' ;
		params += "&legende="+val_leg ;
		params += "&titre="+$('imp_titre').value ;
		params += "&soustitre="+$('imp_soustitre').value ;
		params += "&echelle="+$('echellePrint').value ;
		params += "&sortie="+Impression.getSortiePrint() ;
		params += "&raster="+Raster.buildParamPrint();
		return params ;
	},
	getSortiePrint : function(){
		var result = 'html' ;
		var divImp = $('fichePrint') ;
		var aInp = divImp.getElementsByTagName('input') ;
		for(var i=0; i < aInp.length; i++){
			if(aInp[i].name != 'sortie') continue ;
			if(aInp[i].checked)result = aInp[i].value ;
		}
		return result ;
	},
	redrawVisu : function(){
		if(typeof(Visualiser) != 'undefined'){
			if($(Visualiser.idchekbox).checked)Visualiser.start();	
		}
	}
	
};
