var currentTaskCompleted                = "no";
var assignMode                          = "select";
var pageLoaded                          = false;

/* 
 *-----------------------------------------------------------------------
 * IMAGES FUNCTIONS
 * -----------------------------------------------------------------------
*/

var image1 = new Image();
image1.src = "/images/taskFooterBG_on.gif";
var image2 = new Image();
image2.src = "/images/tag_on.gif";
var image3 = new Image();
image3.src = "/images/edit_on.gif";
var image4 = new Image();
image4.src = "/images/trash_on.gif";
var image5 = new Image();
image5.src = "/images/upArrow_on.gif";
var image6 = new Image();
image6.src = "/images/downArrow_on.gif";
var image7 = new Image();
image7.src = "/images/insertHere_on.gif";
var image8 = new Image();
image8.src = "/images/add_on.gif";
var image9 = new Image();
image9.src = "/images/assign_on.gif";
var image10 = new Image();
image10.src = "/images/move_on.gif";
var image11 = new Image();
image11.src = "/images/submenuBG_on.gif";
var image12 = new Image();
image12.src = "/images/downArrow.gif";
var image13 = new Image();
image13.src = "/images/bubble_orange.gif";
var image14 = new Image();
image14.src = "/images/bubble_blue.gif";
var image15 = new Image();
image15.src = "/images/bubble_red.gif";
var image16 = new Image();
image16.src = "/images/pending.gif";

function swapImage(elementID,imageName,action){
    if (pageLoaded == true){
    	theImage 		                  = document.getElementById(elementID);
    	imageOff    	                  = imageName+".gif";
    	imageOn 		                  = imageName+"_on.gif";
    	if (action == "on"){
    		theImage.src                  = "/images/"+imageOn;
    	} else {
    		theImage.src                  = "/images/"+imageOff;
    	}
    }
}

/* 
 *-----------------------------------------------------------------------
 * CLEAR FUNCTIONS
 * -----------------------------------------------------------------------
*/

function clearForm(formName){
    clearMove();
    hideIt('saveButton');
    hideIt('taskViewBody');
    hideIt('addTagsBody');
    if (document.getElementById('addTaskBody')){
        showIt('addTaskBody');
    } else {
        showIt('rightColAdBox');
    }
    document.getElementById('saveMsg').innerHTML = "";
    var form                            = eval("document."+formName);
    if (form){
        for (i=0;i<form.length;i++){
            form.elements[i].value          = "";
        }
    }
}

function clearChecked(){
    
    var form                            = document.treeForm;
    
    /* Loops through tree and clears checkboxes */
    for (i=0;i<form.length;i++){
        if (form[i].type == "checkbox"){
            if (form[i].checked == true){
                var thisID              = form[i].value;
                document.getElementById('box'+thisID).className     = 'treeBox';
                var bubble              = document.getElementById('bubble'+thisID);
                bubble.src              = bubbleOff;
                bubble.alt              = "off";
            }
            form[i].checked             = false;
            form[i].disabled            = false;
        }
    }
    if (assignMode == "assign"){
        assignMode                      = "select";
        selectedItems.length            = 0;
        selectedSubItems.length         = 0;
    }
    stack.length                        = 0;
    lockedNodes.length                  = 0;
}

function clearMove(){
    /* Loops through all tasks in list and hides Insert Here bars */
    for (i=0;i<listArray.length;i++){
        thisBar                         = "insertHere"+listArray[i];
        
        /* Hides ALL Insert Here bars */
        hideIt(thisBar);
    }    
    hideIt("insertHere0");
}

/* 
 *-----------------------------------------------------------------------
 * TREE FUNCTIONS
 * -----------------------------------------------------------------------
*/

var selectedItems                       = new Array();
var selectedSubItems                    = new Array();

function showTree(taskID,view){
    showBuildingTreeMsg();
    clearForm('editTaskForm');
    if (taskID > 0){
        var vars                        = "task/"+taskID;
    } else {
        var vars                        = "project/0";
    }
    currentTaskID                       = taskID;
    if (view == "search"){
        currentView                     = "tree";
    } else {
        currentView                     = view;
    }
    top.location.href                   = "/showTree/"+vars+"/"+currentView+"/"+accountID+"/";
}

function drillDown(parentTaskID){
    if (document.getElementById('subBox'+parentTaskID).innerHTML == ""){
        document.getElementById('arrow'+parentTaskID).src = "/images/downArrow.gif";
        sendIt('/index.php','POST','action=drillDown&parentTaskID='+parentTaskID);
    } else {
        
        /* Checks to see if the selected task is in the lockedNodes array */
        var allowDrill                  = true;
        for (orignalTaskID in lockedNodes){
            if (inArray(parentTaskID,lockedNodes[orignalTaskID])){
                allowDrill              = false;
            }
        }
        
        /* If the task is not in the lockedNodes array, allows drill down. Otherwise,
        displays error */
        if (allowDrill == true){
            document.getElementById('arrow'+parentTaskID).src = "/images/rightArrow.gif";
            document.getElementById('subBox'+parentTaskID).innerHTML = "";
            hideIt('subBox'+parentTaskID);
            sendIt('/index.php','POST','action=collapseNode&parentTaskID='+parentTaskID);
        } else {
            alert('To collapse this item, you must first deselect its sub-items.')
        }
    }
}

