/*!
* TimeTrackerv3
* http://timetracker.ctrl-al-shift.com/
*
* Copyright 2010, Sam Sargent
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Date:
*/
$(function ()
{
	
	window.onbeforeunload = confirmBrowseAway;
function confirmBrowseAway()
{
  if (!done) {
	  //$("#saveBtn").trigger('click');
	  
    return "You have a timer going - this will be lost and un-recoverable if you proceed...";
  }
}
	 

	
	if (Modernizr.localstorage){
		
   Storage.prototype.setObject = function (key, value)
    {
        this.setItem(key, JSON.stringify(value));
    }
    Storage.prototype.getObject = function (key)
    {
        return this.getItem(key) && JSON.parse(this.getItem(key));
    }
	
	/*for (i=0;i<localStorage.length;i++){
        key = localStorage.key(i);
		
		localStorage.get('priority1')
           
    }*/
	
	if (localStorage.length > 0) 
		loadPaused();
	
	if(localStorage.getItem('priority1') != null)
		$("#priority1").val(localStorage.getItem('priority1'));
	if(localStorage.getItem('priority2') != null)
		$("#priority2").val(localStorage.getItem('priority2'));
	if(localStorage.getItem('bottleneck') != null)
		$("#bottleneck").val(localStorage.getItem('bottleneck'));
	if(localStorage.getItem('followup') != null)
		$("#followup").val(localStorage.getItem('followup'));
	if(localStorage.getItem('notepad') != null)
		$("#notepadTextArea").val(localStorage.getItem('notepad'));
		
} else {
  humanMsg.displayMsg('<strong>Error:</strong> <span class="indent">Your browser doesn\'t support local storage.</span>');
}         
	
	
	 $("span.logSingleTimeRowBtn").live('click', function (ev)
    {
		var  timeID= $(this).parent().parent().attr('data-uid');
		var thisID = $(this).parent().parent().attr('id');
		
		$("#"+thisID).html('<td colspan="8">'+loadingDiv+'</td>');
		$.post("./push_time_to_basecamp", {
                action: 'pushTime',
                timeid: timeID
            }, function (data)
            {
				$("#"+thisID).replaceWith(data);
               	humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">Time Pushed to Basecamp</span>');
            });
		return false;
	});
	 
	 $("span.deleteSingleTimeRowBtn").live('click', function (ev)
    {
		var  timeID= $(this).parent().parent().attr('data-uid');
		var thisID = $(this).parent().parent().attr('id');
		
		$('body').prepend('<div id="dialog-confirm" title="Delete this entry?">'+
	'<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>This item will be permanently deleted and cannot be recovered. Are you sure?</p>'+
'</div>')
		
		
		$("#dialog-confirm").dialog({
			resizable: false,
			height:200,
			modal: true,
			buttons: {
				'Delete': function() {
			$("#"+thisID).html('<td colspan="8">'+loadingDiv+'</td>');
	$.post("./delete_single_time_row", {
                action: 'releteRow',
                id: timeID
            }, function (data)
            {
                $("#"+thisID).remove();
				$("table.#trackedTime > tbody > tr").removeClass("ui-state-default");
				$("table.#trackedTime > tbody > tr:odd").addClass("ui-state-default");
				humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">Delete row with ID '+timeID+'</span>');
            });
					$(this).dialog('close');
					$("#dialog-confirm").remove();
				},
				Cancel: function() {
					$(this).dialog('close');
					$("#dialog-confirm").remove();
				}
			}
		});
		
		return false;
		
	});
	 
	 $("#refreshProjectsCacheBtn").live('click', function (ev)
    	{
			 $("#refreshProjectsCacheBtn").replaceWith(loadingDiv);
				$.post("./refresh_projects_cache", {
                action: 'refreshCache',
            }, function (data)
            {
				var data = $("project", data).map(function() {
					var fullName = $("name:first", this).text();
					
					var budgetedHours = fullName.substring(fullName.indexOf('[')+1,fullName.lastIndexOf(']'));
			
					return {
						value: $("name:first", this).text() +" - "+ $("company name", this).text(),
						projectName: $("name:first", this).text(),
						id: $("id:first", this).text(),
						budget: budgetedHours,
						date: $("created-on", this).text(),
						company: $("company name", this).text()
					};
				}).get();
				
				 $("#loadingImage").replaceWith('<span style="cursor:pointer;" title="Refresh Projects Cache" id="refreshProjectsCacheBtn" class="ui-icon ui-icon-refresh"></span>');
				projectData = data;
				setupAutoComplete();
            });
			 
			
		});
	 
	 
	  $("#refreshToDoListsCacheBtn").live('click', function (ev)
    	{
			$("#todoListForProject").replaceWith(loadingDiv);
			$.post("./refresh_todo_list_cache_for_project", {
                action: 'refreshCache',
				projectID: $(this).attr('data-projectID')
            }, function (data)
            {
				 $("#loadingImage").replaceWith(data);
            });
		});
	
	 
	 
	 $("span.saveTimeRowBtn").live('click', function (ev)
    {
			var  timeID= $(this).parent().parent().attr('data-uid');
			var thisID = $(this).parent().parent().attr('id');
			
			
			
			var newprojectName = $("#edit-projectName-"+timeID).val();
			var newmemo = $("#edit-memo-"+timeID).val();
            var newstartTime = $("#edit-startTime-"+timeID).val();
            var newfinishTime = $("#edit-finishTime-"+timeID).val();
			var newtotalTime = $("#edit-totalTime-"+timeID).val();
            var newtimetolog = $("#edit-timetolog-"+timeID).val();
			var basecamptodoid = $("#edit-todoitemid-"+timeID).val();
            var todoitem = $("#edit-todoitemid-"+timeID+" :selected").text();
			
			var oldTotal = parseFormattedTime($("#daysRunningTotal").html());
			var newTotal = parseInt(oldTotal,10) + parseInt(newtimetolog,10);
			
			$("#daysRunningTotal").html(displayFormattedTimer(newTotal));
			$("#totalDisplay").html(displayFormattedTimer(newTotal));
			
	$("#"+thisID).html('<td colspan="8">'+loadingDiv+'</td>');

		 $.post("./update_single_time_row", {
                action: 'updateRow', 
                id: timeID,
				projectName: newprojectName,
                memo: newmemo,
                startTime: newstartTime,
                finishTime: newfinishTime,
                totalTime: newtotalTime,
                timetolog: newtimetolog,
				basecamptodoID: basecamptodoid,
				todoItem: todoitem
            }, function (data)
            {
                $("#"+thisID).replaceWith(data);
				humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">Updated row with ID '+timeID+'</span>');
				 $("table.#trackedTime > tbody > tr:odd").addClass("ui-state-default");
            });
		 		return false;
	});
	 
	 
	 
	 $("input.editRowInput").live('click', function(ev)
	{
			return false;											
	});
	
   $("span.editTimeRowBtn").live('click', function (ev)
    {
			var timeID= $(this).parent().parent().attr('data-uid');
			var thisID = $(this).parent().parent().attr('id');
			var thisTotal = $(this).parent().parent().attr('data-total');
			$("#"+thisID).html('<td colspan="8">'+loadingDiv+'</td>');
			
			var oldTotal = parseFormattedTime($("#daysRunningTotal").html());
			var newTotal = parseInt(oldTotal,10) - parseInt(thisTotal,10);
			
			$("#daysRunningTotal").html(displayFormattedTimer(newTotal));
			$("#totalDisplay").html(displayFormattedTimer(newTotal));
			
			 $.post("./get_single_time_row", {
                action: 'getRow',
                id: timeID
            }, function (data)
            {
                $("#"+thisID).replaceWith(data);
				humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">Switched to Edit Mode</span>');
            });
		return false;
    });
   
   $("span.resumeTimeRowBtn").live('click', function (ev)
    {
			var timeID= $(this).parent().parent().attr('data-uid');
			var thisID = $(this).parent().parent().attr('id');
			var oldTotal = parseFormattedTime($("#daysRunningTotal").html());
			var newTotal = parseInt(oldTotal,10) - parseInt($(this).parent().parent().attr('data-total'),10);
			$("#"+thisID).remove();
			
			$("#timeNshit").html(loadingDiv);
			
			
			
			
			$("#daysRunningTotal").html(displayFormattedTimer(newTotal));
			$("#totalDisplay").html(displayFormattedTimer(newTotal));
			
			 $.post("./resume_single_time_row", {
                action: 'getRow',
                timeid: timeID
            }, function (data)
            {
                $("#timeNshit").replaceWith(data);
				restartTimer($("#timer-display").html());
				$("#saveBtn").removeClass('ui-state-disabled');
				$("#clearBtn").removeClass('ui-state-disabled');
				humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">Switched to Resume Mode</span>');
								setupAutoComplete();
            });
		return false;
    });
   
   
	
	
    $(".dayToDo").live('keyup',function (event)
    {
        if (event.keyCode == '13')
        {
			var dayNum = $(this).attr('data-daynum');
			var id = $(this).attr('id');
            event.preventDefault();
			 $.post("./add_new_todo", {
				action: 'addNew',
				date: $(this).attr('id'),
				item: $(this).val()
			}, function (data)
			{
				humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">TODO item added!</span>');
				$("#toDoList-" + dayNum).append(data);
				$("#"+id).val('');
			}); 
        }
    });
		
	$("#deleteToDo").live('click', function (ev)
    {
			var  todoid= $(this).attr('rel');
			 $.post("./delete_todo_item", {
				action: 'deleteToDo',
				id: todoid
			}, function (data)
			{
					$("#todoitem-"+todoid).remove();
					humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">TODO item deleted!</span>');
			}); 
    });
	
	
	$("#completeToDo").live('click', function (ev)
    {
		var  todoid= $(this).attr('rel');
		
			 if ($("#todoitem-"+todoid).hasClass('ui-state-disabled'))
            {
                $("#todoitem-"+todoid).removeClass("ui-state-disabled");
				$.post("./todo_item_status", {
					complete: 0,
					id: todoid
				}, function (data)
				{
						humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">Completion status updated.</span>');
				}); 
            }
            else
            {
                $("#todoitem-"+todoid).addClass("ui-state-disabled");
					$.post("./todo_item_status", {
						complete: 1,
						id: todoid
					}, function (data)
					{
							humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">Todo item marked Complete!</span>');
					}); 
            }
    });
	
	/*
	
	        if (ev.type == 'click')
        {
           
        }
		
		*/
	
	
	
	$(".todoItem").live('hover click', function (ev)
    {
        if (ev.type == 'mouseover')
        {
            $(this).addClass("todo-ui-state-hover");
			$(this).append("<a id='deleteToDo' title='Delete' rel='"+$(this).attr('data-id')+"' class='ui-state-error'><span class='ui-icon ui-icon-trash'></span></a><a id='completeToDo' title='Mark Complete' rel='"+$(this).attr('data-id')+"' class='ui-state-error'><span class='ui-icon ui-icon-check'></span></a>");
        }
        if (ev.type == 'mouseout')
        {
            $(this).removeClass("todo-ui-state-hover");
			$("#deleteToDo").remove();
			$("#completeToDo").remove();
        }

    });
	
	
	
		$("#pushSelectedToBC").live('click', function(ev){
		
			if($(this).button( "option", "disabled")){
				log('disabled');
			}else{
				/*$.each(selectedEntries, function(index, value) { 
												 
				var int=self.setInterval("clock()",1000);
				
				  alert(index + ': ' + value); 
				});*/
				selectedCounter = 0;
				eachSelectedTimeEntryInterval = setInterval ( "clock()", 2000 ); 
				
				//log(selectedEntries.toString());
					
			}
			
								  
		}).button({
				  icons: {
					primary: 'ui-icon-transferthick-e-w'
				},
				disabled: true
			});
	
	
	$("#selectUnPushedTime").live('click', function(ev){
		 clearTotal();
		if ($(this).attr('checked') === true)
        {
			$('#trackedTime tbody tr').each(function (index)
			{
					if ($(this).attr('data-bc') == 'true' && $(this).attr('data-logged') == 'false')
					{
						if (!$(this).hasClass('ui-state-active'))
						{
							$(this).addClass("ui-state-active");
						}
					   //log($(this).attr('data-uid'));
						addTotal($(this).attr('data-total'),$(this).attr('data-uid'));
						var options = {};
						$("#selectedRunningTotal").effect('highlight',options,500);
					}
				});	
		}else
        {
            $('#trackedTime tbody tr').each(function (index)
            {
                if ($(this).hasClass('ui-state-active'))
                {
                    $(this).removeClass("ui-state-active");
                }
            });
        }
		
		if(selectedEntries.length > 0)
		{
			$("#pushSelectedToBC").removeClass('ui-state-disabled');
			$( "#pushSelectedToBC" ).button( "option", "disabled", false );
		}
		
								  
	}).button({
              icons: {
                primary: 'ui-icon-suitcase'
            }
        });
	
	
	
    $("#clearSelection").live('click', function (ev)
    {
        if (ev.type == 'click')
        {
            clearTotal();
            $('#trackedTime tbody tr').each(function (index)
            {
                if ($(this).hasClass('ui-state-active'))
                {
                    $(this).removeClass("ui-state-active");
                }
            });
			$("#selectAllTimes").attr('checked', '');
			$("#selectAllTimes + label").removeClass('ui-state-active');
        }
    }).button(
    {
        icons: {
            primary: 'ui-icon-cancel'
        }
    });
/*
$("#clearSelection").click(function(){
				clearTotal();
				
		$('#trackedTime tbody tr').each(function(index) {	
		if($(this).hasClass('ui-state-active'))
			{
				$(this).removeClass("ui-state-active");
			}
  	});
}).button({
              icons: {
                primary: 'ui-icon-cancel'
            }
        });*/
    $("#logSelectionToNetsuite").live('click', function ()
    {
		
			$.ajax({

   type: "POST",

   url: "./flag_selection_logged",

   data: "action=logToNetsuite&ids="+selectedEntries,

   success: function(msg){
	 log(msg);
	 humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">Selection logged to Netsuite</span>');

	                $('table#trackedTime tbody tr').each(function (index)
				{
					if ($(this).hasClass('ui-state-active'))
					{
						//$(this).removeClass('ui-state-active');
						$(this).addClass('ui-state-disabled');
		 
					}
				});

   }

            });
					 
       
    }).button(
    {
        icons: {
            primary: 'ui-icon-transferthick-e-w'
        }
    });
    $("#selectAllTimes").button(
    {
        icons: {
            primary: 'ui-icon-flag'
        }
    }).live('click', function ()
    {
        clearTotal();
        if ($(this).attr('checked') === true)
        {
            $('#trackedTime tbody tr').each(function (index)
            {
                //$(this).trigger('click');		
                if (!$(this).hasClass('ui-state-active'))
                {
                    $(this).addClass("ui-state-active");
                }
                addTotal($(this).attr('data-total'),$(this).attr('data-uid'));
            });
									var options = {};
					$("#selectedRunningTotal").effect('highlight',options,500);
        }
        else
        {
            $('#trackedTime tbody tr').each(function (index)
            {
                if ($(this).hasClass('ui-state-active'))
                {
                    $(this).removeClass("ui-state-active");
                }
            });
        }
    });
    $("table.#trackedTime > tbody > tr:odd").addClass("ui-state-default");
    $("#datepicker").datepicker(
    {
        onSelect: function (dateText, inst)
        {
            var splitDate = dateText.split('/');
			$("#trackedTimeContent").html(loadingDiv);
		var dateToGet = splitDate[2]+"-"+splitDate[0]+"-"+splitDate[1];
        $.post("./get_tracked_time_table", {
            action: 'getTrackedTimeTable',
            date: dateToGet
        }, function (data)
        {
            $("#trackedTimeContent").replaceWith(data);
            $("table.#trackedTime > tbody > tr:odd").addClass("ui-state-default");
            $("#clearSelection").button(
            {
                icons: {
                    primary: 'ui-icon-cancel'
                }
            });
            $("#selectAllTimes").button(
            {
                icons: {
                    primary: 'ui-icon-flag'
                }
            });
            $("#logSelectionToNetsuite").button(
            {
                icons: {
                    primary: 'ui-icon-transferthick-e-w'
                }
            });
        });
        }
    });
    $("table.#trackedTime > tbody > tr").live('hover click', function (ev)
    {
        if (ev.type == 'mouseover')
        {
            $(this).addClass("ui-state-hover");
        }
        if (ev.type == 'mouseout')
        {
            $(this).removeClass("ui-state-hover");
        }
        if (ev.type == 'click')
        {
            if ($(this).hasClass('ui-state-active'))
            {
                $(this).removeClass("ui-state-active");
                removeFromTotal($(this).attr('data-total'),$(this).attr('data-uid'));
						var options = {};
					$("#selectedRunningTotal").effect('highlight',options,500);
            }
            else
            {
                $(this).addClass("ui-state-active");
                addTotal($(this).attr('data-total'),$(this).attr('data-uid'));
						var options = {};
					$("#selectedRunningTotal").effect('highlight',options,500);
            }
        }
    });
	
	
	$("table.#searchResults > tbody > tr").live('hover click', function (ev)
    {
        if (ev.type == 'mouseover')
        {
            $(this).addClass("ui-state-hover");
        }
        if (ev.type == 'mouseout')
        {
            $(this).removeClass("ui-state-hover");
        }
        if (ev.type == 'click')
        {
            if ($(this).hasClass('ui-state-active'))
            {
                $(this).removeClass("ui-state-active");
                removeFromTotal($(this).attr('data-total'),$(this).attr('data-uid'));
            }
            else
            {
                $(this).addClass("ui-state-active");
                addTotal($(this).attr('data-total'),$(this).attr('data-uid'));
            }
        }
    });
	
    $("a.refreshBtn").live('hover click', function (ev)
    {
        if (ev.type == 'mouseover')
        {
            $(this).addClass("ui-state-active");
            $(this).removeClass("ui-state-highlight");
        }
        if (ev.type == 'mouseout')
        {
            $(this).removeClass("ui-state-active");
            $(this).addClass("ui-state-highlight");
        }
        if (ev.type == 'click')
        {
            var thisJob = localStorage.getObject($(this).attr('rel'));
            $("#startTimeValue").html(thisJob['startTimeValue']);
            $("#finishTimeValue").html(thisJob['finishTimeValue']);
            $("#timer-display").html(thisJob['timer-display']);
            $("#saveBtn").removeClass('ui-state-disabled');
			$("#clearBtn").removeClass('ui-state-disabled');
            //$("#startBtn").before("<div id='timeDetails'><label class='field'>Project ID</label><input type='text' class='prjName' id='prjName'/><br/><label class='field'>Memo</label><textarea class='prjMemo' id='prjMemo'></textarea><br/></div>");
            $("#prjMemo").val(thisJob['memo']);
            $("#prjName").val(thisJob['projectID']);
            restartTimer(thisJob['timer-display']);
            localStorage.removeItem($(this).attr('rel'));
			
			currentKeys = JSON.parse(localStorage.getItem('pausedKeys'));
			
			currentKeys.splice($.inArray(parseInt($(this).attr('rel'),10), currentKeys),1);
			
			
			localStorage.setItem('pausedKeys', JSON.stringify(currentKeys));
			
			
            $("#crrJb-" + $(this).attr('rel')).remove();
			humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">Paused job restarted!</span>');
        }
    });
    $("a.deleteBtn").live('hover click', function (ev)
    {
        if (ev.type == 'mouseover')
        {
            $(this).addClass("ui-state-active");
            $(this).removeClass("ui-state-error");
        }
        if (ev.type == 'mouseout')
        {
            $(this).removeClass("ui-state-active");
            $(this).addClass("ui-state-error");
        }
        if (ev.type == 'click')
        {
            //alert($(this).attr('rel'));
			humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">Paused job deleted!</span>');
            localStorage.removeItem($(this).attr('rel'));
			currentKeys = JSON.parse(localStorage.getItem('pausedKeys'));
			currentKeys.splice($.inArray(parseInt($(this).attr('rel'),10), currentKeys),1);
			localStorage.setItem('pausedKeys', JSON.stringify(currentKeys));
            $("#crrJb-" + $(this).attr('rel')).remove();
        }
    });
    $("#prjName").live("change", function ()
    {
        if ($("#prjName").val() != "") $("#saveBtn").removeClass('ui-state-disabled');
    });
    $("#editBtn").live('hover click', function (ev)
    {
        if (ev.type == 'mouseover')
        {
            $(this).addClass("ui-state-hover");
        }
        if (ev.type == 'mouseout')
        {
            $(this).removeClass("ui-state-hover");
        }
        if (ev.type == 'click')
        {
            log($(this));
        }
    });
    $(".portlet-header .closeportal").live('hover click', function (ev)
    {
        if (ev.type == 'mouseover')
        {
            $(this).addClass("ui-state-error");
        }
        if (ev.type == 'mouseout')
        {
            $(this).removeClass("ui-state-error");
        }
        if (ev.type == 'click')
        {
            $(this).parent().parent().remove();
        }
    });
    $("#searchBtn").button(
    {
        icons: {
            primary: 'ui-icon-search'
        }, text: false
    }).click(function ()
    {
        var searchBox = '<div class="rounded_box">' + '<div class="portlet-header ui-corner-all"><span class="ui-icon ui-icon-closethick closeportal"></span><span class="ui-icon ui-icon-minusthick minimise"></span><h2>Search Results - "' + $("#searchInput").val() + '"</h2></div>' +loadingDiv+ '<div>' + '<table id="searchResults"><thead><tr><th scope="col">Project ID</th><th scope="col">Date</th><th scope="col">Start</th><th scope="col">Finish</th><th scope="col">Total</th><th scope="col">Rounded</th><th scope="col">Memo</th>' + '<th scope="col">Options</th></tr></thead></table>' + '</div>' + '</div">';
        $("#wideColumn").prepend(searchBox);
		
        $.post("./search_for_time", {
            action: 'searchTime',
            searchTerm: $("#searchInput").val(),
            UserID: 1,
			page: 1
        }, function (data)
        {
						$("#loadingImage").remove();
            $("#searchResults").append(data);
			$("table#searchResults > tbody > tr:odd").addClass("ui-state-default");
			
			$("table#searchResults > tbody > tr").dblclick( function () { alert("Hello World!"); });
			
			
        });
    });
	
	 $("#searchInput").keyup(function (event)
    {
        if (event.keyCode == '13')
        {
            event.preventDefault();
             var searchBox = '<div class="rounded_box">' + '<div class="portlet-header ui-corner-all"><span class="ui-icon ui-icon-closethick closeportal"></span><span class="ui-icon ui-icon-minusthick minimise"></span><h2>Search Results - "' + $("#searchInput").val() + '"</h2></div>' +loadingDiv+ '<div>' + '<table id="searchResults"><thead><tr><th scope="col">Project ID</th><th scope="col">Date</th><th scope="col">Start</th><th scope="col">Finish</th><th scope="col">Total</th><th scope="col">Rounded</th><th scope="col">Memo</th>' + '<th scope="col">Options</th></tr></thead></table>' + '</div>' + '</div">';
        $("#wideColumn").prepend(searchBox);
        $.post("./search_for_time", {
            action: 'searchTime',
            searchTerm: $("#searchInput").val(),
            UserID: 1,
			page: 1
        }, function (data)
        {
			$("#loadingImage").remove();
            $("#searchResults").append(data);
			$("table#searchResults > tbody > tr:odd").addClass("ui-state-default");
        });
        }
    });
	 
	$("#priority1").change(function() {
 		localStorage.setItem('priority1', $(this).val());
	});
	
	$("#bottleneck").change(function() {
 		localStorage.setItem('bottleneck', $(this).val());
	});
	
	$("#followup").change(function() {
 		localStorage.setItem('followup', $(this).val());
	});
	
		$("#priority2").change(function() {
 		localStorage.setItem('priority2', $(this).val());
	});
	 
	 $("#notepadTextArea").change(function() {
 		localStorage.setItem('notepad', $(this).val());
	});
	 
	 
    $("#completeBtn").button(
    {
        icons: {
            primary: 'ui-icon-check'
        }
    }).click(function ()
    {
        var priorities = "1. " + $("#priority1").val() + "%0D2. " + $("#priority2").val() + "%0DBN. " + $("#bottleneck").val() + "%0DFU. " + $("#followup").val();
		localStorage.removeItem('priority1'); 
		localStorage.removeItem('priority2');
		localStorage.removeItem('bottleneck'); 
		localStorage.removeItem('followup');
$("#priority1").val("")
$("#priority2").val("")
$("#bottleneck").val("")
$("#followup").val("") 		
        $("#prioritiesBox").append('<a style="display:none;" href="mailto:'+$("#twocompletemailingList").val()+'?subject=2 Complete&body=' + priorities + '" id="emailLink">2 Complete</a>');
        window.location = $("#emailLink").attr('href');
        //
    });
    $("#previousDay").live('click', function ()
    {
        var currentDateWindow = $("#trackedTime").attr("data-date").split("-");
		$("#trackedTimeContent").html(loadingDiv);
		var yesterday = parseInt(currentDateWindow[2],10) - 1;
		var oDate = new Date();
		var previousDay = yesterday <= 0 ? (currentDateWindow[0] + '-' + (parseInt(currentDateWindow[1],10) - 1) + '-' + oDate.getDaysInMonth())  : (currentDateWindow[0] + '-' + currentDateWindow[1] + '-' + yesterday);
        $.post("./get_tracked_time_table", {
            action: 'get_tracked_time_table',
            date: previousDay
        }, function (data)
        {
            $("#trackedTimeContent").replaceWith(data);
            $("table.#trackedTime > tbody > tr:odd").addClass("ui-state-default");
            $("#clearSelection").button(
            {
                icons: {
                    primary: 'ui-icon-cancel'
                }
            });
            $("#selectAllTimes").button(
            {
                icons: {
                    primary: 'ui-icon-flag'
                }
            });
            $("#logSelectionToNetsuite").button(
            {
                icons: {
                    primary: 'ui-icon-transferthick-e-w'
                }
            });
			
			$("#pushSelectedToBC").button({
				  icons: {
					primary: 'ui-icon-transferthick-e-w'
				},
				disabled: true
			});
	
	
	$("#selectUnPushedTime").button({
              icons: {
                primary: 'ui-icon-suitcase'
            }
        });
        });
    });
    $("#nextDay").live('click', function ()
    {
        var currentDateWindow = $("#trackedTime").attr("data-date").split("-");
		$("#trackedTimeContent").html(loadingDiv);
		var tomorrow = parseInt(currentDateWindow[2],10) + 1;
		var oDate = new Date();
		var nextDay = tomorrow > oDate.getDaysInMonth() ? (currentDateWindow[0] + '-' + (parseInt(currentDateWindow[1],10) + 1) + '-' + 1)  : (currentDateWindow[0] + '-' + currentDateWindow[1] + '-' + tomorrow);
        $.post("./get_tracked_time_table", {
            action: 'get_tracked_time_table',
            date: nextDay
        }, function (data)
        {
            $("#trackedTimeContent").replaceWith(data);
            $("table.#trackedTime > tbody > tr:odd").addClass("ui-state-default");
            $("#clearSelection").button(
            {
                icons: {
                    primary: 'ui-icon-cancel'
                }
            });
            $("#selectAllTimes").button(
            {
                icons: {
                    primary: 'ui-icon-flag'
                }
            });
            $("#logSelectionToNetsuite").button(
            {
                icons: {
                    primary: 'ui-icon-transferthick-e-w'
                }
            });
			
			$("#pushSelectedToBC").button({
				  icons: {
					primary: 'ui-icon-transferthick-e-w'
				},
				disabled: true
			});
	
	
	$("#selectUnPushedTime").button({
              icons: {
                primary: 'ui-icon-suitcase'
            }
        });
			
			
        });
    });
	
	/*
	
	Next and Previous Weeks for TODO list
	
	*/
	$("a.toDoDateLink").live('click', function ()
    {
		$("#trackedTimeContent").html(loadingDiv);
	    $.post("./get_tracked_time_table", {
            action: 'get_tracked_time_table',
            date: $(this).attr('rel')
        }, function (data)
        {
            $("#trackedTimeContent").replaceWith(data);
            $("table.#trackedTime > tbody > tr:odd").addClass("ui-state-default");
            $("#clearSelection").button(
            {
                icons: {
                    primary: 'ui-icon-cancel'
                }
            });
            $("#selectAllTimes").button(
            {
                icons: {
                    primary: 'ui-icon-flag'
                }
            });
            $("#logSelectionToNetsuite").button(
            {
                icons: {
                    primary: 'ui-icon-transferthick-e-w'
                }
            });
        });
    });
	
	
	$("#previousWeek").live('click', function ()
    {
        var currentDateWindow = $("#toDoList").attr("data-date").split("-");
		$("#todoContent").html(loadingDiv);
		var yesterday = parseInt(currentDateWindow[2],10) - 7;
		var oDate = new Date();
		var previousWeek = yesterday <= 0 ? (currentDateWindow[0] + '-' + (parseInt(currentDateWindow[1],10) - 1) + '-' + oDate.getDaysInMonth())  : (currentDateWindow[0] + '-' + currentDateWindow[1] + '-' + yesterday);
        $.post("./get_to_do_table", {
            action: 'get_to_do_table',
            date: previousWeek
        }, function (data)
        {
           $("#todoContent").replaceWith(data);
        });
    });
    $("#nextWeek").live('click', function ()
    {
        var currentDateWindow = $("#toDoList").attr("data-date").split("-");
		$("#todoContent").html(loadingDiv);
		var tomorrow = parseInt(currentDateWindow[2],10) + 7;
		var oDate = new Date();
		var nextWeek = tomorrow > oDate.getDaysInMonth() ? (currentDateWindow[0] + '-' + (parseInt(currentDateWindow[1],10) + 1) + '-' + 1)  : (currentDateWindow[0] + '-' + currentDateWindow[1] + '-' + tomorrow);
        $.post("./get_to_do_table", {
            action: 'get_to_do_table',
            date: nextWeek
        }, function (data)
        {
            $("#todoContent").replaceWith(data);
        });
    });
	
	$('#prjName').live('blur',function(){
			if($(this).val() != "" && done){
			//log("bluring");
			$("#startBtn").trigger('click');
			}else{
				//log('already started or empy');	
			}
	});
	
	
	function setupAutoComplete()
	{
		
		$("#prjName").autocomplete({
					source: projectData,
					minLength: 2,
					select: function(event, ui) {
					//$("#startBtn").trigger('click');
					//$("#results").html("<br/>Fetching Details...<br/>"+loadingDiv);
						log(ui.item ? ("Selected: " + ui.item.value + ", projectID: " + ui.item.id) : "Nothing selected, input was " + this.value);
						 $("#projectID").val(ui.item.id);
								$("#prjName").after(loadingDiv);
								
								$.post("./get_todo_lists_for_project_from_cache", { action: "getProjectDetails", projectID: ui.item.id, budget:  ui.item.budget, projectName: ui.item.projectName, createdDate: ui.item.date},
   								function(data){
									$("#loadingImage").remove();
									$("#prjName").after("<input type='hidden' value='"+ui.item.id+"' id='basecampProjectID'/>" + data + "<span style=\"cursor:pointer;\" title=\"Refresh ToDo Lists Cache\" id=\"refreshToDoListsCacheBtn\" data-projectID=\""+ui.item.id+"\" class=\"ui-icon ui-icon-refresh\"></span>");
									
					$.post("./get_project_details_from_cache", { action: "getProjectDetails", style: 'tooltip', status:  'active', projectID: ui.item.id, budget:  ui.item.budget, projectName: ui.item.projectName, createdDate: ui.item.date},
   								function(data){
								$("#projectInfoTooltip").qtip({
									 content: data, // Use the tooltip attribute of the element for the content
									    position: {
										  corner: {
											 target: 'bottomRight',
											 tooltip: 'topLeft'
										  }
									   },
									 style: { 
										  width: 200,
										  padding: 5,
										  background: '#ffffff',
										  color: 'black',
										  textAlign: 'center',
										  border: {
											 width: 7,
											 radius: 5,
											 color: '#ffffff'
										  },
										   tip: 'topLeft',
										  name: 'dark' // Inherit the rest of the attributes from the preset dark style
									   },
									 show: { ready: true }
								  });
								});
								});
					}
				});
		
		
	}
	
	
    $("#startBtn").button(
    {
        icons: {
            primary: 'ui-icon-play'
        }
    }).click(function ()
    {
        var options;
        if ($(this).text() == 'Start' || $(this).text() == 'Resume')
        {
            options =
            {
                label: 'Pause',
                icons: {
                    primary: 'ui-icon-pause'
                }
            };
            //$(this).before("<div id='timeDetails'><label class='field'>Project ID</label><input type='text' class='prjName' id='prjName'/><br/><label class='field'>Memo</label><textarea class='prjMemo' id='prjMemo'></textarea><br/></div>");
            //$("#prjName").focus();
			
			
			if(done)
			{
				startTimer();
				var todaysDate = new Date();
				var month = (todaysDate.getMonth()+1);
				month = month < 10 ? "0"+month : month;
				var todaysDateString = todaysDate.getFullYear() + '-' + month + '-' + todaysDate.getDate();
				/*if ($("#trackedTime").attr("data-date") != todaysDateString)
				{
					$("#trackedTimeContent").html(loadingDiv);
					$.post("./get_tracked_time_table", {
						action: 'getTrackedTimeTable'
					}, function (data)
					{
						$("#trackedTimeContent").replaceWith(data);
						$("table.#trackedTime > tbody > tr:odd").addClass("ui-state-default");
						$("#clearSelection").button(
						{
							icons: {
								primary: 'ui-icon-cancel'
							}
						});
						$("#selectAllTimes").button(
						{
							icons: {
								primary: 'ui-icon-flag'
							}
						});
						$("#logSelectionToNetsuite").button(
						{
							icons: {
								primary: 'ui-icon-transferthick-e-w'
							}
						});
					});
				}*/
			}else{
				//restart the timer
				restartTimer($("#timer-display").html());
			}
        }
        else
        {
            if ($("#prjName").val() == "")
            {
                $("#prjName").focus();
                $("#prjName").addClass('error');
                return false;
            }
            else
            {
				var btnLabel = '';
				if(done)
				btnLabel = "Start";
				else
				btnLabel = "Resume";
				
                options =
                {
                    label: btnLabel,
                    icons: {
                        primary: 'ui-icon-play'
                    }
                };
                //$("#saveBtn").addClass('ui-state-disabled');
                pauseTimer();
				//resetProjectTimerFields();
            }
        }
        $(this).button('option', options);
    });
    $("#saveBtn").button(
    {
        icons: {
            primary: 'ui-icon-disk'
        }
    }).click(function ()
    {
        if ($(this).hasClass('ui-state-disabled'))
        {
        }
        else
        {
			$(".qtip").remove();
					$("#refreshToDoListsCacheBtn").remove();
            var totalTimeInMinutes = stopTimer();
			var oldTotal = parseFormattedTime($("#daysRunningTotal").html());
			var newTotal = parseInt(oldTotal,10) + parseInt(totalTimeInMinutes,10);
			$("#daysRunningTotal").html(displayFormattedTimer(newTotal));
			    $("#totalDisplay").html(displayFormattedTimer(newTotal));
					var options = {};
	$("#daysRunningTotal").effect('highlight',options,500);
			oldTotal = parseFormattedTime($("#weeksRunningTotal").html());
			newTotal = parseInt(oldTotal,10) + parseInt(totalTimeInMinutes,10);
			$("#weeksRunningTotal").html(displayFormattedTimer(newTotal));
			$("#weeksRunningTotal").effect('highlight',options,500);
			var todaysDate = new Date();
			$("#timeDetails").slideUp();
			$("#trackedTime").append("<tr id='loadingRow'><td colspan='8'>"+loadingDiv+"</td></tr>")
            $.post("./save_new_time", {
                action: 'saveTime',
                date: todaysDate.getFullYear()+'-'+(todaysDate.getMonth()+1)+'-'+todaysDate.getDate(),
                projectName: $("#prjName").val(),
                memo: $("#prjMemo").val(),
                startTime: $("#startTimeValue").html(),
                finishTime: $("#finishTimeValue").html(),
                totalTime: $("#timer-display").html(),
                NetSuiteTime: totalTimeInMinutes,
				basecampProjectID: $("#basecampProjectID").val(),
				todoid: $("#todoListForProject").val(),
				todoitem: $("#todoListForProject :selected").text()
            }, function (data)
            {
				$("#loadingRow").remove();
                $("#trackedTime").append(data);
				
				resetProjectTimerFields();
				$("#timeDetails").slideDown();
            $("table.#trackedTime > tbody > tr:odd").addClass("ui-state-default");
				humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">Project Time Saved!</span>');
            });
            
            				//$("#timeDetails").remove();
            options =
            {
                label: 'Start',
                icons: {
                    primary: 'ui-icon-play'
                }
            };
            $("#startBtn").button('option', options);
            $("#saveBtn").addClass('ui-state-disabled');
            resetTimer();
        }
        //sessionStorage.testingVar = "hello";
    }).addClass('ui-state-disabled');
	
	
	function resetProjectTimerFields()
	{
		$("#prjName").attr('value', '');
		$("#prjMemo").val('');
		$("#basecampProjectID").remove();
		resetTimer();
		$("#clearBtn").addClass('ui-state-disabled');
		$("#todoListForProject").remove();
		
	}
	
	
	$("#clearBtn").button(
    {
        icons: {
            primary: 'ui-icon-cancel'
        }
    }).click(function (){
		
		
		$('body').prepend('<div id="dialog-confirm-clear" title="Clear this timer?">'+
	'<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>This timer will be permanently cleared and cannot be recovered. Are you sure?</p>'+
'</div>');
		
		
		$("#dialog-confirm-clear").dialog({
			resizable: false,
			height:200,
			modal: true,
			buttons: {
				'Yes': function() {
					$("#prjName").val('');
					$("#prjMemo").val('');
					$("#todoListForProject").slideUp(); 
					 clearInterval(SV);
					resetTimer();
					$(".qtip").remove();
					$("#refreshToDoListsCacheBtn").remove();
					
					
					options =
					{
						label: 'Start',
						icons: {
							primary: 'ui-icon-pause'
						}
					};
					$("#startBtn").button('option', options);
	
					$("#clearBtn").addClass('ui-state-disabled');
					$("#saveBtn").addClass('ui-state-disabled');
					
					$(this).dialog('close');
					$("#dialog-confirm-clear").remove();
				},
				Cancel: function() {
					$(this).dialog('close');
					$("#dialog-confirm").remove();
				}
			}
		});
		
		
		
		
	}).addClass('ui-state-disabled');
});
var sec = 0;
var min = 0;
var hour = 0;
var startTime;
var finishTime;
var formElement;
var SV;
var day = 0;
var done = true;
var state = 1;
var projectName = null;
var totalTime = null;
var pause = true;
var currentJobs = new Array();
var currentJobsCounter = 0;

