/*!
* TimeTrackerv3
* http://timetracker.ctrl-al-shift.com/
*
* Copyright 2010, Sam Sargent
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Date:
*/
$(function ()
{
	
	/*$(window).resize(function() {
		if($(window).width() < 1280)
		{
		$(".wrapper").css("width", "960px");
		$("#trackedTime").css("width", "635px");
		$("#toDoList").css("width", "635px");
		$("#searchResults").css("width", "635px");
		}else{
			$(".wrapper").css("width", "1280px");
		$("#trackedTime").css("width", "935px");
		$("#toDoList").css("width", "935px");
		$("#searchResults").css("width", "935px");
			
		}
							  
	});*/
	
    $('a[rel=tipsy]').tipsy({fade: true, gravity: 's', live: true});
	//$('span[rel=tipsy]').tipsy({fade: true, gravity: 's', live: true});
	
    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('calendarWidget') == "hide")
			$("#calendarWidget").css('display', 'none');
    
    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>');
}         
    
	/*
	$('.daylist').sortable();
	$(".daylist").disableSelection(); 
	*/
    
     $("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;                                           
    });
	 
	/* $("input.editRowInput").live('keyup', function(ev)
    {	
		if (event.keyCode == '13')
        {
			$("span.saveTimeRowBtn").trigger('click');
		}
    });*/
    
   $("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.multiAddBtn").live('click', function (ev)
    {
    	//alert('multiadd');
    	
    	var thisButn = $(this).attr('id');
    	var inputID = $(this).attr("data-id");
    	
    	if($(this).hasClass('ui-icon-document')){
    		$("#"+$(this).attr("data-id")).replaceWith("<textarea class='multiDayToDo' id='"+$(this).attr("data-id")+"' data-daynum='"+$(this).attr("data-daynum")+"'></textarea>");
    		$(this).removeClass('ui-icon-document').addClass('ui-icon-disk');
    	}else{
			
				var dayNum = $(this).attr('data-daynum');
            var id = $(this).attr('id');
			
			if($("#"+inputID).val() == "")
			{
				$(this).addClass('ui-icon-document').removeClass('ui-icon-disk');
				 $("#"+inputID).replaceWith("<input type='text' data-dayNum='"+dayNum+"' class='dayToDo' id='"+inputID+"'/>");
			}else{
				$(this).addClass('ui-icon-document').removeClass('ui-icon-disk');
			
    		
    	
             $.post("./add_new_multi_todo", { 
                action: 'addNew',
                date: $(this).attr('data-id'),
                item: $("#"+inputID).val()
            }, function (data)
            {
                humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">TODO items added!</span>');
                $("#toDoList-" + dayNum).append(data);
                $("#"+inputID).replaceWith("<input type='text' data-dayNum='"+dayNum+"' class='dayToDo' id='"+inputID+"'/>");
    			
				
				$("#toDoList-" + dayNum+" li").sortElements(function(a, b){
                    return $(a).attr('data-type') > $(b).attr('data-type') ? 1 : -1;
                });
				
            });
			}
    	
    	
    	
    		
    		
    		
    	}
    	
    });
   
   
   $("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);
			
			var oldWeekTotal = parseFormattedTime($("#weeksRunningTotal").html());
            var newWeekTotal = parseInt(oldWeekTotal,10) - parseInt($(this).parent().parent().attr('data-total'),10);
			
            $("#"+thisID).remove();
            
            $("#timeNshit").html(loadingDiv);
            
            
            
            
            $("#daysRunningTotal").html(displayFormattedTimer(newTotal));
			$("#weeksRunningTotal").html(displayFormattedTimer(newWeekTotal));
            $("#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;
    });
   
   
   
   /*$(".multiDayToDo").live('keyup',function (event)
    {
        if (event.keyCode == '13')
        {
            var dayNum = $(this).attr('data-daynum');
            var id = $(this).attr('id');
            event.preventDefault();
             $.post("./add_new_multi_todo", { 
                action: 'addNew',
                date: $(this).attr('id'),
                item: $(this).val()
            }, function (data)
            {
                humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">TODO items added!</span>');
                $("#toDoList-" + dayNum).append(data);
                $("#"+id).val('');
				
				$("#toDoList-" + dayNum+" li").sortElements(function(a, b){
                    return $(a).attr('data-type') > $(b).attr('data-type') ? 1 : -1;
                });
				
            });
        }
        
    });*/
    
    
    $(".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('');
				
				$("#toDoList-" + dayNum+" li").sortElements(function(a, b){
                    return $(a).attr('data-type') > $(b).attr('data-type') ? 1 : -1;
                });
				
            }); 
        }
    });
	
	
	
	 $(".editingToDo").live('keyup',function (event)
    {
        if (event.keyCode == '13')
        {
            var id = $(this).attr('id');
            event.preventDefault();
			
             $.post("./update_todo", {
                action: 'updateToDO',
                item: $(this).val(),
				id: $(this).attr('data-id'),
				state: $(this).attr('data-state'),
            }, function (data)
            {
                humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">TODO item edited!</span>');
                $("#"+id).replaceWith(data);	
            }); 
        }
    });
	
	
        
    $("#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>');
            }); 
    });
	
	$("#editToDo").live('click', function (ev)
    {
            var  todoid= $(this).attr('rel');
             $.post("./edit_todo_item", {
                action: 'edittodo',
                id: todoid
            }, function (data)
            {
                    $("#todoitem-"+todoid).replaceWith(data);
                    //humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">TODO item deleted!</span>');
            }); 
    });
    
    
    $(".completeToDo").live('click', function (ev)
    {
        var  todoid= $(this).attr('data-id');
        
		if($(this).is(':checked'))
		{
			$("#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>');
                    }); 
			
			
		}else{
			$("#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>');
                }); 
			
		}
    });
    
    /*
    hec
            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='editToDo' title='Edit' rel='"+$(this).attr('data-id')+"' class='ui-state-highlight'><span class='ui-icon ui-icon-pencil'></span></a>");
        }
        if (ev.type == 'mouseout')
        {
            $(this).removeClass("todo-ui-state-hover");
            $("#deleteToDo").remove();
            $("#editToDo").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'
                }
            });
            
            $("#pushSelectedToBC").button({
                  icons: {
                    primary: 'ui-icon-transferthick-e-w'
                },
                disabled: true
            });
    
    
    $("#selectUnPushedTime").button({
              icons: {
                primary: 'ui-icon-suitcase'
            }
        });
	
        });
        }
    });
    $("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());
    });
	 
	 
	 $("#clearDPBtn").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("")      

});
     
    $("#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("")      //$("#twocompletemailingList").val()
        $("#prioritiesBox").append('<a style="display:none;" href="mailto:?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'
                }
            });
        });
    });
    
	
	$("#viewOptions").click(function(e) {
                e.preventDefault();
                $("#dashboardViewOpsBox").slideToggle();
            });
	
    
    $("#previousWeek").live('click', function ()
    {
        var currentDateWindow = $("#toDoList").attr("data-date").split("-");
        $("#todoContent").html(loadingDiv);
        
        /*var yesterday = parseInt(currentDateWindow[2],10) - 7;
		 log(yesterday);
        var oDate = new Date(currentDateWindow[0], currentDateWindow[1], currentDateWindow[2]);
        var previousWeek = yesterday <= 0 ? (currentDateWindow[0] + '-' + (parseInt(currentDateWindow[1],10) - 1) + '-' + (parseInt(oDate.getDaysInMonth())-Math.abs(parseInt(yesterday))))  : (currentDateWindow[0] + '-' + currentDateWindow[1] + '-' + yesterday);
        log(previousWeek);*/
        
        var yesterday = parseInt(currentDateWindow[2],10) - 7;
		 log(yesterday);
        var oDate = new Date(currentDateWindow[0], currentDateWindow[1], currentDateWindow[2]);
		var previousWeek;
		  
		if(yesterday <= 0)
		{  
			var month = (parseInt(currentDateWindow[1],10) - 1);
			month = parseInt(month,10) < 10 ? '0'+month : month;  
			
			var day = (parseInt(oDate.getDaysInMonth())-Math.abs(parseInt(yesterday)));
			day = parseInt(day,10) < 10 ? '0'+day : day;  
			previousWeek = (currentDateWindow[0] + '-' + month + '-' + day)
		}else{
			previousWeek = (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) + 9;
		 log(tomorrow);
        var oDate = new Date(currentDateWindow[0], currentDateWindow[1], currentDateWindow[2]);
		var nextWeek;
		 
		if(tomorrow > oDate.getDaysInMonth())
		{
			var month = (parseInt(currentDateWindow[1],10) + 1);
			month = parseInt(month,10) < 10 ? '0'+month : month;  
			
			var day = (1+(parseInt(tomorrow)-oDate.getDaysInMonth()));
			day = parseInt(day,10) < 10 ? '0'+day : day;  
			nextWeek = (currentDateWindow[0] + '-' + month + '-' + day)
		}else{
			nextWeek = (currentDateWindow[0] + '-' + currentDateWindow[1] + '-' + tomorrow);
		}
		
        //var nextWeek = tomorrow > oDate.getDaysInMonth() ?   : 
		
		
        //var nextWeek = tomorrow > oDate.getDaysInMonth() ? (currentDateWindow[0] + '-' + (parseInt(currentDateWindow[1],10) + 1) + '-' + (1+(parseInt(tomorrow)-oDate.getDaysInMonth())))  : (currentDateWindow[0] + '-' + currentDateWindow[1] + '-' + tomorrow);
        log(nextWeek);
		$.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);
								$("#saveBtn").removeClass('ui-state-disabled');
								
								
								
								if($("#basecampProjectID").length){
									log('Removing');
									$("#basecampProjectID").remove();
									$("#refreshToDoListsCacheBtn").remove();
									$("#todoListForProject").remove();
								}
								
                                
                                $.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 }
                                  });
                                });*/
                                });
                    }
                });
        
        
    }
	
	
 

 
