//skywalk.js
//var xslMarc2DC = Sarissa.getDomDocument('http://www.w3.org/1999/XSL/Transform', 'stylesheet');
var xslMarc2DC = null;
var resultsProc = null;
var BLANK = "images/blank.gif";
var AmazonWidget = null;
var UnityWidget = null;
var OrdersWidget = null;
var UnityWeb = null;
var rowClicked = false;
var overlayVisible = false;
var homeVisible = false;
var actionMode = 'home';
var	resultsListDisplay = null;
	//Sarissa.clearChildNodes(document.getElementById('resultsPannel'));

var DIRURL = "http://directory.talis.com/ui"
//var DIRURL = "http://opacs.talis.com/silkwormdirectory/?css=true"
var MAPURL = "http://research.talis.com/2005/google-maps/skywalkmapGlobal.html"
//var MAPURL = "http://research.talis.com/2006/google-maps/skywalkmapGlobal2b.html"
//var ILLURL = "http://demov2-agent.auto-graphics.com/IllRequest/DoIllReq.asp?myses=39240&RequestType=Borrow&RequestFrom=sss&pv=A&cr=4813543&cuid=demov2&cusrvr=pandora";
var ILLURL = "ill-front.html";
var MONURL = "http://research.talis.com/2005/google-maps/hawkeyemap.html";
var ABOUTURL = "about-whisper-%%.html";
var PORTALURL = "front_%%.html";
var mapIframe = null;
var dirIframe = null;
var illIframe = null;
var monIframe = null;
var aboutIframe = null;
var portalIframe = null;
var poppedUp = false;
var myLocale = "en_GB";
var path2Dictionaries = "dictionaries/whisper_%%.xml";


function init(){
	/*if(!_SARISSA_IS_MOZ){
		alert("This prototype application is currently only \nconfigured to operate in a Firefox Browser.\n[www.getfirefox.com]");
		history.back();
	}*/
	addEvent(window, 'unload', EventCache.flush,false);
	NiftyCheck();
	xslMarc2DC = Sarissa.getDomDocument();
	xslMarc2DC.async = false;
	xslMarc2DC.load("rjwMARC21slim2OAIDC.xsl");
	resultsProc = new XSLTProcessor();
	resultsProc.importStylesheet(xslMarc2DC);
	resultsListDisplay = new DivList(document.getElementById('resultsPannel'),document.getElementById('infoPannel'),10);

	TalisIntl.init(document,null,path2Dictionaries);

	UnityWeb = new Unity(loadSelector);
	AmazonWidget = new AmazonPannel();
	UnityWidget = new UnityPannel();
	OrdersWidget = new OrdersPannel();
	addEvent(document.getElementById('rad1'),'click',changeFilter,false);
	addEvent(document.getElementById('rad2'),'click',changeFilter,false);
	addEvent(document.getElementById('rad3'),'click',changeFilter,false);
	addEvent(document.getElementById('libSel'),'change',changeFilter,false);
	addEvent(document.getElementById('languageType'),'change',changeLang,false);
	setUpTab(document.getElementById('actionTab1'),startDiscovery);
	setUpTab(document.getElementById('actionTab2'),startMap);
	setUpTab(document.getElementById('actionTab3'),startDirectory);
	setUpTab(document.getElementById('actionTab4'),startIll);
	setUpTab(document.getElementById('actionTab5'),startMon);
	
	//addEvent(document.getElementById('unity-Pannel'),'mouseover',showPopUp,false);
	addEvent(document.getElementById('about'),'click',showAbout,false);
	addEvent(document.getElementById('reviews'),'click',showAbout,false);
	addEvent(document.getElementById('myAccount'),'click',showAbout,false);
//	addEvent(document.getElementById('prefs'),'click',doPrefs,false);


//	suggestInit('searchForm','searchQuery','hints','searchType','http://172.30.3.68/richdatasuggestspike/suggest.aspx?',false);
	suggestInit('searchForm','searchQuery','hints','searchType','http://suggest.richdata.stable.silkworm.net/richdatasuggestspike/suggest.aspx?',false);
//http://suggest.richdata.stable.silkworm.net/richdatasuggestspike/suggest.aspx?term=fred&index=author
	goHome();
	initGoogleTargets();
	initAmazonTargets();
	Rounded("div.av-pannel-pan","all","#FFFFFF","#F7F7F7","smooth border #DDDDDD");
	Rounded("div#amazon-buy-link","all","#FFFFFF","#FFCC00","small border #DDDDDD");
	
}

function pageDn(){
	resultsListDisplay.pageDown();
}	
function pageUp(){
	resultsListDisplay.pageUp();
}	

function changeLang(){
	var sType = document.getElementById("languageType");
	var sIndex = sType.selectedIndex;
	TalisIntl.setLocale(sType.options[sIndex].value);
	TalisIntl.translate(document);
	setAWS(TalisIntl.get("AMAZON-SEARCH_URL"));
	goHome();
	reset();
	return false;
}


var closeimg =  '<img src="overlib/exit.gif" alt="Click to Close" ' +'width="12" height="11" border="0">';
function showPopUp(){
	if(!poppedUp){
		poppedUp = true;
//		overlib('Hello mum',STICKY, LEFT, CAPTION, "", CLOSECLICK,CLOSETEXT, "Close");
var popupmsg = "If you're a librarian and you think your library should be listed here, let us know by emailing platform.beta@talis.com. <BR/><BR/>Tell us where and how you export your holdings and we'll work on getting you listed."
			overlib(popupmsg,
			WIDTH, 250,
			HEIGHT, 100,
			STICKY,
			SHADOW,
			SHADOWOPACITY, 30,
			BGCOLOR, '#000000',
			FGCOLOR, '#FFCC00',
			CLOSETEXT,closeimg,
			LEFT, OFFSETX, 1,
			CLOSECLICK,
			CAPTIONFONTCLASS, 'popup-caption',
			CAPTION, "Talis Whisper");
			nd(15000); //Take it away after 30 secs

	}
}

function setUpTab(e,onclick){
	if(e == null){
		return;
	}
	addEvent(e,'click',onclick,false);
	addEvent(e,'mouseover',tabHighlight,false);
	addEvent(e,'mouseout',tabNormal,false);
}	

function goHome(){
	overlayDown();
	//homeUp();
	startPortal();
	overlayUp();
}