var todaysTotal = 0;
var thisWeeksTotal = 0;

var selectedEntries = new Array();

var currentKeys = new Array();
var projectData = ""; 	

function pauseTimer()
{
	/*
    var jobObject =
    {
        'projectID': $("#prjName").val(),
        'memo': $("#prjMemo").val(),
        'startTimeValue': $("#startTimeValue").html(),
        'finishTimeValue': $("#finishTimeValue").html(),
        'timer-display': $("#timer-display").html(),
        'rounded': displayFormatted(stopTimer())
    };
    //currentJobs[currentJobsCounter] = testObject;
    localStorage.setObject(currentJobsCounter, jobObject);
	currentKeys.push(currentJobsCounter);
	localStorage.setItem('pausedKeys', JSON.stringify(currentKeys));
	
	
	
    var row = "<tr id='crrJb-" + currentJobsCounter + "'>" + "<td>" + jobObject['projectID'].substr(0, 5) + "</td>" + "<td>" + jobObject['startTimeValue'] + "</td>" + "<td>" + jobObject['finishTimeValue'] + "</td>" + "<td>" + jobObject['timer-display'] + "</td>" + "<td><a rel='" + currentJobsCounter + "' id='restart-" + currentJobsCounter + "' title='Resume Timer' class='refreshBtn ui-state-highlight'><span class='ui-icon ui-icon-arrowrefresh-1-s'></span></a><a id='delete-" + currentJobsCounter + "' title='Delete' rel='" + currentJobsCounter + "' class='deleteBtn ui-state-error'><span class='ui-icon ui-icon-trash'></span></a></td>" + "</tr>";
    currentJobsCounter++;
    $("#currentJobs").append(row);
    //$("#timeDetails").remove();
    resetTimer();*/
	
	  clearInterval(SV);
}
function loadPaused()
{
    var i = 0;
    var temp = null;
	var currentPaused = new Array();
	
	if(localStorage.getItem('pausedKeys') != null)
	{
	
	currentPaused = JSON.parse(localStorage.getItem('pausedKeys'));
	
	$.each(currentPaused, function() {
				temp = localStorage.getObject(this);						
	var row = "<tr id='crrJb-" + this + "'>" + "<td>" + temp['projectID'].substr(0, 5) + "</td>" + "<td>" + temp['startTimeValue'] + "</td>" + "<td>" + temp['finishTimeValue'] + "</td>" + "<td>" + temp['timer-display'] + "</td>" + "<td class='optionsCol'><a rel='" + this + "' id='restart-" + this + "' title='Resume Timer' class='refreshBtn ui-state-highlight'><span class='ui-icon ui-icon-arrowrefresh-1-s'></span></a><a id='delete-" + this + "' title='Delete' rel='" + this + "' class='deleteBtn ui-state-error'><span class='ui-icon ui-icon-trash'></span></a></td>" + "</tr>";
        $("#currentJobs").append(row);																		
      i++;
   });
   }
	

/*
  localStorage.setObject(currentJobsCounter, testObject);
		
					 
			
			currentJobsCounter++;
			$("#currentJobs").append(row);
	*/
}

