/**

selector.js by John Bell
v3.2, modified by Jon Ippolito to remove warning for removal of last filter criterion.

selectorData.selectorID
selectorData.width
selectorData.height
selectorData.columnCount
selectorData.columnBuffer
selectorData.dataArray
selectorData.highlightColor
selectorData.highlightTextColor
selectorData.titleHeight
selectorData.buttonHeight
selectorData.titleText
selectorData.titleBuffer


**/
function selectorScreen(selectorData){
	/*********************************************************VARIABLES**/
	//Initialize Class Variables
	
	this.titleHeight = defined(selectorData.titleHeight) ? selectorData.titleHeight : 10;	//Height of the titlebar
	this.titleBuffer = defined(selectorData.titleBuffer) ? selectorData.titleBuffer : 3;	//Buffer between titlebar and columns
	this.buttonHeight = defined(selectorData.buttonHeight) ? selectorData.buttonHeight : 10;//Height of the buttonbar
	this.buttonBuffer = defined(selectorData.buttonBuffer) ? selectorData.buttonBuffer : 3;//Buffer between buttonbar and columns
	//this.screenWidth = defined(selectorData.width) ? selectorData.width : 800;					//Width of the selector
	//this.screenHeight = defined(selectorData.height) ? selectorData.height : 500;					//Height of the selector
	this.columnCount = defined(selectorData.columnCount) ? selectorData.columnCount : 3;	//Number of columns
	this.columnBuffer = defined(selectorData.columnBuffer) ? selectorData.columnBuffer : '2'	;//Percent between columns
	this.columnWidth = ((100 - (this.columnBuffer * this.columnCount)) / this.columnCount);	//Width of the columns
	this.columnHeight = (100 - this.buttonHeight - this.titleHeight - this.titleBuffer - this.buttonBuffer);//Height of the columns
	//this.columnHeight = '100%';
	this.titleText = defined(selectorData.titleText) ? selectorData.titleText : "&nbsp;&nbsp;Add Criterion";	//Title Text
	this.textColor = defined(selectorData.textColor) ? selectorData.textColor : [255,255,156];	//Color of text in the columns

	//	Selector Screen Display Variables (DivPlus style array)	
	//new container
	this.selectorContainer = {		width: '50%',
									left: '25%',
									height: '60%',
									top: '20%',
									display: 'none',
									zindex: 1000 };
	
	this.backgroundStyle = {		top: 0,
									left: 0,
									width: '100%',
									height: '100%',
									opacity: .8,
									backgroundColor: [51,136,51],
									container: selectorData.selectorID,
									//html: "<img src=\"media/bgbig.png\" width=\""+String(this.screenWidth)+"\" height=\""+String(this.screenHeight)+"\" />",
									borderWidth: 0,
									borderColor: [0,80,80],
									display: "block",					//This should be 'none', but a kludge was required
									overflow: "hidden",
									//dragger: {dragConstraints: "both"},
									zindex: -1 };
	
	//  Default column style.  This will be modified by selectorData
	this.columnStyle = {			width: this.columnWidth+'%',
									left: 0,
									height: this.columnHeight + '%',
									top: parseInt(this.titleHeight) + parseInt(this.titleBuffer) + '%',
									//borderWidth: 3,
									borderColor: [0,100,100],
									container: selectorData.selectorID,
									overflow: "auto",
									color: this.textColor,
									zindex: 500};
	this.titleStyle = {				width: '100%',
									left: 0,
									height: this.titleHeight+'%',
									top: 0,
									//borderWidth: 3,
									backgroundColor: [51,85,51],
									borderColor: [0,80,80],
									container: selectorData.selectorID,
									overflow: "hidden",
									html: this.titleText,
									fontSize: 20,
									color: [255,255,156],
									borderWidth: {bottom: 2},
									lineHeight: '200%',
									zindex: 1};
	this.closeButtonStyle = {		height: 16,
									width: 86,
									right: 30,
									bottom: 10,
									backgroundColor: [0,180,180],
									container: selectorData.selectorID,
									textAlign: "center",
									fontSize: 14,
									lineHeight: 16,
									cursor: "pointer",
									borderWidth: 1,
									html: "Close",
									borderColor: [0,255,255],
									onmousedown: "this.returnFalse();",
									onmouseup: "this.selector.setDisplay('none');this.style.backgroundColor = \"rgb(0,180,180)\"; this.style.color = \"rgb(0,0,0)\";",
									onmouseover: "this.style.backgroundColor = \"rgb(0,50,50)\"; this.style.color = \"rgb(255,255,255)\";",
									onmouseout: "this.style.backgroundColor = \"rgb(0,180,180)\"; this.style.color = \"rgb(0,0,0)\";",
									zindex: 2 };

									
	//	Other Class Variables
	this.dataArray = selectorData.dataArray;		//Master data array
	this.selectorID = selectorData.selectorID;		//Stores the name of the selector
	this.currentColumn = 0;							//Index of the current column
	this.columns = new Array();						//Container for columns
	this.columnsSelected = new Array();				//Contains the currently selected item in each column
	this.data = new Array();						//Container for column data
	this.highlightColor = defined(selectorData.highlightColor) ? selectorData.highlightColor : "rgb(0,90,50)";	//Background color of the highlighted items
	this.highlightTextColor = defined(selectorData.highlightTextColor) ? selectorData.highlightTextColor : "rgb(255,255,255)";	//Text color of the higlighted items
	/*********************************************************END VARIABLES**/
	
	//	Build the selector
	//this.backgroundStyle.divID = selectorData.selectorID;
	this.selectorContainer.divID = selectorData.selectorID;
	//this.selector = new DivPlus(this.backgroundStyle);
	this.selector = new DivPlus(this.selectorContainer);
	new DivPlus(this.backgroundStyle);
	//  Kludge to get the display:none bug in the kludge to get around the IE PNG transparency bug
	//this.selector.setLeft(-1000);

	this.titleBar = new DivPlus(this.titleStyle);
	for(var i=0; i<this.columnCount; i++){
		this.columnStyle.left = ((parseInt(this.columnWidth) + parseInt(this.columnBuffer)) * i + parseInt(this.columnBuffer))+'%';
		this.columns.push(new DivPlus(this.columnStyle));
		this.columnsSelected.push("");
	}
	
	//Draw the close button
	this.closeButtonStyle.divID = selectorData.selectorID + "closeButton";
	this.closeButton = new DivPlus(this.closeButtonStyle);
	this.closeButton.element.selector = this.selector;
	this.closeButton.element.returnFalse = this.returnFalse;

	
	this.fillColumn(selectorData.dataArray);
	return this;
}

