/******************************************************************************
* sdsClientRuntime.js
*******************************************************************************

*******************************************************************************
*                                                                             *
* Copyright 2007									                          *
*                                                                             *
******************************************************************************/

function sdsSelectionTableLimitChange(select)
{
	var form = select.form;
	form.submit();
}

var sdsLinks = {};
function sdsTableActionExecute(a, linkName, id, needSelection, parameterName, warning)
{
	var selectionTable = SdsSelectionTable.prototype.getSelectionTableFromElement(a);
	if(selectionTable == null) return false;
	selectionTable.actionExecute(a, linkName, id, needSelection, parameterName, warning);
}

var allSdsSelectionTables = {
}

function SdsSelectionTable(className, enumeratorId, id, hasRanking, hasDragAndDropOnRanking, hasSelection, restictrictAllToVisible, displayMode, selectionLabels)
{
	this._className = className;
	this._enumeratorId = enumeratorId;
	this._id = id;
	allSdsSelectionTables[id] = this;
	this._table = document.getElementById(id);
	this._hasRanking = hasRanking;
	this._hasDragAndDropOnRanking = hasDragAndDropOnRanking;
	this._hasSelection = hasSelection;
	this._restictrictAllToVisible = restictrictAllToVisible;
	this._labels = {};
	this._details = {};
	this._selectionLabels = selectionLabels;
	this._selection = {};
	this._ranks = {};
	this._inputs = [];
	this._displayMode = displayMode;
	this._dragAndDropManager = window.sdsDragAndDropManager.getBestManager();
	if(this._table != null) {
		this._tbody = this._table.getElementsByTagName("tbody")[0];
		if(this._displayMode != 0) {
			this._viewContainer = this._tbody.getElementsByTagName("td")[0];
		}
		var tr = this._tbody.getElementsByTagName("tr")[0];
		var cells = tr.getElementsByTagName("td");
		var nbCols = 0;
		this._nbCols = cells.length;
		if(this._hasRanking && this._hasDragAndDropOnRanking) this.initRanking();
		if(this._hasSelection) this.initSelection();
		if(this._hasSelection || (this._hasRanking && this._hasDragAndDropOnRanking)) this.initSelectionOrRanking();
		this._ok = true;
	} else {
		this._ok = false;
	}
}
SdsSelectionTable.prototype.actionExecute = function(a, linkName, id, needSelection, parameterName, warning) {
    warning = warning == "" ? null : warning;
    var link = sdsLinks[linkName];
    if (link == null) return false;
    var form = a;
    while (form && form.nodeType == 1 && form.tagName != "FORM") {
        form = form.parentNode;
    }
    if (form == null || form.nodeType != 1) return;
    var checkboxes = form.elements["oids"];
    if (checkboxes == null) checkboxes = new Array();
    if (checkboxes.length == null) {
        checkboxes = new Array(checkboxes);
    }
    var oids = "";
    var topCheckbox = document.getElementById("topSelect_" + id);
    if (topCheckbox && topCheckbox.checked && !this._restictrictAllToVisible) {
        oids = "all";
    } else {
        for (var i = 0; i < checkboxes.length; i++) {
            var checkbox = checkboxes[i];
            if (!checkbox.checked) continue;
            if (oids != "") oids += " ";
            oids += checkbox.value;
        }
        if (oids == "" && needSelection) {
            alert("La sélection est vide!\n");
            return false;
        }
    }
    if (parameterName != "" && parameterName != null) {
        if (link.indexOf("?") >= 0) link += "&";
        else link += "?";
        link += parameterName + "=" + oids.replace(/ /g, "+");
    }
    if (warning != null) {
        if (!window.confirm(warning))
            return false;
    }
    if (!isDiffusion) {
        context.previewManager.followLink(document, link);
        return false;
    }
    a.href = link;
    return true;
}

SdsSelectionTable.prototype.getTbody = function()
{
	return this._tbody;
}
SdsSelectionTable.prototype.checkall = function(ev)
{
    ev || (ev = window.event);
    var element = document.all ? ev.srcElement : ev.target;
	var selectionTable = SdsSelectionTable.prototype.getSelectionTableFromElement(element);
	if(selectionTable == null) return;
	return selectionTable.oncheckall(ev, element);
}

SdsSelectionTable.prototype.oncheckall = function(ev, input)
{
	var id = this._id;
	var checked = input.checked;
	var form = input.form;
	var checkboxes;
	checkboxes = form["oids"];
	if(checkboxes == null) checkboxes = new Array();
	if(checkboxes.length == null) {
		checkboxes = new Array(checkboxes);
	}
	var v = checked ? 1:0;
	for(var i=0;i<checkboxes.length;i++) {
		var checkbox = checkboxes[i];
		checkbox.checked = checked;
		if(!this._restictrictAllToVisible) checkbox.disabled = checked;
		this._selection[checkbox.value] = v;
	}
	this.updateSelectionLabel();
	var input = document.getElementById("topSelect_" + id);
	if(input != null) input.checked = checked;
	var input = document.getElementById("bottomSelect_" + id);
	if(input != null) input.checked = checked;
	this.allCheckboxChange();
}

SdsSelectionTable.prototype.oncheck = function(ev, input)
{
	this._selection[input.value] = input.checked ? 1:0;
	this.updateSelectionLabel();
	this.checkboxChange(input);
}

SdsSelectionTable.prototype.formatCountLabel = function(count)
{
	var labels = this._selectionLabels;
	if(labels == null) labels = [];
	var label;
	if(count == 0) {
		label = labels[0];
	} else if(count == 1) {
		label = labels[2];
	} else {
		label = labels[3];
	}
	if(label == null) label = "%1 objet(s)";
	return label.replace("%1", "" + count);
}