var eachSelectedTimeEntryInterval; 
	var selectedCounter = 0;
	
	function clock(){
		if(selectedEntries[selectedCounter] == null){
				clearInterval(eachSelectedTimeEntryInterval);
				log('Done!');
					return false;
			}
	 
	 	var todaysDate = new Date();
		var month = (todaysDate.getMonth()+1);
		
		if(month < 10)
			month = '0'+month;
			
		var day = (todaysDate.getDate());
		
		if(day < 10)
			day = '0'+day;
		
		var thisDate = todaysDate.getFullYear()+''+month+''+day;
	 	log("#"+selectedEntries[selectedCounter]+"-"+thisDate);

		$("#"+selectedEntries[selectedCounter]+"-"+thisDate).html('<td colspan="8">'+loadingDiv+'</td>');
		var thisID = "#"+selectedEntries[selectedCounter]+"-"+thisDate;
		$.post("./push_time_to_basecamp", {
                action: 'pushTime',
                timeid: selectedEntries[selectedCounter]
            }, function (data)
            {
				log(thisID);
				$(thisID).replaceWith(data);
               	humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">Time Pushed to Basecamp</span>');
            });
	 
	 
		log(selectedEntries[selectedCounter].toString());
		selectedCounter++;
	}
	
function parseTimer(timerValue)
{
    var times = timerValue.split(":");
    hour = parseInt(times[0],10);
    min = parseInt(times[1],10);
    sec = parseInt(times[2],10);
}