function startDiscovery(e){
	if(actionMode != 'discovery'){
		actionMode = 'discovery';
		homeDown();
		overlayDown();
	}else{
		reset();
	}
	document.getElementById('searchQuery').focus();
}
function startMap(){
	if(actionMode != 'map'){
		actionMode = 'map';
		document.getElementById('header-text').innerHTML = 'Location';
		if(mapIframe == null){
			mapIframe = document.createElement("iframe");
			mapIframe.setAttribute("id","mapIFrame");
			mapIframe.setAttribute("width","100%");
			mapIframe.setAttribute("height","100%");
			mapIframe.setAttribute("scrolling","no");
			mapIframe.setAttribute("class","overIframe");
		}	
		mapIframe.setAttribute("src",TalisIntl.addLocaleToURL(MAPURL));
		setOverIframe(mapIframe);
		homeDown();
		overlayUp();
	}
}
function startDirectory(){
	if(actionMode != 'directory'){
		actionMode = 'directory';
		document.getElementById('header-text').innerHTML = TalisIntl.translateText('DIRECTORY');
		if(dirIframe == null){
			dirIframe = document.createElement("iframe");
			dirIframe.setAttribute("id","dirIFrame");
			dirIframe.setAttribute("width","100%");
			dirIframe.setAttribute("height","100%");
			dirIframe.setAttribute("scrolling","yes");
			dirIframe.setAttribute("class","overIframe");
		}	
		dirIframe.setAttribute("src",TalisIntl.addLocaleToURL(DIRURL,'loc','-'));
		setOverIframe(dirIframe);
		homeDown();
		overlayUp();
	}
}
function startIll(){
	if(actionMode != 'Ill'){
		actionMode = 'Ill';
		document.getElementById('header-text').innerHTML = TalisIntl.translateText('INTERLEND');
		if(illIframe == null){
			illIframe = document.createElement("iframe");
			illIframe.setAttribute("id","dirIFrame");
			illIframe.setAttribute("width","100%");
			illIframe.setAttribute("height","100%");
			illIframe.setAttribute("scrolling","no");
			illIframe.setAttribute("class","overIframe");
		}	
		illIframe.setAttribute("src",TalisIntl.addLocaleToURL(ILLURL));
		setOverIframe(illIframe);
		homeDown();
		overlayUp();
	}
}

function startMon(){
	if(actionMode != 'Mon'){
		actionMode = 'Mon';
		document.getElementById('header-text').innerHTML = TalisIntl.translateText('MONITOR');
		if(monIframe == null){
			monIframe = document.createElement("iframe");
			monIframe.setAttribute("id","dirIFrame");
			monIframe.setAttribute("width","100%");
			monIframe.setAttribute("height","100%");
			monIframe.setAttribute("scrolling","no");
			monIframe.setAttribute("class","overIframe");
		}	
		monIframe.setAttribute("src",TalisIntl.addLocaleToURL(MONURL));
		setOverIframe(monIframe);
		homeDown();
		overlayUp();
	}
}
function startPortal(){
		actionMode = 'Portal';
		document.getElementById('header-text').innerHTML = TalisIntl.translateText('Portal');
		if(portalIframe == null){
			portalIframe = document.createElement("iframe");
			portalIframe.setAttribute("id","portalIFrame");
			portalIframe.setAttribute("width","100%");
			portalIframe.setAttribute("height","100%");
			portalIframe.setAttribute("scrolling","no");
			portalIframe.setAttribute("class","overIframe");
		}	
		portalIframe.setAttribute("src",TalisIntl.stringSub(PORTALURL));
		setOverIframe(portalIframe);
		homeDown();
		overlayUp();
}
function showAbout(){
	if(actionMode != 'About'){
		actionMode = 'About';
		document.getElementById('header-text').innerHTML = TalisIntl.translateText('ABOUT');
		if(aboutIframe == null){
			aboutIframe = document.createElement("iframe");
			aboutIframe.setAttribute("id","aboutIFrame");
			aboutIframe.setAttribute("width","100%");
			aboutIframe.setAttribute("height","100%");
			aboutIframe.setAttribute("scrolling","no");
			aboutIframe.setAttribute("class","overIframe");
		}	
		aboutIframe.setAttribute("src",TalisIntl.stringSub(ABOUTURL));
		setOverIframe(aboutIframe);
		homeDown();
		overlayUp();
	}
}

function homeUp(){
	if(!homeVisible){
		homeVisible = true;
		document.getElementById('homePage').className = 'home-page';
		document.getElementById('opacPannel').className = 'hidden-pannel';
		actionMode = 'home';
	}
}
function homeDown(){
	if(homeVisible){
		homeVisible = false;
		document.getElementById('homePage').className = 'hidden-pannel';
		document.getElementById('opacPannel').className = 'opac-pannel';
	}
}
function overlayUp(){
	if(!overlayVisible){
		overlayVisible = true;
		document.getElementById('overlay').className = 'overlay-pannel';
		document.getElementById('opacPannel').className = 'hidden-pannel';
	}
}
function overlayDown(){
	if(overlayVisible){
		overlayVisible = false;
		document.getElementById('overlay').className = 'hidden-pannel';
		document.getElementById('opacPannel').className = 'opac-pannel';
	}
}


function setOverIframe(frm){
	parentFrame = document.getElementById('overWindow');
	if(parentFrame.childNodes[0] != null){
		parentFrame.removeChild(parentFrame.childNodes[0]);
	}
	parentFrame.appendChild(frm);
	
}


function reset(){
	cClick();
	poppedUp = false;
	//document.getElementById('infoPannel').innerHTML = "";
	resultsListDisplay.clear();
	//Sarissa.clearChildNodes(document.getElementById('resultsPannel'));
	if(WorkOpen){
  		closeWork();
  	}

	searchResults = new Array();
	AmazonWidget.clear();	
	displayedResults = 0;
	rowClicked = false;
}

function loadSelector(uw){
	insts = uw.getInsts();
	keys = insts.keys();
	vals = insts.values();
	sel = document.getElementById("libSel");
	for(var i = 0;i < vals.length;i++){
		var name = vals[i];
		if(name.length > 36){
			name = name.substring(0,35) + "..";
		}
		sel[i] = new Option(name, keys[i]);
	}
}

function startSearch(){
	reset();
	loadcode(document.getElementById('searchQuery').value);
	document.getElementById('searchQuery').value = "";
}