selectorScreen.prototype.fillColumn = function(columnData){
	for(var i=this.currentColumn; i<this.columns.length; i++) this.columns[i].setHTML("");
	for(var columnItem in columnData){
		if(defined(columnData[columnItem]) == "object"){
			this.insertItem(columnItem, columnData[columnItem], "newColumn");
		} else {
			this.insertItem(columnItem, columnData[columnItem], "selectorAction");
		}
	}	
}

selectorScreen.prototype.insertItem = function(itemName, itemData, itemFunction){
	var newItem = document.createElement("div");
	newItem.style.cursor = "pointer";
	newItem.currentSelection = false;
	newItem.itemData = itemData;
	newItem.currentColumn = this.currentColumn;
	newItem.selector = this;
	newItem.itemFunction = itemFunction;
	newItem.innerHTML = itemName;
	newItem.onmousedown = this.returnFalse;
	newItem.onmouseup = this.itemFunction;
	newItem.onmouseover = this.temporaryHighlight;
	newItem.onmouseout = this.temporaryHighlightOff;
	this.columns[this.currentColumn].element.appendChild(newItem);
}

selectorScreen.prototype.returnFalse = function(){
	return false;
}

selectorScreen.prototype.temporaryHighlight = function(){
	this.style.backgroundColor = this.selector.highlightColor;
	this.style.color = this.selector.highlightTextColor;
}