SdsSelectionTable.prototype.updateSelectionLabel = function()
{
	if(!this._hasSelection) return;
	var id = this._id;
	var label = "";
	var labels = this._selectionLabels;
	var count = 0;
	var inputs = this._tbody.getElementsByTagName("input");
	for(var i=0;i<inputs.length;i++) {
		var input = inputs[i];
		if(input.type != "checkbox") continue;
		if(input.name != "oids") continue;
		if(input.checked) count++;
	}
	if(this._topCheckbox && this._topCheckbox.checked) {
		label = (!this._restictrictAllToVisible) ? labels[1] : labels[3];
	} else {
		if(count == 0) {
			label = labels[0];
		} else if(count == 1) {
			label = labels[2];
		} else {
			label = labels[3];
		}
	}
	label = label.replace("%1", "" + count);
	var span = document.getElementById("topLabel_" + id);
	if(span != null) span.innerHTML = label;
	var span = document.getElementById("bottomLabel_" + id);
	if(span != null) span.innerHTML = label;
	this.allCheckboxChange();
}

SdsSelectionTable.prototype.check = function(ev)
{
    ev || (ev = window.event);
    var element = document.all ? ev.srcElement : ev.target;
	var selectionTable = SdsSelectionTable.prototype.getSelectionTableFromElement(element);
	if(selectionTable == null) return;
	return selectionTable.oncheck(ev, element);
}


SdsSelectionTable.prototype.checkboxChange = function(input)
{
	if(this._displayMode == 0) {
		var tr = input.parentNode.parentNode;
		if(input.checked) {
			tr.className = "sdsTableSelectedRow";
		} else {
			var rank = this._ranks[input.value];
			tr.className = (rank % 2 == 0) ? "odd":"even";
		}
	} else {
		var div = input.parentNode;
		if(input.checked) {
			div.className = "sdsBlockViewSelected";
		} else {
			div.className = "sdsBlockView";
		}
	}
}

SdsSelectionTable.prototype.allCheckboxChange = function()
{
	var checkBoxes = this._tbody.getElementsByTagName("input");
	for(var i=0;i<checkBoxes.length;i++) {
		var input = checkBoxes[i];
		if(input.name != "oids") continue;
		this.checkboxChange(input);
	}
}

SdsSelectionTable.prototype.getEnumerator = function()
{
	return allItlEnumerator[this._enumeratorId];
}
SdsSelectionTable.prototype.getSelectionTableFromElement = function(element)
{
	while(element && element.nodeType == 1) {
		var selectionTable = allSdsSelectionTables[element.id];
		if(selectionTable) return selectionTable;
		element = element.parentNode;
	}
	return null;
}

SdsSelectionTable.prototype.initSelection = function()
{
	this._topCheckbox = document.getElementById("topSelect_" + this._id);
	this._bottomCheckbox = document.getElementById("bottomSelect_" + this._id);
	if(this._topCheckbox) this.addEvent(this._topCheckbox, "click", this.checkall);
	if(this._bottomCheckbox) this.addEvent(this._bottomCheckbox, "click", this.checkall);
	var inputs = this._tbody.getElementsByTagName("input");
	for(var i=0,rank=0;i<inputs.length;i++) {
		var input = inputs[i];
		if(input.type != "checkbox") continue;
		if(input.name != "oids") continue;
		this.addEvent(input, "click", this.check);
		this._ranks[input.value] = rank++;
	}
	this.updateSelectionLabel();
}

SdsSelectionTable.prototype.initRanking = function()
{
	var children = this._tbody.childNodes;
	var count = 0;
	for(var i = 0;i <children.length;i++) {
		var child = children[i];
		if(child.tagName != "TR") continue;
		var oid = this.getTrOid(child);
		this._ranks[oid] = i;
	}
	//this.addEvent(document.body, "mouseup", this.mouseup);
}

SdsSelectionTable.prototype.initSelectionOrRanking = function()
{
	this._tbody.style.cursor = "hand";
	this.addEvent(this._tbody, "click", this.click, false);
	this.addEvent(this._tbody, "selectstart", this.cancelevent);
	this.addEvent(this._tbody, "dragstart", this.cancelevent);
	this.addEvent(this._tbody, "mousedown", this.mousedown, false);
}

SdsSelectionTable.prototype.getTrOid = function(tr)
{
	return parseInt(tr.id.substr(1), 10);
}

SdsSelectionTable.prototype.cancelevent = function(ev)
{
    ev || (ev = window.event);
	ev.cancelBubble = true;
	ev.returnValue = false;
}

SdsSelectionTable.prototype.click = function(ev)
{
    ev || (ev = window.event);
    var element = document.all ? ev.srcElement : ev.target;
	var selectionTable = SdsSelectionTable.prototype.getSelectionTableFromElement(element);
	if(selectionTable == null) return;
	return selectionTable.onclick(ev, element);
}

SdsSelectionTable.prototype.onclick = function(ev, element)
{
	if(!this._disableClick) return;
	if(element.tagName == "A") return;
	var tr = this.getAncestorTr(element);
	if(tr == null) return;
	this.selectTr(tr);
/*
	if(this._hasSelection) {
		var input = tr.getElementsByTagName("input")[0];
		if(input == null) return false;
		var oid = input.value;
		input.click();
	} else {
		this.selectTr(tr);
	}
*/
}

SdsSelectionTable.prototype.mousedown = function(ev)
{
    ev || (ev = window.event);
    var element = document.all ? ev.srcElement : ev.target;
	if(element.tagName == "TBODY") return true;
	if(element.tagName == "INPUT") return;
	if(element.tagName == "A") return true;
	var selectionTable = SdsSelectionTable.prototype.getSelectionTableFromElement(element);
	if(selectionTable == null) return;
	return selectionTable.onmousedown(ev, element);
}

SdsSelectionTable.prototype.getAncestorTr = function(tr)
{
	if(this._displayMode == 0) {
		while(tr && tr.tagName != "TR") {
			tr = tr.parentNode;
		}
		return tr;
	} else {
		while(tr && tr.parentNode && tr.parentNode.tagName != "TD") {
			tr = tr.parentNode;
		}
		return tr;
	}
}