var stack = new Array();

/* Changes state of hidden checkbox when bubble is clicked */
function toggleCheckbox(taskID){
    
    var checkbox                        = document.getElementById('check'+taskID);
    if (checkbox.disabled == false && assignMode == "select"){
        if (checkbox.checked == true){
            checkbox.checked = false;
        } else {
            checkbox.checked = true;
        } 
        selectTreeNode(taskID,'top');
    } else if (checkbox.disabled == false && assignMode == "assign"){
        assignTasks(taskID);
    }
}

/**
* TOGGLE PARENT TASK LOCK
*
* Locks the drillDown arrow on the parent tasks of all selected tasks
**/
function toggleParentTaskLock(taskID,originalTaskID,lockIt){
    
    /* Loops through all values in tree array */
    for (parentTaskID in tree){
        
        /* If the selected task is in the tree and array and the parent task isn't at the top of
        the tree, either locks or unlocks the parent task */
        if (inArray(taskID,tree[parentTaskID]) && parentTaskID != 0){
            
            /* Creates array to hold all parent tasks of this task */
            if (lockedNodes[originalTaskID] == undefined){
                lockedNodes[originalTaskID] = new Array();
            }
            /* If the task is being locked, adds its parent id to the lockedNodes array. Otherwise,
            deletes it from the locked nodes array */
            if (lockIt == true && inArray(parentTaskID,lockedNodes[originalTaskID]) == false){
                lockedNodes[originalTaskID].push(parentTaskID);
            } else if (lockIt == false && inArray(parentTaskID,lockedNodes[originalTaskID]) == true){
                delete lockedNodes[originalTaskID];
            }
            /* Recursively runs this function to bubble up towards top of tree */
            toggleParentTaskLock(parentTaskID,originalTaskID,lockIt);
        }
    }
}
var lockedNodes                         = new Array();
var traversingTree                      = false;

function selectTreeNode(taskID,thisLevel){
    
    var checkbox                        = document.getElementById('check'+taskID);
    var bubble                          = document.getElementById('bubble'+taskID);

    if (thisLevel == "top"){
        if (checkbox.checked == true){
            if (assignMode == "select"){
                bubble.src              = bubbleOn;
                bubble.alt              = "on";
            } else if (assignMode == "assign"){
                bubble.src              = bubbleLocked;
                bubble.alt              = "locked";
            }
            selectItem(taskID,'add');
            document.getElementById('box'+taskID).className     = 'treeBoxSelected';
            
            /* Locks parent task arrows bubbling up to top */
            toggleParentTaskLock(taskID,taskID,true);
            
        } else {
            bubble.src                  = bubbleOff;
            bubble.alt                  = "off";
            selectItem(taskID,'remove');
            document.getElementById('box'+taskID).className     = 'treeBox';
            
            /* Unlocks parent task arrows bubbling up to top */
            toggleParentTaskLock(taskID,taskID,false);
        }
    } else {
        selectItem(taskID,'remove');
        document.getElementById('box'+taskID).className         = 'treeBox';
    }

    if (document.getElementById('subBox'+taskID).innerHTML != ""){
        
        for (i=0;i<tree[taskID].length;i++){
            var thisSubTask                 = tree[taskID][i];
            
            if (thisSubTask != undefined){
                var subCheckbox             = document.getElementById('check'+thisSubTask);
                var subBubble               = document.getElementById('bubble'+thisSubTask);
                
                stack.push(thisSubTask);
                
                if (checkbox.checked == true){
                    if (assignMode == "select"){
                        subBubble.src       = bubbleOn;
                        subBubble.alt       = "disabled";
                    } else if (assignMode == "assign"){
                        subBubble.src       = bubbleLocked;
                        subBubble.alt       = "locked";
                    }
                    subCheckbox.checked     = true;
                    subCheckbox.disabled    = true;
                    document.getElementById('box'+thisSubTask).className     = 'treeBox';
                } else {
                    subBubble.src           = bubbleOff;
                    subBubble.alt           = "off";
                    subCheckbox.checked     = false;
                    subCheckbox.disabled    = false;
                }
                /* Unlocks child task arrows */
                toggleParentTaskLock(thisSubTask,thisSubTask,false);
            }
        }
    }
    if (stack.length > 0 && traversingTree == false){
        var lastTask                        = stack.pop();
        selectTreeNode(lastTask,'sub');
    } else if (traversingTree == true){
        setTimeout(selectTreeNode(taskID,thisLevel),1000);
    }
}

var bubbleOver                      = "/images/bubble_orange.gif";                                         
var bubbleOff                       = "/images/bubble_gray.gif";                                         
var bubbleOn                        = "/images/bubble_green.gif";    
var bubbleLocked                    = "/images/bubble_red.gif";    
var bubbleAssign                    = "/images/bubble_blue.gif";    