function parseFormattedTime(formattedTime)
{
    var times = formattedTime.split(":");
    var itsnowminutes = parseInt(times[0],10) * 60
	itsnowminutes += parseInt(times[1],10);
	
	return itsnowminutes; 
}

function parseTimeString(timeString)
{
	return times = timeString.split(":");
}

function restartTimer(timerValue)
{
    //console.info("restartTime("+edtRowNum+")");
    //sec = 0; min = 0; hour = 0; rmin = 0; rhour = 0;
    options =
    {
        label: 'Pause',
        icons: {
            primary: 'ui-icon-pause'
        }
    };
    $("#startBtn").button('option', options);
    parseTimer(timerValue);
    done = false;
    SV = self.setInterval('updateFinishTime()', 1000);
}
function startTimer()
{
	$("#clearBtn").removeClass('ui-state-disabled');	
    done = false;
    var currentTime = new Date();
    day = currentTime.getDay();
    startTime = currentTime;
    finishTime = null;
    var minutes = currentTime.getMinutes();
    if (minutes < 10) minutes = "0" + minutes; // add padding if required
    $("#startTimeValue").html(currentTime.getHours() + ":" + minutes);
    SV = self.setInterval('updateFinishTime()', 1000);
    return currentTime.getHours() + ":" + minutes;
}
function updateFinishTime()
{
    var currentTime = new Date();
    var minutes = currentTime.getMinutes();
    if (minutes < 10) minutes = "0" + minutes; // add padding if required
    $("#finishTimeValue").html(currentTime.getHours() + ":" + minutes);
    sec++;
    if (sec == 60)
    {
        sec = 0;
        min = min + 1;
    }
    else
    {
        min = min;
    }
    if (min == 60)
    {
        min = 0;
        hour += 1;
    }
    if (sec <= 9)
    {
        sec = "0" + sec;
    }
    {
        totalTime = ((hour <= 9) ? "0" + hour : hour) + ":" + ((min <= 9) ? "0" + min : min) + ":" + sec
        $("#timer-display").html(totalTime);
        $("#project-total-time").val(totalTime);
    }
}
function stopTimer()
{
    clearInterval(SV);
    var roundedTotal = null;
    if (hour == 0 && min <= 15)
    {
        roundedTotal = 15;
        //roundedTotal = "00:15:00";
    }
    else
    {
        min = Math.ceil(min / 5) * 5;
        if (min == 60)
        {
            min = 0;
            hour += 1;
        }
/*if (min < 10) 
			min = "0" + min;
		if (hour < 10) 
			hour = "0" + hour;*/
        //roundedTotal = hour+":"+min+":00";
        roundedTotal = (parseInt(hour,10) * 60) + min;
    }
/*$.post("saveProject.php", { projectName: projectName, date: $("#project-date").val(), startTime: $("#project-start-time").val(), finishTime: $("#project-finish-time").val(), totalTime: $("#project-total-time").val(), roundedTotalTime: roundedTotal, memo: $("#project-memo").val()},
	function(data){$("#day-<? echo($currDayNum); ?>").append("<li>"+projectName+"</li>");});
	*/
    sec = 0;
    min = 0;
    hour = 0;
    done = true;
    return roundedTotal;
}
function emailForm()
{
/*
var daReferrer = document.referrer;
var email = "sam.sargent@bluewiremedia.com.au";
var errorMsg = "here here here is the error error error error";
var subject = "Exception Error";
var body_message = "%0D%0D%0D%0DThank you "+name+" for submitting this error to us. Please tell us in the space above, what you were doing when the error occurred.%0D%0DReferring Page: "+daReferrer+" %0D%0DException Error Message:%0D-------------------------------------------%0D"+errorMsg;

var mailto_link = 'mailto:'+email+'?subject='+subject+'&body='+body_message;
*/
    window.location = $("#emailLink").attr('href');
}
var totalTimeToTrack = 0;
function displayFormatted(minutes)
{
    var hours = parseInt((minutes / 60),10);
    var mins = parseInt((minutes % 60),10);
    mins = mins < 10 ? "0" + mins : mins;
    hours = hours < 10 ? "0" + hours : hours;
    return hours + 'hrs ' + mins + 'mins';
}

