Ext.namespace("Optima");
Optima.TplPhoto = null;
Optima.Photos = function() {
   var cp = null;
   var search  = null;
   var init = function() {
      
      Optima.TplPhoto = new Ext.XTemplate('<tpl for="."><img src="./media/galerie/188/{idImg}"/></tpl>');
      Optima.TplPhoto.compile();
      
      cp = new Ext.state.CookieProvider({
      path: "",
      expires: new Date(new Date().getTime()+(1000*60*60*24*1)),
      domain: ""});  
      
      /*var tpl = new Ext.XTemplate(
         '<tpl for=".">',
         '<div class="search-item">',
            '<h3><span>Le {dateFr}<br />à {commune}</span>',
            '{titre}</h3>',
         '</div></tpl>'
      );*/
      var tpl = new Ext.XTemplate(
         '<tpl for=".">',
            '<div class="thumb-wrap" id="{id}">',
            '<div class="thumb">',
            '<tpl if="this.isLinkable(nbMedias)">',
            '<img src=\'./media/galerie/{id}/mini/{photo}\'/>',
            '</tpl>',
            '</div>',
            '<span>{titre}</span>',
            '<span>Le {dateFr}</span>',
            '<span>à {commune}</span></div>',
            '</tpl>', {
         isVisible: function(date){
            var dtMax = new Date().add(Date.HOUR, 23);
            var dtMin = new Date().add(Date.YEAR, -50);
            return date.between(dtMin,dtMax);
         },
         isLinkable : function(nbMedias){
            return nbMedias > 0;
            
         },
         photoView : function(photo) {
            return photo !== '';
         }
      });
      var st = new Ext.data.Store({
               url : './service/searchPhoto.php',
               reader: new Ext.data.JsonReader({
                   root: 'rows',
                   id: 'id'
               }, [
                   'id','titre',{name :'nbMedias',type:'int'},'photo','commune',{name: 'date',type:'date', dateFormat: 'd/m/Y'},'dateFr','nomSoiree','keyWord'
               ])
             });
      st.load({params : {query:''}});

      /*var panel = new Ext.Panel({
         id:'manifestationList',
         applyTo : 'manifestationList',
         frame:false,
         height:400,
         collapsible:false,
         layout:'fit',
         title:'Résultats',
         autoScroll:true,
         items:*/ new Ext.DataView({
        	 applyTo : 'manifestationList',
            store: st,
            tpl: tpl,
            autoHeight:true,
            singleSelect : true,
            autoWidth : true,
            autoHeight : true,
            multiSelect:false,
            overClass:'x-view-over',
            itemSelector: 'div.thumb-wrap',
            emptyText: '<h2>Pas de résultats</h2>',
            listeners : {
               click : function(view, index, node, e ) {
                     var rec = view.getRecord(node);
                     if (rec.data.nbMedias > 0) {
                        openPhoto(rec.id);
                        /*getWinPhoto().show(node);
                        storeVideo.load({params : {id:rec.id}});
                        storePhoto.load({params : {id:rec.id}});*/
                        
                        
                        
                     }
                  }
            }
         })
      /*});
      new Ext.LoadMask(panel.body,{
         store : st,
         msg : "Recherche en cours"
      });*/

   
      search = new Optima.Photos.Search({
         applyTo : "search",
         store : st
      });
   };
   var openPhoto = function(id){
      Ext.Ajax.request({
    	  url : "service/viewPhotos.php",
    	  params : {
    	  	'id' : id
      	},
      	failure : function(){
      		alert("Pas de photos!");
      	},
      	success : function(rep){
      		var c = Ext.decode(rep.responseText);
      		if (c.success){
      			//alert(rep.responseText)
      			Optima.ViewImages.open(c.rows);
      			Ext.ux.Lightbox.loadImages(c.rows);
      		}
      	}
      })
   };
   
   return {
      init : init,
      getCp : function() {return cp;},
      getSearch : function(){
     	return search; 
    }
   }
}();
Optima.Photos.Search = Ext.extend(Ext.form.TwinTriggerField, {
    initComponent : function(){
        Optima.Photos.Search.superclass.initComponent.call(this);
        this.on('specialkey', function(f, e){
            if(e.getKey() == e.ENTER){
                this.onTrigger2Click();
            }
        }, this);
    },

    validationEvent:false,
    validateOnBlur:false,
    trigger1Class:'x-form-clear-trigger',
    trigger2Class:'x-form-search-trigger',
    hideTrigger1:true,
    width:300,
    hasSearch : false,
    paramName : 'query',
    searchVal : null,

    onTrigger1Click : function(){
        if(this.hasSearch){
            this.el.dom.value = '';
            var o = {start: 0};
            this.store.baseParams = this.store.baseParams || {};
            this.store.baseParams[this.paramName] = '';
            this.store.reload({params:o});
            this.triggers[0].hide();
            this.hasSearch = false;
        }
    },

    onTrigger2Click : function(){
        var v = this.getRawValue();
        var o = {start: 0};
        this.store.baseParams = this.store.baseParams || {};
        this.store.baseParams[this.paramName] = v;
        this.store.reload({params:o});
        this.hasSearch = true;
        this.triggers[0].show();
    },
    onRender : function(ct, position){
        Optima.Photos.Search.superclass.onRender.call(this, ct, position);
        this.setSearch(this.searchVal);
    },
    setSearch : function(val) {
    		if (this.rendered) {
    		
	    		if (val !== null){
	         this.setRawValue(val);
	        }
	        if (this.getRawValue() !== "")
	         this.onTrigger2Click();
        }else{
        	this.searchVal = val;
      	}
  	}
});

Optima.ViewImages = function(){
	var w = null;
	var list = null;
	var rct = 100000;
	var getWin = function(){
		if (w == null){
			w = new Ext.Window({
				closeAction : 'hide',
				modal : true,
				width : 600,
				height : 500,
				layout:'fit',
				items : list = new Ext.DataView({
					autoScroll : true,
					store : new Ext.data.JsonStore({
						fields : ["img","manif"],
						root : 'rows'
					}),
					overClass:'x-view-over',
            		itemSelector:'div.thumb-wrap',
					tpl : new Ext.XTemplate(
						'<tpl for=".">',
				            '<div class="thumb-wrap" id="{manif}/{img}">',
						    '<div class="thumb"><img src="media/galerie/{manif}/mini/{img}" title="{img}"></div>',
						    '</div>',
				        '</tpl>',
				        '<div class="x-clear"></div>'
				      ),
				      listeners : {
				      	click :  {
				      		fn : function(view, index,node,evt){
				      			Ext.ux.Lightbox.openImage(index);
				      		},
				      		scope : this
				      	}
				      }
				}) 
			});
		}
		return w;
	};
	
	
	return{
		open : function(rows){
			var wn = getWin();
			list.store.removeAll();
			var p = [], l = rows.length;
			for (var i = 0; i < l;i++){
				p.push( new list.store.recordType(rows[i]));
			}
			list.store.add(p);
			wn.show();
		}
		
	};

}();

Ext.onReady(function(){
	//Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
      

        
     /*   Ext.QuickTips.init();
        
        Ext.apply(Ext.QuickTips.getQuickTip(), {
         minWidth: 100,
         showDelay: 50,
         trackMouse: true
     });*/
		Optima.Photos.init();
		if (searchVal)
			Optima.Photos.getSearch().setSearch(searchVal);
      alert("Informations\r\nConformément à la loi \"Informatique et libertés\", vous êtes en mesure de nous demander le retrait des photos qui vous concerne. Pour  cela, veuillez contacter l'équipe OPTIMA sur contact@optimasono.info");

},this);