// This file was generated by Dashcode from Apple Inc.
// You may edit this file to customize your web application.
var urlPrefix = ""; 
//var urlPrefix = "http://";
var dataServer = "";
//var dataServer = "oldmary.lqhome.com";
var dataServerApplicationPath = "/cgi-bin/WebObjects/lotiobservation.woa/wa/DirectAction/";// lotiObserver.woa (beta)
//var dataServerApplicationPath = "dataFeed.php?";// lotiObserver.woa (beta)

var mainDatabase;

var ownerID = 0;
var formID = 0;
var formName = "Unset";

var sectionIndex = 0;//current observer page
var currentObservation = null; //
//
var formTemplate = null;	 // 3 arrays: title, description, data[lookfors[]]
//var observerTemplateString = '';
var teachers = [];   // array of teachers: name, email, id (value = name+email) 
var observations = [];//observations;

// display flags
var needsDisplay = false;
var sectionListNeedsDisplay = true;
//
var formNames = []; // an array to hold the names of available forms
var formTemplateArray = []; // an array to hold the formTempates.  An array of array's - new Array(aformID,aformName,aformTemplate);

// application settings
var applicationSettings;
var currentScreen;

// save flags
//
// setup settings
var DAYS_TO_SAVE = 30; //number of days to save cookie information
var useCookies = false;
var uploadEnabled = true; //use to disable upload for web demo application
var debugON = false;
//
// Function: load()
// Called by HTML body element's onload event when the web application is ready to start
//
function load() {
    //
    //document.domain = document.domain;
    //
    //simplePreload('button','button1','button3','button5','button6','button7','clearObservation', 'clearSettings', 'done_Button', 'done_Button1', 'doneButton1', 'editObservation', 'initialSetupButton', 'next', 'back', 'syncButton', 'observationButton', 'uploadButton');
    //
    setupParts();
    //
    //
    //console.log("document.domain="+document.domain);
    //
    resetHeight();
    //
    window.onorientationchange = function() {
		resetHeight(); 
	}
    //
    /*
    // debug cache 
    var cache = window.applicationCache;
    cache.addEventListener('updateready', cacheUpdatereadyListener, false);
    cache.addEventListener('error', cacheErrorListener, false);
    */
    // add swipe support
    /*
    if( window.Touch )
        addSwipeListener(document.getElementById('content'), function(e) { handleSwipe(e); });
    */
    // do online status
    // disabled - may interfear with offline use
    loaded();
    //
	// hide search
	hide(document.getElementById('searchfield'));
    // hide settings area on login page
    //hide(document.getElementById('settingsArea'));
    //
	// remove URL bar
	//goTop();
    //
	// read data from last session
	//_getCookie();
    //

	if (!mainDatabase){
		mainDatabase = CreateRecordStore();//opens connection to device database with SQLight
        //
		// owner data
		_loadOwnerData();
        //console.log("formID:"+formID);
		// form data
		_loadFormData();
         //console.log("formID:"+formID);
		// teacher list
		_loadTeacherData();
         //console.log("formID:"+formID);
		// observations
		_loadObservationData();
         //console.log("formID:"+formID);
		//
	}
  //
  //_clearSettings();
  restoreLocalStorage();
  //
}
/*
function cacheUpdatereadyListener(event){
    _alert("cacheUpdatereadyListener fired! "+event);
}
function cacheErrorListener(event){
    _alert("cacheErrorListener fired! "+event);
}

function handleSwipe(event){
    //
    var observationPage = document.getElementById('observation');
    // is it visable?
    var oDisplay = observationPage.style.display;
    
    if ("none"==oDisplay)
        return;
        
    if ("left" == event.direction)
        nextSection(event);
    if ("right" == event.direction)
        backSection(event);
    
}
*/

function isIPad(){
    return navigator.platform == "iPad";
}
function resetHeight() {	
    //var height = document.getElementById("content").style.height;
   // if (height < screen.height)
    /*
        document.height always returns 1024 or 480 :/ 
    */
    // 1024×768 as opposed to 480×320 
    var screenHeight = document.height;
    var orientation=window.orientation;
	switch(orientation)
	{
		case 0:
            if (isIPad())
                screenHeight = 1024;
            else
                screenHeight = 480;
            break;
        case 180:
            if (isIPad())
                screenHeight = 1024;
            else
                screenHeight = 480;
            break;
        case 90:
            if (isIPad())
                screenHeight = 768;
            else
                screenHeight = 320;
            break;
        case -90:
            if (isIPad())
                screenHeight = 768;
            else
                screenHeight = 320;
            break;

    }
    //
    var statusBarHeight = 20;
    var titleBarHeight = 46;//top title bar is 46, 
    var footerHeight = 40; //Footer area is 40 top margin+18 height
    //
    document.getElementById("content").style.minHeight = screenHeight-statusBarHeight+"px";	
    //document.getElementById("content").style.height = screenHeight-statusBarHeight-footerHeight+"px";	
    //
    document.getElementById("stackLayout").style.minHeight = screenHeight-statusBarHeight-footerHeight+"px";
    document.getElementById("splashScreen").style.minHeight = screenHeight-statusBarHeight+"px";	
    document.getElementById("observation").style.minHeight = screenHeight-statusBarHeight+"px";
    /*
    document.getElementById("splashScreen").style.minHeight = screenHeight-titleBarHeight+"px";
    document.getElementById("teacherList").style.minHeight = screenHeight-titleBarHeight+"px";
    document.getElementById("authenticate").style.minHeight = screenHeight-titleBarHeight+"px";
    document.getElementById("newObservation").style.minHeight = screenHeight-titleBarHeight+"px";
    document.getElementById("observation").style.minHeight = screenHeight-titleBarHeight+"px";
    document.getElementById("teacherInfo").style.minHeight = screenHeight-titleBarHeight+"px";
    document.getElementById("observationDate").style.minHeight = screenHeight-titleBarHeight+"px";
    */
    //document.getElementById("lotiLogo").style.top = (screenHeight-titleBarHeight-80)+"px";//108
}
function online(){
    return window.navigator.onLine;
}
function updateOnlineStatus(msg) {
       var status = document.getElementById("status");
       var condition = window.navigator.onLine ? "ONLINE" : "OFFLINE";
       var state = document.getElementById("state");
       
       if (status){
            status.setAttribute("class", condition);
            state.innerHTML = condition;
       }
       //status.innerHTML = condition;
       //status.innerHTML = msg.toUpperCase();
       //var log = document.getElementById("log");
       //log.appendChild(document.createTextNode("Event: " + msg + "; status=" + condition + "\n"));
}
function loaded() {
   updateOnlineStatus("load");
   document.body.addEventListener("offline", function () {
     updateOnlineStatus("offline");
   }, false);
   document.body.addEventListener("online", function () {
     updateOnlineStatus("online");
   }, false);
 }

function goTop(){
    // put here so can overide or disable
    window.scrollTo(0, 1);
    return;
   
}
// 
function show(theObject){
	if (null === theObject || undefined === theObject)
		return;
	theObject.style.display = 'block';
}

function hide(theObject){
	if (null === theObject || undefined === theObject)
		return;
	theObject.style.display = 'none';
}
function showButton(theObject)
{
	if (null === theObject)
		return;
		
	theObject.object.setEnabled(true);		
	theObject.style.visibility = "visible";
	theObject.style.display = 'block';
}
function hideButton(theObject)
{
	if (null === theObject)
		return;
	theObject.object.setEnabled(false);
	theObject.style.visibility = "hidden";
	theObject.style.display = 'none';	    
}
   