function displayFormattedTimer(minutes)
{
    var hours = parseInt((minutes / 60),10);
    var mins = parseInt((minutes % 60),10);
    mins = mins < 10 ? "0" + mins : mins;
    hours = hours < 10 ? "0" + hours : hours;
    return hours + ':' + mins ;
}

function addTotal(newTime,selectedid)
{
    totalTimeToTrack = parseInt(totalTimeToTrack,10) + parseInt(newTime,10);
    $("#selectedRunningTotal").html(displayFormattedTimer(totalTimeToTrack));
	
	selectedEntries.push(selectedid);	
	//$("#selectedRunningTotal").after(selectedEntries.toString());
	log(selectedEntries.toString());
}
function removeFromTotal(newTime,selectedid)
{
    totalTimeToTrack = parseInt(totalTimeToTrack,10) - parseInt(newTime,10);
    $("#selectedRunningTotal").html(displayFormattedTimer(totalTimeToTrack));
	selectedEntries.splice(selectedEntries.indexOf(selectedid));
	//$("#selectedRunningTotal").after(selectedEntries.toString());
		log(selectedEntries.toString());
}

function resetTimer()
{
    sec = 0;
    min = 0;
    hour = 0;
    done = true;
    $("#startTimeValue").html('00:00');
    $("#finishTimeValue").html('00:00');
    $("#timer-display").html('00:00:00');
}
function clearTotal()
{
	selectedEntries = new Array();
    totalTimeToTrack = 0;
    $("#selectedRunningTotal").html('00:00');
	var options = {};
	$("#selectedRunningTotal").effect('highlight',options,500);
}
var loadingDiv = "<img src='http://beta.tracktime4.me/img/dots-white.gif' id='loadingImage' class='loadingImage'/>";
window.log = function ()
{
    var a = "history";
    log[a] = log[a] || [];
    log[a].push(arguments);
    window.console && console.log[console.firebug ? "apply" : "call"](console, Array.prototype.slice.call(arguments))
};
window.logargs = function (a)
{
    log(a, arguments.callee.caller.arguments)
};