function loadcode(query) {
	var sType = document.getElementById("searchType");
	var sIndex = sType.selectedIndex;

	if(sType.options[sIndex].value == 'keyword'){
		var words = query.split(" ");
		var formatted = "";
		for(var i = 0;i < words.length;i++){
			if(i > 0){
				formatted += " and ";
			}
			formatted += '"' + words[i] + '"';
		}
		query = formatted;
	}else	if(sType.options[sIndex].value == 'title'){
		query = 'title %3D "'+query+'"';
	}else if(sType.options[sIndex].value == 'author'){
		query = 'author %3D "'+query+'"';
	}else if(sType.options[sIndex].value == 'isbn'){
		query = 'bath.isbn %3D "'+query+'"';
	}
//alert(query);
	loadCodeFormatted(query);
}
function loadCodeFormatted(query){
	var start = searchResults.length + 1;
	var qty = 50;
	if(start == 1){
		qty = 10;
	}
//	var input = 'http://opacs.talis.com/silkwormdirectorydemo/lookup.aspx?token=AA240751QQu&sid=z3950:tb2';
	var input = 'http://biblite.silkworm.net/UnionM21?version=1.1&operation=searchRetrieve&recordSchema=dc';
	input += "&startRecord=";
	input += start;
	input += "&maximumRecords=";
	input += qty;
	input += "&query=";
	
	input += query;

  var req = new XMLHttpRequest();
  if (req) {
    req.onreadystatechange = function() {if(req.readyState == 4)loadResults(req.responseXML,query,qty);}
    ;
    req.open('GET', proxyUrl(encodeURI(input)));
    req.send(null);
  }
}


var pos = 0;

function loadResults(resXML,query,qty){
	if(resXML == null){
		return;
	}
//	var responseXML = resultsProc.transformToDocument(resXML);
responseXML = resXML;

//alert(""+Sarissa.serialize(responseXML));

	pos = 1;
	
	//var res = responseXML.getElementsByTagName("srw_dx:dc");
	var res = getElementsByTagName(responseXML,"info:srw/schema/1/dc-schema","srw_dc","dc");
//alert("Recs: "+res.length);
	for(var i =0;i<res.length;i++){
		result = loadResult(res[i],resultsListDisplay);
	}
	amzFireBatch();
	holdFireBatch();
	if(qty == res.length && searchResults.length < 1000){
		setTimeout(function() {loadCodeFormatted(query);},1); //Fire off next search batch in background
	}
	Sarissa.clearChildNodes(responseXML);// Clearup unneeded DOMs	
	Sarissa.clearChildNodes(resXML);	// Clearup unneeded DOMs	
}



function redisplay(){
	if(searchResults.length == 0){
		return;
	}
	clearSelectedResults();
	rowClicked = false;
	resultsListDisplay.clear();
	displayedResults = 0;
	for(var i = 0;i < searchResults.length;i++){
		r = searchResults[i];
		r.showHide();
	}
}

var searchResults = new Array();
var displayedResults = 0;

function loadResult(res,dispayList){
	var r = new Result(res,dispayList,searchResults.length);
	searchResults.push(r);
	//alert(r.getMarc().getIsbn()); 
	//r.getText().innerHTML= index +"<br/>"+r.getMarc().getIsbn(); 
	return r;
}



///////////////////////////// Result Class
function Result(resultXML,displayList,index){
	this._index = index;
	this.selected = false;
	this._XML = resultXML;
	this._DisplayList = displayList;
	this._Marc = new MarcRecord(resultXML);
	this._pannel = null;
	this._Holdings = null;
	this._Amazon = null;
	this._Orders = null;
	this._gotExtras = false;
	if(this._Marc.hasIsbn()){
		this._Holdings = new Holding(this._Marc.getIsbn(),this );
	}
	
}

Result.prototype.loadExtras = function(){
	if(!this._gotExtras){
		this._gotExtras = true;
		if(this._Marc.hasIsbn()){
			this._Amazon = new Amazon(this._Marc.getIsbn(),this);
			this._orders = new Ordering(this._Marc.getIsbn(),this);
		}
	}
}
	
	
Result.prototype.createPannel = function(){
	this._pannel = document.createElement('div');
	this._pannel.className = "result-pannel";
	this._pannel.setAttribute("resultIndex",this._index);
	this.createImage();
	this.createText();
}

Result.prototype.createText = function(){
	this._text = document.createElement('div');
	this._text.className = "result-text";
	this._pannel.appendChild(this._text);
	this._text.innerHTML = this.createTextDisplay();
}

Result.prototype.createTextDisplay = function(){
	ret = new StringBuffer();
	ret.append('<span class="result-line-one">');
	ret.append(this._Marc.getTitle());
	ret.append(" ");
	ret.append(this._Marc.getCreator());
	ret.append("</span><br/>");
	ret.append(this._Marc.getPublisher());
	ret.append(" ");
	ret.append(this._Marc.getDate());
	if(this._Marc.getIdentifier() != ""){
		ret.append("<br/>Isbn: ");
		ret.append(this._Marc.getIdentifier());
	}
	return ret.toString();
}
Result.prototype.getText = function(){
	return this._text;
}
Result.prototype.getAmazon = function(){
	return this._Amazon;
}
Result.prototype.getHoldings = function(){
	return this._Holdings;
}
Result.prototype.getOrders = function(){
	return this._orders;
}

Result.prototype.createImage = function(){
	this._image = document.createElement('img');
//	this._image.setAttribute("class","result-image");
	this._image.className = "result-image";
	this._image.alt = "";
	this._image.src = BLANK;
	this._pannel.appendChild(this._image);
}
Result.prototype.getImage = function(){
	return this._image;
}

Result.prototype.updateImage= function(src,alt){
	this._image.src = src;
	this._image.alt = alt;
}

Result.prototype.getPannel = function(){
	if(this._pannel == null){
		this.createPannel();
	}
	return this._pannel;
}

Result.prototype.getMarc = function(){
	return this._Marc;
}

Result.prototype.select = function(){
	selectResult(this);
}
Result.prototype.doSelect = function(){
	this.selected = true;
	this._pannel.setAttribute('class','result-pannel-sel');
	this._pannel.className = 'result-pannel-sel';
	this.widgetsUpdate();
}

Result.prototype.enable = function(){
	addEvent(this.getPannel(),'click',resultClick,false);
	addEvent(this.getPannel(),'mouseover',resultOver,false);
}

Result.prototype.disable = function(){
	EventCache.flushNodeEvents(this._pannel);
}


Result.prototype.widgetsUpdate = function(){
	UnityWidget.update(this);
	OrdersWidget.update(this);
	updateGoogleWidget(this);
	
}

Result.prototype.deselect = function(){
	deselectResult(this);
}

Result.prototype.doDeselect = function(){
	if(this.selected){
		this.selected = false;
		this._pannel.setAttribute('class','result-pannel');
		this._pannel.className = 'result-pannel';
	}
}