// ************************************************************************************************************************************
// teacher
// creates a teacher object
function teacher(name, email, id)
{
	this.id = id;
	this.name = name;
	this.email = email;
	this.visible = true;//use for filtering
    //
	this.school = null;//placeholder for eventual fetch of extra info from server
	this.lastObservationDate = null;//placeholder for eventual fetch of extra info from server
    //
    //also add? number of observations?  observation id array?
    //
	if (name !== null)
		this.value = name+' <span class="teacherEmail">'+email+'</span>';
	else
		this.value = '<span class="teacherEmail">'+email+'</span>';
}
// observation
// creates an observation object
function observation(teacherID, theformID)
{
	if (null === formTemplate){
        _alert("ERROR  No form template found!  An observation cannot be created without a form template.", 'Error');
		return;
     }   
    //
	this.teacherID = teacherID;

    if (null === theformID)
        this.formID = new Number(formID);// global formID
    else 
        this.formID = new Number(theformID);// this formID
    //
	this.beginDate = new Date();//
	this.endDate = null;//
	this.done = false;
	this.values = [];//array to store checked vs unchecked
	this.othertext = []; //array of othertext values
	this.comment = "";//field to hold the teacher info comment
	//
    if (debugON){
        console.log("new observation before setupTemplate, Global formID="+formID);
        console.log("new observation before setupTemplate, passedin theformID="+theformID);
        //
        console.log("new observation before setupTemplate, formTemplate.name="+formTemplate.name);
        console.log("new observation before setupTemplate, formTemplate.id="+formTemplate.id);
    }
    //set the right formTemplate - setupFormTemplate changes global formTemplate to formID's template
    //var savedTemplate = setupFormTemplate(this.formID);
    //
    formTemplate = setupFormTemplate(this.formID);
    // 
    this.formName = formTemplate.name;
    //
    if (debugON){
        console.log("new observation after setupTemplate, formTemplate.name="+formTemplate.name);
        console.log("new observation after setupTemplate, formTemplate.id="+formTemplate.id);
    }
	//
	// for each section, create an array of lookfor values set to 0
	for (var i=0;i<formTemplate.title.length;i++){	// i equates to sectionIndex
		var sectionDataArray = [];//new Array(formTemplate.data[i].length);					//need to create a new one each time through loop
		for(var j=0;j< formTemplate.data[i].length; j++){// j equates to lookforIndex
			sectionDataArray[j] = 0;
			// if lookfor has ":" create storage for the text
			if (formTemplate.data[i][j].indexOf(":") > -1){
				this.othertext[i] = [];
				this.othertext[i][j] = "";
			}
		}
		//	values[i] = [0,0,0,0,0,0,0,0,0,0];
		this.values[i] = sectionDataArray.slice();	
        
	}
	// restore formTemplate
    //formTemplate = savedTemplate;
    //
}
function setupFormTemplate(theformID){
    var newTemplate = formTemplate;
    //set Global formTemplate to the 
    // form identified by this ID
    if (null !== newTemplate && newTemplate.id+0 === theformID+0){
        if (debugON)
            console.log("setupFormTemplate  formTemplate matches DEFAULT");
        // its all good...
        formID = newTemplate.id;
        formName = newTemplate.name;
        //
        if (debugON){
            console.log("setupFormTemplate formID: "+formID);
            console.log("setupFormTemplate formName: "+formName);}
        //
    } else {
        // load different form
        if (debugON){
            console.log("setupFormTemplate  formTemplate does not match !");
            //
            console.log("    setupFormTemplate  formTemplate.id "+newTemplate.id);
            console.log("    setupFormTemplate  theformID "+theformID);
            //
            console.log("    setupFormTemplate  formTemplate.name "+newTemplate.name);
            console.log("    setupFormTemplate formName: "+formName);
        }
        //
        if (formTemplateArray.length > 0){
            for (var i=0;i<formTemplateArray.length;i++){
                var itemID = new Number(formTemplateArray[i][0]);
                if (debugON)
                    console.log("itemID="+itemID)
                if (itemID+0 == theformID+0){
                    // found the right form
                    formID = new Number(itemID);
                    formName = formTemplateArray[i][1];
                    newTemplate = formTemplateArray[i][2];//sets the global form template
                    // alternative...
                    // formTemplate may be storeing wrong id, name in array!
                    //newTemplate.id =formID;
                    //newTemplate.name =formName;
                    //formID = newTemplate.id;
                    //formName = newTemplate.name;
                    if (debugON){
                        console.log("formID reset: "+formID);
                        console.log("formName reset: "+formName);
                        console.log("formTemplate reset:  id "+newTemplate.id+" name "+newTemplate.name);
                    }
                    break; // all done
                }
            }
        }
    }
    /*
    
    */
    return newTemplate;
}
function packedValues(theObservation){
	//0000100"theothertext",00111,11001"",001000000
	var tempString = "";
	var numberOfItems = 0;
	for (var i=0;i<theObservation.values.length;i++){
		numberOfItems = theObservation.values[i].length;
        
		for(var j=0;j< numberOfItems; j++){
			//
            if (undefined === theObservation.values[i][j]){
                theObservation.values[i][j] = 0;
            } else if (null == theObservation.values[i][j]){
                theObservation.values[i][j] = 0;
            } else if (NaN == theObservation.values[i][j]){
                theObservation.values[i][j] = 0;
            }// NaN
            tempString += theObservation.values[i][j];
            //
		}
       
        // i = sectionNumber
        // J-1 = nbrOfLookforsInSection
        // could use a TRY catch.....
        try {
            if (null !== theObservation.othertext && i < theObservation.othertext.length && null !== theObservation.othertext[i] && null !== theObservation.othertext[i][numberOfItems-1]){
                //othertext[i][j] = "";
                var theText = theObservation.othertext[i][numberOfItems-1];
                if ("" !== theText && !(undefined === theText)){
                    tempString += "\""+theText.cleanstring()+"\"";
                } else if (undefined === theText){
                    theObservation.othertext[i][numberOfItems-1] = "";
                } else {
                    tempString += "\"\"";
                }
            }
        } catch(e) {
            console.log("ERROR in packedValues theObservation.othertext: "+e);
        }
        //
		// add seperator
		if (i<theObservation.values.length-1)
			tempString += "~";
	}
    
	return tempString;
}
function setPackedValues(theObservation, valueString){
	//0000100"theothertext"~00111~11001""~001000000
	// remove first and last quote....
   
	if ("\"" == valueString.charAt(0)){
		valueString = valueString.slice(1); //from 1 to the end of the string
	}
	if ("\"" == valueString.charAt(valueString.length-1)){
		valueString = valueString.slice(0,-1); //from 0 to 1 less than the end of the string
	}
    //
	var sectionArray = valueString.split("~");
	var lookforArray = [];
	theObservation.values = [];
	for (var i=0;i<sectionArray.length;i++){
		var lookforString = sectionArray[i];
        //
       
		//pull off each charactor
		theObservation.values[i] = [];
		for (var j=0;j<lookforString.length;j++){
			// could fail
			if ("\"" !== lookforString.charAt(j)){
				theObservation.values[i][j] = new Number(lookforString.charAt(j));
			} else {
				// hit a quote, grab the rest and exit
				theObservation.othertext[i] = [];
                var tempText = lookforString.slice(j+1,-1);
                tempText = tempText.cleanstring();
				theObservation.othertext[i][j-1] =  tempText;
				break;
			}
			
		}
       
	}
}
// observationTemplate
// creates an observationTemplate object
function observationTemplate(title, data, description)
{
    this.id = formID;
    this.name = formName;//"Unset";
    //
	this.title = title;				//array of sectiontitles
	this.description = description; //description of section
	this.data = data;				//array of lookfors
}
/*
function observationTemplate(id, name, title, data, description)
{
    this.id = id;
    this.name = name;
    //
	this.title = title;				//array of sectiontitles
	this.description = description; //description of section
	this.data = data;				//array of lookfors
}
*/
// ************************************************************************************************************************************
// Private utility functions
// ************************************************************************************************************************************
//
function _alert(message, title){
    //
    // alert message using phonegap
    //
    if (null == title)
        title = "Warning";
    
    // if phoneGap use nice alert message
    if (typeof(PhoneGap) !== 'undefined') {
    
        try {
            navigator.notification.alert(message, title);
        } catch(e) {
            alert(message);
        }
    } else
        alert(message);
    // 
    return;    
}
function _confirm(message, okLabel, cancelLabel, title){
    //
    // alert message using phonegap
    //
    if (null == title)
        title = "Confirm";
    
    // if phoneGap use nice alert message
    if (typeof(PhoneGap) !== 'undefined') {
    
        try {
            navigator.notification.alert(message, title, okLabel, cancelLabel);
        } catch(e) {
            return confirm(message, okLabel, cancelLabel);
        }
    } 
    // 
    return false;    
}
function _saveFormData(){
	//
	if (debugON)
		alert("_saveFormData");
	
	// new SQLight way
	if (!useCookies && !mainDatabase){
		mainDatabase = CreateRecordStore();//opens connection to device database with SQLight
	}
	//
	if (!useCookies && mainDatabase){
		//alert('Saving form data');
		var theData = "";
		for (i=0;i<formTemplate.data.length;i++){		
			theData += formTemplate.data[i].join('~');
            //
            // encode here??
            //theData += encodeString(formTemplate.data[i].join('~'));
			if (i < formTemplate.data.length-1)
				theData += '&&';
		} 
		//
		//alert('form data is:'+theData);
		//
		var fieldNames = ["id","name","titles","descriptions","lookfors"];
		var fieldValues = [formTemplate.id, encodeString(formTemplate.name), encodeString(formTemplate.title.join('~')), encodeString(formTemplate.description.join('~')), encodeString(theData)];
        //		var fieldValues = [formID, encodeString(formTemplate.title.join('~')), encodeString(formTemplate.description.join('~')), theData];

		//
		mainDatabase.addRow("formData",fieldNames,fieldValues);	
	} 	
	return;
}

function _saveOwnerData(){

	//alert("_saveOwnerData");
	// new SQLight way
	if (!useCookies && !mainDatabase){
		mainDatabase = CreateRecordStore();//opens connection to device database with SQLight
	}
	//
	var rememberMe = 0; // 0 = false
	if (document.getElementById('rememberCheckbox').checked)
		rememberMe = 1; // 0 = false
	//
	if (!useCookies && mainDatabase){
		// Example: addRow(tableName,fieldArray, valueArray)
		// od = ownerID+'&&'+document.getElementById('userID').value+'&&'+document.getElementById('pswd').value+'&&'+document.getElementById('rememberCheckbox').checked;
		//
		mainDatabase.addRow("ownerData",["id","userid","pswd","rememberMe"],[ownerID,encodeString(document.getElementById('userID').value),encodeString(document.getElementById('pswd').value),rememberMe]);
	
	} else {
		var name = "odata";
		var theData = getOwnerData();
		//debugON = true;
		if (debugON)
			alert("_saveOwnerData Cookies theData ="+theData);
		//
		replaceCookie(name,theData,DAYS_TO_SAVE);
		//
	}
	return;
}

function _loadOwnerData(){	
	//
	if (!useCookies && mainDatabase){
		mainDatabase.getOwnerData();
	} else {
		var theCookieString = readCookie("odata");
		//
		//theCookieString = "1208900&lotiadmin&lotiadmin&true";
		//
		if (debugON)
			alert("_loadOwnerData theCookieString:"+theCookieString);
		if (theCookieString){
			var p = unescape(theCookieString); 
			if (debugON)
				alert("_loadOwnerData Cookie odata:"+p);
			
            
			var a = p.split('&&');
            if (p.indexOf('&&') == -1)
                a = p.split('&');//in case was stored with just one
			//
			ownerID = new Number(a[0]);
			document.getElementById('userID').value = a[1];
			document.getElementById('pswd').value = a[2];
			document.getElementById('rememberCheckbox').checked = a[3];
		}
	}	
	return;
}

function _loadObservationData() {
	if (!useCookies && mainDatabase){
		mainDatabase.getObservationData();	
		// 
	} else 
		_loadObservationCookieData();
	//
	return;
}

function _loadFormData(){
	//
	if (!useCookies && mainDatabase){
		mainDatabase.getFormData();
    }
	return;

}

function _loadTeacherData(){
	if (!useCookies && mainDatabase){
		//
		mainDatabase.getTeacherData();	
	} 
	return;
}

function encodeString(theString){
	var newString = "\""+escape(theString)+"\"";
	return new String(newString);
}
function decodeString(theString){
	var newString = unescape(theString);
	// remove quotes????
	return new String(newString);
}
function _saveTeacherData(){
	//
	//alert("_saveTeacherData");
	// new SQLight way
	if (!useCookies && !mainDatabase){
		mainDatabase = CreateRecordStore();//opens connection to device database with SQLight
	}
	//
	if (!useCookies && mainDatabase){
		// Example: addRow(tableName,fieldArray, valueArray)
		// //transaction.executeSql('insert into formData (id, titles, descriptions, lookfors) VALUES (0,"one~two~three", "done~dtwo~dthree", "one~lfone~lftwo~lfthree&two~lfone~lftwo~lfthree~lffour");', [], nullDataHandler, errorHandler);
		var theData = "";
		for (var i = 0; i < teachers.length; i++){		
			mainDatabase.addRow("teachers",["id","name","email"],[teachers[i].id,encodeString(teachers[i].name),encodeString(teachers[i].email)]);	
		} 	
	} else if (useCookies){
		//cookie
		var name = "teachers";
		var theData = getTeacherData();
		//
		replaceCookie(name,theData,DAYS_TO_SAVE);
		//
	}
	return;	
}

function sortTeacher(a,b)
{
	//Compare "a" and "b" in some fashion, and return -1, 0, or 1
	/*
		-1: Sort "a" to be a lower index than "b"
		0: "a" and "b" should be considered equal, and no sorting performed.
		1: Sort "b" to be a lower index than "a".
	*/
	var aVal = a.value.toLowerCase().trim();
	var bVal = b.value.toLowerCase().trim();
	//
	if (aVal < bVal)
		return -1;
	else if (aVal > bVal)
		return 1;
	else
		return 0;
	//
	return returnValue;
}
function _saveObservationData(){
//
	if (debugON)
			alert("_saveObservationData...");
	//
	// new SQLight way
	if (!useCookies && !mainDatabase){
		mainDatabase = CreateRecordStore();//opens connection to device database with SQLight
	}
	var cookieString = "";
	var tempObservation;
	// get currentObservation comment
	//
    var savedFormID = formID;
    var savedFormName = formName;
    //
	for (var i = 0; i < observations.length; i++){		
		tempObservation = observations[i];
		var theData = packedValues(tempObservation);
		var beginDate = encodeString(tempObservation.beginDate.getTime());
		var endDate = "null";
		if (tempObservation.done){
            endDate = beginDate;
			//if (null !== tempObservation.endDate)
			//   endDate = encodeString(tempObservation.endDate.getTime());
		} else if (null !== tempObservation.endDate){ //added 05/08/09 try to fix: done and end date messed up
            tempObservation.done = true;
            endDate = beginDate; //encodeString(tempObservation.endDate.getTime());
        } else
			tempObservation.endDate = null;
		//
        //formName = tempObservation.name;
        //formID = tempObservation.formID;
        //
		var dataArray = [tempObservation.teacherID,tempObservation.formID,beginDate,endDate,encodeString(theData), encodeString(tempObservation.comment.cleanstring())];

		//var dataArray = [tempObservation.teacherID,formID,beginDate,endDate,encodeString(theData)];
		if (!useCookies && mainDatabase){
			mainDatabase.addRow("observations",["teacherid","formid","begindate","enddate","packedValues", "comment"],dataArray);
			//mainDatabase.addRow("observations",["teacherid","formid","begindate","enddate","packedValues"],dataArray);
		} else {
			// save in cookie
			cookieString += dataArray.join('&&');
			//add record delimiter
			if (i < observations.length-1)
			{
				cookieString += '\\';
			}
			
		}	
	} 
    //
    // restore formName and ID
    formName = savedFormName;
    formID = savedFormID;
    //
	// save cookie
	if (useCookies){
		if (debugON)
			alert("_saveObservationData Cookies cookieString ="+cookieString);

		replaceCookie('observations',cookieString,DAYS_TO_SAVE);
	}
	return;
}

