/*
  A web application for browsing manuscripts of the Iliad
  copyright (c) 2007, Christopher W. Blackwell

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License
   as published by the Free Software Foundation; either version 2
   of the License, or (at your option) any later version.
   
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

  Christopher W. Blackwell. Furman University. christopher.blackwell@furman.edu
  
  Javascript code generated by GMapImageCutter © 2007 Richard Milton, Centre for Advanced Spatial Analysis (CASA), University College London (UCL)
*/

var app;
var debugOn = false;
var useProxy = true;


 $(document).ready(function(){
	 
    document.mimeType="text/html";    
    
    app = new msbrowser(debugOn,useProxy);
	 	 
 });



 
/* **************************************************** */ 
/* ** BEGIN Class Constants and Constructor */

//Misc
msbrowser.prototype.versiondate="August 3, 2007";
msbrowser.prototype.proxyString="http://chs75.chs.harvard.edu/cgi-bin/cheapproxy.cgi?remote=";

//Temp Stuff
msbrowser.prototype.localTI = "scenario/TextInventory.xml"

//Scenario stuff
msbrowser.prototype.scenarioURL = "scenario/HMTBrowserScenario.xml";
msbrowser.prototype.scenarioCiteIndex = "folioCitation";
msbrowser.prototype.scenarioImageIndex = "folioImage";
msbrowser.prototype.scenarioIndexService = "";
msbrowser.prototype.scenarioCTSService = "";
msbrowser.prototype.textInventoryXML = null;
msbrowser.mscollection = null;
msbrowser.currentMS = 0;
msbrowser.prototype.msCollectionID = "ms_collection"; //the collection that defines which editions we are dealing with

//String stuff
msbrowser.prototype.URNString = "urn:cts:greekLit:tlg0012.tlg001:";
msbrowser.prototype.citation = "";
msbrowser.prototype.RefIndexCitationQueryString1 = "Index?request=QueryIndex&indexID=folioCitation&ref=";
msbrowser.prototype.RefIndexCitationQueryString2 = "&value=&querytype=wholeword";

//QueryStuff
msbrowser.prototype.citationResultsXML = null;
msbrowser.prototype.citationResultsHTML = "Results will appear here";

//Strings for the image-viewer links
msbrowser.prototype.imageViewerURL = "image-viewer";


//Page-divisions in HTML
msbrowser.prototype.contentsDiv = "contentsDiv";
msbrowser.prototype.displayDiv = "displayDiv";
msbrowser.prototype.debugDivID = "debugDiv";
msbrowser.prototype.messageDivID = "messageDiv";
msbrowser.prototype.cite_ms_popupID = "cite_ms";
msbrowser.prototype.folio_ms_popupID = "folio_ms";
msbrowser.prototype.choiceDivID = "choiceDiv";
msbrowser.prototype.citationField = "citation_box";
msbrowser.prototype.folioBox = "folio_box";
msbrowser.prototype.rectoVerso = "recto_verso";
msbrowser.prototype.wait_message_gewgaw = "<img src='ui_graphics/spinner_mac.gif' style='margin-right: 10px;'/>";

/**
 * Constructor for msbrowser class.
 * @class A class for managing the msbrowser application.
 * See the fileoverview documentation for a summary of how this file
 * is organized.
 * @param showDebug Boolean value, true if debugging console should be
 * displayed.
 * @constructor
 */
function msbrowser(showDebug,useProxy) {
    	this.debugOn = showDebug;
    	this.useProxy = useProxy;
    	    	
    	this.postMessage("Loading scenario… please be patient.");
    	
	//this.postDebug("Initiating constructor");

	this.scenarioXML = null;
	this.textInventory = null;

	this.msArray = new Array();

	this.scenarioLoaded = false;
//	this.postDebug("Scenario loaded: " + this.scenarioLoaded);

	/*
		getScenario > processScenario >
		getTextInventory > 
		
		For now, TI stuff will be hard-coded below
	*/
	this.getScenario(this.scenarioURL);
		
} //application constructor







/* Switch between the image-view and the toc-view */



