var tarification ={};
 
(function($){
	
    $.CBQ_tarification = 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("CBQ_tarification", base);
        
        base.init = function(){
            
            
            //base.changemod = changemod;
           // base.addrow = addrow | base.addrow;
           // base.removerow = removerow;

            base.options = $.extend({},$.CBQ_tarification.defaultOptions, options);
			
            // Put your initialization code here
			base.numrrows_tableGrillePeriode = base.options.numitm;
			
			//for(var i in tarification.data){base.numrrows_tableGrillePeriode++;}
			//tarification = {};
			//tarification.data = [];
			base.theClickedDate=null;

			//
			var currentTime = new Date();
			var month = currentTime.getMonth() + 1;
			var day = currentTime.getDate();
			var year = currentTime.getFullYear();
			base.today = {'year':year, 'month':month, 'day':day};
			////console.log(base.today);
			
			$('input[name=fields[tarifmod]]').click(function(){
				$('#trtarifmod_1').hide();
				$('#trtarifmod_2').hide();
				$('#trtarifmod_3').hide();
				$('#tr'+$(this).attr('id')).show();
				//
				////console.log(base);
				tarification.type=$(this).val();
				//tarification.data = [];				
				
			});
			
			////console.log(tarification);
			
			$('#ajouterperiodegrille').click(function(){
				base.addrow();
			});
			
						
			
				base.initEIPFields();
				base.initDateFields();
				base.initdelete();
        }
        
        base.addrow = function(){
			if(tarification.data==null || tarification.data=="undefined" || tarification.data==undefined){
				tarification.data=[];
			}
			tarification.data[base.numrrows_tableGrillePeriode] = [];
			tarification.data[base.numrrows_tableGrillePeriode]['periode'] = '';
			tarification.data[base.numrrows_tableGrillePeriode]['journee'] = '';
			tarification.data[base.numrrows_tableGrillePeriode]['2jours'] = '';
			tarification.data[base.numrrows_tableGrillePeriode]['3jours'] = '';
			tarification.data[base.numrrows_tableGrillePeriode]['5jours'] = '';
			tarification.data[base.numrrows_tableGrillePeriode]['7jours'] = '';
			tarification.data[base.numrrows_tableGrillePeriode]['mois'] = '';
			tarification.data[base.numrrows_tableGrillePeriode]['saison'] = '';
			tarification.data[base.numrrows_tableGrillePeriode]['annee'] = '';
			tarification.data[base.numrrows_tableGrillePeriode]['remarque'] = '';
			
			
				$(' <tr id="grilleRow_'+base.numrrows_tableGrillePeriode+'">\
                <td bgcolor="#FFFFFF" align="left" style=""><div class="editable_date" id="periode_'+base.numrrows_tableGrillePeriode+'">Choisissez une date, cliquez ici'+'</div><br /></td>\
                <td  bgcolor="#FFFFFF"style=""><p class="editable_textarea currency" id="journee_'+base.numrrows_tableGrillePeriode+'">0.00</p></td>\
                <td bgcolor="#FFFFFF" style=""><p class="editable_textarea currency" id="2jours_'+base.numrrows_tableGrillePeriode+'">0.00</p></td>\
                <td bgcolor="#FFFFFF" style=""><p class="editable_textarea currency" id="3jours_'+base.numrrows_tableGrillePeriode+'">0.00</p></td>\
                <td bgcolor="#FFFFFF" style=""><p class="editable_textarea currency" id="5jours_'+base.numrrows_tableGrillePeriode+'">0.00</p></td>\
                <td bgcolor="#FFFFFF" style=""><p class="editable_textarea currency" id="7jours_'+base.numrrows_tableGrillePeriode+'">0.00</p></td>\
                <td bgcolor="#FFFFFF" style=""><p class="editable_textarea currency" id="mois_'+base.numrrows_tableGrillePeriode+'">0.00</p></td>\
                <td bgcolor="#FFFFFF" style=""><p class="editable_textarea currency" id="saison_'+base.numrrows_tableGrillePeriode+'">0.00</p></td>\
                <td bgcolor="#FFFFFF" style=""><p class="editable_textarea currency" id="annee_'+base.numrrows_tableGrillePeriode+'">0.00</p></td>\
              </tr>\
              <tr id="tr2grilleRow_'+base.numrrows_tableGrillePeriode+'">\
			  <td bgcolor="#FFFFFF"><div style="position:relative; clear:both; font-size:9px;z-index:25px;margin:2px; border:1px solid #ccc;" id="deleteGrilleRow_'+base.numrrows_tableGrillePeriode+'" class="GrilleRowDeleter">Effacer</div></td>\
                <td bgcolor="#FFFFFF" colspan="8" style=""><em>Remarques:</em><br /><p class="editable_textarea" id="remarque_'+base.numrrows_tableGrillePeriode+'" style="padding-left:5px;"> - </p></td>\
                </tr>').appendTo('#TableGrillePeriodes');
				
				
				
				
				base.numrrows_tableGrillePeriode++;

				base.initEIPFields();
				base.initDateFields();
				base.initdelete();

        }
	
	
base.initdelete = function(){
	////console.log('initdelete');
	//$('#deleteGrilleRow_'+base.numrrows_tableGrillePeriode).click(function(){
	$('.GrilleRowDeleter').unbind('click').bind('click',function(){
		var thisid = $(this).attr('id').split('_')[1];
		//tarification.data.splice(thisid,1);
		//
		tarification.data[thisid]=null;
		//
		////console.log($(this).prev());
		$($(this).parents('tr')[0]).prev().remove();
		$($(this).parents('tr')[0]).remove();
	});
	
};	
/**********************************************************************************************************************************************/
base.initDateFields = function(){
	$('.editable_date').unbind('DatePicker');
	
	//var theItem = $("#periode_"+p_periode);
	
	
	
	$('.editable_date').DatePicker({
		locale: {
			days: ["Dimanche", "Lundi", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
			daysShort: ["Dim", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
			daysMin: ["Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa", "Di"],
			months: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Decembre"],
			monthsShort: ["Jan", "Fev", "Mar", "Avr", "Mai", "Jun", "Jul", "Aou", "Sep", "Oct", "Nov", "Dec"],
			weekMin: '#'
		},

		format:'d/m/Y',
		date:	'' /*$('#field_27').html()*/,
		current: ''/*$('#field_27').html()*/,
		starts: 1,
		position: 'r',
		mode: 'range',
		rel: base.theClickedDate,
		onBeforeShow: function(){
			//
			//// // 			//console.log($(this).html());
			
			var myregexp = /.*?_(.*)/i;
			var match = myregexp.exec($(this).attr('id'));
			if (match != null) {
				base.theClickedDate = match[1];
			} else {
				base.theClickedDate = 0;
			}
			
			//
			//$(this).data('datepicker').rel = p_periode;
			//this.currentID = p_periode;
			//			// // //console.log(theItem);
			//			// // //console.log(this);
			//$('.editable_date').DatePickerSetDate($('.editable_date').html(), true);
		},
		onChange: function(formated, dates){
			var periode = formated.join( ' <br /> ' );
			//theItem.html(periode);
			//var options = $(this).data('datepicker');
			//			// // //console.log(theClickedDate);
			//// //
			////console.log("#periode_"+$(this).attr("rel"));
			$( "#periode_"+base.theClickedDate ).html(periode);
			//
			if(!tarification.data[base.theClickedDate]){
				tarification.data[base.theClickedDate] = [];
			}
			tarification.data[base.theClickedDate]['periode'] = formated.join( ' ' );	
			
		},
		onRender: function(date) {
			var now = '';/*'<?php print(gmmktime(0, 0, 0, date('m'), date('d')-1, date('Y')));?>';	*/
			var ladate = Math.round(new Date().getTime()/1000);
			//			// // //console.log(now);
			//			// // //console.log(ladate);
			//			// // //console.log(' ');
			return {
				disabled: (ladate < now)/*,
				className: date.valueOf() == now.valueOf() ? 'datepickerSpecial' : false*/
			}
		}
	});
}


	base.initEIPFields = function(){
		$(".editable_textarea").editable(function(value, settings) { 
			// 
			//// 			//console.log(this);
			//// 			//console.log(value);
			//// 			//console.log(settings);
			////console.log(this);
			var myregexp = /remarque_(.*)/i;
			var match = myregexp.exec($(this).attr('id'));
			
			if (match != null && match.length > 1) {
				 thevalue = value = jQuery.trim(value);
				 
				 if(!tarification.data[match[1]]){
					tarification.data[match[1]] = [];
				}
				tarification.data[match[1]]['remarque'] = thevalue;
				
			} else {
				
				thevalue = value = jQuery.trim(value);
				$(this).html(value);
				value = $(this).formatCurrency({useHtml:true})[0].formatedcurrency;
	
				////console.log(value);
				
				var myregexp = /(.*)_(.*)/i;
				var match = myregexp.exec($(this).attr('id'));
				////console.log(match);
				if (match != null && match.length > 1) {
					//base.theClickedRow = match[2];
					if(!tarification.data[match[2]]){
						tarification.data[match[2]] = [];
					} 
					tarification.data[match[2]][match[1]] = thevalue;				
					////console.log(tarification.data);
				}
				/*
				
				var myregexp = /.*?_(.*)/i;
			var match = myregexp.exec($(this).attr('id'));
			if (match != null) {
				base.theClickedDate = match[1];
			} else {
				base.theClickedDate = 0;
			}
			
			*/
				
			}
			return(value);
		  }, { 
			  indicator : "<img src='http://www.chalets.qc.ca/css/themes/classic/indicator.gif' />",
			  type   : 'textarea',
			  onblur : 'submit',
			  select : true,
			  /*submit : 'OK',
			  cancel : 'cancel',*/
			  placeholder:'0.00',
			  select:true,
			  cssclass : "editable"/*,
			  callback:function(p_obj, p_arr){
			  // // //console.log('-----------------');
			  // // //console.log(p_obj);
			  // // //console.log(p_arr);
				//.toFixed(2);
			  }*/
			}
		);
		
	
	}
/**********************************************************************************************************************************************/
		
        
        base.init();
    }

	
    $.CBQ_tarification.defaultOptions = {
        defaultopt: "GRILLE",
        numitm: 10
    }
	
	

    $.fn.cBQ_tarification = function( options){
        return this.each(function(){
            (new $.CBQ_tarification(this, options));
        });
    }
	
    // This function breaks the chain, but returns
    // the CBQ_tarification if it has been attached to the object.
    $.fn.getCBQ_tarification = function(){
        return this.data("CBQ_tarification");
    }


})(jQuery);