function today()
{
	var date = new Date();
	return date.toGMTString();
}

//
// ***********************************************************************************************
//

function getTeacherListFromServer(){
	var feedURL = urlPrefix+dataServer+dataServerApplicationPath;
	if (!ownerID==0)
		feedURL = feedURL + "getUserList?uid="+ ownerID;
	else
		return;
	// ok ownerID is NOT zero...
    
	// XMLHttpRequest setup code
	var xmlRequest = new XMLHttpRequest();	
		// The feed to fetch
	var onloadHandler = function() { teacherListLoaded(xmlRequest); };	// The function to call when the feed is loaded; currently calls the XMLHttpRequest load snippet
	xmlRequest.onload = onloadHandler;
	// ****** ASYNC=false call, waits for response -- needs timeout system *********/
	xmlRequest.open("GET", feedURL, false);
	//
	xmlRequest.setRequestHeader("Cache-Control", "no-cache");
        // setup timeout
    // grab the time, give chance to abort in the call back if time exceeded
    var startDateTime = new Date().getTime();	
    //
    var timeoutID = window.setTimeout(function(){
        _alert('The request has timed out. The server is too busy or your Internet connection is unavailable.', 'Error');
        xmlRequest.abort();
        }, 5000);
    //
    var readyStateHandler = function() {checkReadyStateStatus(xmlRequest, startDateTime); };
    xmlRequest.onreadystatechange=readyStateHandler;
    //	
	xmlRequest.send(null);
    //
    window.clearTimeout(timeoutID);
    //
}
function teacherListLoaded(xmlRequest) 
{
	var statusMessage = document.getElementById('message');
	var savedStatus = statusMessage.innerText;
    
	if (xmlRequest.status == 200) {
		// Parse and interpret results
		// XML results found in xmlRequest.responseXML
		// Text results found in xmlRequest.responseText
		//
		// get the teacher list
		var responseText = xmlRequest.responseText;
		if (responseText.indexOf('Unavilable') > -1){
			_alert("Server is currently unavilable, please try again later.","Error");
            statusMessage.innerText = savedStatus;
			return;
		}  else {
			//parse teacher list
			statusMessage.innerText = "Teacher data retrieved, Createing teacher list.....";
			//
			parseTeacherList(responseText);//does a sort
			statusMessage.innerText = "Teacher List updated "+today();
			//
			// save teacher data
			_saveTeacherData();
			//
			needsDisplay = true;
			// 
		}
		
	} else {
		_alert("Error fetching data: HTTP status " + xmlRequest.status,"Error");
		//alert("You are not connected to the Internet.  Connect to the Internet and try again");
		statusMessage.innerText = "Error connecting to the server";
	}
}
function connectToServer(){
	// Values you provide
	var feedURL = urlPrefix+dataServer+dataServerApplicationPath;
    //feedURL="http://oldmary.lqhome.com/cgi-bin/WebObjects/lotiobservation.woa/wa/DirectAction/";
	//
	var layout = document.getElementById('list');
	var statusMessage = document.getElementById('message');
	//
	// Turn OFF sync button while fetching data...... document.getElementById('syncButton').
	//statusMessage.value = "Connecting.....";
	//
	var userid = document.getElementById('userID');
	userid = userid.value;
	var pswd = document.getElementById('pswd');
	pswd = pswd.value;
	//	
	if (ownerID==0){
		//authorize and get ownerID and formTemplate
		feedURL = feedURL + "authUser?userID="+ escape(userid.trim()) +"&pswd="+ escape(pswd.trim());
		//
		statusMessage.innerText = "Validating Username and Password.....";
		//
		if (""==userid || ""==pswd){
			_alert("Invalid Username or Password.  Please correct and try again.");
			statusMessage.innerText = "Invalid Username or Password";
			return;
		}
		
		//
	} else {
		//
		statusMessage.innerText = "Retrieving Teacher List.....";
		//
		feedURL = feedURL + "getUserList?uid="+ ownerID;
	}
	//alert("feedURL="+feedURL);
	//		
	//	authUser?userID=lotiadmin&pswd=lotiadmin
	//
	//	newObservation put request with form values
	//

	// The feed to fetch
	var onloadHandler = function() { xmlLoaded(xmlRequest); };	// The function to call when the feed is loaded; currently calls the XMLHttpRequest load snippet

	// XMLHttpRequest setup code
	var xmlRequest = new XMLHttpRequest();
	xmlRequest.onload = onloadHandler;// xmlLoaded
    //
    //    feedURL = escape(feedURL);
    //feedURL = encodeURIComponent(feedURL);

    //feedURL = encodeURI(feedURL);
    //feedURL="http://oldmary.lqhome.com/cgi-bin/WebObjects/lotiobservation.woa/wa/DirectAction/authUser?userID=lotiguest&pswd=lotiguest";
    //
    if (debugON)
        console.log("feedURL is *"+feedURL+"*");
    //
    // ****** ASYNC=false call, waits for response -- needs timeout system *********
	xmlRequest.open("GET", feedURL, false);
	xmlRequest.setRequestHeader("Cache-Control", "no-cache");
    //
    // setup timeout
    // grab the time, give chance to abort in the call back if time exceeded
    var startDateTime = new Date().getTime();	
    //
    var timeoutID = window.setTimeout(function(){
        _alert('The request has timed out. The server is too busy or your Internet connection is unavailable.', 'Error');
        xmlRequest.abort();
        }, 5000);
    //
    var readyStateHandler = function() {checkReadyStateStatus(xmlRequest, startDateTime); };
    xmlRequest.onreadystatechange=readyStateHandler;
    //	
    try {
        xmlRequest.send(null);
    } catch(error) {
        _alert("The server request returned an error.  Error "+error.message,"Error");
    }
    //
    window.clearTimeout(timeoutID);
    //
}
// Called when an XMLHttpRequest loads a feed; works with the XMLHttpRequest setup snippet
function xmlLoaded(xmlRequest) 
{
	var statusMessage = document.getElementById('message');
	
	if (xmlRequest.status == 200) {
		// Parse and interpret results
		// XML results found in xmlRequest.responseXML
		// Text results found in xmlRequest.responseText
		//
		// get the ownerID and the form data
		var responseText = xmlRequest.responseText;
		if (responseText.indexOf('Unavilable') > -1){
			_alert("The server is currently unavilable, please try again later.","Error");
			return;
		}
		if (ownerID == 0){//and remember pswd
			//
			var tempString = parseOwnerID(responseText);
			if ("User Not Found"==tempString){
				_alert("Invallid Username or Password.  Please correct and try again");
				return;
			}
			ownerID = new Number(tempString);//could fail, need to TEST to make sure this is a number not NaN
			if (ownerID == NaN){
				_alert("There was an error retrieving your User information from the server.  Please conact technical support.","Error");
				return;
			}
			//
			// save ownerData
			_saveOwnerData();
			//
			statusMessage.innerText = "Authorization complete, retrieveing Observation form.....";
			// now parseFormData
            //
            //  GLOBALS
            //
			formID = new Number(parseTemplateID(responseText));
            formName = parseTemplateName(responseText);
            formTemplate = parseObserverTemplate(responseText);
            //
            /*
            formTemplate.name = formName; // should be set in parseObserverTemplate->new observationTempate(id,titles,data);
            formTemplate.id = formID;     
			*/
            statusMessage.innerText = "Observation form retrieved, Saving.....";
			// save form
			_saveFormData();
            //
            // set current template
            var templateNameObject = document.getElementById("currentTemplateName");
            if (templateNameObject && null !== formName)
                templateNameObject.innerText = formName;
            else
                templateNameObject.innerText = "Unset";
            //
			
			//
			statusMessage.innerText = "Observation form complete, retrieveing teacher list.....";
			// save ??? (in case of crash or something)
			// call again, this time getting teacher list
			connectToServer();
		} else {
			//parse teacher list
			statusMessage.innerText = "Teacher data retrieved, Createing teacher list.....";
			//
			parseTeacherList(responseText);
			statusMessage.innerText = "Teacher List updated "+today();
			//
			// save teacher data
			_saveTeacherData();
			//
			needsDisplay = true;
			// now open the teacher list
			goTeacherList();
		}
		
	} else {
        var responseText = xmlRequest.responseText;
		_alert("There was an Error connecting to the server: HTTP status " + xmlRequest.status+"\nThe server said: "+responseText.strip(),"Error");
		//alert("You are not connected to the Internet.  Connect to the Internet and try again");
	}
}
function getServerData(fieldName, textBlock){

    var output = null;
	var startFieldName = "** "+fieldName+":";
	var fldLength = startFieldName.length;
	var endFieldName = ":end_"+fieldName;
	var srcStart = textBlock.indexOf(startFieldName);
    var srcEnd = textBlock.indexOf(endFieldName);
    //
    if (srcStart > -1 && srcEnd > -1){
        output = textBlock.substring((srcStart + fldLength), srcEnd);
        output=output.trim();
    }
	
	return output;
}
function openTeacherList(event){
//	
	//
	if (ownerID==0){
		var layout = document.getElementById('stackLayout').object;
        currentScreen = 'authenticate';
		layout.setCurrentView('authenticate', false, true);
	} else {
        if (currentScreen == 'teacherList')
            goTeacherList();
        else if (currentScreen == 'newObservation')
            goObservationMain(); //needs currentObservation
        else if (currentScreen == 'observation')
            goObservationSection();  //needs currentObservation, currentSection  
        else if (currentScreen == 'teacherInfo')
            goTeacherInfo();  //needs currentObservation, currentSection  
        else if (currentScreen == 'observationDate')
            goObservationDate();  //needs currentObservation, currentSection  
        else
            goTeacherList();
	}
	
}
  
// ************************************************************************************************************************************