Result.prototype.update = function(obj){
	if(obj instanceof Holding){
		this.holdingUpdate(obj);
	}
	if(obj instanceof Ordering){
		this.ordersUpdate(obj);
	}
	if(obj instanceof Amazon){
		this.AmazonUpdate(obj);
	}
}

Result.prototype.holdingUpdate = function(hold){
	hold.getParent().showHide();
}
Result.prototype.ordersUpdate = function(ord){
		if(this.selected){
			OrdersWidget.update(this);	
		}
}
Result.prototype.showHide = function(){
	show = false;
	sel = getFilterSel();
	
	if(sel == 'all'){
		show = true;
	}else{
		hols = this.getHoldings();
		if(sel == 'all-holdings'){
			if(hols != null && hols.hasHoldings()){
				show = true;
			}
		}else{
			if(hols != null && hols.hasHoldings()){
				//Check individual
				var sType = document.getElementById("libSel");
				var sIndex = sType.selectedIndex;
				if(hols.hasHolding(sType.options[sIndex].value)){
					show = true;
				}
			}
		}
	}	
	if(show){
		this._DisplayList.append(this);
		if(displayedResults++ == 0){
			this.select();
		}	
	}
}

Result.prototype.AmazonUpdate = function(amazon){
	if(amazon.useful()){
		var im = amazon.getSmallImage();
		if(im != null && im.length > 0){
			this.updateImage(amazon.getSmallImage(),this._Marc.getTitle()+ " " + this._Marc.getCreator());
		}
		if(this.selected){
			AmazonWidget.update(amazon);	
		}
	}else{
		this._Amazon = null;
	}
}
var selectedSet = new Array();

function selectResult(result){
	clearSelectedResults();
	selectedSet.push(result);
	result.doSelect();
}

function deselectResult(result){
	result.doDeselect();
}

function clearSelectedResults(){
	while(selectedSet.length > 0){
		var res = selectedSet.pop();
		deselectResult(res);
	}
	clearGoogleWidget();
}
////////////////////////////// - Result Class

////////////////////////////// MarcRecord Object
function MarcRecord(marcXML){
	this._isbn = null;
	this._hasIsbn = false;
	this._identifier = "";
	this._creator = "";
	this._title = "";
	this._subject = "";
	this._publisher = "";
	this._date = "";
	this.getIsbnFromRecord(marcXML);
	this.loadTags(marcXML);
}

MarcRecord.prototype.getIsbnFromRecord = function(marcXML){
	var potIsbn = "";
	var nodes = marcXML.selectNodes("./*[local-name() = 'identifier']");
	if(nodes.length > 0 && nodes[0].firstChild != null){
		potIsbn = nodes[0].firstChild.nodeValue;
	}
	potIsbn = removeBadISBNChars(potIsbn);
	if(isValidIsbn(potIsbn)){
		this._hasIsbn = true;
		this._isbn = potIsbn;
	}
}
MarcRecord.prototype.loadTags = function(marcXML){
				var nodes = marcXML.selectNodes("./*[local-name() = 'title']");
				if(nodes.length > 0 && nodes[0].firstChild != null){
					this._title = nodes[0].firstChild.nodeValue;
				}
				nodes = marcXML.selectNodes("./*[local-name() = 'creator']");
				if(nodes.length > 0 && nodes[0].firstChild != null){
					this._creator = nodes[0].firstChild.nodeValue;
				}
				nodes = marcXML.selectNodes("./*[local-name() = 'subject']");
				if(nodes.length > 0 && nodes[0].firstChild != null){
					this._subject = nodes[0].firstChild.nodeValue;
				}
				nodes = marcXML.selectNodes("./*[local-name() = 'publisher']");
				if(nodes.length > 0 && nodes[0].firstChild != null){
					this._publisher = nodes[0].firstChild.nodeValue;
				}
				nodes = marcXML.selectNodes("./*[local-name() = 'date']");
				if(nodes.length > 0 && nodes[0].firstChild != null){
					this._date = nodes[0].firstChild.nodeValue;
				}
}

MarcRecord.prototype.getTagValue = function(marcXML,tag){
	node = marcXML.selectSingleNode(tag);
	if(node != null){
		return Sarissa.getText(node);
	}
	return "";
}
MarcRecord.prototype.getIsbn = function(){
	return this._isbn;
}
MarcRecord.prototype.hasIsbn = function(){
	return this._hasIsbn;
}
MarcRecord.prototype.getIdentifier = function(){
	return this._identifier;
}
MarcRecord.prototype.getTitle = function(){
	return this._title;
}
MarcRecord.prototype.getCreator = function(){
	return this._creator;
}
MarcRecord.prototype.getPublisher = function(){
	return this._publisher;
}
MarcRecord.prototype.getDate = function(){
	return this._date;
}
MarcRecord.prototype.getSubject = function(){
	return this._subject;
}

////////////////////////////// -  MarcRecord Object



////////////////////////////////////// AmazonPannel

function AmazonPannel(){
	pannel = document.getElementById("amazon-pannel");
	this._newSpan = document.getElementById("new-price");
	this._usedSpan = document.getElementById("used-price");
	this._img = document.getElementById("amazon-image");
	this._buy = document.getElementById("amazon-buy-link");
	addEvent(this._buy,'click',amazonBuyClick,false);
	this._current = null;
}

AmazonPannel.prototype.update = function(amz){
	this._newSpan.innerHTML=amz.getNewPrice();
	this._usedSpan.innerHTML=amz.getUsedPrice();
	var img = amz.getMediumImage();
	if(img == null || img.length == 0){
		img = BLANK;
	}
	this._img.src = img
	this._img.alt = "";
	//this._buy.href = amz.getURL();
	this._current = amz;
}	
AmazonPannel.prototype.clear = function(){
	this._newSpan.innerHTML="";
	this._usedSpan.innerHTML="";
	this._img.src = BLANK;
	this._img.alt = "";
	this._buy.href = "";
	this._current = null;
}
AmazonPannel.prototype.getCurrent = function(){
	return this._current;
}

function amazonBuyClick(){
	if(AmazonWidget.getCurrent() != null){
		doWork("AmazonBuy",AmazonWidget);
	}
}	

////////////////////////////////////// - AmazonPannel	

////////////////////////////////////// OrdersPannel

function OrdersPannel (){
	var cols = new Array();
	cols[0] = "";
	for(var i = 1;i <= 12;i++){
		cols[i] = TalisIntl.translateText("MONTH_LETTER_"+i);
	}
	this._cols = cols;
	this._pannel = document.getElementById("orders-display");
}

