
var http;
var isWorking = false;

var currNav = "";   //variable to keep track of currently selected top-nav:  'person', 'category', 'status', or 'priority'

function initAppTrack(){
    //load default list to page
    getList('','','person');
    //load default nav
    getSubNav('person');
    currNav="person";
}

//**************
//**  THE FOLLOWING FUNCTIONS MANAGE EDITING A SINGLE ENTRY
//*************
//this function runs when a line item is clicked
function editItem(listItem){
    listId = listItem.id;
    //get item details via Ajax - populate main viewing area
    getListDetails(listId);
}

var http3;
function getListDetails(listId){
    http3 = initAjax();
	var d = new Date();
	t = d.getTime();
    http3.open("GET", "/agWork/theList/ajaxActions/getListDetails.php?tm="+t+"&id=" + escape(listId) , true);
    http3.onreadystatechange = handleGetListDetailsResponse;
    isWorking = true;
    http3.send(null);
}

//this function handles the resuls from getList
function handleGetListDetailsResponse(selected) {
    if (http3.readyState == 4) {
        var listDetails = http3.responseText;
        document.getElementById("itemListHolder").innerHTML=listDetails;
        isWorking = false;
    }
}


//this function manages the default text for the note box
function startNoteText(noteBox){
    if((noteBox.value=="enter new note") || (noteBox.value=="enter description of request")){
        noteBox.value="";
    }
}


//this function handles saving a new note for an existing entry
var http5;
function saveNote(noteFrm, listId){
    http5 = initAjax();
    newNoteText = noteFrm.value;
    //need to replace characters that cause problems with SQL
    newNoteText = escapeToHTML(newNoteText);
    document.editList.note.value="saving note...";
	var d = new Date();
	t = d.getTime();
    http5.open("GET", "/agWork/theList/ajaxActions/saveNote.php?tm="+t+"&noteText=" + escape(newNoteText) + "&listId="+escape(listId) , true);
    http5.onreadystatechange = handlesaveNoteResponse;
    isWorking = true;
    http5.send(null);
}

//this function handles the resuls from getList
function handlesaveNoteResponse() {
    if (http5.readyState == 4) {
        var newNote = http5.responseText;
        document.getElementById("comments").innerHTML = newNote + document.getElementById("comments").innerHTML;
        document.editList.note.value="enter new note";
        isWorking = false;
        http5=null;
    }
}


//this function is triggered when a user is changed - prompts to send email or not
//  accepts the full form
//  and the id of the user PRIOR to edits
function changeUser(frm, origUserId){
	return;//removed for demo purposes
    selectedUserId = frm.user[frm.user.selectedIndex].value
    if(selectedUserId!=origUserId){     //new user, prompt for email
        frm.user.style.margin="0 0 0px 0";
        frm.sendEmail.checked=true;
        document.getElementById("sendEmailCheck").style.display="block";
    }else{                              //back to original user - no email
        frm.sendEmail.checked=false;
    }
}


//this function saves changes to a list item
//  it accepts the entire form,
//  the id of the list item
//  object reference to <a>
var http6;
function saveListChanges(frm, listId){
    newUser = frm.user.value;
    newSendEmail = "";//removed for demo frm.sendEmail.checked;
    newRequestType = frm.fixFeature.value;
    newPriority = frm.priority.value;
    newDifficulty = frm.difficulty.value;
    newCategory = frm.category.value;
    newStatus = frm.status.value;
    document.getElementById("saveListLink").innerHTML="<b>saving...</b>"

    http6=initAjax();
	var d = new Date();
	t = d.getTime();
    http6.open("GET", "/agWork/theList/ajaxActions/saveListChanges.php?tm="+t+"&listId=" + listId + "&newUser=" + escape(newUser) + "&newSendEmail="+escape(newSendEmail) + "&newRequestType="+escape(newRequestType) + "&newPriority="+escape(newPriority) + "&newDifficulty="+escape(newDifficulty) + "&newCategory="+escape(newCategory) + "&newStatus="+escape(newStatus) , true);
    http6.onreadystatechange = handleSaveListChangesResponse;
    isWorking = true;
    http6.send(null);

}


//this function handles the resuls from getList
function handleSaveListChangesResponse() {
    if (http6.readyState == 4) {
        document.getElementById("saveListLink").innerHTML="<b style='color:#973838;'>changes saved</b>"
        setTimeout('document.getElementById("saveListLink").innerHTML="save changes"',2000);
        //this run returns nothing (note: need to check for errors!)
        //var newNote = http6.responseText;
        //document.getElementById("comments").innerHTML = newNote + document.getElementById("comments").innerHTML;
        isWorking = false;
        http6=null;
    }
}


//this function manages adding a new list item
var http7;
function newListItem(){
    http7=initAjax();
    showLoading();
	var d = new Date();
	t = d.getTime();
    http7.open("GET", "/agWork/theList/ajaxActions/newListItem.php?tm="+t, true);
    http7.onreadystatechange = handleNewListItemResponse;
    isWorking = true;
    http7.send(null);
}