function parseOwnerID( theString){
	//
	return getServerData("ownerID",theString);//removes trailing "/n' !!!!
}
function parseTemplateID( theString) {

	return getServerData("templateID",theString);
}
function parseTemplateName( theString) {

	return getServerData("templateName",theString);
}
function parseObserverTemplate(theString){
        //
		// save for later
		//observerTemplateString = theString;
		//
        var templateString = getServerData("observationTemplate",theString);

        // put into record store
        // we need two arrays title and data
        // title is each pageName/catagory
        // each record ends with \n and each field by a "*"
        // subfields are seperated by "~"
        var recordSeporator = "\\n";
        var fieldSeporator = "*";
        var subFieldSeporator = "~";
        var tempString = templateString;
        var theRecordString;
        var theFieldString;
        //String theSubFieldString;
        var beginPosition = 0;
        var endPosition;
        var nbrOfRecords = 0;
        var fieldIndex = 0;
        //
        // Mutable Array to hold records
        var recordArray = [];
        // Mutable Array to hold fields
        
        // Mutable Array to hold subFields
        var subFieldArray = [];
        // notice I did all my variable definitions OUTSIDE
        // the loop - that is because object creation and destruction
        // can seriously degrade performance in a tight loop
        //
        while (tempString.indexOf(recordSeporator) > -1){
            
            endPosition = tempString.indexOf(recordSeporator);
            theRecordString = tempString.substring(beginPosition, endPosition);
            //
            // parse theRecordString
            //  /*
            var fieldArray = [];//start with a fresh fieldArray, needed so each is different
            fieldIndex = 0;//start with 0 based field index
            while (theRecordString.indexOf(fieldSeporator) > -1){
                theFieldString = theRecordString.substring(0, theRecordString.indexOf(fieldSeporator));
                // add to field array
                //fieldArray.addElement(theFieldString);
				//
				fieldArray[fieldIndex] = theFieldString;
				//
                theRecordString = theRecordString.substring(theRecordString.indexOf(fieldSeporator)+fieldSeporator.length,theRecordString.length);
                // if fieldIndex == 0 add to the title array
                // else add to the data array
                fieldIndex++;
            }
            
            // */
            // add to the recordArray
            //recordArray.addElement(fieldArray);//doesn't copy so need a new fieldArray each time'
			recordArray[recordArray.length] = fieldArray;
            //
            // next record
            // remove processed portion of the string
            tempString = tempString.substring(endPosition+recordSeporator.length,tempString.length);
            nbrOfRecords++;
        }
        
        // create title[] *new* description[] & data []
        var title = [];//new Object[1];// an array of pagenames/titles
        var data = [];//new Object[nbrOfRecords];
        var description = [];// = new String[nbrOfRecords];
        var str = [];// = new String[nbrOfRecords];//
        
        var tempStr;
        var subFieldString;
        var subFieldIndex = 0;
        var currentRecord=[];
        //
        //java.util.Enumeration e = recordArray.elements();
        //int i = 0;
		for (var i = 0; i < recordArray.length; i++){
        //while (e.hasMoreElements()){
            //
            //currentRecord = e.nextElement();
			currentRecord = recordArray[i];
            // must have 3 fields! title, descript, array of labels for items
            ////System.out.println("  processing currentRecord:"+currentRecord);
            //
            str[i] = currentRecord[0];//first field in record is title
			if (null !== currentRecord[1])
				description[i]=currentRecord[1];//may be empty!
			else
				description[i]="";
				
            // now loop to process data fields
            //tempStr[] = new String[fieldIndex];
            subFieldString =currentRecord[2];
            subFieldIndex = 0;
            //subFieldArray.removeAllElements();
			subFieldArray = [];
			// recordArray[recordArray.length] = fieldArray;
			//
			
            while (subFieldString.indexOf(subFieldSeporator) > -1){
                ////System.out.println(".");
                tempStr = subFieldString.substring(0,subFieldString.indexOf(subFieldSeporator));
                //subFieldArray.addElement(new String(tempStr));
				subFieldArray[subFieldArray.length] = tempStr;
                // remove old
                subFieldString = subFieldString.substring(subFieldString.indexOf(subFieldSeporator)+subFieldSeporator.length,subFieldString.length);
                subFieldIndex++;
            }
            //

            // create string arrary
            var dataString = [];// = new String[subFieldIndex];
            for (var j=0;j<subFieldArray.length;j++){
                dataString[j] = subFieldArray[j];
            }
            data[i] = dataString;
            //
            //i++;
            title = str;
            //endloop
        }
        //
        
        //
        // load record store
        //writeStream(title, data, description);
		return new observationTemplate(title, data, description);
}
function parseTeacherList(serverReplyString) {
        //System.out.println("parseUserList");
		//
		var statusMessage = document.getElementById('message');
        //
		//alert("serverReplyString "+serverReplyString);
		//
		if (serverReplyString === null){
				return;
				}
			//
			statusMessage.innerText = "Processing server reply.....";
			//
            var recordSeperator = "\n";
            var fieldSeperator = "~";
            var currentRecord;
			var currentField;
			
            var userInfo = getServerData("userList",serverReplyString);//removes trailing "\n' !!!!
			if (userInfo === null){
				statusMessage.innerText = "Teacher list on Server does not contain any items.";
				return;
			}
			userInfo += '\n'; //add trailing \n back in.
			//
            //
            var offset = 0;
            var foffset = 0;
            var userCount = 0;
            var fieldCount = 0;
            //
            var endOffset = userInfo.indexOf(recordSeperator, offset);
            //
			statusMessage.innerText = "Creating customized Teacher List.....";
			//
            while (endOffset > -1 && offset < endOffset){
                currentRecord = userInfo.substring(offset,endOffset);

                foffset = 0;
                fieldCount = 0;
				var fieldValues = [];//currentRecord.split('\n');
                while (currentRecord.indexOf(fieldSeperator, foffset) > -1) {
                    currentField = currentRecord.substring(foffset,currentRecord.indexOf(fieldSeperator,foffset));
                    //
                    if(currentField === null){
                        //ds.writeUTF("");
						fieldValues[fieldCount] = "";
                    }  else {
                        //ds.writeUTF(currentField);                     // write Name, email
						fieldValues[fieldCount] = currentField.trim();
                    }                   
                    //
                    foffset = currentRecord.indexOf(fieldSeperator, foffset)+fieldSeperator.length;
                    fieldCount++;
                    //
                }
                // last field; userID
                currentField = currentRecord.substring(foffset);
                currentField = currentField.trim();
                if (currentField.length >0 ){
                    //
                    //int user_ID = ;
					//ds.writeInt(Integer.parseInt(currentField));
					fieldValues[fieldCount] = currentField.trim();
					//
                    fieldCount++;
                }
				//
				//rs_User.addRecord(record, 0, record.length);
				//name, email, id
				//
				statusMessage.innerText = "Addting teacher # "+(userCount+1);
				//
                if (fieldValues.length > 2)
                    teachers[userCount] = new teacher(fieldValues[0], fieldValues[1],fieldValues[2]);
                //
				//record = null;
                //
                offset = endOffset+recordSeperator.length;
                endOffset = userInfo.indexOf(recordSeperator, offset);
                //
                if (endOffset == -1)
                    endOffset = userInfo.length;
                else if (endOffset == userInfo.length)
                    endOffset = -1;
                //
                userCount++;
                //
            }
			//
			statusMessage.innerText = "Teacher List created; "+userCount+" Teachers in list";
			//
        // done 
        // sort
		teachers.sort(sortTeacher);
}

// ************************************************************************************************************************************
function teacherData(){
	//
	var listData = ["item 1"]; //default value
	//		
	if (null !== teachers && teachers.length > -1){
		for (var i=0;i<teachers.length; i++){
			listData[i] = teachers[i].value;
		}
		//teacherList.dataSource._rowData = listData;
	} 
	//
	return listData;
}
// on load event? or on focus hmmmm
function refreshTeacherList(){
	// replace innerHTML for the list....
	/*
	<li id="listRowTemplate" apple-template="true" class="listRowTemplate_template" style="border-top-width: 0px; " apple-always-show-guides="true">
		<div id="label" apple-part="com.apple.Dashcode.part.text" class="label_template" apple-text-overflow="ellipsis">Item</div>
		<div id="arrow" apple-part="com.apple.Dashcode.part.box" class="arrow_template"></div>
	</li>
	*/
	// sort
	//teachers.sort(sortTeacher);
    //
    // number of teachers...
    var textObjectToChange = document.getElementById('numberOfTeachers');
    //replace with the number of teachers in the list
    if (textObjectToChange){
        textObjectToChange.innerText = teachers.length+" Teachers listed";
    }
    //
    
	// clear
	document.getElementById('list').innerHTML = '';	//
	for (var i = 0; i < teachers.length; i++)
	{
	   if (teachers[i].visible){
            // formTypeBadge
            var formTypeBadge = '<div id="formTypeBadge__'+i+'" style="display: none;" apple-part="com.apple.Dashcode.part.roundedrectanglewebshape" apple-style="image-theme: 1; image-shape: 3; image-button-type: 3; image-opacity: 1.00; image-top-color: 1,1,1,1; image-bottom-color: 0.6154,0.6154,0.6154,1; image-radius: 5,5,5,5; image-border: 1; image-border-color: 0.5294,0.5294,0.5294,1; image-border-width: 1; shine-strength: 0.90; shine-alpha-level: 0.67; shine-height: 0.50; glass-arc-height: 0.06; shadow-include-shadow: 0;" class="formTypeBadge_template">\n<div id="numberOfObservations__'+i+'" style="display: none;" apple-part="com.apple.Dashcode.part.webtext" class="apple-text apple-no-children numberOfObservations_template" apple-default-image-visibility="hidden" apple-text-overflow="ellipsis">2</div>\n<div id="observationType__'+i+'" apple-part="com.apple.Dashcode.part.webtext" class="apple-text apple-no-children observationType_template" apple-default-image-visibility="hidden" apple-text-overflow="ellipsis" apple-style="part-height-dependent: true;part-width-dependent: true;">H.E.A.T.</div>\n</div>\n';
            //
            // **
			document.getElementById('list').innerHTML += '<li id="listRowTemplate__'+i+'" apple-template="true" class="listRowTemplate_template" style="border-top-width: 0px;" apple-always-show-guides="true"  onclick="newObservation('+i+')">\n<div id="l'+teachers[i].id+'" apple-part="com.apple.Dashcode.part.text" class="label_template" apple-text-overflow="ellipsis">'+teachers[i].value+'</div>\n'+formTypeBadge+'<div id="arrow_'+i+'" apple-part="com.apple.Dashcode.part.box" class="arrow_template1"></div>\n</li>';
            // **
            var recordList = findObservation(teachers[i].id);
			if (recordList){
				// get first observation on the list
				var tempObservation = observations[recordList[0]];
                if (debugON){
                    console.log("listRowTemplate Found Observation: "+tempObservation);
                    console.log(" observation.name: "+tempObservation.formName);
                    }
				if (tempObservation.done){
					// set color
					document.getElementById('l'+teachers[i].id).style.color="green";
				} else
					document.getElementById('l'+teachers[i].id).style.color="#4263CC";
                //
                if (document.getElementById('formTypeBadge__'+i)){
                    document.getElementById('formTypeBadge__'+i).style.display="";//show it
                    if (tempObservation.formName)
                        document.getElementById('observationType__'+i).innerHTML=tempObservation.formName;//show it
                    //document.getElementById('numberOfObservations__'+i).style.display="";//show it 
                } 
			}
		}

	} // end teachers loop
	
	//
	needsDisplay = false; // show we've done creating it	
}

