function PopupWindow(theURL,winName,features) {
	window.open(theURL,winName,features);
}
function bodyElement(){
	return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}
function getCookie(name){
	if (document.cookie.length>0){
  		start=document.cookie.indexOf(name + "=")
  		if (start!=-1){ 
    		start=start + name.length+1 
    		end=document.cookie.indexOf(";",start)
    		if (end==-1) {
    			end=document.cookie.length
    		}
    		return unescape(document.cookie.substring(start,end))
    	} 
  	}
	return ""
}
function toggleCustomRadio(formEle, checkedEle) {
	var radios = formEle.elements[checkedEle.name];
	for(var i=0; i<radios.length; i++){
		radios[i].checked=(radios[i].id == checkedEle.id ? true:false);
		$(radios[i].id+"Label").className=(radios[i].checked? 'radioon' :'radiooff');
	}
}
function positionPopup(parentEle, popupEle, relativeLeft, relativeTop) {
	if(parentEle && popupEle) {
	
		if(parentEle.style.display=='none') {
			parentEle.style.display='block';
			var pos=Position.cumulativeOffset(parentEle);
			parentEle.style.display='none';
		} else {
			var pos=Position.cumulativeOffset(parentEle);
		}
		var left=(pos[0]+relativeLeft)+"px";
		var top=(pos[1]+relativeTop)+"px";
		popupEle.style.left=left;
		popupEle.style.top=top;
		
	
		
		if($(popupEle.id+"IFrame")) {
			var iFrame=$(popupEle.id+"IFrame");
			iFrame.style.left=left;
			iFrame.style.top=top;
		}
	}
}
function buildPopupIFrame(popupEle, allBrowsers) {
	if( (navigator.appName=="Microsoft Internet Explorer" || allBrowsers) && popupEle && !$(popupEle.id+"IFrame")) {
		var iFrame = document.createElement("iframe");
		iFrame.id=popupEle.id+"IFrame";
		iFrame.src="blank.html";
		iFrame.style.border="1px solid red";	
		iFrame.style.display="none";
		iFrame.style.position="absolute";
		iFrame.style.filter='progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';
		document.body.appendChild(iFrame);
	}
}
function togglePopup(popupEle, newState, zIndex) {
	if(popupEle) {		
		if(newState) {
			newState = (newState=="block"?"block":"none");
		}else {
			newState = (popupEle.style.display == "block" ? "none" : "block");
		}
		popupEle.style.display=newState;	
		
		var popupIFrame = $(popupEle.id+"IFrame");
		if(popupIFrame) {
			if(!popupIFrame.style.width) {
				popupIFrame.style.width=popupEle.offsetWidth+"px";
				popupIFrame.style.height=popupEle.offsetHeight+"px";
				if(!zIndex) {
					zIndex = 1500;
				}
				popupEle.style.zIndex=zIndex;
				popupIFrame.style.zIndex=popupEle.style.zIndex-1;
			}
			popupIFrame.style.display=newState;
		}
	}
}
function fixSafariEncode(s){
	var fixedString = s;
	try {
		fixedString = decodeURI(escape(fixedString));
	}
	catch(err){
	
	}
	return fixedString;
}
document.observe("dom:loaded", function() {
	if ($('acctDetailsContent')) {
		$('acctDetailsSelector').update($('acctDetailsContent').innerHTML);
		$('acctDetailsTemp').remove();
		buildPopupIFrame($("acctDetailsSelector"), true);
		
		$('acctDetails').onmouseover = $('acctDetailsSelector').onmouseover;
		$('acctDetails').onmouseout = $('acctDetailsSelector').onmouseout;
		
		$('acctDetailsSelector').hide();
		$('acctDetailsSelector').style.left = getRealOffsetLeft($('acctDetails'))+'px';
		$('acctDetailsSelector').style.top = $('acctDetails').offsetTop + $('acctDetails').getHeight() +'px';
		
		if ($('acctDetailsSelectorIFrame')) {
			$('acctDetailsSelectorIFrame').style.top = $('acctDetails').offsetTop + $('acctDetails').getHeight() +'px';
			$('acctDetailsSelectorIFrame').style.width = $('acctDetailsSelector').getWidth()+'px';
			$('acctDetailsSelectorIFrame').style.height = $('acctDetailsSelector').getHeight()+'px';
			$('acctDetailsSelectorIFrame').style.zIndex = $('acctDetailsSelector').zIndex -1;
		}
	}
	
	
	if($("ControlPanelToggle") && !$("controlPanelLocation1")) {
		$("ControlPanelToggle").observe("click", ControlPanel.lazyLoadControlPanel);
	}
});
var ControlPanel = {
	lazyLoadControlPanel: function() {
	
		$("ControlPanelToggle").stopObserving("click");
		LazyLoad.loadJS("/js/ajax_controlpanel.js", function() {
			ControlPanelAjax.init();
		});
	}
};
function uv_updateCreditPlan(userID, updateCP) {
	if($("uv_defaultPlan")) {
		var newVal = $F("uv_defaultPlan");
		
	
		if(updateCP && $("CONTROL_SETTING_DEFAULT_CREDIT_TYPE")) {
			$("CONTROL_SETTING_DEFAULT_CREDIT_TYPE").value = newVal;
		}
		
	
		var URL = "ajax_class_creator.php?ajax_action=save&ajax_class=controlpanel&setting=CONTROL_SETTING_DEFAULT_CREDIT_TYPE&value="+newVal+"&userID="+userID;
		var myAjax =new Ajax.Request(URL, {method: 'get'});	
	}
}
function getRealOffsetLeft(element) {
	var offset = 0;
	do {
		offset += element['offsetLeft'];
		element = element.offsetParent;
	} while (element != document.body && element != null);
	return offset;
}
var LazyLoad = {
	
	loadJS: function(urls, callback) {
	
		var urls = (urls.constructor === Array ? urls : [urls])
		urls.each(function(url) {
			var js = new LazyLoadJS(url, callback);
			js.load();
		});
	},
	
	
	loadCSS: function(urls) {
		var urls = (urls.constructor === Array ? urls : [urls])
		var head = $$("head")[0];
		urls.each(function(url) {
			var url = url.replace(/[^a-zA-Z0-9.\-_\/]/g, "");
			var css = document.createElement('link');
			css.type = "text/css";
			css.rel = "stylesheet";
			css.href = istock.cssCacheURL + url; 
		
		
			head.appendChild(css);
		});
	}
};
var LazyLoadJS = Class.create();
LazyLoadJS.prototype = {
	
	
	initialize: function(url, callback) {
	
		this.maxTries = 3;
	
	
		this.numTries = 0;
		
	
		this.url = url.replace(/[^a-zA-Z0-9.\-_\/]/g, "");
		
	
		this.callback = callback;
	},
		
	
	load: function() {
		
		var script = document.createElement("script");
		script.type = "text/javascript";
		script.src = istock.jsCacheURL + this.url;
		
	
		if(Prototype.Browser.Opera || Prototype.Browser.IE) {
			script.onreadystatechange = function() {
		
			
			
			
				if(script.readyState === "loaded" || script.readyState === "complete") {
					try {
					
						if(this.callback) {
							this.callback();
						}
					} catch(e) { 
						if(this.maxTries <= this.numTries) {
						
							return;
						}
						this.numTries++;
					
						this.load();
					}
				}
			}.bind(this);
		}
	
	
		else if ((Prototype.Browser.WebKit && !navigator.userAgent.match(/Version\/3/)) ) {
			
		
			var timer = setInterval(function() {
				if (document.readyState === "loaded" || document.readyState === "complete") {
					try {
					
						if(this.callback) {
							this.callback();
						}
						clearInterval(timer);
					} catch(e) {
						if(this.maxTries <= this.numTries) {
							clearInterval(timer);
						
	        				return;
	        			}
						this.numTries++;						
					}
				}
			}.bind(this), 10);
		}
	
		else {
			if(this.callback) {
				script.observe("load", this.callback.bind(this));
			}
		}
		
	
	
		document.body.appendChild(script);
	}
};
function TopsearchFormValidate(){
	
	return true;
}
function ToggleSearchOptionGroup(groupID, iconID, auto){
	groupObj = GetDocumentElementByID(groupID);
	iconObj = GetDocumentElementByID(iconID);
	if ( groupObj.style.display == 'none' || !groupObj.style.display ){
		groupObj.style.display = 'block';
		iconObj.src = '/images/icon_arrow_down.gif';
		if ( !auto ){ SetSearchOptionCookie(groupID, true) };
	} else {
		groupObj.style.display = 'none';
		iconObj.src = '/images/icon_arrow_right.gif';
		if ( !auto ){ SetSearchOptionCookie(groupID, false) };
	}
}
function SetSearchOptionCookie(groupID, state) {
	var today = new Date();
	var expire = new Date();
	expire.setTime(today.getTime()+3600000*24*30);
	if ( state ){
		stateString = 'on';
	} else {
		stateString = 'off';
	}
	document.cookie = "iStock_" + groupID + "=" + stateString +
	";path=/" +
	";expires="+expire.toGMTString() +
	";domain=.istockphoto.com" +
	";"						
}
function GetDocumentElementByID(objID) {
	var ie = document.all;
	var dom = document.getElementById;
  if ( ie ) {
    return document.all[objID];
  }
  else if ( dom ) {
    return document.getElementById(objID);
  }
}

function toggle( targetId ){
  if (document.getElementById){
  		target = document.getElementById( targetId );
  			if (target.style.display == "none"){
  				target.style.display = "";
  			} else {
  				target.style.display = "none";
  			}
  	}
}

function newImage(arg) {
     if (document.images) {
          rslt = new Image();
          rslt.src = arg;
          return rslt;
     }
}
function changeImages() {
     if (document.images && (preloadFlag == true)) {
          for (var i=0; i<changeImages.arguments.length; i+=2) {
               document[changeImages.arguments[i]].src = changeImages.arguments[i+1];
          }
     }
}
var preloadFlag = false;
function preloadImages() {
     if (document.images) {
	blue = newImage("images/blue/toplogo.gif");
	pink = newImage("images/pink/toplogo.gif");
	lime = newImage("images/lime/toplogo.gif");
	gold = newImage("images/gold/toplogo.gif");
	grey = newImage("images/grey/toplogo.gif");
	preloadFlag = true;
     }
}
function setActiveStyleSheet(title) {
  var i, a, main;
  for (i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if (a.getAttribute("rel") &&
        a.getAttribute("rel").indexOf("style") != -1 &&
        a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
}
function getActiveStyleSheet() {
  var i, a;
  for (i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if (a.getAttribute("rel") &&
        a.getAttribute("rel").indexOf("style") != -1 &&
        a.getAttribute("title") &&
        !a.disabled
        ) return a.getAttribute("title");
  }
  return null;
}
function getPreferredStyleSheet() {
  var i, a;
  for (i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if (a.getAttribute("rel") &&
        a.getAttribute("rel").indexOf("style") != -1 &&
        a.getAttribute("rel").indexOf("alt") == -1 &&
        a.getAttribute("title")
        ) return a.getAttribute("title");
  }
  return null;
}
function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}
window.onload = function(e) {
  var cookie = readCookie("style");
  var title = cookie ? cookie : getPreferredStyleSheet();
  setActiveStyleSheet(title);
}
window.onunload = function(e) {
  var title = getActiveStyleSheet();
  createCookie("style", title, 365);
}
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);

ATTRIBUTE_NODE = 2;
CDATA_SECTION_NODE = 4;
COMMENT_NODE = 8;
DOCUMENT_FRAGMENT_NODE = 11;
DOCUMENT_NODE = 9;
DOCUMENT_TYPE_NODE = 10;
ELEMENT_NODE = 1;
ENTITY_NODE = 6;
ENTITY_REFERENCE_NODE = 5;
NOTATION_NODE = 12;
PROCESSING_INSTRUCTION_NODE = 7;
TEXT_NODE = 3;
UNINITIALIZED = 0;
LOADING = 1;
LOADED = 2;
INTERACTIVE = 3;
COMPLETE = 4;
OK = 200;
NOT_FOUND = 404;
DOM_VERSION = "0.1.2";

function encode(s) {
	var l = s.length;
	var cooked = "";
	for (var i = 0; i < l; i++) {
		var c = s.charAt(i);
		switch (c) {
			case '\'':
				cooked += "&apos;";
				break;
			case '<':
				cooked += "&lt;";
				break;
			case '>':
				cooked += "&gt;";
				break;
			case '&':
				cooked += "&amp;";
				break;
			case "\"":
				cooked += "&quot;";
				break;
			default:
				if (c >= 128) {
					cooked += "&#" + (s.charCodeAt(i)) + ";";
				}
				break;
		}
	}	
	return cooked;
}
function hideAndSeek(target) {
	for (var i = 0; i < arguments.length; i++) {
		target = arguments[i];
		if (isArray(target)) { 
			var a = true;
			for (var i = 0; i < target.length; i++) {
				a = a && hideAndSeek(target[i]);
			}
			return a;
		} else {
			var t = get(target);
			if (! t) { return false; }
			if (t.style.display == "") {
				t.style.display = "none";
			} else {
				t.style.display = "";
			}
			return true;
		}
	}
}
function show(target) {
		var t = get(target);
		if (! t) { return false; } 
		
		t.style.display = "";
		return true;
}
function hide(target) {
		var t = get(target);
		if (! t) { return false; } 
		t.style.display = "none";
		return true;
}
function hideChildren(target, hide) {
	display = '';
	if (arguments.length == 1 || arguments[1] == true) {
		display = 'none';
	}
	var t = get(target);
	if (! t) { return false; }
	var children = t.childNodes;
	for (var i = 0; i < children.length; i++) {
		if (children[i].nodeType == ELEMENT_NODE) { 
			children[i].style.display = display;
		}
	}
	return true;
}
function setText(id, words) {
	var e = get(id);
	if (! e) { return false; }
   
	if (e.nodeType == TEXT_NODE) {
		e.nodeValue = words;
   
	} else {
    
		while (e.childNodes.length > 0) {
			e.removeChild(e.childNodes[0]);
		}
	
		e.appendChild(text(words));		
	}
	return true;
}
function inArray(array, element, func) {
	if (! func) {
		func = _argument;
	}
	var l = array.length;
	for (var i = 0; i < l; i++) {
		if (func(array[i]) == func(element)) {
			return true;
		}
	}
	return false;
}
function _argument(r) {
	return r;
}
function getNextElement(id, name) { return nextElement(id, name); }
function nextElement(id, name) {
	var t = get(id);
	if (! t) { return false; }
	while (t = t.nextSibling) {
	
		if (t.nodeType == ELEMENT_NODE) {
		
			if (! name) {
				return t;	
		
			} else if (name.toLowerCase() == t.nodeName.toLowerCase()) {
				return t;
			}
		}
	}
	return false;
}
function reverseChildren(t) {
	var parent = get(t);
	if (! parent) { return false; }
	
	var children = parent.childNodes;
	var nodes = Array();
	var count = children.length;
   
	for (var i = 0; i < count; i++) {
		nodes[i] = children.item(0);
		parent.removeChild(children[0]);
	}
	for (var i = nodes.length - 1; i >= 0; i--) {
		parent.appendChild(nodes[i]);
	}
	
	return true;
}
function duplicate(tag, zid) {
	var e = get(tag);
	if (! e) { return false; }
	if (e.nodeType == TEXT_NODE) {
		var d = text(e.nodeValue);
		return d;
	} else {
		var d = document.createElement(e.tagName);
		if (e.attributes.length) {
			attrs = e.attributes;
			for (var i = 0; i < attrs.length; i++) {
				var av = e.getAttribute(attrs[i].nodeName);
				var a = attrs[i].nodeName;
				if (a == 'id' && arguments.length == 2) {
					var r = new RegExp(":i:", "g");
					av = av.replace(r, zid);
				} 
				d.setAttribute(a, av);
			}
		}
		if (e.hasChildNodes()) {
			var count = e.childNodes.length;
			for (var i = 0; i < count; i++) {
				
				if (arguments.length == 2) {
					var d2 = duplicate(e.childNodes[i], zid);
				} else {
					var d2 = duplicate(e.childNodes[i]);
				}
				d.appendChild(d2);
			}
		} 
	}
	return d;
}
function disable(element, enabled) {
	if (arguments.length == 1) {
		enabled = false;
	}
	enable(element, enabled);
	return true;
}
function enable(element, enabled) {
	if (arguments.length == 1) {
		enabled = true;
	}
	var e = get(element);
	if (!e) { return false; }
	var name = e.tagName.toLowerCase();
	if (name == "form") {
		var tags = getByTagName(e, "fieldset");
		if (tags) {
			for (var i = 0; i < tags.length; i++) {
				enable(tags[i], enabled);
			}
		}
	
		var tags = getByTagName(e, ["input", "select", "textarea", "option"]);
		if (tags) {
			for (var i = 0; i < tags.length; i++) {
				disable(tags[i], enabled);
			}
		}
		
	} else if (name == "fieldset") {
		var tags = getByTagName(e, ["input", "select", "textarea", "option"]);
		if (tags) {
			for (var i = 0; i < tags.length; i++) {
				enable(tags[i], enabled);
			}
		}
	} else if (name == "input" || name == "select" || name == "textarea" || name == "option") {
		if (enabled) {
				e.removeAttribute("disabled");
		} else {
			e.setAttribute("disabled", "disabled");
		}
	}
	return true;
}
function get(id) {
	if (typeof id == "string") {
		return document.getElementById(id);
	} else {
		return id;
	}
}
function getNodeClass(obj) {
	var result = false;
	if (obj.getAttributeNode("class") != null) {
		result = obj.getAttributeNode("class").value;
	}
	return result;
}
function getByClass(parent, elementName, className) {
	var tag = false;
	if (arguments.length == 1) {
		tag = document;
		elementName = '*';
		className = arguments[0];
	} else if (arguments.length == 2) {
		tag = document;
		className = elementName;
		elementName = parent;
	} else {
		tag = get(parent);
	}
	if (! tag) { return false; }
	var nodes = new Array();
	var elements = getByTagName(tag, elementName);
	if (! elements) { return false; }
	for (var i = 0; i < elements.length; i++) {
		var c = getNodeClass(elements[i]);
		if (c && inArray(c.split(' '), className)) {
			nodes[nodes.length] = elements[i];
		}
	}
	return nodes;
}
function text(chars) {
	return document.createTextNode(chars);
}
function add(parent, child) {
	var p = get(parent);
	p.appendChild(node(child));
}
function snip(child) {
	var c = get(child);
	if (c) {
		var p = c.parentNode;
		if (! p) { return false; }
		p.removeChild(c);
	}
	return c;
}
function trimchildren(parent) {
	var p = get(parent);
	if (!p) { return false; } 
	while (p.hasChildNodes()) {
		var t = p.firstChild;
		p.removeChild(t);
	}
	
	return true;
}
function getParentNamed(tag, name, level) {
	if (! level) {
		level = 1;
	}
	var n = get(tag);
	if (! n) { return false; }
	var parent;
	var count = 0;
	while (parent = n.parentNode) {
		if (parent.nodeName.toLowerCase() == name.toLowerCase()) {
			count++;
			if (count == level) {
				return parent;
			}
		}
		n = parent;
	}
	return false;
}
function getFirstChildNamed(tag, name) {
    var parent = get(tag);
    var nodes = getByTagName(parent, name);
    
    if (nodes && nodes.length > 0) {
        return nodes[0];
    }
    return false;
}
function getByTagName(tag, name) {
	if (arguments.length == 1) {
		return document.getElementsByTagName(tag);
	} else {
		var t = get(tag);
		if (! t) { return false; }
		if (typeof name == "string") {
			name = new Array(name);
		}
		
	
		var tags = new Array();
		
		for (var i = 0; i < name.length; i++) {
			var result = t.getElementsByTagName(name[i]);
			for (var j = 0; j < result.length; j++) {
				if (result[j]) {
					tags = tags.concat(result[j]);
				}
			}
		}
		if (! tags.length) {
			tags = false;
		}
		return tags;
	}
}
function getNodeValue(node) {
	var n = get(node);
	if (!n) { return false; }
	
	if (n.nodeType == TEXT_NODE) {
		return n.nodeValue;
	} else if (n.nodeType == ELEMENT_NODE && n.childNodes.length > 0) {
		var text = '';
		for (var i = 0; i < n.childNodes.length; i++) {
			text += getNodeValue(n.childNodes[i]);
		}
		return text;
	} else {
		return '';
	}
}
function selectAll(select, b) {
	var s = get(select);
	if (b == null) { b = true; }
	
	var options = getByTagName(s, "option");
	for (var i = 0; i < options.length; i++) {
		options[i].selected = b;
	}
}
function countSelected(select) {
	var s = get(select);
	var count = 0;
	
	var options = getByTagName(s, "option");
	if (! options) { return 0; }
	for (var i = 0; i < options.length; i++) {
		if (options[i].selected) count++;
	}
	
	return count;
}
function getSelectedValue(select) {
  var s = get(select);
  if (! s) { return false; }
  var count = 0;
  
  var selected = new Array();
  var options = getByTagName(s, "option");
  if (! options) { return false; }
  
  var j = 0;
  for (var i = 0; i < options.length; i++) {
  	if (options[i].selected) {
  	  selected[j] = options[i].value;
  	  j++;
  	}
  }
  if (j > 0) {
    return selected;
  } else {
    return false;
  }
}
function getSelectedText(select) {
  var s = get(select);
  if (! s) { return false; }
  var count = 0;
  
  var selected = new Array();
  var options = getByTagName(s, "option");
  if (! options) { return false; }
  var j = 0;
  for (var i = 0; i < options.length; i++) {
  	if (options[i].selected) {
  	  selected[options[i].value] = options[i].text;
      j++;
  	}
  }  
  if (j > 0) {
      return selected;
  } else {
    return false;
  }
}
function getSelected(select) {
    return getSelectedText(select);
}
function removeOption(select, value) {
	return removeOptionByValue(select, value);
}
function clearOptions(select) {
	var s = get(select);
	if (! s) { return false; }
	var options = getByTagName(s, "option");
	for (var i = 0; i < s.childNodes.length; i = 0) {
		s.removeChild(s.lastChild);
	}
	return true;
}
function removeOptionByText(select, text) {
	var s = get(select);
	if (! s) { return false; }
	var flag = false;
	
	var options = getByTagName(s, "option");
	for (var i = 0; i < options.length; ) {
		if (getNodeValue(options[i]) == text) {
			s.removeChild(options[i]);
			flag = true;
		} else {
			i++;
		}
	}
	return flag;
}
function removeOptionByValue(select, value) {
	var s = get(select);
	if (! s) { return false; }
	
	var options = getByTagName(s, "option");
	for (var i = 0; i < options.length; i++) {
		if (options[i].value == value) {
			s.removeChild(options[i]);
			return true;
		}
	}
	return false;
}
function _valueSort(a, b) {
	if (a.value < b.value) { 
		return -1;
	} else if (a.value > b.value) {
		return 1;
	} else { return 0; }
}
function _captionSort(a, b) {
	if (a.text < b.text) {
		return -1;
	} else if (a.text > b.text) {
		return 1;
	} else { return 0; } 
}
function sortOptions(select, f) {
	if (f == null) { 
		f = _valueSort;
	}
	var s = get(select);
	if (! s) {
		return false;
	}
	var options = select.options;
	if (! options) {
		return false;
	}
	var holder = Array();
	for (var i = 0; i < options.length; i++) {
		holder[i] = options[i];
		s.removeChild(options[i]);
	}	
	holder.sort(f);
	for (var i = 0; i < holder.length; i++) {
		s.appendChild(holder[i]);
	}
	return true;
}
function selectOption(s, value) {
	
	if (arguments.length == 1) {
		value = 0;
	}
	var select = get(s);
	if (! select) { return false; }
	var options = select.options;
	if (! options) { return false; }
	for (var i = 0; i < options.length; i++) {	
		if (options[i].value == value) {
			options[i].selected = true;
			return true;
		}
	}
	return false;
}
function _getBoxValues(type, f, name) {
	var t = get(f);
	if (! t) { return false; }
	var inputs = getByTagName(t, "input");
	var values = new Array();
	for (var i=0; i < inputs.length; i++) {
		if (inputs[i].type == type && inputs[i].checked) {
			if (name) {
				if (inputs[i].name.toUpperCase() == name.toUpperCase()) {
					values.push(inputs[i].value);
				}
			} else {
				values.push(inputs[i].value);
			}
		}
	}
	
	if (values.length == 0) {
		return false;	
	} else {
		return values;
	}
}
function getCheckValues(f, name) {
	return _getBoxValues("checkbox", f, name)
}
function getLabelText(id) {
	var input = get(id);
	if (! input) { return false; }
	var label;
	if (id.nodeType == ELEMENT_NODE && id.nodeName.toLowerCase() == "label") { 
		label = input;
	} else {
		label = getParentNamed(input, "label");
	}
	
	if (! label) { return false; }
	return getNodeText(label);
}
function getNodeText(n) {
	var node = get(n);
	if (! node) { return false; }
	var string = '';
	if (node.nodeType == ELEMENT_NODE) {
		var children = node.childNodes;
		for (var i = 0; i < children.length; i++) {
			var t = getNodeText(children[i], trim);
			string += t ? t : '';
		}
	} else if (node.nodeType == TEXT_NODE) {
		string += node.nodeValue;
	} else {
		return '';
	}
	return string;
}
function getRadioValue(f, name) {
	
	var radios = _getBoxValues("radio", f, name);
	if (radios.length) {
		return radios[0];
	} else {
		return false;
	}
}
function getRadioText(f, name) {
	var t = get(f);
	if (! t) { return false; }
	
	var inputs = getByTagName(t, "input");
	for (var i = 0; i < inputs.length; i++) {
		if (inputs[i].type=="radio" && inputs[i].checked) {
            if (name) {            
                if (inputs[i].name.toUpperCase() == name.toUpperCase()) {
                   
                    var label = getParentNamed(inputs[i], "label");
                    return getNodeValue(label);
                }
            } else {
                var label = getParentNamed(inputs[i], "label");
                return getNodeValue(label);
			}
		}
	}	
	return false;
}
function checkBox(f, name, b, value) {
    var t = get(f);
    if (! t) { return false; }
    
    if (arguments.length < 3) {
        b = true;
    }
    
    var inputs = getByTagName(t, "input");
	for (var i = 0; i < inputs.length; i++) {
        var inputType = inputs[i].type.toUpperCase();
		if (inputType == "RADIO" || inputType == "CHECKBOX") {
            var inputName = inputs[i].name;
            if (name.toUpperCase() == inputName.toUpperCase()) {
                if (arguments.length <  4 || inputs[i].value == value) {
                    inputs[i].checked = b;
                    return true;
                } 
            } 
		}
	}
	return false;
}