$("#prefilPhoneCall").live('click',function(){
	
	$("#callPhoneNumber").val($(this).attr('data-phone'));
	$("#callEmail").val($(this).attr('data-email'));
	$("#callCompany").val($(this).attr('data-company'));
	$("#callName").val($(this).attr('data-name'));
	
	$("#callNotes").focus();
											
});



$("#phoneCallDetails input").live('change',function(){
        //$("#prjMemo").val($("#prjMemo").val() +" "+$(this).attr('title')+":"+ $(this).val());
		
		if($(this).attr('id') == 'callName' && $(this).val() != "")
        {
			$(this).after(loadingDiv);
            $.post("./check_for_person_in_highrise_by_name", { action: "check_for_person_in_highrise", callerName: $(this).val()},
            function(data){
				$("#loadingImage").remove();
                    if(data.PersonID !=-1)
                    {
						$(".qtip").remove();
                            $("#callName").qtip({
                                     content: "<img src='http://tracktime4.me/img/basecamp.png'/>This person exists in Highrise<br/>"+data.html, // Use the tooltip attribute of the element for the content
                                     position: {
                                          corner: {
                                             target: 'rightMiddle',
                                             tooltip: 'leftMiddle'
                                          }
                                       },
                                     style: { 
                                          width: 200,
                                          padding: 5,
                                          background: '#ffffff',
                                          color: 'black',
                                          textAlign: 'center',
                                          border: {
                                             width: 7,
                                             radius: 5,
                                             color: '#ffffff'
                                          },
                                          tip: 'leftMiddle',
                                          name: 'dark' // Inherit the rest of the attributes from the preset dark style
                                       },
                                     show: { ready: true },
                                     hide: { when: { event: 'unfocus' } }
                                  });
                        
                        
                    }else{
                        $(".qtip").remove();
                        $("#callName").qtip({
                                     content: "<img src='http://tracktime4.me/img/basecamp.png'/>"+data.html, // Use the tooltip attribute of the element for the content
                                        position: {
                                          corner: {
                                             target: 'rightMiddle',
                                             tooltip: 'leftMiddle'
                                          }
                                       },
                                     style: { 
                                          width: 200,
                                          padding: 5,
                                          background: '#ffffff',
                                          color: 'black',
                                          textAlign: 'center',
                                          border: {
                                             width: 7,
                                             radius: 5,
                                             color: '#ffffff'
                                          },
                                          tip: 'leftMiddle',
                                          name: 'dark' // Inherit the rest of the attributes from the preset dark style
                                       },
                                     show: { ready: true },
                                     hide: { when: { event: 'unfocus' } }
                                  });
                    }
                    
            }, "json");
            
        }
        
        /*if($(this).attr('id') == 'callEmail')
        {
            $.post("./check_for_person_in_highrise", { action: "check_for_person_in_highrise", callerEmail: $(this).val()},
            function(data){
                    if(data.PersonID !=-1)
                    {
                            $("#callEmail").qtip({
                                     content: "<img src='http://tracktime4.me/img/basecamp.png'/>This person exists in Highrise<br/><label style='font-size:10px;'>Dropbox as Note<input type='checkbox' value='"+data.PersonID[0]+"' title='Dropbox' id='callDropbox'/></label>", // Use the tooltip attribute of the element for the content
                                     position: {
                                          corner: {
                                             target: 'rightMiddle',
                                             tooltip: 'leftMiddle'
                                          }
                                       },
                                     style: { 
                                          width: 200,
                                          padding: 5,
                                          background: '#ffffff',
                                          color: 'black',
                                          textAlign: 'center',
                                          border: {
                                             width: 7,
                                             radius: 5,
                                             color: '#ffffff'
                                          },
                                          tip: 'leftMiddle',
                                          name: 'dark' // Inherit the rest of the attributes from the preset dark style
                                       },
                                     show: { ready: true },
                                     hide: { when: { event: 'unfocus' } }
                                  });
                        
                        
                    }else{
                        
                        $("#callEmail").qtip({
                                     content: "<img src='http://tracktime4.me/img/basecamp.png'/>This person <span style='color:#f00; font-weight:bold;'>does not exist</span> in Highrise", // Use the tooltip attribute of the element for the content
                                        position: {
                                          corner: {
                                             target: 'rightMiddle',
                                             tooltip: 'leftMiddle'
                                          }
                                       },
                                     style: { 
                                          width: 200,
                                          padding: 5,
                                          background: '#ffffff',
                                          color: 'black',
                                          textAlign: 'center',
                                          border: {
                                             width: 7,
                                             radius: 5,
                                             color: '#ffffff'
                                          },
                                          tip: 'leftMiddle',
                                          name: 'dark' // Inherit the rest of the attributes from the preset dark style
                                       },
                                     show: { ready: true },
                                     hide: { when: { event: 'unfocus' } }
                                  });
                    }
                    
            }, "json");
            
        }*/
});