function newObservation(teacherIndex){
	//
	//goTop();
	//
	var id = teachers[teacherIndex].id;
	var teacherName = teachers[teacherIndex].value;
	var teacherEmail = teachers[teacherIndex].email;
	// id is teacherID
	//alert("New Observation: "+id);
	//
	// find any existing observation for this teacher....
	var recordList = findObservation(id);
	// *** Create observation Object ***
	if (!recordList){
		currentObservation = new observation(id, formID);
		// add new observation to array
		observations[observations.length] = currentObservation;
		// remind teacher list it needs to be redrawn
		needsDisplay = true;
		// ***********************************
	} else {
        
		var recordIndex = recordList[0];//recordList.length-1 (last record)
        if (debugON)
            console.log("newObservation(teacherIndex) recordIndex = "+recordIndex);
		currentObservation = observations[recordIndex];//first one found
        // set current form...
        formTemplate = setupFormTemplate(currentObservation.id);
	}
	// currentObservation is now set
	// set email
	var emailButton = document.getElementById('emailButton');
	if (emailButton)
		emailButton.object.setEmailAddress(teacherEmail);
	//
	//  ** change teacher Info List item text **
	sectionIndex = 0;//page 1
	// page title
	document.getElementById('tiList').innerHTML = '<li id="listRowTemplate2" apple-template="true" class="listRowTemplate_template" style="border-top-width: 0px; "  onclick="goTeacherInfo(event)"><div id="teacherName" apple-part="com.apple.Dashcode.part.text" class="label_template" apple-text-overflow="ellipsis">'+teacherName+'</div><div id="arrow1" apple-part="com.apple.Dashcode.part.box" class="arrow_template"></div></li>';// teacherName;	
	// ** change teacher info date **
	var textObjectToChange = document.getElementById('tName');
	textObjectToChange.innerHTML = teacherName;
	//
	textObjectToChange = document.getElementById('beginDate');
	//
    textObjectToChange.innerText = shorterDate(currentObservation.beginDate.toLocaleString());
	// needs on click method for editing
	//
	// set for redraw
	sectionListNeedsDisplay = true;
	//
	//display
	goObservationMain();
}
function shorterDate(theDate){
    //
    var newDate = "";//returns a string
    
    // limit to first 3 char of month
    // ie.e Jan 1, 2008 hh:mm am/pm PDT
    if (null !== theDate){
        newDate = theDate.substring(0,3);
        // from first space (after month) 'till the end
        beginIndex = theDate.indexOf(" ");//first space
        newDate = newDate+theDate.substring(beginIndex);//from first space 'till the end
    }
    return newDate;
}
function refreshObserverSection(){
	// replace innerHTML for the current Observer section....
	// formTemplate = 3 arrays; titles, descriptions, data[lookfors]
	if (null !== formTemplate){
		//
		if (null === sectionIndex)
			sectionIndex = 0;
		
		var lookfors = formTemplate.data[sectionIndex];
		if (null ===lookfors){
			sectionIndex = 0;
			lookfors = formTemplate.data[sectionIndex];
		}
		
		// clear
		document.getElementById('lookforList').innerHTML = '';	//
		// description
		document.getElementById('descriptionText').innerText = formTemplate.description[sectionIndex];
		//
		var otherTextField = document.getElementById("otherText");
		//
		var hasOtherText = false;
		var isChecked = false;
		for (var i = 0; i < lookfors.length; i++)
		{
		/*
<input type="checkbox" name="Checkbox" checked="checked" apple-group="checkboxbutton" id="checkboxbutton1">
<div id="lookforLabel" apple-part="com.apple.Dashcode.part.text" class="label1_template" apple-text-overflow="ellipsis">Item</div>

		*/
			//  checked="checked"   onclick="clickLookfor(event)"
			//alert(currentObservation.values[sectionIndex][i] );
			if (currentObservation !== null && currentObservation.values[sectionIndex][i] == 1){
			    isChecked = true;
			} else {
				isChecked = false;
			}
			//
			if (!isChecked){
				document.getElementById('lookforList').innerHTML += '<li id="listRowTemplate1" apple-template="true" class="checkBoxRow_template" onclick="clickLookfor(event)"><input type="checkbox" name="'+lookfors[i]+'" apple-group="checkboxbutton" id="checkboxbutton_'+i+'" class="lookforCheckbox_template">\n<div id="lookforLabel_'+i+' " apple-part="com.apple.Dashcode.part.text" class="lookforLabel_template" apple-text-overflow="ellipsis">'+lookfors[i]+'</div>';
			} else {
				document.getElementById('lookforList').innerHTML += '<li id="listRowTemplate1" apple-template="true" class="checkBoxRow_template" onclick="clickLookfor(event)"><input type="checkbox" name="'+lookfors[i]+'" apple-group="checkboxbutton" checked="checked" id="checkboxbutton_'+i+'"  class="lookforCheckbox_template">\n<div id="lookforLabel_'+i+' " apple-part="com.apple.Dashcode.part.text" class="lookforLabel_template" apple-text-overflow="ellipsis">'+lookfors[i]+'</div>';
			}
			if (lookfors[i].indexOf(":") > -1){
				hasOtherText = true;
				// if lookfors[i] contains "Other:" then add text to the input box.
				otherTextField.value = "";
				if (isChecked){
					otherTextField.value = currentObservation.othertext[sectionIndex][i];
				}
			} 
			//				
			document.getElementById('lookforList').innerHTML += '</li>';
		} // end lookfor loop
		//
		//
		if (null !== otherTextField){
			if (hasOtherText){
				show(otherTextField);
				//otherTextField.style.display="block";
			} else {
				hide(otherTextField);
				//otherTextField.style.display="none";
			}
		}
		// buttons....
		var nextButton = document.getElementById('next');
		var backButton = document.getElementById('back');
		var doneButton = document.getElementById('doneButton');
		/*
		if (sectionIndex == 0){
			// page 1
			backButton.setText("Teacher List");
			nextButton.setText("Next");
		} else
		*/
		  if (sectionIndex == (formTemplate.title.length-1)){
			// last page
			// hide Next button, show Done button
			//visibility: hidden;
			// OFF
			hideButton(nextButton);
			//nextButton.object.setEnabled(false);
			//nextButton.style.visibility = "hidden";
			// ON
			showButton(doneButton);
			//doneButton.object.setEnabled(true);
			//doneButton.style.visibility = "visible";
			
		} else {
			//hide done button, show next button
			showButton(nextButton);
			//nextButton.object.setEnabled(true);
			//nextButton.style.visibility = "visible";
			//
			hideButton(doneButton);
			//doneButton.object.setEnabled(false);
			//doneButton.style.visibility = "hidden";
		}
		//
	}

}
function refreshSectionTitle(){
	if (null !== formTemplate){
			//formTemplate has title, data, description)
			var sections = formTemplate.title;
			// title
            var sectionTitle = document.getElementById('sectionTitle');
            if (null !== sectionTitle)
                sectionTitle.innerText = sections[sectionIndex];
			//
		}
		//
}
function refreshSectionList(){
	/*
		<option class="apple-hidden">Section 1</option>
		<option class="apple-hidden">Section 2</option>
		<option class="apple-hidden">Section 3</option>
	*/
	if (null !== formTemplate){
		// clear
		document.getElementById('sectionList').innerHTML = '';	//
		//formTemplate has title, data, description)
		var sections = formTemplate.title;
		//
		//if (sectionListNeedsDisplay){
			for (var i = 0; i < sections.length; i++)
			{
					document.getElementById('sectionList').innerHTML += '<li id="listRowTemplate3" apple-template="true" class="listRowTemplate_template" style="border-top-width: 0px; " onclick="changeSection(event)"> <div id="label2'+i+'" apple-part="com.apple.Dashcode.part.text" class="label_template" apple-text-overflow="ellipsis">'+sections[i]+'</div> <div id="arrow2'+i+'" apple-part="com.apple.Dashcode.part.box" class="arrow_template"></div></li>\n';
				 
			}
			sectionListNeedsDisplay = false;
		//}
		//
		// title
		var sectionTitle = document.getElementById('sectionTitle');
        if (null !== sectionTitle)
            sectionTitle.innerText = sections[sectionIndex];
		//
		// change button and background colors if DONE
		var clearButton = document.getElementById('clearObservation');
		var editButton = document.getElementById('editObservation');
		var doneButton = document.getElementById('doneButton1');
		//
		if (null !== currentObservation && currentObservation.done){
			//
			// Hide clear button, show Edit button
			// OFF
			hideButton(clearButton);
			hideButton(doneButton);
			//clearButton.object.setEnabled(false);
			//clearButton.style.visibility = "hidden";
			// ON
			showButton(editButton);
			//editButton.object.setEnabled(true);
			//editButton.style.visibility = "visible";
			//
			document.getElementById('tiList').style.opacity = 0.5;
			document.getElementById('sectionList').style.opacity = 0.5;			
		} else {
			// Hide clear button, show Edit button
			// OFF
			hideButton(editButton);
			// ON
			showButton(clearButton);
			showButton(doneButton);
			//
			document.getElementById('tiList').style.opacity = 1.0;
			document.getElementById('sectionList').style.opacity = 1.0;
		}

	}
}
// This object implements the dataSource methods for the list.
var teacherListData = {
	
	// Sample data for the content of the list. 
	// Your application may also fetch this data remotely via XMLHttpRequest.  //this.teachers[].value
	_rowData: teachers,
	
	// The List calls this method to find out how many rows should be in the list.
	numberOfRows: function() {
		return this._rowData.length;
	},
	
	// The List calls this method once for every row.
	prepareRow: function(rowElement, rowIndex, templateElements) {
		// templateElements contains references to all elements that have an id in the template row.
		// Ex: set the value of an element with id="label".
		if (templateElements.label) {
			templateElements.label.innerText = this._rowData[rowIndex].value;
		}

		// Assign a click event handler for the row.
		rowElement.onclick = function(event) {
			// Do something interesting
			_alert("Row "+rowIndex);
		};
	}
};

function readOtherText(itemIndex){
	var otherTextField = document.getElementById("otherText");
	otherTextField.value = currentObservation.othertext[sectionIndex][itemIndex];
}
function writeOtherText(){
	if (null !== formTemplate){
			//
			var textIndex = formTemplate.data[sectionIndex].length-1;
			var lastLookfor = formTemplate.data[sectionIndex][textIndex];
			if (lastLookfor.indexOf(":") > -1){
				//save othertext
				var otherTextField = document.getElementById("otherText");
				if (null !== otherTextField && null !== otherTextField.value && !(""==otherTextField.value)){
					//assumes currentObservation and sectionIndex ocrrect
					currentObservation.othertext[sectionIndex][textIndex] = otherTextField.value;
				} else if (undefined !== textIndex)
					currentObservation.othertext[sectionIndex][textIndex] = "";
			}
		}

}
function changeSection(event)
{
	// save
	_saveObservationData();
	//
	// scroll to the top
	//goTop();
	// set sectionIndex = item selected
	var tempString = "";
	if (event.target.id.indexOf("label2") > -1){
		tempString = event.target.id.substring(6);
		sectionIndex = new Number(tempString);	//should be everything after label2..
	} else {
		var doubleTemp = event.target.innerHTML;
		var begin = doubleTemp.indexOf("label2");
		if (begin > -1){
			begin+=6;
			var end = begin+2;//2 chars
			tempString = doubleTemp.substring(begin,end);
			tempString = tempString.cleanstring().replace(/"\""/g,"");//strip quotes
			sectionIndex = new Number(tempString);
		}
	}
	//alert("sectionIndex = "+sectionIndex);
	//
	refreshSectionTitle();
	refreshObserverSection();
	goObservationSection(event);
}

function nextSection(event)
{
	// scroll to the top
	goTop();
	//
	writeOtherText();	
	// save
	_saveObservationData();
	//
	if (sectionIndex < formTemplate.title.length-1){
		// move pointer
		sectionIndex++;
		// update display
		refreshSectionTitle();
		refreshObserverSection();
	} else {		
		// last page
		//goObservationMain();  /*save already done above ??*/
        if (sectionIndex !== 0){
            // returning from the observer pages
            refreshSectionTitle();
            sectionIndex = 0;
        }
        //
        // save again
        _saveObservationData();
        //
        if (sectionListNeedsDisplay)
            refreshSectionList();
        //
		endObservation(event);
	}
	// scroll to the top
	goTop();
}

function backSection(event)
{
    // scroll to the top
    goTop();

	//
	writeOtherText();
    //	
    // save
    _saveObservationData();
    //
	if (sectionIndex == 0){
        // save is in goObservatonMain
		// page 1
        hide(document.getElementById("observation"));
		goObservationMain();
        //cview.style.display = "none";
	} else {
    	        
        //				
		// move pointer
		sectionIndex--;
		// update display
		refreshSectionTitle();
		//refreshSectionList();		
		// construct page
		//	section title, description, lookfors
		//	  , back button, forward button
		refreshObserverSection();
	}
	// scroll to the top
	goTop();

}