SdsSelectionTable.prototype.onmousedown = function(ev, element)
{
	var tr = this.getAncestorTr(element);
	var canDrag = false;
	if(tr !=null) {
		var oid = this.getTrOid(tr);
		var canDrag = this._selection[oid] == 1;
		var type = "collection:" + this._className;
		if(canDrag) {
			if(this._hasDragAndDropOnRanking) {
				this._disableClick = true;
				this.dragstart(ev, element);
			} else if(this._dragAndDropManager.hasTargetForType(type)) {
				this._disableClick = true;
				var count = 0;
				for(var oid in this._selection) {
					if(this._selection[oid]) count++;
				}
				var label = this.formatCountLabel(count);
				var dragObject = new SdsDragAndDropObject(type, this.getSelectedOids(), label);
				this._dragAndDropManager.start(ev, dragObject);
			} else {
				this._disableClick = false;
				this.selectTr(tr);
			}
		} else {
			this._disableClick = false;
			if(this.movestart(ev, element) != null) {
				//if(!this.isSelected(tr)) 
				this.selectTr(tr);
				this.addEvent(document.body, "mousemove", this.mousemove);
			}
		}
		this.addEvent(document.body, "mouseup", this.mouseup);
	}
}

SdsSelectionTable.prototype.isSelected = function(tr)
{
	var oid = this.getTrOid(tr);
	return this._selection[oid] == 1;
}

SdsSelectionTable.prototype.selectTr = function(tr)
{	
	if(this._hasSelection) {
		var input = tr.getElementsByTagName("input")[0];
		if(input == null) return false;
		var oid = input.value;
		input.click();
		this._selection[oid] = input.checked ? 1:0;
	} else {
		var oid = this.getTrOid(tr);
		if(this._selection[oid] == 1) {
			var rank = this._ranks[oid];
			tr.className = (rank % 2 == 0) ? "odd":"even";
			this._selection[oid] = 0;
		} else {
			tr.className = "sdsTableSelectedRow";
			this._selection[oid] = 1;
		}
	}
}

SdsSelectionTable.prototype.getTrRank = function(element)
{
	var tr = this.getAncestorTr(element);
	if(tr == null) return;
	var oid = this.getTrOid(tr);
	return this._ranks[oid];
	
}

SdsSelectionTable.prototype.movestart = function(ev, element)
{
	rank = this.getTrRank(element);
	if(rank == null) return;
	return this._minRank = this._maxRank = this._lastRank = this._startRank = rank;
}
SdsSelectionTable.prototype.getSelectedOids = function()
{
	var oids = "";
	for(var oid in this._selection) {
		if(this._selection[oid] != 1) continue;
		if(oids != "") oids += " ";
		oids += oid;
	}
	return oids;
}

SdsSelectionTable.prototype.getSelectionDescr = function()
{
	var oids = [];
	var labels = [];
	var details = [];
	for(var oid in this._selection) {
		if(this._selection[oid] != 1) continue;
		var label = this._labels[oid];
		if(label == null) label = "????";
		var detail = this._details[oid];
		if(detail == null) detail = "????";
		oids[oids.length] = oid;
		labels[labels.length] = label;
		details[details.length] = detail;
	}
	return {oids:oids, labels:labels, details:details};
}

SdsSelectionTable.prototype.getAllDescr = function()
{
	var oids = [];
	var labels = [];
	var details = [];
	for(var oid in this._ranks) {
		var label = this._labels[oid];
		if(label == null) label = "????";
		var detail = this._details[oid];
		if(detail == null) detail = "????";
		oids[oids.length] = oid;
		labels[labels.length] = label;
		details[details.length] = detail;
	}
	return {oids:oids, labels:labels, details:details};
}

SdsSelectionTable.prototype.setOidLabel = function(oid, label)
{
	this._labels[oid] = label;
}

SdsSelectionTable.prototype.setLabels = function(labels)
{
	this._labels = labels;
}
SdsSelectionTable.prototype.setDetails = function(details)
{
	this._details = details;
}

SdsSelectionTable.prototype.dragstart = function(ev, element)
{
	var oids = this.getSelectedOids();
	if(oids == "") return;
	this._drag = oids;
	var shadowRow = this._shadowRow;
	if(shadowRow == null) {
		this._shadowRow = shadowRow = document.createElement("TR");
		var shadowCell = this._shadowCell = document.createElement("TD");
		shadowRow.className = "sdsTableSelectedRow";
		shadowRow.appendChild(shadowCell);
		shadowCell.colSpan = this._nbCols;
		shadowCell.innerHTML = "";
		shadowCell.style.height = "10px";
	}
	this.addEvent(document.body, "mousemove", this.dragmove);
}
SdsSelectionTable.prototype.dragmove = function(ev)
{
	ev || (ev = window.event);
    var element = document.all ? ev.srcElement : ev.target;
	var selectionTable = SdsSelectionTable.prototype.getSelectionTableFromElement(element);
	if(selectionTable == null) {
		return;
	}
	if(document.all && ev.button == 0) {
		selectionTable.dragstop(ev, element);
		return;
	}
	if(selectionTable == null) return;
	return selectionTable.ondragmove(ev, element);
}

SdsSelectionTable.prototype.ondragmove = function(ev, element)
{
	this.findTableRow(ev, element);
}

SdsSelectionTable.prototype.getPositionTop = function(elm)
{
	var mOffsetTop = elm.offsetTop;
	var mOffsetParent = elm.offsetParent;
	
	while(mOffsetParent!=null) {
		//if(document.all && mOffsetParent.currentStyle.position == "absolute") break;
		//if(!document.all && window.getComputedStyle(mOffsetParent, "").position == "absolute") break;

		mOffsetTop += mOffsetParent.offsetTop;
		mOffsetParent = mOffsetParent.offsetParent;
	}	
	return mOffsetTop;
}