/*$("body").keydown(function (e) {
    log(e.keyCode)
});*/

$("input[name=typeGrp]").live('change', function(){
	if($("#callTypeMessage").is(':checked')){ 
		$("#notesLbl").before('<label class="field" id="whoForLbl">Who For:</label><input type="text" title="Who For" id="callMessageFor"/>');
		$("#callMessageFor").focus();
		$.ajax({
			url: "http://tracktime4.me/system/application/models/contacts.xml",
			dataType: "xml",
			success: function( xmlResponse ) {
				var data = $( "contact", xmlResponse ).map(function() {
					return {
						id: $( "firstname", this ).text() + " " + $( "lastname", this ).text(),
						value: $( "username", this ).text()
					};
				}).get();
				$( "#callMessageFor" ).autocomplete({
					source: data,
					minLength: 0,
					select: function( event, ui ) {
						log( ui.item ?
							"Selected: " + ui.item.value + ", email: " + ui.item.id :
							"Nothing selected, input was " + this.value );
					}
				});
			}
		});
	}else{
		$("#whoForLbl").remove();
		$("#callMessageFor").remove();
	}
	
	if($("#callTypeSales").is(':checked')){
		
		$("#phoneCallDetails").qtip({
									content: {
											 title: {
												text: 'Phone Tracker Cheat Sheet Notes',
												button: 'Close'
											 },
											 url: 'http://tracktime4.me/system/application/views/phone_cheat_sheet.html'
										  },
                                        position: {
                                          corner: {
                                             target: 'leftMiddle',
                                             tooltip: 'rightMiddle'
                                          }
                                       },
                                     style: { 
                                          width: 960, 
                                          padding: 5,
                                          background: '#ffffff',
                                          color: 'black',
                                          textAlign: 'left',
                                          border: {
                                             width: 7,
                                             radius: 5,
                                             color: '#ffffff'
                                          },
                                          tip: 'rightMiddle',
                                          name: 'dark' // Inherit the rest of the attributes from the preset dark style
                                       },
                                     show: { ready: true },
                                  hide: false
                                  });
		
		
		/*$("#phoneCallDetails").qtip({
                                     content: { url: 'http://tracktime4.me/system/application/views/phone_cheat_sheet.html' }, // Use the tooltip attribute of the element for the content
                                        position: {
                                          corner: {
                                             target: 'leftMiddle',
                                             tooltip: 'rightMiddle'
                                          }
                                       },
                                     style: { 
                                          width: 800,
                                          padding: 5,
                                          background: '#ffffff',
                                          color: 'black',
                                          textAlign: 'left',
                                          border: {
                                             width: 7,
                                             radius: 5,
                                             color: '#ffffff'
                                          },
                                          tip: 'rightMiddle',
                                          name: 'dark' // Inherit the rest of the attributes from the preset dark style
                                       },
                                     show: { ready: true },
                                   hide: { when: 'click', delay: 2000 }
                                  });*/
		
	}else{
		
		
	}
											  
});