function toggleBubble(taskID,action){
    
    var checkbox                    = document.getElementById('check'+taskID);
    var bubble                      = document.getElementById('bubble'+taskID);
                                         
	if (action == "over" && checkbox.disabled == false){
	    if (bubble.alt == "off"){
		    bubble.src                  = bubbleOver;
	    } else if (bubble.alt == "assignOff"){
	        bubble.src                  = bubbleAssign;
	    }
	} else if (action == "out"){
		if (bubble.alt == "off" || bubble.alt == "assignOff"){
	        bubble.src              = bubbleOff;
	    } else if (bubble.alt == "on"){
	        bubble.src              = bubbleOn;
	    }
	}
	if (checkbox.disabled == false){
	    bubble.style.cursor        = "pointer";
	} else {
	    bubble.style.cursor        = "default";
	}
}

function selectItem(itemID,action){

    if (action == "add"){
        selectedItems.push(itemID);
    } else if (action == "remove"){
        var tempArray                   = new Array();
        for (i=0;i<selectedItems.length;i++){
            if (selectedItems[i] != itemID){
                tempArray.push(selectedItems[i]);
            }
        }
        selectedItems                   = tempArray;
    }
}

function checkSubTasks(parentTaskID){
    
    var checkbox                    = document.getElementById('check'+parentTaskID);

    if (checkbox.checked == true){
        if (inArray(parentTaskID,selectedItems)){
            selectTreeNode(parentTaskID,'top');
        } else {
            selectTreeNode(parentTaskID,'sub');
        }
    }
}

function showBuildingTreeMsg(){
    if (document.getElementById('subBox0')){
        var elementID               = "subBox0";
    } else if (document.getElementById('listBody')){
        var elementID               = "listBody";
    } else if (document.getElementById('searchConsole')){
        var elementID               = "searchConsole";
    }
    document.getElementById(elementID).innerHTML = "<br><div class='bold' align='center'><img src='/images/loading.gif' alt='Loading ...' alt='Building your tree ...' align='absmiddle'>&nbsp;&nbsp;Building your tree ...</div>";
    document.getElementById(elementID).innerHTML += "<div class='text2' align='center'>(This may take a while. Please be patient.)</div>";
}

function expandTree(){
    showBuildingTreeMsg();
    sendIt('/index.php','POST','action=expandTree');
}

function collapseTree(){
    sendIt('/index.php','POST','action=collapseTree');
}

/* 
 *-----------------------------------------------------------------------
 * ASSIGN FUNCTIONS
 * -----------------------------------------------------------------------
*/

function toggleAssign(parentTaskID){
    
    if (selectedItems.length == 0){
        showStatus('error','Please select an item');
    } else {
        assignMode                          = "assign";
        var form                            = document.treeForm;
        
        /* Loops through tree and stores checked values in array */
        for (i=0;i<form.length;i++){
            if (form[i].type == "checkbox" && form[i].checked == true){
                selectedSubItems.push(form[i].value);
            }
        }

        /* Clears checked values */
    //    clearChecked();
        
        for (i=0;i<form.length;i++){
            if (form[i].type == "checkbox"){
                
                var thisTaskID              = form[i].value;
                var bubble                  = document.getElementById('bubble'+thisTaskID);
                var checkbox                = document.getElementById('check'+thisTaskID);

                if (inArray(thisTaskID,selectedSubItems) || inArray(parentTaskID,selectedSubItems)){
                    checkbox.checked        = true;
                    checkbox.disabled       = true;
                    bubble.src              = bubbleLocked;
                    bubble.alt              = "locked";
                } else {
                    checkbox.checked        = false;
                    checkbox.disabled       = false;
                    bubble.src              = bubbleOff;
                    bubble.alt              = "assignOff";
                }
            }
        }
    }
}

function assignTasks(assignTo){
    showBuildingTreeMsg();
    var assignList                      = "";
    assignList                          = selectedItems.join(',');
    sendIt('/index.php','POST','action=assign&assignList='+assignList+'&parentTaskID='+assignTo);
    clearChecked();
}

/* Removes deleted items from tree */
function emptyTreeBoxes(emptyThese){
    
    var empty                           = emptyThese.split(",");
    for (i=0;i<empty.length;i++){
        if (empty[i] != 0){
            if (document.getElementById('box'+empty[i])){
                var thisID                      = parseInt(empty[i]);
                var thisNode                    = document.getElementById('box'+thisID);
                thisNode.parentNode.removeChild(thisNode);
            }
            delete tree[empty[i]];
        }
    }
    for (thisParentArray in tree){
        for (i=0;i<tree[thisParentArray].length;i++){
            if (inArray(tree[thisParentArray][i],empty)){
                delete tree[thisParentArray][i];
            }
        }
    }
    clearChecked();
    selectedItems.length                = 0;
    selectedSubItems.length             = 0;
}

/* 
/* 
 *-----------------------------------------------------------------------
 * ADD FUNCTIONS
 * -----------------------------------------------------------------------
*/

function addTask(){
    var addForm                         = document.addTaskForm;
    var editForm                        = document.editTaskForm;
    var taskName                        = addForm.taskName.value;
    if (taskName == ""){
        alert('Please enter a task name');
    } else {
        taskName                        = encodeURIComponent(addForm.taskName.value);
        sendIt('/index.php','POST','action=add&taskName='+taskName+'&parentTaskID='+listID+'&currentView='+currentView);
        clearForm('addTaskForm');
        addForm.taskName.focus();
    }
    return false;
}

