/**
 * @author sartois
 */
(function($) {

    /**
     * Main plugin definition.
     * Call it like that :
     * 
     * $("#myFormId").kJS_FormManager();
     * 
     * This plugin need a xml configuration file.
     * Each validator must be describe with a node, like that :
     * 
     * <type id="01" name="obligatory">
     *   <information><![CDATA[Your information message]]></information>
     *   <error><![CDATA[Your error message]]></error>
     * </type>
     * 
     * Then, this plugin waits for an object called "conf", wich describe some needed params :
     * 
     * conf = {
     * 	  "fieldName" : {
     * 	     "paramName1" : "paramvalue1"
     *       "paramName2" : "paramvalue2"
     * 	  },
     *    "otherFieldName" : {
     *        ...
     *    }
     * };
     * 
     * @param {Object} options
     */
    $.fn.kJS_FormManager = function(options){
        
        var opts = $.extend( {}, $.fn.kJS_FormManager.params, options), xmlContent = {};
        //console.debug(opts);
        opts.authClass = [];
        
        /**
         * get the xml content
         */
        $.ajax({ type: "GET", url: opts.xmlFile, timeout:10000, async:false, dataType:"xml",
            success:function(xml){
                $( opts.nodeName, xml).each(function(i){
                
                	var sNodeName = $(this).attr("name");
                	
                    xmlContent[ sNodeName ] = {
                    	"info" : $( opts.infoNodeName, this ).text(),
                    	"error" : $( opts.errorNodeName, this ).text()
                    };
                    
                    opts.authClass.push( splitUnNeededChar( sNodeName ) );
                    
		        });
            },
            error:function(){
            	console.error("kJS_FormManager can't get the tooltip content xml file. Please check-it !");
            }
        });
        
        if( opts.includeHelpers != "" ){
        	includeHelpers( opts.includeHelpers, opts.defaultJsPath );
        }
        
        
        
        /**
         * Plugin body, loop through each element you called the plugin on.
         */
        return this.each(function()
        {
            $t = $(this);
            
            $t.bind( "failure", {}, function( e ){
          	  	
            	//if( e.type == "validatorFailed") e.stopPropagation();
            	
            	alert( "bindé : "+ e.pattern );
          	  
          	  	return false;
          	  	
            });
        	
            /**
             * Loop through each child element, and call ui.kTooltip
             */
            $(":input", this).each( function() {
               
               var child = $(this),
               		aClass = child.attr("class").split(' '),
               			name =  child.attr("name");
               
               //console.log("----------"+name+"----------");
               //console.debug(aClass)
               
               if ( aClass.length >= 1 )
               {
            	   /**
            	    * This switch may seems useless, but if you need to customize plugin behavior, you should do it here.
            	    */
                   switch (this.tagName)
                   {
                   		case "TEXTAREA":
                   		case "SELECT":
                   		case "INPUT":
                   			
                   			var sType = ( typeof child.attr("type") != "undefined" ) ? child.attr("type") : "";
                           
                   			switch( sType )
                   			{
                   				case "":
                   				case "text":
                   				case "radio":
                   				case "checkbox":
                   				case "password":
                            	   
                                   var c = setInfo( aClass, xmlContent, opts );
                                   
                                   if( c != "" ){
                                     
                                   child.kTooltip({ 
                                	   nodeName:name, content:c, id: name, contentType : "custom", arrowWay:"left-top", leftOffset:"470px", topOffset:"-10px"
                                   });
                                   }
                                   
                                   //child.kValidator({ type:aClass, mode:"souple" });

                                   break;
                                   
                               case "file":
                               case "hidden":
                               case "submit":
                               case "button":
                               case "image":
                               case "reset":
                               default :
                            	   /** do nothing **/
                                   break;
                           }
                           
                           break;
                           
                       default:
                    	   /** do nothing **/
                           break;
                   }//end switch
               }//end if
            });//end each  
        });//end each
    };//end fonction

    
    /**;
     * FormateTooltipText
     * 
     * 
     * @param {Object} aClass
     * @param {Object} $thisName
     * @param {Object} xmlContent
     * @param {Object} opts
     */
    var setInfo = function(  aClass, xmlContent, opts )
    {
        var elTTip = {
        	"info" : "",
        	"error" :""
        };
        
        /**
         * Loop through aClass, aka the string array that contains the aClass defined in the tpl
         */
        for( var i = 0, limit = aClass.length ; i < limit ; i++ )
        {
            /**
             * If the class have an argument ( like : authChar(alpha) ), then params[2] holds it.
             */
            var params = aClass[i].match(/(\w+)\((\w+)\)$/);
            
            if (  in_array( aClass[i], opts.authClass ) )
            {
          
	            if( params === null )
	            {
	                elTTip.info += "<p>" + xmlContent[ aClass[i] ][ "info" ] + "</p>";
	                //elTTip.error += "<p>" + xmlContent[ aClass[i] ][ "error" ] + "</p>";
	            }
	            else
	            {
	               switch( params[1] )
	               {
	               		case "minLength" :
	               			elTTip.info += "<p>"+params[2]+" "+xmlContent[ params[1] ][ "info" ]+"</p>";
	               			//elTTip.error += "<p>"+xmlContent[ params[1] ][ "error" ]+"</p>";
	                        break;
	                        
	               		case "callBack" :
	                        /** nothing to do here */
	                        break;
	                        
	                    case "authChar" :
	                    case "enum" :
	                    default :
	                    	elTTip.info += "<p>"+xmlContent[ aClass[i] ][ "info" ]+"</p>";
	                    	//elTTip.error += "<p>"+xmlContent[ aClass[i] ][ "error" ]+"</p>";
	                        break;
	                }
	            }
            }
            else if(aClass[i] == 'sponsorEmail(idparrain)')
            {
            	elTTip.info += "<p>"+xmlContent[ aClass[i] ][ "info" ]+"</p>";
            }
        }
        if( elTTip.info == "" ) return "";
        
        return elTTip;
    };
    
    var includeHelpers = function( sJsName, defaultJsPath  ){
    	
    	aJsName = sJsName.split(",");
    	
    	$.each(aJsName, function(i,val){
    		include_js( defaultJsPath+"/"+val );
    	});
    	
    	function include_js( scriptname ){
    		var html_doc = document.getElementsByTagName('head').item(0);
        	var js = document.createElement('script');
        	js.setAttribute('type', 'text/javascript');
        	js.setAttribute('src', scriptname );
        	html_doc.appendChild(js);
        	return true;
    	};
    	
    };//end includeHelpers;
    
    var splitUnNeededChar = function( sRawCssClass ){
    	
    	var test = sRawCssClass.indexOf("(");
    	return ( test !== -1 ) ? sRawCssClass.substr(0, test) : sRawCssClass ;
    };
    
    
    /**
     * Little helper function to build the html select widget.
     * 
     * @param {Object} options
     */
    $.fn.kJS_setSelectDate = function( options ){
    
        var opts = $.extend( {}, $.fn.kJS_setSelectDate.params, options);
        
        /**
         * Check if kinkama.js and jquery.selectboxutils.js are functions, if both aren't, trigger errror.
         */
        if( typeof $().numericOptions != "function" && typeof kinkama != "function" ){
            console.error("kJS_setSelectDate dependencies are not included. Missing jquery.selectboxutils.js and kinkama.js.");
            
            return;
        }
        else if( typeof $().numericOptions != "function" && typeof kinkama == "function" ) {
            include_dom("/Views/js/=support=/jqueryPlugins/jquery.selectboxutils.js");
        }
        
        /**
         * This plugin is called on the parent form ( this ), but works with opts.sSelectMonthId, opts.sSelectDayId and opts.sSelectYearId
         * Don't be disturb ...
         */
        return this.each( function() {
            
            var ObjetDate = new Date();
		    var currentYear = ObjetDate.getFullYear();
		    var dDay = ObjetDate.getDate();
		    var mMonth = ObjetDate.getMonth();

    		$('#'+opts.sSelectMonthId).numericOptions({ from: 1, to: 12, labels: opts.aMonthTranslation, selectedIndex : mMonth });
		
    		/*$('#'+opts.sSelectDayId ).numericOptions({ selectedIndex:dDay }).datePulldown({
    			year: $('#'+opts.sSelectYearId ),
    			month: $('#'+opts.sSelectMonthId )
    		});*/
        });
    };
    
    
    $.fn.kJS_addCallBackBeforeSubmit = function( options ){
        
        var opts = $.extend( {}, $.fn.kJS_setSelectDate.params, options);
        
        return this.each( function() {
        
            var $form = $(this);
            
            $form.submit(function() {
                
                var callback = opts.callBack;
                if ($.isFunction(callback)) callback(); 
                //return false;
            });
        });
    };
    
    
    setBirthDay = function( options ){
        
        if( typeof options.yearId == "undefined" ) options.yearId = '#annee';
        if( typeof options.monthId == "undefined" ) options.monthId = '#mois';
        if( typeof options.dayId == "undefined" ) options.dayId = '#jour';
        if( typeof options.inputHidden == "undefined" ) options.inputHidden = '#birthday';
        
        if( typeof $().getValue != "function" ) include_dom("/Views/js/=support=/jqueryPlugins/jquery.field.js");
            
        var year = $( options.yearId ).getValue();
        var month = $( options.monthId ).getValue();
        var day = $( options.dayId ).getValue();
    
        $( options.inputHidden ).setValue = year+'-'+month+'-'+day;
        
        return true;
	};
    
    /**
     * Defaults main plugin params
     */
    $.fn.kJS_FormManager.params = {
        
        xmlFile:"information.xml",
        nodeName:"type",
        infoNodeName:"information",
        errorNodeName:"error",
        defaultJsPath : '/js',
        includeHelpers : "",
        includeCSS : ""
    };
    
    $.fn.kJS_setSelectDate.params = {
        
        aMonthTranslation : [ "janvier","février","mars","avril","mai","juin","juillet","aout","septembre","octobre","novembre","décembre"],
        sSelectMonthId : "mois",
        sSelectDayId : "jour",
        sSelectYearId : "annee"
        
    };
    
    $.fn.kJS_addCallBackBeforeSubmit.params = {
        callBack : ""
    };
    
    
})(jQuery);