OrdersPannel.prototype.clear = function(){
	Sarissa.clearChildNodes(this._pannel);
}
OrdersPannel.prototype.update = function(result){
	try{
		this._result = result;
		this._orders = result.getOrders().getOrds();
	}catch(e){
		return;
	}
	this.clear();
	if(this._orders.length == 0){
		return;
	}
	var bod = this.createTable();
	var curyear = "";
	var maxcol = 0;
	var row = null;
	for(var i = 0;i < this._orders.length;i++){
		var nbs = "&nbsp;";
		var line = this._orders[i];
		var year = line.getYear();
		var month = line.getMonth();
		var count = line.getCount();
		var td;
		if(year != curyear){
				if(row != null){//Finish off previous row
					while(++maxcol <= 12){
						td = document.createElement('td');
						td.className = 'orders-display-table-count';
						row.appendChild(td);
						td.appendChild(this.createBar(0));
					}
			}
			curyear = year;
			row = document.createElement('tr');
			bod.appendChild(row);
			maxcol = 0;
			td = document.createElement('td');
			td.className = 'orders-display-table-year';
			td.appendChild(document.createTextNode(year));
			row.appendChild(td);
		}
		while(++maxcol < month){
				td = document.createElement('td');
				td.className = 'orders-display-table-count';
				row.appendChild(td);
				td.appendChild(this.createBar(0));
		}
		td = document.createElement('td');
		td.className = 'orders-display-table-count';
		row.appendChild(td);
		td.appendChild(this.createBar(count));
	}
	if(row != null){//Finish off last row
		while(++maxcol <= 12){
			td = document.createElement('td');
			td.className = 'orders-display-table-count';
			row.appendChild(td);
			td.appendChild(this.createBar(0));
		}
	}
}

OrdersPannel.prototype.createBar = function(hgt){
		var bar = document.createElement('img');
		bar.className = 'orders-display-table-bar';
		bar.src = 'images/bar.gif'
		bar.height = (2 * hgt);
	return bar;
}

OrdersPannel.prototype.createTable = function(){
	var tab = document.createElement('table');
	this._pannel.appendChild(tab);
	tab.className = 'orders-display-table';
	var bod = document.createElement('tbody');
	tab.appendChild(bod);
	var hdr = document.createElement('tr');
	bod.appendChild(hdr);
	for(var i = 0;i < this._cols.length;i++){
		var cell = document.createElement('th');
		if(i == 0){
			cell.className = 'orders-display-table-year';
		}else{
			cell.className = 'orders-display-table-hdr';
		}
		cell.appendChild(document.createTextNode(this._cols[i]));
		hdr.appendChild(cell);
	}
	return bod;
}
	


		
////////////////////////////////////// - OrdersPannel

////////////////////////////////////// UnityPannel
function UnityPannel(){
	pannel = document.getElementById("unity-pannel");
	this._count = document.getElementById("unity-count");
	this._countStart = document.getElementById("unity-count-label");
	this._countEnd = document.getElementById("unity-count-label-end");
	this._list = document.getElementById("libraries-list");
	this._result = null;
	this._inst = null;
	this._panCache = new Array();
}

UnityPannel.prototype.update = function(result){
	this.clear();
	this._result = result;
	var h = result.getHoldings();
	if(h == null){
		return;
	}
	var insts = h.getInsts();
	this._countStart.innerHTML='<span tal:dict="AVAILABLE_AT">Available at </span>&nbsp;';
	this._count.innerHTML=insts.length ;
	if(insts.length == 1){
		this._countEnd.innerHTML='&nbsp;<span tal:dict="LIBRARY">Library</span>';
	}else{
		this._countEnd.innerHTML='&nbsp;<span tal:dict="LIBRARIES">Libraries</span>';
	}
	
	var table = document.createElement("table");
	table.setAttribute("id","libs-list-table");
	table.setAttribute("border","0");
	table.setAttribute("cellspacing","0");
	table.setAttribute("cellpadding","0");
	var body = document.createElement("tbody");
	table.appendChild(body);
	for(var i = 0; i<insts.length;i++){
		var tr = document.createElement("tr");
		body.appendChild(tr);
		var cell = document.createElement("td");
		tr.appendChild(cell);
		var d = document.createElement('div');
	//	d.setAttribute("class","institution-list");
		d.className = "institution-list";
		d.setAttribute("instCode",insts[i].getCode());
		addEvent(d,'click',this.clickLib,false);
		addEvent(d,'mouseover',this.selLib,false);
		addEvent(d,'mouseout',this.unselLib,false);
		d.appendChild(document.createTextNode(insts[i].getName()));
		this._panCache.push(d);
		cell.appendChild(d);
	}
	this._list.appendChild(table);
}

UnityPannel.prototype.getResult = function(){
	return this._result;
}
UnityPannel.prototype.getSelectedInst = function(){
	return this._inst;
}
UnityPannel.prototype.getSelectedInstName = function(){
	return UnityWeb.getInstFromCode(this._inst);
}

UnityPannel.prototype.clickLib = function(e){
	if(this != UnityWidget){
		UnityWidget.clickLib(e);
		return;
	}
  var el;
  if (window.event && window.event.srcElement){
    el = window.event.srcElement;
  }
  if (e && e.target){
    el = e.target;
  }
  if (!el){
    return;
  }
  while (el.getAttribute("instCode") == null &&
      el.nodeName.toLowerCase() != 'body'){
    el = el.parentNode;
  }
  if(el.nodeName.toLowerCase() == 'body'){
  	return;
  }
  all = document.getElementById("libs-list-table").getElementsByTagName("div");
  for(var i = 0;i<all.length;i++){
  	d = all[i];
  	if(d.className == "institution-list-sel"){
  		d.className = "institution-list";
  	}
  }
  
  el.className = "institution-list-sel";
  this._inst = el.getAttribute("instCode");
  var actf = document.getElementById("libActionForm");
  var action = null;
  for(var i=0;i<actf.libact.length;i++){
	if(actf.libact[i].checked){
		action = actf.libact[i].value;
	}
  }
  if(action == "opac"){
  	doWork('goOPAC',this);
  }else{
  	doWork('goUnity',this);
  }
  
}
UnityPannel.prototype.selLib = function(e){
  var el;
  if (window.event && window.event.srcElement){
    el = window.event.srcElement;
  }
  if (e && e.target){
    el = e.target;
  }
  if (!el){
    return;
  }
  while (el.getAttribute("instCode") == null &&
      el.nodeName.toLowerCase() != 'body'){
    el = el.parentNode;
  }
  if(el.nodeName.toLowerCase() == 'body'){
  	return;
  }
  all = document.getElementById("libs-list-table").getElementsByTagName("div");
  for(var i = 0;i<all.length;i++){
  	d = all[i];
  	if(d.className == "institution-list-sel"){
  		d.className = "institution-list";
   	}
  }
  
  el.className = "institution-list-sel";
}
UnityPannel.prototype.unselLib = function(e){
  var el;
  if (window.event && window.event.srcElement){
    el = window.event.srcElement;
  }
  if (e && e.target){
    el = e.target;
  }
  if (!el){
    return;
  }
  while (el.getAttribute("instCode") == null &&
      el.nodeName.toLowerCase() != 'body'){
    el = el.parentNode;
  }
  if(el.nodeName.toLowerCase() == 'body'){
  	return;
  }
  
  el.className = "institution-list";
}


	
UnityPannel.prototype.clear = function(){
	Sarissa.clearChildNodes(this._list);
	this._countStart.innerHTML="";
	this._count.innerHTML="";
	this._countEnd.innerHTML="";
	for(var i = 0;i < this._panCache.length;i++){
		EventCache.flushNodeEvents(this._panCache[i]);
	}
	this._panCache = new Array();

}
////////////////////////////////////// - UnityPannel
////////////////////////////////////// Unity