function addTags(){
    
    if (selectedItems.length == 0){
        showStatus('error','Please select an item');
    } else {
        var form                        = document.addTagsForm;
        var tagsList                    = encodeURIComponent(form.taskTags.value);
        
        if (tagsList != ""){
            document.getElementById('addTagsMsg').innerHTML = 'Saving ...';
            
            var form                    = document.treeForm;
            var tasksList               = "";
            
            for (i=0;i<form.length;i++){
                if (form[i].type == "checkbox" && form[i].checked == true){
                    tasksList          += form[i].value+",";
                }
            }
            sendIt('/index.php','POST','action=tagTasks&tasksList='+tasksList+'&tagsList='+tagsList);
        } else {
            form.taskTags.focus();
        }
    }
}

/* Adds new task HTML to top of task list using DOM */
function showNewTask(newTaskID,taskHTML){
    
    /* Hides emptyList message if it exists */
    hideIt('emptyList');
    
    /* Adds new task ID to top of listArray */
    listArray.unshift(newTaskID);
    
    /* Decodes task html */
    taskHTML                            = decodeURIComponent(taskHTML);
    
    /* Navigates DOM to top of task list */
    var taskList                        = document.getElementById('taskList');
    var taskListChildren                = taskList.getElementsByTagName('div');
    var firstItem                       = taskListChildren[1];
    
    /* If the task list has only one child (the top Insert Here bar), then inserts
    the taskCompletedDivider so tasks can be marked as completed and moved to correct
    part of list, even if page hasn't been refreshed. */
    if (taskListChildren.length == 1){
        
        /* Creates new div to hold taskCompletedDivider */
        var taskCompletedDivider        = document.createElement('div');
        taskCompletedDivider.setAttribute('id','taskCompletedDivider');
        
        /* Inserts taskCompletedDivider */
        document.getElementById('taskList').appendChild(taskCompletedDivider);
        firstItem                       = taskCompletedDivider;
    }
    /* Creates new div to hold task html */
    var htmlNode                        = document.createElement('div');
    htmlNode.setAttribute('class','task');
    htmlNode.setAttribute('className','task');
    htmlNode.setAttribute('id','task'+newTaskID);
    htmlNode.innerHTML                  = taskHTML;
    
    /* Inserts task at top of list */
    taskList.insertBefore(htmlNode,firstItem);
    
    /* Jumps list to new task */
    window.location.hash                = "taskAnchor"+newTaskID; 
    
    /* Highlights then fades new task */
    Fade.fade_element('color','taskName'+newTaskID,30,2000,'#83E56D','#FFFFFF');
}

/* 
 *-----------------------------------------------------------------------
 * MOVE FUNCTIONS
 * -----------------------------------------------------------------------
*/

/* Shows Insert Here bars and highlights selected task */
function moveTask(taskID){

    clearForm('editTaskForm');
    currentTaskID                       = taskID;
    showIt("insertHere0");
    
    /* Loops through all tasks in list and shows Insert Here bars */
    for (i=0;i<listArray.length;i++){
        thisBar                         = "insertHere"+listArray[i];
        
        /* Hides ALL Insert Here bars */
        hideIt(thisBar);
        
        /* Shows all Insert Here bars except the one for the selected task.
        It can't be Inserted Here -- it already IS here. */
        if (taskID != listArray[i]){
            showIt(thisBar);
        } else {
            
            /* Hides Insert Here bar for the task preceding the selected task.
            Clicking it would basically be saying, "Insert this task between this
            task and the one above," which translates to "insert this task here."
            Since the task is already here, we don't need the preceding Insert Here bar. */
            if (i==0){
                hideIt("insertHere0");
            }
            var hideThis                = listArray[i-1];
            hideIt("insertHere"+hideThis);
        }
    }
    
}

/* Inserts moved task's new position into database */
function insertTask(taskID){
    sendIt('/index.php','POST','action=move&insertHere='+taskID+'&insertThis='+currentTaskID+'&parentTaskID='+listID+'&currentView='+currentView);
}

/* Moves selected item to new position in list */
function showNewPosition(moveThisTask,toThisTask){
    
    var moveThis                        = document.getElementById('task'+moveThisTask);
    var taskList                        = document.getElementById('taskList');
    
    if (toThisTask != 0){
        var toThis                      = document.getElementById('task'+toThisTask);
        taskList.insertBefore(moveThis,toThis.nextSibling);  
    } else {
        var firstItem                   = taskList.getElementsByTagName('div')[1];
        taskList.insertBefore(moveThis,firstItem);
    }
    
    removeTaskFromListArray(moveThisTask);
    
    /* If task is being moved to top of list, appends it to beginning of listArray.
    Otherwise, loops through listArray and inserts task in new position */
    if (toThisTask == 0){
        listArray.unshift(moveThisTask);
    } else {
        for (i=0;i<listArray.length;i++){
            if (listArray[i] == toThisTask){
                listArray.splice(i+1,0,moveThisTask);
                break;
            }
        }
    }
    highlightTask('off',currentTaskID);
    
    if (document.getElementById('taskName'+moveThisTask)){
        Fade.fade_element('color','taskName'+moveThisTask,30,2000,'#83E56D','#FFFFFF');
    }
    clearMove();  
}