SdsSelectionTable.prototype.getPositionLeft = function(elm)
{
	var mOffsetLeft = elm.offsetLeft;
	var mOffsetParent = elm.offsetParent;
	
	while(mOffsetParent!=null) {
		if(document.all && mOffsetParent.currentStyle.position == "absolute") break;
		if(!document.all && window.getComputedStyle(mOffsetParent, "").position == "absolute") break;
		mOffsetLeft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;
	}	
	return mOffsetLeft;
}

SdsSelectionTable.prototype.findTableRow = function(ev, element)
{
	var lastPosition = this._targetPosition;
	var tr = this.getAncestorTr(element);
	if(tr == null || tr.parentNode != this._tbody) return;
	this._targetPosition = null;
	if(this._shadowRow == null) return;
	if(tr != this._shadowRow) {
		var p = this.getTrRank(tr);
		var minY = this.getPositionTop(tr);
		var maxY = minY + tr.clientHeight;
		if(ev.clientY * 2 > minY + maxY) {
			p++;
		}
		if(p != lastPosition) {
			if(this._shadowRow.parentNode && this._shadowRow.parentNode.nodeType == 1) this._tbody.removeChild(this._shadowRow);
			if(p >= lastPosition) {
				if(tr.nextSibling) {
					this._tbody.insertBefore(this._shadowRow, tr.nextSibling);
				} else {
					this._tbody.appendChild(this._shadowRow);
				}
			} else {
				this._tbody.insertBefore(this._shadowRow, tr);
			}
		}
	}
	var previous = this._shadowRow.previousSibling;
	var position = 0;
	while(previous) {
		position++;
		previous = previous.previousSibling;
	}
	this._targetPosition = position;
	if(!document.all) {
		var w = element.ownerDocument.defaultView;
		selection = w.getSelection();
		selection.removeAllRanges();
	}
}


SdsSelectionTable.prototype.mouseup = function(ev)
{
    ev || (ev = window.event);
    var element = document.all ? ev.srcElement : ev.target;
	var selectionTable = SdsSelectionTable.prototype.getSelectionTableFromElement(element);
	if(selectionTable == null) return;
	return selectionTable.onmouseup(ev, element);
}

SdsSelectionTable.prototype.onmouseup = function(ev, element)
{
	if(this._drag) this.dragstop(ev, element);
	else this.movestop(ev, element);
}

SdsSelectionTable.prototype.movestop = function(ev, element)
{
	this._minRank = this._maxRank = this._lastRank = this._startRank = null;
	this.removeEvent(document.body, "mousemove", this.mousemove);
	ev.cancelBubble = true;
	ev.returnValue = false;
}

SdsSelectionTable.prototype.dragstop = function(ev, element)
{
	var doJob = false;
	var anchor = null;
	if(this._targetPosition != null && this._drag != null) {
		var enumerator = this.getEnumerator();
		if(enumerator != null) {
			var oids = this._drag.split(" ");
			var map = {};
			for(var i=0;i<oids.length;i++) {
				var oid = oids[i];
				if(oid == "") continue;
				map[oid] = 1;
			}
			var oids = enumerator.getOids().split(" ");
			var position = this._targetPosition;
			if(position > oids.length) position = oids.length;
			var oidString = "";
			for(var i=0;i<position;i++) {
				var oid = oids[i];
				if(oid == "") continue;
				if(map[oid]) continue;
				if(oidString != "") oidString += " ";
				oidString += oid;
			}
			if(oidString != "") oidString += " ";
			oidString += this._drag;
			for(var i=position;i<oids.length;i++) {
				var oid = oids[i];
				if(oid == "") continue;
				if(map[oid]) continue;
				if(oidString != "") oidString += " ";
				oidString += oid;
			}
			doJob = true;
			anchor = "I" + this._drag.split(" ")[0];
		}
	}
	this._targetPosition = null;
	this._drag = null;
	ev.cancelBubble = true;
	ev.returnValue = false;
	this.removeEvent(document.body, "mousemove", this.dragmove);
	this.removeEvent(document.body, "mouseup", this.mouseup);
	if(this._shadowRow && this._shadowRow.parentNode) {
		this._shadowRow.parentNode.removeChild(this._shadowRow);
	}	
	if(doJob) enumerator.reOrder(oidString, anchor);
}

SdsSelectionTable.prototype.mousemove = function(ev)
{
    ev || (ev = window.event);
    var element = document.all ? ev.srcElement : ev.target;
	var selectionTable = SdsSelectionTable.prototype.getSelectionTableFromElement(element);
	if(selectionTable == null) {
		return;
	}
	if(selectionTable._startRank == null || (document.all && ev.button == 0)) {
		selectionTable.movestop(ev, element);
		return;
	}
	return selectionTable.onmousemove(ev, element);
}

SdsSelectionTable.prototype.getTrByRank = function(rank)
{
	if(this._displayMode == 0) {
		return this._tbody.childNodes[rank];
	} else {
		return this._viewContainer.childNodes[rank];
	}
}

SdsSelectionTable.prototype.onmousemove = function(ev, element)
{
	var rank = this.getTrRank(element);
	if(rank == null) return;
	if(rank ==  this._lastRank) return;
	this._disableClick = true;
	var tr = this.getAncestorTr(element);
	var lastTr = this.getTrByRank(this._lastRank);
	if(rank == this._startRank) {
		if(rank > this._lastRank) {
			for(var r = this._lastRank; r <= rank;r++) {
				var t = this.getTrByRank(r);
				if(this.isSelected(t)) this.selectTr(t);
			}
		} else {
			for(var r = rank; r <= this._lastRank;r++) {
				var t = this.getTrByRank(r);
				if(this.isSelected(t)) this.selectTr(t);
			}
		}
	} else if(rank > this._startRank) {
		if(rank > this._lastRank) {
			for(var r = this._lastRank; r <= rank;r++) {
				var t = this.getTrByRank(r);
				if(!this.isSelected(t)) this.selectTr(t);
			}
		} else {
			for(var r = rank; r <= this._lastRank;r++) {
				var t = this.getTrByRank(r);
				if(this.isSelected(t)) this.selectTr(t);
			}
		}
	} else {
		if(rank < this._lastRank) {
			for(var r = rank; r <= this._lastRank;r++) {
				var t = this.getTrByRank(r);
				if(!this.isSelected(t)) this.selectTr(t);
			}
		} else {
			for(var r = this._lastRank; r <= rank;r++) {
				var t = this.getTrByRank(r);
				if(this.isSelected(t)) this.selectTr(t);
			}
		}
		
	}
	this._lastRank = rank;
	if(!document.all) {
		var w = element.ownerDocument.defaultView;
		selection = w.getSelection();
		selection.removeAllRanges();
	}

}
SdsSelectionTable.prototype.addEvent = function(element, evname, func, capture) 
{
    if (element.attachEvent) { // IE
        element.attachEvent("on" + evname, func);
    } else if (element.addEventListener) { // Gecko / W3C
        element.addEventListener(evname, func, capture != false);
    } else {
        element["on" + evname] = func;
    }
}