function a(href, title, c, id, s, onclick, child) {
	
	var a = _createElement("a", c, id, s, child);
	
	a.setAttribute("href", href);
	a.setAttribute("title", title);
	if (onclick) {
		a.setAttribute("onclick", onclick);
	}
	
	return a;
}
function img(src, alt, c, id, s, width, height) {
	
	var img = _createElement("img", c, id, s);
	
	img.setAttribute("src", arguments[0]);
	img.setAttribute("alt", arguments[1]);
	
	if (width != null) { img.setAttribute("width", width); } 
	if (height != null) { img.setAttribute("height", height); } 
	return img;
}
function p(t, c, id, s) {
	return _createElement("p", c, id, s, t);
}
function div(c, id, s, child) {
	return _createElement("div", c, id, s, child);
}
function span(child, c, id, s) {
	return _createElement("span", c, id, s, child);	
}
function hr(c, id, s) {
	return _createElement("hr", c, id, s);
}
function br() {
	return document.createElement("br");
}
function strong(t, c, id, s) {
	var e = _createElement("strong", c, id, s);
	if (t != null) {
		e.appendChild(node(t));	
	}
	return e;
}
function em(t, c, id, s) {
	var e = _createElement("em", c, id, s);
	if (t != null) {
		e.appendChild(node(t));	
	}
	return e;
}
function pre(t, c, id, s) {
	var e = _createElement("pre", c, id, s);
	if (t != null) {
		e.appendChild(node(t));
	}
}
function code(t, c, id, s) {
	var e = _createElement("code", c, id, s);
	if (t != null) {
		e.appendChild(node(t));
	}
}
function dfn(t, c, id, s) {
	var e = _createElement("dfn", c, id, s);
	if (t != null) {
		e.appendChild(node(t));
	}
}
function cite(t, c, id, s) {
	var e = _createElement("cite", c, id, s);
	if (t != null) {
		e.appendChild(node(t));
	}
}
function del(t, cite, datetime, c, id, s) {
	var e = _createElement("del", c, id, s);
	if (t != null) {
		e.appendChild(node(t));
	}
	
}
function ins(t, cite, datetime, c, id, s) {
	var e = _createElement("cite", c, id, s);
	if (t != null) {
		e.appendChild(node(t));
	}
	
}
function blockquote(t, c, id, s) {
	var e = _createElement("quote", c, id, s);
	if (t != null) {
		e.appendChild(node(t));
	}
}
function address(t, c, id, s) {
	var e = _createElement("address", c, id, s);
	if (t != null) {
		e.appendChild(node(t));
	}	
}
function acronym(t, lang, c, id, s) {
	var e = _createElement("address", c, id, s);
	if (t != null) {
		e.appendChild(node(t));
	}
	
	if (lang != null) {
		e.setAttribute("lang", lang);
	}
}
function abbr(t, lang, c, id, s) {
	var e = _createElement("abbr", c, id, s);
	if (t != null) {
		e.appendChild(node(t));
	}	
	if (lang != null) {
		e.setAttribute("lang", lang);
	}
}

function checkbox(name, value, checked, onclick, c, id, s) {
	var c = _createElement("input", c, id, s);
	c.setAttribute("type", "checkbox");
	c.setAttribute("name", name);
	
	if (onclick != null) {
		c.setAttribute("onclick", onclick);
	}
	
	if (value != null) {
		c.setAttribute("value", value);
	}
	
	if (checked != null && checked) { 
		c.setAttribute("checked", "checked");
	}
	
	return c;
}
function radio(name, value, checked, onclick, c, id, s) {
	var c = _createElement("input", c, id, s);
	c.setAttribute("type", "radio");
	c.setAttribute("value", value);
	c.setAttribute("name", name);
	if (onclick != null) {
		c.setAttribute("onclick", onclick);
	}
	if (checked != null && checked) { 
		c.setAttribute("checked", "");
	}
	
	return c;
}
function label(t, input, c, id, s) {
	var l = _createElement("label", arguments[2], arguments[3], arguments[4]);
	l.appendChild(node(t));
	l.appendChild(node(input));	
	
	return l;
}
function select(c, id, s, onchange, size, multiple) {
	var s =  _createElement("select", c, id, s);
	if (size != null) {
		s.setAttribute("size", size);
	}
	
	if (multiple) {
		s.setAttribute("multiple", "multiple");
	}
	
	if (onchange != null) {
		s.setAttribute("onchange", onchange);
	}
	
	return s;
}
function button(name, value, onclick, c, id, s) {
	var b = _createElement("input", c, id, s);
	b.setAttribute("type", "button");
	b.setAttribute("name", name);
	b.setAttribute("value", value);
	
	if (onclick != null) {
		b.setAttribute("onclick", onclick);	
	}
	
	return b;
}
function reset(name, value, onclick, c, id, s) {
	var b = _createElement("input", c, id, s);
	b.setAttribute("type", "reset");
	b.setAttribute("name", name);
	b.setAttribute("value", value);
	
	if (onclick != null) {
		b.setAttribute("onclick", onclick);	
	}
	
	return b;
}
function submit(name, value, onclick, c, id, s) {
	var b = _createElement("input", c, id, s);
	b.setAttribute("type", "submit");
	b.setAttribute("name", name);
	b.setAttribute("value", value);
	
	if (onclick != null) {
		b.setAttribute("onclick", onclick);	
	}
	
	return b;
}
function option(value, name) {
	var o = _createElement("option");
	o.appendChild(node(name));
	o.setAttribute("value", value);
	
	return o;
}
function fileInput(name, c, id, s) {
	var f = _createElement("input", c, id, s);
	f.setAttribute("type", "file");
	
	return f;
}
function password(name, value, c, id, s) {
	
	var p = _createElement("input", c, id, s);
	p.setAttribute("type", "password");
	if (value != null) { 
		p.setAttribute("value", value);
	}
	
	return p;
}
function hiddenInput(name, value, id) {
	var e = _createElement("input");
	e.setAttribute("name", name);
	e.setAttribute("type", "hidden");
	if (value != null) { e.setAttribute("value", value); }
	if (id) {
		e.setAttribute("id", id);
	}
	
	return e;
}
function textInput(name, value, maxlength, size, onchange, id) {
	var t = _createElement("input");
	t.setAttribute("name", name);
	t.setAttribute("type", "text");
	t.setAttribute("value", (value != null ? value : ''));
	if (maxlength) {
		t.setAttribute("maxlength", maxlength);
	}
	
	if (size) {
		t.setAttribute("size", size);
	}
	if (onchange) {
		t.setAttribute("onchange", onchange);
	}
	if (id) {
		t.setAttribute("id", id);
	}
	
	return t;
}
function textarea(name, value, rows, cols, c, id, s) {
	var t = _createElement("textarea", c, id, s);
	t.appendChild(node(value));
	t.setAttribute("rows", rows);
	t.setAttribute("cols", cols);
	
	return t;
}

function table(c, id, s, spacing) {
	var t = _createElement("table", c, id, s);
	if (spacing != null) {
		t.setAttribute("cellspacing", spacing);
	}
	
	return t;
}
function tbody(c, id, s) {
	return _createElement("tbody", c, id, s);
}
function thead(c, id, s) {
	return _createElement("thead", c, id, s);
}
function tfoot(c, id, s) {
	return _createElement("tfoot", c, id, s);
}
function tr(c, id, s) { 
	return _createElement("tr", c, id, s);
}
function td(c, id, s, t) {
	var e = _createElement("td", c, id, s);
	if (t != null) { e.appendChild(node(t)); } 
	return e;
}
function th(c, id, s, t) {
	var e = _createElement("th", c, id, s);
	if (t != null) { e.appendChild(node(t)); } 
	return e;
}
function ol(c, id, s, start) {
	var e = _createElement("ol", c, id, s);
	if (start != null) {
		e.setAttribute("start", start);
	}
	return e;
}
function dl(c, id, s) {
	var e = _createElement("dl", c, id, s);
}
function ul(c, id, s) {
	var e = _createElement("ul", c, id, s);
	return e;
}
function li (child, c, id, s) {
	var l = _createElement("li", c, id, s);
	l.appendChild(node(child));
	
	return l;
}
function dt(child, c, id, s) {
	var l = _createElement("dt", c, id, s);
	l.appendChild(node(child));
	
	return l;
}
function dd(child, c, id, s) {
	var l = _createElement("dd", c, id, s);
	l.appendChild(node(child));
	return l;
}