function clearSettings(event)
{
	// WARN if there are observations to send	
	if (confirm('Clear all settings and data?',"Yes", "Cancel")){
        // if YES...
        // are there any observations?
		if (observations.length > 0){
            // exit if they say NO - don't clear my stuff
            if (!confirm("You have saved observations, are you sure you want to change users and delete them?","Yes", "No"))
				return;
		}
        
        hide(document.getElementById('settingsArea'));
    // reset message
        var message = document.getElementById("message");
        if (message)
            message.innerText = "Enter your LoTi Username and Password";
        // clear all the settings and data
       _clearSettings(); 
    }
}
function _clearSettings()
{
    //
    //
    resetGlobals();
    //
    // clear user id and pswd
    var emptyString = "";
    var userid = document.getElementById('userID');
    userid.value = emptyString;
    var pswd = document.getElementById('pswd');
    pswd.value = emptyString;
    //	
    //setCheckbox("rememberCheckbox", false);
    var checkboxToChange = document.getElementById('rememberCheckbox');
    var checkboxValue = true;	
    checkboxToChange.checked = checkboxValue;
    //
    // moved to resetGlobals.....
    // DeleteRecordStore();
    // mainDatabase = CreateRecordStore();
    //
}

function resetGlobals(){
		// erase owner data from database
		if (!useCookies && mainDatabase && !(ownerID == 0))
			DeleteRecordStore();
			//mainDatabase.deleteRow("ownerData",'"id"',ownerID);
		//
		ownerID = 0;
		formID =0;
        //
        formName = "Unset";
        //
		sectionIndex = 0;
        currentObservation = null;
		//
		teachers = []
		observations = [];
        
        formNames = [];
        formTemplateArray = [];
        
		formTemplate = null;
        
		_clearCookie();
		needsDisplay = true;
		sectionListNeedsDisplay = true;
        //
        _clearLocalSettings();
		//
		return;
}

function toggleCheckbox(elementID){
	var checkboxToChange = document.getElementById(elementID);
	if (null !== checkboxToChange)
		checkboxToChange.checked = !checkboxToChange.checked;//flip the switch
	// does nothing if element not found
}
function setCheckbox(elementID, newValue){
	var checkboxToChange = document.getElementById(elementID);
	
	if (null !== checkboxToChange)
		checkboxToChange.checked = newValue;
	// does nothing if element not found
}

function hasDoneObservations()
{
	if (null !== observations){
		for (var i = 0;i< observations.length;i++){
			if (observations[i].done)
				return true;
		}
	}
	return false;
}
function countDoneObservations()
{
    var numberDone = 0;
	if (null !== observations){
		for (var i = 0;i< observations.length;i++){
			if (observations[i].done)
				numberDone++;
		}
	}
	return numberDone;
}
/* ************************************** */
function goTeacherList()
{
	//var teacherList = document.getElementById('list').object;	
	//
    _clearLocalSettings();
    //
    _saveObservationData();// will save blank ones....
    
    //var teacherList = document.getElementById('teacherList');
    //teacherList.style.display = "none";
    
	if (needsDisplay)
		refreshTeacherList();
	//
	// reset currentObservation to null
	// currentObservation holds the observation object only while
	// on the observation pages
	//
	currentObservation = null;
	//
	// turn on Upload button if there are any observations
	var uploadButton = document.getElementById('uploadButton');
	//
    //  number to upload text
    var textObjectToChange = document.getElementById('numberToUpload');
    //
	if (hasDoneObservations()){
		//uploadButton
		//set visible
		showButton(uploadButton);
		//
        // set upload text
        // number of observations to upload...
        var nbrToUpload = countDoneObservations();
        if (textObjectToChange && nbrToUpload > 0){
            if (nbrToUpload ==1){
                textObjectToChange.innerText = nbrToUpload+" Observation ready to upload";
            } else {
                textObjectToChange.innerText = nbrToUpload+" Observations ready to upload";
            }
            //
            show(textObjectToChange);
        }
		//
	} else {
		//uploadButton OFF
		hideButton(uploadButton);
		//upload text OFF
        hide(textObjectToChange);
	}
    //
    // turn on settings if logged in
    if (!(ownerID == 0) )
        show(document.getElementById('settingsArea'));
    else
        hide(document.getElementById('settingsArea'));
	//
	var layout = document.getElementById('stackLayout').object;
    currentScreen = 'teacherList';
    layout.setCurrentView(currentScreen, true, true);
	//
    _saveSettings();
    //
	goTop();
	//
}
function goObservationSection(event)
{
	//
	goTop();
	// save
	_saveObservationData();
	//
	var layout = document.getElementById('stackLayout').object;
    currentScreen = 'observation';
	layout.setCurrentView('observation', false, true);
	//
	goTop();

}
function writeTeacherComment(){
	//var commentField = document.getElementById("commentText");
	var commentItem = document.getElementById('commentText');
	if (null !== commentItem && !(""==commentItem.value)){
		currentObservation.comment = commentItem.value;
	}
}
function goObservationMain(event)
{
    var layout = document.getElementById('stackLayout').object;
    var cview = layout.getCurrentView();
    //
    var reverseTransition = false;
	//
    // 'teacherList' or 'observation'
    if ('teacherList' == cview.id) {
        //set form
        var currentFormObject = document.getElementById("currentTemplateName");
        var observationFormName = document.getElementById("currentTemplateName2");
        //
        if (debugON){
            console.log("goObservationMain->currentObservation.formID = "+currentObservation.formID);
            console.log("goObservationMain->currentObservation.formName = "+currentObservation.formName);
        }
        // update formname on Observation page
        observationFormName.innerText = currentObservation.formName;
        
        //
        if (currentObservation.formID+0 == formID+0 ){
            // same as current form
            //observationFormName.innerText = currentObservation.formName;// same as DEFAULT (should be in currentObservation.formName
            if (debugON)
                console.log("DEFAULT currentObservation.formID+0 == formID+0 ");
            //
        } else {
            //
            // form doesnt match - find and change to the correct template
            _alert("This Observation was made with a different Observation form.  Changing forms....");
            //return;
            if (formTemplateArray.length > 0){
                for (var i=0;i<formTemplateArray.length;i++){
                    var itemID = new Number(formTemplateArray[i][0]);
                    if (itemID+0 == currentObservation.formID+0){
                        // found the right form
                        formID = itemID;
                        formName = formTemplateArray[i][1];
                        formTemplate = formTemplateArray[i][2];//sets the global form template
                        //
                        // update Default form name
                        currentFormObject.innerText = formName;
                        //
                        if (debugON){
                            console.log(" **formID reset: "+formID);
                            console.log(" **formName reset: "+formName);
                            console.log(" **formTemplate reset:"+formTemplate.name);
                        }
                        break; // all done
                    }
                }
            }
        }
        //
        if (debugON)
            console.log("observationFormName.innerText set to: "+observationFormName.innerText);
        //
        refreshSectionTitle();
        sectionIndex = 0;
        if (sectionListNeedsDisplay)
            refreshSectionList();
        //    
        reverseTransition = false;
    } else {
        // returning from the observer pages, 'observation' currentView
        goTop();
        refreshSectionTitle();
        sectionIndex = 0;
        // save
        _saveObservationData();
        //
        if (sectionListNeedsDisplay)
            refreshSectionList();
        //
        reverseTransition = true;
    }
	//
    currentScreen = 'newObservation';
    layout.setCurrentView('newObservation', reverseTransition, true);
	//
	goTop();
}
function goSettings(event)
{
	//
	var layout = document.getElementById('stackLayout').object;
    currentScreen = 'authenticate';
	layout.setCurrentView('authenticate', false, true);//use settings view later
	//
	goTop();
	//
}
function goTeacherInfo(event)
{
	goTop();
	//
	// set the comment text block
	if (null !== currentObservation){
		var commentItem = document.getElementById('commentText');
		commentItem.value = currentObservation.comment;
	}
	//
	// save
	//_saveObservationData();
	//
	var layout = document.getElementById('stackLayout').object;
	layout.setCurrentView('teacherInfo', false, true);//use settings view later
	//
	goTop();
	//
}
/* ************************************** */
function resetTeacherListFilter(){
	for (i=0;i<teachers.length;i++){
		//mark visible
		teachers[i].visible = true;
	}
}

function filterTeacherList(event)
{
    // Insert Code Here
	var searchString = event.srcElement.value.toLowerCase();//"b";//stuff the user entered in the box
	//filter(testfunction[thisobj])
	var tempString;
	for (i=0;i<teachers.length;i++){
		tempString = teachers[i].value.toLowerCase();
		if (tempString.indexOf(searchString) > -1){
			//mark visible
			teachers[i].visible = true;
		} else {
			// mark hidden
			teachers[i].visible = false;
		}
	}
	needsDisplay = true;
	goTeacherList();
}


function clickLookfor(event)
{
	// checkboxbutton_1
	// lookforLabel_1
	
	// lookfortext = event.target.innerText;
	// lookforLabel_1 in event.target.outerHtml;
	var theHtml = event.target.outerHTML;
	var beginPosition = theHtml.indexOf("lookforLabel_");
	var checkboxItem = false;
	var checked = false;
	if (beginPosition > -1)
		beginPosition += "lookforLabel_".length;
	else {//must have clicked the checkbox
		beginPosition = theHtml.indexOf("checkboxbutton_");
		beginPosition += "checkboxbutton_".length;
		checkboxItem = true;//if true checkbox.checked has already been flipped
	}
	//
	var lookforNumber = 0;
	if (beginPosition > -1){
		var tempString = theHtml.substr(beginPosition,2); //two chars after the _
		//tempString.parseInt();
		lookforNumber = new Number(tempString.cleanstring().replace(/'\"'/g,''));
	}
	// find the checkbox element and check it
	var checkbox = document.getElementById('checkboxbutton_'+lookforNumber); //document.getElementById('rememberCheckbox').checked
	if (checkboxItem && null !== checkbox)
		checked = !checkbox.checked;
	else
		checked = checkbox.checked;
	//
	if (checked){
		checkbox.checked = false;
		// set the currentObservation value
		currentObservation.values[sectionIndex][lookforNumber] = 0;
	} else {
		checkbox.checked = true;
		currentObservation.values[sectionIndex][lookforNumber] = 1;
	}
	//
}

function clickConnect(event)
{
    if (!online()){
       _alert("You are currently OFFLINE.  You cannot login without a valid internet connection.","Alert");
       return;
    }
    // reset ownerID, teacher list
	if (observations.length > 0){
			if (!confirm("You have observations to send to the server, are you sure you want to change users and delete them?"))
				return;
	} else if (teachers.length > 0){
		//you sure you want to change teachers?
		if (!confirm("Are you sure you want to download a new teacher list?"))
				return;
	}
	//
	// passed validation tests			
	resetGlobals();
	//
	connectToServer();
    //

}
//
Array.prototype.find = function(searchStr) {
  var returnArray = false;
  for (i=0; i<this.length; i++) {
    if (typeof(searchStr) == 'function') {
      if (searchStr.test(this[i])) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    } else {
		if (this[i] == searchStr) {
			if (!returnArray) { returnArray = [] }
			returnArray.push(i);
		}
    }
  }
  return returnArray;
}
function findObservation(searchStr) {
	// find an observation by teacherID
    if (debugON)
        console.log("findObservation by teacherID");
    // returns false if not found, length is number found
  var returnArray = false;
  for (i=0; i<observations.length; i++) {
	if (observations[i].teacherID == searchStr) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    }
	return returnArray;	
}



function clearObservation(event)
{
    if (!confirm("Are you sure you want to delete this observation?"))
		return;
	// delete it
	_clearObservation();
}
/*  ****** Private method     *****   */
function _clearObservation()
{
	// delete it
	deleteCurrentObservation();
	// go back to teacher list
	needsDisplay = true;
	goTeacherList();
}