SdsSelectionTable.prototype.removeEvent = function(element, evname, func) 
{
	if (element.detachEvent) { // IE
		element.detachEvent("on" + evname, func);
	} else if (element.removeEventListener) { // Gecko / W3C
		element.removeEventListener(evname, func, true);
	} else {
		element["on" + evname] = null;
	}
}



function SdsSplitterPanel(containerId, rank, vertical, div, parameters)
{
    this._containerId = containerId;
    this._rank = rank;
    this._vertical = vertical;
    this._div = div;
    if(parameters == null) parameters = [20, 100];
    this._min = parameters[0];
    this._size = parameters[1];
    div.id = containerId + "_d" + rank;
}

SdsSplitterPanel.prototype.getContainer = function()
{
    return SdsSplitterContainer.prototype._containers[this._containerId];
}
SdsSplitterPanel.prototype.setSize = function(size)
{
    if(this._vertical) {
        return this.setHeight(size);
    } else {
        return this.setWidth(size);
    }
}
SdsSplitterPanel.prototype.getSize = function()
{
    if(this._vertical) {
        return this._height;
    } else {
        return this._width;
    }
}
SdsSplitterPanel.prototype.setHeight = function(size)
{
     if(size == this._height) return false;
     this._height = size;
     this._div.style.height = size + "px";
     this._needResize = true;
     return true;
}
SdsSplitterPanel.prototype.setWidth = function(size)
{
     if(size == this._width) return false;
     this._width = size;
     this._div.style.width = size + "px";
     this._needResize = true;
     return true;
}

SdsSplitterPanel.prototype._studyContent = function()
{
	if(this._studyContentDone) return this._singleChildElement;
	this._studyContentDone = true;
    var childElement = null;
    var children = this._div.childNodes;
    var n = 0;
    for(var i=0;i<children.length;i++) {
        var child = children.item(i);
        switch(child.nodeType) {
        case 1:
			if(child.tagName == "SCRIPT") continue;
			childElement = child;
	        n++;
            break;
        case 3:
            var t = child.nodeValue;
            t = t.replace(/^\s+/, "").replace(/\s+$/, "");
            if(t != "") n++;
        }
    }
    if(n == 1 && childElement) {
		this._singleChildElement = childElement;
	}
	return this._singleChildElement;
}

SdsSplitterPanel.prototype.startMove = function()
{
	if(document.all) return;
	var childElement = this._studyContent();
	if(childElement == null || childElement.tagName != "IFRAME") return;
	var target = childElement.contentDocument.body;
	SdsSplitter.prototype.addEvent(target, "mouseup", SdsSplitterContainer.prototype.onmouseup, false); 
	SdsSplitter.prototype.addEvent(target, "mousemove", SdsSplitterContainer.prototype.onmousemove, false); 
}

SdsSplitterPanel.prototype.stopMove = function()
{
	if(document.all) return;
	var childElement = this._studyContent();
	if(childElement == null || childElement.tagName != "IFRAME") return;
	var target = childElement.contentDocument.body;
	SdsSplitter.prototype.removeEvent(target, "mouseup", SdsSplitterContainer.prototype.onmouseup, false); 
	SdsSplitter.prototype.removeEvent(target, "mousemove", SdsSplitterContainer.prototype.onmousemove, false); 
}

SdsSplitterPanel.prototype.resize = function()
{
    if(!this._needResize || this._inResize) return;
    this._needResize = false;
    this._inResize = true;
	var childElement = this._studyContent();
    if(childElement) {
        var subContainer = SdsSplitterContainer.prototype._containers[childElement.id]        
		if(subContainer) {
		    subContainer.setSizes(this._width, this._height);
        } else {
            switch(childElement.tagName) 
            {
            case "IFRAME":
                childElement.width = this._width;
                childElement.height = this._height;
                break;
            }
        }
    }
    this._inResize = false;
}

SdsSplitterPanel.prototype.changeSize = function(delta)
{
    var size = this._vertical ? this._height: this._width;
    if(delta > 0 || size + delta - this._min >= 0) {
        size += delta;
        this.setSize(size);
        return 0;
    }
    this.setSize(this._min);
    return size + delta - this._min;
}
SdsSplitterPanel.prototype.reset = function()
{
    this._lastSize = null;
}
function SdsSplitter(containerId, rank, vertical, div)
{
    this._containerId = containerId;
    this._rank = rank;
    this._div = div;
    this._vertical = vertical;
    div.id = containerId + "_s" + rank;
    this.addEvent(div, "mousedown", SdsSplitterContainer.prototype.onmousedownsplitter);
	this._moveCounter = 0;
}
SdsSplitter.prototype.reset = function()
{
}
SdsSplitter.prototype.setSize = function(size)
{
    if(this._vertical) {
        this._div.style.width = size + "px";
    } else {
        this._div.style.height = size + "px";
    }
}
SdsSplitter.prototype.getSize = function()
{
    if(this._vertical) {
        return this._div.style.width;
    } else {
        return this._div.style.height;
    }
}
SdsSplitter.prototype.getContainer = function()
{
    return SdsSplitterContainer.prototype._containers[this._containerId];
}

