/*

Copyright (c) 2005, Daniel Juliano
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this 
      list of conditions and the following disclaimer.
    * The names of contributors to this source code may not be used to endorse 
      or promote products derived from this software without specific prior 
      written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

/*

Script Summary:

This 'main' area holds a list of all tags in the contacts xml document as
well as a two dimensional array holding all contact information.  Retrieve
this list thru an XMLHttpRequest, then make it available by reference to the
other scripts (like search / sort / display).

*/

var mainPrefs = null;		// list of preferences, key-value pairs
var mainTitles = null;		// list of titles to display (first_name displays as First Name)
var mainContacts = null;	// actual contact information
var mainFirstTimeThru = false;

function initializeMain() {
	buttonMakeUtilVisible();
	buttonMakeTableVisible();
	xmlRequest('server.php', null, mainReturnXML);
}

// Callback method for xmlRequest().
function mainReturnXML(xml) {
	
	// Transfer DOM to a set of arrays for easy manipulation.
	mainReadTitles(xml);
	mainReadContacts(xml);
	mainCompleteInitialization();
}

function mainCompleteInitialization() {

	// Pass pointers of main arrays to each utility.
	initializeSearch(mainContacts, 1, 2);
	initializeSort(mainContacts, mainTitles, 'sort_table', '1, 2, 3');
	initializeList(mainContacts, mainTitles, '1, 2, 3');
	
	// Build the contact editing forms.
	formBuildAdd();
	formBuildView();
	formBuildEdit();
	
	// Cause the 'sort' list of contacts to show.
	buttonMakeUtilVisible("util_choice_list");
	buttonDisplayActionPaint();
}

// Create a two dimensional array to hold a mapping between tags used for contact
// information and the title to display on the add / edit / delete form.
function mainReadTitles(xml) {
	var titles = xmlFindChild(xml, "list_titles");
	var records = titles.getElementsByTagName("record");
	
	mainTitles = Array();
	for (var i = 0; i < records.length; i++) {
		if (records[i].nodeType == 1) {
			mainTitles[mainTitles.length] = records[i].firstChild.nodeValue;
		}
	}
	
	// First time thru, create default title listing and alert user.
	if (mainTitles.length < 2) {
		var message = "";
		message += "Welcome to JaxContact.\n";
		message += "A default profile will be set up for you ";
		message += "so that you can begin adding contacts.\n";
		message += "If you have viewed this message multiple times, ";
		message += "you must remember to click 'Save Changes' in order ";
		message += "to save contact information to the server.\n";
		alert(message);
		
		mainFirstTimeThru = true;
		
		mainTitles[mainTitles.length] = "ID";
		mainTitles[mainTitles.length] = "First Name";
		mainTitles[mainTitles.length] = "Last Name";
		mainTitles[mainTitles.length] = "Street Address";
		mainTitles[mainTitles.length] = "City";
		mainTitles[mainTitles.length] = "State";
		mainTitles[mainTitles.length] = "Zip";
		mainTitles[mainTitles.length] = "Home Phone";
		mainTitles[mainTitles.length] = "Work Phone";
		mainTitles[mainTitles.length] = "Mobile Phone";
	}
}

// Create a two dimensional contacts array from the xml DOM.
function mainReadContacts(xml) {
	
	mainContacts = Array();
	if (mainFirstTimeThru) return;
	
	// Contact information for one person is held in an xml node like so:
	//  <record>
	//    <a1>Daniel</a1>
	//    <a2>Juliano</a2>
	//  </record>
	//
	// Where the <a1> tag will translate to a title "First Name", and <a2>
	// will translate to title "Last Name".  We do this for two reasons:
	//  1) Titles can contain spaces and capitalization, abstracted from
	//     xml tags which cannot
	//  2) Xml tags like <a1> and <a2> take up very little space, which 
	//     helps with load and submit times
	
	var contacts = xmlFindChild(xml, "list_contacts");
	var records = contacts.getElementsByTagName("record");
	
	// Count the number of contact attributes.
	var count = 0;
	var children = records[0].childNodes;
	for (var i = 0; i < children.length; i++) {
		if (children[i].nodeType == 1) {
			count++;
		}
	}
	
	// Create a two dimensional array to hold each contact and its information.
	var tag = "";
	for (var i = 0; i < records.length; i++) {
		mainContacts[i] = Array();
		for(var j = 0; j < count; j++) {
			tag = "a" + j.toString();
			if (records[i].getElementsByTagName(tag)[0].firstChild) {
				mainContacts[i][j] = records[i].getElementsByTagName(tag)[0].firstChild.nodeValue;
			} else {
				mainContacts[i][j] = "";
			}
		}
	}
}

// Alert out the table.  Useful for debugging.
function mainAlertTable() {
	var message = "";
	for (var i = 0; i < sortArray.length; i++) {
		for (var j = 0; j < sortArray[i].length; j++) {
			message += sortArray[i][j] + ", ";
		}
		message += "\n";
	}
	alert(message);
}
// Format numbers to two digits, as in '03'.
function mainFormatToTwo(index) {
	var twoDecimals = /^(\d)$/;
	return ("" + index).replace(twoDecimals, "0$1");
}
function mainParseFormatted(index) {
	var noDecimals = /^(0+)/;
	var value = ("" + index).replace(noDecimals, "");
	if (value != null && value != "") return parseInt(value);
	return 0;
}