msbrowser.prototype.getScenario=function() {
 
// 	this.postDebug("entered getScenario okay.");
 	
 	var msbrowser = this;
  	$.ajax
    	(
		{
		url: msbrowser.scenarioURL,
		type: 'GET',
		asynch: false,
		datatype: 'xml',
	 	error: function(err) {
	 	alert("Error: "  + err);
	 	msbrowser.postDebug("Scenario error: " + err);
	 //msbrowser.ajaxErrorHandler("Scenario request");
	  },
	 success: function(data) {
	 msbrowser.processScenario(data);
	  }
	});
 	
 	
}

msbrowser.prototype.processScenario=function(data) {
	var debugDiv = document.getElementById(this.debugDivID);

	//this.postDebug("processing scenario");
	this.scenarioXML = $(data);

	this.scenarioCTSService = $("resources/resource[@resourceType='CTSURN']//service",this.scenarioXML ).attr("serviceURL");

	this.scenarioIndexService = $("resources/resource[@resourceType='indexNS']//service",this.scenarioXML ).attr("serviceURL");

	//this.postDebug( "CTS service at: " +  this.scenarioCTSService );
	//this.postDebug( "Index service at: " +  this.scenarioIndexService );

	//Move on from here
	this.getTextInventory();
}

msbrowser.prototype.getTextInventory=function() {
 //this.postDebug("entered getTextInventory okay.");
 	this.postMessage("Loading CTS TextInventory… please be patient.");
// 
  	var msbrowser = this;
  	
  	//Here we use a local TextInventory.xml file, to avoid laborious network traffic.
  	//This may change in the future.
  	
  	
  	
 	var tempURL = msbrowser.localTI;

 	
 	msbrowser.postDebug(tempURL);


  	$.ajax
    	(
		{
		url: tempURL,
		type: 'GET',
		datatype: 'xml',
		asynch: false,
	 	error: function(err) {
	 	alert("Error: "  + err);
	 	msbrowser.postDebug("TI error: " + err);
	  },
	 success: function(data) {
	 msbrowser.processTextInventory(data);
	  }
	});
 	
}

// Here's where we get a list of manuscripts by ID
// these will be stored in an array of objects:
//
//	msbrowser.mscollection[n]	.id
//							.info
//							


msbrowser.prototype.processTextInventory=function(data) {
	var allEditions = null;
	var myEditions = null;
	var tempObject = null;
	var msbrowser = this;
	var n;
	

	
	msbrowser.mscollection = null; // clear it out
	msbrowser.mscollection = new Array;
		
	//this.postDebug("processing ti");
	this.textInventoryXML = $(data);
	
	allEditions = $("editioncomments[/memberof]", this.textInventoryXML);

	$(allEditions).each(function() {
		testMembership = $("memberof",this).attr("collection");
		if ( testMembership == msbrowser.msCollectionID) {
			
			//build msbrowser.mscollection
			tempObject = new Object;
			tempObject.id = $(this).attr("projid");
			tempObject.info = $(this).text();
			
			msbrowser.postDebug(tempObject.id);
			
			n = msbrowser.mscollection.length;
			
			msbrowser.mscollection[n] = tempObject;
			
	
		}
	});

//	this.postDebug("Some more stuff from scenario: " +  $("*:nth(1)",tempNode).text() );	
	
//msbrowser.postDebug(msbrowser.mscollection.length + " objects stored in MS Array.");



	//Move on from here
	this.grabBasicData();



}


msbrowser.prototype.grabBasicData=function() {

	var tempMSstring = $.getURLParam("ms");
	var tempString;
	
	this.currentMS = -1;
		
	for (var counter = 0; counter < this.mscollection.length; counter++) {
		tempString = this.mscollection[counter].id;
		tempString = tempString.split(':');
		tempString = tempString[1];
				
		if (tempString == tempMSstring) {
			this.currentMS = counter;
		};
	}
		
	//What will I do with this.currentMS??

	this.buildTOCForm();
	
}