Date.prototype.formatDate=function(sFormatString){try{var vError=null;var iNumArguments=arguments.length;if(!('getDayOfYear'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getDayOfYear');}
if(!('getDaysInMonth'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getDaysInMonth');}
if(!('getGMTOffset'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getGMTOffset');}
if(!('getLong12Hours'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getLong12Hours');}
if(!('getLong24Hours'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getLong24Hours');}
if(!('getLongDate'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getLongDate');}
if(!('getLongDayName'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getLongDayName');}
if(!('getLongMinutes'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getLongMinutes');}
if(!('getLongMonth'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getLongMonth');}
if(!('getLongMonthName'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getLongMonthName');}
if(!('getLongSeconds'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getLongSeconds');}
if(!('getMeridiem'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getMeridiem');}
if(!('getOrdinalSuffix'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getOrdinalSuffix');}
if(!('getRFC822Date'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getRFC822Date');}
if(!('getShort12Hours'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getShort12Hours');}
if(!('getShort24Hours'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getShort24Hours');}
if(!('getShortDayName'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getShortDayName');}
if(!('getShortMonth'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getShortMonth');}
if(!('getShortMonthName'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getShortMonthName');}
if(!('getShortYear'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getShortYear');}
if(!('getSwatchTime'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getSwatchTime');}
if(!('getTimeSeconds'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getTimeSeconds');}
if(!('getTimezone'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getTimezone');}
if(!('getTimezoneOffsetSeconds'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getTimezoneOffsetSeconds');}
if(!('getWeekOfYear'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.getWeekOfYear');}
if(!('isDaylightSavingsTime'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.isDaylightSavingsTime');}
if(!('isLeapYear'in this)){throw vError=new MethodNotAvailableException('Date.formatDate','Date.isLeapYear');}
if(iNumArguments!=1){throw vError=new IllegalArgumentException('Date.formatDate',1,iNumArguments);}
if(typeof sFormatString!='string'){throw vError=new TypeMismatchException('Date.formatDate','string',typeof sFormatString);}
var sDayOfYear=this.getDayOfYear();var sDaysInMonth=this.getDaysInMonth();var sGMTOffset=this.getGMTOffset();var sIsDaylightSavingsTime=this.isDaylightSavingsTime();var sIsLeapYear=this.isLeapYear();var sLong12Hours=this.getLong12Hours();var sLong24Hours=this.getLong24Hours();var sLongDate=this.getLongDate();var sLongDayName=this.getLongDayName();var sLongMinutes=this.getLongMinutes();var sLongMonth=this.getLongMonth();var sLongMonthName=this.getLongMonthName();var sLongSeconds=this.getLongSeconds();var sMeridiem=this.getMeridiem();var sOrdinalSuffix=this.getOrdinalSuffix();var sRFC822Date=this.getRFC822Date();var sShort12Hours=this.getShort12Hours();var sShort24Hours=this.getShort24Hours();var sShortDayName=this.getShortDayName();var sShortMonth=this.getShortMonth();var sShortMonthName=this.getShortMonthName();var sShortYear=this.getShortYear();var sSwatchTime=this.getSwatchTime();var sTimeSeconds=this.getTimeSeconds();var sTimezone=this.getTimezone();var sTimezoneOffsetSeconds=this.getTimezoneOffsetSeconds();var sWeekOfYear=this.getWeekOfYear();if(!sDayOfYear||!sDaysInMonth||!sGMTOffset||!sIsDaylightSavingsTime||!sIsLeapYear||!sLong12Hours||!sLong24Hours||!sLongDate||!sLongDayName||!sLongMinutes||!sLongMonth||!sLongMonthName||!sLongSeconds||!sMeridiem||!sOrdinalSuffix||!sRFC822Date||!sShort12Hours||!sShort24Hours||!sShortDayName||!sShortMonth||!sShortMonthName||!sShortYear||!sSwatchTime||!sTimeSeconds||!sTimezone||!sTimezoneOffsetSeconds||!sWeekOfYear){throw vError=new UnknownException('Date.formatDate');}
var sFormatStringLength=sFormatString.length;var sFormattedDate='';for(var i=0;i<sFormatStringLength;i++){var sChar=sFormatString.charAt(i);switch(sChar){case'a':sFormattedDate+=sMeridiem;break;case'A':sFormattedDate+=sMeridiem.toUpperCase();break;case'B':sFormattedDate+=sSwatchTime;break;case'd':sFormattedDate+=sLongDate;break;case'D':sFormattedDate+=sShortDayName;break;case'F':sFormattedDate+=sLongMonthName;break;case'g':sFormattedDate+=sShort12Hours;break;case'G':sFormattedDate+=sShort24Hours;break;case'h':sFormattedDate+=sLong12Hours;break;case'H':sFormattedDate+=sLong24Hours;break;case'i':sFormattedDate+=sLongMinutes;break;case'I':sFormattedDate+=sIsDaylightSavingsTime;break;case'j':sFormattedDate+=this.getDate().toString();break;case'l':sFormattedDate+=sLongDayName;break;case'L':sFormattedDate+=sIsLeapYear;break;case'm':sFormattedDate+=sLongMonth;break;case'M':sFormattedDate+=sShortMonthName;break;case'n':sFormattedDate+=sShortMonth;break;case'O':sFormattedDate+=sGMTOffset;break;case'r':sFormattedDate+=sRFC822Date;break;case's':sFormattedDate+=sLongSeconds;break;case'S':sFormattedDate+=sOrdinalSuffix;break;case't':sFormattedDate+=sDaysInMonth;break;case'T':sFormattedDate+=sTimezone;break;case'U':sFormattedDate+=sTimeSeconds;break;case'w':sFormattedDate+=this.getDay().toString();break;case'W':sFormattedDate+=sWeekOfYear;break;case'y':sFormattedDate+=sShortYear;break;case'Y':sFormattedDate+=this.getFullYear().toString();break;case'z':sFormattedDate+=sDayOfYear;break;case'Z':sFormattedDate+=sTimezoneOffsetSeconds;break;default:sFormattedDate+=sChar;}}}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sFormattedDate;}}
Date.prototype.getDayOfYear=function(){try{var vError=null;var iNumArguments=arguments.length;if(!('isLeapYear'in this)){throw vError=new MethodNotAvailableException('Date.getDayOfYear','Date.isLeapYear');}
if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getDayOfYear',0,iNumArguments);}
var iMonth=this.getMonth();var sIsLeapYear=this.isLeapYear();if(!sIsLeapYear){throw vError=new UnknownException('Date.getDayOfYear');}
var iDaysInFebruary=(parseInt(sIsLeapYear)==1)?29:28;var aDaysInMonth=new Array(31,iDaysInFebruary,31,30,31,30,31,31,30,31,30,31);var iDayOfYear=0;for(var i=0;i<iMonth;i++){iDayOfYear+=aDaysInMonth[i];}
iDayOfYear+=this.getDate();var sDayOfYear=iDayOfYear.toString();}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sDayOfYear;}}
Date.prototype.getDaysInMonth=function(){try{var vError=null;var iNumArguments=arguments.length;if(!('isLeapYear'in this)){throw vError=new MethodNotAvailableException('Date.getDaysInMonth','Date.isLeapYear');}
if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getDaysInMonth',0,iNumArguments);}
var iMonth=this.getMonth();var sIsLeapYear=this.isLeapYear();if(!sIsLeapYear){throw vError=new UnknownException('Date.getDaysInMonth');}
switch(iMonth){case 1:var iDaysInMonth=(parseInt(sIsLeapYear)==1)?29:28;break;case 3:case 5:case 8:case 10:var iDaysInMonth=30;break;default:var iDaysInMonth=31;}
var sDaysInMonth=iDaysInMonth.toString();}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sDaysInMonth;}}
Date.prototype.getDaysInYear=function(){try{var vError=null;var iNumArguments=arguments.length;if(!('isLeapYear'in this)){throw vError=new MethodNotAvailableException('Date.getDaysInYear','Date.isLeapYear');}
if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getDaysInYear',0,iNumArguments);}
var sIsLeapYear=this.isLeapYear();if(!sIsLeapYear){throw vError=new UnknownException('Date.getDaysInYear');}
var sDaysInYear=(sIsLeapYear=='1')?'366':'365';}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sDaysInYear;}}
Date.prototype.getEasterDay=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getEasterDate',0,iNumArguments);}
var iYear=this.getFullYear();var a=iYear%19;var b=Math.floor(iYear/100);var c=iYear%100;var d=Math.floor(b/4);var e=b%4;var f=Math.floor((b+8)/25);var g=Math.floor((b-f+1)/3);var h=(19*a+b-d-g+15)%30;var i=Math.floor(c/4);var k=c%4;var l=(32+2*e+2*i-h-k)%7;var m=Math.floor((a+11*h+22*l)/451);var p=(h+l-7*m+114)%31;var iEasterDay=p+1;}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:iEasterDay;}}
Date.prototype.getEasterMonth=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getEasterMonth',0,iNumArguments);}
var iYear=this.getFullYear();var a=iYear%19;var b=Math.floor(iYear/100);var c=iYear%100;var d=Math.floor(b/4);var e=b%4;var f=Math.floor((b+8)/25);var g=Math.floor((b-f+1)/3);var h=(19*a+b-d-g+15)%30;var i=Math.floor(c/4);var k=c%4;var l=(32+2*e+2*i-h-k)%7;var m=Math.floor((a+11*h+22*l)/451);var iEasterMonth=Math.floor((h+l-7*m+114)/31);}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:iEasterMonth;}}
Date.prototype.getGMTOffset=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getGMTOffset',0,iNumArguments);}
var iTimezoneOffset=this.getTimezoneOffset();var iAbsTimezoneOffset=Math.abs(iTimezoneOffset);var sTimezoneOffsetSign=(iTimezoneOffset!=iAbsTimezoneOffset)?'-':'+';var iTimezoneOffsetHours=iAbsTimezoneOffset/60;var sTempTimezoneOffsetHours=iTimezoneOffsetHours.toString();var sTimezoneOffsetHours=(iTimezoneOffsetHours<10)?'0'+sTempTimezoneOffsetHours:sTempTimezoneOffsetHours;var iTimezoneOffsetMinutes=iAbsTimezoneOffset%60;var sTempTimezoneOffsetMinutes=iTimezoneOffsetMinutes.toString();var sTimezoneOffsetMinutes=(iTimezoneOffsetMinutes<10)?'0'+sTempTimezoneOffsetMinutes:sTempTimezoneOffsetMinutes;var sGMTOffset=sTimezoneOffsetSign+sTimezoneOffsetHours+sTimezoneOffsetMinutes;}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sGMTOffset;}}
Date.prototype.getLong12Hours=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getLong12Hours',0,iNumArguments);}
var iShort12Hours=this.getHours()%12;var sLong12Hours=iShort12Hours.toString();if(iShort12Hours==0){sLong12Hours='12';}else if(iShort12Hours<10){sLong12Hours='0'+sLong12Hours;}}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sLong12Hours;}}
Date.prototype.getLong24Hours=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getLong24Hours',0,iNumArguments);}
var iShort24Hours=this.getHours();var sLong24Hours=iShort24Hours.toString();if(iShort24Hours<10){sLong24Hours='0'+sLong24Hours;}}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sLong24Hours;}}
Date.prototype.getLongDate=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getLongDate',0,iNumArguments);}
var iShortDate=this.getDate();var sLongDate=iShortDate.toString();if(iShortDate<10){sLongDate='0'+sLongDate;}}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sLongDate;}}
Date.prototype.getLongDayName=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getLongDayName',0,iNumArguments);}
var aLongDayNames=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');var sLongDayName=aLongDayNames[this.getDay()];}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sLongDayName;}}
Date.prototype.getLongMinutes=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getLongMinutes',0,iNumArguments);}
var iShortMinutes=this.getMinutes();var sLongMinutes=iShortMinutes.toString();if(iShortMinutes<10){sLongMinutes='0'+sLongMinutes;}}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sLongMinutes;}}
Date.prototype.getLongMonth=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getLongMonth',0,iNumArguments);}
var iShortMonth=this.getMonth()+1;var sLongMonth=iShortMonth.toString();if(iShortMonth<10){sLongMonth='0'+sLongMonth;}}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sLongMonth;}}
Date.prototype.getLongMonthName=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getLongMonthName',0,iNumArguments);}
var aLongMonthNames=new Array('January','February','March','April','May','June','July','August','September','October','November','December');var sLongMonthName=aLongMonthNames[this.getMonth()];}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sLongMonthName;}}
Date.prototype.getLongSeconds=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getLongSeconds',0,iNumArguments);}
var iShortSeconds=this.getSeconds();var sLongSeconds=iShortSeconds.toString();if(iShortSeconds<10){sLongSeconds='0'+sLongSeconds;}}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sLongSeconds;}}
Date.prototype.getMeridiem=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getMeridiem',0,iNumArguments);}
var sMeridiem=(this.getHours()<12)?'am':'pm';}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sMeridiem;}}
Date.prototype.getOrdinalSuffix=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getOrdinalSuffix',0,iNumArguments);}
switch(this.getDate()){case 1:case 21:case 31:var sOrdinalSuffix='st';break;case 2:case 22:var sOrdinalSuffix='nd';break;case 3:case 23:var sOrdinalSuffix='rd';break;default:var sOrdinalSuffix='th';}}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sOrdinalSuffix;}}
Date.prototype.getRFC822Date=function(){try{var vError=null;var iNumArguments=arguments.length;if(!('getGMTOffset'in this)){throw vError=new MethodNotAvailableException('Date.getRFC822Date','Date.getGMTOffset');}
if(!('getLong24Hours'in this)){throw vError=new MethodNotAvailableException('Date.getRFC822Date','Date.getLong24Hours');}
if(!('getLongMinutes'in this)){throw vError=new MethodNotAvailableException('Date.getRFC822Date','Date.getLongMinutes');}
if(!('getLongSeconds'in this)){throw vError=new MethodNotAvailableException('Date.getRFC822Date','Date.getLongSeconds');}
if(!('getShortDayName'in this)){throw vError=new MethodNotAvailableException('Date.getRFC822Date','Date.getShortDayName');}
if(!('getShortMonthName'in this)){throw vError=new MethodNotAvailableException('Date.getRFC822Date','Date.getShortMonthName');}
if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getRFC822Date',0,iNumArguments);}
var sGMTOffset=this.getGMTOffset();var sLong24Hours=this.getLong24Hours();var sLongMinutes=this.getLongMinutes();var sLongSeconds=this.getLongSeconds();var sShortDayName=this.getShortDayName();var sShortMonthName=this.getShortMonthName();if(!sGMTOffset||!sLong24Hours||!sLongMinutes||!sLongSeconds||!sShortDayName||!sShortMonthName){throw vError=new UnknownException('Date.getRFC822Date');}
var sRFC822Date=sShortDayName+', '+this.getDate()+' '+sShortMonthName+' '+this.getFullYear()+' '+sLong24Hours+':'+sLongMinutes+':'+sLongSeconds+' '+sGMTOffset;}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sRFC822Date;}}
Date.prototype.getShort12Hours=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getShort12Hours',0,iNumArguments);}
var iTempShort12Hours=this.getHours()%12;var sShort12Hours=((iTempShort12Hours==0)?12:iTempShort12Hours).toString();}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sShort12Hours;}}
Date.prototype.getShort24Hours=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getShort24Hours',0,iNumArguments);}
var sShort24Hours=this.getHours().toString();}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sShort24Hours;}}
Date.prototype.getShortDayName=function(){try{var vError=null;var iNumArguments=arguments.length;if(!('getLongDayName'in this)){throw vError=new MethodNotAvailableException('Date.getShortDayName','Date.getLongDayName');}
if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getShortDayName',0,iNumArguments);}
var sLongDayName=this.getLongDayName();if(!sLongDayName){throw vError=new UnknownException('Date.getShortDayName');}
var sShortDayName=sLongDayName.substr(0,3);}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sShortDayName;}}
Date.prototype.getShortMonth=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getShortMonth',0,iNumArguments);}
var sShortMonth=(this.getMonth()+1).toString();}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sShortMonth;}}
Date.prototype.getShortMonthName=function(){try{var vError=null;var iNumArguments=arguments.length;if(!('getLongMonthName'in this)){throw vError=new MethodNotAvailableException('Date.getShortMonthName','Date.getLongMonthName');}
if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getShortMonthName',0,iNumArguments);}
var sLongMonthName=this.getLongMonthName();if(!sLongMonthName){throw vError=new UnknownException('Date.getShortMonthName');}
var sShortMonthName=sLongMonthName.substr(0,3);}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sShortMonthName;}}
Date.prototype.getShortYear=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getShortYear',0,iNumArguments);}
var sShortYear=this.getFullYear().toString().substr(2);}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sShortYear;}}
Date.prototype.getSwatchTime=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getSwatchTime',0,iNumArguments);}
var iTempSwatchTime=Math.floor(((this.getHours()*3600)+((this.getMinutes()+this.getTimezoneOffset()+60)*60)+this.getSeconds())/86.4);var iSwatchTime=(iTempSwatchTime>=1000)?iTempSwatchTime-1000:iTempSwatchTime;var sSwatchTime=iSwatchTime.toString();if(iSwatchTime<10){sSwatchTime='@00'+sSwatchTime;}else if(iSwatchTime<100){sSwatchTime='@0'+sSwatchTime;}else{sSwatchTime='@'+sSwatchTime;}}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sSwatchTime;}}
Date.prototype.getTimeSeconds=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getTimeSeconds',0,iNumArguments);}
var sTimeSeconds=Math.floor(this.getTime()/1000).toString();}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sTimeSeconds;}}
Date.prototype.getTimezone=function(){return'<< NOT IMPLEMENTED >>';}
Date.prototype.getTimezoneOffsetSeconds=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getTimezoneOffsetSeconds',0,iNumArguments);}
var sTimezoneOffsetSeconds=(this.getTimezoneOffset()*60).toString();}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sTimezoneOffsetSeconds;}}
Date.prototype.getWeekOfYear=function(){try{var vError=null;var iNumArguments=arguments.length;if(!('getDayOfYear'in this)){throw vError=new MethodNotAvailableException('Date.getWeekOfYear','Date.getDayOfYear');}
if(!('isLeapYear'in this)){throw vError=new MethodNotAvailableException('Date.getWeekOfYear','Date.isLeapYear');}
if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getWeekOfYear',0,iNumArguments);}
var iYear=this.getFullYear();var iYearM1=iYear-1;var sDayOfYear=this.getDayOfYear();var sIsLeapYear=this.isLeapYear();var sIsLeapYearM1=(new Date('January 1, '+iYearM1.toString())).isLeapYear();if(!sDayOfYear||!sIsLeapYear||!sIsLeapYearM1){throw vError=new UnknownException('Date.getWeekOfYear');}
var iYearM1Mod100=iYearM1%100;var iDayOfYear=parseInt(sDayOfYear);var iJan1DayOfWeek=1+((((Math.floor((iYearM1-iYearM1Mod100)/100)%4)*5)+(iYearM1Mod100+Math.floor(iYearM1Mod100/4)))%7);var iDayOfWeek=1+(((iDayOfYear+(iJan1DayOfWeek-1))-1)%7);var iDaysInYear=(parseInt(sIsLeapYear)==1)?366:365;var iWeekOfYear=0;if((iDayOfYear<=(8-iJan1DayOfWeek))&&(iJan1DayOfWeek>4)){iWeekOfYear=((iJan1DayOfWeek==5)||((iJan1DayOfWeek==6)&&(parseInt(sIsLeapYearM1)==1)))?53:52;}else if((iDaysInYear-iDayOfYear)<(4-iDayOfWeek)){iWeekOfYear=1;}else{iWeekOfYear=Math.floor((iDayOfYear+(7-iDayOfWeek)+(iJan1DayOfWeek-1))/7);if(iJan1DayOfWeek>4){iWeekOfYear-=1;}}
var sWeekOfYear=iWeekOfYear.toString();if(iWeekOfYear<10){sWeekOfYear='0'+sWeekOfYear;}}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sWeekOfYear;}}
Date.prototype.getZodiacSign=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.getZodiac',0,iNumArguments);}
var iMonth=this.getMonth()+1;var iDay=this.getDate();var sZodiacSign='';if(iMonth==1&&iDay>=20||iMonth==2&&iDay<=18){sZodiacSign="Aquarius";}else if(iMonth==2&&iDay>=19||iMonth==3&&iDay<=20){sZodiacSign="Pisces";}else if(iMonth==3&&iDay>=21||iMonth==4&&iDay<=19){sZodiacSign="Aries";}else if(iMonth==4&&iDay>=20||iMonth==5&&iDay<=20){sZodiacSign="Taurus";}else if(iMonth==5&&iDay>=21||iMonth==6&&iDay<=21){sZodiacSign="Gemini";}else if(iMonth==6&&iDay>=22||iMonth==7&&iDay<=22){sZodiacSign="Cancer";}else if(iMonth==7&&iDay>=23||iMonth==8&&iDay<=22){sZodiacSign="Leo";}else if(iMonth==8&&iDay>=23||iMonth==9&&iDay<=22){sZodiacSign="Virgo";}else if(iMonth==9&&iDay>=23||iMonth==10&&iDay<=22){sZodiacSign="Libra";}else if(iMonth==10&&iDay>=23||iMonth==11&&iDay<=21){sZodiacSign="Scorpio";}else if(iMonth==11&&iDay>=22||iMonth==12&&iDay<=21){sZodiacSign="Sagittarius";}else if(iMonth==12&&iDay>=22||iMonth==1&&iDay<=19){sZodiacSign="Capricorn";}}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sZodiacSign;}}
Date.prototype.isDaylightSavingsTime=function(){return'<< NOT IMPLEMENTED >>';}
Date.prototype.isLeapYear=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.isLeapYear',0,iNumArguments);}
var iFullYear=this.getFullYear();var sIsLeapYear=(((iFullYear%4)==0)&&(((iFullYear%100)!=0)||((iFullYear%400)==0)))?'1':'0';}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sIsLeapYear;}}
Date.prototype.isWeekday=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.isWeekday',0,iNumArguments);}
var iDayOfWeek=this.getDay();var sIsWeekDay=(iDayOfWeek>0&&iDayOfWeek<6)?'1':'0';}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sIsWeekDay;}}
Date.prototype.isWeekend=function(){try{var vError=null;var iNumArguments=arguments.length;if(iNumArguments>0){throw vError=new IllegalArgumentException('Date.isWeekend',0,iNumArguments);}
var iDayOfWeek=this.getDay();var sIsWeekEnd=(iDayOfWeek==0||iDayOfWeek==6)?'1':'0';}
catch(vError){if(vError instanceof Error){vError.handleError();}}
finally{return vError?null:sIsWeekEnd;}}