/**
 * @author mobitect
 */

function initPage() {

	doUpdateSettings();
	doTimer();

	// If they have not yet set the company and token api then set page to settings page
	var settingsXML = localStorage.getItem("settings");
	if (settingsXML == null) {
		alert("Please set the company name and API token in the settings tab to download your data.");
	}

}

function executeSearch(searchType, e) {
	//First find out, if it is a keypress then verify that we search on keypress
	var charCode;
    
    if(e && e.which){
        charCode = e.which;
    }else if(window.event){
        e = window.event;
        charCode = e.keyCode;
    }

    //Charcode 13 = Enter
	settingContainer = document.getElementById("KeyPressSearch");
    if ((settingContainer.className.indexOf("togButtonOn") == -1) && (charCode != 13))
		return;
	
	// This will take the results of the search window and filter the appropriate lists 
	var filterStr="";
	if (searchType == "Contact") {
		filterStr  = document.getElementById('contactFilter').value;
		var myList = $("#Contacts>ul>li>a");
	} else if (searchType == "Task") {
		filterStr  = document.getElementById('taskFilter').value;
		var myList = $("#Tasks>ul>li>a");
	} else if (searchType == "Notes") {
		filterStr  = document.getElementById('noteFilter').value;
		var myList = $("#Notes>ul>li>a");
	}

	if (myList.length === 0) {
			return false;
	}
	myList.each(function () {
			if ($(this).html().toLowerCase().indexOf(filterStr.toLowerCase()) == -1) {
					$(this).parent('li').hide();
			} else {
					$(this).parent('li').show();   
			}
	});
}

function saveNote() {
	//	This will take a note and save it to HighriseHQ

	var PersonID  = document.getElementById('ContactID').value;
	var noteValueStr  = document.getElementById('noteString').value;
	var noteStr = "<note>";
	noteStr += "<body>"+noteValueStr+"</body>";
	noteStr += "</note>"

	// Load the API token from localstorage, if it is blank then skip the sync
	var companyName = "";
	var apiToken = "";
	var settingsXML = localStorage.getItem("settings");

	if (settingsXML != null) {
		var xmlobject = (new DOMParser()).parseFromString(settingsXML, "text/xml");
		companyName = $(xmlobject).find('company-name').text();
		apiToken = $(xmlobject).find('api-token').text();
	}

	var proxyServer="";
	var highriseServer="";
	var url="";
	var currentURL = document.URL;

	// This part is simply for debugging purposes, if the url contains cavanagh-pc then ignore the appendServer
	if ( (currentURL.indexOf("cavanagh-pc") == -1) && (url.indexOf("php") == -1 ) ){
		url = "http://mobitect.com/crm/proxy/post_note.php?user=";
		url += apiToken;
		url += "&pwd=X&company=";
		url += companyName;
		url += "&person=";
		url += PersonID;
		url += "&bodyStr=";
		url += noteStr;
	}

	if(req) { 
		req = new XMLHttpRequest();
		req.onreadystatechange = processReqChange;
		req.open("GET", url, true);
		req.send(null);
	}	
}

function doUpdateItems(url) {

	// Update the network status
	var status = document.getElementById('status');
	status.innerHTML = navigator.onLine ? '<font color="forestgreen">Online</font>' : '<font color="red">Offline</font>';

	// If network status is available download the latest changes and update the lists
	if (navigator.onLine == true) {
		// First download the latest changes
		downloadAllData(url);
	}

}