function handleNewListItemResponse() {
    if (http7.readyState == 4) {
        var newListScreen = http7.responseText;
        document.getElementById("itemListHolder").innerHTML = newListScreen;
        isWorking = false;
        http7=null;
    }
}



//this function manages saving a new list item
var http8;
function saveNewListItem(frm){
    newUser = frm.user.value;
    enteredByUser = frm.enteredBy[frm.enteredBy.selectedIndex].value;
    newSendEmail = "";	// disabled: frm.sendEmail.checked;
    newRequestType = frm.fixFeature.value;
    newPriority = frm.priority.value;
    newDifficulty = frm.difficulty.value;
    newCategory = frm.category.value;
    newStatus = frm.status.value;
    newDescr = frm.shortDescr.value;
    //escape special characters
    newDescr = escapeToHTML(newDescr);
    document.getElementById("saveListLink").innerHTML="<b>saving...</b>"
//document.getElementById("itemListHolder").innerHTML="/agWork/theList/ajaxActions/saveNewListItem.php?newUser=" + escape(newUser) + "&newSendEmail="+escape(newSendEmail) + "&newRequestType="+escape(newRequestType) + "&newPriority="+escape(newPriority) + "&newDifficulty="+escape(newDifficulty) + "&newCategory="+escape(newCategory) + "&newStatus="+escape(newStatus) + "&newDescr=" + escape(newDescr) + "&enteredBy=" + escape(enteredByUser);
//return;
    http8=initAjax();
	var d = new Date();
	t = d.getTime();
    http8.open("GET", "/agWork/theList/ajaxActions/saveNewListItem.php?tm="+t+"&newUser=" + escape(newUser) + "&newSendEmail="+escape(newSendEmail) + "&newRequestType="+escape(newRequestType) + "&newPriority="+escape(newPriority) + "&newDifficulty="+escape(newDifficulty) + "&newCategory="+escape(newCategory) + "&newStatus="+escape(newStatus) + "&newDescr=" + escape(newDescr) + "&enteredBy=" + escape(enteredByUser) , true);
    http8.onreadystatechange = handleSaveNewListItemResponse;
    isWorking = true;
    http8.send(null);
}

function handleSaveNewListItemResponse() {
    if (http8.readyState == 4) {
        //this just returns the id of the new item
        var newListId = http8.responseText;
        http8=null;
        //should just be able to do a getListItemDetail with the new id
		//document.getElementById("itemListHolder").innerHTML = newListId;	//DEBUG
		
        if(newListId.indexOf("error")!=-1){
            //if error, say so
            document.getElementById("itemListHolder").innerHTML = "<ul id='listItems'><li>error saving new item.<br /><br />"+newListId+"</li></ul>";
        }else{
            getListDetails(newListId);
        }
		
		
        isWorking = false;
    }
}



//**************
//**  THE FOLLOWING FUNCTIONS MANAGE LOGGING IN
//*************
var http4;
function logonUser(usernm, psswd, lnk){
    http4 = initAjax();
    lnk.innerHTML="logging on...";
	var d = new Date();
	t = d.getTime();
    http4.open("GET", "/agWork/theList/ajaxActions/logonUser.php?tm="+t+"&user_name=" + escape(usernm) + "&user_password=" + escape(psswd) , true);
    http4.onreadystatechange = handleLogonUserResponse;
    isWorking = true;
    http4.send(null);
}


//this function handles the resuls from getList
function handleLogonUserResponse(link) {
    if (http4.readyState == 4) {
        var userState = http4.responseText;
        //update the user area for both the blog, and the list
        document.getElementById("appTrackUserInfo").innerHTML = userState;
        //document.getElementById("blogUserInfo").innerHTML = userState;
        isWorking = false;
        http4=null;
    }
}


//**************
//**  THE FOLLOWING FUNCTIONS MANAGE SEARCHING
//*************
var http9;
function startSearch(){
	window.alert("coming soon");
	return;
 	http9 = initAjax();
    lnk.innerHTML="logging on...";
	var d = new Date();
	t = d.getTime();
    http9.open("GET", "/agWork/theList/ajaxActions/searchStart.php?tm="+t, true);
    http9.onreadystatechange = handleStartSearchResponse;
    isWorking = true;
    http9.send(null);
}

//this function handles the resuls from getList
function handleStartSearchResponse() {
    if (http9.readyState == 4) {
        var searchScreen = http9.responseText;
        document.getElementById("itemListHolder").innerHTML=searchScreen;
        isWorking = false;
        http9=null;
    }
}

var http10;
function getSearchResults(){
 	http10 = initAjax();
    lnk.innerHTML="logging on...";
	var d = new Date();
	t = d.getTime();
    http10.open("GET", "/agWork/theList/ajaxActions/searchResults.php?tm="+t, true);
    http10.onreadystatechange = handleGetSearchResultsResponse;
    isWorking = true;
    http10.send(null);
}

//this function handles the resuls from getList
function handleGetSearchResultsResponse() {
    if (http10.readyState == 4) {
        var searchRes = http10.responseText;
        document.getElementById("itemListHolder").innerHTML=searchRes;
        isWorking = false;
        http10=null;
    }
}