/* 
 *-----------------------------------------------------------------------
 * COMPLETE FUNCTIONS
 * -----------------------------------------------------------------------
*/

function completeTask(taskID,parentTaskID){
    clearForm('editTaskForm');
    sendIt('/index.php','POST','action=complete&taskID='+taskID+'&parentTaskID='+parentTaskID+'&currentView='+currentView+'&tagID='+currentTagID);
}

function uncompleteTask(taskID,parentTaskID){
    sendIt('/index.php','POST','action=uncomplete&taskID='+taskID+'&parentTaskID='+parentTaskID+'&currentView='+currentView+'&tagID='+currentTagID);
}

function moveCompletedTask(taskID,taskHTML){
    replaceTask(taskID,taskHTML);
    showNewPosition(taskID,'CompletedDivider');
}

/* 
 *-----------------------------------------------------------------------
 * GET FUNCTIONS
 * -----------------------------------------------------------------------
*/

var originalTask                        = new Array();

function confirmLoseChanges(){
    
    var editForm                        = document.editTaskForm;
    var name                            = editForm.taskName.value;
    var description                     = editForm.taskDesc.value;
    var tags                            = editForm.taskTags.value;
    
    /* If task info has been stored in the originalTask array, checks to see if it
    matches the info currently in the Edit Task form. If it doesn't, that means
    the task has been changed and hasn't been saved. */
    if (originalTask.length > 0){
        if ((originalTask[0] != undefined && originalTask[0] != name) || (originalTask[1] != undefined && originalTask[1] != description) || (originalTask[2] != undefined && originalTask[2] != tags)){
            var confirmThis             = confirm('This item has unsaved changes which be lost. Are you sure you want to continue?');
            return confirmThis;
        } else {
            return true;
        }
    } else {
        return true;
    }
}

function getTasks(taskID,parentTaskID){
    currentView                         = "list";
    clearForm('editTaskForm');
    top.location.href                   = "/project/"+parentTaskID+"/task/"+taskID+"/"+currentView+"/";
}

function getTask(taskID){
    
    var editForm                        = document.editTaskForm;
    var name                            = editForm.taskName.value;
    var description                     = editForm.taskDesc.value;
    var tags                            = editForm.taskTags.value;
    
    if (confirmLoseChanges()){
        
        clearForm('editTaskForm');
        showIt('taskViewBody');
        hideIt('addTaskBody');
        hideIt('rightColAdBox');
        showIt('saveButton');
        showIt('addTaskButton');
        sendIt('/index.php','POST','action=getTask&taskID='+taskID+'&currentView='+currentView);
    }
}

function getTags(){
    currentView                         = "list";
    top.location.href                   = "/tags/"+currentView+"/"+accountID+"/";
}


function getPending(){
    currentView                         = "pending";
    top.location.href                   = "/pending/"+currentView+"/"+accountID+"/";
}

function getTasksByTag(tagID,tagName){
    clearForm('editTaskForm');
    top.location.href                   = "/tag/"+tagName+"/"+currentView+"/"+tagID+"/"+accountID+"/";
}

/* 
 *-----------------------------------------------------------------------
 * DELETE FUNCTIONS
 * -----------------------------------------------------------------------
*/

/* Confirms whether user wants to delete task. If yes, then send AJAX request to delete task */
function deleteTask(taskID,parentTaskID){
    var confirmIt                       = confirm('Are you sure you want to delete this item?');
    if (confirmIt){
        clearForm('editTaskForm');
        sendIt('/index.php','POST','action=delete&taskID='+taskID+'&parentTaskID='+parentTaskID+'&currentView='+currentView+'&tagID='+currentTagID);
    }
}

/* Confirms whether user wants to delete selected task(s). If yes, then send AJAX request to delete task */
function deleteTasks(){
    
    if (selectedItems.length == 0){
        showStatus('error','Please select an item');
    } else {
        var form                            = document.treeForm;
        var deleteList                      = "";
        
        for (i=0;i<form.length;i++){
            if (form[i].type == "checkbox" && form[i].checked == true){
                deleteList                 += form[i].value+",";
            }
        }
        if (deleteList != ""){
            var confirmMsg                  = "Are you sure you want to delete the selected item(s)?\n\n";
            confirmMsg                     += "IMPORTANT: If there are any sub-items for the selected item(s), the sub-items will be deleted too.\n\n";
            confirmMsg                     += "Click OK to continue, or Cancel to abort";
            var confirmIt                   = confirm(confirmMsg);
            if (confirmIt){
                sendIt('/index.php','POST','action=deleteTasks&deleteList='+deleteList);
            }
        }
    }
}

