
// Global Variables
var _xReq; // XMLHttpRequest object
var _xResp; // XMLHttpRequest response object
var _crmcWa; // working Attribute
var _crmcInitialized = false; // whether the initialization function has been run
var editDiv, eh_table, s_div, a_div, f_div; // div handles
var _crmcWaiting = false; // is the render function waiting on the load function
var _crmcAtts = new Array(); // master collection of Attribute (multi-control support)

// General functions
function crmc_Init() {
	editDiv = document.getElementById('crmc_e_div');
	eh_table = document.getElementById('crmc_header');
	s_div = document.getElementById('crmc_s_list');
	a_div = document.getElementById('crmc_a_list');
	f_div = document.getElementById('crmc_footer');

	_crmcInitialized = true;
}

function crmcOpenAttEdit(att, loadFunc) {
	_crmcWa = att;
	
	if(_crmcInitialized == false) {
		crmc_Init();
	}

	s_div.innerHTML = '<i>Loading...</i>';
	a_div.innerHTML = '';

	eh_table.rows[0].cells[0].innerHTML = 'Choose ' + _crmcAtts[_crmcWa].AttName + '(s)';

	if(_crmcAtts[_crmcWa].Loaded == false) {
		if(_crmcAtts[_crmcWa].LoadDynamic == false) {
			eval(loadFunc + '()');
		}
	} else {
		_crmcAtts[_crmcWa].CopyTempItems();
	}
	
	editDiv.style.display = 'block';
	
	/*o3_x and o3_y are display state variables used in overlib.js to track mouse positions.
	  These values are relative to the top left corner of the browser page. */
	var x = o3_x-350 + 'px';
	var y = 0;
	if(o3_y > 250){
		y = o3_y-250 + 'px';
	}
	else{
		y = 5;
	}
	editDiv.style.left = x;
	editDiv.style.top = y;
	  
	buildAttEditView();
}


// UI Functions
function loadXMLResponseData() {
	var att_node, att, itemNodes;
	for(n = 0; n < _xResp.childNodes.length; n++) {
		att_node = _xResp.childNodes[n];
		if(att_node.nodeType == 1 && att_node.nodeName != 'method') { // element node types that aren't the 'method' node only
			if(_crmcAtts[att_node.nodeName] != null) {
				att = _crmcAtts[att_node.nodeName];
				itemNodes = att_node.getElementsByTagName('item');
				for(i = 0; i < itemNodes.length; i++) {
					if(itemNodes.item(i).nodeType == 1) {
						node = itemNodes.item(i);
						att.AvailableItems[att.AvailableItems.length] = new Array(node.attributes[0].value, node.childNodes[0].data);
						if(node.attributes[1].value == '1') {
							att.SelectedItems[att.SelectedItems.length] = new Array(node.attributes[0].value, node.childNodes[0].data);
						}
					}
				}
				att.Loaded = true;
			}
		}
	}
	if(_crmcWaiting && _crmcWa != null) {
		_crmcWaiting = false;
		buildAttEditView();
	}
}
function buildAttEditView() {
	if(_crmcAtts[_crmcWa].Loaded == false) {
		_crmcWaiting = true;
		return;
	}

	var selected = _crmcAtts[_crmcWa].TempSelectedItems;
	var available = _crmcAtts[_crmcWa].AvailableItems;
	
	// render selected items
	var s_output = '<table cellpadding="0" cellspacing="0" width="100%" style="font-family: Tahoma, Verdana; font-size: 11px;">';
	if(selected.length == 0) {
		s_output += '<tr><td colspan="2"><i>None selected</i></td></tr>';
	} else {
		for(s = 0; s < selected.length; s++) {
			s_output += '<tr><td>' + selected[s][1] + '</td>';
			s_output += '<td align="right"><a href="javascript:void(0);" onclick="RemoveItem(\'' + selected[s][0] + '\');">[remove]</a></td></tr>';
		}
	}
	s_output += '</table>';
	
	// render available items
	var a_output = '<table cellpadding="0" cellspacing="0" width="100%" style="font-family: Tahoma, Verdana; font-size: 11px;">'
	var a_count = 0;
	for(a = 0; a < available.length; a++) {
		if(in_array(selected, available[a][0]) == false) {
			a_output += '<tr><td>' + available[a][1] + '</td>';
			a_output += '<td align="right"><a href="javascript:void(0);" onclick="AddItem(\'' + available[a][0] + '\');">[add]</a></td></tr>';
			a_count++;
		}
	}
	
	if(a_count == 0) {
		a_output += '<tr><td colspan="2"><i>None available</i></td></tr>';
	} 
	
	a_output += '</table>';
	
	s_div.innerHTML = s_output;
	a_div.innerHTML = a_output;
	f_div.innerHTML = '<a href="javascript:void(0);" onclick="crmcSaveAndClose();"><b>[Done]</b></a>';
}
function AddItem(itemId) {
	_crmcAtts[_crmcWa].AddItem(itemId);
	buildAttEditView();
}
function RemoveItem(itemId) {
	_crmcAtts[_crmcWa].RemoveItem(itemId);
	buildAttEditView();
}
function AddAll(){
	var available = _crmcAtts[_crmcWa].AvailableItems;
	var selected = _crmcAtts[_crmcWa].TempSelectedItems;	
	for(avail = 0; avail < available.length; avail++) {
		if(selected.length > 0){
			var alreadySelected = false;
			for(var sel=0; sel<selected.length; sel++){
				if(selected[sel][0] == available[avail][0]){
					alreadySelected = true;
					break;
				}
			}
			if(!alreadySelected){
				_crmcAtts[_crmcWa].AddItem(available[avail][0]);
			}
		}
		else{_crmcAtts[_crmcWa].AddItem(available[avail][0]);}
	}
	buildAttEditView();
}
function RemoveAll(){
	var selected = _crmcAtts[_crmcWa].TempSelectedItems;
	
	for(rem = 0; rem < selected.length; rem++) {
		_crmcAtts[_crmcWa].RemoveItem(selected[rem][0]);
	}
	buildAttEditView();
}
function crmcCloseEditDiv() {
	editDiv.style.display = 'none';
}
function crmcCancelEditDiv() {
	if( _crmcAtts[_crmcWa].Changed == 2 && confirm('You have made changes.\nDo you want to keep them?') ) {
		crmcSaveAndClose();
	} else {
		if(_crmcAtts[_crmcWa].Changed != 1) { 
			_crmcAtts[_crmcWa].Changed = 0;
		}
		crmcCloseEditDiv();
	}
}
function crmcSaveAndClose() {
	_crmcAtts[_crmcWa].SaveItems();
	crmcCloseEditDiv();
}


