Ext.onReady(function() {		
	function test(){
		alert(Ex.get("frametest").getValue());
	}
	
if(Ext.get('rmPhoto')){
	Ext.get('rmPhoto').on('click',rmPhoto);
}
	
if(Ext.get('addPhoto')){
	Ext.get('addPhoto').on('click',addPhoto);
}
if(Ext.get('finishButton')){
	Ext.get('finishButton').on('click',goOut);	
}

});

	function addPhoto(){
		var curFile = Ext.get("currentFile").getValue();
		var nb = 0;
		if(curFile != ""){
		var tabFile = curFile.split("_");
		nb = parseInt(tabFile[1],10)
		if(nb >= 4){
			Ext.MessageBox.alert('Attention','Vous &ecirc;tes limit&eacute; &agrave; 4 photos');
			return false;
		}
		}
		
		/*nb++;
		var f = "file_"+nb;
		Ext.get("currentFile").dom.value = f;*/
			
		var contenaire = Ext.get('htmlFile');
		var contenu = contenaire.dom.innerHTML;
		if(contenu == ""){		//var htmlFile = '<input type="file" name="file" id="myfileuploader"/>&nbsp;&nbsp;<input src="/plateforme/Commons/images/site/accept.png" type="image" Value="submit"/> ';
		//htmlFile += '&nbsp;&nbsp;<a href="#" onclick="rmDepotPhoto()"><img src="/plateforme/Commons/images/site/cancel.png" style="margin-top:3px;"/></a>';
		var htmlFile = '<input type="file" name="file" id="myfileuploader"/> <input type="submit" value="Envoyer"/> ';
		htmlFile += ' <input type="button" Value="Annuler" onclick="rmDepotPhoto()"/>';
		contenaire.update(contenu+htmlFile);
		}
		
	}
	
function rmDepotPhoto(){
	var contenaire = Ext.get('htmlFile');
	contenaire.update("");
}

function rmPhoto(namePhoto){
	var tab = namePhoto.split("_");
	var wind = Ext.MessageBox.getDialog();
	
	// Objet PhotoObject
	var pO = getPhotoObject(tab[0]+"_"+tab[1], tab[2]);
	//var photoFullName = pO.fullName;
	
	/**
	 * on affiche l'image dans le bouton de suppression
	 * @type Boolean
	 */
	wind.autoWidth = true;
	Ext.MessageBox.confirm(
		'Attention'
		,'<img src="/portail/Commons/images/'+tab[0]+"_"+tab[1]+"/"+pO.fullName+'" alt="Photo &agrave; supprimer"/><br/>Voulez vous supprimer cette photo ?'
		,function(btn){
	
	if(btn == "yes"){
	
	Ext.Ajax.request({
			url: "/Annonce/Data/removePhoto",
			params : { namephoto : namePhoto, ext : pO.extension },
			success: function( result, request ) {
				var myresult = Ext.util.JSON.decode(result.responseText);
				if(myresult.status == 1){
					/**
					 * on enl&eacute;ve la ligne que l'on vient de supprimer
					 */
					var name = "photo_"+tab[2];
					var nameObject = Ext.get(name);
					if(nameObject) nameObject.remove();
					/**
			  		 * on reconstruit notre vue
			  		 */
			  		var str = "";
			  		var ref = tab[0]+'_'+tab[1];
					for(var i = 1 ; i < myresult.nbphoto+1 ; i++){
						str += '<li id="photo_'+i+'">';
						str += '<a href="#showPhoto" onmouseover="showPhotoTips(\'photo_'+i+'\',\''+ref+'\',\''+i+'\')"> '+ref+'_'+i+'.jpg</a>&nbsp';
						str += '<a href="#rmPhoto" onclick="rmPhoto(\''+ref+'_'+i+'\')"><img src="/plateforme/Commons/images/site/rem_co.gif"/></a></li>'
					}
					var div = Ext.get("resumePhoto");
					//div.update(str);
					/**
					 * on met a jour le compteur de fichier
					 */
					var compteur_objet = Ext.get("currentFile");  
					var compteur_file = compteur_objet.getValue();
					var compteurTab = compteur_file.split("_");
					var compteurString = compteurTab[1];
					var compteur = parseInt(compteurString , 10);
					var newCompteur = compteur-1;
					// on remet en place notre compteur
					compteur_objet.dom.value = "file_"+newCompteur;
					
					
					/**
				 	 * nous allons supprimer la vignette si existe
				 	 */
					var indicephoto = parseInt(tab[2]);
					var realIndice = indicephoto;
					var divVignette = Ext.get("resumePhotovignette_"+realIndice);
					if(divVignette){
						divVignette.remove();
					}
					
					
				}
			},
			failure: function ( result, request) { 
			},
			callback: function (result, request){
			} 
		});/* fin de la requete ajax */
		
	}/* fin du if btn */	
		
	}); /* fin du message box confirm */
	
}/* fin de la fonction rmPhoto */