var UnityInstitutions = null;
function Unity(callback){
	this.init(callback);
	//setTimeout("alert('Insts: '+UnityInstitutions.size())",5000);
}
Unity.prototype.getInsts = function(callback){
	return UnityInstitutions;
}	
Unity.prototype.init = function(callback){
	if(UnityInstitutions == null){
		UnityInstitutions = new Hashtable();
		var ainput = "http://research.talis.com/2005/unityweb/institutions.php";
   		var areq = new XMLHttpRequest();
  		var thisClass = this;
  		if (areq) {
    			areq.onreadystatechange = function() {if(areq.readyState == 4)thisClass.loadResult(areq,callback);}
    			;
    			areq.open('GET', ainput,true);
    			areq.send(null);
			}
	}
}
	
Unity.prototype.getInstFromCode = function(code){
	return	UnityInstitutions.get(code);
}

Unity.prototype.loadResult = function(req,callback){
	resDom = req.responseXML;
	insts = resDom.getElementsByTagName('institution');
	for(var i=0;i<insts.length;i++){
		UnityInstitutions.put(insts[i].getAttribute('instCode'),insts[i].getAttribute('name'));
	}
	callback(this);	
}
////////////////////////////////////// - Unity	
function tabHighlight(e){
  var el;
  if (window.event && window.event.srcElement){
    el = window.event.srcElement;
  }
  if (e && e.target){
    el = e.target;
  }
  if (!el){
    return;
  }
  while ((el.className == null || el.className != "tabcell") &&
      el.nodeName.toLowerCase() != 'body'){
    el = el.parentNode;
  }
  if(el.nodeName.toLowerCase() == 'body'){
  	return;
  }
  
  el.className = "tabcell-sel";
  
}
function tabNormal(e){
  var el;
  if (window.event && window.event.srcElement){
    el = window.event.srcElement;
  }
  if (e && e.target){
    el = e.target;
  }
  if (!el){
    return;
  }
  while ((el.className == null || el.className != "tabcell-sel") &&
      el.nodeName.toLowerCase() != 'body'){
    el = el.parentNode;
  }
  if(el.nodeName.toLowerCase() == 'body'){
  	return;
  }
  
  el.className = "tabcell";
  
}

/////////////////////////////////// doWork
var WorkOpen = false;
var Task = null;
function doWork(task, source){
  var actionURL = createActUrl(task, source);
  if(actionURL.indexOf("http://") != -1){
	doWin(actionURL);
	return;
  }

  if(WorkOpen){
  	closeWork();
  }
  WorkOpen = true;
  var rp = document.getElementById("resultsPannel");
  var wp = document.getElementById("workPannel");
  
  rp.setAttribute("class","hidden-pannel");
  rp.className = "hidden-pannel";
  wp.setAttribute("class","work-pannel");
  wp.className = "work-pannel";
  addEvent(document.getElementById('workHeaderClose'),'click',closeWork,false);
  
  doTask(actionURL, wp);
  
 }

function closeWork(e){
  closeTask();
  var rp = document.getElementById("resultsPannel");
  var wp = document.getElementById("workPannel");
  wp.setAttribute("class","hidden-pannel");
  wp.className = "hidden-pannel";
  rp.setAttribute("class","results-pannel");
  rp.className = "results-pannel";
  Sarissa.clearChildNodes(document.getElementById("workBody"));
  WorkOpen = false;
}

function doTask(actionURL, workPannel){
	//alert(actionURL);
	wp = document.getElementById("workBody");
	ifr = document.createElement("iframe");
	wp.appendChild(ifr);
	ifr.setAttribute("id","workFrame");
	ifr.setAttribute("width","99%");
	ifr.setAttribute("height","100%");
	ifr.setAttribute("scrolling","yes");
	ifr.setAttribute("src",actionURL);
}

function closeTask(){
	if(Task == "goUnity"){
		//unityLogoff();	
	}
}
function createActUrl(task, source){
//	alert("task: "+task);
	if(task == "goOPAC"){
		var result = source.getResult();
		var marc = result.getMarc();
		isbn = marc.getIsbn();
		inst = source.getSelectedInst();
		//alert(isbn + " from "+inst);
//		return "http://opacs.talis.com/silkwormdirectory/lookup.aspx?token=AA240751QQu&sid=redirect:"+inst+".UnityWeb&isbn="+isbn;

//http://api.talis.com/1/node/items/1.swdefault/bib?title=abbey
		return "http://api.talis.com/1/node/items/"+inst+".inst/bib?isbn="+isbn;
	}
	if(task == "goUnity"){
		var result = source.getResult();
		var marc = result.getMarc();
		var ret = "ill-front.html?";
		ret += "&Lender=" + source.getSelectedInstName();
		ret += "&ISBN=" + marc.getIsbn();
		ret += "&Title=" + marc.getTitle();
		ret += "&Author=" + marc.getCreator();
		ret += "&Date=" + marc.getDate();
		ret += "&Publisher=" + marc.getPublisher();

//document.getElementById('infoPannel').innerHTML = encodeURI(ret);
		return encodeURI(TalisIntl.addLocaleToURL(ret));
		
	}
	
	if(task == "AmazonBuy"){
		//alert(source.getCurrent().getURL());
		return source.getCurrent().getURL();
	}

	return "http://www.talis.com";
}