function deleteCurrentObservation(){
	//
	if (null === currentObservation){
		return;
	}
	var teacherID = currentObservation.teacherID;
	
	var recordList = findObservation(teacherID);
	// remove each from observations array
	if (recordList){
		for (var i=0;i<recordList.length;i++){
			observations.splice(recordList[i],1);//remove element recordList[i] from array
		}
	}
	// ok so delete it!
	if (!useCookies && mainDatabase)
		mainDatabase.deleteRow("observations",'"teacherid"',teacherID);
	else
		_saveObservationData();
		
}
function checkReadyStateStatus(xmlRequest, startDateTime){
    var thisDateTime = new Date().getTime();	
    var elapsedTime = thisDateTime - startDateTime;
    //
    switch(xmlRequest.readyState)
    {
    /*
        0: uninitialized
        1: loading
        2: loaded
        3: interactive
        4: complete
    */
        case 4:
            if(xmlRequest.status==200)
            {// do something?
                //alert('The upload request took '+elapsedTime);
                //window.clearTimeout(timeoutID);
            }
            break;
        default:
            //alert('xmlRequest.readyState = '+xmlRequest.readyState);
           if (elapsedTime > 5000){// 5 seconds....
                //_alert('The upload request has timed out. The server is too busy or your Internet connection is unavailable.', 'Error');
                xmlRequest.abort();
                //
            }
            break;
    }
}
function sendObservation(theData, theComment){
	var sucess = false;
	//var theURL = "http://"+dataServer+dataServerApplicationPath+"newObservation?test=";
	var theURL = urlPrefix+dataServer+dataServerApplicationPath+"newObservation?comment=";
	//
	if (theComment){
		theURL += theComment;
	}
	//
	// XMLHttpRequest setup code
	var xmlRequest = new XMLHttpRequest();
    //    
	var onloadHandler = function() { checkUploadStatus(xmlRequest); };	
	//
	xmlRequest.onload = onloadHandler;
	// need asycronous call setting (wait for reply)
	//xmlRequest.onreadystatechange = processReqChange;
	xmlRequest.open("POST", theURL, false);//open("method", "URL"[, asyncFlag[, "userName"[, "password"]]])
	//
	xmlRequest.setRequestHeader("Cache-Control", "no-cache");
	xmlRequest.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
	xmlRequest.setRequestHeader("Content-Language", "en-US");
	//
    // grab the time, give chance to abort in the call back if time exceeded
    var startDateTime = new Date().getTime();	
    //
    var timeoutID = window.setTimeout(function(){
        _alert('The upload request has timed out. The server is too busy or your Internet connection is unavailable.', 'Error');
        xmlRequest.abort();
        }, 5000);
    //
    var readyStateHandler = function() {checkReadyStateStatus(xmlRequest, startDateTime); };
    xmlRequest.onreadystatechange=readyStateHandler;
    //	
    // wrap in an if so they don't click twice?
	xmlRequest.send(theData+"\n");
    //
    window.clearTimeout(timeoutID);
	// returns after completion
	//need to poll status and abort if it takes too long
	//xmlRequest.abort();
	//can check for sucess here
	if (xmlRequest.responseText.indexOf('Request Complete') > -1){
		//alert(xmlRequest.responseText);
		sucess = true;
	} else {
		//Request Failed - Reason: Database Save error!
		var start = xmlRequest.responseText.indexOf('<body>')+6;
		var end = xmlRequest.responseText.indexOf('</body>');
		var messageText = xmlRequest.responseText.slice(start, end);
		_alert("Observation Upload Failed!  The server said: "+messageText,"Error");
	}
	//
	return sucess;
}

function checkUploadStatus(xmlRequest){
	if (xmlRequest.status == 200) {
		//
	} else {
		_alert("There was an error connecting to the server.  Check your internet connection and try again","Error");
	}
	return;
}

function uploadObservatons(event)
{
    //
    // User clicked the *Upload* button
    //
    if (!online()){
       _alert("You are currently OFFLINE.  You cannot upload your observations without a valid internet connection.","Alert");
       return;
    }
	if (!uploadEnabled){
		alert("Uploads disabled, simulating observation upload....");
	}
    if (!confirm("Are you sure you want to upload your observations?"))
		return;
    //
    _uploadObservatons();
    
}
function _uploadObservatons()
{
	// Uses Global:
    //  currentObserverion, observations, uploadEnabled, needsDisplay
    //
	// check connection?
	//checkConnectionStatus();//async call, returns AFTER this is done :/
	//
	var uploadCounter = 0;
	// upload the observations
	var observationList = observations.slice(); //work from a copy since we're changing it in the loop
	var theData = null;
	for (var i=0;i<observationList.length;i++){
		currentObservation = observationList[i];
		if (null !== currentObservation && currentObservation.done){
			// send it
			var sucess = true;
			//
			var beginDate = currentObservation.beginDate.getTime();
			var endDate = currentObservation.endDate.getTime();
			var lotiUserID = currentObservation.teacherID;
			//
			var theComment = escape(currentObservation.comment); 
			//
			if (uploadEnabled){
				//do this one....
				// fields are ownerID, templateID, lotiUserID, odate, odateEnd, packedValues 
				var theData = ownerID+"~"+formID+"~"+lotiUserID+"~"+beginDate+"~"+endDate+"~"+packedValues(currentObservation)+"~\n";
				//
				sucess = sendObservation(theData, theComment);
			}
			if (sucess || !uploadEnabled){
				// delete it
				deleteCurrentObservation();
				uploadCounter++;
			}
		}
	}
	//
	currentObservation = null;
	observationList = null;
	//
	_alert(uploadCounter+" observations uploaded","Upload Complete");
	//remove uploaded observaton	
	needsDisplay = true;
	goTeacherList();		
}


function toggleEdit(event)
{
    // Clear done flag
	// and end date
	if (null !== currentObservation){
		currentObservation.done = false;
		currentObservation.endDate = null;
		sectionListNeedsDisplay = true;
		needsDisplay = true;//redraw the teacher list
		goObservationMain();
	}
}


function goObservationDate(event)
{
	goTop();
	// save
	//_saveObservationData();
	
	// make sure it redraws the date
	var	textObjectToChange = document.getElementById('beginDateDisplay');
	var tempDate = currentObservation.beginDate;
	if (null === tempDate)
		tempDate = new Date();
	//	
	textObjectToChange.innerText = tempDate.toLocaleString();//
	// set popup values
	
	document.getElementById('month_popup').value = tempDate.getMonth()+1;// zero based index
	var day = document.getElementById('day_popup').value = tempDate.getDate();
	var year = document.getElementById('year_popup').value = tempDate.getYear();
	//
	var layout = document.getElementById('stackLayout').object;
    currentScreen = 'observationDate';
	layout.setCurrentView('observationDate', false, true);//use settings view later
	//
	goTop();
	//
}

function updateDateDisplay(event){
	//
    var month = document.getElementById('month_popup').value-1;
	var day = document.getElementById('day_popup').value;
	var year = document.getElementById('year_popup').value;
	// create new date
	var tempDate = new Date();
	tempDate.setMonth(month);
	tempDate.setDate(day);
	tempDate.setYear(year);
	//
	// redraw it onscreen
	var	textObjectToChange = document.getElementById('beginDateDisplay');
	textObjectToChange.innerText = tempDate.toLocaleString();
	//
	return;
}
function doneEditDate(event)
{
	var month = document.getElementById('month_popup').value-1;
	var day = document.getElementById('day_popup').value;
	var year = document.getElementById('year_popup').value;
	// create new date and replace in observation
	var tempDate = new Date();
	tempDate.setMonth(month);
	tempDate.setDate(day);
	tempDate.setYear(year);
	// set the observation
	currentObservation.beginDate = tempDate;
	// make sure it redraws the date
	var	textObjectToChange = document.getElementById('beginDate');
	textObjectToChange.innerText = shorterDate(currentObservation.beginDate.toLocaleString());//
    //
    currentObservation.endDate = currentObservation.beginDate;
	//
	var layout = document.getElementById('stackLayout').object;
     currentScreen = 'teacherInfo';
	layout.setCurrentView('teacherInfo', true, true);//use settings view later
	//
	//goTop();
	//
	return;
}

function endObservation(event)
{
	//
	// last page
	if (null !== currentObservation){
		// mark done
		currentObservation.done = true;
		// put in end date
        if (null === currentObservation.endDate)
            currentObservation.endDate = new Date();//currentObservation.beginDate;//use begin date since we can edit that
	}
    //save 
    _saveObservationData();
    //
	// hide done button, show edit
    var clearButton = document.getElementById('clearObservation');
    var editButton = document.getElementById('editObservation');
	var doneButton = document.getElementById('doneButton1');
    hideButton(clearButton);
	hideButton(doneButton);
    showButton(editButton);
    //
	sectionListNeedsDisplay = true;
	needsDisplay = true;
	//
	goTeacherList();
	//
}


function toggleFind(event)
{
    var findButton = document.getElementById('findButton');
	var searchField = document.getElementById('searchfield');
	if (searchField.style.display == 'none')
		show(searchField);
	else
		hide(searchField);
	//
}

var updateComments = function(event)
{
		var picklist = document.getElementById('commentPickList');
		var commentItem = document.getElementById('commentText');
        //
		// get selected item
		var selectedText = picklist.value;//
        //
        //alert("selectedText="+selectedText);
        //
		// add to comment text
        if ("" == commentItem.value){
            commentItem.value = selectedText;
        } else {
            commentItem.value = commentItem.value+" "+selectedText;
        }
		// undo the selection?
		picklist.value = "";
}

function returnFromTeacherInfo(event)
{
	writeTeacherComment();	
	//
	goObservationMain();//does the save
	//		
}
function returnObservationMain(event)
{
	writeOtherText();	
	//
	goObservationMain();//does the save
	//		
}


function goSplashScreen(event)
{
    // Insert Code Here
	//
	var layout = document.getElementById('stackLayout').object;
	layout.setCurrentView('splashScreen', false, true);
	//
	goTop();
	//
}


function goLookfors(event)
{
    //
	writeTeacherComment();	
    //
    sectionIndex = 0;//setting
    refreshSectionTitle();
	refreshObserverSection();
	goObservationSection(event);
}


function checkOtherBox(event)
{
    // The other textbox has changed
    // get the last checkbox on this page and 
    try {
        var lookforNumber = currentObservation.values[sectionIndex].length-1;
        var checkbox = document.getElementById('checkboxbutton_'+lookforNumber); 
        checkbox.checked = true;
        // set data object
        currentObservation.values[sectionIndex][lookforNumber] = 1;
    } catch (err){
        //log message
    }
}