setupPhoneCall();

function setupPhoneCall(){
	
	$("#startCallBtn").button(
    {
        icons: {
            primary: 'ui-icon-contact'
        }
    }).live('click',function ()
    {
        //Save Current Timer
        if(!done){
             saveBeforePhone = true;
        $("#saveBtn").trigger('click'); 
        }else{
        $("#prjName").val("Phone Call");
         /*$("#prjName").autocomplete("search", "BW155");
         $("#prjName").focus();
         $("#prjName").val($("#prjName").val()+" ");
         var e = $.Event("keydown");
            e.keyCode = 40;
            $("#prjName").trigger(e);
        
        var e = $.Event("keydown");
            e.keyCode = 9;
            $("#prjName").trigger(e);
        */
        $('#prjName').trigger('change');
        $('#prjName').trigger('blur');
        //$("#saveBtn").removeClass('ui-state-disabled');
        $("#prjMemo").val("Will be filled out on save...");
        
        
        $(this).parent().html('<div id="phoneCallDetails"><h3 class="about">Phone Call Tracker</h3>'+
        '<label class="field">Name</label>'+
         '<input type="text" title="Name" id="callName"/>'+
         '<label class="field">Phone #</label>'+
         '<input type="text" title="Phone" id="callPhoneNumber"/>'+
         '<label class="field">Email Address</label>'+
         '<input type="text" title="Email" id="callEmail"/>'+
         '<label class="field">Company Name</label>'+
         '<input type="text" title="Company" id="callCompany"/>'+
		 '<label class="field">Type of Call?</label>'+
         '<label>New Enquiry <input type="radio" name="typeGrp" title="Sales" id="callTypeSales"/></label>'+
		 '<label>Message <input type="radio" name="typeGrp" title="Message" id="callTypeMessage"/></label>'+
         '<label class="field" id="notesLbl">Notes</label>'+
         '<textarea id="callNotes" title="Message" class="notepad" style="width:230px; height:60px;"></textarea><br/>'+
         '<button id="saveCallBtn">Save</button><button id="closeCallBtn">Close</button></div>'); 
        
         $("#callName").focus();
         phoneCall = true;
        
    $("#saveCallBtn").button(
    {
        icons: {
            primary: 'ui-icon-disk'
        }
    }).click(function(){
       /* if($('#callDropbox').is(':checked')){ 
        $.post("./push_note_for_person_in_highrise", { action: "push_note_for_person_in_highrise", personID: $("#callDropbox").val(), notes: $("#callNotes").val()},
            function(data){
                //log("Note pushed to highrise");
            });
        }*/
		$(".qtip").remove();
		
		if($('#callTypeMessage').is(':checked')){ 
        $.post("./send_phone_message_email", { action: "send_phone_message_email", to: $("#callMessageFor").val(), notes: $("#callNotes").val(), subject: "Phone Message: "+$("#callName").val()+"("+$("#callCompany").val()+") PRB: "+$("#callPhoneNumber").val()+""},
            function(data){
                humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">Email message sent!</span>');
            });
        }
		
		var memo = "";
		
        $('#phoneCallDetails input[type=text]').each(function(index) {
    		memo += $(this).attr('title')+":"+ $(this).val()+"\n";
  });
		
		$("#prjMemo").val(memo);
        
        
        $("#saveBtn").trigger('click');
    });
    
    $("#closeCallBtn").button(
    {
        icons: {
            primary: 'ui-icon-cancel'
        }
    }).click(function(){
    $("#clearBtn").trigger('click');
    //if cleared - clear phone call details
       //if(done)
            resetPhoneCall();
    });

        }
        
    });
	
}


 $(".highriseLookupFill").live('click',function(){
	var formatted = "";
	
		formatted += "<h3>"+$(this).attr('data-name')+"</h3>";
		formatted += "<input type='hidden' id='personID' value='"+$(this).attr('data-id')+"'/>";
		formatted += "<p class='notbig'><strong>Phone:</strong><br/>"+$(this).attr('data-phone')+"</p>";
		formatted += "<p class='notbig'><strong>Email:</strong><br/>"+$(this).attr('data-email')+"</p>";
		formatted += "<p class='notbig'><strong>Company:</strong><br/>"+$(this).attr('data-company')+"<br/>";
		formatted += "<h4>Add a note to this person in Highrise</h4>";
		formatted += "<textarea class='prjMemo' name='highrisenote' id='highrisenote'></textarea><br/>";
		formatted += "<button id='addHighriseNote'>Submit</button>";
		formatted += "<button id='resetHighriseLookup'>Reset</button>";
		
		$("#highriseDetatils").html(formatted);
		
								$("#addHighriseNote").button(
						{
							icons: {
								primary: 'ui-icon-contact'
							}
						}).click(function (){
							
							$("#addHighriseNote").addClass('ui-state-disabled');
							
							
								options =
								{
									label: 'Submitting...',
									icons: {
										primary: 'ui-icon-contact'
									}
								};
					
							$(this).button('option', options);

							
							 $.post("./push_note_for_person_in_highrise", { action: "push_note_for_person_in_highrise", personID: $("#personID").val(), notes: $("#highrisenote").val()},
								function(data){
									 humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">Note Pushed to Highrise</span>');
									 $("#highrisenote").val('');
									 
									 options =
									{
										label: 'Submit',
										icons: {
											primary: 'ui-icon-contact'
										}
									};
						
								$("#addHighriseNote").button('option', options);
									 
									 
									 
									 $("#addHighriseNote").removeClass('ui-state-disabled');
								});
							
						});
						
						$("#resetHighriseLookup").button(
						{
							icons: {
								primary: 'ui-icon-person'
							}
						}).click(function (){
							$("#highriseDetatils").html("<input type='text' class='prjName' id='highriseName'/><button id='searchHighrise'>Search</button>");
							
							$("#searchHighrise").button(
							{
								icons: {
									primary: 'ui-icon-search'
								}
							});
						});
											
});
 
     $("#highriseName").live('keyup',function (event)
    {
        if (event.keyCode == '13')
        {
            event.preventDefault();
            $(this).after(loadingDiv);
		 $.post("./highrise_lookup_by_name", { action: "check_for_person_in_highrise", callerName: $("#highriseName").val()},
            function(data){
				$("#loadingImage").remove();
                    if(data.PersonID !=-1)
                    {
						$("#highriseDetatils").html(data.html);
						
						$("#addHighriseNote").button(
						{
							icons: {
								primary: 'ui-icon-contact'
							}
						}).click(function (){
							$("#addHighriseNote").addClass('ui-state-disabled');
							options =
								{
									label: 'Submitting...',
									icons: {
										primary: 'ui-icon-contact'
									}
								};
					
							$(this).button('option', options);
							
							 $.post("./push_note_for_person_in_highrise", { action: "push_note_for_person_in_highrise", personID: $("#personID").val(), notes: $("#highrisenote").val()},
								function(data){
									 humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">Note Pushed to Highrise</span>');
									 						 $("#highrisenote").val('');
									 options =
									{
										label: 'Submit',
										icons: {
											primary: 'ui-icon-contact'
										}
									};
						
								$("#addHighriseNote").button('option', options);
									 $("#addHighriseNote").removeClass('ui-state-disabled');
								});
							
						});
						
						$("#resetHighriseLookup").button(
						{
							icons: {
								primary: 'ui-icon-person'
							}
						}).click(function (){
							$("#highriseDetatils").html("<input type='text' class='prjName' id='highriseName'/><button id='searchHighrise'>Search</button>");
							
							$("#searchHighrise").button(
							{
								icons: {
									primary: 'ui-icon-search'
								}
							});
						});
		
						
						
					}else{
						$("#highriseDetatils").html(data.html);
						$("#searchHighrise").button(
							{
								icons: {
									primary: 'ui-icon-search'
								}
							});
					}
            }, "json");
        }
    });
 
    
	$("#searchHighrise").button(
    {
        icons: {
            primary: 'ui-icon-search'
        }
    }).live('click',function ()
    {
    	$(this).before(loadingDiv);
		 $.post("./highrise_lookup_by_name", { action: "check_for_person_in_highrise", callerName: $("#highriseName").val()},
            function(data){
				$("#loadingImage").remove();
                    if(data.PersonID !=-1)
                    {
						$("#highriseDetatils").html(data.html);
						
						$("#addHighriseNote").button(
						{
							icons: {
								primary: 'ui-icon-contact'
							}
						}).click(function (){
							$("#addHighriseNote").addClass('ui-state-disabled');
							 options =
									{
										label: 'Submitting...',
										icons: {
											primary: 'ui-icon-contact'
										}
									};
						
								$(this).button('option', options);
							
							 $.post("./push_note_for_person_in_highrise", { action: "push_note_for_person_in_highrise", personID: $("#personID").val(), notes: $("#highrisenote").val()},
								function(data){
									 humanMsg.displayMsg('<strong>Success:</strong> <span class="indent">Note Pushed to Highrise</span>');
									 						 $("#highrisenote").val('');
									 options =
									{
										label: 'Submit',
										icons: {
											primary: 'ui-icon-contact'
										}
									};
						
								$("#addHighriseNote").button('option', options);
									 $("#addHighriseNote").removeClass('ui-state-disabled');
								});
							
						});
						
						$("#resetHighriseLookup").button(
						{
							icons: {
								primary: 'ui-icon-person'
							}
						}).click(function (){
							$("#highriseDetatils").html("<input type='text' class='prjName' id='highriseName'/><button id='searchHighrise'>Search</button>");
							
							$("#searchHighrise").button(
							{
								icons: {
									primary: 'ui-icon-search'
								}
							});
						});
		
						
						
					}else{
						$("#highriseDetatils").html(data.html);
					}
            }, "json");
	});
	
    
    $("#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'))
        {
			log("its disabled man");
        }
        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: $("#trackedTime").attr('data-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>');
                
				if(saveBeforePhone){ 
					setupPhoneCall();
				 //$('#startCallBtn').trigger('click');
				}
                
                
                
            });
            
            /*if(phoneCall){
            $("#phoneCallDetails").slideUp();
                setTimeout("resetPhoneCall()", 1000);
            phoneCall = false;
            }*/
            
                            //$("#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 saveBeforePhone = false;