SdsSplitter.prototype.addEvent = function(element, evname, func, capture) 
{
    if (element.attachEvent) { // IE
        element.attachEvent("on" + evname, func);
    } else if (element.addEventListener) { // Gecko / W3C
        element.addEventListener(evname, func, capture != false);
    } else {
        element["on" + evname] = func;
    }
}
SdsSplitter.prototype.removeEvent = function(element, evname, func, capture) 
{
	if (element.detachEvent) { // IE
		element.detachEvent("on" + evname, func);
	} else if (element.removeEventListener) { // Gecko / W3C
		element.removeEventListener(evname, func, capture != false);
	} else {
		element["on" + evname] = null;
	}
}
SdsSplitter.prototype.getEventPosition = function(ev)
{
    if(document.all) {
        return (this._vertical ? ev.y:ev.x);
    } else {
        return (this._vertical ? ev.clientY:ev.clientX);
    }
}

SdsSplitter.prototype.startMove = function(ev, container)
{
	this._startPosition = this.getEventPosition(ev);
	this._lastDelta = 0;
	if(document.all) this._div.setCapture();
	container._currentSplitter = this;
	this._currentContainer = container;
	this.addEvent(container._div, "mouseup", SdsSplitterContainer.prototype.onmouseup); 
	this.addEvent(container._div, "mousemove", SdsSplitterContainer.prototype.onmousemove); 
	for(var i=0;i<container._panels.length;i++) {
		panel = container._panels[i];
		panel.startMove();
	}
	var beforeSize = container.getSizeBefore(this._rank);
	var minBeforeSize = container.getMinSizeBefore(this._rank);
	var afterSize = container.getSizeAfter(this._rank);
	var minAfterSize = container.getMinSizeAfter(this._rank);
	this._minPosition = minBeforeSize - beforeSize;
	this._maxPosition = afterSize - minAfterSize;
}

SdsSplitter.prototype.getPositionLeft = function(elm)
{
	var mOffsetLeft = elm.offsetLeft;
	var mOffsetParent = elm.offsetParent;
	
	while(mOffsetParent!=null) {
		if(document.all && mOffsetParent.currentStyle.position == "absolute") break;
		if(!document.all && window.getComputedStyle(mOffsetParent, "").position == "absolute") break;
		mOffsetLeft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;
	}	
	return mOffsetLeft;
}

SdsSplitter.prototype.getPositionTop = function(elm)
{
	var mOffsetTop = elm.offsetTop;
	var mOffsetParent = elm.offsetParent;
	
	while(mOffsetParent!=null) {
		if(document.all && mOffsetParent.currentStyle.position == "absolute") break;
		if(!document.all && window.getComputedStyle(mOffsetParent, "").position == "absolute") break;

		mOffsetTop += mOffsetParent.offsetTop;
		mOffsetParent = mOffsetParent.offsetParent;
	}	
	return mOffsetTop;
}

SdsSplitter.prototype.move = function(ev, container)
{
	var pos = this.getEventPosition(ev);
	if(!document.all) {
		var w = ev.target.ownerDocument.defaultView;
		while(w != window && w != w.parent) {
			var pw = w.parent;
			var iframes = pw.document.getElementsByName(w.name);
			var iframe = null;
			for(var i=0;i<iframes.length;i++) {
				iframe = iframes[i];
				if(iframe.tagName != "IFRAME") continue;
				break;
			}
			if(iframe == null) break;
			pos += (this._vertical ? this.getPositionTop(iframe):this.getPositionLeft(iframe));
			w = pw;
		}
	}
	var delta = pos - this._startPosition;
    if(delta < this._minPosition || this._maxPosition < delta) {
        return;
    }
    var d = this._lastDelta;
    this._lastDelta = delta;
    delta -= d;
    if(delta == 0) return;
    container.changeSize(this._rank, delta, true);
    container.changeSize(this._rank+1, -delta, false);
}
SdsSplitter.prototype.stopMove = function(ev, container)
{
	this._startY = null;
	if(document.all) this._div.releaseCapture();
	this.removeEvent(this._div, "mouseup", SdsSplitterContainer.prototype.onmouseup); 
	this.removeEvent(this._div, "mousemove", SdsSplitterContainer.prototype.onmousemove); 
    container.reset();
    container._currentSplitter = null;
}

function SdsSplitterContainer(vertical, fullWidth, fullHeight, id, parameters, widthConstraint, heightConstraint)
{
	splitterContainers[id] = this;
	var container = this._div = document.getElementById(id);
    if(container == null) return;
    if(parameters == null) parameters = [];
    this._vertical = vertical;
    this._id = id;
    this._panels = [];
    this._splitters = [];
    var container = this._div = document.getElementById(id);
    var children = container.childNodes;
    this._fullHeight = fullHeight;
    this._fullWidth = fullWidth;
    for(var i=0;i<children.length;i++) {
        var child = children.item(i);
        if(child.nodeType != 1) continue;
        var rank = this._splitters.length;
        if(rank < this._panels.length) {
            this._splitters[rank] = new SdsSplitter(id, rank, vertical, child);
        } else {
            this._panels[this._panels.length] = new SdsSplitterPanel(id, rank, vertical, child, parameters[rank]);
        }
    }
    this._containers[id] = this;
    this.addEvent(container, "resize", SdsSplitterContainer.prototype.onresize);
    this.setup();
	this._widthConstraint = widthConstraint;
	this._heightConstraint = heightConstraint;
	if(!splitterNeedResize) {
		addResizeActions(sdsWindowResizeSplitters);
		splitterNeedResize = true;
	}
}

SdsSplitterContainer.prototype.reset = function()
{
    for(var i=0;i<this._panels.length;i++) {
        this._panels[i].reset();
    }
    for(var i=0;i<this._splitters.length;i++) {
        this._splitters[i].reset();
    }
}