/* Confirms whether user wants to delete tag. If yes, then send AJAX request to delete tag */
function deleteTag(tagID){
    var confirmIt                           = confirm('Are you sure you want to delete this tag?\n\n NOTE: This will not delete the tasks associated with the tag, just the tag itself.');
    if (confirmIt){
        clearForm('editTaskForm');
        sendIt('/index.php','POST','action=deleteTag&tagID='+tagID+'&currentView='+currentView);
    }
}

/* Hides deleted task and removes it from taskListArray */
function removeDeletedTask(taskID){
    
    /* Removes deleted task */
    var thisNode                            = document.getElementById('task'+taskID);
    thisNode.parentNode.removeChild(thisNode);
    
    /* Checks number of children remaining in task list */
    var taskList                            = document.getElementById('taskList');
    taskListChildren                        = taskList.getElementsByTagName('div');
    
    /* If there is only one child in the task list (the top Insert Here bar), or if
    there are two children and one is the taskCompletedDivider (meaning the other is
    the top Insert Here bar), then the task list is empty. */
    if (taskListChildren.length == 1 || (taskListChildren.length == 2 && document.getElementById('taskCompletedDivider'))){
        
        /* If emptyList already exists on this page, shows it. Otherwise creates it and
        inserts it into page. */
        if (document.getElementById('emptyList')){
            
            showIt('emptyList');
            
        } else {
        
            /* Creates emptyList html */
            var emptyListHTML                   = "<em>There are no items currently assigned to this list.</em><br><br> <div class=\"text3\"><img src=\"/images/quickTip.gif\" align=\"absmiddle\"> Check out the <a href=\"/help\" class=\"link\">Help</a> section for some useful tips and hints.</div>";
            
            /* Creates new div to hold emptyList html */
            var htmlNode                        = document.createElement('div');
            htmlNode.setAttribute('id','emptyList');
            htmlNode.innerHTML                  = emptyListHTML;
            
            /* Inserts emptyList */
            document.getElementById('listBody').appendChild(htmlNode);
        }
    }
    removeTaskFromListArray(taskID);
}

/* 
 *-----------------------------------------------------------------------
 * SAVE/LOAD FUNCTIONS
 * -----------------------------------------------------------------------
*/

function loadTask(name,description,tags){
    
    var editForm                        = document.editTaskForm;
    clearMove();
    showIt('taskViewBody');
    editForm.taskName.value             = decodeURIComponent(name);
    editForm.taskDesc.value             = decodeURIComponent(description);
    editForm.taskTags.value             = decodeURIComponent(tags);
    
    originalTask[0]                     = editForm.taskName.value;
    originalTask[1]                     = editForm.taskDesc.value;
    originalTask[2]                     = editForm.taskTags.value;
}

function saveTask(taskID){
    
    /* Resets the originalTask array */
    originalTask.length                 = 0;
    
    var editForm                        = document.editTaskForm;
    var taskName                        = encodeURIComponent(editForm.taskName.value);
    var taskDesc                        = encodeURIComponent(editForm.taskDesc.value);
    var taskTags                        = encodeURIComponent(editForm.taskTags.value);
    document.getElementById('saveMsg').innerHTML = 'Saving ...';
    sendIt('/index.php','POST','action=save&taskID='+taskID+'&taskName='+taskName+'&taskDesc='+taskDesc+'&taskTags='+taskTags+'&parentTaskID='+listID+'&currentView='+currentView+'&tagID='+currentTagID);
}

function replaceTask(taskID,taskHTML){
    
    hideIt('emptyList');
    
    var taskList                        = document.getElementById('taskList');
    var taskListDivs                    = taskList.getElementsByTagName('div');
    for (i=0;i<taskListDivs.length;i++){
        if (taskListDivs[i].id == "task"+taskID){
            var removeThis              = document.getElementById('task'+taskID);
            taskList.removeChild(removeThis);
            var oldNodeNum              = i;
            break;
        }
    }

    /* Creates new div to hold new taskHTML */
    var newTask                         = document.createElement('div');
    newTask.setAttribute('class','task');
    newTask.setAttribute('className','task');
    newTask.setAttribute('id','task'+taskID);
    newTask.innerHTML                   = decodeURIComponent(taskHTML);
    
    /* Replaces html of old task with that of new task */
    taskListDivs                        = taskList.getElementsByTagName('div');
    var insertBeforeThis                = taskListDivs[oldNodeNum];
    taskList.insertBefore(newTask,insertBeforeThis);
    
    highlightTask('selected',taskID);

    /* Highlights then fades edited task */
    if (document.getElementById('taskName'+taskID)){
        Fade.fade_element('color','taskName'+taskID,30,2000,'#83E56D','#FFFFFF');
    }
    clearForm('editTaskForm');
}

/* 
 *-----------------------------------------------------------------------
 * SEARCH FUNCTIONS
 * -----------------------------------------------------------------------
*/

function loadSearch(){
    clearForm('editTaskForm');
    currentView                         = "search";
    listID                              = 0;
    top.location.href                   = "/ls/"+currentView+"/"+listID+"/"+accountID+"/";
}

