var availablePartNodes;
var ajaxRequestQueue;
var testing = false;
var mode;

function ajaxInit(){
	ajaxRequestQueue = new Array();
	set_availablePartNodes();
}

function set_availablePartNodes(){
	availablePartNodes = new Array();
	var table = document.getElementById("partsTable");
	for( var i=0; i<table.rows.length; i++ ){
		var splitId = table.rows.item(i).id.split("_");
		if( splitId[0] != "insertableRowNode" ) continue;
		availablePartNodes.push(table.rows.item(i));
	}
}

function expandOrCollapsePart(locationId,mode,model,year,chapter){
	if( document.getElementById("insertableRowNode_"+locationId) ) collapsePart(locationId);
	else expandPart(locationId,mode,model,year,chapter);
}

function expandPart(locationId,mode,model,year,chapter){
	if(testing) alert("expandPart");
	if( document.getElementById("insertableRowNode_"+locationId) ) return;
	var i = indexIn_availablePartNodes(locationId);
	if( i !== false ) addFrom_availablePartNodes(locationId, i);
	else makeAjaxRequest(locationId,mode,model,year,chapter);
	makeCollapsableForAll();
	checkExpandabilityForAll();
}

function collapsePart(locationId){
	if(testing) alert("collapsePart");
	if( !document.getElementById("insertableRowNode_"+locationId) ) return;
	var removableNode = document.getElementById("insertableRowNode_"+locationId)
	removableNode.parentNode.removeChild(removableNode);
	makeExpandableForAll();
	checkCollapsabilityForAll();
}

function indexIn_availablePartNodes(locationId){
	for(var i=0; i<availablePartNodes.length; i++){
		var splitId = availablePartNodes[i].id.split("_");
		if( splitId[1] == locationId ) return i;
	}
	return false;
}

function addFrom_availablePartNodes(locationId, i){
	if(testing) alert("addFrom_availablePartNodes");
	var clickedRow = document.getElementById("pageLocation_"+locationId);
	clickedRow.parentNode.insertBefore(availablePartNodes[i],clickedRow.nextSibling);
}

function makeAjaxRequest(locationId,mode,model,year,chapter){
	if(testing) alert("makeAjaxRequest");
	var newRequest = new AjaxRequest(locationId);
	newRequest.requestObj.open("get", "../galleries/itemFinder.php?mode="+mode+"&item="+locationId+"&model="+model+"&year="+year+"&chapter="+chapter, true);
	ajaxRequestQueue.push(newRequest);
	displayLoading(locationId);
	newRequest.requestObj.send(null);
}

function AjaxRequest(locationId){
	this.locationId = locationId;
	this.requestObj = createXMLHttp();
}

function createXMLHttp(){
	if(testing) alert("createXMLHttp");
	if(typeof XMLHttpRequest != "undefined"){ var ajaxRequestObj = new XMLHttpRequest(); }
	else if(window.ActiveXObject){
		var versions = ["MSXML2.XMLHttp.5.0","MSXML2.XMLHttp.4.0",
			"MSXML2.XMLHttp.3.0","MSXML2.XMLHttp","Microsoft.XMLHttp"];
		for(var i=0; i < versions.length; i++){
			try{
				var ajaxRequestObj = new ActiveXObject(versions[i]);
			}
			catch(e){}
		}
	}
	ajaxRequestObj.onreadystatechange = checkState;
	return ajaxRequestObj;
}

function checkState(){
	for( var i=0; i<ajaxRequestQueue.length; i++ ){
		if( ajaxRequestQueue[i].requestObj.readyState == 4 ){
			if( ajaxRequestQueue[i].requestObj.status == 200 ){
				if(testing) alert(ajaxRequestQueue[i].requestObj.responseText);
				domInsert(ajaxRequestQueue[i].requestObj.responseXML, ajaxRequestQueue[i].locationId, false);
			}
			else{
				if(testing) alert(ajaxRequestQueue[i].requestObj.status+"::"+ajaxRequestQueue[i].responseText);
				domInsert(null, ajaxRequestQueue[i].locationId, true); //NOTE: PART-NOT-FOUND ERROR IS CAUGHT SERVER SIDE AND VALID XML RESPONSE IS SENT.
			}
			ajaxRequestQueue.splice(i,1);
		}
	}
}


function trim(string01){
	var regEx = /^\s+|\s+$/g;
	return string01.replace(regEx,'');
}

