//                                    OM
/******************************************************************************
 * @file jquery.datetime.js
 *
 *
 * @section LICENSE
 *
 * HPE Confidential
 * Copyright 2015 Hewlett-Packard Enterprise Company, L.P.
 *
 * @section DESCRIPTION
 *
 * Date amd time plugin
 *
 * Developer					Date 						Description
 *------------------------------------------------------------------------------
 * Srikanth Bemineni           11/14/2015					Initial plugin
 *******************************************************************************/

$(document).ready(function(){
	(function($){

		$.fn.hpsumDateTime = function(options){

			var monthsInfo	= [	{ name : "January" ,  days : 31 },
								{ name : "February" ,  days : 28 },
								{ name : "March" ,  days : 31 },
								{ name : "April" ,  days : 30 },
								{ name : "May" ,  days : 31 },
								{ name : "June" ,  days : 30 },
								{ name : "July" ,  days : 31 },
								{ name : "August" ,  days : 31 },
								{ name : "September" ,  days : 30 },
								{ name : "October" ,  days : 31 },
								{ name : "November" ,  days : 30 },
								{ name : "December" ,  days : 31 }		];
			var weekdaysInfo = [ "Sunday","Monday" , "Tuesday" , "Wednesday" , "Thursday", "Friday","Saturday" ];
								

			function dateTimeSelector(element , options)
			{
				this.init = function(){
					var defaultoptions = { date : ""};
					// This should be  a <div>
					this.element = element;
					this.datetimeoptions  = $.extend({},defaultoptions , options);
					this.setup();
				}

				this.setup = function(){

					var _this = this;
					//If there is existing 
					$('#dati-datetime-window').detach();
					$(this.element).attr("readonly",true);
					$(this.element).attr("placeholder","yyyy-mm-dd hh:mm");
					this.uid = uuid();
					$(this.element).addClass("dt-input-" + this.uid);
					
					$(this.element).attr("data-date-id", "date-" + this.uid );
					
					$(this.element).on('click',function(event){

						 var id = "date-"+_this.uid;
						 if($('#dati-datetime-window').attr("data-date-id") == id )
						 {
						 	//click on the same input object;
						 	event.stopPropagation();
						 	return;
						 }

						 $('#dati-datetime-window').detach();
						 
						 //Recreate the calendar window again.
						 show.apply(_this);	 
						 	
						 event.stopPropagation();
					});

					$(document).mousedown(function (e) {
       					if ( (!$('#dati-datetime-window').is(e.target) // if the target of the click isn't the container...
            				   && $('#dati-datetime-window').has(e.target).length === 0 ) && // ... nor a descendant of the container
            				!$(_this.element).is(e.target)) //or the input element
        				{
            				var id = "date-"+_this.uid;
							if($('#dati-datetime-window').attr("data-date-id") == id )
							{
								closeWindow.apply(_this);
							}
        				}
    				});

					populateDate.apply(this);
					//updateTime.apply(this);


				}

				this.setDate = function(date){
					this.datetimeoptions.date = date;
					updateAll.apply(this);

				}

				function show(){

					var _this=this;

					var html = '<div id="dati-datetime-window" class="dt-date-window" data-date-id="date-'+ this.uid +'">' +
									'<div class="dt-calendar">'+ 
										generateMonthHeader.apply(this) +
										generateMonthTable.apply(this) +
									'</div>'+
									'<div class="dt-time">'+
										getTimeheader.apply(this) +
										generateTimeControls.apply(this) +
									'</div>'+
									'<div class="dt-controls">'+
										'<a class="dt-button dt-now" href="#">Now</a>'+
										'<a class="dt-button dt-done" href="#">Done</a>'+
									'</div>'+
								'</div>';
					$('body').append(html);

					//Lets set the position
					//Doctype needs to be set for this to work.
					var inoffset = $(this.element).offset();
					var inputheight= $(this.element).outerHeight(true);
					var datewinheight = $('.dt-date-window').outerHeight(true);
					var top = 0;
					var left = inoffset.left;
					if((datewinheight + 5 ) < inoffset.top )
					{
						//place it above the input
						top = (inoffset.top - datewinheight)-1;
					    $('.dt-date-window').removeClass('dt-bottom-round');
					    $('.dt-date-window').addClass('dt-top-round');
					}
					else
					{
						//Place below the input
						top = (inoffset.top+inputheight)+1;
						$('.dt-date-window').removeClass('dt-top-round');
					    $('.dt-date-window').addClass('dt-bottom-round');
					}
					$('.dt-date-window').css("top",top);
					$('.dt-date-window').css("left",left);
					$('.dt-date-window').css("z-index",401);


					
					$('.dt-date-window').css("display", "none" );

					$('.dt-date-window').fadeIn(100, function(){	

						$('.dt-date-window').on('click',function(event){
    							event.stopPropagation();
						});

						//Lets connect all the clicks on the links after the animation is complete
						$('.dt-calendar-left').on('click',function(event){
						    changeCalendar.apply(_this,['Down']);
						    event.preventDefault();
						});

						$('.dt-calendar-right').on('click',function(event){
						    changeCalendar.apply(_this,['Up']);
						    event.preventDefault();
						});

						$('.dt-time-controls-table .dt-time-input-hour').on('input propertychange' , function(){
							//this is  input
							var val = $(this).val();
							var isNotaNum = isNaN(val);
							if( val == NaN || val === ""  || parseInt(val) > 23 || isNotaNum)
							{
								$(this).css('border',"1px solid #c90000");
								//Need to disable done button
								$('.dt-done').addClass('dt-disabled');

							}
							else
							{
								$('.dt-done').removeClass('dt-disabled');
								$(this).css('border',"1px solid #cccccc");	
								_this.hour = parseInt(val);
							}

						});

						$('.dt-time-controls-table .dt-time-input-minute').on('input propertychange' , function(){
							//this is  input
							var val = $(this).val();
							var isNotaNum = isNaN(val);
							if(val == NaN || val === ""  || parseInt(val) > 59 || isNotaNum)
							{
								$(this).css('border',"1px solid #c90000");
								//Need to disable done button
								$('.dt-done').addClass('dt-disabled');
							}
							else
							{
								$('.dt-done').removeClass('dt-disabled');
								$(this).css('border',"1px solid #cccccc");	
								_this.minute = parseInt(val);
							}
						});

						$('.dt-time-hour-up').on('click',function(event){
								if(_this.hour + 1 <= 23){
									_this.hour++;
									$('.dt-done').removeClass('dt-disabled');
									$('.dt-time-controls-table .dt-time-input-hour').css('border',"1px solid #cccccc");	
								}
								$('.dt-time-controls-table .dt-time-input-hour').val(_this.hour);
								event.preventDefault();

						});

						$('.dt-time-hour-down').on('click',function(event){
							if(_this.hour - 1 >= 0 ){
									_this.hour--;
									$('.dt-done').removeClass('dt-disabled');
									$('.dt-time-controls-table .dt-time-input-hour').css('border',"1px solid #cccccc");	
							}

							$('.dt-time-controls-table .dt-time-input-hour').val(_this.hour);
							event.preventDefault();
						});

						$('.dt-time-minute-up').on('click',function(event){
							if(_this.minute + 1 <= 59 ){
									_this.minute++;
									$('.dt-done').removeClass('dt-disabled');
									$('.dt-time-controls-table .dt-time-input-minute').css('border',"1px solid #cccccc");	
							}
							$('.dt-time-controls-table .dt-time-input-minute').val(_this.minute);
							event.preventDefault();

						});

						$('.dt-time-minute-down').on('click',function(event){
							if(_this.minute - 1 >= 0 ){
									_this.minute--;
									$('.dt-done').removeClass('dt-disabled');
									$('.dt-time-controls-table .dt-time-input-minute').css('border',"1px solid #cccccc");	
							}
							$('.dt-time-controls-table .dt-time-input-minute').val(_this.minute);
							event.preventDefault();
						});

						$('.dt-calendar').on('click','.dt-calendar-table a',function(event){
							//this is anchor tag;
							_this.day = parseInt($(this).attr("data-date"));
							_this.selectedDate = new Date(_this.year, _this.month, _this.day,_this.hour,_this.minute,0);
							$('.dt-calendar-table .dt-date-selected').removeClass("dt-date-selected");
							$($(this).parent()).addClass("dt-date-selected");
							event.preventDefault();
						});

						$('.dt-now').on('click',function(event){
							_this.datetimeoptions.date = new Date();
							updateAll.apply(_this);
							event.preventDefault();
						});

						$('.dt-done').on('click',function(event){
							if(!$(this).hasClass('dt-disabled'))
							{
								closeWindow.apply(_this);
							}
							event.preventDefault();
						});


					});

				}

				function updateAll()
				{
					populateDate.apply(this);
					changeCalendar.apply(this,[null]);
					$('.dt-time-controls-table .dt-time-input-hour').val(this.hour);
					$('.dt-time-controls-table .dt-time-input-minute').val(this.minute);
					updateTime.apply(this);
				}


				//Up move the month up
				//'Down'  will move a month down
				// Empty will refresh the current calendar
				function changeCalendar( direction )
				{
					if(direction === 'Up')
					{
						if(this.month != 11)
						{
							this.month++;
						}
						else
						{
							this.month  = 0;
							this.year++;
						}
					}
					else if(direction == 'Down')
					{
						if(this.month != 0 )
						{
							this.month--;
						}
						else
						{
							this.month  = 11;
							this.year--;
						}
					}

					$('.dt-calendar > .dt-calendar-table').detach();
					$('.dt-calendar').append(generateMonthTable.apply(this));
					$('.dt-calendar > .dt-calendar-header #dati-month-label').text(monthsInfo[this.month].name + ' ' + this.year.toString());
				}

				function populateDate()
				{

					if (typeof this.datetimeoptions.date === "string" && this.datetimeoptions.date !== "" )
					{
						//'December 17, 1995 03:24:00'
						//'1995-12-17T03:24:00'
						this.track_date = new Date(this.datetimeoptions.date);
					}
					else if(this.datetimeoptions.date instanceof Date )
					{
						 this.track_date = this.datetimeoptions.date;
					}
					
                    this.today = new Date();

					if(this.track_date == null)
						this.track_date = this.today;	

					this.day = this.track_date.getDate();
					this.month = this.track_date.getMonth();
					this.dayoftheweek = this.track_date.getDay();
					this.year = this.track_date.getFullYear();
					this.hour = this.track_date.getHours();
					this.minute = this.track_date.getMinutes();
					this.selectedDate = this.track_date;
				}

				function getTimeheader()
				{

					var html = '<div class="dt-time-header">'+
							'<table style="width:100%;">'+
								'<tr>'+
								'<td style="width:20%; text-align:left;"></td>'+
								'<td style="width:60%; text-align:center;"><i class="fa fa-clock-o"></i></td>'+
								'<td style="width:20%; text-align:right;"></td>'+
								'</tr>'+
							'</table>'+
							'</div>';
					return html;
				}

				function generateTimeControls()
				{
					var html = '<table class="dt-time-controls-table">'+
								'<tr>'+
									'<td>'+
										'<a href="#" class="dt-time-hour-up"><i class="fa fa-chevron-up"></i></a>'+
									'</td>'+
									'<td></td>'+
									'<td>'+
										'<a href="#" class="dt-time-minute-up"><i class="fa fa-chevron-up"></i></a>'+
									'</td>'+
								'</tr>'+
								'<tr>'+
									'<td>'+
										'<input class="dt-time-input-hour" type="text" maxlength="2" size="2" value="'+ this.hour + '"/>'+
									'</td>'+
									'<td style="font-size:11px;"><div><i class="fa fa-circle"></i></div><div><i class="fa fa-circle"></i></div></td>'+
									'<td>'+
										'<input class="dt-time-input-minute" type="text" maxlength="2" size="2" value="'+ this.minute + '"/>'+
									'</td>'+
								'</tr>'+
								'<tr>'+
									'<td>'+
										'<a href="#" class="dt-time-hour-down"><i class="fa fa-chevron-down"></i></a>'+
									'</td>'+
									'<td></td>'+
									'<td>'+
										'<a href="#" class="dt-time-minute-down"><i class="fa fa-chevron-down"></i></a>'+
									'</td>'+
								'</tr>'+
							'</table>';
						return html;
				}

				function generateMonthHeader()
				{					
					var html = '<div class="dt-calendar-header">'+
									'<table style="width:100%;">'+
										'<tr>'+
											'<td style="width:20%; text-align:left;">'+
												'<a href="#" class="dt-calendar-left"><i class="fa fa-chevron-left"></i></a>'+
											'</td>'+
											'<td id="dati-month-label" style="width:60%; text-align:center;">'+ monthsInfo[this.month].name + ' ' + this.year.toString() +  '</td>'+
											'<td style="width:20%; text-align:right;">'+
												'<a href="#" class="dt-calendar-right"><i class="fa fa-chevron-right"></i></a>'+
											'</td>'+
										'</tr>'+
									'</table>'+
								'</div>';
					return html;
				}

				function generateMonthTable()
				{

					var monthtodisplay = new Date(this.year , this.month , 1);

					var inSelectedMonthYear = false;

					if(this.year === this.selectedDate.getFullYear() && this.month === this.selectedDate.getMonth())
						inSelectedMonthYear = true;


					var html = '<table class="dt-calendar-table">'+
										'<thead>'+
  											'<tr>'+
  												'<th>Sun</th>'+
     											'<th>Mon</th>'+
     											'<th>Tue</th>'+
     											'<th>Wed</th>'+
     											'<th>Thu</th>'+
     											'<th>Fri</th>'+
     											'<th>Sat</th>'+
  											'</tr>'+
 										'</thead>'+
 										'<tbody>';
 					var monthstarted = false;
 					var j = 0; 
 					var incdays = 1;
 					var days = getDaysinaMonth(this.month , this.year);
 					for( i = 0 ; i < 42 ; i++ )
 					{
 						  
 						  //Start of the week check
 						  if(j == 0)
 						  {
 						  	html += "<tr>";
 						  }

 						  if(monthstarted  && incdays <= days)
 						  {
 						  	if( inSelectedMonthYear == true && incdays == this.selectedDate.getDate())
 						  	{
 						  		html += '<td class="dt-date-selected"><a data-date="'+ incdays.toString() +'" href="#">'+ incdays.toString() +"</a></td>";
 						  	}else{
 						  		html += '<td><a data-date="'+ incdays.toString() +'" href="#">'+ incdays.toString() +"</a></td>";
 						  	}
 						  }else
 						  {
 						  	 if(j == monthtodisplay.getDay() && incdays <= days)
 						  	 {
 						  	 	 if( inSelectedMonthYear == true && 1 == this.selectedDate.getDate())
 						  		 {
 						  		 	html += '<td class="dt-date-selected"><a data-date="1" href="#">1</a></td>';
 						  		 }
 						  		 else
 						  		 {
 						  	 	 	html += '<td><a data-date="1" href="#">1</a></td>';
 						  	 	 }
 						  	 	 monthstarted = true;
 						  	 	 //reset i since we found the starting weekday of the month.
 						  	 	 incdays=1;
 						  	 }else
 						  	 {
 						  	 	html += "<td>&nbsp;</td>";
 						  	 }
 						  }

 						  j++;

 						  if(incdays != 0 )
 						  	incdays++;

 						  //End of the week check
 						  if( j > 6)
 						  {
 						  	 html += "</tr>";
 						  	 j = 0;
 						  }

 					}
 											
 					html +='</tbody>'+
						   '</table>';

					return html;

				}

				function getDaysinaMonth( month , year )
				{
				  if(month == 1)
				  {
				  	 if( (year%4 == 0 && year%100 != 0) && year%400 == 0 )
				  	 {
				  	 	return 29;
				  	 }

				  	 return 28;
				  }
				  else
				  {
				  	return monthsInfo[month].days; 
				  }
				}

				function updateTime()
				{
					var string = tDN((this.selectedDate.getMonth()+1)).toString()+ "-" +
								 tDN(this.selectedDate.getDate()).toString() + "-" +
								 tDN(this.selectedDate.getFullYear()).toString()+" "+
								 tDN(this.hour).toString()+":"+
								 tDN(this.minute).toString();
					$(".dt-input-" + this.uid).val(string);
				}

				//Two digit number
				function tDN(i) 
				{
		    		if (i<10)   // add zero in front of numbers < 10
		    		{
		    		   i = "0" + i 
		    		} 
		    		return i;
				}

				function closeWindow()
				{
					$('.dt-date-window').fadeOut(100,function(){ $('.dt-date-window').detach(); });
					updateTime.apply(this);
				}

				
				function uuid()
				{
					
					return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    				var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
    					return v.toString(16);
					});
				}


				this.init();
			}



			if (typeof options === "string") {
                //To call the plugin functions after initialization.
                var args = Array.prototype.slice.call(arguments, 1);

                if(!this[0])
                	return;
              
                //assuming jquery object is returned
                var dateTimeInstance = $.data(this[0], '_hpsumDateTime');
                //Lets try to get the data from the element
                if (!dateTimeInstance) {
                        log.error("This object has not yet been initialized to use Date Time Plugin");
                        return;
                    } else if (!$.isFunction(dateTimeInstance[options]) || options.charAt(0) === '_') {
                        log.error("No function by name " + options + ' exist in Date Time Plugin');
                        return;
                    }
                    // call method
                if(options == "destroy")
                {
                	dateTimeInstance.destroy();
                	$.removeData(this[0],'_hpsumDateTime');
                	dateTimeInstance = null;
                	return
                }

                return dateTimeInstance[options].apply(dateTimeInstance, args);
                
            } else {
                //Request for a new initialization
                return this.each(function() {
                    var dateTimeInstance = $.data(this, '_hpsumDateTime')
                    if (!dateTimeInstance) {
                        dateTimeInstance = new dateTimeSelector(this, options);
                        $.data(this, '_hpsumDateTime', dateTimeInstance);
                    }
                });
            }


		}

	})(jQuery);

})