function getSearch(searchFor){
    
    clearForm('editTaskForm');
    var form                            = document.searchForm;
    var searchBox                       = form.searchBox;
    var searchByName                    = form.searchByName;
    var searchByDesc                    = form.searchByDesc;
    var searchByTag                     = form.searchByTag;
    
    if (searchFor != undefined && searchFor != ""){
        searchBox.value                 = searchFor;
    } 
    if (searchBox.value == ""){
        showStatus('error','Please enter a search term.');
    } else if (searchByName.checked == false && searchByDesc.checked == false && searchByTag.checked == false){
        showStatus('error','Please check at least one Search By box.');
    } else {
        var searchFor                   = encodeURIComponent(searchBox.value);
        top.location.href               = "/s/"+searchFor+"/"+currentView+"/"+searchByName.checked+"/"+searchByDesc.checked+"/"+searchByTag.checked+"/"+accountID+"/";
    }
    return false;
}

function searchByAll(isChecked){
    document.getElementById('searchByName').checked         = isChecked;
    document.getElementById('searchByDesc').checked         = isChecked;
    document.getElementById('searchByTag').checked          = isChecked;
}

function uncheckAll(){
    
    if (document.getElementById('searchByName').checked == true && document.getElementById('searchByDesc').checked == true && document.getElementById('searchByTag').checked == true){
        document.getElementById('searchAll').checked      = true;
    } else {
        document.getElementById('searchAll').checked      = false;
    }
}


/* 
 *-----------------------------------------------------------------------
 * HELPER FUNCTIONS
 * -----------------------------------------------------------------------
*/

/* Loops through listArray and removes task */
function removeTaskFromListArray(taskID){
    for (i=0;i<listArray.length;i++){
        if (listArray[i] == taskID){
            listArray.splice(i,1);
            break;
        }
    }
}

function inArray(needle,haystack){
    
    var returnValue = false;

    for (a=0;a<haystack.length;a++){
        if (haystack[a] == needle){
            returnValue = true;
        }
    }
    return returnValue;
}


function highlightTask(state,taskID){
    
    if (currentTaskID != taskID && currentTaskID != 0){
        if (document.getElementById('taskBody'+currentTaskID)){
            highlightTask('off',currentTaskID,currentTaskCompleted);
        }
    }
    
    currentTaskID                                                       = taskID;
    
    /* Text */
    var taskName                                                        = "taskName"+taskID;
    var subtasks                                                        = "subtasks"+taskID;
    
    /* Background */
    var taskBody                                                        = "taskBody"+taskID;
    var taskFooter                                                      = "taskFooter"+taskID;
    
    if (document.getElementById(taskBody) && document.getElementById(taskName) && document.getElementById(taskFooter)){
    
        if (state == "off"){
           
            document.getElementById(taskBody).className                     = "taskBody";
            document.getElementById(taskName).className                     = "taskNameLink";
            document.getElementById(taskFooter).className                   = "taskFooter";
            
            if (document.getElementById(subtasks)){
                document.getElementById(subtasks).className                 = "completedSubtasks";
            }
            
        } else if (state == "selected"){
            
            document.getElementById(taskBody).className                     = "taskBodySelected";
            document.getElementById(taskName).className                     = "taskNameSelected";
            document.getElementById(taskFooter).className                   = "taskFooterSelected";
            
            if (document.getElementById(subtasks)){
                document.getElementById(subtasks).className                 = "completedSubtasksSelected";
            }
        }
    }
    
}

function confirmCancel(){
    var confirmIt = confirm('Are you sure you want to cancel?');
    
    if (confirmIt){
        originalTask.length = 0;
        clearForm('addTaskForm');
        clearForm('editTaskForm');
        clearForm('addTagsForm');
        highlightTask('off',currentTaskID);
    }
}

function setListName(listName){
    document.getElementById('listNameBox').innerHTML = decodeURIComponent(listName);
}

function printPage(){
    window.open(window.location.href+"?print=preview");
}

/* 
 *-----------------------------------------------------------------------
 * USER FUNCTIONS
 * -----------------------------------------------------------------------
*/

function logIn(){
    
    var form                            = document.loginForm;
    var email                           = form.email.value
    var password                        = form.password.value;
    var rememberMe                      = form.rememberMe.checked;
    
    if (email == ""){
        showStatus('error','Please enter your email address.');
    } else if (password == ""){
        showStatus('error','Please enter your password.');
    } else {
        sendIt('/index.php','POST','action=login&email='+encodeURIComponent(email)+'&password='+encodeURIComponent(password)+'&rememberMe='+rememberMe);
    }
}

function changeEmail(){
    var form                            = document.changeEmailForm;
    var email                           = form.email.value
    var password                        = form.password.value;
    
    if (email == ""){
        showStatus('error','Please enter your new email address.');
    } else if (password == ""){
        showStatus('error','Please enter your current password.');
    } else {
        sendIt('/index.php','POST','action=changeEmail&email='+encodeURIComponent(email)+'&password='+encodeURIComponent(password));
    }
}

function logOut(){
    sendIt('/index.php','POST','action=logOut');
}