function domInsert(domDoc, locId, hasError){
	if( locId ) var locationId = locId;
	else return;
	var mode = document.getElementById("mode").value.toLowerCase();
	if( domDoc && domDoc.getElementsByTagName("note") ) var newNotes = domDoc.getElementsByTagName("note");
	if( newNotes && newNotes[0] ) var newNote = newNotes[0].firstChild.nodeValue;
	if( hasError ) var newNote = "Additional item data is temporarily unavailable.";
	if( domDoc && domDoc.firstChild.attributes.getNamedItem("pictureid") ) var newPicId = domDoc.firstChild.attributes.getNamedItem("pictureid").nodeValue;

	var clickedRow = document.getElementById("pageLocation_"+locationId);
	var newPosition = clickedRow.sectionRowIndex + 1;

	var newRow = clickedRow.parentNode.insertRow(newPosition);
	newRow.setAttribute("id", "insertableRowNode_"+locationId);

	var td01 = newRow.insertCell(0);
	td01.setAttribute("class", "insertedNoteCell");
	if( !newNote ) var trimmedNote = String.fromCharCode(160);
	else var trimmedNote = trim(newNote);
	var text01 = document.createTextNode(trimmedNote);
	td01.appendChild(text01);
	td01.className = "insertedNoteCell"; //IE DOESN'T RENDER STYLE IF YOU USE setAttribute()


	var td02 = newRow.insertCell(1);
	if( newPicId && newPicId != "" ){
		var trimmedPicId = trim(newPicId);
		var img01 = document.createElement("img");
		img01.setAttribute("src", "../galleries/data/images/thumbs/"+mode+"/"+trimmedPicId+".jpg");
		img01.onclick = openLargePic;
		td02.appendChild(img01);
		td02.className = "insertedPicCell";
		img01.className = "insertedPic";
	}
	else{
		var div01 = document.createElement("div");
		var div02 = document.createElement("div");
		var text02 = document.createTextNode("Image Not Available");
		div02.appendChild(text02);
		div01.appendChild(div02);
		td02.appendChild(div01);
		div01.className = "noImage";
		div02.className = "noImageText";
		td02.className = "insertedPicCell";
	}
	availablePartNodes.push(newRow);
	removeLoading(locationId);
}

function displayLoading(locationId){
	var loadingMessageCell = document.getElementById("loading_"+locationId);
	var text01 = document.createTextNode("Loading...");
	loadingMessageCell.appendChild(text01);
	loadingMessageCell.className = "loading";
}

function removeLoading(locationId){
	var loadingMessageCell = document.getElementById("loading_"+locationId);
	loadingMessageCell.removeChild(loadingMessageCell.lastChild);
}

function expandAll(){
	if(testing) alert("expandAll");
	if(document.getElementById("showAll").className == "expandableInactive") return;
	var table = document.getElementById("partsTable");
	for( var i=0; i < table.rows.length; i++ ){
		var rowId = table.rows.item(i).id;
		if(!rowId) continue;
		if( rowId.substr(0,12) != "pageLocation" ) continue;
		var splitId = rowId.split("_");
		var params = document.getElementById("params_"+splitId[1]).value;
		var splitParams = params.split("_");
		expandPart(splitParams[0],splitParams[1],splitParams[2],splitParams[3],splitParams[4]);
	}
	document.getElementById("showAll").className = "expandableInactive";	
	document.getElementById("hideAll").className = "expandableActive";	
}

function collapseAll(){
	if(testing) alert("collapseAll");
	if(document.getElementById("hideAll").className == "expandableInactive") return;
	var table = document.getElementById("partsTable");
	for( var i=0; i < table.rows.length; i++ ){
		var rowId = table.rows.item(i).id;
		if(!rowId) continue;
		if( rowId.substr(0,12) != "pageLocation" ) continue;
		var splitId = rowId.split("_");
		var params = document.getElementById("params_"+splitId[1]).value;
		var splitParams = params.split("_");
		collapsePart(splitParams[0]);
	}	
	document.getElementById("showAll").className = "expandableActive";	
	document.getElementById("hideAll").className = "expandableInactive";	
}

function makeExpandableForAll(){
	document.getElementById("showAll").className = "expandableActive";	
}

function makeCollapsableForAll(){
	document.getElementById("hideAll").className = "expandableActive";	
}

function checkExpandabilityForAll(){
	if(testing) alert("checkExpandabilityForAll");
	var expandable = false;
	var table = document.getElementById("partsTable");
	for( var i=0; i < table.rows.length; i++ ){
		var rowId = table.rows.item(i).id;
		if(!rowId) continue;
		if( rowId.substr(0,12) != "pageLocation" ) continue;
		splitId = rowId.split("_");
		if(!document.getElementById("insertableRowNode_"+splitId[1])){
			expandable = true;
			break;
		}
	}
	document.getElementById("showAll").className = expandable ? "expandableActive" : "expandableInactive";
}

function checkCollapsabilityForAll(){
	if(testing) alert("checkCollapsabiliytForAll");
	var collapsable = false;
	var table = document.getElementById("partsTable");
	for( var i=0; i < table.rows.length; i++ ){
		var rowId = table.rows.item(i).id;
		if(!rowId) continue;
		if( rowId.substr(0,12) != "pageLocation" ) continue;
		splitId = rowId.split("_");
		if(document.getElementById("insertableRowNode_"+splitId[1])){
			collapsable = true;
			break;
		}
	}
	document.getElementById("hideAll").className = collapsable ? "expandableActive" : "expandableInactive";
}

var fullSizedImageWindow;
function openLargePic(navEvt){
	if(navEvt) var smallPicNode = navEvt.target;
	else var smallPicNode = event.srcElement;
	var mode = document.getElementById("mode").value.toLowerCase();
	var pattern = ".+"+mode+"\/";
	var regEx = new RegExp(pattern);
	largePic = smallPicNode.src.replace(regEx,"");
	regEx = /\.jpg/;
	largePic = largePic.replace(regEx,"");
	var path = "../galleries/picView.php?mode="+mode+"&pic="+largePic;
	fullSizedImageWindow = window.open(path,'fullSizedImage');
	fullSizedImageWindow.focus();
}