var phoneCall = false;
var nowLoading = false;
var waitingInteral;
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 resetPhoneCall(){
    
    $('#phoneCallDetails').replaceWith('<h3 class=\'about\'>Phone Call Tracker</h3><button id=\'startCallBtn\'>Phone Call</button>');
    
    $("#startCallBtn").button(
        {
            icons: {
                primary: 'ui-icon-contact'
            }
        });
    
}


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');  
	$("#startBtn").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 <= 5)
    {
        roundedTotal = 5;
        //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;}}

/**
 * jQuery.fn.sortElements
 * --------------
 * @param Function comparator:
 *   Exactly the same behaviour as [1,2,3].sort(comparator)
 *   
 * @param Function getSortable
 *   A function that should return the element that is
 *   to be sorted. The comparator will run on the
 *   current collection, but you may want the actual
 *   resulting sort to occur on a parent or another
 *   associated element.
 *   
 *   E.g. $('td').sortElements(comparator, function(){
 *      return this.parentNode; 
 *   })
 *   
 *   The <td>'s parent (<tr>) will be sorted instead
 *   of the <td> itself.
 */
jQuery.fn.sortElements = (function(){
 
    var sort = [].sort;
 
    return function(comparator, getSortable) {
 
        getSortable = getSortable || function(){return this;};
 
        var placements = this.map(function(){
 
            var sortElement = getSortable.call(this),
                parentNode = sortElement.parentNode,
 
                // Since the element itself will change position, we have
                // to have some way of storing its original position in
                // the DOM. The easiest way is to have a 'flag' node:
                nextSibling = parentNode.insertBefore(
                    document.createTextNode(''),
                    sortElement.nextSibling
                );
 
            return function() {
 
                if (parentNode === this) {
                    throw new Error(
                        "You can't sort elements if any one is a descendant of another."
                    );
                }
 
                // Insert before flag:
                parentNode.insertBefore(this, nextSibling);
                // Remove flag:
                parentNode.removeChild(nextSibling);
 
            };
 
        });
 
        return sort.call(this, comparator).each(function(i){
            placements[i].call(getSortable.call(this));
        });
 
    };
 
})();

/**
 * jQuery sound plugin (no flash)
 * 
 * port of script.aculo.us' sound.js (http://script.aculo.us), based on code by Jules Gravinese (http://www.webveteran.com/) 
 * 
 * Copyright (c) 2007 JĚ¦rn Zaefferer (http://bassistance.de) 
 * 
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *   
 * $Id: jquery.sound.js 5854 2008-10-04 10:22:25Z joern.zaefferer $
 */

/**
 * API Documentation
 * 
 * // play a sound from the url
 * $.sound.play(url)
 * 
 * // play a sound from the url, on a track, stopping any sound already running on that track
 * $.sound.play(url, {
 *   track: "track1"
 * });
 * 
 * // increase the timeout to four seconds before removing the sound object from the dom for longer sounds
 * $.sound.play(url, {
 *   timeout: 4000
 * });
 * 
 * // stop a sound by removing the element returned by play
 * var sound = $.sound.play(url);
 * sound.remove();
 * 
 * // disable playing sounds
 * $.sound.enabled = false;
 * 
 * // enable playing sounds
 * $.sound.enabled = true
 */

(function($) {
	
$.sound = {
	tracks: {},
	enabled: true,
	template: function(src) {
		// todo: move bgsound element and browser sniffing in here
		// todo: test wmv on windows: Builder.node('embed', {type:'application/x-mplayer2', pluginspage:'http://microsoft.com/windows/mediaplayer/en/download/',        id:'mediaPlayer', name:'mediaPlayer', displaysize:'4', autosize:'-1', bgcolor:'darkblue', showcontrols:'false', showtracker:'-1', showdisplay:'0', showstatusbar:'-1', videoborder3d:'-1', width:'0', height:'0', src:audioFile, autostart:'true', designtimesp:'5311', loop:'false'});
		// is_win = (agt.indexOf("windows") != -1);
		return '<embed style="height:0" loop="false" src="' + src + '" autostart="true" hidden="true"/>';
	},
	play: function(url, options){
		if (!this.enabled)
			return;
		options = $.extend({
			url: url,
			timeout: 2000
		}, options);
		
		if (options.track) {
			if (this.tracks[options.track]) {
				var current = this.tracks[options.track];
				// TODO check when Stop is avaiable, certainly not on a jQuery object
				current[0].Stop && current[0].Stop();
				current.remove();  
			}
		}
		
		var element = $.browser.msie
		  	? $('<bgsound/>').attr({
		        src: options.url,
				loop: 1,
				autostart: true
		      })
		  	: $(this.template(options.url));
			
		element.appendTo("body");
		
		if (options.track) {
			this.tracks[options.track] = element;
		}
		
		setTimeout(function() {
			element.remove();
		}, options.timeout)
		
		return element;
	}
};

})(jQuery);

/*
 * Another In Place Editor - a jQuery edit in place plugin
 *
 * Copyright (c) 2009 Dave Hauenstein
 *
 * License:
 * This source file is subject to the BSD license bundled with this package.
 * Available online: {@link http://www.opensource.org/licenses/bsd-license.php}
 * If you did not receive a copy of the license, and are unable to obtain it,
 * email davehauenstein@gmail.com,
 * and I will send you a copy.
 *
 * Project home:
 * http://code.google.com/p/jquery-in-place-editor/
 *
 */

/*
 * Version 1.0.1
 *
 * bg_out (string) default: transparent hex code of background color on restore from hover
 * bg_over (string) default: #ffc hex code of background color on hover
 * callback (function) default: null function to be called when editing is complete; cancels ajax submission to the url param
 * cancel_button (string) default: <input type=”submit” class=”inplace_cancel” value=”Cancel”/> image button tag to use as “Cancel” button
 * default_text (string) default: “(Click here to add text)” text to show up if the element that has this functionality is empty
 * element_id (string) default: element_id name of parameter holding element_id
 * error (function) this function gets called if server responds with an error
 * field_type (string) “text”, “textarea”, or “select”; default: “text” The type of form field that will appear on instantiation
 * on_blur (string) “save” or null; default: “save” what to do on blur; will be overridden if $param show_buttons is true
 * original_html (string) default: original_html name of parameter holding original_html
 * params (string) example: first_name=dave&last_name=hauenstein paramters sent via the post request to the server
 * save_button (string) default: <input type=”submit” class=”inplace_save” value=”Save”/> image button tag to use as “Save” button
 * saving_image (string) default: uses saving text specify an image location instead of text while server is saving
 * saving_text (string) default: “Saving…” text to be used when server is saving information
 * select_options (string) comma delimited list of options if field_type is set to select
 * select_text (string)default text to show up in select box
 * show_buttons (boolean) default: false will show the buttons: cancel or save; will automatically cancel out the onBlur functionality
 * success (function) default: null this function gets called if server responds with a success
 * textarea_cols (integer) default: 25 set cols attribute of textarea, if field_type is set to textarea
 * textarea_rows (integer) default: 10 set rows attribute of textarea, if field_type is set to textarea
 * update_value (string) default: update_value name of parameter holding update_value
 * url (string) POST URL to send edited content
 * value_required (string) default: false if set to true, the element will not be saved unless a value is entered
 *
 */

jQuery.fn.editInPlace = function(options) {

	/* DEFINE THE DEFAULT SETTINGS, SWITCH THEM WITH THE OPTIONS USER PROVIDES */
	var settings = {
		url:				"",
		params:				"",
		field_type:			"text",
		select_options:		"",
		textarea_cols:		"25",
		textarea_rows:		"10",
		bg_over:			"#ffc",
		bg_out:				"transparent", 
		saving_text:		"Saving...",
		saving_image:		"",
		default_text:		"(Click here to add text)",
		select_text:		"Choose new value",
		value_required:		null,
		element_id:			"id", 
		update_value:		"update_value",
		original_html:		"original_html",
		save_button:		'<button class="inplace_save">Save</button>',
		cancel_button:		'<button class="inplace_cancel">Cancel</button>',
		show_buttons:		false,
		on_blur:			"save",
		callback:			null,
		success:			null,
		error:				function(request){
                                alert("Failed to save value: " + request.responseText || 'Unspecified Error');
                            }
	};

	if(options) {
		jQuery.extend(settings, options);
	}

	/* preload the loading icon if it exists */
	if(settings.saving_image != ""){
		var loading_image = new Image();
		loading_image.src = settings.saving_image;
	}

	/* THIS FUNCTION WILL TRIM WHITESPACE FROM BEFORE/AFTER A STRING */
	String.prototype.trim = function() {
		return this.replace(/^\s+/, '')
							 .replace(/\s+$/, '');
	};

	/* THIS FUNCTION WILL ESCAPE ANY HTML ENTITIES SO "Quoted Values" work */
	String.prototype.escape_html = function() {
		return this.replace(/&/g, "&amp;")
							 .replace(/</g, "&lt;")
							 .replace(/>/g, "&gt;")
							 .replace(/"/g, "&quot;");
  };

	/* CREATE THE INPLACE EDITOR */
	return this.each(function(){

		if(jQuery(this).html() == "") jQuery(this).html(settings.default_text);

		var editing = false;

		//save the original element - for change of scope
		var original_element = jQuery(this);

		var click_count = 0;

		jQuery(this)

		.mouseover(function(){
			jQuery(this).css("background", settings.bg_over);
		})

		.mouseout(function(){
			jQuery(this).css("background", settings.bg_out);
		})

		.click(function(){
			click_count++;

			if(!editing)
			{
				editing = true;

				//save original text - for cancellation functionality
				var original_html = jQuery(this).html();
				var buttons_code  = (settings.show_buttons) ? settings.save_button + ' ' + settings.cancel_button : '';

				//if html is our default text, clear it out to prevent saving accidentally
				if (original_html == settings.default_text) jQuery(this).html('');

				if (settings.field_type == "textarea")
				{
					var use_field_type = '<textarea name="inplace_value" class="inplace_field" style="width:100%;">' + jQuery(this).text().trim().escape_html() + '</textarea>';
				}
				else if(settings.field_type == "text")
				{
					var use_field_type = '<input type="text" name="inplace_value" class="inplace_field" value="' +
											jQuery(this).text().trim().escape_html() + '" />';
				}
				else if(settings.field_type == "select")
				{
					var optionsArray = settings.select_options.split(',');
					var use_field_type = '<select name="inplace_value" class="inplace_field"><option value="">' + settings.select_text + '</option>';
						for(var i=0; i<optionsArray.length; i++){
							var optionsValuesArray = optionsArray[i].split(':');
							var use_value = optionsValuesArray[1] || optionsValuesArray[0];
							var selected = use_value == original_html ? 'selected="selected" ' : '';
							use_field_type += '<option ' + selected + 'value="' + use_value.trim().escape_html() + '">' + optionsValuesArray[0].trim().escape_html() + '</option>';
                        }
						use_field_type += '</select>';
				}

				/* insert the new in place form after the element they click, then empty out the original element */
				jQuery(this).html('<form class="inplace_form" style="display: inline; margin: 0; padding: 0;">' + use_field_type + ' ' + buttons_code + '</form>');

			}/* END- if(!editing) -END */

			if(click_count == 1)
			{
				function cancelAction()
				{
					editing = false;
					click_count = 0;

					/* put the original background color in */
					original_element.css("background", settings.bg_out);

					/* put back the original text */
					original_element.html(original_html);

					return false;
				}

				function saveAction()
				{
					/* put the original background color in */
					original_element.css("background", settings.bg_out);

                    var this_elem = jQuery(this);

					var new_html = (this_elem.is('form')) ? this_elem.children(0).val() : this_elem.parent().children(0).val();

					/* set saving message */
					if(settings.saving_image != ""){
						var saving_message = '<img src="' + settings.saving_image + '" alt="Saving..." />';
					} else {
						var saving_message = settings.saving_text;
					}

					/* place the saving text/image in the original element */
					original_element.html(saving_message);

					if(settings.params != ""){
						settings.params = "&" + settings.params;
					}

					if(settings.callback) {
						html = settings.callback(original_element.attr("id"), new_html, original_html, settings.params);
						editing = false;
						click_count = 0;
						if (html) {
							/* put the newly updated info into the original element */
							original_element.html(html || new_html);
						} else {
							/* failure; put original back */
							alert("Failed to save value: " + new_html);
							original_element.html(original_html);
						}
					} else if (settings.value_required && (new_html == "" || new_html == undefined)) {
						editing = false;
						click_count = 0;
						original_element.html(original_html);
						alert("Error: You must enter a value to save this field");
					} else {
						jQuery.ajax({
							url: settings.url,
							type: "POST",
							data: settings.update_value + '=' + new_html + '&' + settings.element_id + '=' + original_element.attr("data-id") + settings.params + '&' + settings.original_html + '=' + original_html + '&field=' + original_element.attr("data-field"),
							dataType: "html",
							complete: function(request){
								editing = false;
								click_count = 0;
							},
							success: function(html){
								/* if the text returned by the server is empty, */
   								/* put a marker as text in the original element */
								var new_text = html || settings.default_text;

								/* put the newly updated info into the original element */
								original_element.html(new_text);
								if (settings.success) settings.success(html, original_element);
							},
							error: function(request) {
								original_element.html(original_html);
								if (settings.error) settings.error(request, original_element);
							}
						});
					}

					return false;
				}

				/* set the focus to the new input element */
				original_element.children("form").children(".inplace_field").focus().select();

				/* CLICK CANCEL BUTTON functionality */
				original_element.children("form").children(".inplace_cancel").click(cancelAction);

				/* CLICK SAVE BUTTON functionality */
				original_element.children("form").children(".inplace_save").click(saveAction);

                /* if cancel/save buttons should be shown, cancel blur functionality */
                if(!settings.show_buttons){
                    /* if on_blur is set to save, set the save funcion */
    				if(settings.on_blur == "save")
    					original_element.children("form").children(".inplace_field").blur(saveAction);
    				/* if on_blur is set to cancel, set the cancel funcion */
    				else
    					original_element.children("form").children(".inplace_field").blur(cancelAction);
                }

				/* hit esc key */
				$(document).keyup(function(event){
				    if (event.keyCode == 27) {
						cancelAction();
				    }
				});

                original_element.children("form").submit(saveAction);

			}/* END- if(click_count == 1) -END */
		});
	});
};