function rmTmpPhoto(champName,filename){
	/**
	 * on supprime le champs hidden dans notre page
	 */
	var el = Ext.get(champName);
	el.remove();
	/**
	 * on supprime maintenant notre li information
	 */
	var nameli = 'li_'+champName;
	var myli = Ext.get(nameli);
	if(myli) myli.remove();
	/**
	 * on remet à jour la machine
	 */ 
	var cur = Ext.get("currentFile");
	var val = cur.getValue();
	var tabN = val.split("_");
	var int = parseInt(tabN[1]);
	var nval = int-1;
	cur.dom.value = "file_"+nval;
	
	/**
	 * dans le cas ou il n'y a plus de photo a charger
	 */
	if(nval < 1) {
		cur.dom.value = "";
		var l = Ext.get("loadPhoto");
		l.remove();
	}
	/**
	 * on nettoye sur le disque
	 */
	Ext.Ajax.request({
			url: "/Annonce/Data/removeTmpPhoto",
			params : {namephoto : filename},
			success: function( result, request ) {
				//var myresult = Ext.util.JSON.decode(result.responseText);
				if(result.responseText == 0){
					Ext.MessageBox.alert('Attention',"Votre fichier n'a pu &ecirc;tre supprim&eacute;");
				}else{
					/**
				 	 * nous allons supprimer la vignette si existe
				 	 */
					var tabString = champName.split("_");
					var indicephoto = parseInt(tabString[1]);
					var realIndice = indicephoto + 1;
					var divVignette = Ext.get("resumePhotovignette_"+realIndice);
					if(divVignette){
						divVignette.remove();
					}
				}
			},
			failure: function ( result, request) { 
			},
			callback: function (result, request){
			} 
		});  
}


function showPhotoTips(idPhoto,ref,indice){
    var namePhoto = ref+'_'+indice+".jpg";
    
    Ext.QuickTips.init();
    
    var tips = new Ext.ToolTip({
        target: idPhoto,
        width: 110,
        trackMouse: true, 
        autoLoad: {
        	url: '/Annonce/data/photo/',
        	params : {name : namePhoto , reference : ref}
        },
        dismissDelay: 15000 // auto hide after 15 seconds
    });
}

/*
 *
 * @author: mblondel
 */
function getPhotoObject(ref, indice){
	var photo = new Object();
	photo.reference = ref;
	photo.indice = indice;
	photo.fullName = getPhotoFullName(ref, indice);
	photo.extension = getPhotoExtension(photo.fullName);
	return photo;
}
/**
 * Pour récupérer le nom et l'extension de l'image
 * ref : reference du dossier
 * indice : numero de la photo (1,2,3)
 * @author: mblondel
 */
function getPhotoFullName(ref, indice){
	var urlPhoto = Ext.query("#resumePhotovignette_"+indice + " img")[0].src; 
	var fullNamePhoto = "";
	var tab = urlPhoto.split("/");
	fullNamePhoto = tab[tab.length-1];
	return fullNamePhoto;
}
/**
 * Pour récupérer le nom et l'extension de l'image
 * @author: mblondel
 */
function getPhotoExtension(fullName){
	var tab = fullName.split(".");
	return tab[tab.length-1];	
}

function showPhoto(idPhoto,ref,indice,dontconstruct){
	var winContainer = Ext.get('hello-win');
	if(winContainer){
		winContainer.remove();
	}
	
	var namePhoto = "";
	
	if(!dontconstruct){
		namePhoto = getPhotoFullName(ref, indice);
		createpopup(ref,namePhoto);
    }else{
    	namePhoto = indice;
    	createpopup(ref,namePhoto);
    }
}

function createpopup(ref,namePhoto){
	
	Ext.DomHelper.insertFirst("photo_aff_container",{
	 			id:"hello-win",
	 			tag : "div",
	 			cls : 'x-hidden', 
	 			children : {tag : "div", cls : "x-window-header" , html : "Votre photo"}
	 		});
	
	var win = new Ext.Window({
                el:'hello-win',
				layout:'column',
                width:400,
                autoWidth : true,
                autoHeight : true,
                html : "<img id='photoshowed' src='/portail/Commons/images/"+ref+"/"+namePhoto+"' alt='votre photo'/>"
                ,buttons: [
                {
                    text: 'fermer',
                    id : 'quitButton',
                   	handler: function(){
                   		win.close();
                   }
                }
                ]
            });
     
            
      win.show("photo_aff_container");
      
      Ext.get("photoshowed").on("click",function(){
      		win.close();
      });
}