function retrieveForms(event) {
    // Insert Code Here
    //
    // show Fetching Form list from server message...
    //
    getFormsFromServer();
    /*
    
    // return to main screen
    var settingsStackLayout = document.getElementById('settingsStackLayout').object;
    settingsStackLayout.setCurrentView('view1');
    
    */
    //
}
function getFormsFromServer(){
	// Values you provide
    //	/wa/DirectAction/getTemplateList?ownerID=1235982	[&orgID=xxxxxxx]
    
    // dataServer is lotiObserver rather than lotiobservation
    //var dataServer = "mary.lqhome.com";
    var special_dataServerApplicationPath = "/cgi-bin/WebObjects/lotiObserver.woa/wa/DirectAction/";
    //
	var feedURL = urlPrefix+dataServer+special_dataServerApplicationPath;
	//
	var statusMessage = document.getElementById('message');
    var savedStatus = statusMessage.innerText;
	//
	// Turn OFF sync button while fetching data...... document.getElementById('syncButton').
	//statusMessage.value = "Connecting.....";
	//	
	if (ownerID==0){
			_alert("You must log in before you can change your Observation form.  Please correct and try again.");
			statusMessage.innerText = "Invalid Username or Password";
			return;
		
	} else {
		//
		statusMessage.innerText = "Retrieving available Observation forms .....";
		//
		feedURL = feedURL + "getTemplateList?ownerID="+ ownerID;
	}
	//
    // XMLHttpRequest setup code
	var xmlRequest = new XMLHttpRequest();
	// The feed to fetch
	var onloadHandler = function() { xmlLoadedObserverForm(xmlRequest); };	// The function to call when the feed is loaded; currently calls the XMLHttpRequest load snippet
	
	xmlRequest.onload = onloadHandler;// xmlLoadedObserverForm
	xmlRequest.open("GET", feedURL, false);
	xmlRequest.setRequestHeader("Cache-Control", "no-cache");
    
       // grab the time, give chance to abort in the call back if time exceeded
    var startDateTime = new Date().getTime();	
    //
    var timeoutID = window.setTimeout(function(){
        _alert('The request has timed out. The server is too busy or your Internet connection is unavailable.', 'Error');
        xmlRequest.abort();
        }, 5000);
    //
    var readyStateHandler = function() {checkReadyStateStatus(xmlRequest, startDateTime); };
    xmlRequest.onreadystatechange=readyStateHandler;
    //	
    // wrap in an if so they don't click twice?
	xmlRequest.send(null);
    //
    window.clearTimeout(timeoutID);
	// returns after completion
	//need to poll status and abort if it takes too long
	//xmlRequest.abort();
    
    statusMessage.innerText = savedStatus;
    //
	
}
// Called when an XMLHttpRequest loads a feed; works with the XMLHttpRequest setup snippet
function xmlLoadedObserverForm(xmlRequest) 
{
	var statusMessage = document.getElementById('message');
    var savedStatus = statusMessage.innerText;
	
	if (xmlRequest.status == 200) {
		// Parse and interpret results
		// XML results found in xmlRequest.responseXML
		// Text results found in xmlRequest.responseText
		//
		// get the ownerID and the form data
		var responseText = xmlRequest.responseText;
		if (responseText.indexOf('Unavilable') > -1){
			_alert("Server is currently unavilable, please try again later.","Error");
            statusMessage.innerText = savedStatus;
			return;
		}
		//if (ownerID == 0){//and remember pswd
			//
			//
			//statusMessage.innerText = "Retrieveing Observation form.....";
            //
            var templateList = getServerData("templateList",responseText);
            var templateArray = templateList.split('<br>');
            var raw_templateString;
            //
            var aformID = formID;
            var aformTemplate = formTemplate;
            var aformName = formName;
            //
            var formArray = new Array();
            var nameArray = new Array();
            //
            for(var i=0;i<templateArray.length;i++){
                raw_templateString = templateArray[i];
                if (raw_templateString.length > 4){
                    //  parse Form Data
                    formID = parseTemplateID(raw_templateString);
                    formName = getServerData("templateName",raw_templateString);
                    
                    aformTemplate = parseObserverTemplate(raw_templateString);
                    //
                    formArray[formArray.length] = new Array(formID,formName,aformTemplate);
                    nameArray[nameArray.length] = formName;
                    // if current form, set selection
                    if (formID+0 == aformID+0)
                        document.getElementById("currentTemplateName").innerText = aformName;
                }
            }
			//
			// save form
			//_saveFormData();
			//
            // set list
            formNames = nameArray;
            formTemplateArray =formArray; // save for later...
            //
            // reset Globals
            formID = aformID;
            formName = aformName;
            //
            document.getElementById("formsList").object.reloadData();

            //
		//} 		
	} else {
		_alert("There was an Error connecting to the server: HTTP status " + xmlRequest.status+"\nThe server said: "+responseText.strip(),"Error");
		//alert("You are not connected to the Internet.  Connect to the Internet and try again");
	}
    //
    statusMessage.innerText = savedStatus;
    //
    return;
}

// This object implements the dataSource methods for the list.
var formsListDataSource = {
	
	// Sample data for the content of the list. 
	// Your application may also fetch this data remotely via XMLHttpRequest.
	_rowData: formNames,//["H.E.A.T", "H.E.A.R.T", "CAPA"],
	_selectedCheckItem: null,
    
	// The List calls this method to find out how many rows should be in the list.
	numberOfRows: function() {
        this._rowData = formNames;
		return this._rowData.length;
	},
	
	// The List calls this method once for every row.
	prepareRow: function(rowElement, rowIndex, templateElements) {
		// templateElements contains references to all elements that have an id in the template row.
		// Ex: set the value of an element with id="label".
        
        var formnameObject = document.getElementById("currentTemplateName");
        var checkItem = templateElements.check;
        var labelItem = templateElements.label1;
        var thisformname = this._rowData[rowIndex];
        
		if (labelItem) {
			labelItem.innerText = thisformname;
		}
        
        if (checkItem){
            
            if (formnameObject.innerText == thisformname){
                show(checkItem);
                labelItem.style.color="#4263CC";
                _selectedCheckItem = checkItem; 

            } else {
                labelItem.style.color="black";
                hide(checkItem);
                }
        }
		// Assign a click event handler for the row.
		rowElement.onclick = function(event) {
			// Do something interesting
			//alert("Row "+rowIndex);
            //
            // set currentTemplateName
            formnameObject.innerText = thisformname;
            //
            if (_selectedCheckItem){
                hide(_selectedCheckItem);
                
                var parentElement = _selectedCheckItem.parentElement;
                var oldLabel;
                if (parentElement.children.length == 2)
                    oldLabel = parentElement.children[0];
                else
                    oldLabel = parentElement.children[1];

                oldLabel.style.color="black";
                
            } 
            _selectedCheckItem = checkItem; 

            show(checkItem);//show the checkbox
            if (labelItem)
                labelItem.style.color="#4263CC";
            //
            var formsList = document.getElementById("formsList").object;
            //formsList.setSelectionIndexes([rowIndex], false);
            formsList.setSelectionIndexes([], false);


		};
	}
};

function selectForm(event)
{
    // Insert Code Here
    //var objDiv = document.getElementById("teacherList");
    //objDiv.scrollTop = objDiv.scrollHight;
    event.preventDefault();
    
    // put here so can overide or disable
    var settingsStackLayout = document.getElementById('settingsStackLayout').object;
    settingsStackLayout.setCurrentView('view2', false, true);
    
    // retrieve forms list
    retrieveForms(event);
    
}


function doneSelectForm(event)
{
    // Insert Code Here
    //event.preventDefault();
    //
    //  Uses GLOBAL formTemplateArray
    //
    // switch forms
    // formTemplateArray = []; // an array to hold the formTempates - new Array(aformID,aformName,aformTemplate);
    var formnameObject = document.getElementById("currentTemplateName");    // has name of selected form
    var aformID;
    var aformName
    var aformTemplate;
    
    if (formnameObject){
        // get formID and template and set
        for (var i=0; i< formTemplateArray.length; i++){
            
            aformName = formTemplateArray[i][1];
            //
            if (formnameObject.innerText === aformName){
                //
                aformID = formTemplateArray[i][0];
                aformTemplate = formTemplateArray[i][2];
                //
                // set Globals
                formID = new Number(aformID);
                formTemplate = aformTemplate;
                formName = aformName;
                // name is already set
                // save form
                _saveFormData();
                
                break;//no need to process any more
            }

        }
    }
    // return to settings menu display
    var settingsStackLayout = document.getElementById('settingsStackLayout').object;
    settingsStackLayout.setCurrentView('view1', true, true);
    
}

/*   ***********************************************************************
	Application Settings

This uses localStorage to save and restore application settings data.

Currently stores the currently selected form and which stackLayout screen 
the user was on when they quit.

	uses and sets GLOBAL applicationSettings, formID, formName, formTemplate, currentScreen

Created:  09/20/10
Modified: 
**************************************************************************** 
*/


// formID, formName, formTemplate, currentScreen are in Main.js
//	if (typeof(document.currentScreen) == 'undefined') 
/* *******
Put restoreLocalStorage() in the onLoad event
changes are saved on exit.
**********
*/
function restoreLocalStorage(){
	//
	// sets GLOBAL applicationSettings via _loadSettings()
	//
	if (typeof(localStorage) == 'undefined') {
		_alert('Browser Error - local storage not supported! Update your operating system to the latest version.','Error');
   	}
	_loadSettings();
	// Save changes if the user leaves the page.
  	 window.onbeforeunload = function () {
		return _saveSettings();
    };

	return;
}
function _saveSettings(){
	//
	// uses GLOBAL applicationSettings
	//
	if (applicationSettings===null || applicationSettings==='undefined')
		_initSettings();
	//
	localStorage.removeItem("settings");
	try {
		//localStorage.setItem("settings", applicationSettings);
        localStorage.setItem("settings", applicationSettings.value);
        console.log("saved settings are: "+localStorage.getItem("settings").replace(/##/g,", "));
	} catch (error) {
		_alert("Error loading local storage.  Error message was: "+error.message,"Error");
	}
	return;
}

function _loadSettings(){
	//
	// sets GLOBAL applicationSettings
	// sets GLOBAL formID, currentScreen, sectionIndex via restoreSettings()
	//
	var tempSettings = localStorage.getItem("settings");
	// if null create
	if (tempSettings===null || tempSettings==='undefined'){
        applicationSettings = null;
		_saveSettings();
		//applicationSettings = localStorage.getItem("settings");
	} else {
        var tempArray = tempSettings.split("##");
        applicationSettings = new settings();
        //
        applicationSettings.value = tempSettings;
        //
        applicationSettings.formID = new Number(tempArray[0]);
        applicationSettings.currentScreen = tempArray[1];
        applicationSettings.sectionIndex = new Number(tempArray[2]);
        //
        console.log("loaded settings are: "+applicationSettings.value.replace(/##/g,", "));
    }
	//
	_restoreSettings();
	//
	return;
}

function _restoreSettings(){
	//
	// uses GLOBAL applicationSettings
	// sets GLOBAL formID, currentScreen, sectionIndex
	//
	if (applicationSettings !== null){
		// set globals
		formID = applicationSettings.formID ? applicationSettings.formID : 0;
		currentScreen = applicationSettings.currentScreen ? applicationSettings.currentScreen : "authenticate";
        sectionIndex = applicationSettings.sectionIndex ? applicationSettings.sectionIndex : 0;
        //
        //
        if (formID > 0){
            var testformTemplate = setupFormTemplate(formID); 
            //
            var formnameObject = document.getElementById("currentTemplateName");
            if (testformTemplate){
                formnameObject.innerText = testformTemplate.name;
                formTemplate = testformTemplate;
            }
        }
        //
	} else
		_alert('Error loading application settings - _restoreSettings()','Error');
	return;
}
function _initSettings(){
	//
	// sets GLOBAL applicationSettings
	// uses GLOBAL formID, formName, formTemplate, currentScreen, currentObservation
	//
	// save default selected form:
	// formID, formName, formTemplate
	// and currentScreen
	//
	//applicationSettings = {"formID":formID,"formName":formName,"formTemplate":formTemplate,"currentScreen":currentScreen, "sectionIndex":sectionIndex, "currentObservation":currentObservation};
	applicationSettings = new settings();
    //
	return;
}
function settings(){
    // creates a new applicationSettings object
    this.formID =formID;
    this.currentScreen =currentScreen;
    var tempArray = new Array(formID, currentScreen, sectionIndex);
    this.value = tempArray.join("##");
}
function _clearLocalSettings(){
    applicationSettings = null;
	localStorage.clear();

}

/* **************************************************************************** 
*/