function updateOnDemandList(listType, listData) {
	var updatedAtDate = $(listData).find('updated-at').text();
	var ulElem =document.getElementById(listType);;
	// If the item already exists then remove it so it can be updated (i.e. if the name changed)
	var itemElem = document.getElementById($(listData).find('id').text());
	if (itemElem != null)
		ulElem.removeChild(itemElem);

	var newLi = document.createElement("Li");
	newLi.setAttribute("id",$(listData).find('id').text());
	var newAnchor = document.createElement("A");

	newAnchor.setAttribute("style","text-decoration:none;color:#111111");
	newAnchor.setAttribute("id",$(listData).find('id').text());
	newAnchor.innerHTML = "<font size=3>("+updatedAtDate.substring(0,10)+")</font><br>"+$(listData).find('body').text();
	newLi.appendChild(newAnchor);
	ulElem.appendChild(newLi);

}
function updateList(listType, subType) {

	var pairs = "";
	var key = "";
	var i=0;

	// First I need to check the status LocalStorage to see if there are any new or updated items
	// I do this by getting the latest timestamp and comparing it to the timestamp of the list
	var storageLastModified = localStorage.getItem(listType+"-last-modified");

	
	if (listType == "person") {
		if  (storageLastModified < personListLastModified) 
			return;
		else 
			personListLastModified = storageLastModified;
	}	
	
	var ulElem =document.getElementById(listType+subType);;
	var newItemCount = 0;

	// Append the new items if they are not there
	for (i=0; i<=localStorage.length-1; i++) {

		key = localStorage.key(i);
		if ( (key.indexOf("last-modified") == -1) && (key.indexOf("settings") == -1) )
		{
				var myItem = localStorage.getItem(key);
				var xmlobject = (new DOMParser()).parseFromString(myItem, "text/xml");

				$(xmlobject).find(listType).each(function(){
					var id = $(this).find('id').text();
					var newName = "";

					if (listType == "task") {
						if (subType == "Overdue" ) {
							if ($(this).find('frame').text() == "overdue")
								newName =  $(this).find('body').text();
						} else if (subType == "ThisWeek") {
							if ($(this).find('frame').text() == "this_week")
								newName =  $(this).find('body').text();
						} else if (subType == "NextWeek") {
							if ($(this).find('frame').text() == "next_week")
								newName =  $(this).find('body').text();
						}
						else if (subType == "Later") {
							if ($(this).find('frame').text() == "later")
								newName =  $(this).find('body').text();
						}
					}
					else if (listType == "person") {
						newName =  $(this).find('first-name').text()+" "+$(this).find('last-name').text();
					} else if (listType == "notification") {
						newName =  $(this).find('subject').text();
					}
					
					
					// If the newName is blank then it likely means that it is an item from a differnent group
					if (  (newName.indexOf(contactFilterStr) != -1) && (newName != "") ) {
						var newLi = document.createElement("Li");
						newLi.setAttribute("id",key);
						var newAnchor = document.createElement("A");
		
						if (listType == "person") {
							newAnchor.setAttribute('onclick','updateContactDetails('+key+');'); 
							newAnchor.setAttribute("href","#Contact_Details");
							newAnchor.setAttribute("style","text-decoration:none;color:#111111");
						} else if (listType == "notification") {
							newAnchor.setAttribute('onclick','updateNotificationDetails("'+key+'");'); 
							newAnchor.setAttribute("href","#Notification_Details");
						} 

						newAnchor.setAttribute("id",newName);
						newAnchor.innerHTML = newName;
						// If the item already exists then remove it so it can be updated (i.e. if the name changed)
						var itemElem = document.getElementById(key);
						if (itemElem != null)
							ulElem.removeChild(itemElem);

						newLi.appendChild(newAnchor);
						ulElem.appendChild(newLi);
						newItemCount += 1;
					}
					});

		}
        }
	
	// If there is a new item added to the list then re-sort
	if ( (newItemCount > 0 ) ) {
		if (listType == "person") {
			// If there is a new person then I should also try to re-download the companies
			doUpdateItems("companies.xml");
			//sortUnorderedList(listType, false);
			$("ul#person>li").tsort();
		} else if ( (listType == "task") ) {
			if (subType == "Overdue")
				$("ul#taskOverdue>li").tsort();
			else if (subType == "ThisWeek")
				$("ul#taskThisWeek>li").tsort();
			else if (subType == "NextWeek")
				$("ul#taskNextWeek>li").tsort();
			else if (subType == "Later")
				$("ul#taskLater>li").tsort();
		}
	}
}



// used by the orientation sample
if("orientation" in window)
{
	setTimeout("updateOrientation()",10000);
}

// used by the orientation sample
function updateOrientation()
{
	var displayStr = "Orientation " + "(" + window.orientation + "): ";
	
	switch(window.orientation)
	{	
		case 0:
			displayStr += "Portrait";
		break;
		
		case -90:
			displayStr +=  "Landscape (right, screen turned clockwise)";
		break;
		
		case 90:
			displayStr += "Landscape (left, screen turned counterclockwise)";
		break;
		
		case 180:
			displayStr += "Portrait (upside-down portrait)";
		break;
		
	}
	document.getElementById("orientationBucket").innerHTML = displayStr;
}

var startDate = null;