function node(arg) {
	if (typeof(arg) == "string") {
		return document.createTextNode(arg);
	} else if (typeof(arg) == "number") { 
		return document.createTextNode("" + arg);
	} else {
		return arg;
	}
}
function _createElement(type, c, id, s, child) {
	
	var e = document.createElement(type);
	if (arguments[1] != null) { e.setAttribute("class", c); } 
	if (arguments[2] != null) { e.setAttribute("id", id); }
	if (arguments[3] != null) { e.setAttribute("style", s); } 
	if (arguments[4] != null) { e.appendChild(node(child)); }
	
	return e;
}
function checkAllBoxes(f, b, name) {
	
	var form = get(f);
	if (! form) { return false; }
	
	if (arguments.length == 1) {
		b = true;
		name = null;
	} else if (arguments.length == 2) {
		name == null;
	}
	
	var count = 0;
	var children = getByTagName(form, "input");
	for (var i = 0; i < children.length; i++) {
		if (children[i].type == "checkbox") {
			if (name) {
				if (children[i].name == name) {
					children[i].checked = b;
					count++;
				} 
			} else {
				children[i].checked = b;
				count++;
			}
		}
	}
	return count;
}
function countCheckedBoxes(f, name) {
	var form = get(f);
	if (! form) { return false; }
	
	var count = 0;
	var children = getByTagName(form, "input");
	for (var i = 0; i < children.length; i++) {
		if (children[i].type == "checkbox" && children[i].checked) {
			if (name) {
				if (children[i].name == name) {
					count++;
				} 
			} else {
				count++;
			}
		}
	}
	return count;
}
function getInputValues(f, name) {
	var form = get(f);
	if (! form) { return false; }
	var boxes = new Array();
	var children = getByTagName(form, "input");
	for (var i = 0; i < children.length; i++) {
		if (name) {
			if (children[i].name == name) {
				boxes.push(children[i].value);
			}
		} else {
			boxes.push(children[i].value);
		}
	}
	return boxes;
}
function getCheckedBoxValues(f, name) {
	var form = get(f);
	if (! form) { return false; }
	
	var boxes = new Array();
	var children = getByTagName(form, "input");
	for (var i = 0; i < children.length; i++) {
		if (children[i].type == "checkbox" && children[i].checked) {
			if (name) {
				if (children[i].name == name) {
					boxes.push(children[i].value);
				} 
			} else {
				boxes.push(children[i].value);
			}
		}
	}
	return boxes;
}
function isAlien(a) { return isObject(a) && typeof a.constructor != 'function'; }
function isArray(obj) { return(typeof(obj.length)=="undefined") ? false : true; }
function isBoolean(a) { return typeof a == 'boolean'; }
function isEmpty(o) {
    var i, v;
    if (isObject(o)) {
        for (i in o) {
            v = o[i];
            if (isUndefined(v) && isFunction(v)) { return false; }
        }
    }
    return true;
}
function isFunction(a) { return typeof a == 'function'; }
function isNull(a) { return typeof a == 'object' && !a;}
function isNumber(a) { return typeof a == 'number' && isFinite(a);}
function isObject(a) { return (a && typeof a == 'object') || isFunction(a);}
function isString(a) { return typeof a == 'string';}
function isUndefined(a) { return typeof a == 'undefined'; } 
ajaxWin = {
	contents:'',
	json:[],
	loaded: false,
	
	show: function(json) {
		ajaxWin.json = json;
		
		ajaxWin.buildContents();
		if(this.loaded){
			ajaxWin.activateWindow();
		}else{
			Event.observe(window, 'load', ajaxWin.activateWindow);
		}
	},
	
	
	buildContents: function() {
	
		json = ajaxWin.json;
	
		ajaxWin.contents = '<h2 class="hdr" id="ajaxWinHdr">';
			ajaxWin.contents += '<a onclick="' + (json.cnclFunc ? json.cnclFunc : '') + ' ajaxWin.cancelWindow(); return false" style="cursor:pointer; font-size:.8em;" class="fr close_btn" title="'+(json.cnclText ? json.cnclText : 'Cancel')+'" ></a>';
			ajaxWin.contents += json.title;
		ajaxWin.contents += '</h2>';
		
		
		
		ajaxWin.contents += '<div style="padding:0 1em 1em 1em">';
			
		
			if (json.hdrTxt || json.hdrIcon) {
				ajaxWin.contents += '<table class="ndnt">';
					ajaxWin.contents += '<tr>';
						ajaxWin.contents += '<td class="m"><img src="'+json.hdrIcon+'" alt="" style="padding-right:6px" /></td>';
						ajaxWin.contents += '<td><strong class="'+json.hdrTxtClass+'">'+json.hdrTxt+'</strong></td>';
					ajaxWin.contents += '</tr>';
				ajaxWin.contents += '</table>';
			
				ajaxWin.contents += '<div class="hr"></div>';
			}
			ajaxWin.contents += json.cntnt;
		
		ajaxWin.contents += '</div>';
		
		
		ajaxWin.contents += '<div class="ftr">';
			ajaxWin.contents += json.footer;
		
			
		ajaxWin.contents += '</div>';
	},
	
	activateWindow: function() {
			
		json = ajaxWin.json;
		
	
		if ( !$('ajaxWin')){
			new Insertion.Bottom('wrapper', '<div id="ajaxWinBG" style="display: none;" ></div>');
			new Insertion.Bottom('wrapper', '<div id="ajaxWin" style="display: none;" >'+ajaxWin.contents+'</div>');
		} else {
			$('ajaxWin').hide();
		 	$('ajaxWin').update(ajaxWin.contents);
		}
		
	
		if (typeof(json.wdth) != 'undefined') {
			$('ajaxWin').style.width = json.wdth+'px';
		}
	
		w = $('ajaxWin').getWidth();
		h = $('ajaxWin').getHeight();
		viewportDims = document.viewport.getDimensions();
		scrollOffsets = document.viewport.getScrollOffsets();
		
	
		$('ajaxWinBG').style.width = (viewportDims['width']*3)+scrollOffsets['left']+'px';
		$('ajaxWinBG').style.height = (viewportDims['height']*3)+scrollOffsets['top']+'px';
	
		$('ajaxWin').style.top = Math.max(0, parseInt((viewportDims['height']/2)-(h/2)+scrollOffsets['top']))+'px';
		$('ajaxWin').style.left = Math.max(0, parseInt((viewportDims['width']/2)-(w/2)+scrollOffsets['left']))+'px';
		
	
		$$('#ajaxWin select').each(function(elm){
			new Autocompleter.SelectBox(elm, {'width':230});
		});
		$('ajaxWinBG').style.display = 'block';
		$('ajaxWin').style.display = 'block';
		
	
		draggable = new Draggable('ajaxWin',{handle:'ajaxWinHdr'});
		if (draggable) $('ajaxWinHdr').setStyle('cursor:move');
		
	},
	
	cancelWindow: function() {
		if ($('ajaxWin')) $('ajaxWin').remove();
		if ($('ajaxWinBG')) $('ajaxWinBG').remove();
	}
}
Event.observe(window, 'load', function(){ajaxWin.loaded = true;});
var Tabs = {
	currentTab: '',
	currentParentTab: '',
	historyTab: new Hashtable(),
	setParentTab: function(tabID) {
		this.currentParentTab = tabID;
		if (this.historyTab.containsKey(tabID)) {
			this.currentTab = this.historyTab.get(tabID);
		}
		else {
			this.currentTab = '';
		}
	},
	setDefaultTab: function(tabID) {
		if (this.currentTab.length < 1){
			this.currentTab = tabID;
			if (this.currentParentTab.length > 0) {
				this.historyTab.put(this.currentParentTab, this.currentTab);
			}
		}
	},
	switchToTab: function(tabID) {
		if (this.currentTab.length > 0) {
			this.switchFromTab(this.currentTab);
		}
		if (this.currentParentTab.length > 0) {
			this.historyTab.put(this.currentParentTab, tabID);
		}
		this.currentTab = tabID;
		document.getElementById(tabID).className="tabContainer";		
		document.getElementById(tabID + '_Content').style.display = 'block';
	},
	switchFromTab: function(tabID) {
		document.getElementById(tabID).className="tabContainerOff";
		document.getElementById(tabID + '_Content').style.display = 'none';	
	}
}
function Hashtable() {
   this.hashtable = new Array()
};
Hashtable.prototype.clear = function(){
	this.hashtable = new Array();
};
Hashtable.prototype.containsKey = function(key){
    var exists = false;
    for (var i in this.hashtable) {
        if (i == key && this.hashtable[i] != null) {
            exists = true;
            break;
        }
    }
    return exists;
};
Hashtable.prototype.containsValue = function(value){
    var contains = false;
    if (value != null) {
        for (var i in this.hashtable) {
            if (this.hashtable[i] == value) {
                contains = true;
                break;
            }
        }
    }
    return contains;
};
Hashtable.prototype.get = function(key){
    return this.hashtable[key];
};
Hashtable.prototype.isEmpty = function(){
    return (parseInt(this.size()) == 0) ? true : false;
};
Hashtable.prototype.keys = function(){
    var keys = new Array();
    for (var i in this.hashtable) {
        if (this.hashtable[i] != null)
            keys.push(i);
    }
    return keys;
};
Hashtable.prototype.put = function(key, value){
    if (key == null || value == null) {
        throw "NullPointerException {" + key + "},{" + value + "}";
    }else{
        this.hashtable[key] = value;
    }
};
Hashtable.prototype.remove = function(key){
    var rtn = this.hashtable[key];
    this.hashtable[key] = null;
    return rtn;
};
Hashtable.prototype.size = function(){
    var size = 0;
    for (var i in this.hashtable) {
        if (this.hashtable[i] != null)
            size ++;
    }
    return size;
};
Hashtable.prototype.toString = function(){
    var result = "";
    for (var i in this.hashtable)
    {     
        if (this.hashtable[i] != null)
            result += "{" + i + "},{" + this.hashtable[i] + "}\n";  
    }
    return result;
};
Hashtable.prototype.values = function(){
    var values = new Array();
    for (var i in this.hashtable) {
        if (this.hashtable[i] != null)
            values.push(this.hashtable[i]);
    }
    return values;
};
var BatchTagEdit = {
	busySmallURL: 'images/loading_small.gif',
								
	busyURL: 'images/loading.gif',
	emptyImageURL: 'images/image_place_holder.gif',
								
	activeBatch: 0, 
	addToBatchButtons: new Array,
							 
	rowIndex: new Array,
					
	baseImageWidth: new Array,
	imagePadding: new Array,
									
	baseDivWidth: new Array,
	baseDivHeight: new Array,
	imagesPerPage: new Array,
	numRows: new Array,
	maxImageWidth: new Array,
	currentTableShift: new Array,
	currentTableVShift: new Array,
	notBase: new Array,
	imageSelect: new Array,
	pageNum: new Array,
	totalPages: new Array,
	nextPage: new Array,
	nextPageFileIDs: new Array,
	prevPage: new Array,
	prevPageFileIDs: new Array,
	currentPageFileIDs: new Array,
	selectDisabled: new Array,
	commonTerms: new Array,
	toAddTerms: new Array,
	toRemoveTerms: new Array,
	revisionNumber: new Array,
	disambigEmptyXML: '',
	
	disambigXML: new Array,
	
	disambigTerms: new Array,
	disambigRemovedTerms: new Array,
	draggables: new Array,
	navBarVars: new Object(),
	images: new Array,
	failed: function(req){
		$('BatchEditLoading').style.visibility = 'hidden';
		alert('An error occured while communicating with the server. Please try again.');
	},
	silentFailed: function(req){
	
		$('BatchEditLoading').style.visibility = 'hidden';
	},
	initializeImage: function(
			batchID, 
			baseImageWidth, 
			imagePadding, 
			baseDivWidth, 
			baseDivHeight, 
			imagesPerPage, 
			maxImageWidth, 
			pageNum, 
			totalPages,
			numRows
			){
		this.activeBatch = batchID;
 		rowID = this.rowIndex.indexOf(batchID);
		if(rowID == -1){
			this.rowIndex[this.rowIndex.length] = Number(batchID);
	 		rowID = this.rowIndex.indexOf(batchID);
		}
		this.baseImageWidth[rowID] = baseImageWidth;
		this.imagePadding[rowID] = imagePadding;
		this.baseDivWidth[rowID] = this.getBaseDivWidth(batchID);
		this.baseDivHeight[rowID] = baseDivHeight;
		this.imagesPerPage[rowID] = imagesPerPage;
		this.maxImageWidth[rowID] = maxImageWidth;
		this.currentTableShift[rowID] = 0;
		this.currentTableVShift[rowID] = 0;
		this.notBase[rowID] = new Array;
		this.imageSelect[rowID] = new Array;
		this.pageNum[rowID] = pageNum;
		this.totalPages[rowID] = totalPages;
		this.nextPage[rowID] = null;
		this.prevPage[rowID] = null;
		this.nextPageFileIDs[rowID] = new Array;
		this.prevPageFileIDs[rowID] = new Array;
		this.currentPageFileIDs[rowID] = new Array;
		this.selectDisabled[rowID] = false;
		this.numRows[rowID] = numRows;
		this.loadNextPage(batchID);
		return;
		this.loadPrevPage(batchID);
	},
	initFileID: function(batchID, index, fileID){
 		rowID = this.rowIndex.indexOf(batchID);
		this.currentPageFileIDs[rowID][index] = fileID;
	},
	initAddToBatchButton: function(fileID){
	
		this.addToBatchButtons.push(fileID);
	},
	getBaseDivWidth: function(batchID){
		div = $('batchImageTool_' + batchID);
		if(typeof(div) == 'object'){
			return div.offsetWidth;
		}else{
			return false;
		}
	},
									 
	imageHover: function(e, batchID){
		rowID = this.rowIndex.indexOf(batchID);
		if(!this.baseDivWidth[rowID]){
			this.baseDivWidth[rowID] = this.getBaseDivWidth(batchID);
			return;
		}
		var layerx = e.layerX;
	
		if(typeof(layerx) != 'number'){
			layerx = e.x;
		}
		
	
		var x = (layerx + this.currentTableShift[rowID]) - 1;
		
		var imagePartial = (x/this.baseDivWidth[rowID]) * this.imagesPerPage[rowID];
		var imageIndex = Math.round(imagePartial-0.5);
		imagePartial = (imagePartial - imageIndex) - 0.5;
		
		if(imageIndex < 0){
			imageIndex = 0;
		}else	if(imageIndex >= this.imagesPerPage[rowID]){
			imageIndex = this.imagesPerPage[rowID] - 1;
		}
		
		if(imagePartial < -0.5){
			imagePartial = -0.5;
		}else if(imagePartial > 0.5){
			imagePartial = 0.5;
		}
		
		var imageStrength = 1 - (Math.abs(imagePartial));
		var imageWidth = ((this.maxImageWidth[rowID] - this.baseImageWidth[rowID])*imageStrength);
		var	otherIndex = -1;
		
		if(imageIndex == 0){
			if(imagePartial < 0){
				otherIndex = -1;
				imageWidth = ((this.maxImageWidth[rowID] - this.baseImageWidth[rowID])*(imageStrength-0.5)*2);
			}else{
				otherIndex = 1;
			}
		}else if(imageIndex == (this.imagesPerPage[rowID] - 1)){
			if(imagePartial > 0){
				otherIndex = -1;
				imageWidth = ((this.maxImageWidth[rowID] - this.baseImageWidth[rowID])*(imageStrength-0.5)*2);
			}else{
				otherIndex = imageIndex - 1;
			}
		}else{
			if(imagePartial < 0){
				otherIndex = imageIndex - 1;
			}else{
				otherIndex = imageIndex + 1;
			}
		}
	
		if(this.notBase[rowID].length > 0){
			this.notBase[rowID].each(
				(
					function(imageID, index){
						BatchTagEdit.resetImage(imageID, batchID);
					}
				).bind(this)
			);
			this.notBase[rowID] = new Array;
		}
		$('imageRow' + imageIndex + '_' + batchID).style.width = (imageWidth + this.baseImageWidth[rowID]) + 'px';
		this.notBase[rowID].push(imageIndex);
		if(otherIndex >= 0){
			otherStrength = 1 - imageStrength;
			otherWidth = ((this.maxImageWidth[rowID] - this.baseImageWidth[rowID])*otherStrength);
			
			$('imageRow' + otherIndex + '_' + batchID).style.width = (otherWidth + this.baseImageWidth[rowID]) + 'px';
			this.notBase[rowID][this.notBase[rowID].length] = otherIndex;
		}else{
			otherWidth = 0;
		}
		
		var table = $('imageRow_' + batchID);
		var tableWidth = table.offsetWidth;
		var tableShift = -Math.round((x/this.baseDivWidth[rowID]) * (tableWidth - this.baseDivWidth[rowID]));
	
	
		var tableHeight = table.offsetHeight;
		this.currentTableShift[rowID] = tableShift;
		
		table.style.left = tableShift + 'px';
	},
	addImage: function(imageID){
		batchID = this.activeBatch;
 		rowID = this.rowIndex.indexOf(batchID);
		this.showAddToBatchButton(false, imageID);
	
		if(this.currentPageFileIDs[rowID].length < this.imagesPerPage[rowID]){
			$('imageRow' + this.currentPageFileIDs[rowID].length + '_' + batchID).src = this.busyURL;
		}
		var url = "ajax_class_creator.php";
		var params = "ajax_action=addImage&ajax_class=tagedit" +
			"&image=" + imageID +
			"&pageSize=" + this.imagesPerPage[rowID] +
			"&batchID=" + batchID;
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.showPage.bind(this),
				onFailure: this.silentFailed.bind(this)
			}
		);
	},
							 
	addAllImages: function(){
		batchID = this.activeBatch;
 		rowID = this.rowIndex.indexOf(batchID);
		this.addToBatchButtons.each(
			(
				function(imageID, index){
					this.showAddToBatchButton(false, imageID);
					
				}
			).bind(this)
		);
	
		if(this.currentPageFileIDs[rowID].length < this.imagesPerPage[rowID]){
			$('imageRow' + this.currentPageFileIDs[rowID].length + '_' + batchID).src = this.busyURL;
		}
		var url = "ajax_class_creator.php";
		var params = "ajax_action=addImage&ajax_class=tagedit" +
			"&image=" + this.addToBatchButtons.join() +
			"&pageSize=" + this.imagesPerPage[rowID] +
			"&batchID=" + batchID;
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.showPage.bind(this),
				onFailure: this.silentFailed.bind(this)
			}
		);
	},
							 
	resetImage: function(imageID, batchID){
		rowID = this.rowIndex.indexOf(batchID);
		$('imageRow' + imageID + '_' + batchID).style.width = this.baseImageWidth[rowID] + 'px';
	},
	
	resetImages:function(batchID){
 		rowID = this.rowIndex.indexOf(batchID);
		for (i=0; i < this.imagesPerPage[rowID]; i++) {
			this.resetImage(i, batchID);
		}
		$('imageRow_' + batchID).style.left = '0px';
	},
							 
	selectImage:function(batchID, imageIndex){
		rowID = this.rowIndex.indexOf(batchID);
		if(this.selectDisabled[rowID] || imageIndex >= this.currentPageFileIDs[rowID].length){
		
			return;
		}
		imageID = this.currentPageFileIDs[rowID][imageIndex];
		foundAt = this.imageSelect[rowID].indexOf(imageID);
		
		if(foundAt > -1){
			this.imageSelect[rowID] = this.imageSelect[rowID].without(imageID);
			$('imageRow' + imageIndex + '_' + batchID).style.backgroundColor = '';
		}else{
			this.imageSelect[rowID].push(imageID);
			$('imageRow' + imageIndex + '_' + batchID).style.backgroundColor = '#ff9900';
		}
		this.showSelectCount(batchID);
	},
	showSelectCount: function(batchID){
		rowID = this.rowIndex.indexOf(batchID);
		
		var count = this.imageSelect[rowID].length;
		var selectCount = $('BatchEditSelectCount');
		if(count > 1){
			selectCount.innerHTML = '(' + count + ' files selected)';
		}else if(count > 0){
			selectCount.innerHTML = '(' + count + ' file selected)';
		}else{
			selectCount.innerHTML = '';
		}
	},
	loadPrevPage:function(batchID){
 		rowID = this.rowIndex.indexOf(batchID);
		this.prevPage[rowID] = null;
		this.prevPageFileIDs[rowID] = null;
		
	
		if(this.pageNum[rowID] <= 0){
			
			return;
		}
		var url = "ajax_class_creator.php";
		var params = "ajax_action=getBatchPage&ajax_class=tagedit" +
			"&page=" + (this.pageNum[rowID] - 1) +
			"&pageSize=" + this.imagesPerPage[rowID] +
			"&batchID=" + batchID;
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.storePrevPage.bind(this),
				onFailure: this.silentFailed.bind(this)
			}
		);
	},
	storePrevPage: function(req){
	
	
		var data = AjaxUtil.receiveArray(req.responseText);
		if(data.error == 1) {
			this.failed();
			return;
		}
		var batchID = Number(data.batchID);
		var rowID = this.rowIndex.indexOf(batchID);
		var thePrevPage = new Array;
		var thePrevPageFileIDs = new Array;
		if(data.fileIDs.length > 0){
			data.fileIDs.each(
				(
					function(fileID, index){
						var anImage = new Image();
						anImage.src =	data.fileThumbs[index]; 
						anImage.onmouseover = function(){
							showtrailBatch(data.fileThumbsBig[index],data.fileTitles[index],data.fileTypes[index]);
						}
						thePrevPageFileIDs[index] = fileID;
						thePrevPage[index] = anImage;
					}
				).bind(this)
			);
		}
		this.prevPage[rowID] = thePrevPage;
		this.prevPageFileIDs[rowID] = thePrevPageFileIDs;
	
		this.refreshRecentBatches(batchID,data.recentBatches);
	 	return;
	},
	showPrevPage:function(batchID){
 		rowID = this.rowIndex.indexOf(batchID);
		if(this.pageNum[rowID] < 1){
			this.showPageOfPage(batchID);
			return;
		}
		if(this.prevPage[rowID] == null){
			this.loadPage(batchID, this.pageNum[rowID] - 1);
			return;
		}
		
	
	
	
		this.selectDisabled[rowID] = true;
		this.nextPage[rowID] = new Array;
		this.nextPageFileIDs[rowID] = new Array;
		theCurrentFileIDs = new Array;
		
		if(this.prevPage[rowID].length > 0){
			this.prevPage[rowID].each(
				(
					function(image, index){
						var imgElement = $('imageRow' + index + '_' + batchID);
						var onmouseoverAttr = imgElement.onmouseover;
						if(index < this.currentPageFileIDs[rowID].length){
							this.nextPage[rowID][index] = new Image();
							this.nextPage[rowID][index].src = imgElement.src;
							this.nextPage[rowID][index].onmouseover = onmouseoverAttr;
							this.nextPageFileIDs[rowID][index] = this.currentPageFileIDs[rowID][index];
						}
						imgElement.onmouseover = image.onmouseover;
						imgElement.src = this.busyURL;
						imgElement.src = image.src;
						if(this.imageSelect[rowID].indexOf(this.prevPageFileIDs[rowID][index]) > -1){
							imgElement.style.backgroundColor = '#ff9900';
						}else{
							imgElement.style.backgroundColor = '';
						}
						theCurrentFileIDs[index] = this.prevPageFileIDs[rowID][index];
					}
				).bind(this)
			);
		}
		for (i = this.prevPage[rowID].length; i < this.imagesPerPage[rowID]; i++){
			imgElement = $('imageRow' + i + '_' + batchID);
			onmouseoverAttr = imgElement.onmouseover;
			if(i < this.currentPageFileIDs[rowID].length){
				this.nextPage[rowID][i] = new Image();
				this.nextPage[rowID][i].src = imgElement.src;
				this.nextPage[rowID][i].onmouseover = onmouseoverAttr;
				this.nextPageFileIDs[rowID][i] = this.currentPageFileIDs[rowID][i];
			}
			imgElement.onmouseover = null;
			imgElement.src = 'images/image_place_holder.gif';
			imgElement.style.backgroundColor = '';
		}
		this.pageNum[rowID] = this.pageNum[rowID] - 1;
		this.currentPageFileIDs[rowID] = theCurrentFileIDs;
		this.selectDisabled[rowID] = false;
		this.showPageOfPage(batchID);
		this.loadPrevPage(batchID);
		
		return;
	},
	showPrevButton:function(batchID){
 		rowID = this.rowIndex.indexOf(batchID);
		if(this.pageNum[rowID] > 0){
			$('batchImageToolPrevPage_' + batchID).style.visibility = 'visible';
		}else{
			$('batchImageToolPrevPage_' + batchID).style.visibility = 'hidden';
		}
	},
	loadNextPage:function(batchID){
 		rowID = this.rowIndex.indexOf(batchID);
	
		this.nextPage[rowID] = null;
		this.nextPageFileIDs[rowID] = null;
		var url = "ajax_class_creator.php";
		var params = "ajax_action=getBatchPage&ajax_class=tagedit" +
			"&page=" + (this.pageNum[rowID] + 1) +
			"&pageSize=" + this.imagesPerPage[rowID] +
			"&batchID=" + batchID;
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.storeNextPage.bind(this),
				onFailure: this.silentFailed.bind(this)
			}
		);
	},
	storeNextPage: function(req){
	
	
		var data = AjaxUtil.receiveArray(req.responseText);
		if(data.error == 1) {
			this.failed();
			return;
		}
		var batchID = Number(data.batchID);
		var rowID = this.rowIndex.indexOf(batchID);
		var theNextPage = new Array;
		var theNextPageFileIDs = new Array;
		if(data.fileIDs.length > 0){
			data.fileIDs.each(
				(
					function(fileID, index){
						var anImage = new Image();
						anImage.src =	data.fileThumbs[index]; 
						anImage.onmouseover = function(){
							showtrailBatch(data.fileThumbsBig[index],data.fileTitles[index],data.fileTypes[index]);
						}
						theNextPageFileIDs[index] = fileID;
						theNextPage[index] = anImage;
					}
				).bind(this)
			);
		}
		this.nextPage[rowID] = theNextPage;
		this.nextPageFileIDs[rowID] = theNextPageFileIDs;
	
		this.refreshRecentBatches(batchID,data.recentBatches);
	 	return;
	},
	showNextPage:function(batchID){
 		rowID = this.rowIndex.indexOf(batchID);
		if(this.pageNum[rowID] > (this.totalPages[rowID] - 1)){
			this.showPageOfPage(batchID);
			return;
		}
		if(this.nextPage[rowID] == null){
			this.loadPage(batchID, this.pageNum[rowID] + 1);
			return;
		}
	
	
		this.selectDisabled[rowID] = true;
		this.prevPage[rowID] = new Array;
		this.prevPageFileIDs[rowID] = new Array;
		theCurrentFileIDs = new Array;
		
		if(this.nextPage[rowID].length > 0){
			this.nextPage[rowID].each(
				(
					function(image, index){
						var imgElement = $('imageRow' + index + '_' + batchID);
						var onmouseoverAttr = imgElement.onmouseover;
						if(index < this.currentPageFileIDs[rowID].length){
							this.prevPage[rowID][index] = new Image();
							this.prevPage[rowID][index].src = imgElement.src;
							this.prevPage[rowID][index].onmouseover = onmouseoverAttr;
							this.prevPageFileIDs[rowID][index] = this.currentPageFileIDs[rowID][index];
						}
						imgElement.onmouseover = image.onmouseover;
						imgElement.src = this.busyURL;
						imgElement.src = image.src;
						if(this.imageSelect[rowID].indexOf(this.nextPageFileIDs[rowID][index]) > -1){
							imgElement.style.backgroundColor = '#ff9900';
						}else{
							imgElement.style.backgroundColor = '';
						}
						theCurrentFileIDs[index] = this.nextPageFileIDs[rowID][index];
					}
				).bind(this)
			);
		}
		for (i = this.nextPage[rowID].length; i < this.imagesPerPage[rowID]; i++){
			imgElement = $('imageRow' + i + '_' + batchID);
			var onmouseoverAttr = imgElement.onmouseover;
			if(i < this.currentPageFileIDs[rowID].length){
				this.prevPage[rowID][i] = new Image();
				this.prevPage[rowID][i].src = imgElement.src;
				this.prevPage[rowID][i].onmouseover = onmouseoverAttr;
				this.prevPageFileIDs[rowID][i] = this.currentPageFileIDs[rowID][i];
			}
			imgElement.onmouseover = null;
			imgElement.src = this.emptyImageURL;
			imgElement.style.backgroundColor = '';
		}
		this.pageNum[rowID] = this.pageNum[rowID] + 1;
		this.currentPageFileIDs[rowID] = theCurrentFileIDs;
		this.selectDisabled[rowID] = false;
		
		this.showPageOfPage(batchID);
	
		this.loadNextPage(batchID);
		
		return;
	},
	showNextButton:function(batchID){
 		rowID = this.rowIndex.indexOf(batchID);
		if(this.pageNum[rowID] < (this.totalPages[rowID]-1)){
			$('batchImageToolNextPage_' + batchID).style.visibility = 'visible';
		}else{
			$('batchImageToolNextPage_' + batchID).style.visibility = 'hidden';
		}
	},
	loadPage:function(batchID, pageNum){
		$('BatchEditLoading').style.visibility = 'visible';
		rowID = this.rowIndex.indexOf(batchID);
		pageNum = Math.max(0, Math.min((this.totalPages[rowID]-1), pageNum));
		var url = "ajax_class_creator.php";
		var params = "ajax_action=getBatchPage&ajax_class=tagedit" +
			"&page=" + pageNum +
			"&pageSize=" + this.imagesPerPage[rowID] +
			"&batchID=" + batchID;
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.showPage.bind(this),
				onFailure: this.silentFailed.bind(this)
			}
		);
	},
	
	showPage: function(req){
		$('BatchEditLoading').style.visibility = 'hidden';
	
		
		var data = AjaxUtil.receiveArray(req.responseText);
		
		if(data.error == 1) {
			this.failed();
			return;
		}
	
		var batchID = Number(data.batchID);
		var rowID = this.rowIndex.indexOf(batchID);
	
	
		this.selectDisabled[rowID] = true;
		this.nextPage[rowID] = new Array;
		this.nextPageFileIDs[rowID] = new Array;
		this.prevPage[rowID] = new Array;
		this.prevPageFileIDs[rowID] = new Array;
		this.currentPageFileIDs[rowID] = new Array;
		if(typeof(data.fileIDs.length) == 'undefined'){
			data.fileIDs.length = 0;
		}
		if(data.fileIDs.length > 0){
			data.fileIDs.each(
				(
					function(fileID, index){
						var imgElement = $('imageRow' + index + '_' + batchID);
						imgElement.src =	data.fileThumbs[index]; 
						imgElement.onmouseover = function(){
							showtrailBatch(data.fileThumbsBig[index],data.fileTitles[index],data.fileTypes[index]);
						}
					 
						this.currentPageFileIDs[rowID][index] = fileID;
						if(this.imageSelect[rowID].indexOf(fileID) > -1){
							imgElement.style.backgroundColor = '#ff9900';
						}else{
							imgElement.style.backgroundColor = '';
						}
						this.currentPageFileIDs[rowID][index] = fileID;
					}
				).bind(this)
			);
		}
		
		for (i = data.fileIDs.length; i < this.imagesPerPage[rowID]; i++){
			imgElement = $('imageRow' + i + '_' + batchID);
			imgElement.onmouseover = null;
			imgElement.src = 'images/image_place_holder.gif';
			imgElement.style.backgroundColor = '';
		}
	
		if(data.addToBatchButtons && data.addToBatchButtons.length > 0){
			data.addToBatchButtons.each(
				(
					function(id, index){
						this.showAddToBatchButton(true, id);
					}
				).bind(this)
			);
		}
		this.pageNum[rowID] = Number(data.pageNum);
		this.totalPages[rowID] = data.totalPages;
		
		this.selectDisabled[rowID] = false;
		this.showPageOfPage(batchID);
	
	
	
		this.loadNextPage(batchID);
		this.loadPrevPage(batchID);
		
		this.refreshRecentBatches(batchID,data.recentBatches);
		
		return;
	},
	showPageOfPage: function(batchID){
 		rowID = this.rowIndex.indexOf(batchID);
		pageOfPage = $('batchImageToolPage_' + batchID);
		pageOfPage.innerHTML = pageOfPage.innerHTML.replace(/^(\D*)\d+(\D+)\d+(\D*)$/,'$1' + Math.max(Number(1),(Number(this.pageNum[rowID]) + Number(1))) + '$2' + Math.max(1,this.totalPages[rowID]) + '$3');
		this.showPrevButton(batchID);
		this.showNextButton(batchID);
		this.rememberBatch(batchID);
		this.showSelectCount(batchID);
	},
	rememberBatch: function(batchID){
		rowID = this.rowIndex.indexOf(batchID);
		if(batchID > 0){
			page = this.pageNum[rowID];
		}else{
			page = 0;
		}
		var url = "ajax_class_creator.php";
		var params = "ajax_action=rememberBatch&ajax_class=tagedit" +
			"&page=" + page +
			"&batchID=" + batchID;
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.saveRememberBatch.bind(this)
			}
		);
	},
	saveRememberBatch: function(req){
	
	},
	
	jumpPage:function(batchID){
 		rowID = this.rowIndex.indexOf(batchID);
		var newPageControl = $('batchImageToolJumpPage_' + batchID);
		var newPage = newPageControl.value;
		
		newPageControl.value = '';
		
		if(isNaN(newPage)){
			alert('please enter a number');
		}else if(Number(newPage) < 1 || Number(newPage) > this.totalPages[rowID]){
			alert('That page does not exist');
		}else{
			newPage = Number(newPage);
			this.loadPage(batchID, newPage - 1);
		}
	},
	showFirstPage:function(batchID){
 		rowID = this.rowIndex.indexOf(batchID);
		this.loadPage(batchID, 0);
	},
	showLastPage:function(batchID){
 		rowID = this.rowIndex.indexOf(batchID);
		this.loadPage(batchID, this.totalPages[rowID]-1);
	},
	moveSelected:function(batchID, targetType){
		$('BatchEditLoading').style.visibility = 'visible';
 		rowID = this.rowIndex.indexOf(batchID);
		if(targetType == 'New'){
			target = $('batchImageToolNew_' + batchID).value;
			target = encodeURI(target);
	    target = target.replace(/&/g, '%26');
	    target = target.replace(/=/g, '%3D');
		}else{
			target = $('batchImageToolRecent_' + batchID).value;
			if(isNaN(target)){
				return;
			}
		}
		this.imageSelect[rowID].each(
			(
				function(id, index){
					this.showAddToBatchButton(true, id);
				}
			).bind(this)
		);
		
		var url = "ajax_class_creator.php";
		var params = "ajax_action=moveTo&ajax_class=tagedit" +
			"&selected=" + this.imageSelect[rowID] +
			"&target=" + target +
			"&targetType=" + targetType +
			"&page=" + this.pageNum[rowID] +
			"&pageSize=" + this.imagesPerPage[rowID] +
			"&batchID=" + batchID;
		this.imageSelect[rowID] = new Array;
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.showPage.bind(this),
				onFailure: this.failed.bind(this)
			}
		);
	},
	createBatch: function(title){
		$('BatchEditLoading').style.visibility = "visible";
		var title = $('batchImageToolNew').value;
		var url = "ajax_class_creator.php";
		var params = "ajax_action=createNew&ajax_class=tagedit" +
			"&title=" + encodeURIComponent(title) +
			"&buttons=" + this.addToBatchButtons;
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.initToBatch.bind(this),
				onFailure: this.failed.bind(this)
			}
		);
	},
	
	useBatch: function(batchID, pageNum){
		$('BatchEditLoading').style.visibility = 'visible';
		if(!batchID){
			var batchID = $('batchImageToolRecent').value;
		}
		if(!pageNum){
			pageNum = 0;
		}
		var url = "ajax_class_creator.php";
		var params = "ajax_action=loadBatch&ajax_class=tagedit" +
			"&batchID=" + batchID +
			"&page=" + pageNum +
			"&buttons=" + this.addToBatchButtons;
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.initToBatch.bind(this),
				onFailure: this.failed.bind(this)
			}
		);
	},
	initToBatch: function(req){
	
		var data = AjaxUtil.receiveArray(req.responseText);
		
		if(data.error == 1) {
			this.failed();
			return;
		}
	
		$('BatchEditLoading').style.visibility = 'hidden';
		if(data.problem && data.problem == 'batch deleted'){
		
			return;
		}
		
		var BatchEditTitle = $('BatchEditTitle');
		BatchEditTitle.innerHTML = data.title;
		var BatchEditDiv = $('BatchEditTabs');
		BatchEditDiv.innerHTML = data.tools;
		var batchID = Number(data.batchID);
		this.initializeImage(
				Number(data.initImage[0]),
				data.initImage[1],
				data.initImage[2],
				data.initImage[3],
				data.initImage[4],
				data.initImage[5],
				data.initImage[6],
				data.initImage[7],
				data.initImage[8],
				data.initImage[9]
			);
		data.initImageIDs.each(
			(
				function(ID, index){
					if(ID != 'empty'){
						this.initFileID(batchID, index, ID);
					}
				}
			).bind(this)
		);
		var rowID = this.rowIndex.indexOf(batchID);
		
		this.initializeOps(
				data.initOps[0],
				data.initOps[1],
				data.initOps[2]
			);
		
		data.initOpsTerms.each(
			(
				function(termOpPair, index){
					if(termOpPair[0] == 'toAdd'){
						this.initToAddTerm(batchID, termOpPair[1]);
					}else if(termOpPair[0] == 'toRemove'){
						this.initToRemoveTerm(batchID, termOpPair[1]);
					}else if(termOpPair[0] == 'common'){
						this.initCommonTerm(batchID, termOpPair[1]);
					}
				}
			).bind(this)
		);
		
		data.initTabs.each(
			(
			 	function(tabID, index){
					if(tabID != 'empty'){
						if(index == 0){
							Tabs.switchToTab(tabID);
						}else{
							Tabs.switchFromTab(tabID);
						}
					}
				}
			).bind(this)
		);
		
		this.showSelectCount(batchID);
		
		BatchEditDiv.style.display = 'inline';
		
		this.showBatchEdit(true);
		this.showAddToBatchButtons(true, data.addableIDs);
	},
	
	selectPage: function(batchID){
		rowID = this.rowIndex.indexOf(batchID);
		this.currentPageFileIDs[rowID].each(
			(
				function(fileID, index){
					if(this.imageSelect[rowID].indexOf(fileID) == -1){
						this.selectImage(batchID, index, fileID);
					}
				}
			).bind(this)
		);
	},
	deleteSelected: function(batchID){
		$('BatchEditLoading').style.visibility = 'visible';
		rowID = this.rowIndex.indexOf(batchID);
		if(!confirm('Delete selected images from this batch')){
			return;
		}
		target = '';
		targetType = 'delete';
		var url = "ajax_class_creator.php";
		var params = "ajax_action=moveTo&ajax_class=tagedit" +
			"&selected=" + this.imageSelect[rowID] +
			"&target=" + target +
			"&targetType=" + targetType +
			"&page=" + this.pageNum[rowID] +
			"&pageSize=" + this.imagesPerPage[rowID] +
			"&batchID=" + batchID;
		this.imageSelect[rowID] = new Array;
		
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.showPage.bind(this),
				onFailure: this.failed.bind(this)
			}
		);
	},
	refreshRecentBatches: function(batchID, data){
		var recentSelect = $('batchImageToolRecent');
		var recentSelectBatch = $('batchImageToolRecent_' + batchID);
		for (var i = recentSelect.length; i > 0; i--) {
			recentSelect.remove(i);
		}
		for (var i = recentSelectBatch.length; i > 0; i--) {
			recentSelectBatch.remove(i);
		}
 		data.each(
			(
				function(option, index){
					if(option[1] != batchID){				
						var newOption = document.createElement('option');
						newOption.text = option[0];
						newOption.value = option[1];
						
						var newOption2 = document.createElement('option');
						newOption2.text = option[0];
						newOption2.value = option[1];
						try {
							recentSelectBatch.add(newOption, null);
							recentSelect.add(newOption2, null);
						}catch(ex) {
							recentSelect.add(newOption);
							recentSelectBatch.add(newOption2);
						}
					}
				}
			).bind(this)
		);
	},
	initializeOps: function(batchIDIn, emptyDisambigXML, revisionNumber){
		var batchID = Number(batchIDIn);
		this.activeBatch = batchID;
 		rowID = this.rowIndex.indexOf(batchID);
		if(rowID == -1){
			this.rowIndex[this.rowIndex.length] = batchID;
	 		rowID = this.rowIndex.indexOf(batchID);
		}
		this.commonTerms[rowID] = new Array;
		this.disambigXML[rowID] = '';
		this.disambigEmptyXML = emptyDisambigXML;
		this.disambigTerms[rowID] = new Array;
		this.disambigRemovedTerms[rowID] = new Array;
		this.toAddTerms[rowID] = new Array;
		this.toRemoveTerms[rowID] = new Array;
		this.revisionNumber[rowID] = revisionNumber;
	},
	
	initCommonTerm: function(batchID, termID){
		rowID = this.rowIndex.indexOf(batchID);
		this.commonTerms[rowID].push(termID);
		if(this.toAddTerms[rowID].indexOf(termID) == -1 && this.toRemoveTerms[rowID].indexOf(termID) == -1){
			this.displayTerm(batchID, termID, true, 'common');
		}
	},
	initToAddTerm: function(batchID, termID){
		rowID = this.rowIndex.indexOf(batchID);
		this.toAddTerms[rowID].push(termID);
		this.displayTerm(batchID, termID, true, 'add');
		this.displayTerm(batchID, termID, false, 'common');
	},
	initToRemoveTerm: function(batchID, termID){
		rowID = this.rowIndex.indexOf(batchID);
		this.toRemoveTerms[rowID].push(termID);
		this.displayTerm(batchID, termID, true, 'remove');
		this.displayTerm(batchID, termID, false, 'common');
	},
	getMoreCommon: function(batchID){
		$('BatchEditLoading').style.visibility = 'visible';
		var url = "ajax_class_creator.php";
		var params = "ajax_action=getCommonTerms&ajax_class=tagedit" +
			"&common=" + this.commonTerms[rowID] +
			"&batchID=" + batchID;
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.storeCommonTerms.bind(this),
				onFailure: this.failed.bind(this)
			}
		);
	},
	storeCommonTerms: function(req){
   
   
    var data = AjaxUtil.receiveArray(req.responseText);
    if(data.error == 1) {
	  	this.failed();
		  return;
		}
		batchID = Number(data.batchID);
		rowID = this.rowIndex.indexOf(batchID);
		var container = $('batchOpsToolCommon_' + batchID);
		html = container.innerHTML;
		container.innerHTML = html + data.newCommonDisplay;
		
		if(data.newCommonTerms && data.newCommonTerms.length > 0){
			data.newCommonTerms.each(
				(
					function(termID, index){
						this.commonTerms[rowID].push(termID);
						if(this.toAddTerms[rowID].indexOf(termID) == -1 
							&& this.toRemoveTerms[rowID].indexOf(termID) == -1){
							this.displayTerm(batchID, termID, true, 'common');
						}
					}
				).bind(this)
			);
		}else if(data.newCommonTerms) {
			termID = data.newCommonTerms[1];
			
			this.commonTerms[rowID].push(termID);
			if(this.toAddTerms[rowID].indexOf() == -1 && this.toRemoveTerms[rowID].indexOf(termID) == -1){
				this.displayTerm(batchID, termID, true, 'common');
			}
		}
		$('BatchEditLoading').style.visibility = 'hidden';
	},
	setAddMoreCommon: function(batchID){
		rowID = this.rowIndex.indexOf(batchID);
		rawKeysBox = $('batchOpsToolAddMoreTags_' + batchID);
		rawKeysBox.value = TagDisambiguation.cleanKeys(rawKeysBox.value);
	
		rootTag = this.disambigEmptyXML.match(TagDisambiguation.assetTagListRegex);
	
		tagStart = "<tag tagid=\"\" lang=\"\" string=\"";
		tagEnd = "\"></tag>\n";
		csvRegex = "\\s*,\\s*";
		csvRegex = new RegExp(csvRegex, "gi");
		keys = rawKeysBox.value;
		keys = TagDisambiguation.entityEncode(keys);
		newTags = tagStart + keys.replace(csvRegex, tagEnd + tagStart) + tagEnd;
	
		this.disambigXML[rowID]= this.disambigEmptyXML.replace(TagDisambiguation.assetTagListRegex, rootTag[0] + '\n' + newTags);
		
	
		this.addMoreCommon(batchID);
	},
					 
	addMoreCommon: function(batchID){
		rowID = this.rowIndex.indexOf(batchID);
		
		$('batchOpsToolAddMoreBusy_' + batchID).style.visibility = 'visible';
		var url = "ajax_class_creator.php";
		var params = "ajax_action=addCommonTerms&ajax_class=tagedit" +
			"&common=" + this.commonTerms[rowID] +
			"&disambigXML=" + encodeURIComponent(this.disambigXML[rowID]) +
			"&batchID=" + batchID;
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.disambigCommonTerms.bind(this),
				onFailure: this.failed.bind(this)
			}
		);
	},
	disambigCommonTerms: function(req){
	
    var data = AjaxUtil.receiveArray(req.responseText);
    if(data.error == 1) {
	  	this.failed();
		  return;
		}
		batchID = Number(data.batchID);
		rowID = this.rowIndex.indexOf(batchID);
		$('batchOpsToolAddMoreBusy_' + batchID).style.visibility = 'hidden';
		this.disambigXML[rowID] = data.disambigXML;
		this.disambigTerms[rowID] = data.disambigTerms;
		this.disambigRemovedTerms[rowID] = new Array;
		this.showDisambig(batchID, data.disambigRows);
	},
	showDisambig: function(batchID, rows){
		opsDisambig = $('batchOpsToolDisambig_' + batchID);
		opsDisambigRows = $('batchOpsToolDisambigRows_' + batchID);
		opsTermsTable = $('batchOpsToolTermsTable_' + batchID);
		opsTermsTable.style.display = 'none';
		opsDisambigRows.innerHTML = rows;
		opsDisambig.style.display = 'block';
	},
	hideDisambig: function(batchID){
		opsDisambig = $('batchOpsToolDisambig_' + batchID);
		opsDisambigRows = $('batchOpsToolDisambigRows_' + batchID);
		opsTermsTable = $('batchOpsToolTermsTable_' + batchID);
		opsDisambigRows.innerHTML = '';
		opsDisambig.style.display = 'none';
		opsTermsTable.style.display = 'block';
		
	
	},
	cancelDisambig: function(batchID){
		rowID = this.rowIndex.indexOf(batchID);
		this.disambigXML[rowID] = '';
		this.disambigTerms[rowID] = '';
		this.disambigRemovedTerms[rowID] = '';
		this.hideDisambig(batchID);
	},
	saveDisambig: function(batchID){
		rowID = this.rowIndex.indexOf(batchID);
			
		this.disambigTerms[rowID].each(
			(
				function(termID, index){
          regexTerm = '<term((\\s+termid\\s*=\\s*("|\')' +
            termID +
            '\\3)|(\\s+chosen\\s*=\\s*("|\')(true|false)\\5)){2}\\s*(\\/)?\\>(.*?)\\</term\>\\s*';
						
				  regexTerm = new RegExp(regexTerm, "i");
					matches = this.disambigXML[rowID].match(regexTerm);
					if(matches != null && 
							this.toAddTerms[rowID].indexOf(termID) == -1 &&
							this.toRemoveTerms[rowID].indexOf(termID) == -1){
						this.addToCommmon(batchID, termID, matches[8]);
					}
				}
			).bind(this)
		);
		this.disambigXML[rowID] = '';
		this.disambigTerms[rowID] = '';
		this.disambigRemovedTerms[rowID] = '';
		this.hideDisambig(batchID);
	},
	disambigRemoveButton: function(batchID, tagid){
		rowID = this.rowIndex.indexOf(batchID);
 
   
    tagRegex = "\\<tag\\s*tagid=\"" + tagid + "\"\\s*lang=\"[^\"]*\"\\s*string=\"[^\"]*\"\\>(.|\\n)*?\\<\\/tag\\>";
    tagRegex = new RegExp(tagRegex, "gi");
		this.disambigRemovedTerms[rowID][tagid] = this.disambigXML[rowID].match(tagRegex);
		this.disambigXML[rowID] = this.disambigXML[rowID].replace(tagRegex, '');
	
		tagTD = $('minusTD_' + tagid);
		tagTD.innerHTML = '<img src="images/buttons/plussign.gif" onclick="BatchTagEdit.disambigUnremoveButton(' + batchID + ',\'' + tagid + '\');" style="cursor: pointer;">';
		tagTD = $('tagTD_' + tagid);
		tagTD.innerHTML = '<div style="text-decoration: line-through;">' + tagTD.innerHTML + '</div>';
		tagTD = $('langTD_' + tagid);
		tagTD.innerHTML = '<div style="text-decoration: line-through;">' + tagTD.innerHTML + '</div>';
		tagTD = $('termsTD_' + tagid);
		tagTD.style.visibility = 'hidden';
	},
  disambigUnremoveButton: function(batchID, tagid){
		rowID = this.rowIndex.indexOf(batchID);
		
	
		rootTag = this.disambigXML[rowID].match(TagDisambiguation.assetTagListRegex);
		this.disambigXML[rowID] = this.disambigXML[rowID].replace(TagDisambiguation.assetTagListRegex, rootTag[0] 
				+ '\n' + this.disambigRemovedTerms[rowID][tagid]);
		divRegex = /\<div style="text-decoration: line-through;?"\>/i;
		divRegex2 = /\<\/div\>/;
		tagTD = $('minusTD_' + tagid);
		tagTD.innerHTML = '<img src="images/buttons/minussign.gif" onclick="BatchTagEdit.disambigRemoveButton(' +
			batchID + ',\'' + tagid + '\');" style="cursor: pointer;">';
		tagTD = $('tagTD_' + tagid);
		html = tagTD.innerHTML
		html = html.replace(divRegex, '');
		html = html.replace(divRegex2, '');
		tagTD.innerHTML = '';
		tagTD.innerHTML = html;
		tagTD = $('langTD_' + tagid);
		html = tagTD.innerHTML
		html = html.replace(divRegex, '');
		html = html.replace(divRegex2, '');
		tagTD.innerHTML = html;
		tagTD = $('termsTD_' + tagid);
		tagTD.style.visibility = 'visible';
	},
	disambigSpellingChange:function(batchID, tagid, newTag){
	
		rowID = this.rowIndex.indexOf(batchID);
		rootTag = this.disambigXML[rowID].match(TagDisambiguation.assetTagListRegex);
	
		tagRegex = "\\<tag\\s*tagid=\"" + tagid + "\"\\s*lang=\"[^\"]*\"\\s*string=\"([^\"]*)\"\\>(.|\\n)*?\\<\\/tag\\>";
		tagRegex = new RegExp(tagRegex, "i");
		match = this.disambigXML[rowID].match(tagRegex);
	
		if(typeof(match) == 'object' && match[1] == newTag){
		
			addTag = " newtag=\"true\"";
		}else{
			addTag = "";
		}
		tagStart = "<tag tagid=\"\" " + addTag + " lang=\"" + rootTag[1] + "\" string=\"";
		tagEnd = "\"></tag>\n";
		this.disambigXML[rowID] = this.disambigXML[rowID].replace(tagRegex, tagStart + TagDisambiguation.entityEncode(newTag) + tagEnd);
	
		this.addMoreCommon(batchID);
	},
	disambigLangSelect: function(batchID, tagid, lang){
	
		rowID = this.rowIndex.indexOf(batchID);
	
		tagRegex = "(\\<tag\\s*tagid=\"" + tagid + "\"\\s*lang=\")[^\"]*";
		tagRegex = new RegExp(tagRegex, "i");
		this.disambigXML[rowID] = this.disambigXML[rowID].replace(tagRegex, '$1' + lang);
	
		this.addMoreCommon(batchID);
	},
	disambigBoxCheck: function(batchID, tagid, termid, checked){
	
		chosen = 'false';
		if(checked){
			chosen = 'true';
			this.disambigTerms.push(termid);
		}else{
			this.disambigTerms[rowID].splice(this.disambigTerms[rowID].indexOf(termid), 1);
		}
	
		tagRegex = "(\\<tag\\s*tagid=\"" + tagid + "\"\\s*lang=\"[^\"]*\"\\s*string=\"[^\"]*\"\\>(.|\\n)*?\\<term\\s*termid=\"" +
			termid + "\"\\s*chosen=\")(true|false)";
		
		tagRegex = new RegExp(tagRegex, "i");
		this.disambigXML[rowID] = this.disambigXML[rowID].replace(tagRegex, '$1' + chosen);
	},
	delToAdd: function(batchID, termID){
		rowID = this.rowIndex.indexOf(batchID);
		if(this.displayTerm(batchID, termID, false, 'add')){
			this.toAddTerms[rowID].splice(this.toAddTerms[rowID].indexOf(termID), 1);
			this.opsUpdate(batchID, 'delToAdd', termID);
		}
		inRemove = this.toRemoveTerms[rowID].indexOf(termID);
		
		if(inRemove == -1){
			this.displayTerm(batchID, termID, true, 'common');
		}
	},
	delToRemove: function(batchID, termID){
		rowID = this.rowIndex.indexOf(batchID);
		if(this.displayTerm(batchID, termID, false, 'remove')){
			this.toRemoveTerms[rowID].splice(this.toRemoveTerms[rowID].indexOf(termID), 1);
			this.opsUpdate(batchID, 'delToRemove', termID);
		}
		inAdd = this.toAddTerms[rowID].indexOf(termID);
		if(inAdd == -1){
			this.displayTerm(batchID, termID, true, 'common');
		}
	},
	addToCommmon: function(batchID, termID, prefSyn){
		if(!this.displayTerm(batchID, termID, true, 'common')){
			var newTerm = '<div ' +
				'id="batchOpsToolCommonTerm' + termID + '_' + batchID + '" ' +
					'class="left" ' +
					'style="' +
						'width: 150px; ' +
						'display: block; ' +
				'">' +
				'<img src="images/buttons/minussign.gif" ' +
					'onclick="BatchTagEdit.addToRemove(' + batchID + ',\'' + termID + '\')"' +
				'>' +
				'<img src="images/buttons/plussign.gif" ' +
					'onclick="BatchTagEdit.addToAdd(' + batchID + ',\'' + termID + '\')"' +
				'>' +
				'<div ' +
					'id="batchOpsToolCommonLabel' + termID + '_' + batchID + '" ' +
					'style="' +
						'display: inline; ' +
					'"' +
				'>' +
				prefSyn +
				'</div>' +
				'</div>';
			var commonDiv = $('batchOpsToolCommon_' + batchID);
			commonDiv.innerHTML = newTerm + commonDiv.innerHTML;
		}
	},
	addToAdd: function(batchID, termID){
		rowID = this.rowIndex.indexOf(batchID);
		this.displayTerm(batchID, termID, false, 'common');
		if(!this.displayTerm(batchID, termID, true, 'add')){
			var lable = $('batchOpsToolCommonLabel' + termID + '_' + batchID).innerHTML;
			var toAddDiv = $('batchOpsToolToAdd_' + batchID);
			
			existingAdd = '<div ' +
				'id="batchOpsToolToAddTerm' + termID + '_' + batchID + '" ' +
				'class="left" style="width: 150px;">' + 
				'<img src="images/buttons/minussign.gif" ' + 
				'onclick="BatchTagEdit.delToAdd(' + batchID + ',\'' + termID + '\')">' +
				lable + '</div>';
			toAddDiv.innerHTML = toAddDiv.innerHTML + existingAdd;
		}
		
		this.toAddTerms[rowID].push(termID);
		this.opsUpdate(batchID, 'addToAdd', termID);
		this.delToRemove(batchID, termID);
	},
	addToRemove: function(batchID, termID){
		rowID = this.rowIndex.indexOf(batchID);
		this.displayTerm(batchID, termID, false, 'common');
		if(!this.displayTerm(batchID, termID, true, 'remove')){
			var lable = $('batchOpsToolCommonLabel' + termID + '_' + batchID).innerHTML;
			var toRemoveDiv = $('batchOpsToolToRemove_' + batchID);
			
			existingRemove = '<div ' +
				'id="batchOpsToolToRemoveTerm' + termID + '_' + batchID + '" ' +
				'class="left" style="width: 150px;">' + 
				'<img src="images/buttons/minussign.gif" ' + 
				'onclick="BatchTagEdit.delToRemove(' + batchID + ',\'' + termID + '\')">' +
				lable + '</div>';
			toRemoveDiv.innerHTML = toRemoveDiv.innerHTML + existingRemove;
		}
		this.toRemoveTerms[rowID].push(termID);
		this.opsUpdate(batchID, 'addToRemove', termID);
		this.delToAdd(batchID, termID);
	},
	displayTerm: function(batchID, termID, show, group){
		var divName = 'batchOpsTool';
		if(group == 'common'){
			divName = divName + 'CommonTerm';
		}else if(group == 'add'){
			divName = divName + 'ToAddTerm';
		}else if(group == 'remove'){
			divName = divName + 'ToRemoveTerm';
		}else{
			return false;
		}
		divName = divName + termID + '_' + batchID;
		var theDiv = $(divName);
		if(typeof(theDiv) != 'object' || theDiv == null){
			return false;
		}
		if(show){
			theDiv.style.display = 'block';
		}else{
			theDiv.style.display = 'none';
		}
		return true;
	},
	opsUpdate: function(batchID){
		rowID = this.rowIndex.indexOf(batchID);
		
		this.revisionNumber[rowID]++;
		var url = "ajax_class_creator.php";
		var params = "ajax_action=opsUpdate&ajax_class=tagedit" +
			"&toAdd=" + this.toAddTerms[rowID] +
			"&toRemove=" + this.toRemoveTerms[rowID] +
			"&revisionNumber=" + this.revisionNumber[rowID] +
			"&batchID=" + batchID;
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.opsUpdated.bind(this),
				onFailure: this.failed.bind(this)
			}
		);
	},
	
	opsUpdated: function(req){
	
		var data = AjaxUtil.receiveArray(req.responseText);
		
		if(data.error == 1) {
			this.failed();
			return;
		}
	},
	save: function(batchID){
		rowID = this.rowIndex.indexOf(batchID);
		
		var url = "ajax_class_creator.php";
		var params = "ajax_action=saveBatch&ajax_class=tagedit" +
			"&batchID=" + batchID;
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.resetBatchMode.bind(this),
				onFailure: this.failed.bind(this)
			}
		);
	},
	deleteBatch: function(batchID){
		rowID = this.rowIndex.indexOf(batchID);
		
		var url = "ajax_class_creator.php";
		var params = "ajax_action=deleteBatch&ajax_class=tagedit" +
			"&batchID=" + batchID;
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.resetBatchMode.bind(this),
				onFailure: this.failed.bind(this)
			}
		);
	},
	resetBatchMode: function(req){
	
		var data = AjaxUtil.receiveArray(req.responseText);
		if(data.error == 1){
			this.failed;
			return;
		}
		$('BatchEditTabs').innerHTML = data.tools;
		$('BatchEditTitle').innerHTML = data.title;
		rowID = this.rowIndex.indexOf(Number(data.batchID));
		this.activeBatch = 0; 
		this.rowIndex[rowID] = new Array;
		this.imageSelect[rowID] = new Array;
		this.pageNum[rowID] = 0;
		this.totalPages[rowID] = 0;
		this.nextPage[rowID] = new Array;
		this.nextPageFileIDs[rowID] = new Array;
		this.prevPage[rowID] = new Array;
		this.prevPageFileIDs[rowID] = new Array;
		this.currentPageFileIDs[rowID] = new Array;
		this.selectDisabled[rowID] = false;
		this.commonTerms[rowID] = new Array;
		this.toAddTerms[rowID] = new Array;
		this.toRemoveTerms[rowID] = new Array;
		this.revisionNumber[rowID] = 0;
		this.addToBatchButtons.each(
			(
				function(id, index){
					this.showAddToBatchButton(false, id);
				}
			).bind(this)
		);
	},
	cancel: function(){
		this.showBatchEdit(false);
	},
	endBatchMode: function(req){
	
		var data = AjaxUtil.receiveArray(req.responseText);
		
		if(data.error == 1) {
			this.failed();
			return;
		}
		$('BatchEditTabs').innerHTML = data.tools
	},
	showTitleTool: function(batchID){
		$('batchInfoToolTitle_' + batchID).style.display = 'none';
		$('batchInfoToolTitleTool_' + batchID).style.display = 'inline';
	},
	saveTitle: function(batchID){
		rowID = this.rowIndex.indexOf(batchID);
		titleText = $('batchInfoToolTitleToolText_' + batchID);
		
		var url = "ajax_class_creator.php";
		var params = "ajax_action=saveBatchTitle&ajax_class=tagedit" +
			"&title=" + encodeURIComponent(titleText.value) +
			"&batchID=" + batchID;
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.saveTitleResponse.bind(this),
				onFailure: this.failed.bind(this)
			}
		);
	},
	saveTitleResponse: function(req){
    var data = AjaxUtil.receiveArray(req.responseText);
    if(data.error == 1) {
	  	this.failed();
		  return;
		}
		batchID = Number(data.batchID);
		var infoTitle = $('batchInfoToolTitle_' + batchID);
		var title = $('BatchEditTitle');
		
		infoTitle.innerHTML = data.title;
		title.innerHTML = data.title;
		
		
		this.hideTitleTool(batchID);
	},
	hideTitleTool: function(batchID){
		var title = $('batchInfoToolTitle_' + batchID);
		var titleTool = $('batchInfoToolTitleTool_' + batchID);
		var titleText = $('batchInfoToolTitleToolText_' + batchID);
		titleText.value = title.innerHTML;
		title.style.display = 'inline';
		titleTool.style.display = 'none';
	},
	
	showCommentsTool: function(batchID){
		$('batchInfoToolComments_' + batchID).style.display = 'none';
		$('batchInfoToolCommentsTool_' + batchID).style.display = 'inline';
	},
	saveComments: function(batchID){
		rowID = this.rowIndex.indexOf(batchID);
		commentsText = $('batchInfoToolCommentsToolText_' + batchID);
		
		var url = "ajax_class_creator.php";
		var params = "ajax_action=saveBatchComments&ajax_class=tagedit" +
			"&comments=" + encodeURIComponent(commentsText.value) +
			"&batchID=" + batchID;
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.saveCommentsResponse.bind(this),
				onFailure: this.failed.bind(this)
			}
		);
	},
	saveCommentsResponse: function(req){
    var data = AjaxUtil.receiveArray(req.responseText);
    if(data.error == 1) {
	  	this.failed();
		  return;
		}
		batchID = Number(data.batchID);
		var comments = $('batchInfoToolComments_' + batchID);
		comments.innerHTML = data.comments;
		this.hideCommentsTool(batchID);
	},
	hideCommentsTool: function(batchID){
		var comments = $('batchInfoToolComments_' + batchID);
		var commentsTool = $('batchInfoToolCommentsTool_' + batchID);
		var commentsText = $('batchInfoToolCommentsToolText_' + batchID);
		commentsText.value = comments.innerHTML;
		comments.style.display = 'inline';
		commentsTool.style.display = 'none';
	},
	showNotifyTool: function(batchID){
		$('batchInfoToolNotify_' + batchID).style.display = 'none';
		$('batchInfoToolNotifyTool_' + batchID).style.display = 'inline';
	},
	saveNotify: function(batchID){
		rowID = this.rowIndex.indexOf(batchID);
		notifyText = $('batchInfoToolNotifyToolSelect_' + batchID);
		
		var url = "ajax_class_creator.php";
		var params = "ajax_action=saveBatchNotify&ajax_class=tagedit" +
			"&notify=" + encodeURI(notifyText.value) +
			"&batchID=" + batchID;
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.saveNotifyResponse.bind(this),
				onFailure: this.failed.bind(this)
			}
		);
	},
	saveNotifyResponse: function(req){
    var data = AjaxUtil.receiveArray(req.responseText);
    if(data.error == 1) {
	  	this.failed();
		  return;
		}
		batchID = Number(data.batchID);
		var notify = $('batchInfoToolNotify_' + batchID);
		notify.innerHTML = data.notifyLabel;
		this.hideNotifyTool(batchID);
	},
	hideNotifyTool: function(batchID){
		var notify = $('batchInfoToolNotify_' + batchID);
		var notifyTool = $('batchInfoToolNotifyTool_' + batchID);
		var notifyText = $('batchInfoToolNotifyToolSelect_' + batchID);
		notifyText.value = notify.innerHTML;
		notify.style.display = 'inline';
		notifyTool.style.display = 'none';
	},
	showStatusTool: function(batchID){
		$('batchInfoToolStatus_' + batchID).style.display = 'none';
		$('batchInfoToolStatusTool_' + batchID).style.display = 'inline';
	},
	saveStatus: function(batchID){
		rowID = this.rowIndex.indexOf(batchID);
		statusText = $('batchInfoToolStatusToolSelect_' + batchID);
		var url = "ajax_class_creator.php";
		var params = "ajax_action=saveBatchStatus&ajax_class=tagedit" +
			"&status=" + encodeURI(statusText.value) +
			"&batchID=" + batchID;
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.saveStatusResponse.bind(this),
				onFailure: this.failed.bind(this)
			}
		);
	},
	saveStatusResponse: function(req){
	
    var data = AjaxUtil.receiveArray(req.responseText);
    if(data.error == 1) {
	  	this.failed();
		  return;
		}
		batchID = Number(data.batchID);
		var status = $('batchInfoToolStatus_' + batchID);
		status.innerHTML = data.statusLabel;
		this.hideStatusTool(batchID);
	},
	hideStatusTool: function(batchID){
		var status = $('batchInfoToolStatus_' + batchID);
		var statusTool = $('batchInfoToolStatusTool_' + batchID);
		var statusText = $('batchInfoToolStatusToolSelect_' + batchID);
		statusText.value = status.innerHTML;
		status.style.display = 'inline';
		statusTool.style.display = 'none';
	},
	showBatchEdit: function(show){
		if(show){
			$('BatchEdit').style.display = 'inline';
			Droppables.add('BatchEdit', {onDrop:BatchTagEdit.imageDrop})
			this.rememberBatch(this.activeBatch);
			this.showAddToBatchButtons(true);
			this.loadAddableButtons(this.activeBatch);
		}else{
			Droppables.remove('BatchEdit');
			$('BatchEdit').style.display = 'none';
			this.rememberBatch(-1);
			this.showAddToBatchButtons(false);
		}
	},
	loadAddableButtons: function(batchID){
		if(batchID < 1){
			return;
		}
		var url = "ajax_class_creator.php";
		var params = "ajax_action=getAddable&ajax_class=tagedit" +
			"&batchID=" + batchID +
			"&buttons=" + this.addToBatchButtons;
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.showAddableButtons.bind(this),
				onFailure: this.failed.bind(this)
			}
		);
	},
	showAddableButtons: function(req){
	
    var data = AjaxUtil.receiveArray(req.responseText);
    if(data.error == 1) {
	  	this.failed();
		  return;
		}
		batchID = Number(data.batchID);
		this.showAddToBatchButtons(true, data.addableIDs);
	},
	imageDrop: function(imageElement){
		matches = imageElement.id.match(/subimageThumb_(\d+)/);
		if(matches[1] != null){
			BatchTagEdit.addImage(matches[1]);
		}
	},
						 
	showAddToBatchButtons: function(show, buttonIDs){
		this.addToBatchButtons.each(
			(
				function(id, index){
					element = $('addToLightBoxButton_' + id + '__');
					if(element){
						if(show){
							element.style.display = 'none';
						}else{
							element.style.display = 'inline';
						}
					}
				}
			).bind(this)
		);
		if(show){
			$('BatchEditStart').style.display = 'none';	
		}else{
			$('BatchEditStart').style.display = 'inline';	
		}
		if(show){
			if(buttonIDs && buttonIDs.length > 0){
				this.addToBatchButtons.each(
					(
						function(id, index){
							if(buttonIDs.indexOf(id.toString()) > -1){
								this.showAddToBatchButton(true, id);
							}else{
								this.showAddToBatchButton(false, id);
							}
						}
					).bind(this)
				);
			}
		}else{
			addToBatchButtons = document.getElementsByClassName('batchEditAdd');
			addToBatchButtons.each(
				(
					function(button, index){
						button.style.display = 'none';
					}
				).bind(this)
			);
		}
	},
	showAddToBatchButton: function(show, buttonID){
		var button = $('batchEditAddButton_' + buttonID);
		if(button){
			if(show){
				button.style.display = 'inline';
			}else{
				button.style.display = 'none';
			}
		}
	},
	initDraggables: function(delay){
		return;
		if(delay){
			if(this.draggables.length > 0){
				this.draggables.each(
					(
						function(elementID, index){
							new SubsDraggable(elementID,{dragelement:getDragElement,change:hidetrail});
						}
					).bind(this)
				);
			}
		}else{
			window.setTimeout('BatchTagEdit.initDraggables(false)',6000);
		}
	},
									
	initDraggable: function(id){
		return;
		this.draggables.push(id);
	},
	initNavBar: function(
			Items_Total,
			Items_Per_Page,
			CurrentPage,
			NavLink){
		
		this.navBarVars.Items_Total = Items_Total;
		this.navBarVars.Items_Per_Page = Items_Per_Page;
		this.navBarVars.CurrentPage = CurrentPage;
		this.navBarVars.NavLink = NavLink;
	},
	getNavBar: function(){
		var url = "ajax_class_creator.php";
		var cleanNavLink = this.navBarVars.NavLink;
		cleanNavLink = encodeURIComponent(cleanNavLink);
    cleanNavLink = cleanNavLink.replace(/&/g, '%26');
	  cleanNavLink = cleanNavLink.replace(/=/g, '%3D');
	  cleanNavLink = cleanNavLink.replace(/\?/g, '%3F');
		var params = "ajax_action=getNavBar&ajax_class=tagedit" +
			"&Items_Total=" + this.navBarVars.Items_Total +
			"&Items_Per_Page=" + this.navBarVars.Items_Per_Page +
			"&CurrentPage=" + this.navBarVars.CurrentPage +
			"&NavLink=" + cleanNavLink + '';
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.showNavBar.bind(this),
				onFailure: this.failed.bind(this)
			}
		);
	},
	showNavBar: function(req){
    var data = AjaxUtil.receiveArray(req.responseText);
    if(data.error == 1) {
	  	this.failed();
		  return;
		}
		var navBarDivs = document.getElementsByClassName('navBar');
		navBarDivs.each(
			(
				function(aNavBarDiv, index){
					aNavBarDiv.innerHTML = data.navBar;
				}
			).bind(this)
		);
	},
	showIDs: function(batchID){
	  rowID = this.rowIndex.indexOf(batchID);
    alert(this.currentPageFileIDs[rowID]);
	},
	dummyFunction: function(){
		alert('called');
	}
}
var IS_TagHint = Class.create();
IS_TagHint.prototype = {
	name: 'IS_TagHint', 
	_tagHintCache: {},
	_lookupHistory: {},
	_currentLookup: '',
	_currentHintData: new Array(),
	_hintDataIndexes: {},
	_hintLinkIndexes: {},
	_iframeID: '',
	_iframeAdded: false,
	initialize: function(options) {
		this.options = {
		
		
		
		
		
		
			autoRequestHints: true,
			requestStaticHints: true,
			defaultLanguage: 'EN_US',
			groupByTermID: true,
			setTextDisambiguationOnSelect: true,
			defaultPartialTagLookupLength: 3
		};
		Object.extend(this.options, options || { });
		this._iframeID = "iframe_" + this.options.textHintBoxID;
	},
	failed: function(req) {
	
		return false;
	},
	dummy: function(){
		return false;
	},
	getEventKeynum: function(e){
		var keynum;
		if(e && e.which) {
			keynum=e.which;
	
	
		} else {
			e=event;
			keynum=e.keyCode;
		}
		return keynum;
	},

	getHintsFromPartialTagOnKeydown: function(e){
		var keynum = this.getEventKeynum(e);
		if ( keynum == 40 || keynum == 38 || keynum == 13 ){
			keychar = String.fromCharCode(keynum);
		
			if ( keynum == 40 ){
				this.selectNextHint();
				return true;
			}
			if ( keynum == 38 ){
				this.selectPreviousHint();
				return true;
			}
			if ( keynum == 13 ){
				this.setTextDisambiguationFromSelectedHint()
				return true;
			}
		}
		return false;
	},
	getHintsFromPartialTagOnKeyup: function(e){
		var keynum = this.getEventKeynum(e);
		if ( keynum == 40 || keynum == 38 || keynum == 13 ){
			return false;
		}
	
		return this.getHintsFromPartialTag();
	},
	getHintsFromPartialTag: function(partialTag, language){
	
		partialTagLookupLength = this.options.defaultPartialTagLookupLength;
	
		if ( !partialTag ){
			var textField = $(this.options.textFieldID);
			partialTag = textField.value.toLowerCase();
		}
	
		if ( !language ){
			language = this.options.defaultLanguage;
			if ( this.options.languageFieldID !== '' ){
				var languageField = $(this.options.languageFieldID);
				if ( languageField ){
					if ( languageField.value ){
						language = languageField.value;
					}
				}
			}
		}
		partialTagLength = partialTag.length;
		partialCount = Math.floor(partialTag.length/partialTagLookupLength);
		partialTagStart = partialTag.substring(0, partialCount*partialTagLookupLength);
		if ( partialTagStart.length < partialTagLookupLength ){
			return false
		}
		return this.requestHintsFromPartialTag(partialTagStart, language);
	},
	requestHintsFromPartialTag: function(partialTagStart, language){
	
		if ( this._tagHintCache[language] && this._tagHintCache[language][partialTagStart] ){
			this.showHintsForPartialTag(this._tagHintCache[language][partialTagStart]);
			return true;
		}
	
	
	
		if ( this._lookupHistory[partialTagStart] ){
			this._currentLookup = partialTagStart;
		
			this.showLoadingBox();
			return false;
		}
		this._lookupHistory[partialTagStart] = true;
	
	
	
		if ( this._currentLookup == partialTagStart ){
			return false;
		}
		this._currentLookup = partialTagStart;
	
		this.showLoadingBox();
	
	
	
		var url, params;
		if ( this.options.requestStaticHints == true ){
			var page;
			if ( this.options.groupByTermID ){
				page = 'term_hint';
			} else {
				page = 'tag_hint';
			}
			url = page + "/" + encodeURIComponent(language) + "/" + encodeURIComponent(partialTagStart) + ".txt";
			params = "";
		} else {
		
			url = "ajax_class_creator.php";
			params = "ajax_action=getHintsFromPartialTag&ajax_class=taghint" +
				"&language=" + language +
				"&partialTag=" + partialTag +
				"&groupByTermID=" + (groupByTermID?1:0) +
				"";
		}
	
		var myAjax = new Ajax.Request
			(
				url, 
				{ 
					method: "get", 
					parameters: params,
					onComplete: this.requestHintsFromPartialTagComplete.bind(this),
					onFailure: this.failed.bind(this)
				}
			);
		return true;
	},
	requestHintsFromPartialTagComplete: function(req){
	
		var data = AjaxUtil.receiveArray(req.responseText);
		if ( typeof data != 'object' ){
			return false;
		}
	
		if ( !data.pTS || !data.l ){
			return false;
		}
	
		if ( typeof this._tagHintCache[data.l] != 'object' ){
			this._tagHintCache[data.l] = {};
		}
		this._tagHintCache[data.l][data.pTS] = data;
	
	
		if ( data.pTS != this._currentLookup ){
			return false;
		}
	
		this.hideLoadingBox();
	
		this._currentLookup = '';
	
		return this.showHintsForPartialTag(this._tagHintCache[data.l][data.pTS]);
	},
	showHintsForPartialTag: function(hintData){
		this.hideLoadingBox();
		var textHintBox = $(this.options.textHintBoxID);
		var textField = $(this.options.textFieldID);
		var hintID, anchorElement, textNode;
		if(hintData.tHs && hintData.tHs.length > 0){
			var hintLinks = new Array();
			var usedHints = {};
			this._currentHintData = hintData;
			this._hintDataIndexes = {};
			this._hintLinkIndexes = {};
		
		
		
		
		
			var toDisplay = 'txt';
			if ( this.options.textDisambiguationFieldID != '' ){
				toDisplay = 'la';
			}
			var synonyms = new Array();
			var label = '';
			for ( var i=0; i<hintData.tHs.length; i++ ){
				this._currentHintData.tHs[i].index = null;
				this._currentHintData.tHs[i].hintID = null;
				synonyms = new Array();
				if ( this.options.groupByTermID && hintData.tHs[i].s && hintData.tHs[i].s.length > 0 ){
					for ( var s=0; s<hintData.tHs[i].s.length; s++ ){
						if ( hintData.tHs[i].s[s].toLowerCase().indexOf(textField.value.toLowerCase()) === 0 ){
							synonyms[synonyms.length] = hintData.tHs[i].s[s];
						}
					}
					if ( synonyms.length == 0 ){
						continue;
					}
				} else {
					if ( hintData.tHs[i][toDisplay].toLowerCase().indexOf(textField.value.toLowerCase()) !== 0 ){
						continue;
					}
					synonyms[synonyms.length] = hintData.tHs[i][toDisplay];
				}
				if ( usedHints[hintData.tHs[i][toDisplay].toLowerCase()] ){
					continue;
				}
				usedHints[hintData.tHs[i][toDisplay].toLowerCase()] = true;
				this._currentHintData.tHs[i].index = i;
				this._currentHintData.tHs[i].hintID = 'SearchBarTextHintLink_' + i;
				label = '';
				if ( synonyms.length > 0 && synonyms[0].toLowerCase().replace(/ /, '').indexOf(hintData.tHs[i].txt.toLowerCase().replace(/ /, '')) !== 0 ){
					label += synonyms[0];
					label += '<i style="color: #999999;"> ..' + hintData.tHs[i][toDisplay] + '</i>';
				} else {
					label = hintData.tHs[i][toDisplay];
				}
				link = '<a id="' + this._currentHintData.tHs[i].hintID + '" class="TH_HintLink" ' +
					'style="display: block; white-space: nowrap; color: #000000;" ' +
					'href="javascript:void(0);"' +
					'title="' + synonyms.join(", ").replace(/"/, '%22') + '"' +
					'>' + label + '</a>';
				hintLinks[hintLinks.length] = link;
				this._hintDataIndexes[this._currentHintData.tHs[i].hintID] = i;
				this._hintLinkIndexes[this._currentHintData.tHs[i].hintID] = hintLinks.length-1;
				if ( hintLinks.length > 20 ){
					break;
				}
			}
		
			if ( hintLinks.length == 0 ){
				this.resetHintBox();
				return false;
			}
		
			textHintBox.innerHTML = hintLinks.join("\n");
		
		
		
			textHintBox.style.display = "block";
			if ( this._iframeAdded == false ){
				iframeElement = document.createElement("iframe");
				iframeElement.id = this._iframeID;
				iframeElement.style.position = "absolute";
				iframeElement.style.zIndex = getCurrentStyle(textHintBox, "z-index") - 1;
				iframeElement.style.border = "0px";
				iframeElement.style.top = getCurrentStyle(textHintBox, "top");
				iframeElement.style.left = getCurrentStyle(textHintBox, "left");
				iframeElement.style.backgroundColor = "#ffffff";
				textHintBox.parentNode.insertBefore(iframeElement, textHintBox);
				this._iframeAdded = true;
			}
			var iframe = $(this._iframeID);
			iframe.style.display = "block";
			iframe.style.width = textHintBox.getWidth() + "px";
			iframe.style.height = textHintBox.getHeight() + "px";
		
			var tagHint;
			for ( var hintID in this._hintDataIndexes ){
				tagHint = {'tagHint':this, 'hintDataIndex':this._hintDataIndexes[hintID]}
				$(hintID).onclick = this._setTextDisambiguationFromHintDummy.bind(tagHint);
			}
		} else {
			this.resetHintBox();
		}
		return true;
	},
	_setTextDisambiguationFromHintDummy: function(){
		return this.tagHint.setTextDisambiguationFromHint(this.hintDataIndex);
	},
	setTextDisambiguationFromHint: function(hintDataIndex, dontHideHints){
		var textHintBox = $(this.options.textHintBoxID);
		var textField = $(this.options.textFieldID);
		if ( this.options.textDisambiguationFieldID != '' ){
			textField.value = this.quotePhrase(this._currentHintData.tHs[hintDataIndex].txt);
			var textDisambiguationField = $(this.options.textDisambiguationFieldID);
			textDisambiguationField.value = Object.toJSON(this._currentHintData.tHs[hintDataIndex].tDa);
			if ( typeof this.options.textDisambiguationCallback == 'function' ){
				this.options.textDisambiguationCallback(this._currentHintData.tHs[hintDataIndex].tDa);
			}
		} else {
			textField.value = this.quotePhrase(this._currentHintData.tHs[hintDataIndex].la);
		}
		if ( !dontHideHints ){
			this.resetHintBox();
		}
		return true;
	},
	quotePhrase: function(text){
		if ( text.match(/ /) ){
			return '"' + text + '"';
		} else {
			return text;
		}
	},
	setTextDisambiguationFromSelectedHint: function(){
		var hintID = this.getSelectedHintID();
		if ( !hintID ){
			return false;
		}
		var hintDataIndex = this.getTagHintDataIndexFromHintID(hintID);
		if ( hintDataIndex == -1 ){
			return false;
		}
		return this.setTextDisambiguationFromHint(hintDataIndex);
	},
	getTagHintDataIndexFromHintID: function(hintID){
		if ( typeof this._hintDataIndexes[hintID] == 'number' && this._hintDataIndexes[hintID] > -1 ){
			return this._hintDataIndexes[hintID];
		} else {
			return -1;
		}
	},
	selectNextHint: function(){
		return this.changeSelectedHint(1);
	},
	selectPreviousHint: function(){
		return this.changeSelectedHint(-1);
	},
	changeSelectedHint: function(indexDelta){
		var textHintBox = $(this.options.textHintBoxID);
		var linkElems = textHintBox.getElementsByClassName("TH_HintLink");
		var	selectedIndex = this.getSelectedHintIndex();
		var newSelectedIndex = -1;
		if ( selectedIndex > -1 && linkElems[selectedIndex] ){
		
			if ( linkElems[selectedIndex + indexDelta] ){
				linkElems[selectedIndex].selected = false;
				linkElems[selectedIndex].style.backgroundColor = "transparent";
				newSelectedIndex = selectedIndex + indexDelta;
				linkElems[newSelectedIndex].style.backgroundColor = "#e3e3e3";
				linkElems[newSelectedIndex].selected = true;
				if ( this.options.setTextDisambiguationOnSelect ){
					this.setTextDisambiguationFromHint(this.getTagHintDataIndexFromHintID(linkElems[newSelectedIndex].id), true);
				}
			} 
	
		} else if ( newSelectedIndex == -1 && linkElems[0] ){
			newSelectedIndex = 0
			linkElems[newSelectedIndex].style.backgroundColor = "#e3e3e3";
			linkElems[newSelectedIndex].selected = true;
			if ( this.options.setTextDisambiguationOnSelect ){
				this.setTextDisambiguationFromHint(this.getTagHintDataIndexFromHintID(linkElems[newSelectedIndex].id), true);
			}
		}
		return newSelectedIndex;
	},
	getSelectedHintIndex: function(){
		var textHintBox = $(this.options.textHintBoxID);
		var linkElems = textHintBox.getElementsByClassName("TH_HintLink");
		for ( var i=0; i<linkElems.length; i++ ){
			if ( linkElems[i].selected == true ){
				return i;
			}
		}
		return -1
	},
	getSelectedHintID: function(){
		var	selectedIndex = this.getSelectedHintIndex();
		if ( selectedIndex == -1 ){
			return false;
		}
		var textHintBox = $(this.options.textHintBoxID);
		var linkElems = textHintBox.getElementsByClassName("TH_HintLink");
		if ( linkElems[selectedIndex] ){
			return linkElems[selectedIndex].id;
		}
		return false;
		
	},
	resetHintBox: function (delay){
		var timeout = 0;
		if ( typeof delay == "number" ){
			timeout = delay;
		}
		setTimeout(this._resetHintBox.bind(this),timeout);
	},
	_resetHintBox: function(){
		var textHintBox = $(this.options.textHintBoxID);
		this._currentLookup = '';
		this._currentHintData = {};
		if ( this._iframeAdded ){
			$(this._iframeID).style.display = "none";
		}
		textHintBox.style.display = "none";
		textHintBox.innerHTML = "";
		this.hideLoadingBox();
	},
	showLoadingBox: function(){
		this.toggleLoadingBox("block");
	},
	hideLoadingBox: function(){
		this.toggleLoadingBox("none");
	},
	toggleLoadingBox: function(display){
		if ( this.options.textHintLoadingBoxID && $(this.options.textHintLoadingBoxID) ){
			$(this.options.textHintLoadingBoxID).style.display = display;
		}
	}
};
function getCurrentStyle(oElm, strCssRule){
	var strValue = "";
	if(document.defaultView && document.defaultView.getComputedStyle){
		strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	}
	else if(oElm.currentStyle){
		try{
			strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
				return p1.toUpperCase();
			});
			strValue = oElm.currentStyle[strCssRule];
		}
		catch(e){
		
		}
	}
	return strValue;
}
var TagDisambiguation = {
	assetTagListRegex: new RegExp("\\<assetTagList\\s*language=\"([^\"]*)\"\\s*\\>", 'i'),
										 
	removedTagsArray: new Array,
	getAssetMap: function(){
	
	},
	
	addButton: function(){
	
		rawKeysBox = $('RawKeywords');
		
		rawKeysBox.value = this.cleanKeys(rawKeysBox.value);
		
	
		rootTag = $('StructuredTagList').value.match(this.assetTagListRegex);
	
		tagStart = "<tag tagid=\"\" lang=\"" + rootTag[1] + "\" string=\"";
		tagEnd = "\"></tag>\n";
		
		csvRegex = "\\s*,\\s*";
		csvRegex = new RegExp(csvRegex, "gi");
		keys = rawKeysBox.value;
		keys = this.entityEncode(keys);
		
		newTags = tagStart + keys.replace(csvRegex, tagEnd + tagStart) + tagEnd;
		tagList = $('StructuredTagList');
	
		tagList.value = tagList.value.replace(this.assetTagListRegex, rootTag[0] + '\n' + newTags);
	
		$('RawKeywords').value = '';
	
		this.getDisambig();
	},	 
	toggleTagAndTerm: function(tag, termID, add){
		if ( add ){
			this.addTagAndTerm(tag, termID);
		} else {
			this.removeTagAndTerm(tag, termID);
		}
	},
	addTagAndTerm: function(tag, termID){
	
	
	
		rootTag = $('StructuredTagList').value.match(this.assetTagListRegex);
		tagElement = this.formatTagAndTerm(tag, termID, rootTag[1]);
		tagList = $('StructuredTagList');
	
		tagList.value = tagList.value.replace(this.assetTagListRegex, rootTag[0] + '\n' + tagElement);
	
	}, 
	formatTagAndTerm : function(tag, termID, lang){
		tag = this.entityEncode(tag);
	
		tagElement = "<tag tagid=\"\" lang=\"" + lang + "\" string=\"" + tag + "\">";
		tagElement = tagElement + "\n<termList>\n<term termid=\"" + termID + "\" chosen=\"true\"></term>\n</termList>\n";
		tagElement = tagElement + "</tag>\n";
		return tagElement;
	},
	removeTagAndTerm: function(tag, termID){
	
	
	
		rootTag = $('StructuredTagList').value.match(this.assetTagListRegex);
		tagElement = this.formatTagAndTerm(tag, termID, rootTag[1]);
		tagList = $('StructuredTagList');
	
		start = tagList.value.indexOf(tagElement);
		tagListStart = tagList.value.substr(0, start);
		tagListEnd = tagList.value.substr(start + tagElement.length + 1);	
	
		tagList.value = tagListStart + tagListEnd;
	
	}, 
	removeAll: function(){
	
		regexTagids = "tagid\s*=\s*('|\")([a-f0-9]{32})";
		regexTagids = new RegExp(regexTagids, "gi");
		tagList = $('StructuredTagList');
		matches = tagList.value.match(regexTagids);
		
		matches.each(
			(
				function(tagidAtt, index){
					matchLength = tagidAtt.length;
					tagid = tagidAtt.substring(matchLength-32, matchLength);
					this.removeButton(tagid);
				}
			).bind(this)
		);	
	},
						 
	removeButton: function(tagid){
	
		
	
		tagRegex = "\\<tag\\s*tagid=\"" + tagid + "\"\\s*lang=\"[^\"]*\"\\s*string=\"[^\"]*\"\\>(.|\\n|\\r)*?\\<\\/tag\\>";
		tagRegex = new RegExp(tagRegex, "gi");
		tagList = $('StructuredTagList');
		
		this.removedTagsArray[tagid] = tagList.value.match(tagRegex);
				
		tagList.value = tagList.value.replace(tagRegex, '');
	
		tagTD = $('minusTD_' + tagid);
		tagTD.innerHTML = '<img src="images/buttons/plussign.gif" onclick="TagDisambiguation.unremoveButton(\'' + tagid + '\');" style="cursor: pointer;">';
		tagTD = $('tagTD_' + tagid);
		tagTD.innerHTML = '<div style="text-decoration: line-through;">' + tagTD.innerHTML + '</div>';
		
		tagTD = $('langTD_' + tagid);
		tagTD.innerHTML = '<div style="text-decoration: line-through;">' + tagTD.innerHTML + '</div>';
		
		tagTD = $('termsTD_' + tagid);
		tagTD.style.visibility = 'hidden';
	
	
	},
	unremoveButton: function(tagid){
	
		rootTag = $('StructuredTagList').value.match(this.assetTagListRegex);
		tagList = $('StructuredTagList');
	
		tagList.value = tagList.value.replace(this.assetTagListRegex, rootTag[0] + '\n' + this.removedTagsArray[tagid]);
		divRegex = /\<div style="text-decoration: line-through;?"\>/i;
		divRegex2 = /\<\/div\>/;
		tagTD = $('minusTD_' + tagid);
		tagTD.innerHTML = '<img src="images/buttons/minussign.gif" onclick="TagDisambiguation.removeButton(\'' + tagid + '\');" style="cursor: pointer;">';
		tagTD = $('tagTD_' + tagid);
		html = tagTD.innerHTML
		html = html.replace(divRegex, '');
		html = html.replace(divRegex2, '');
		tagTD.innerHTML = '';
		tagTD.innerHTML = html;
		tagTD = $('langTD_' + tagid);
		html = tagTD.innerHTML
		html = html.replace(divRegex, '');
		html = html.replace(divRegex2, '');
		tagTD.innerHTML = html;
		
		tagTD = $('termsTD_' + tagid);
		tagTD.style.visibility = 'visible';
	},
	spellingChange: function(tagid, newTag){
	
		rootTag = $('StructuredTagList').value.match(this.assetTagListRegex);
	
		tagRegex = "\\<tag\\s*tagid=\"" + tagid + "\"\\s*lang=\"[^\"]*\"\\s*string=\"([^\"]*)\"\\>(.|\\n|\\r)*?\\<\\/tag\\>";
		tagRegex = new RegExp(tagRegex, "i");
		tagList = $('StructuredTagList');
		match = tagList.value.match(tagRegex);
			
	
		if(typeof(match) == 'object' && match[1] == newTag){
		
			addTag = " newtag=\"true\"";
		}else{
			addTag = "";
		}
	
		tagStart = "<tag tagid=\"\" " + addTag + " lang=\"" + rootTag[1] + "\" string=\"";
		tagEnd = "\"></tag>\n";
		tagList.value = tagList.value.replace(tagRegex, tagStart + this.entityEncode(newTag) + tagEnd);
	
		this.getDisambig();
	},
	boxCheck: function(tagid, termid, checked){
	
		chosen = 'false';
		if(checked){
			chosen = 'true';
		}
							
		
	
		tagRegex = "(\\<tag\\s*tagid=\"" + tagid + "\"\\s*lang=\"[^\"]*\"\\s*string=\"[^\"]*\"\\>(.|\\n|\\r)*?\\<term\\s*termid=\"" + termid + "\"\\s*chosen=\")(true|false)";
		tagRegex = new RegExp(tagRegex, "i");
		tagList = $('StructuredTagList');
	
		tagList.value = tagList.value.replace(tagRegex, '$1' + chosen);
	},
	langSelect: function(tagid, lang){
	
	
		tagRegex = "(\\<tag\\s*tagid=\"" + tagid + "\"\\s*lang=\")[^\"]*";
		tagRegex = new RegExp(tagRegex, "i");
		tagList = $('StructuredTagList');
		tagList.value = tagList.value.replace(tagRegex, '$1' + lang);
		
	
		this.getDisambig();
	},
	getDisambig: function(){
	
	
		var fileTypeIDs = $F('disambig_filetypes');
		
	
	
	
		$('keywords_Content').style.visibility = 'hidden';
		var loadingImage = $('keywords_Loading');
		if(loadingImage){
			loadingImage.style.display = 'inline';
		}
		var xml = $('StructuredTagList').value;
		xml = encodeURIComponent(xml);
	
	
	
	
		var url = "ajax_class_creator.php";
		var params = "ajax_action=getDisambiguation&ajax_class=tagdisambiguation" + 
			"&xml="+xml +
			"&fileTypeIDs="+fileTypeIDs +
			"";
		var req = new Ajax.Request(
				url,
				{
					method: 'post',
					parameters: params,
					onComplete: this.drawDisambiguation.bind(this),
					onFailure: this.failed.bind(this)
				}
		);
	},
	drawDisambiguation: function(req){
	
		var data = AjaxUtil.receiveArray(req.responseText);
    if(data.error == 1) {
			this.failed();
			return;
		}
		$('disambigTable').innerHTML = '';
		$('disambigTable').innerHTML = data.html;	
		var keywordContent = $('keywords_Content');
		if(keywordContent){
			keywordContent.style.visibility = 'visible';
		}
		var loadingImage = $('keywords_Loading');
		if(loadingImage){
			loadingImage.style.display = 'none';
		}
		$('StructuredTagList').value = '';
		$('StructuredTagList').value = data.xml;
	
		if(data.flavour == 'wiki'){
			Wiki.afterDrawDisambiguation(data)
		}else{
			$('copyTags_Content').innerHTML = data.tags;
		}
	},
	failed: function(req){
	
		alert('An error occured while communicating with the server. Please try again later.');
	},
	replacePunctuationAndWhitespace: function (tags){
	
		tags = tags.replace(/\n+/g, ' ');
		tags = tags.replace(/\r+/g, ' ');
	
		tags = tags.replace(/(\s|_|\.)+/g, ' ');
	
		tags = tags.replace(/(,|\(|\)|\.|\?|!|\||\+|\\|\/|=|"|:|;)+/g, ',');
		return tags;
	},
	cleanKeys: function(tags) {
		var tagList = [];
	
		tags = this.replacePunctuationAndWhitespace(tags);
	
		tags = tags.replace(/\s*,\s*/g, ",");
		tags = tags.replace(/(^\s*)|(\s*$)/g, "");
		tags = tags.replace(/(^,*)|(,*$)/g, "");
		tags = tags.replace(/,,*/g, ",");
		tagList = tags.split(',');
		tagList = tagList.uniq();
		tags = tagList.join(','); 
		return tags;
	
		
	},
	entityEncode: function(tags){
		tags = tags.replace(/[\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x7f]/, '');
	
		tags = tags.replace(/&/g, "&amp;");
		tags = tags.replace(/\</g, "&lt;");
		tags = tags.replace(/\>/g, "&gt;");
		tags = tags.replace(/\"/g, "&quot;");
		tags = tags.replace(/\'/g, "&apos;");
		return tags
	},
	submit: function(){
		var catOne = $('cat1');
		var catTwo = $('cat2');
		var catThree = $('cat3');
		var RawKeys = $('RawKeywords');	
		RawKeys.value = this.cleanKeys(RawKeys.value);
		var toAdd = RawKeys.value;
		if( !/[123456789]+/.test(catOne.value) && 
				!/[123456789]+/.test(catTwo.value) &&
				!/[123456789]+/.test(catThree.value) 
				){
			Tabs.setDefaultTab('keywords');
			Tabs.switchToTab('categories');
			alert('Please select at least one category');
			return false;
		}
		
		if(toAdd.length > 0){
			if(!confirm('There are currently unsaved tags in the keyword box. Click \'OK\' to save these changes without adding the new tags, or \'Cancel\' to add the tags and continue editing this file.')){
				this.addButton();
				return false;
			}
		}
	
		if(this.hasUnchosen()){
			if(!confirm('You should provide at least one appropriate search term for each of the tags related to this image before completing the disambiguation process. A term is one of the possible meanings provided in the right hand column for each of the tags you\'ve added. Only check those possible terms which are relevant to this particular image. A search term is needed in order to make your file searchable.\n\nDo you want to continue without choosing terms?')){
				return false;
			}
		}
		
		document.FileInfoForm.submit();
	},
	hasUnchosen: function(){
	
		termListRegex = "\\<termList\\>(?:\\r|\\n|\\s)*(?:\\<term\\s*termid=\"[0-9_]*\"\\s*chosen=\"(?:false)\"\\>(?:\\r|\\n|\\s)*\\<\/term>(?:\\r|\\n|\\s)*)+\\<\/termList\\>";
		termListRegex = new RegExp(termListRegex, "i");
		tagList = $('StructuredTagList');
		if(termListRegex.test(tagList.value)){
			return true;
		}
		return false;
	},
	toggleTermChildren : function(childDiv, toggleImg){
		var d = $(childDiv);
		var i = $(toggleImg);
		if ( d.className == 'termChildrenHidden' ){
			d.className = 'termChildrenVisible';
			i.src = '/images/icon_minus.gif';
		} else {
			d.className = 'termChildrenHidden';
			i.src = '/images/icon_plus.gif';
		}
	},
	toggleCandidateWarning : function(id){
		var d = $(id);
		if ( d.className == 'addingCandidateWarningHidden' ){
		
			d.className = 'addingCandidateWarningVisible';
		} else {
		
			d.className = 'addingCandidateWarningHidden';
		}
	}
}
var IS_TagClarification = Class.create();
IS_TagClarification.prototype = {
  name: 'IS_TagClarification',
  initialize: function(options) {
    this.options = {
		
		
		
		
			params: {}
		
     
    };
    Object.extend(this.options, options || { });
		this._textDisambiguation = this.options.textDisambiguation;
  },
  failed: function(req) {
   
    return false;
  },
	drawForm: function(){
		if ( typeof this._textDisambiguation != 'object'){
			return false;
		}
		var tagClarificationOuterBox;
		if ( this.options.tagClarificationOuterBoxID && $(this.options.tagClarificationOuterBoxID) ){
			tagClarificationOuterBox = $(this.options.tagClarificationOuterBoxID);
		}
		var tagClarificationInnerBox = $(this.options.tagClarificationInnerBoxID);
		tagClarificationInnerBox.appendChild(this.getHeaderElement());
	
		this._checkedElements = new Array();
		var unambiguousMaps = new Array();
		for ( var i=0; i<this._textDisambiguation.m.length; i++ ){
		
			if ( this._textDisambiguation.m[i].c.length > 0 || this._textDisambiguation.m[i].ts.length <= 1 ){
				unambiguousMaps[unambiguousMaps.length] = this._textDisambiguation.m[i];
				continue;
			} else {
				tagClarificationInnerBox.appendChild(this.getTagClarificationElement(this._textDisambiguation.m[i]));
			}
		}
	
		if ( unambiguousMaps.length == this._textDisambiguation.m.length ){
			return false;
		}
		tagClarificationInnerBox.appendChild(this.getClearElement());
		var submitElement = document.createElement("input");
		submitElement.type = "image";
		submitElement.src = this.options.submitButtonImgSrc;
		submitElement.className = "right";
		submitElement.style.marginLeft = "5px";
		submitElement.onclick = this.submit.bind(this);
		tagClarificationInnerBox.appendChild(submitElement);
		tagClarificationInnerBox.appendChild(this.getClearElement());
	
		for ( var i=0; i<this._checkedElements.length; i++ ){
			this._checkedElements[i].checked = true;
		}
		tagClarificationInnerBox.style.display = "block";	
		if ( tagClarificationOuterBox ){
			tagClarificationOuterBox.style.display = "block";
		}
	
	},
	getHeaderElement: function(){
		var headerElement = document.createElement("div");
		headerElement.className = "left";
		headerElement.style.marginRight = "3px";
		headerElement.appendChild(document.createTextNode(this.options.strings["Did you mean"] + " "));
		return headerElement;
	},
	getClearElement: function(){
		var clearElement = document.createElement("div");
		clearElement.style.clear = "both";
		return clearElement;
	},
	getTagClarificationElement: function(tagMap){
	
		var tagClarification = this;
		var tagClarificationElement = document.createElement("div");
		tagClarificationElement.className = "left";
	
		tagClarificationElement.style.paddingRight = "10px";
		tagClarificationElement.style.paddingBottom = "10px";
		var chosen = {};
		var chosenAuto = {};
		for ( var i=0; i<tagMap.c.length; i++ ){
			chosen[tagMap.c[i]] = true;
		}
		for ( var i=0; i<tagMap.cA.length; i++ ){
			chosenAuto[tagMap.cA[i]] = true;
		}
		var tagLabelElement = document.createElement("b");
		tagLabelElement.style.fontSize = "1.1em";
		tagLabelElement.appendChild(document.createTextNode(tagMap.t));
		tagClarificationElement.appendChild(tagLabelElement);
		tagClarificationElement.appendChild(document.createTextNode(" " + this.options.strings["as in..."]));
	
		var tagChoiceElement;
		var tagChoiceCheckboxElement;
		var tagChoiceLabelElement;
		var checkboxID;
		for ( var i=0; i<tagMap.ts.length; i++ ){
			checkboxID = "TagClarification_Checkbox_" + tagMap.t + "_" + tagMap.ts[i].tID;
			tagChoiceElement = document.createElement("div");
		
			tagChoiceElement.style.whiteSpace = "nowrap";
			tagChoiceCheckboxElement = document.createElement("input");
			tagChoiceCheckboxElement.id = checkboxID;
			tagChoiceCheckboxElement.type = "checkbox";
			tagChoiceCheckboxElement.value = encodeURIComponent(Object.toJSON({'tag':tagMap.t, 'termID':tagMap.ts[i].tID}));
			tagChoiceCheckboxElement.onclick = function(){
				var choice = decodeURIComponent(this.value).evalJSON();
				if ( this.checked ){
					tagClarification.setChoice(choice.tag, choice.termID);
				} else {
					tagClarification.unsetChoice(choice.tag, choice.termID);
				}
			}
			if ( chosen[tagMap.ts[i].tID] || chosenAuto[tagMap.ts[i].tID] ){
				this._checkedElements[this._checkedElements.length] = tagChoiceCheckboxElement;
				tagChoiceCheckboxElement.checked = "checked";
			}
			tagChoiceLabelElement = document.createTextNode(" " + tagMap.ts[i].la);
			tagChoiceElement.appendChild(tagChoiceCheckboxElement);
			tagChoiceElement.appendChild(tagChoiceLabelElement);
			tagClarificationElement.appendChild(tagChoiceElement);
		}
		for ( var termID in chosenAuto ){
			this.setChoice(tagMap.t, termID);
		}
		return tagClarificationElement;
		
	},
	setChoice: function(tag, termID){
	
		var choiceSet = false;
    for ( var i=0; i<this._textDisambiguation.m.length; i++ ){
			if ( this._textDisambiguation.m[i].t === tag ){
				for ( var n=0; n<this._textDisambiguation.m[i].c.length; n++ ){
					if ( this._textDisambiguation.m[i].c[n] === termID ){
						choiceSet = true;
						break;
					}
				}
				if ( choiceSet == false ){
					this._textDisambiguation.m[i].c[this._textDisambiguation.m[i].c.length] = termID;
					choiceSet = true;
				}
			}
		}
	
	},
	unsetChoice: function(tag, termID){
	
		var newChoices = new Array();
    for ( var i=0; i<this._textDisambiguation.m.length; i++ ){
			if ( this._textDisambiguation.m[i].t === tag ){
				for ( var n=0; n<this._textDisambiguation.m[i].c.length; n++ ){
					if ( this._textDisambiguation.m[i].c[n] !== termID ){
						newChoices[newChoices.length] = this._textDisambiguation.m[i].c[n];
					}
				}
				this._textDisambiguation.m[i].c = newChoices;
			}
		}
	
	},
	formatURL: function(){
		var url = this.options.url;
		var glue = '?';
		if ( url.match(/\?/) ){
			glue = '&'
		}
		if ( this.options.params.length > 0 ){
			for ( var i in this.options.params ){
				url += glue + i + '=' + this.options.params[i];
				glue = '&';
			}
		}
		url += glue + this.options.textDisambiguationParamName + "=" + encodeURIComponent(Object.toJSON(this._textDisambiguation));
		return url;
	},
	submit: function(){
		document.location = this.formatURL();
	},
  dummy: function(){
    return false;
  }
}
var AjaxUtil = {
	receiveArray: function(responseText) {
		if ( typeof responseText != 'string' ){
			return responseText;
		}
    	eval('var ret = ' + responseText);
    	return ret;
	},
	trim: function(str) {
    	return str.replace(/^(\s+)?(\S*)(\s+)?$/, '$2');
	},
	ltrim: function(str) {
    	return str.replace(/^\s*/, '');
	},
	rtrim: function(str) {
    	return str.replace(/\s*$/, '');
	},
	xmldoc2string: function(xmlDocObject){
	
	
	
		var xmlMod=null;
		try{
			var xmlMod = imprt("xml");
		} catch(e){
		
			throw "importing of xml module failed.";
		}
	
		try {	
			var xmlString = xmlMod.node2XML(xmlDocObject.documentElement);
		} catch(e) {
			throw e;
		}
		return xmlString;
	},
	
	xmlrpc_extractpayload: function(responseText){
	
	
	
	
		var xmlrpcMod=null;
		try{
			var xmlrpcMod = imprt("xmlrpc");
		}catch(e){
		
			throw "importing of xmlrpc module failed.";
		}
	
		try {
			var xmlPayload = xmlrpcMod.unmarshall(responseText);
		} catch(e) {
			if ( e.constructor == xmlrpcMod.Fault ){
			
				throw e;
			} else {
				alert(e);
			}
		}
		return xmlPayload;
	},
	
	xmlrpc_formatrequest: function(methodName, methodParameters){
	
	
	
		
	
	
		
		var message = new XMLRPCMessage(methodName);
		message.addParameter(methodParameters);
		return message.xml();
	},
	xmlrpc_receivepayload: function(responseText) {
	
		try {
		
			xmlPayload = this.xmlrpc_extractpayload(responseText);
	
		
		
		
		
			var xmlDoc;
			try {
			
				var xmlDOMParser = new DOMParser();
				xmlDoc = xmlDOMParser.parseFromString(xmlPayload, "text/xml");
			} catch(e){
			
			
				try {
					xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
					xmlDoc.async="false";
					xmlDoc.loadXML(xmlPayload);
				} catch(e){
					throw e;
				}
			}
		} catch(e) {
		
			if ( typeof e == 'object' && e.faultCode ){
				throw e;
			} else {
				alert(e);
			}
		}
		return xmlDoc;
	},
	
	requestState: function(req) {
		switch (req.readyState) {
			case 1: case 2: case 3:
				return true;
				break;
		default:
			return false;
			break;
		}
	}, 
	
	showTimeoutMessage: function() {
		alert('The request has timed out. Please try again.');
	},
	
	defaultOnFailure: function() {
		alert('The request has failed.');
	},
	
	isFailure: function(req) {
		if(AjaxFailure.isNotXmlHttpRequest(req)) {
			return true;
		}
		if(AjaxFailure.isHeaderlessContent(req)) {
			this.showTimeoutMessage();
			return true;
		}
		if(AjaxFailure.isFailureString(req)) {
			return true;
		}
		return false;
	}
}
var AjaxFailure = {
	isHeaderlessContent: function(req) {
		return (req.getResponseHeader('X-Headerless-Content') == 'YES' ? true : false);
	},
	
	isFailureString: function(req) {
		return (req.responseText == 'ajax_fail' ? true : false);
	},
	
	isNotXmlHttpRequest: function(req) {
		return (req.responseText ? false : true);
	}
}
var HierBrowser = {
	_debug: false,
  busyURL: 'images/loading.gif',
  busySmallURL: 'images/loading_small.gif',
	kidArrowURL: 'images/hb_arrow.gif',
	dataType: new Array,
	currentID: new Array,
	Prefix: new Array,
	name: new Array,
	knownIDs: new Array,
	knownColumns: new Array,
	knownParents: new Array,
	knownLabels: new Array,
	knownNumKids: new Array,
	currentPathFromRoot: new Array,
	useAddClick: new Array,
	addedIDs: new Array,
	onChangeFunc: new Array,
	addClickFunc: new Array,
	initialSelections: new Array,
	prefLang: new Array,
  failed: function(req){
		alert('An error occured while communicating with the server. Please try again.');
	},
	getBrowserID: function(prefix, debugID){
		browserID = this.Prefix.indexOf(prefix);
		if(browserID == -1){
			alert(debugID + ': Browser Not Found: ' + prefix + '\nin: ' + this.Prefix);
		}
		return browserID;
	},
	setDataType: function(prefix, type){
		browserID = this.getBrowserID(prefix, 10);
		this.dataType[browserID] = type;
	},
	setName: function(prefix, name){
		browserID = this.getBrowserID(prefix,11);
		this.name[browserID] = name;
	},
	setPrefix: function(prefix){
		this.Prefix.push(prefix);
		browserID = this.getBrowserID(prefix,12);
		this.knownIDs[browserID] = new Array;
		this.knownColumns[browserID] = new Array;
		this.knownParents[browserID] = new Array;
		this.knownLabels[browserID] = new Array;
		this.knownNumKids[browserID] = new Array;
		this.currentPathFromRoot[browserID] = new Array;
		this.addedIDs[browserID] = new Array;
		this.initialSelections[browserID] = new Array;
		this.prefLang[browserID] = '4';
	},
	setPrefLang: function(prefix, langID){
		browserID = this.getBrowserID(prefix,13);
		this.prefLang[browserID] = langID;
	},
	getCurrentID: function(prefix){
		browserID = this.getBrowserID(prefix,14);
		return this.currentID[prefix];
	},
	getColumnsAjax: function(prefix, id, columnIndex){
	
		browserID = this.getBrowserID(prefix,15);
		this.busy(prefix, true, id);
		var url = "ajax_class_creator.php";
		var params = "ajax_action=getColumns&ajax_class=hierbrowser" +
			"&prefix=" + prefix +
			"&prefLang=" + this.prefLang[browserID] +
			"&id=" + id +
			"&dataType=" + this.dataType[browserID] +
			"&addClick=" + this.useAddClick[browserID] + 
			"&hbName=" + this.name[browserID] +
			"&columnIndex=" + columnIndex;
		var req = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: params,
				onComplete: this.showColumnsAjax.bind(this),
				onFailure: this.failed.bind(this)
			}
		);
		this.currentID[browserID] = id;
	},
	showColumnsAjax: function(req){
	
		var data = AjaxUtil.receiveArray(req.responseText);
		if(data.error == 1) {
			this.failed();
		}
		if(data.HBError){
			alert(data.HBError);
			return;
		}
		prefix = data.prefix;
		browserID = this.getBrowserID(prefix,16);
		if(data.cols){
			var colDiv = null;
			var colIndex = 0;
			data.cols.each(
				(
					function(col, index){
						colIndex = data.unifiedIndex[index];
						colDiv = $(this.Prefix[browserID] + '_col' + colIndex);
						if(!colDiv){
							var table = $(this.Prefix[browserID] + '_table').tBodies[0];
							var newCol = table.rows[0].insertCell(-1);
							newCol.vAlign = "top";
							newCol.innerHTML = '<div id="' + this.Prefix[browserID] + '_col' + colIndex + '" style="display: none;"></div>';
							var prevCol = $(this.Prefix[browserID] + '_col' + (colIndex-1));
							colDiv = $(this.Prefix[browserID] + '_col' + colIndex);
							colDiv.style.display = 'none';
							colDiv.style.border = prevCol.style.border;
							colDiv.style.margin = prevCol.style.margin;
							colDiv.style.padding = prevCol.style.padding;
							colDiv.style.height = prevCol.style.height;
							colDiv.style.width = prevCol.style.width;
							colDiv.style.overflow = prevCol.style.overflow;
							colDiv.style.position = prevCol.style.position;
						}
						colDiv.innerHTML = col;
						colDiv.style.display = 'block';
						this.storeCol(prefix, data.colIDs[index], col, data.parentIDs[index], data.labels[index], data.numKids[index]);
					}
				).bind(this)
			);
			colIndex++;
			colDiv = $(this.Prefix[browserID] + '_col' + colIndex);
			while(colDiv){
				colDiv.style.display = 'none';
				colDiv.innerHTML = '';
				colIndex++;
				colDiv = $(this.Prefix[browserID] + '_col' + colIndex);
			}
			this.hideAdded(prefix);
			if(data.siblings){
				data.siblings.each(
						(
 						 function(sibling, index){
							this.storeCol(prefix, sibling, null, data.parentID, data.siblingLabels[index], data.siblingNumKids[index]);
						}
					).bind(this)
				);
			}
		}
	
		this.onChange(prefix, data.id, data.label);
		this.highlightPathFromRoot(prefix, false);
		this.currentPathFromRoot[browserID] = this.getPathFromRoot(prefix, data.id);
		this.debug_showStore(prefix);
		this.highlightPathFromRoot(prefix, true);
		this.slideColumns(prefix);
		
		this.busy(prefix, false, data.id);
		return;
	},
	showColumns: function(prefix, id, colIndex){
		browserID = this.getBrowserID(prefix,17);
		var unifiedIndex = null;
		var col = null;
		var hasKids = false;
		var pathFromRoot = this.getPathFromRoot(prefix,id);
		var colDiv = null;
		if(pathFromRoot == false){
			this.getColumnsAjax(prefix, id, 0);
			return 0;
		}
		id = pathFromRoot[colIndex];
		unifiedIndex = this.knownIDs[browserID].indexOf(id.toString());
		do{
			col = this.knownColumns[browserID][unifiedIndex];
			if(col == null){
				this.getColumnsAjax(prefix, id, 0);
				return 0;
			}
			colDiv = $(this.Prefix[browserID] + '_col' + colIndex);
			if(!colDiv){
				var table = $(this.Prefix[browserID] + '_table').tBodies[0];
				var newCol = table.rows[0].insertCell(-1);
				newCol.vAlign = "top";
				newCol.innerHTML = '<div id="' + this.Prefix[browserID] + '_col' + colIndex + '" style="display: none;"></div>';
				var prevCol = $(this.Prefix[browserID] + '_col' + (colIndex-1));
				colDiv = $(this.Prefix[browserID] + '_col' + colIndex);
				colDiv.style.display = 'none';
				colDiv.style.border = prevCol.style.border;
				colDiv.style.margin = prevCol.style.margin;
				colDiv.style.padding = prevCol.style.padding;
				colDiv.style.height = prevCol.style.height;
				colDiv.style.width = prevCol.style.width;
				colDiv.style.overflow = prevCol.style.overflow;
				colDiv.style.position = prevCol.style.position;
			}
			colDiv.innerHTML = col;
			colDiv.style.display = 'block';
			colIndex++;
			id = pathFromRoot[colIndex];
			unifiedIndex = this.knownIDs[browserID].indexOf(id.toString());
			hasKids = this.knownNumKids[browserID][unifiedIndex];
			if(hasKids == null){
				hasKids = true;
			}else if(hasKids > 0){
				hasKids = true;
			}else{
				hasKids = false;
			}
		}while((colIndex < pathFromRoot.length) && hasKids);
		colDiv = $(this.Prefix[browserID] + '_col' + colIndex);
		while(colDiv){
			colDiv.style.display = 'none';
			colDiv.innerHTML = '';
			colIndex++;
			colDiv = $(this.Prefix[browserID] + '_col' + colIndex);
		}
		
		this.highlightPathFromRoot(prefix, false);
		this.currentPathFromRoot[browserID] = pathFromRoot;
		this.debug_showStore(prefix);
		this.highlightPathFromRoot(prefix, true);
		this.hideAdded(prefix);
		this.slideColumns(prefix);
		unifiedIndex = this.knownIDs[browserID].indexOf(pathFromRoot[pathFromRoot.length - 1].toString());
		
		this.onChange(prefix, this.knownIDs[browserID][unifiedIndex], this.knownLabels[browserID][unifiedIndex]);
		return;
	},
	onChange: function(prefix, id, label){
		browserID = this.getBrowserID(prefix,18);
		if(this.onChangeFunc[browserID] == null){
			alert('No onchange function set\nID: ' + id + '\nLabel: ' + label);
		}else{
			this.onChangeFunc[browserID](id, label);
		}
	},
	addInitialSelection: function(prefix, mtID, label){
		browserID = this.getBrowserID(prefix,19);
		var initSelect = {
			id: mtID,
			label: label
		};
		this.initialSelections[browserID].push(initSelect);
	},
	triggerInitialSelections: function(prefix){
		browserID = this.getBrowserID(prefix,20);
		this.initialSelections[browserID].each(
			(
				function(selection, index){
					this.addClick(prefix, selection.id, selection.label);
				}
			).bind(this)
		);
	},
	addClick: function(prefix, id, label){
		browserID = this.getBrowserID(prefix,21);
		var plusSign = $(this.Prefix[browserID] + '_addClick' + id);
		if(plusSign){
			plusSign.style.visibility = 'hidden';
		}
		this.addedIDs[browserID].push(id);
		if(this.addClickFunc[browserID] == null){
			alert('No addClick function set\nID: ' + id + '\nLabel: ' + label);
		}else{
			this.addClickFunc[browserID](id, label);
		}
	},
	removeClick: function(prefix, id){
		browserID = this.getBrowserID(prefix,22);
		var plusSign = $(this.Prefix[browserID] + '_addClick' + id);
		if(plusSign){
			plusSign.style.visibility = 'visible';
		}
		this.addedIDs[browserID] = this.addedIDs[browserID].without(id);
	},
	hideAdded: function(prefix){
		browserID = this.getBrowserID(prefix,23);
		var plussign = null;
		this.addedIDs[browserID].each(
			(
				function(id, index){
					plussign = $(this.Prefix[browserID] + '_addClick' + id);
					if(plussign){
						plussign.style.visibility = 'hidden';
					}
				}
			).bind(this)
		);
	},		
	setOnChange: function(prefix, func){
		browserID = this.getBrowserID(prefix,24);
		this.onChangeFunc[browserID] = func;
	},
	setAddClick: function(prefix, func){
		browserID = this.getBrowserID(prefix,25);
		this.addClickFunc[browserID] = func;
		if(func != null){
			this.useAddClick[browserID] = true;
		}else{
			this.useAddClick[browserID] = false;
		}
	},
	highlightPathFromRoot: function(prefix, show){
		browserID = this.getBrowserID(prefix,26);
		var newClassName = 'HBElementSelected';
		if(!show){
			newClassName = 'HBElementUnselected';
		}
		var lastColOffset = 0;
		var lastColWidth = 0;
		this.currentPathFromRoot[browserID].each(
			(
				function(id, index){
					var selectedDiv = $(this.Prefix[browserID] + '_element' + id);
					var col = $(this.Prefix[browserID] + '_col' + (index - 1));
					if(selectedDiv){
						selectedDiv.className = newClassName;
						if(show){
							selectionOffset = Position.positionedOffset(selectedDiv);
							if(col){
								colOffset = Position.positionedOffset(col);
								scrollOffset = selectionOffset[1] - colOffset[1];
								col.scrollTop = scrollOffset;
								lastColOffset = Position.positionedOffset(col)[0];
								lastColWidth = col.offsetWidth;
							}
						}
					}
				}
			).bind(this)
		);
		if(show){
			var viewPort = $(this.Prefix[browserID]);
			var scrollTo = (lastColOffset + (2*lastColWidth)) - viewPort.offsetWidth;
		
			viewPort.scrollLeft = scrollTo;
		}
	},
	slideColumns: function(prefix){
		return;
	},
	storeCol: function(prefix, ID, col, parentID, label, numKids){
	
		browserID = this.getBrowserID(prefix,27);
		var unifiedIndex = this.knownIDs[browserID].indexOf(ID.toString());
		if(unifiedIndex == -1){
			unifiedIndex = this.knownIDs[browserID].length;
			this.knownColumns[browserID][unifiedIndex] = null;
		}
		this.knownIDs[browserID][unifiedIndex] = ID.toString();
		if(col != null){
			this.knownColumns[browserID][unifiedIndex] = col;
		}
		this.knownParents[browserID][unifiedIndex] = parentID;
		this.knownLabels[browserID][unifiedIndex] = label;
		this.knownNumKids[browserID][unifiedIndex] = numKids;
		this.debug_showStore(prefix);
	},
	debug_showStore: function(prefix){
		if(!this._debug){
			return;
		}
		browserID = this.getBrowserID(prefix,28);
		html = 'browser: ' + prefix + '(' + browserID + ')' + '<br/>';
		if(this.currentPathFromRoot){
			html += 'PFR: ' + this.currentPathFromRoot[browserID].join(' -> ') + '<br/>';
		}else{
			html += 'no PFR yet<br/>';
		}
		if(this.knownIDs[browserID]){
			html += '<table border="1">' +
				'<tr>' +
					'<td>UI</td>' +
					'<td>ID</td>' +
					'<td>label</td>' +
					'<td>parent</td>' +
					'<td>numKids</td>' +
					'<td>col</td>' +
				'</tr>';
			this.knownIDs[browserID].each(
				(
					function(id, index){
						var hasCol = 'no';
						if(this.knownColumns[browserID][index] != null){
							hasCol = 'yes';
						}
						html += '<tr>'+
							'<td>' + index + '</td>' +
							'<td>' + id + '</td>' +
							'<td>' + this.knownLabels[browserID][index] + '</td>' +
							'<td>' + this.knownParents[browserID][index] + '</td>' +
							'<td>' + this.knownNumKids[browserID][index] + '</td>' +
							'<td>' + hasCol + '</td>' +
						'</tr>';
					}
				).bind(this)
			);
		
			html += '</table>';
		}else{
			html += 'no store yet<br/>';
		}
		$('stat').innerHTML = html;
	},
	getPathFromRoot: function(prefix, id){
		browserID = this.getBrowserID(prefix,29);
	
		var path = false;
		var unifiedIndex = this.knownIDs[browserID].indexOf(id.toString());
		if(unifiedIndex < 0){
		
			return new Array;
		}
		
		var parentID = this.knownParents[browserID][unifiedIndex];
		
		if(parentID == null){
		
			return new Array;
		}
		
		if(this.isRoot(id)){
		
			path = new Array;
			path[0] = id;
		}else{
			path = this.getPathFromRoot(prefix, parentID);
			if(path === false){
				return false;
			}
			path.push(id);
		}
		return path;
	},
	setPathFromRoot: function(prefix, path){
		browserID = this.getBrowserID(prefix,30);
		var pathArray = path.split(/,/);
		this.currentPathFromRoot[browserID] = pathArray;
	},
	isRoot: function(id){
		if(id > 1){
			return false;
		}
		return true;
	},
	busy: function(prefix, isBusy, id){
		browserID = this.getBrowserID(prefix,31);
		var loadingImg = null;
		if(!id){
			loadingImg = $('loadingImage');
			if(loadingImg){
				if(isBusy){
					loadingImg.style.visibility = 'visible';
				}else{
					loadingImg.style.visibility = 'hidden';
				}
			}
		}else{
			var arrowImg = $(this.Prefix[browserID] + '_kidArrow_' + id);
			var loadingImg = $(this.Prefix[browserID] + '_kidLoading_' + id);
			if(!loadingImg || !arrowImg){
				return;
			}
			if(isBusy){
				arrowImg.style.display = 'none';
				loadingImg.style.display = 'inline';
			}else{
				arrowImg.style.display = 'inline';
				loadingImg.style.display = 'none';
			}
		}
	}
}
var CatBrowser = {
	addedIDs: new Array(),
	addedLabels: new Array(),
	boolMode: 'all',
	prefix: '',
	init: function(prefix, prefLang){
		if(!prefix){
			return;
		}
		this.prefix = prefix;
		HierBrowser.setOnChange(prefix, this.switchToCat.bind(this));
		HierBrowser.setAddClick(prefix, this.addCat.bind(this));
		HierBrowser.setPrefLang(prefix, prefLang);
		HierBrowser.triggerInitialSelections(prefix);
	},
	switchToCat: function(id, label){
		this.showSelected();
		return true;
	},
	addCat: function(id, label){
		if(this.addedIDs.indexOf(id) > -1){
			return;
		}
		this.addedIDs.push(id);
		var unifiedIndex = this.addedIDs.indexOf(id);
		this.addedLabels[unifiedIndex] = label;
		this.showSelected();
		
		return true;
	},
	removeCat: function(id){
		var unifiedIndex = this.addedIDs.indexOf(id);
		if(unifiedIndex < 0){
			return false;
		}
		this.addedIDs.splice(unifiedIndex, 1);
		this.addedLabels.splice(unifiedIndex, 1);
		HierBrowser.removeClick(this.prefix, id);
		
		this.showSelected();
	},
	setBoolMode: function(mode){
		if(mode == 'any' || mode.toLowerCase() == 'or'){
			this.boolMode = 'any';
		}else{
			this.boolMode = 'all';
		}
		this.showSelected();
	},
	showSelected: function(){
		var resultsDiv = $('browseResults');
		
		var table = '';
		if(this.addedIDs.length > 0){
			table += 
				'<table>' +
					'<tr>' +
						'<td align="right" valign="top">' +
							'Match ';
			if(this.addedIDs.length > 1){
				var anySelected = '';
				var allSelected = '';
				if(this.boolMode == 'any'){
					anySelected = 'selected ';
				}else{
					allSelected = 'selected ';
				}
				table +=
								'<select ' +
									'id="MajortermBrowser_boolMode" ' +
									'style="' +
										'width: 55px; ' +
									'" ' +
									'onchange="CatBrowser.setBoolMode(this.value); " ' +
								'>' +
									'<option id="any" value="any" ' + anySelected + '>Any</option>' +
									'<option id="all" value="all" ' + allSelected + '>All</option>' +
								'</select>' +
							' of the following:';
			}else{
				table +=
					'the following:';
			}
			table +=
						'</td>' +
						'<td valign="top">' +
							'<div ' +
								'style="' +
									'height: 72px; ' +
									'overflow: auto; ' +
								'" ' +
							'>' +
								'<table>';
		}
		this.addedIDs.each(
			(
				function(id, index){
					table += 
						'<tr>' +
							'<td>' +
								'<img ' +
									'src="/images/minussign_small.gif" ' +
									'onclick="CatBrowser.removeCat(\''+ id + '\');" ' +
									'style="' +
										'cursor: pointer; ' +
									'"' +
								'/>' +
							'</td>' +
							'<td>' +
								'<div '+
									'onclick="HierBrowser.showColumns(\'' + this.prefix + '\', \'' + id + '\', 0);" ' +
									'style="' +
										'cursor: pointer; ' +
									'" ' +
								'>' +
									this.addedLabels[index] +
								'</div>' +
							'</td>' +
						'</tr>';
				}
			).bind(this)
		);
		if(this.addedIDs.length > 0){
			table += 
								'</table>' +
							'</div>' +
						'</td>' +
					'</tr>' +
				'</table>';
		}
		$('majortermsList').value = this.addedIDs.join(',');
		$('majortermsConjunction').value = this.boolMode;
		resultsDiv.innerHTML = table;
	}
}
var popupBoxOffsetFromMouse=[-5,-5];
if (document.getElementById || document.all){
	document.write('<div id="popupBoxModalBackground" style="position: absolute; visibility: hidden; left: 0px; top: 0px; width: ' + getDocWidth() + 'px; height: ' + getDocHeight() + 'px; z-index: 50"></div>');
}
function showPopupBox(popupElement, e, popupResetCallback, isModal){
	if ( typeof popupElement == 'string' ){
		popupElement = document.getElementById(popupElement);
	}
	
	movePopupBox(popupElement, e);
	popupElement.style.visibility="visible";
	if ( isModal && popupResetCallback ){
		document.getElementById('popupBoxModalBackground').onclick = function (modalE){
			popupResetCallback(popupElement, modalE);
			popupElement.style.visibility = 'hidden';
			document.getElementById('popupBoxModalBackground').style.visibility = 'hidden';
		};
		document.getElementById('popupBoxModalBackground').style.visibility = 'visible';
	}
}
function hidePopupBox(popupElement){
	if ( typeof popupElement == 'string' ){
		popupElement = document.getElementById(popupElement);
	}
	popupElement.style.visibility="hidden";
	document.getElementById('popupBoxModalBackground').style.visibility = 'hidden';
}
function movePopupBox(popupElement, e){
	var xcoord = popupBoxOffsetFromMouse[0];
	var ycoord = popupBoxOffsetFromMouse[1];
	var docwidth = getDocWidth();
	var docheight = getDocHeight();
	if (typeof e != "undefined"){
	
		var x = 0;
		var y = 0;	
		
		if(e.pageX || e.pageY) {
			x = e.pageX;
			y = e.pageY;
		} else if (e.clientX || e.clientY) {
			x = e.clientX;
			y = e.clientY;
		
		
		}
		
				
		if (docwidth - x < popupElement.offsetWidth + xcoord){
			xcoord = x - xcoord - popupElement.offsetWidth;
		} else {
			xcoord += x;
		} 
					
		if (docheight + getTrueBody().scrollTop - y < popupElement.offsetHeight + ycoord){
			ycoord = y - ycoord - popupElement.offsetHeight;
		} else {
			ycoord += y;
		}
	} else if (typeof window.event != "undefined"){
	
		if (docwidth - event.clientX < popupElement.offsetWidth + xcoord){
			xcoord = event.clientX - xcoord - popupElement.offsetWidth + getTrueBody().scrollLeft;
		} else {
			xcoord += event.clientX + getTrueBody().scrollLeft;
		}
		if (docheight - event.clientY < popupElement.offsetHeight + ycoord){
			ycoord = event.clientY - ycoord - popupElement.offsetHeight + getTrueBody().scrollTop;
		} else {
			ycoord += event.clientY + getTrueBody().scrollTop;
		}
	}	else {
		return;
	}
	
	popupElement.style.left = xcoord+"px"
	popupElement.style.top = ycoord+"px"
}
var SIDE_TOP = 1;
var SIDE_BOTTOM = 2;
var SIDE_LEFT = 4;
var SIDE_RIGHT = 8;
var QUADRANT_TOP_LEFT = SIDE_TOP | SIDE_LEFT;
var QUADRANT_TOP_RIGHT = SIDE_TOP | SIDE_RIGHT;
var QUADRANT_BOTTOM_LEFT = SIDE_BOTTOM | SIDE_LEFT;
var QUADRANT_BOTTOM_RIGHT = SIDE_BOTTOM | SIDE_RIGHT;
function whichQuadrant(pageX, pageY, pointX, pointY){
	var quadrant = 0;
	var halfX = pageX/2;
	var halfY = pageY/2;
	if ( pointX < halfX ){
		quadrant |= SIDE_LEFT;
	} else {
		quadrant |= SIDE_RIGHT;
	}
	if ( pointY < halfY ){
		quadrant |= SIDE_TOP;
	} else {
		quadrant |= SIDE_BOTTOM;
	}
	return quadrant;
}
function getDocWidth(){
	return (document.all? getTrueBody().scrollLeft+getTrueBody().clientWidth : pageXOffset+window.innerWidth-15);
}
function getDocHeight(){
	return (document.all? Math.min(getTrueBody().scrollHeight, getTrueBody().clientHeight) : Math.min(window.innerHeight));
}
function getTrueBody(){
	return ( (!window.opera && document.compatMode && document.compatMode!="BackCompat") || window.opera)? document.documentElement : document.body
}
function debugOnClickEventHandler(e){
	s = typeof e + ":\n";
	s += 'type = ' + e.type + "\n";
	s += 'target = ' + e.target + "\n";
	s += 'layerX = ' + e.layerX + "\n";
	s += 'layerY = ' + e.layerY + "\n";
	s += 'pageX = ' + e.pageX + "\n";
	s += 'pageY = ' + e.pageY + "\n";
	s += 'screenX = ' + e.screenX + "\n";
	s += 'screenY = ' + e.screenY + "\n";
	s += 'which = ' + e.which + "\n";
	s += 'modifiers = ' + e.modifiers + "\n";
	alert(s);
}
var offsetfrommouse=[15,15];
var displayduration=0;
var currentimageheight = 270;
if (document.getElementById || document.all){
	document.write('<div id="trailimageid">');
	document.write('</div>');
}
function gettrailobj(){
if (document.getElementById)
return document.getElementById("trailimageid").style
else if (document.all)
return document.all.trailimagid.style
}
function gettrailobjnostyle(){
if (document.getElementById)
return document.getElementById("trailimageid")
else if (document.all)
return document.all.trailimagid
}
function truebody(){
return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}
function showtrail(imagename,title,description,ratingaverage,ratingnumber,showthumb,height,filetype, width){
	if (height > 0){
		currentimageheight = height;
	}
	document.onmousemove=followmouse;
	cameraHTML = '';
	if ( !ratingnumber ){
		ratingnumber = 0;
		ratingaverage = 0;
	}
	for(x = 1; x <= 5; x++){
		if (ratingaverage >= 1){
			cameraHTML = cameraHTML + '<img src="/images/camera_1.gif">';
		} else if (ratingaverage >= 0.5){
			cameraHTML = cameraHTML + '<img src="/images/camera_05.gif">';
		} else {
			cameraHTML = cameraHTML + '<img src="/images/camera_0.gif">';
		}
	
		ratingaverage = ratingaverage - 1;
	}
	cameraHTML = cameraHTML + ' (' + ratingnumber + ' Review';
	if ( ratingnumber > 1 ) cameraHTML += 's';
	cameraHTML = cameraHTML + ')';
	newHTML = '<div style="padding: 5px; background-color: #FFF; border: 1px solid #888;">';
	newHTML = newHTML + '<h2>' + title + '</h2>';
	newHTML = newHTML + 'Rating: ' + cameraHTML + '<br/>';
	newHTML = newHTML + description.replace(/\[[^\]]*\]/g, '') + '<br/>';
	if (showthumb > 0){
		newHTML = newHTML + '<div align="center" style="padding: 8px 2px 2px 2px;">';
		if(filetype == 8) {
			newHTML = newHTML +	'<object width="380" height="285" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0">';
			newHTML = newHTML + '<param name="movie" value="video_loupe.swf">';
			newHTML = newHTML + '<param name="quality" value="best">';
			newHTML = newHTML + '<param name="loop" value="true">';
			newHTML = newHTML + '<param name="FlashVars" value="videoLocation=' + imagename + '&bufferPercent=25">';
			newHTML = newHTML + '<EMBED SRC="video_loupe.swf" LOOP="true" QUALITY="best" FlashVars="videoLocation=' + imagename + '&bufferPercent=25" WIDTH="380" HEIGHT="285">';
			newHTML = newHTML + '</object></div>';
		} else {
			newHTML = newHTML + '<img src="' + imagename + '"';
			if ( filetype == 1 && height > 0 && width > 0 ){
				newHTML = newHTML + ' height="' + height + '" width="' + width + '"';
			}
			newHTML = newHTML + ' border="0"/></div>';
		}
	}
	newHTML = newHTML + '</div>';
	gettrailobjnostyle().innerHTML = newHTML;
	gettrailobj().display="inline";
}
function showtrailBatch(imagename,title,filetype){
	document.onmousemove=followmouseBatch;
	cameraHTML = '';
	newHTML = '<div style="padding: 5px; background-color: #FFF; border: 1px solid #888;" id="trailInnerDiv">';
	newHTML = newHTML + '<h2>' + title + '</h2>';
	newHTML = newHTML + '<div align="center" style="padding: 8px 2px 2px 2px;">';
	if(filetype == 8) {
		newHTML = newHTML +	'<object width="380" height="285" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0">';
		newHTML = newHTML + '<param name="movie" value="video_loupe.swf">';
		newHTML = newHTML + '<param name="quality" value="best">';
		newHTML = newHTML + '<param name="loop" value="true">';
		newHTML = newHTML + '<param name="FlashVars" value="videoLocation=' + imagename + '">';
		newHTML = newHTML + '<EMBED SRC="video_loupe.swf" LOOP="true" QUALITY="best" FlashVars="videoLocation=' + imagename + '" WIDTH="380" HEIGHT="285">';
		newHTML = newHTML + '</object></div>';
	} else {
		newHTML = newHTML + '<img src="' + imagename + '" border="0"></div>';
	}
	newHTML = newHTML + '</div>';
	gettrailobjnostyle().innerHTML = newHTML;
	gettrailobj().display="inline";
	gettrailobj().position="absolute";
	currentimageheight = $('trailInnerDiv').offsetHeight;
	
}
function hidetrail(){
	gettrailobj().innerHTML = " ";
	gettrailobj().display="none"
	document.onmousemove=""
	gettrailobj().left="-500px"
}
function followmouse(e){
	var xcoord=offsetfrommouse[0]
	var ycoord=offsetfrommouse[1]
	var docwidth=document.all? truebody().scrollLeft+truebody().clientWidth : pageXOffset+window.innerWidth-15
	var docheight=document.all? Math.min(truebody().scrollHeight, truebody().clientHeight) : Math.min(window.innerHeight)

	if (typeof e != "undefined"){
		if (docwidth - e.pageX < 380){
			xcoord = e.pageX - xcoord - 400;
		} else {
			xcoord += e.pageX;
		}
		if (docheight - e.pageY < (currentimageheight + 110)){
		
			if ( document.body ){
				scrollTop = Math.max(truebody().scrollTop, document.body.scrollTop);
			} else {
				scrollTop = truebody().scrollTop;
			}
			ycoord += e.pageY - Math.max(0,(110 + currentimageheight + e.pageY - docheight - scrollTop));
		} else {
			ycoord += e.pageY;
		}
	} else if (typeof window.event != "undefined"){
		if (docwidth - event.clientX < 380){
			xcoord = event.clientX + truebody().scrollLeft - xcoord - 400;
		} else {
			xcoord += truebody().scrollLeft+event.clientX
		}
		if (docheight - event.clientY < (currentimageheight + 110)){
			ycoord += event.clientY + truebody().scrollTop - Math.max(0,(110 + currentimageheight + event.clientY - docheight));
		} else {
			ycoord += truebody().scrollTop + event.clientY;
		}
	}
	if(ycoord < 0) { ycoord = ycoord*-1; }
	gettrailobj().left=xcoord+"px"
	gettrailobj().top=ycoord+"px"
}
function followmouseBatch(e){
	var xcoord=offsetfrommouse[0]
	var ycoord=offsetfrommouse[1]
	var docwidth=document.all? truebody().scrollLeft+truebody().clientWidth : pageXOffset+window.innerWidth-15
	var docheight=document.all? Math.min(truebody().scrollHeight, truebody().clientHeight) : Math.min(window.innerHeight)
	var trailInnerDiv = $('trailInnerDiv');
	var currentimageheight = trailInnerDiv.offsetHeight;
	var currentimagewidth = trailInnerDiv.offsetWidth;
	scrollPos = Position.realOffset(truebody());
	
	if (typeof e != "undefined"){
		if (docwidth - e.pageX < 380){
			xcoord = e.pageX - xcoord - 400;
		} else {
			xcoord += e.pageX;
		}
		if ((e.pageY - scrollPos[1]) + currentimageheight > docheight){
			ycoord = -ycoord + (e.pageY - currentimageheight);
		} else {
			ycoord += e.pageY;
		}
	} else if (typeof window.event != "undefined"){
		if (event.clientX + currentimagewidth > docwidth){
			xcoord = -xcoord + ((event.clientX + scrollPos[0]) - currentimagewidth);
		} else {
			xcoord += (event.clientX + scrollPos[0]);
		}
		if (event.clientY + currentimageheight > docheight){
			ycoord = -ycoord + ((event.clientY + scrollPos[1]) - currentimageheight);
		} else {
			ycoord += (event.clientY + scrollPos[1]);
		}
	}
	if(ycoord < 0) { ycoord = ycoord*-1; }
	gettrailobj().left=xcoord+"px"
	gettrailobj().top=ycoord+"px"
}
function AddCheckedFilesToLighbox(formName, fieldName){
	fileIDs = '';
	fileIDFields = document[formName][fieldName];
	for (i=0; i<fileIDFields.length; ++i){
		if ( fileIDFields[i].checked ){
			if ( fileIDs.length ){
				fileIDs += ',';
			}
			fileIDs += fileIDFields[i].value;
		}
	}
	window.open('popup_add_to_lightbox.php?DontRedirect=1&id='+fileIDs,
		'Popup', 'scrollbars=yes,width=400,height=500');
}
var debugModeOn = false;
function DebugMessage(message) {
    if (debugModeOn) {
        alert(message);
    }
}
function ajaxac_createXMLHttp() {
    var ret = null;
    try {
        ret = new ActiveXObject('Msxml2.XMLHTTP');
    }
    catch (e) {
        try {
            ret = new ActiveXObject('Microsoft.XMLHTTP');
        }
        catch (ee) {
            ret = null;
        }
    }
    if (!ret && typeof XMLHttpRequest != 'undefined')
        ret = new XMLHttpRequest();
    return ret;
}
function ajaxac_attachWidget(hook, id) {
    if (hook.length > 0 && id.length > 0) {
        evalStr = hook + " = document.getElementById('" + id + "');";
        eval(evalStr);
    }
}
function ajaxac_receivejsarray(code) {
   
		if ( typeof code != 'string' ){
			return code;
		}
    eval('var ret = ' + code);
    return ret;
}
function ajaxac_countdowntimer(cmd, ms) {
    this.cmd = cmd;
    this.ms = ms;
    this.tp = 0;
}
ajaxac_countdowntimer.prototype.start = function() {
    if (this.tp > 0) {
        this.reset();
    }
    this.tp = window.setTimeout(this.cmd, this.ms);
}
ajaxac_countdowntimer.prototype.reset = function() {
    if (this.tp > 0) {
        window.clearTimeout(this.tp);
    }
    this.tp = 0;
}
function trim(str) {
    return str.replace(/^(\s+)?(\S*)(\s+)?$/, '$2');
}
function ltrim(str) {
    return str.replace(/^\s*/, '');
}
function rtrim(str) {
    return str.replace(/\s*$/, '');
}
function delay(milliseconds) {
    var then, now;
    then = new Date().getTime();
    now = then;
    while ((now - then) < milliseconds) {
        now = new Date().getTime();
    }
}
function ajaxac_getkeycode(e) {
    if (document.layers) {
        return e.which;
    }
    else if (document.all) {
        return event.keyCode;
    }
    else if (document.getElementById) {
        return e.keyCode;
    }
    return 0;
}
function ajaxac_xmlrpc_formatrequest(methodName, methodParameters){

	var message = new XMLRPCMessage(methodName);
	message.addParameter(methodParameters);
	return message.xml();
}
function ajaxac_xmlrpc_receivepayload(responseText) {
	try {
		
	
		xmlPayload = ajaxac_xmlrpc_extractpayload(responseText);
	
	
	
	
		var xmlDoc;
	
		
		try {
		
			var xmlDOMParser = new DOMParser();
			xmlDoc = xmlDOMParser.parseFromString(xmlPayload, "text/xml");
		} catch(e){
		
		
			try {
				xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async="false";
				xmlDoc.loadXML(xmlPayload);
			} catch(e){
				throw e;
			}
		}
		
	} catch(e) {
	
		if ( typeof e == 'object' && e.faultCode ){
			throw e;
		} else {
			alert(e);
		}
	}
	return xmlDoc;
}
function ajaxac_xmlrpc_extractpayload(responseText){

	var xmlrpcMod=null;
	try{
		var xmlrpcMod = imprt("xmlrpc");
	}catch(e){
	
		throw "importing of xmlrpc module failed.";
	}
	try {
		var xmlPayload = xmlrpcMod.unmarshall(responseText);
	} catch(e) {
		if ( e.constructor == xmlrpcMod.Fault ){
		
			throw e;
		} else {
			alert(e);
		}
	}
	return xmlPayload;
}
function ajaxac_xmldoc2string(xmlDocObject){

	var xmlMod=null;
	try{
		var xmlMod = imprt("xml");
	} catch(e){
	
		throw "importing of xml module failed.";
	}
	try {
		
		var xmlString = xmlMod.node2XML(xmlDocObject.documentElement);
		
	} catch(e) {
		throw e;
	}
	return xmlString;
}
function lightboxPopupBoxReset(popupBoxElementID){
	document.getElementById('AddToLightboxResponseMessages').style.display = 'none';
	document.getElementById('AddToLightboxResponseMessages').innerHTML = '';
	document.getElementById('AddToLightboxContentAdd').style.display = 'block'; 
	document.getElementById('AddToLightboxHelpButton1').style.display = 'inline'; 
	document.getElementById('AddToLightboxHelpButton2').style.display = 'none'; 
	document.getElementById('AddToLightboxContentHelp').style.display = 'none';
	document.getElementById('AddToLightboxContentCreateNew').style.display = 'none';
	document.getElementById('AddToExisting').checked = true;
	document.getElementById('AddToNew').checked = false;
	document.LightboxForm.Name.value = '';
	document.LightboxForm.Description.value = '';
	document.LightboxForm.Keywords.value = '';
}
function lightboxPopupBoxShowHelp(popupBoxElementID){
	document.getElementById('AddToLightboxResponseMessages').style.display = 'none';
	document.getElementById('AddToLightboxResponseMessages').innerHTML = '';
	document.getElementById('AddToLightboxContentAdd').style.display = 'none'; 
	document.getElementById('AddToLightboxHelpButton1').style.display = 'none'; 
	document.getElementById('AddToLightboxHelpButton2').style.display = 'inline'; 
	document.getElementById('AddToLightboxContentHelp').style.display = 'block'
}
function lightboxPopupBoxHideHelp(popupBoxElementID){
	document.getElementById('AddToLightboxContentAdd').style.display = 'block';  
	document.getElementById('AddToLightboxHelpButton1').style.display = 'inline'; 
	document.getElementById('AddToLightboxHelpButton2').style.display = 'none'; 
	document.getElementById('AddToLightboxContentHelp').style.display = 'none'
}
function lightboxPopupBoxClose(){
	lightboxPopupBoxReset('lightboxPopupBox');
	hidePopupBox('lightboxPopupBox');
}
var AddToLightbox = Class.create();
AddToLightbox.prototype = {
	initialize: function(id, parentNodeID, fileID, popupBoxID, formName, jsCallback, isModal, imgSrc, label,seachCacheID, copyLightboxID, imgTitle, enabled) {
		this.id = id;
		this.parentNodeID = parentNodeID;
		this.labelID = "addToLightBoxLabel_" + id;
		this.buttonID = "addToLightBoxButton_" + id;
		this.fileID = fileID;
		this.popupBoxID = popupBoxID;
		this.formName = formName;
		this.jsCallback = jsCallback;
		this.isModal = isModal;
		this.imgSrc = imgSrc;
		this.searchCacheID = seachCacheID;
		this.copyLightboxID = copyLightboxID;
		this.imgTitle = imgTitle;
		this.label = label;
		this.buildLink(enabled);
	},
	
	buttonClick: function(e) {
		showPopupBox($(this.popupBoxID), e, this.jsCallback, this.isModal);
		$(this.formName).FileID.value = this.fileID;
		$(this.formName).SearchCacheID.value = this.searchCacheID;
		$(this.formName).LightboxID.value = this.copyLightboxID;
	},
	
	buttonClickDisabled: function(e) {
		showPopupBox($(this.popupBoxID), e, null, this.isModal);
	},
	
	buildLink: function(enabled) {
		var img = document.createElement("img");
		img.setAttribute("id", this.buttonID);
		img.setAttribute("src", this.imgSrc);
		img.setAttribute("alt", "Add To Lightbox");
		img.setAttribute("title", this.imgTitle);
		img.setAttribute("className", 'lightboxAdd');
		img.setAttribute("class", 'lightboxAdd');
		
		if(enabled) {
			img.onclick = this.buttonClick.bind(this);
		} else {
			img.onclick = this.buttonClickDisabled.bind(this);
		}
				
		$(this.parentNodeID).appendChild(img);
		
		var span = document.createElement("span");
		span.setAttribute("id", this.labelID);
		span.innerHTML = this.label;
		span.onclick = this.buttonClick.bind(this);
		$(this.parentNodeID).appendChild(img);
	}
}	
var SearchBarBetaAjax = Class.create();
SearchBarBetaAjax.prototype = {
	preDisambigChoices: new Array,
	currentPreDisambigCheck: 0, 
	initialize: function(context) {
		this.colorSelector='Simple';
		this.tagHint = new IS_TagHint({
			textHintBoxID: 'SearchBarTextHintBox',
			textHintLoadingBoxID: 'SearchBarTextHintLoadingBox',
			textFieldID: 'SearchBarText',
			languageFieldID: 'SearchBarLanguage',
			textDisambiguationFieldID: 'TopSearchTextDisambiguation'
		});
	},
	
	
	loadEvents: function() {
		this.searchBarTextObserver();
		
	
		var fileTypes = new Array('Image','Illustration [Vector]','Flash','Video');
		fileTypes.each(function(type, index) {
			$("SearchBarFileType"+type).observe('click', function() {
				this.toggleFileType(type);
			}.bind(this));
		}.bind(this));
		
		$('SearchBarForm').observe('submit', this.searchBarFormOnSubmit.bind(this));
		
		$('SearchBarSubmitImage').observe('click', function() {
			return this.searchBarFormOnSubmit();
		}.bind(this));
		
		$('SearchBarAdvancedToggle').observe('click', function() {		
			this.toggleSearchBar(false);
		}.bind(this));
		
		$('SearchBarHelpToggle').observe('click', function() {
			window.open('popup_search_tips.php#basic','Popup','scrollbars=yes,width=700,height=470');
		});
		
	
	
	
		if( $('SearchWithin') ) {
		
		
		
		
			$('SearchBarSortBy').observe('change', function() {
				this.setSortBy($F('SearchBarSortBy'), true); 
				if ( $('SearchWithinCheckbox') ){ 
					$('SearchWithinCheckbox').checked = true; 
					this.setSearchWithin('');
				} else if ($('FO_SearchWithInCheckbox')){
					$('FO_SearchWithinCheckbox').checked = true; 
					this.setSearchWithin('FO_');
				}
				return this.searchBarFormOnSubmit();
			}.bind(this));
		}
		else{
			$('SearchBarSortBy').observe('change', function() {
				this.setSortBy($F('SearchBarSortBy'), false);
			}.bind(this));
		}
		
		if($('SearchWithin')){
			$('SearchWithinCheckbox').observe('click', function(){
				this.setSearchWithin('');
			}.bind(this));
		}else if($('FO_SearchWithin')){
			$('SearchWithinCheckbox').observe('click', function(){
				this.setSearchWithin('FO_');
			}.bind(this));
		}
		
		
	},
	
	searchBarFormOnSubmit: function(event) {
		if(TopsearchFormValidate()) { 			
			$('TopSearchFileTypeSizePrice').value = $F('SearchBarFileTypeSizePrice');
			$('TopSearchOrder').value = $F('SearchBarOrder');
			$('TopSearchText').value = this.getTextValue($('SearchBarText'), $('SearchBarTipText'));
			
			$('topsearch').submit();
		} 
		Event.stop(event);
		return false;
	},
	
	searchBarTextObserver: function() { 
		if ($('SearchBarText')) {
		
		
			$('SearchBarText').setAttribute('autocomplete', 'off');
			
		
			if ($F('SearchBarText') == '') $('SearchBarText').value = $F('SearchBarTipText');
			
			Event.observe('SearchBarText', 'keydown', function(e) {
				if ($F('SearchBarText').length >= 3) searchBarAjax.tagHint.getHintsFromPartialTagOnKeydown(e);
			});
			
			Event.observe('SearchBarText', 'keyup', function(e) {
				if ($F('SearchBarText').length >= 3) searchBarAjax.tagHint.getHintsFromPartialTagOnKeyup(e);
				else searchBarAjax.tagHint.resetHintBox();
			});
			
			Event.observe('SearchBarText', 'focus', function(e) {
				if ($F('SearchBarText') == $F('SearchBarTipText')) {
					$('SearchBarText').value = '';
					$('SearchBarText').style.color = '#000';
				} else searchBarAjax.tagHint.getHintsFromPartialTag();
			});
			Event.observe('SearchBarText', 'blur', function(e) {
				if ($F('SearchBarText') == '') {
					$('SearchBarText').value = $F('SearchBarTipText');
					$('SearchBarText').style.color = '#999';
				}
				searchBarAjax.tagHint.resetHintBox(250);
			});
		}
	},
	toggleFileType: function(selectedFileType) {
	
		if(!$("SearchBarFileTypeImage").checked && !$("SearchBarFileTypeFlash").checked && !$("SearchBarFileTypeIllustration [Vector]").checked && !$("SearchBarFileTypeVideo").checked) {
			$("SearchBarFileType"+selectedFileType).checked = true;
			return;
		}
		
	
	
		var fileTypeSizePrice = $F('SearchBarFileTypeSizePrice').evalJSON(true);
		
	
		var newFileTypeSizePrice = new Array();
		
	
	
		var hasVideo = 0;
		
	
		fileTypeSizePrice.each(function(fileType){
			
		
			if(fileType.type == selectedFileType){
				if(fileType.type=='Image'){
					fileType.size = ($('SearchBarFileType'+selectedFileType).checked ? 'All' : 'None');
				}
			
				else if(fileType.type=='Video') {
					hasVideo++;
					fileType.size = ($('SearchBarFileType'+selectedFileType).checked ? 'All' : 'None');
				}
				else{
					fileType.priceOption = ($('SearchBarFileType'+selectedFileType).checked ? 'All' : 'None');
				}
			}
			
		
			if(fileType.type != 'Video' || (hasVideo <= 1 && fileType.type == 'Video')){
				newFileTypeSizePrice.push(fileType);
			}
		});
		
		var fileTypeSizePriceJsonString = Object.toJSON(newFileTypeSizePrice);
		
	
		$('SearchBarFileTypeSizePrice').value = fileTypeSizePriceJsonString;		
		
	
		if(typeof(filtersAndOptions) != "undefined") {
			fileTypeSizePrice.each(function(fileType){
				switch(fileType.type) {
					
				
					case 'Image':
						var type = "FO_Image"
						$(type).value = fileType.size;
						filtersAndOptions.imageOnChange();
						filtersAndOptions.params['FO_FileType'].value[type].value = fileType.size;
						break;
						
					case 'Flash':
						var type = "FO_Flash";
						$(type).value = fileType.priceOption;
						filtersAndOptions.flashOnChange();
						filtersAndOptions.params['FO_FileType'].value[type].value = fileType.priceOption;
						break;
						
					case 'Illustration [Vector]':
						var type = "FO_Illustration";
						$(type).value = fileType.priceOption;
						filtersAndOptions.illustrationOnChange();
						filtersAndOptions.params['FO_FileType'].value[type].value = fileType.priceOption;
						break;
						
					case 'Video':	
						switch (fileType.size) {
							case 'All 4_3':
							case 'None 4_3':
							case 'PAL':
							case 'DV':
							case 'NTSC':
								var type = "FO_Video4_3";
								$(type).value = fileType.size;
								filtersAndOptions.video43OnChange();
								filtersAndOptions.params['FO_FileType'].value[type].value = fileType.size;
								break;	
							case 'All 16_9':
							case 'None 16_9':
							case 'HD 720':
							case 'HD 1080':
								var type = "FO_Video16_9";
								$(type).value = fileType.size;
								filtersAndOptions.video169OnChange();
								filtersAndOptions.params['FO_FileType'].value[type].value = fileType.size;
								break;	
							case 'All':
							case 'None':
							
								var type = "FO_Video4_3";
								$(type).value = fileType.size+' 4_3';
								filtersAndOptions.video43OnChange();
								
								filtersAndOptions.params['FO_FileType'].value[type].value = fileType.size+' 4_3';
								var type = "FO_Video16_9";
								$(type).value = fileType.size+' 16_9';
								filtersAndOptions.video169OnChange();
								filtersAndOptions.params['FO_FileType'].value[type].value = fileType.size+' 16_9';
								break;
						}
					default:
						var type = "";
						break;
				}
			});
		}
		
	
	
		if($("toolPortfolioLink")) {
			var rExp = new RegExp("(.*)fileTypeSizePrice=(.*?)&(.*)", "i");
			var o = $("toolPortfolioLink")
			var matches = o.href.match(rExp);
			o.href=matches[1]+"fileTypeSizePrice="+encodeURI(fileTypeSizePriceJsonString)+"&"+matches[3];
		}
		
	
		var url = "ajax_class_creator.php";
		var params = "ajax_action=saveFileType&ajax_class=searchbarbeta&fileTypeSizePrice="+fileTypeSizePriceJsonString;
		var myAjax = new Ajax.Request
			(
				url, 
				{ 
					method: "get", 
					parameters: params,
					onComplete: this.toggleFileTypeCompleted.bind(this),
					onFailure: this.failed.bind(this)
				}
			);
	},
	
	toggleFileTypeCompleted: function(req) {
			
		var data = req.responseText;
		
	}, 
	
	setSortBy: function(value, skipAJAX) {
		if ( !skipAJAX ){
			skipAJAX = false;
		}
		$('SearchBarOrder').value=value;
		if ( skipAJAX == false ){
			var url = "ajax_class_creator.php";
			var params = "ajax_action=SetSortBy&ajax_class=searchbarbeta&sortBy="+value;
			var myAjax = new Ajax.Request
				(
					url, 
					{ 
						method: "get", 
						parameters: params,
						onComplete: this.setSortByCompleted.bind(this),
						onFailure: this.failed.bind(this)
					}
				);	
		}
	},
	
	setSortByCompleted: function(req) {
		var data = AjaxUtil.receiveArray(req.responseText);
		
		if($("FO_Sort")) {
			$("FO_Sort").value = data.orderString;
		}
		
		if($("toolPortfolioLink")) {
			var rExp = new RegExp("(.*)order=(.*?)&(.*)", "i");
			var o = $("toolPortfolioLink")
			var matches = o.href.match(rExp);
			o.href=matches[1]+"order="+encodeURI(data.orderID)+"&"+matches[3];
		}
	},
	
	failed: function(req) {
	
		return false;
	},
	setHiddenSearchFormFields: function(filters){
		for ( i in filters ){
		
			$(i).value = filters[i];
		}
	},
	getTextValue: function(obj, tipObj){
		if ( obj.value == tipObj.value ){
			return '';
		} else {
			return obj.value;
		}
	},
	
	toggleSearchBar: function(toSimple) {
		var containerBasic = $('SearchBarContainerBasic');
		var containerAdvanced = $('SearchBarContainerAdvanced');
		var advancedSearchLoading = $('AdvancedSearchLoading');
	
		if(toSimple) {
			containerBasic.show();
			togglePopup(containerAdvanced);
			advancedSearchLoading.hide();
			
		} else {
			advancedSearchLoading.show();
			containerBasic.hide(); 
			
		
			if(typeof(filtersAndOptions) === "undefined") {
				LazyLoad.loadJS("/js/ajax_searchfiltersandoptionsbeta.js", this.initAdvancedSearch.bind(this));
			}
			else {
				advancedSearchLoading.hide();
				togglePopup(containerAdvanced);
			}			
		}
	},
	
	initAdvancedSearch:function() {
		filtersAndOptions = new SearchFiltersAndOptionsBetaAjax('FileSearch');
	},
	
	setSearchWithin:function(prefix) {
		if(prefix=="FO_") {
			var isWithin = $("FO_SearchWithinCheckbox").checked;
			$("SearchWithinCheckbox").checked = isWithin;
		} else {
			var isWithin = $("SearchWithinCheckbox").checked;
		
		
		
			if($("FO_SearchWithinCheckbox")) {
				$("FO_SearchWithinCheckbox").checked = isWithin;
			}
		}
		if(isWithin) {
			this.setHiddenSearchFormFields($(prefix+"SearchWithinContract").value.evalJSON(true));
		} else {
			this.setHiddenSearchFormFields($(prefix+"SearchWithinNew").value.evalJSON(true));			
		}
	},
	SearchBarFormSubmit: function(){
		return this.SearchBarFormSubmitGetDisambig();
	},
	SearchBarFormSubmitGetDisambig: function(){
		var searchText = $('SearchBarText');
		var chosenTerms = Array();
		this.currentPreDisambigCheck++;
		var url = "ajax_class_creator.php";
		var params = "ajax_action=getDisambiguation&ajax_class=searchbarbeta" +
			"&searchText=" + this.replacePunctuationAndWhitespace(searchText.value) +
			"&checkNumber=" + this.currentPreDisambigCheck +
			"&preDisambigChoices=" + this.preDisambigChoices.join(',') +
			"";
		var myAjax = new Ajax.Request
			(
				url, 
				{ 
					method: "get", 
					parameters: params,
					onComplete: this.SearchBarFormShowDisambig.bind(this),
					onFailure: this.failed.bind(this)
				}
			);
		ajaxWin.show({
      'title':'',
      'hdrIcon':'/images/loading.gif',
      'hdrTxtClass':'',
      'hdrTxt':'',
      'cntnt':'',
      'footer':'',
      'wdth':300,
			'cnclFunc': 'searchBarAjax.cancelPreDis(' + this.currentPreDisambigCheck + '); '
		});
		return false;
	},
	cancelPreDis: function(checkNumber){
		if(this.currentPreDisambigCheck == checkNumber){
			this.currentPreDisambigCheck++;
		}
	},
	SearchBarFormShowDisambig: function(req){
	
		var data = AjaxUtil.receiveArray(req.responseText);
		if(Number(data.checkNumber) !== Number(this.currentPreDisambigCheck)){
			return false;
		}
		if(data.tags && data.tags.length > 0){
			ajaxWin.show(data.html);
			return false;
		}
		if(TopsearchFormValidate()){
			var filters = $('SearchBarCopySearchBarFiltersJSON').value.evalJSON(true);
			for ( i in filters){
				$(i).value = eval(filters[i]);
				continue; 
				alert(i + ' = ' + eval(filters[i]));
			}
			$('topsearch').submit()
		}
		return false;
	},
	hideDisambig: function(){
		var preDisambiguation = $('SearchBarPreDisambiguation');
		preDisambiguation.style.display = 'none';
	},
	setPreDisambig: function(id, checked){
		var searchBarForm = $('topsearch');
		var inputField = $(id);
		if(!inputField){
			inputField = document.createElement("input");
			inputField.setAttribute("type", "hidden");
			inputField.setAttribute("name", id);
			inputField.setAttribute("id", id);
			searchBarForm.appendChild(inputField);
		}
		if(checked){
			inputField.value = 'true';
			this.preDisambigChoices.push(id);
		}else{
			inputField.value = 'false';
			this.preDisambigChoices = this.preDisambigChoices.without(id);
		}
	},
	replacePunctuationAndWhitespace: function (string){
   
    string = string.replace(/\n+/g, ' ');
    string = string.replace(/\r+/g, ' ');
   
    string = string.replace(/(\s|_|\.)+/g, ' ');
   
    string = string.replace(/(,|\(|\)|\.|\?|!|\||\+|\\|\/|=|"|:|;)+/g, ',');
    return string;
  },
	dummy: function(){
		return false;
	}
};
document.observe('dom:loaded', function() {
	searchBarAjax = new SearchBarBetaAjax(); 
	searchBarAjax.loadEvents();
});
sfHover = function() {
	var sfEls = $$('.sosfh li');
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
Event.observe(window, 'load', function() {
	if (window.attachEvent) window.attachEvent("onload", sfHover);
	if ($('acctDetailsContent')) {
		$('acctDetailsSelector').update($('acctDetailsContent').innerHTML);
		$('acctDetailsTemp').remove();
		buildPopupIFrame($("acctDetailsSelector"), true);
		
		$('acctDetails').onmouseover = $('acctDetailsSelector').onmouseover;
		$('acctDetails').onmouseout = $('acctDetailsSelector').onmouseout;
		
		$('acctDetailsSelector').hide();
		$('acctDetailsSelector').style.left = $('acctDetails').offsetLeft+'px';
		$('acctDetailsSelector').style.top = $('acctDetails').offsetTop + $('acctDetails').getHeight() +'px';
		
		if ($('acctDetailsSelectorIFrame')) {
			$('acctDetailsSelectorIFrame').style.left = $('acctDetails').offsetLeft+'px';
			$('acctDetailsSelectorIFrame').style.top = $('acctDetails').offsetTop + $('acctDetails').getHeight() +'px';
			$('acctDetailsSelectorIFrame').style.width = $('acctDetailsSelector').getWidth()+'px';
			$('acctDetailsSelectorIFrame').style.height = $('acctDetailsSelector').getHeight()+'px';
			$('acctDetailsSelectorIFrame').style.zIndex = $('acctDetailsSelector').zIndex -1;
		}
	}
});