function signUp(){
    
    var form                            = document.signUpForm;
    var email                           = form.email.value
    var password                        = form.password.value;
    var confirmPassword                 = form.confirmPassword.value;
    var rememberMe                      = form.rememberMe.checked;
    
    if (email == ""){
        showStatus('error','Please enter your email address.');
    } else if (password == ""){
        showStatus('error','Please enter your password.');
    } else if (password.length < 6){
        showStatus('error','Your password is too short. It must be at least 6 characters long.');
    } else if (confirmPassword == ""){
        showStatus('error','Please retype your password.');
    } else if (confirmPassword != password){
        showStatus('error','Your passwords do not match. Please try again.');
    } else {
        sendIt('/index.php','POST','action=signUp&email='+encodeURIComponent(email)+'&password='+encodeURIComponent(password)+'&rememberMe='+rememberMe);
    }
}

function resendConfirmationEmail(){
    sendIt('/index.php','POST','action=resendConfirmationEmail');
}

function resetPassword(){
    
    var form                            = document.resetPasswordForm;
    var email                           = form.email.value
    var password                        = form.password.value;
    var confirmPassword                 = form.confirmPassword.value;
    var authKey                         = form.authKey.value;
    
    if (password == ""){
        showStatus('error','Please enter your new password.');
    } else if (password.length < 6){
        showStatus('error','Your new password is too short. It must be at least 6 characters long.');
    } else if (confirmPassword == ""){
        showStatus('error','Please retype your new password.');
    } else if (confirmPassword != password){
        showStatus('error','Your new passwords do not match. Please try again.');
    } else {
        sendIt('/index.php','POST','action=resetPassword&email='+encodeURIComponent(email)+'&password='+encodeURIComponent(password)+'&authKey='+encodeURIComponent(authKey));
    }
}

function sendPassword(){
    
    var form                            = document.loginForm;
    var email                           = form.email.value
    
    if (email == ""){
        showStatus('error','Please enter your email address.');
    } else {
        sendIt('/index.php','POST','action=forgotPassword&email='+encodeURIComponent(email));
    }
}

function resendConfirmation(){
    
    var form                            = document.signUpForm;
    var email                           = form.email.value
    
    if (email == ""){
        showStatus('error','Please enter your email address.');
    } else {
        sendIt('/index.php','POST','action=resendConfirmation&email='+encodeURIComponent(email));
    }
}

/* 
 *-----------------------------------------------------------------------
 * SHOW/HIDE FUNCTIONS
 * -----------------------------------------------------------------------
*/

function showAddTask(){

    if (currentTaskID != 0 || currentTaskID == undefined){
        highlightTask('off',currentTaskID);
    }
    showIt('addTaskBody');
    hideIt('taskViewBody');
    hideIt('addTagsBody');
    clearMove();
    document.addTaskForm.taskName.focus();
}

function showAddTags(){
    if (selectedItems.length == 0){
        showStatus('error','Please select an item');
    } else {
        showIt('addTagsBody');
        hideIt('rightColAdBox');
        document.addTagsForm.taskTags.focus();
    }
}

function toggleHelpMenu(section){
    
    if (document.getElementById(section+"Arrow").alt == "Show "+section){
        document.getElementById(section+"Arrow").src = "/images/downArrow.gif";
        document.getElementById(section+"Arrow").alt = "Hide "+section;
    } else {
        document.getElementById(section+"Arrow").src = "/images/rightArrow.gif";
        document.getElementById(section+"Arrow").alt = "Show "+section;
    }
    showHide(section+"Menu");
}

function markPending(taskID,pendingStatus){
    if (pendingStatus == "show"){
        showHide('pendingStatus'+taskID);
    } else {
        sendIt('/index.php','POST','action=markPending&taskID='+taskID+'&pendingStatus='+pendingStatus+'&currentView='+currentView);
    }
}
function getWindowHeight() {
	var windowHeight = 0;
	if (typeof(window.innerHeight) == 'number') {
		windowHeight = window.innerHeight;
	}
	else {
		if (document.documentElement && document.documentElement.clientHeight) {
			windowHeight = document.documentElement.clientHeight;
		}
		else {
			if (document.body && document.body.clientHeight) {
				windowHeight = document.body.clientHeight;
			}
		}
	}
	return windowHeight;
}
function getWindowWidth() {
	var windowWidth = 0;
	if (typeof(window.innerWidth) == 'number') {
		windowWidth = window.innerWidth;
	}
	else {
		if (document.documentElement && document.documentElement.clientWidth) {
			windowWidth = document.documentElement.clientWidth;
		}
		else {
			if (document.body && document.body.clientWidth) {
				windowWidth = document.body.clientWidth;
			}
		}
	}
	return windowWidth;
}
function setContent() {
	if (document.getElementById) {
		var windowHeight = getWindowHeight();
		var windowWidth = getWindowWidth();
		if (windowHeight > 0) {
			var contentElement = document.getElementById('statusMsg');
			var contentHeight = contentElement.offsetHeight-12;
			var contentWidth = contentElement.offsetWidth-12;
//			if (windowHeight - contentHeight > 0) {
				contentElement.style.position = 'relative';
				contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px';
				contentElement.style.left = ((windowWidth / 2) - (contentWidth / 2)) + 'px';
//			}
//			else {
//				contentElement.style.position = 'static';
//			}
		}
	}
}

window.onresize = function() {
	//setContent();
}