// XMLHttpRequest functions
function loadXMLHttpDoc(url) {
	if(window.XMLHttpRequest) {
		_xReq = new XMLHttpRequest();
		_xReq.onreadystatechange = processXReqChange;
		try {
			_xReq.open("GET", url, true);
		} catch(ex) {
			alert(ex);
		}
		_xReq.send(null);
	} else if(window.ActiveXObject) {
		_xReq = new ActiveXObject("Microsoft.XMLHTTP");
		if(_xReq) {
			_xReq.onreadystatechange = processXReqChange;
			_xReq.open("GET", url, true);
			_xReq.send();
		}
	}
}
function processXReqChange() {
	if(_xReq.readyState == 4) {
		if(_xReq.status == 200) {
			_xResp = _xReq.responseXML.documentElement;
      		p_method = _xResp.getElementsByTagName('method')[0].firstChild.data;
			eval(p_method + '()');
		} else {
			alert('There was a problem retrieving the XML data:\n' + _xReq.statusText);
		}
	}
}

// Objects
function topLvlObj(ObjId, Attributes) {
	this.ObjId = ObjId;
	this.Attributes = Attributes;
	this.GetAttribute = getAttribute;
}
function getAttribute(attName) {
	var att;
	for(i = 0; i < this.Attributes.length; i++) {
		if(this.Attributes[i].AttName == attName) {
			att = this.Attributes[i];
			break;
		}
	}
	return att;
}
function crmcAttribute(ID, ClientID, AttName) {
	this.ID = ID; // Reference Id, something to keep Attribute unique in page scope
	this.ClientID = ClientID; // ClientID for full hidden field reference
	this.AttName = AttName; // Attribute Name (Actual ChmAttribute Name)
	this.LoadDynamic = false; // whether data is pulled from a XMLHttpRequest
	this.LoadDynamicUri = ''; // Uri to use for XMLHttpRequest
	this.Initialized = false; // whether basic initialization for the att has happened
	this.Loaded = false; // data loaded
	this.Changed = 0; // Have values changed (0, 1, or 2)
	this.AvailableItems = new Array(); // Available Items collection
	this.SelectedItems = new Array(); // Selected Items collection
	this.TempSelectedItems = new Array(); // Temp Selected Items
	this.CopyTempItems = copyTempItems; // copy function
	this.AddItem = add_Item; // add item function
	this.RemoveItem = remove_Item; // remove item function
	this.GetItem = get_Item; // get item function
	this.SaveItems = save_Items; // method that saves items to SelectedItems collection and hidden field
	this.OnSaveItems = null; // open "event" for custom post-save actions
}
function copyTempItems() {
	this.TempSelectedItems = clone_array(this.SelectedItems);
}
function add_Item(itemId) {
	this.TempSelectedItems[this.TempSelectedItems.length] = this.GetItem(itemId);
	this.Changed = 2;
}
function remove_Item(itemId) {
	var tmpArray = this.TempSelectedItems;
	this.TempSelectedItems = new Array();
	this.Changed = 2;
		
	for(s = 0; s < tmpArray.length; s++) {
		if(tmpArray[s][0] != itemId) {
			this.TempSelectedItems[this.TempSelectedItems.length] = this.GetItem(tmpArray[s][0]);
		}
	}
}
function get_Item(itemId) {
	var itemArray;
	for(a = 0; a < this.AvailableItems.length; a++) {
		if(this.AvailableItems[a][0] == itemId) {
			itemArray = this.AvailableItems[a];
			break;
		}
	}
	return itemArray;
}
function save_Items() {
	this.SelectedItems = clone_array(this.TempSelectedItems);
	var str = '';
	for(i = 0; i < this.SelectedItems.length; i++) {
		if(i > 0) { str += ','; }
		str += this.SelectedItems[i][0];
	}
	document.getElementById(this.ClientID + '_ValuesString').value = str;
	if(this.Changed == 2) { this.Changed = 1; }
	
	if(this.OnSaveItems != null) {
		this.OnSaveItems(this);
	}
}


// support functions
function in_array(a, v) {
	tr = false;
	for(i=0; i<a.length; i++) {
		if(a[i][0] == v) {
			tr = true;
			break;
		}
	}
	return tr;
}
function clone_array(a) {
	var r = new Array();
	for(i=0; i<a.length; i++) {
		r[i] = a[i];
	}
	return r;
}