msbrowser.prototype.buildTOCForm=function() {
	var counter;
	var tempString;
	var cite_ms = "#" + this.cite_ms_popupID;
	var folio_ms = "#" + this.folio_ms_popupID;

	this.postMessage("Data gathered; building form…");

	//Populate 2 mss popup menus
	$(cite_ms).empty();
	$(folio_ms).empty();
	
	
	for (counter = 0; counter < this.mscollection.length; counter++) {
		tempString = '<option label = "' + this.mscollection[counter].info;
		tempString = tempString + '" value="' + this.mscollection[counter].id + '" ';
				
		tempString = tempString + '>' + this.mscollection[counter].info + '</option>';
		
		//this.postDebug(tempString);
		
		$(cite_ms).append(tempString);
		$((folio_ms)).append(tempString);
	}
	
	$(cite_ms).append('<option label="all" value="all">All manuscripts</option>');
	
	//If there is a selection already, add it as the default choice
	if (this.currentMS >= 0) {
		$(cite_ms).append('<option label="-" value="all">-</option>');
		$(folio_ms).append('<option label="-" value="">-</option>');
		tempString = '<option label = "' + this.mscollection[this.currentMS].info;
		tempString = tempString + '" value="' + this.mscollection[this.currentMS].id + '" ';
				
		tempString = tempString + '>&middot; ' + this.mscollection[this.currentMS].info + '</option>';
		
		//this.postDebug(tempString);
		
		$(cite_ms).append(tempString);
		$((folio_ms)).append(tempString);
	}
	
	//this.postDebug( $(cite_ms).val() );

	this.postMessage("");	
}

msbrowser.prototype.citationChoices=function() {
	var citationField = "#" + this.citationField;
	var citation;
	var refindexURL;

	//Populate some variables from the form
	citation = this.URNString + $(citationField).val();
	this.citation = citation;
	
	this.postDebug(this.citation);
	
	refindexURL = this.scenarioIndexService + this.RefIndexCitationQueryString1 + this.citation + this.RefIndexCitationQueryString2;

	if (this.useProxy){	
		refindexURL = escape(refindexURL);
		refindexURL = this.proxyString + refindexURL;
	} else {
		refindexURL = "http://" + refindexURL;
	}
	
	this.postDebug(refindexURL);
	
// http://chs75.harvard.edu:8080/refindex/Index?request=QueryIndex&indexID=folioCitation&ref=urn%3Acts%3AgreekLit%3Atlg0012.tlg001%3A1.9&value=&querytype=wholeword	
	
	this.postDebug("entered queryFolioCitation okay.");
 	
	this.postMessage("Finding online manuscripts… please be patient.");

 	
 	var msbrowser = this;
  	$.ajax
    	(
		{
		url: refindexURL,
		type: 'GET',
		asynch: false,
		datatype: 'xml',
	 	error: function(err) {
	 	alert("Error: "  + err);
	 	msbrowser.postDebug("Scenario error: " + err);
	  },
	 success: function(data) {
	 msbrowser.queryCitation(data);
	  }
	});


}

msbrowser.prototype.queryCitation=function(data) {
	var citeBox = "#" + this.cite_ms_popupID;
	var choiceDivID = "#" + this.choiceDivID;
	this.citationResultsHTML = "";

	var msbrowser = this;
	var tempValue;
	var tempText;
	var tempMS;
	var tempFolio;
	var tempCitation;
	var chosenMS = $(citeBox).val();
	
	var validCounter;
	var validTestMS;
	var isValidMS = false;
	
	this.postDebug("Entered queryCitation okay.");
	
	var n = "0";


	if (chosenMS != "all") {
		chosenMS = chosenMS.split(':');
		chosenMS = chosenMS[1];
	}
	
	this.citationResultsXML = $(data);
	
	var allResults = $("record", this.citationResultsXML);


 	$(allResults).each(function() {
 		tempValue = $("value",this).text();
 		tempText = tempValue.split('-');
 		tempMS = tempText[0];
 		tempFolio = tempText[1];
 		
 		tempCitation = $("ref",this).text();
 		
 		
		//confirm that the entry is for a valid ms, from our TextInventory
 		isValid = false;
		for (validCounter = 0; validCounter < msbrowser.mscollection.length; validCounter++) {
			validTestMS = msbrowser.mscollection[validCounter].id;
			validTestMS = validTestMS.split(":");
			validTestMS = validTestMS[1];
		//	msbrowser.postDebug("valid: " + validTestMS);
		//	msbrowser.postDebug("valid test: " + tempMS);
			if (validTestMS == tempMS) {
				isValid = true;
			}
		}

		//Check to see if this is one of our manuscripts
		if ((( chosenMS == "all") || (tempMS == chosenMS)) && (isValid))  {
		//Check to see if the urn really matches
			if (tempCitation == msbrowser.citation ) {
				msbrowser.postDebug(tempCitation + " appears on " + tempFolio + " of manuscript " + tempMS);

				msbrowser.citationResultsHTML = msbrowser.citationResultsHTML + msbrowser.createLink(tempCitation,tempFolio,tempMS);
				n++; // our counter
			}
		}

	});
	
	if ( this.citationResultsHTML == "" ) {
		 this.citationResultsHTML = "<p>No results found for this citation.</p>";
	} else {
		if (n == 1) {
		tempText = "<p>(" + n + " folio found.)</p>";
		} else {
		tempText = "<p>(" + n + " folios found.)</p>";
		}
		this.citationResultsHTML = "<ol>" + this.citationResultsHTML + "</ol>" + tempText;
	}
	
	this.postMessage("");
	
	$(choiceDivID).html(this.citationResultsHTML);
	$(choiceDivID).fadeIn("fast");
	

	
}