var UnitySessionID;
var UnityUrlRoot = "http://172.30.3.32:20002/WebZ/";
function buildUnityURL(source){
	setUnitySessionID();
	Uurl = UnityUrlRoot + "sessionid=";
	Uurl += "&MRItemAuthor=Nathan, Richard P.&MRItemTitle=Reagan and the States&uwillsubmit.x=1&rotaLoc-NW115=1";
	Uurl += "&MRItemIsbn="+source.getResult().getMarc().getIsbn();
}

function setUnitySessionID(){
var input = UnityUrlRoot + "UwAuthorize?sessionid=0&next=startscreen&bad=UnityWeb/error/authofail.html&autho=WebZUser&password=dev";
 var req = new XMLHttpRequest();
  if (req) {
    req.onreadystatechange = function() {if(req.readyState == 4)loadUnitySessionID(req.responseText);}
    ;
    req.open('GET',proxyUrl(input) );
    req.send(null);
  }
}

function unityLogoff(){
var input = UnityUrlRoot + "UwLogOut?sessionid=" + UnitySessionID;
 var req = new XMLHttpRequest();
  if (req) {
    req.onreadystatechange = function() {false;}
    ;
    req.open('GET',proxyUrl(input) );
    req.send(null);
  }
}

var regUnitSess = /sessionid=([\d\-]*)/;
function loadUnitySessionID(text){
	regUnitSess.test(text+" ");
	UnitySessionID = RegExp.$1;
}
	

	
	

/////////////////////////////////// - doWork
function getFilterSel(){
	var sf = document.getElementById("searchForm");
	for(var i=0;i<sf.filter.length;i++){
		if(sf.filter[i].checked){
			return sf.filter[i].value;
		}
	}
	return "";
}

function changeFilter(e){
	redisplay();
}	



function resultClick(e) {
	resultSelect(e,true);
}

function resultOver(e) {
	if(!rowClicked){
		resultSelect(e,false);
	}else{
		endEvent(e);
	}
}

var lastClickedResult = null;
function resultSelect(e,click) {

  result = getSourceResult(e);
  if(result == null){
  	return;
  }
  
  if(click){
  	if(result == lastClickedResult){
  		lastClickedResult = null;
  		rowClicked = false;
  	}else{
  		lastClickedResult = result;
  		rowClicked = true;;
  	}
  }	
  selectResult(result);
  amaz = result.getAmazon();
  if(amaz == null){
  	AmazonWidget.clear();
  }else{
    	AmazonWidget.update(amaz);
  }
  UnityWidget.update(result);

  return endEvent(e);
}

function resultDeselect(e) {

  result = getSourceResult(e);
  if(result == null){
  	return;
  }
  
  result.deselect();

  return endEvent(e);
}

function getSourceResult(e) {
  var el;
  if (window.event && window.event.srcElement){
    el = window.event.srcElement;
  }
  if (e && e.target){
    el = e.target;
  }
  if (!el){
    return null;
  }
  while (el.getAttribute("resultindex") == null &&
      el.nodeName.toLowerCase() != 'body'){
    el = el.parentNode;
  }
  if(el.nodeName.toLowerCase() == 'body'){
  	return null;
  }
  
  index = el.getAttribute("resultindex");
  if(index == null){
  	return null;
  }
  
  result = searchResults[index];
  
  return result;
}
function endEvent(e){
    if (window.event) {
      window.event.cancelBubble = true;
      window.event.returnValue = false;
    }
    if (e && e.stopPropagation && e.preventDefault) {
      e.stopPropagation();
      e.preventDefault();
  }
}

var myHost = null;
function getMyHost(){
	if(myHost == null){
		myHost = location.protocol + "//";
		myHost += location.host;
		if(location.port.length > 0){
			myHost += ":" + location.port;
		}
	}
	return myHost;
}

function updateGoogleWidget(res){
	setGoogleWidget(res.getMarc().getIsbn());
}

function clearGoogleWidget(){
	setGoogleWidget("");
}
function setGoogleWidget(val){
	if(val == null){
		val = "";
	}
	imp = document.getElementById("google-input");
	imp.value = val;
}

function initGoogleTargets(){
		TalisIntl.put("GOOGLE-SEARCH_URL","http://www.google.co.uk/search?","en_GB");
		TalisIntl.put("GOOGLE-SEARCH_URL","http://www.google.com/search?","en_US");
		TalisIntl.put("GOOGLE-SEARCH_URL","http://www.google.fr/search?","fr_FR");
		TalisIntl.put("GOOGLE-SEARCH_URL","http://www.google.de/search?","de_DE");
		TalisIntl.put("GOOGLE-SEARCH_URL","http://www.google.es/search?","es_ES");
		TalisIntl.put("GOOGLE-SEARCH_URL","http://www.google.co.jp/search?","ja_JP");
		TalisIntl.put("GOOGLE-SEARCH_URL","http://www.google.com/search?hl=zh-CN&","zh_CN");
}
function initAmazonTargets(){
		TalisIntl.put("AMAZON-SEARCH_URL","http://webservices.amazon.co.uk/onca/xml?","en_GB");
		TalisIntl.put("AMAZON-SEARCH_URL","http://webservices.amazon.com/onca/xml?","en_US");
		TalisIntl.put("AMAZON-SEARCH_URL","http://webservices.amazon.fr/onca/xml?","fr_FR");
		TalisIntl.put("AMAZON-SEARCH_URL","http://webservices.amazon.de/onca/xml?","de_DE");
		TalisIntl.put("AMAZON-SEARCH_URL","http://webservices.amazon.com/onca/xml?","es_ES");
		TalisIntl.put("AMAZON-SEARCH_URL","http://webservices.amazon.co.jp/onca/xml?","ja_JP");
		TalisIntl.put("AMAZON-SEARCH_URL","http://webservices.amazon.com/onca/xml?","zh_CN");
		setAWS(TalisIntl.get("AMAZON-SEARCH_URL"));

}
function doGoogleWin(){
	 var s = TalisIntl.get("GOOGLE-SEARCH_URL");
	 s += "q=" + document.getElementById('google-input').value;
	 doWin(s);
}
function doWin(s){
	 win = window.open(s,'_linkWindow','width=800,height=600,toolbar,scrollbars,location');
	 win.focus();
}



function proxyUrl(target){
	ret = getMyHost()+"/2005/simple-proxy/get?uri="+encodeURIComponent(target);
	debug(ret);
	return ret;
}
function debugProxyUrl(target){
	ret = getMyHost()+"/2005/simple-proxy/get?debug=true&uri="+encodeURIComponent(target);
	alert("encoded: "+ret);
	debug(ret);
	return ret;
}

