(function($){

	pluginName = 'hegydPopup';

    $.hegydPopup = function(el, options){
        // To avoid scope issues, use 'base' instead of 'this'
        // to reference this class from internal events and functions.
        var base = this;
        
        // Access to jQuery and DOM versions of element
        base.$el = $(el);
        base.el = el;
        // Add a reverse reference to the DOM object
        base.$el.data("hegydPopup", base);
        
        base.init = function(initOptions){
			base.box = $('#hegydPopup');
			if(base.box.length != 1){
				log('Erreur : Impossible de trouver la hegydPopup');
				return false;
			}
			base.closer = base.box.find('.jsClose');
			if(base.closer.length==1){
				base.closer.click(function(){ // DONE ONE TIME 
					base.hide();
					return false;
				}).removeClass('jsClose');
			}
            base.options = $.extend({},$.hegydPopup.defaultOptions, initOptions);
			base.options.className = base.$el.attr('rel');
            // Put your initialization code here
			base.options.url = base.$el.attr('href');
			if(base.options.url){
				base.setListener();
			}
        };

		// ------------------------------------	
		// LISTENER 
		// ------------------------------------	

		base.setListener = function(){
			var button = base.$el;
			button.click(function(){
				base.go();
				return false;
			});
		}

		// ------------------------------------	
		// SHOW / HIDE
		// ------------------------------------	
		//
		base.show = function(){
			base.box.stop().css({display: 'block',opacity: '0'}).fadeTo(800,1);
			if(base.options.className){
				base.box.addClass(base.options.className);
			}
		}

		base.hide = function(){
			base.box.stop().fadeTo(200,0,function(){ base.box.css({display: 'none'}).removeClass(function(index,className){return className.replace('popUp','');});});
		}

		base.setText = function(content){
			base.box.find('.jsContent').html(content);
		}

		base.go = function(content){
			$.ajax({
				url: base.options.url,
				type: "post",
				data: 'ajax=1',
				dataType: "json",
				success: function(response){
					base.processResponse(response);
				}
			});
		}

		// ------------------------------------	
		// PROCESSING DATA  
		// ------------------------------------	

		base.processResponse = function(response){
			if(response.code == 1 && response.response){
				base.setText(response.response);
				base.dynamiseContent();
				base.show();
			}else{
				showInfoBox('Une erreur s\'est produite. Action impossible.');
			}
		}

		base.processFormResponse = function(response){
			if(response.code == 1){
				if(response.actionState == 1){
					var callbackFunction = base.box.find('form:first input[name$="[ajaxCallback]"]').val();
					if(callbackFunction && $.isFunction(window[callbackFunction])){
						window[callbackFunction](response);
					}
					base.hide();
					if(response.response){
						showInfoBox(response.response);
					}
				}else{
					base.box.find('.fieldError').remove();
					if(response.errors){
						$.each(response.errors,function(key,value){
							var inputEl = base.box.find('[name$="['+key+']"]');

							if (inputEl.length) {
								inputEl.after('<span class="fieldError">'+value+'</span>');
							} else {
								inputEl = base.box.find('[name$="['+key+'][]"]');

								if (inputEl.length)
									inputEl.first().closest('td').append('<span class="fieldError">'+value+'</span>');
							}
						})
					}else if(response.response){
						showInfoBox(response.response);
						base.hide();
					}
				}
			}else{
				showInfoBox('Une erreur s\'est produite. Action impossible.');
				base.hide();
			}
		}

		base.dynamiseContent = function(){
			// BOUTON D'ACTIONS 
			var confirmEl = base.box.find('a[href="#confirm"]');
			var cancelEl = base.box.find('a[href="#cancel"]');
			var formEl = base.box.find('form:first');
			//log(confirmEl);
			confirmEl.unbind('click').click(function(){
				formEl.trigger('submit');
				return false;	
			});
			cancelEl.unbind('click').click(function(){
				base.hide();
				return false;
			});
			formEl.submit(function(event,params){
				$.ajax({
					url: formEl.attr('action'),
					type: "post",
					data: formEl.serialize()+'&ajax=1',
					dataType: "json",
					success: function(response){
						base.processFormResponse(response);
						if(typeof params != 'undefined'){
							if(typeof params.callback != 'uncdefined' && $.isFunction(params.callback)){
								params.callback();
							}
						}
					}
				});
				return false;
			});
		}

    };
   


    $.hegydPopup.defaultOptions = {
    };
    
    $.fn.hegydPopup = function(method){
		
		// récupération des arguments et nom de la methode 
		var methodArguments = arguments;
		var methodName = method;

		// obtain property value 
		if(methodName == 'property' && arguments[1] && this[0]){
			var property = arguments[1];
			if( !(plugin = $(this[0]).data(pluginName)) ){
				plugin = new $.hegydPopup(this[0]);
			}
			if(plugin[property]){
				return plugin[property];
			}else{
				return null;
			}
		}
	
		// method and initialisation 
		return this.each(function(){
			// si le plugin n'est pas encore associé à l'objet , l'associé 
			if( !(plugin = $(this).data(pluginName)) ){
				plugin = new $.hegydPopup(this);
			}
		
			// si methodName correspond à une méthode 
			if( plugin[methodName] ){
				methodArguments = Array.prototype.slice.call( methodArguments, 1 )
			// sinon si c'est un objet ou rien de passé , faire methode init 
			}else if( typeof method === 'object' || !method){
				methodName = 'init';
			}else {
				return log('ERROR');
			}	
			return plugin[methodName].apply( this, methodArguments);
		});

    };
    
    // This function breaks the chain, but returns
    // the hegydPopup if it has been attached to the object.
    $.fn.gethegydPopup = function(){
        this.data("hegydPopup");
    };
    
})(jQuery);