msbrowser.prototype.createLink=function(citation,folio,ms) {
	var tempText;
	var tempURL;
	var tempString;
	var humanFolio = this.humanizeFolio(folio);
	
	tempString = ms + " : " + folio;
	tempString = tempString + "&nbsp;&nbsp;&nbsp;- " + humanFolio + " of " + this.getMSDescription(ms);
	
	tempURL = this.imageViewerURL + "?folio=" + folio + "&ms=" + ms + "&image=";
	
	tempText = "<li>";
	tempText = tempText + "<a href='" + tempURL + "'>";
	tempText = tempText + tempString;
	tempText = tempText + "</a></li>";
	
	return tempText;


}

msbrowser.prototype.folioJump=function() {
	var folioBox = "#" + this.folioBox;
	var rectoVerso = "#" + this.rectoVerso;
	var msMenu = "#" + this.folio_ms_popupID;
	var tempMS = $(msMenu).val();
	tempMS = tempMS.split(":");
	tempMS = tempMS[1];
	var tempFolio = $(folioBox).val() + $(rectoVerso).val();
	
	var tempURL = this.imageViewerURL + "?folio=" + tempFolio + "&ms=" + tempMS + "&image=";
	
	window.open(tempURL,"_self");
	
	
	
	
}

/* ********************************************** */
/* BEGIN Utilities */

msbrowser.prototype.getMSDescription=function(ms) {
	var msDescription = ""; 
	var tempID;
	for (var counter = 0; counter < this.mscollection.length; counter++) {
		tempID = this.mscollection[counter].id
		tempID = tempID.split(":");
		tempID = tempID[1];
		if (tempID == ms) {
			msDescription = this.mscollection[counter].info;
		};
	}
	
	if ( msDescription == "" ) { msdescription = ms; }
	
	return msDescription;

}

msbrowser.prototype.humanizeFolio=function(folio) {
	//Assumes 1 or more digits, followed by "r" or "v" _and nothing else_!
	var tempText = "";
	
	var pageNumber = folio.substring(0,folio.length-1);
	var side = folio.substring(folio.length-1);
	
	if (side == "r") {
		side = "front (recto)";
	} else {
		side = "back (verso)";
	}
	
	tempText = "the " + side + " of folio " + pageNumber;
	
	return tempText;
}

msbrowser.prototype.clearChoices=function() {

	var choiceDivID = "#" + this.choiceDivID;
	
	$(choiceDivID).fadeOut("slow");
	$(choiceDivID).empty();

}


/**
 * Adds a message to list in debugging console.
 * @param thisText string
 */
msbrowser.prototype.postDebug=function(thisText) {
	var debugDiv = document.getElementById(this.debugDivID);
	var tempP = document.createElement("p");
	tempP.innerHTML = thisText;
	debugDiv.appendChild(tempP);
	
	if (debugOn) {
		debugDiv.style.display = "block";
	} else {
		debugDiv.style.display = "none";
	}
	
}

/**
 * Adds a message to list to the message division.
 * @param thisText string
 */
msbrowser.prototype.postMessage=function(thisText) {
	var messageDiv = "#" + this.messageDivID;
	
	if (thisText == "") {
		$(messageDiv).fadeOut("normal");
		$(messageDiv).empty();
	} else {
		$(messageDiv).empty();
		$(messageDiv).append(this.wait_message_gewgaw);
		$(messageDiv).append(thisText);
		$(messageDiv).fadeIn("normal");
	};
	
	
	
	
}