function StringBuffer(){
	this.__strings__ = new Array();
}
StringBuffer.prototype.append = function (str){
	this.__strings__.push(str);
}
StringBuffer.prototype.appendln = function (str){
	this.__strings__.push(str+'\n');
}
StringBuffer.prototype.toString = function (){
	return this.__strings__.join("");
}

function debug(text){
	//document.getElementById('debugPannel').innerHTML = text;
}

////////////////////ISBN stuff
var regISBN = /([^\S]?\d{7,9}[\dX][^\S]?)/g
function extractIsbn(text){
	ret = null;
	if(regISBN.test(text+" ")){
		regISBN.lastIndex = 0;
	        for (var match = null, lastLastIndex = 0; (match = regISBN.exec(text)); ) {
	            	//alert("GOTONE!!!!!!!!!"+ match[0]);
	        	if(isValidIsbn(match[0])){
	            			
	            		ret = match[0];
	            	}
	            	lastLastIndex = regISBN.lastIndex;
	        }
	}
	return ret;
}
function isValidIsbn (InString)  {
	var r1 = /^\s/
	InString = InString.replace(r1,"");
   if(InString.length==0)
      {
      return (false);}
   var RefString="1234567890- Xx";
   var NewString=""
   var holder = 0
   for (Count=0; Count < InString.length; Count++)  {
      TempChar= InString.substring (Count, Count+1);
      if (RefString.indexOf (TempChar, 0)==-1)
         {
         return (false);}
      if ((Count < 9) && (TempChar=="X"))
         {
         return (false);}
      if ((Count < 9) && (TempChar=="x"))
         {
         return (false);}
      if ((RefString.indexOf (TempChar, 0)==10) ||
         (RefString.indexOf (TempChar, 0)==11))
         NewString=NewString;
      else (NewString=NewString+TempChar);
      }
      if (NewString.length!=10)
	 {
         return (false);}
      if (NewString.length==10)
	 var StartNum=10
	 var CheckNum = 0
	 for (Count=0; Count < NewString.length; Count++)
	 {
	 TempChar= NewString.substring (Count, Count+1);
         if ((TempChar=="X")||(TempChar=="x"))
	    TempChar=10;
         holder = holder+(TempChar*StartNum);
         StartNum=StartNum-1;
	 }
	 CheckNum = holder%11;
	 if (CheckNum==0)
	    return (true);
	 else 
	    return (false);
}	

///////////////////	
function addEvent(elm, evType, fn, useCapture) {
  // cross-browser event handling for IE5+, NS6 and Mozilla 
  // By Scott Andrew 
  if (elm.addEventListener) { 
    elm.addEventListener(evType, fn, useCapture); 
    return true; 
  } else if (elm.attachEvent) { 
    var r = elm.attachEvent('on' + evType, fn);
    EventCache.add(elm, evType, fn); 
    return r; 
  } else {
    elm['on' + evType] = fn;
  }
}


    function getValOrNull(loc,ns,prefix,tag){
     var ret = getNodeOrNull(loc,ns,prefix,tag);
     if(ret != null && ret.firstChild != null){
      return ret.firstChild.nodeValue;
     }
     return "";
  }
    function getAttOrNull(loc,ns,prefix,tag,attNs,attPrefix,attName){
     var nd = getNodeOrNull(loc,ns,prefix,tag);
     if(nd != null){
      var ret = getAttribute(nd,attNs,attPrefix,attName);
      return ret;
     }
     return "";
  }
       
    function getNodeOrNull(loc,ns,prefix,tag){
     var ret = getElementsByTagName(loc,ns,prefix,tag);
     if(ret != null){
      ret = ret[0];
     }
     return ret;
 }
 
 function getElementsByTagName(loc,ns,prefix,tag){
     var ret;
     
     //alert(loc+","+ns+","+prefix+","+tag);
     
     if(ns != null && ns.length > 0){
      if(_SARISSA_IS_IE){
      	if(prefix.length > 0){
      		tag = prefix + ":" + tag;
      	}
       ret = loc.getElementsByTagName(tag);
      }else{
       ret = loc.getElementsByTagNameNS(ns,tag);
      }
    }else{
      ret = loc.getElementsByTagName(tag);
     }
     return ret;
 }
 
 function getAttribute(loc,ns,prefix,name){
     var ret;
     if(ns != null && ns.length > 0){
      if(_SARISSA_IS_IE){
       ret = loc.getAttribute(prefix + ":" + name);
      }else{
       ret = loc.getAttributeNS(ns,name);
      }
    }else{
      ret = loc.getAttribute(name);
     }
     return ret;
 }
 
 function removeBadISBNChars( isbn ){
    if(isbn == null){
    	return null;
    }
    var filteredValues = "0123456789Xx";     // valid characters, everything else Is invalid.
    var returnString = "";
    for (var i = 0; i < isbn.length; i++)
    {  // Search through string and append unfiltered values to returnString.
        var c = isbn.charAt(i);
        if (filteredValues.indexOf(c) != -1) returnString += c;
    }
    return returnString;
}

function isValidIsbn (InString)  {
	if(InString == null){
		return "";
	}
 var r1 = /^\s/
 InString = InString.replace(r1,"");
   if(InString.length==0)
      {
      return (false);}
   var RefString="1234567890- Xx";
   var NewString=""
   var holder = 0
   for (Count=0; Count < InString.length; Count++)  {
      TempChar= InString.substring (Count, Count+1);
      if (RefString.indexOf (TempChar, 0)==-1)
         {
         return (false);}
      if ((Count < 9) && (TempChar=="X"))
         {
         return (false);}
      if ((Count < 9) && (TempChar=="x"))
         {
         return (false);}
      if ((RefString.indexOf (TempChar, 0)==10) ||
         (RefString.indexOf (TempChar, 0)==11))
         NewString=NewString;
      else (NewString=NewString+TempChar);
      }
      if (NewString.length!=10)
  {
         return (false);}
      if (NewString.length==10)
  var StartNum=10
  var CheckNum = 0
  for (Count=0; Count < NewString.length; Count++)
  {
  TempChar= NewString.substring (Count, Count+1);
         if ((TempChar=="X")||(TempChar=="x"))
     TempChar=10;
         holder = holder+(TempChar*StartNum);
         StartNum=StartNum-1;
  }
  CheckNum = holder%11;
  if (CheckNum==0)
     return (true);
  else 
     return (false);
}