//**************
//**  THE FOLLOWING FUNCTIONS DEFINE NAVIGATION AND MOVING ABOUT THE APP
//*************

function showLoading(){
    document.getElementById("itemListHolder").innerHTML="<ul id='listItems'><li style='font-size:3em; text-align:center; color:#B6DAF3; padding-top:100px;'>Loading...</li></ul>";
}


//this is the function that gets the main body list.  The parameters are:
//  orderBy:  a string defining the field to sort on
//  where: a string defining the name value pairs of the final where clause:  eg.  name,patrick|status,new  equates to "where name=patrick and status=new"
//  listType: a string defining what the list results should look like (which columns/headings) : 'person', 'category', 'status', or 'priority'
var lastOrderByField="";//keep track of last order by field to toggle sort
var sortDirection="desc"
function getList(orderBy, where, listType){
    http = initAjax();
    showLoading();

    //determine orderBy
    if(orderBy!=""){
        if(orderBy==lastOrderByField){
            toggleSort();
        }else{
            sortDirection="desc";   //default to descending
        }
        lastOrderByField = orderBy;
        orderBy = orderBy + "," + sortDirection;
    }

    //determine where
    whereArray = where.split("|");
    if(whereArray.length>0){
        //here!  need to sort this out to allow sorting within a subview (eg. "Patrick")
    }
	var d = new Date();
	t = d.getTime();
    http.open("GET", "/agWork/theList/ajaxActions/getList.php?tm="+t+"&orderBy=" + escape(orderBy) +"&where="+ escape(where) + "&listType=" + escape(listType), true);
    http.onreadystatechange = handleGetListResponse;
    isWorking = true;
    http.send(null);
}


//this function handles the resuls from getList
function handleGetListResponse() {
    if (http.readyState == 4) {
        var newList = http.responseText;
        document.getElementById("itemListHolder").innerHTML=newList;
        isWorking = false;
    }
}

//simple function to toggle the sort direction
function toggleSort(){
    if(sortDirection=="desc"){
        sortDirection="asc";
    }else{
        sortDirection="desc";
    }
}


//this function sets the top-level nav, eventually setting the lower level nav
//  it is passed the top level nav name:  either 'person', 'category', 'priority', 'status' or 'requester'
//  and the list item object of the top level nav
function setNav(selected, listItem){
    //first, hide all sub lists of the sibling list items (ie, hide all subnavs)
    //get parent list
    topList = listItem.parentNode;
    //get all top level items
    topListItems = topList.getElementsByTagName("LI");
    for(i=0;i<topListItems.length;i++){
        //get the child UL (the subnav list)
        subList = topListItems[i].getElementsByTagName('UL');
        if(subList.length>0){
            topListItems[i].removeChild(subList[0]);
        }
        //while here, remove any 'selected' classes
        topListItems[i].className = topListItems[i].className.replace("selected", "");
    }

    //set global variable
    currNav=selected;

    //all subnavs hidden, now set current as selected, and show subnav
    currTopNav = document.getElementById(selected);
    currTopNav.className += " selected";
    getSubNav(selected);

    //finally load main frame with list
    getList('','',selected);
}



//this function gets the subnav for the selected nav
//  it accepts one parameter: the name of the top level nav:  either 'person', 'category', 'priority' or 'status'
var http2;
function getSubNav(selected){
    http2 = initAjax();
	var d = new Date();
	t = d.getTime();
    http2.open("GET", "/agWork/theList/ajaxActions/getSubNav.php?tm="+t+"&nav=" + escape(selected) , true);
    http2.onreadystatechange = handleGetNavResponse;
    isWorking = true;
    http2.send(null);
}

//this function handles the resuls from getList
function handleGetNavResponse() {
    if (http2.readyState == 4) {
        var newList = http2.responseText;
        document.getElementById(currNav).innerHTML+=newList;
        isWorking = false;
    }
}



//this function sets the passed list item as selected, and removes the selected class from all siblings
function setSubNav(listItem){
    fullList = listItem.parentNode;
    allListItems = fullList.getElementsByTagName("LI");
    for(i=0;i<allListItems.length;i++){
        allListItems[i].className = allListItems[i].className.replace("selected","");
    }
    listItem.className += " selected";
}





//function to escape typed characters from html entities
function escapeFromHTML(text){
    while(text.indexOf("<br />")!=-1){
       text = text.replace("<br />","\n");
    }
    return text;
}


//function to escape typed characters to html entities
function escapeToHTML(text){
    while(text.indexOf("'")!=-1){
       text = text.replace("'","&#39;");
    }
    while(text.indexOf("(")!=-1){
       text = text.replace("(","&#40;");
    }
    while(text.indexOf(")")!=-1){
       text = text.replace(")","&#41;");
    }
    while(text.indexOf("\n")!=-1){
       text = text.replace("\n","<br />");
    }
	//getting rid of any script tags so people with nothing better to do won't mess me up...
	while(text.indexOf("<script")!=-1){
       text = text.replace("<script","sc.ript");
    }
	
    return text;
}






//this function initializes the http object
function initAjax(){
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
	  xmlhttp.overrideMimeType("text/xml");
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}
