
jQuery.fn.datetime = function() {

	var userLang 		= arguments[0]['userLang'] || 'en';
	var b24Hour			= !(arguments[0]['americanMode'] || false);
	var markerClass		= 'hasDateTime';
    var minuteIncrement = arguments[0]['minuteIncrement'];

	return this.each(function(){

				var datepicker_def 	= {
							changeMonth: true,
							changeYear: true,
							dateFormat: 'M d, yy',
							showButtonPanel: true,
							onSelect: writeDate
				};

				var lang = {};

				lang['en'] = {
								time: 	'Time',
								hour:	'Hour',
								minute:	'Minute',
								close:	'Close'
							};

				lang['de'] = {
								time: 	'Zeit',
								hour:	'Stunde',
								minute:	'Minute',
								close:	'Schließen'
							};

				$(this).data('sets',datepicker_def);
				$(this).data('userLang',userLang);
				$(this).data('b24Hour',true);

				function renderPickerPlug(b24Hour_,lang_) {
					var loadedLang = lang[lang_] || lang['en'];

					if (!$('#pickerplug').length) {

						var htmlins = '<ul id="pickerplug">';
						htmlins += '<li>';
						htmlins += '<div id="datepicker"></div>';
						htmlins += '</li>';
						htmlins += '<li>';
						htmlins += '<div id="timepicker">';
						htmlins += '<h3 id="tpSelectedTime">';
						htmlins += '	<span id="text_time"></span>';
						htmlins += '	<span class="selHrs" >00</span>';
						htmlins += '	<span class="delim" >:</span>';
						htmlins += '	<span class="selMins">00</span>';
						htmlins += '</h3>';
						htmlins += '<ul id="sliderContainer">';
						htmlins += '	<li>';
						htmlins += '        <h4 id="text_hour"></h4>';
						htmlins += '        <div id="hourSlider" class="slider"></div>';
						htmlins += '	</li>';
						htmlins += '	<li>';
						htmlins += '        <h4 id="text_minute"></h4>';
						htmlins += '        <div id="minuteSlider" class="slider"></div>';
						htmlins += '	</li>';
						htmlins += '</ul>';
						htmlins += '</div>';
						htmlins += '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" id="text_close"></button>';
						htmlins += '</li>';
						htmlins += '</ul>';
						$('body').append(htmlins);

						$('#datepicker').datepicker();
						$(document).mousedown(closePickPlug);
						$('#pickerplug .ui-datepicker-close').click(closePickPlug);
                        $('#pickerplug').addClass('noReZIndex').css('zIndex','50000');

	 // Slider
						$('#hourSlider').slider({
							orientation: "vertical",
							range: 'min',
							min: 0,
							max: 23,
							step: 1,
							slide: function(event, ui) {
								writeDate(writeTime(ui.value,'hour'),'time');
							},
							change: function(event, ui) {
								$('#tpSelectedTime .selHrs').effect('highlight', 1000);
							}
						});
                        
                        if(minuteIncrement == 1){
						    // Slider
						    $('#minuteSlider').slider({
							    orientation: "vertical",
							    range: 'min',
							    min: 0,
							    max: 59,
							    step: 1,
							    slide: function(event, ui) {
								    writeDate(writeTime(ui.value,'minute'),'time');
							    },
							    change: function(event, ui) {
								    $('#tpSelectedTime .selMins').effect('highlight', 1000);
							    }
						    });
                        }
                        else{
                            // Slider
                            $('#minuteSlider').slider({
                                orientation: "vertical",
                                range: 'min',
                                min: 0,
                                max: 45,
                                step: 15,
                                slide: function(event, ui) {
                                    writeDate(writeTime(ui.value,'minute'),'time');
                                },
                                change: function(event, ui) {
                                    $('#tpSelectedTime .selMins').effect('highlight', 1000);
                                }
                            });
                        }
                        

		//Inline editor bind
						$('#tpSelectedTime .selHrs').keyup(function(e){
							if((e.which <= 57 && e.which >= 48) && ($(this).text() >=1 && $(this).text() <=12 ) ){
							//console.log("Which: "+e.which);
						   $('#hourSlider').slider('value', parseInt($(this).text()));
							//console.log("Val: "+parseInt($(this).val()))
							}else{
								$(this).val($(this).text().slice(0, -1));
							}
							//if($(this).val() < 1){
							//    $(this).val(1);
							//}
						});

		//Inline editor bind
						$('#tpSelectedTime .selMins').keyup(function(e){
							if((e.which <= 57 && e.which >= 48) && ($(this).text() >=0 && $(this).text() <=59 ) ){
							//console.log("Which: "+e.which);
						   $('#minuteSlider').slider('value', parseInt($(this).text()));
							//console.log("Val: "+parseInt($(this).val()))
							}else{
								$(this).text($(this).text().slice(0, -1));
							}
							//if($(this).val() < 1){
							//    $(this).val(1);
							//}
						});
					}
					$('#text_time').text(loadedLang['time']);
					$('#text_hour').text(loadedLang['hour']);
					$('#text_minute').text(loadedLang['minute']);
					$('#text_close').text(loadedLang['close']);

					$('#pickerplug').data('userLang',lang_);
					$('#pickerplug').data('b24Hour',b24Hour_);
				}

				$(this).bind('focus',function(){

					var top 	= $(this).offset().top+$(this).outerHeight();
					var left 	= $(this).offset().left;

					if ($(this).data('userLang') 	!= $('#pickerplug').data('userLang') ||
						$(this).data('b24Hour') 	!= $('#pickerplug').data('userLang') ) {
						renderPickerPlug($(this).data('b24Hour'),$(this).data('userLang'));
					}

					$('#pickerplug').css({
										left: left+'px',
										top: top+'px'
										}).show('normal');

					if ($(this).data('userLang')!='en' && lang[$(this).data('userLang')]) {
						$('#datepicker').datepicker('option', $.extend({},
												$.datepicker.regional[$(this).data('userLang')]));
						$('#datepicker').datepicker('option', $.extend($(this).data('sets')));
					} else {
						$('#datepicker').datepicker('option', $.extend({},
												$.datepicker.regional['']));
						$('#datepicker').datepicker('option', $.extend($(this).data('sets')));
					}

					parseTime(this);

					if ($('#pickerplug').css('display') == 'none') {
						$('#pickerplug').show('normal');
					}

					$(this).bind('keyup',parseTime);
					//$(this).bind('slider',writeTime);

					$(this).addClass(markerClass);

					$('#pickerplug').data('inputfield',this);
				});


                function convertDate(myDate){
                    // need to change format from "yy-mm-dd" to "M dd, yy"
                    var tempDate = Array;
                    tempDate = myDate.split("-");

                    // no need to convert
                    if(tempDate.length <= 1){
                        return myDate;
                    }

                    var monthNames = Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
                    var newYear = tempDate[0];
                    var newMonth = monthNames[tempDate[1]-1];
                    var newDay = parseInt(tempDate[2],10);
                    return newMonth+' '+newDay+', '+newYear;
                }

                function convertTime(myTime){
                    // need to transform time to format "hh:nn:ss"
                    var tempTime = Array();
                    var tempHour = 0;
                    var tempMinute = 0;
                    var tempSecond = '00';

                    tempTime = myTime.split(":");
                    tempHour = parseInt(tempTime[0],10);
                    if(tempHour <= 9){
                        tempHour = '0' + tempHour;
                    }
                    tempMinute = parseInt(tempTime[1],10);
                    if(tempMinute <= 9){
                        tempMinute = '0' + tempMinute;
                    }
                    return tempHour+":"+tempMinute+":"+tempSecond;
                }

                function TrimWhitespace(str){
                    str = str.replace(/^\s+/, '');
                    for (var i = str.length - 1; i >= 0; i--) {
                        if (/\S/.test(str.charAt(i))) {
                            str = str.substring(0, i + 1);
                            break;
                        }
                    }
                    return str;
                }

                function RemoveNonNumericCharacters(myString){
                    // strip all non-numeric characters
                    var value = '';
                    var temp = TrimWhitespace(myString);
                    var myLength = temp.length;
                    var allowedCharacters = Array(0,1,2,3,4,5,6,7,8,9);
                    for(var position=0; position < myLength; position++){
                        var currentCharacter = temp[position];
                        if(allowedCharacters.indexOf(currentCharacter) !== -1){
                            value = value + currentCharacter;
                        }
                    }
                    return value;
                }

				function parseTime (obj) {
                    var tempTest = ($(obj).val() || $(this).val()).split(" ");
                    // make sure to parse the correct format
                    if(tempTest.length == 4){
                        // incoming format = mon dd, yyyy hh:nn:ss
                        var tempMonth = ''; // tempTest[0]
                        var tempDay = '';   // tempTest[1]
                        var tempYear = '';  // tempTest[2]
                        var tempTime = '';  // tempTest[3]
                        var time = {};

                        tempYear = tempTest[2];
                        switch(tempTest[0]){
                            case 'Jan' : tempMonth = '01'; break;
                            case 'Feb' : tempMonth = '02'; break;
                            case 'Mar' : tempMonth = '03'; break;
                            case 'Apr' : tempMonth = '04'; break;
                            case 'May' : tempMonth = '05'; break;
                            case 'Jun' : tempMonth = '06'; break;
                            case 'Jul' : tempMonth = '07'; break;
                            case 'Aug' : tempMonth = '08'; break;
                            case 'Sep' : tempMonth = '09'; break;
                            case 'Oct' : tempMonth = '10'; break;
                            case 'Nov' : tempMonth = '11'; break;
                            case 'Dec' : tempMonth = '12'; break;
                        }
                        tempDay = tempTest[1].substr(0,2);
                        tempTime = tempTest[3];
                        time[0] = tempYear+'-'+tempMonth+'-'+tempDay;
                        time[1] = tempTime;
                    }
                    else{
                        var time = ($(obj).val() || $(this).val()).split(" ");
                    }

					if (time.length < 2) {
                        var dateArray = new Date();
                        time[0] = dateArray.getFullYear()+'-'+(dateArray.getMonth()+1)+'-'+dateArray.getDate();
						time[1] = '00:00:00';
					}

                    // put the date and time into the widget for storage
					$('#pickerplug').data('lastdate',time[0]);	//lastdate = time[0];
					$('#pickerplug').data('lasttime',time[1]);  //lasttime = time[1];
					time = time[1].split(":");

					if (time.length < 2) {
						time = ['00','00','00'];
					}

					var hour	= time[0] || '00';
					var minute 	= time[1] || '00';

					writeTime(hour,'hour');
					writeTime(minute,'minute');

					$('#hourSlider').slider('option', 'value', hour);
					$('#minuteSlider').slider('option', 'value', minute);
					$('#datepicker').datepicker('setDate',
                        //$.datepicker.parseDate(datepicker_def['dateFormat'],$('#pickerplug').data('lastdate'))
                        $.datepicker.parseDate('yy-mm-dd',$('#pickerplug').data('lastdate'))
                    );
                    $('#datepicker').datepicker('option','dateFormat','M d, yy');
                    $('#datepicker').datepicker('option','yearRange','1890:2010');

				}

				function writeTime(fragment,type) {
					var time = '';
                    var displayHours = '';
                    var displayMinutes = '';
					switch (type) {
						case 'hour':
	                    	var hours = parseInt(fragment,10);
	                    	if(hours <=  9){
                                displayHours = '0' + hours;
	                    	}
                            else{
                                displayHours = hours;
	                    	}
	                    	$('#tpSelectedTime .selHrs').text(displayHours);
	                    	time = hours+':'+$('#tpSelectedTime .selMins').text();
							break;
						case 'minute':
                            var minutes = parseInt(fragment,10);
                            if(minutes <= 9){
                                displayMinutes = '0' + minutes;
                            }
                            else{
                                displayMinutes = minutes;
                            }
	                    	$('#tpSelectedTime .selMins').text(displayMinutes);
	                        time = $('#hourSlider').slider('option', 'value')+':'+displayMinutes;
							break;
					}
					return time;
				}

				function writeDate (text,type) {
                    var myTime = "";
                    var myDate = "";
                    if(type == 'time'){
                        myTime = convertTime(text);
                        $('#pickerplug').data('lasttime',myTime);
                        myDate = convertDate($('#pickerplug').data('lastdate'));
                    }
                    else{
                        myDate = convertDate(text);
                        $('#pickerplug').data('lastdate',myDate);
                        myTime = convertTime($('#pickerplug').data('lasttime'));
                    }
                    // put the date and time strings into the text field
					$($('#pickerplug').data('inputfield')).val(myDate+' '+myTime);
				}

				function closePickPlug (event) {
                    if($('#pickerplug').css('display') == 'none'){
                        return;
                    }
					if (($(event.target).parents('#pickerplug').length ||
						$(event.target).hasClass(markerClass)) &&
						!$(event.target).hasClass('ui-datepicker-close')) {
						return;
					}

					$('#pickerplug').hide('normal');
					$(this).unbind('click',closePickPlug);
					$(this).unbind('keyup',parseTime);
					$(this).removeClass(markerClass);
//                    if(DoEnableSave != undefined){
//                        DoEnableSave();
//                    }
				}

            });

           }