SdsSplitterContainer.prototype.addEvent = function(element, evname, func) 
{
    if (element.attachEvent) { // IE
        element.attachEvent("on" + evname, func);
    } else if (element.addEventListener) { // Gecko / W3C
        element.addEventListener(evname, func, true);
    } else {
        element["on" + evname] = func;
    }
}
SdsSplitterContainer.prototype.getFullSize = function()
{
    return this._vertical ? this._fullHeight : this._fullWidth;
}
SdsSplitterContainer.prototype.setup = function()
{
   	var maxSize = this.getFullSize();
    var totalSize = 0;
    var sizes = [];
    for(var i=0;i<this._panels.length;i++) {
        var panel = this._panels[i];
        if(this._vertical) {
            panel._height = panel._size; 
            if(panel._height == 0) panel._height = 100; 
            panel._width = this._fullWidth;
        } else {
            panel._width = panel._size; 
            if(panel._width == 0) panel._width = 100; 
            panel._height = this._fullHeight;
        }
        var size = this._vertical ? panel._height : panel._width;
        totalSize += size;
        sizes[i] = size;
    }
    maxSize -= this._splitters.length * 5;
    if(maxSize == totalSize) return;
    var scale = maxSize / totalSize;
    var total = 0;
    for(var i=0;i<this._panels.length;i++) {
        var panel = this._panels[i];
        var newSize;
        if(i == this._panels.length - 1) {
            newSize = maxSize - total;
        } else {
            newSize = Math.round(scale * sizes[i]);
            total += newSize;
        }
        panel.setSize(newSize);
        panel.resize();
    }
    this.resize();
}
SdsSplitterContainer.prototype.debug = function()
{
	debugger;
}
SdsSplitterContainer.prototype.onWindowResize = function()
{
	var newWidth = this._fullWidth;
	var newHeight = this._fullHeight;
	var hasChange = false;
	var ancestor = this._div.offsetParent;
	if(this._widthConstraint != null) {
		if(true || ancestor == document.body) {
			newWidth = document.body.parentNode.clientWidth - this._widthConstraint;
		} else {
			newWidth = this._div.offsetParent.clientWidth - this._widthConstraint;
		}
		if(newWidth > 0) {
			hasChange = true;
		} else {
			newWidth = this._fullWidth;
		}
	}
	if(this._heightConstraint != null) {
		if(true || ancestor == document.body) {
			newHeight = document.body.parentNode.clientHeight - this._heightConstraint;
		} else {
			newHeight = this._div.offsetParent.clientHeight - this._heightConstraint;
		}
		if(newHeight > 0) {
			hasChange = true;
		} else {
			newHeight = this._fullHeight;
		}
	}
	//alert(this._id + "\n" + this._fullWidth + " -> " + newWidth + "\n" + this._fullHeight + " -> " + newHeight);
	if(hasChange) {
		if(this._fullWidth != newWidth || this._fullHeight != newHeight) {
			if(this._fullWidth != newWidth) this._div.style.width = newWidth + "px";
			if(this._fullHeight != newHeight) this._div.style.height = newHeight + "px";
			this.setSizes(newWidth, newHeight);
		}
	}
}
SdsSplitterContainer.prototype.consoleDump = function(msg, clear)
{
	var splitterConsole = document.getElementById("splitterConsole");
	if(splitterConsole == null) {
		splitterConsole = document.createElement("DIV");
		splitterConsole.id = "splitterConsole";
		splitterConsole.style.height = "20px";
		splitterConsole.style.overflow = "auto";
		splitterConsole.style.borderStyle = "solid";
		splitterConsole.style.borderSize = "1px";
		splitterConsole.style.borderColor = "black";
		document.body.appendChild(splitterConsole);
	}
	if(clear) splitterConsole.innerHTML = "";
	var div = document.createElement("DIV");
	div.appendChild(document.createTextNode(msg));
	splitterConsole.appendChild(div);
}
SdsSplitterContainer.prototype.getSplitter = function(rank)
{
    return this._splitters[rank];
}
SdsSplitterContainer.prototype.getPanel = function(rank)
{
    return this._panels[rank];
}
SdsSplitterContainer.prototype.getSizeBefore = function(rank)
{
    var size = 0;
    for(var i=0;i<=rank;i++) {
        var panel = this._panels[i];
        size += this._vertical ? panel._height : panel._width;
    }
    return size;
}

SdsSplitterContainer.prototype.getMinSizeBefore = function(rank)
{
    var size = 0;
    for(var i=0;i<=rank;i++) {
        var panel = this._panels[i];
        size += panel._min;
    }
    return size;
}
SdsSplitterContainer.prototype.getSizeAfter = function(rank)
{
    var size = 0;
    for(var i=rank+1;i<this._panels.length;i++) {
        var panel = this._panels[i];
        size += this._vertical ? panel._height : panel._width;
    }
    return size;
}