selectorScreen.prototype.temporaryHighlightOff = function(){
	if(this.currentSelection==false) {
		this.style.backgroundColor = "transparent";
		var RGBcolor = "rgb("+this.selector.textColor[0]+","+this.selector.textColor[1]+","+this.selector.textColor[2]+")";
		this.style.color = RGBcolor;
	}
}

selectorScreen.prototype.itemFunction = function(){
	this.style.backgroundColor = this.selector.highlightColor;
	this.style.color = this.selector.highlightTextColor;
	for(var i=this.currentColumn; i<this.selector.columnsSelected.length; i++){
		if(defined(this.selector.columnsSelected[i]) == "object"){
			this.selector.columnsSelected[i].currentSelection = false;
			this.selector.columnsSelected[i].style.backgroundColor="transparent";
			var RGBcolor = "rgb("+this.selector.textColor[0]+","+this.selector.textColor[1]+","+this.selector.textColor[2]+")";
			this.selector.columnsSelected[i].style.color = RGBcolor;
		}
	}
	this.selector.columnsSelected[this.currentColumn] = this;
	this.currentSelection = true;
	switch(this.itemFunction){
		case "newColumn":
			this.selector.currentColumn = this.currentColumn + 1;
			this.selector.fillColumn(this.itemData);
		break;
		case "selectorAction":
			this.selector.selectorAction(this.itemData);
		break;
		default: alert("error in itemFunction");
	}
}

selectorScreen.prototype.selectorAction = function(selection){
	addCriterion(this.columnsSelected[0].innerHTML, selection);
	
//	var displayHTML = "<a href=\"#\" onmousedown='return false' ";
//	displayHTML += "onmouseover='topMenu.setHelp(\"criteriaItem\")' ";
//	displayHTML += "onmouseout='topMenu.clearHelp()' ";
//	displayHTML += "onmouseup='removeCriterion(\""+this.columnsSelected[0].innerHTML+"\",";
//	displayHTML += "\""+selection+"\"); this.innerHTML=\"\"; topMenu.clearHelp();' >";
//	displayHTML += this.columnsSelected[0].innerHTML+": "+selection;
//	displayHTML += "<br /></a>";
//	
//	topMenu.selectors["Master"].element.innerHTML += displayHTML;
//	topMenu.buttons.helpText["criteriaItem"] = "Remove this filter rule";
	this.hide();

//	return false;
}

selectorScreen.prototype.display = function(){
	this.selector.setDisplay("block");
	// this.selector.setLeft(this.backgroundStyle.left);
	// this.selector.setTop(this.backgroundStyle.top);
}

selectorScreen.prototype.hide = function(){
	for(var i=0; i<this.columns.length; i++) this.columns[i].setHTML("");
	this.currentColumn = 0;
	this.fillColumn(this.dataArray);
	for(var i=0; i<this.columnsSelected.length; i++){
		if(defined(this.columnsSelected[i]) == "object"){
			this.columnsSelected[i].currentSelection = false;
			this.columnsSelected[i].style.backgroundColor="transparent";
			var RGBcolor = "rgb("+this.textColor[0]+","+this.textColor[1]+","+this.textColor[2]+")";
			this.columnsSelected[i].style.color = RGBcolor;
		}
	}
	this.selector.setDisplay("none");
}


//Carried over from old pool_tools
function findCriterion(selectorNumber, selectorText){
	for(tag in selectorOptions[selectorNumber]){
		if(selectorText==selectorOptions[selectorNumber][tag]){
			addCriterion(selectorNumber, tag);
		}
	}
}