SdsSplitterContainer.prototype.getMinSizeAfter = function(rank)
{
    var size = 0;
    for(var i=rank+1;i<this._panels.length;i++) {
        var panel = this._panels[i];
        size += panel._min;
    }
    return size;
}
SdsSplitterContainer.prototype.changeSize = function(rank, delta, up)
{
    var panel = this._panels[rank];
    var d = panel.changeSize(delta);
    if(d != 0) {
        if(up) {
            this.changeSize(rank - 1, d);
        } else {
            this.changeSize(rank + 1, d);
        }
    }
    panel.resize();
}
SdsSplitterContainer.prototype._containers = {};
SdsSplitterContainer.prototype.getInstance = function(element)
{
    if(element == null || element.nodeType != 1) return null;
    var instance = SdsSplitterContainer.prototype._containers[element.id];
    if(instance != null) return instance;
    return SdsSplitterContainer.prototype.getInstance(element.parentNode);
}
SdsSplitterContainer.prototype.onmousedownsplitter = function(ev)
{
    ev || (ev = window.event);
    var element = document.all ? ev.srcElement : ev.target;
	if(element == null) return;
	var id = element.id;
	var pos = id.lastIndexOf("_");
	var rank = parseInt(id.substr(pos + 2), 10);
	var containerId = id.substr(0, pos);
	var container = SdsSplitterContainer.prototype._containers[containerId];
	if(container == null) return;
	SdsSplitterContainer.prototype._currentId = containerId;
	var splitter = container.getSplitter(rank);
	if(splitter == null) return;
	splitter.startMove(ev, container);
}
SdsSplitterContainer.prototype.onmouseup = function(ev)
{
    ev || (ev = window.event);
	var container = SdsSplitterContainer.prototype._containers[SdsSplitterContainer.prototype._currentId];
	if(container == null || container._currentSplitter == null) return;
	container._currentSplitter.stopMove(ev, container);
	container._currentSplitter = null;
	SdsSplitterContainer.prototype._currentId = null;
}
SdsSplitterContainer.prototype.onmousemove = function(ev)
{
    ev || (ev = window.event);
	var container = SdsSplitterContainer.prototype._containers[SdsSplitterContainer.prototype._currentId];
	if(container == null || container._currentSplitter == null) return;
	container._currentSplitter.move(ev, container);
}
SdsSplitterContainer.prototype.onresize = function(ev)
{
	ev || (ev = window.event);
    var element = document.all ? ev.srcElement : ev.target;
	if(element == null) return;
	var container = SdsSplitterContainer.prototype.getInstance(element);
	if(container == null) return;
	container.resize();
}
SdsSplitterContainer.prototype.setSizes = function(width, height)
{
    this._fullWidth = width;
    this._fullHeight = height;
	this._div.style.width = width + "px";
	this._div.style.height = height + "px";
	this.fullSizeHasChanged();
	this.resize();
}
SdsSplitterContainer.prototype.resize = function()
{
    if(this._vertical) {
        var maxSize = this._fullWidth;
        for(var i=0;i<this._panels.length;i++) {
            var panel = this._panels[i];
            panel.setWidth(maxSize);
            panel.resize();
        }
        for(var i=0;i<this._splitters.length;i++) {
            var splitter = this._splitters[i];
            splitter._div.style.width = maxSize + "px";
        }
    } else {
        var maxSize = this._fullHeight;
        for(var i=0;i<this._panels.length;i++) {
            var panel = this._panels[i];
            panel.setHeight(maxSize);
            panel.resize();
        }
        for(var i=0;i<this._splitters.length;i++) {
            var splitter = this._splitters[i];
            splitter._div.style.height = maxSize + "px";
        }
    }
}
SdsSplitterContainer.prototype.maximize = function(rank)
{
    if(rank >= this._panels.length) return false;
    var fullSize = this.getFullSize();
    var size = this.getMinSizeBefore(rank - 1);
    size += this._splitters.length * 5;
    size += this.getMinSizeAfter(rank);
    size = fullSize - size;
    if(size < 0) return false;
    for(var i=0;i<this._panels.length;i++) {
        var panel = this._panels[i];
        if(i != rank) {
            panel.setSize(panel._min);
        } else {
            panel.setSize(size);
        }
        panel.resize();
    }
    return false;
}

SdsSplitterContainer.prototype.distribute = function()
{
    if(this._panels.length == 0) return false;
    var fullSize = this.getFullSize();
    var size = this.getMinSizeAfter(-1);
    size += this._splitters.length * 5;
    var totalSize = size = fullSize - size;
    if(size < 0) return false;
    size = Math.floor(size / this._panels.length);
    for(var i=0;i<this._panels.length;i++) {
        var panel = this._panels[i];
        panel.setSize(panel._min + size);
        panel.resize();
    }
    
}

SdsSplitterContainer.prototype.fullSizeHasChanged = function()
{
    if(this._panels.length == 0) return false;
    var fullSize = this.getFullSize();
    var minSize = this.getMinSizeAfter(-1);
	minSize += this._splitters.length * 5;
	var effectiveSize = this._splitters.length * 5;
    effectiveSize += this.getSizeAfter(-1);
	if(fullSize < minSize) fullSize = minSize;
	if(effectiveSize == fullSize) return;
	var ratio = fullSize / effectiveSize;
	var total = 0;
    for(var i=0;i<this._panels.length-1;i++) {
        var panel = this._panels[i];
		var newSize = Math.floor((panel.getSize()) * ratio);
		if(newSize < panel._min) newSize = panel._min;
		//alert(ratio + " " + fullSize  + " " + effectiveSize + "\n" + panel.getSize() + " -> " + newSize);
		total += newSize;
        panel.setSize(newSize);
        //panel.resize();
    }
	var panel = this._panels[i];
    panel.setSize(fullSize - total - this._splitters.length * 5);
    //panel.resize();
}

SdsSplitterContainer.prototype.check = function()
{
	var msg = "check " + this._id + "\n";
	msg += "fullSize : " + this._fullWidth + " x " + this._fullHeight + "\n";
	for(var i=0;i<this._panels.length;i++) {
        var panel = this._panels[i];
		msg += "panel " + i + ": " + panel._width + " x " + panel._height + "\n";
        var sep = this._splitters[i];
		if(sep) {
			msg += "sep " + i + ": " + sep.getSize() + "\n";
		}
	}
	msg += "div client : " + this._div.clientWidth + "x" + this._div.clientHeight + "\n";
	msg += "div scroll : " + this._div.scrollWidth + "x" + this._div.scrollHeight + "\n";
	msg += "div dim : " + this._div.style.width + "x" + this._div.style.height + "\n";
	alert(msg);
}

var splitterContainers = {}
var splitterNeedResize = false;

function sdsWindowResizeSplitters()
{
	for(var id in splitterContainers) {
		var splitterContainer = splitterContainers[id];
		splitterContainer.onWindowResize();
	}
}

function sdsInitWindowResizeSplitters()
{
	setTimeout("sdsWindowResizeSplitters()", 1);
}

addLoadAction(sdsInitWindowResizeSplitters);