function addCriterion(selectorName,selectorItem){
	var selectorArray = eval(selectorArrayMap[selectorName]);
	var displayHTML = "<a id=\""+selectorName+"\" href=\"#\" onmousedown='return false' ";
	displayHTML += "onmouseover='topMenu.setHelp(\"criteriaItem\")' ";
	displayHTML += "onmouseout='topMenu.clearHelp()' ";
	displayHTML += "onmouseup='removeCriterion(\""+selectorName+"\",";
//	displayHTML += "\""+selectorItem+"\"); this.innerHTML=\"\"; topMenu.clearHelp();' >";
	displayHTML += "\""+selectorItem+"\", this);' >";
	if(selectorName == 'title') displayHTML += 'X&nbsp;&nbsp;In Title: '+selectorItem;
	else displayHTML += "X&nbsp;&nbsp;" + selectorName+": "+selectorArray[selectorItem];
	displayHTML += "<br /></a>";
	
	topMenu.selectors["Master"].element.innerHTML += displayHTML;
	topMenu.buttons.helpText["criteriaItem"] = "Remove this filter rule";	
	
	criterion.push([selectorName, selectorItem]);
	workingBasin.state.filters = criterion;
	if(init == false) ProtoHistoryObj.savePool(workingBasin.state);
	
	//ADDED 2/25/06
	var now = new Date();
	now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
	
	var criterionCookie = getCookie(selectorName);
	if(!criterionCookie) setCookie(selectorName, selectorItem, now);
	else {
		var cookieArray = criterionCookie.split("||||");
		var found = false;
		for(var i = 0; i < cookieArray.length; i++){
			if(cookieArray[i] == selectorItem) found = true;	
		}
		if(!found) cookieArray.push(selectorItem);
		var cookieString = cookieArray.join("||||");
		setCookie(selectorName, cookieString, now);
	}
	
	//END ADDED
	
	workingBasin.filterFish();
}

function addInitialCriterion(selectorName, selectorValue){
//This is the same as the function above except that selectorValue is a human-readable word.  It searches selectorName to find selectorItem
	var selectorArray = eval(selectorArrayMap[selectorName]);
	for(var hr in selectorArray){
		if(selectorArray[hr] == selectorValue){
			addCriterion(selectorName, hr);
			break;
		}
	}
}

function removeCriterion(selectorName, selectorItem, anchorText){
	// Jon removed dire warning in v3.2 but left criterion length accounting.	
	for(var i=criterion.length - 1; i >= 0; i--){
		if(criterion[i][0] == selectorName && criterion[i][1] == selectorItem){
			criterion.splice(i, 1);	
		}	
	}	

	//Titles are treated differently...
	if(selectorName == 'title') {
		document.getElementById('searchBox').value = '';	
	}
	anchorText.innerHTML="";
	topMenu.clearHelp();
	
	//ADDED 2/25/06
	var now = new Date();
	now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
	
	var criterionCookie = getCookie(selectorName);
	if(criterionCookie) {
		var cookieArray = criterionCookie.split("||||");
		for(var i = 0; i < cookieArray.length; i++){
			if(cookieArray[i] == selectorItem) cookieArray.splice(i,1);	
		}
		var cookieString = cookieArray.join("||||");
		setCookie(selectorName, cookieString, now);
	}
	
	//END ADDED
	
	ProtoHistoryObj.savePool(workingBasin.state);
	workingBasin.filterFish();
}



///New cookie handling functions
//Copy/Paste from http://www.webreference.com/js/column8/functions.html

/*
   name - name of the cookie
   value - value of the cookie
   [expires] - expiration date of the cookie
     (defaults to end of current session)
   [path] - path for which the cookie is valid
     (defaults to path of calling document)
   [domain] - domain for which the cookie is valid
     (defaults to domain of calling document)
   [secure] - Boolean value indicating if the cookie transmission requires
     a secure transmission
   * an argument defaults when it is assigned null as a placeholder
   * a null placeholder is not required for trailing omitted arguments
*/

function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

/*
  name - name of the desired cookie
  return string containing value of specified cookie or null
  if cookie does not exist
*/

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

/*
   name - name of the cookie
   [path] - path of the cookie (must be same as path used to create cookie)
   [domain] - domain of the cookie (must be same as domain used to
     create cookie)
   path and domain default if assigned null or omitted if no explicit
     argument proceeds
*/

function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}