// 09/02 (c)theCo.de AG, peter@theCo.de

var flag_strings = new Array(
  'dependent', //   1
  'hotkeys',   //   2
  'location',  //   4
  'menubar',   //   8
  'resizable', //  16
  'scrollbars',//  32
  'status',    //  64 
  'toolbar'    // 128
);

var undefined;
var cmsPageContext = new Array();
var onloadQueue = new Array();
var collectedChildren;

var OP   = (navigator.appName.toLowerCase()=='opera')?true:false;
var IE   = (document.all)?true:false;
var DOM  = (document.getElementById)?true:false;
var SAFARI = (navigator.userAgent.toLowerCase().indexOf("safari") != -1);

var mediaUrlReceiver = null; // html element to receive media search panel results
var mediaPropertyReceiver = null;
/* runtime include of js files. Two calling options:
	includeJS(fileurl);
	includeJS(filename, bundle);
*/
function includeJS() {
	var fileURL = arguments[0];
	if (arguments.length==2) {
		// file for specific bundle requested
		fileURL = getContextProperty("baseURL")[arguments[1]] + arguments[0]; 
	}
	var newScript = document.createElement("script");
	newScript.type = "text/javascript";
	newScript.src = fileURL;
	document.getElementsByTagName("head")[0].appendChild(newScript);
}


/* add a function to the window onload handler queue
   Attention: Could be overridden by (malicious) javascript from e.g. ad banners
*/
function addToWindowOnloadQueue(func) {
	if (window.onload && window.onload!=processOnloadQueue) {
		onloadQueue.push(window.onload); 
	}
	window.onload = processOnloadQueue;
	onloadQueue.push(func);
}

function processOnloadQueue() {
	for (var oli=0;oli<onloadQueue.length;++oli) {
		onloadQueue[oli]();
	}
}

function tc_popup (name, flags, sizeX, sizeY, posX, posY) {

  var opts = '';

  for (i = 0; i < flag_strings.length; ++i) {
    opts += (opts.length ? ',' : '');
    opts += flag_strings[i];
    opts += '=';
    opts += (flags&0x1)?'yes':'no';
    flags = flags >> 1;
  }

  if (sizeX) {
    opts += ',width='+sizeX;
    if (sizeY) {
      opts += ',height='+sizeY;
      if (posX) {
        opts += ',left='+posX;
        if (posY) {
          opts += ',top='+posY;
        }
      }
    }
  }

  var thepopup = window.open ('', name, opts);
  thepopup.focus();
  //  alert (opts);
}

// scroll viewport to element functions
function scrollViewToElement(element, offset) {
	if (element) {
		var y = getTop(element);
		if (y>offset) y = y - offset;
		var x = getLeft(element);
		if (x>offset) x = x - offset;
		window.scrollTo(x,y);
	}
}

function scrollViewToElementWithId(id, offset) {
	if (id!="") {
		var element = document.getElementById(id);
		scrollViewToElement(element, offset);
	}
}


// ---- BROWSER COMPATIBLE ATTRIBUTE Functions

// gets the absolute position (relative to body) of this element
function getLeft(l) {
  return absoluteLeft(l);
}
function getTop(l) {
  return absoluteTop(l);
}

// sets the absolute position (relative to body) of this element
function setLeft(l, pos) {
	var leftOffset = 0;
    var myParent = l.offsetParent;
    while (myParent) {
        leftOffset  += myParent.offsetLeft;
        myParent = myParent.offsetParent;
    } 
    
	l.style.left = (pos - leftOffset)+"px";
}

function setTop(l, pos) {
	var topOffset = 0;
    var myParent = l.offsetParent;
    while (myParent) {
        topOffset  += myParent.offsetTop;
        myParent = myParent.offsetParent;
    } 
	l.style.top = (pos - topOffset)+"px";
}

function win_innerWidth() {
	if (window.innerWidth) return window.innerWidth;
	else if (document.body && document.body.clientWidth) return document.body.clientWidth; 
	else return 0;
}

function win_innerHeight() {
	if (window.innerHeight) return window.innerHeight;
	else if (document.body && document.body.clientHeight) return document.body.clientHeight;
	else return 0;
}

// get page xscroll offset
function pageXOfset() {
  if(IE || OP)	
    return(document.body.scrollLeft);

  return(window.pageXOffset);  
}

// get page yscroll offset
function pageYOfset()
{
  if(IE || OP)	
    return (document.body.scrollTop);
  
  return(window.pageYOffset);
}

// get absolute top coordinate of element
function absoluteTop(aDiv) {
    var myTop = aDiv.offsetTop;
    var myParent = aDiv.offsetParent;
    while (myParent) {
        myTop  += myParent.offsetTop;
        myParent = myParent.offsetParent;
    }
    return myTop;
} 

// get absolute left coordinate of element
function absoluteLeft(aDiv) {
    var myLeft = aDiv.offsetLeft;
    var myParent = aDiv.offsetParent;
    while (myParent) {
        myLeft  += myParent.offsetLeft;
        myParent = myParent.offsetParent;
    } 
    return myLeft;
}

// popup tracker mechanism

var popuptracker = null;

function trackedPopup(actionurl,windowname, awidth, aheight) {
    var width;
    var height;
    if (awidth==undefined)
        width=610;
    else
        width = awidth;
    if (aheight==undefined)
        height=580;
    else
        height = aheight;
    popuptracker = window.open(actionurl, windowname, "status=YES, scrollbars=YES, resizable=YES, width="+width+", height="+height); 
    popuptracker.focus();
    window.onunload = closeTrackedPopup;
    return false;
}

function isPopupOpen() {
    if (popuptracker != null) return (!popuptracker.closed);
    return false; 
}

function popupClosed() { 
    popuptracker = null;
}

function popupFocus() { 
    if (popuptracker!=null && !popuptracker.closed) {
    	popuptracker.focus();
    }
}

function closeTrackedPopup() {
    if (popuptracker!=null && !popuptracker.closed) { 
        popuptracker.close(); 
    }
}

// getter and setter for generic page context values
function setContextProperty(key, val) {
	cmsPageContext[key] = val;
}
function getContextProperty(key) {
	return cmsPageContext[key];
}


// collect all HTML Elements in a flat array (document.all[] with DOM tech)
function collectChildren(obj) {
	if (obj==document.body && document.all)
		return document.all;
	var collected = new Array();
	if (obj.childNodes.length>0) {
		for (var i=0;i<obj.childNodes.length;i++) {
			if(!obj.childNodes[i].nodeValue) {
			  collected.push(obj.childNodes[i]);
			  if (obj.childNodes[i].tagName!="SELECT")
			  	collected = collected.concat(collectChildren(obj.childNodes[i]));
			}
		}
	}
	return collected;
}



/* Multiline tooltips */
var Tooltips = {
	collect: function(rootElement) {
		var elements = rootElement?$(rootElement).descendants():$(document.body).descendants();
		elements.each(Tooltips._attach);
		if (!$("CMSTooltip")) { // create tooltip division if needed
			new Insertion.Bottom($(document.body),"<div id=\"CMSTooltip\"></div>");
		}
		$("CMSTooltip").hide();
	},
	hide: function() {
		$("CMSTooltip").hide();
		if (Tooltips._currentEffect) Tooltips._currentEffect.cancel();
	},
	_attach: function(e) { 
		var elem = $(e);
		if (elem.title) {
			elem.setAttribute("tooltip", elem.title.replace(/\n/g,"<br>"));
			elem.removeAttribute("title");
			Event.observe(elem, "mouseover", Tooltips._overhandler);
			Event.observe(elem, "mouseout", Tooltips._outhandler);
		} else if (elem.readAttribute("title_classic")) {
			elem.setAttribute("title",elem.readAttribute("title_classic"));
		}
	},	
	_overhandler: function(event) {
		var elt = Event.element(event);
		var text = elt.readAttribute("tooltip");
		if (!text) {
			var parent = TCUtils.parentElementWithAttribute(elt,"tooltip");
			if (parent) text = parent.readAttribute("tooltip");
		}
		if (text) {
			var tip = $("CMSTooltip");
			tip.innerHTML = text;
			tip.show();
			var pos = Position.cumulativeOffset(elt);
			var x = pos[0] + elt.offsetWidth/2 - tip.offsetWidth/4;
			var y = pos[1] + elt.offsetHeight+12; 
			tip.style.left = 0;
			tip.style.top = y;
			if (x + tip.offsetWidth > win_innerWidth() + pageXOfset() - 16) {
				x = pageXOfset() + win_innerWidth() - tip.offsetWidth -4 - 16;
			}
			if (x<0) { x = 5; }
			tip.style.left = x;	
			if (y + tip.offsetHeight > win_innerHeight() + pageYOfset()) {
				y = pos[1] - tip.offsetHeight - 4;
			}
			tip.style.top = y;
			tip.hide();
			Tooltips._currentEffect = new Effect.Appear("CMSTooltip",{duration:.33});
		}
	},
	_outhandler: function(event) {
		Tooltips.hide();
	},
	_currentEffect: null	
};

var TCUtils = {
	parentElementWithAttribute: function(element, attributeName) {
		var parents = $(element).ancestors();
		var parent = parents.shift();
		var val;
	    while (parent) {
	        val = parent.readAttribute(attributeName);
	        if (val) break;
			parent = parents.shift();
	    }
	    return parent;		
	}
}




/* FUNCTIONS AND GLOBAL VARS FOR DRAGANDDROP CMSPLACEMENTCONTAINER */

var CMSunselectable = false;
var CMSdragDiv = null;
var CMSdragOffsetX = 0;
var CMSdragOffsetY = 0;
var CMSzArray = new Array();

function startDrag(evnt) { 
	var me = this;
	if (!evnt) var evnt = window.event;

	if (!CMSunselectable) {
		var all = collectChildren(document.body);
		for (var i=0; i<all.length;i++) {
			if (all[i].id!="BEDRAGGER" && all[i].tagName!="INPUT") {
				all[i].unselectable = "ON";
			} 
		}
		CMSunselectable = true;
	}
	var s = me.id.substring(9);
	CMSdragDiv = document.getElementById("BEPOS" + s);
	if (CMSdragDiv) {
		var srcX = getLeft(CMSdragDiv);
		var srcY = getTop(CMSdragDiv);
		CMSdragOffsetX = evnt.clientX - srcX;
		CMSdragOffsetY = evnt.clientY - srcY;
	}
	document.body.onmousemove = dragMove;
	document.body.onmouseup = stopDrag;
	if (evnt.preventDefault) evnt.preventDefault();
	return true;
}

function stopDrag(evnt) {
	if (CMSdragDiv) {
		if (!evnt) var evnt = window.event;
		var s = CMSdragDiv.id.substring(5);
		var xval = document.getElementById("BEXPOS4" + s);
		var yval = document.getElementById("BEYPOS4" + s);
		if (xval) {
			xval.value = CMSdragDiv.style.left;
		}
		if (yval) {
			yval.value = CMSdragDiv.style.top;
		}
	}
	CMSdragDiv = null;
	document.body.onmousemove = null;
	document.body.onmouseup = null;
}

function dragMove(evnt) {
	if (CMSdragDiv) {
		if (!evnt) var evnt = window.event;
		status = evnt.clientX + " " + evnt.clientY;
		setTop(CMSdragDiv, evnt.clientY - CMSdragOffsetY);
		setLeft(CMSdragDiv, evnt.clientX - CMSdragOffsetX);
		if (evnt.preventDefault) evnt.preventDefault();
		return true;
	}
}

function getZArray() {
	if (CMSzArray.length==0) {
		var all = collectChildren(document.getElementById("ROOT"));
		for (var i=0; i<all.length;i++) {
			if (all[i].id.indexOf("BEZINDEX4")==0) {
				if (!all[i].value) {
					all[i].value = document.getElementById("BEPOS"+all[i].id.substring(9)).style.zIndex;
				}
				CMSzArray.push(all[i]);
			} 
		}			
	}
	return CMSzArray;
}

function moveToFront(me) { 
	var s = me.parentNode.id.substring(5);
	var field = document.getElementById("BEZINDEX4"+s);
	var val = parseInt(field.value);
	var values = getZArray();
	var maxval = 0;
	for (var i=0;i<values.length;i++) {
		if (values[i] != field) {
			if (values[i].value>maxval) {
				maxval = values[i].value;
			}
			values[i].value = parseInt(values[i].value)-10;
			document.getElementById("BEPOS"+values[i].id.substring(9)).style.zIndex = values[i].value;
		}
	}		
	field.value = maxval;
	me.parentNode.style.zIndex = maxval;
}

function moveToBack(me) {
	var s = me.parentNode.id.substring(5);
	var field = document.getElementById("BEZINDEX4"+s);
	var val = parseInt(field.value);
	var values = getZArray();
	for (var i=0;i<values.length;i++) {
		if (values[i] != field) {
			values[i].value = parseInt(values[i].value)+10;
			document.getElementById("BEPOS"+values[i].id.substring(9)).style.zIndex = values[i].value;
		}
	}		
	field.value = "5000";
	me.parentNode.style.zIndex = "5000";	
}

function setDragHandlers4(id) {
	var element = document.getElementById(id);
	if (element) {
		element.onmousedown = startDrag;
		element.onmouseup = stopDrag;
	}
}

function switchOverflow(box, containerid) {
	var container = document.getElementById(containerid);
	if (box.checked) {
		container.style.overflow = "visible";
	}
	else {
		container.style.overflow = "hidden";
	}
}

/* FUNCTIONS AND GLOBAL VARS FOR CMSROTATIONCONTAINER */

var rotlist = new Array();
var rotcount = new Array();

function registerRotationElement(container, element) {
	if (!rotlist[container]) {
		rotlist[container] = new Array();
		rotcount[container] = 0;
		document.getElementById(element).style.display = "block";
	}
	rotlist[container].push(element);
}

function startRotation(container, interval) {
	if (interval==0) interval = 3;
	window.setInterval("rotateContainer(\""+container+"\")", interval*1000);
}

function rotateContainer(container) {
	var n = rotcount[container];
	document.getElementById(rotlist[container][n]).style.display = "none";
	n = (n+1)%rotlist[container].length;
	document.getElementById(rotlist[container][n]).style.display = "block";
	rotcount[container] = n;
}


/*
	Trys to retrun the CSSRule with CSSSheet.cssRules.selectorText , otherwise returns null
*/
function getRuleInStyleSheets(selector) { 
	var _sss =	document.styleSheets;
	for (var j=0;j<_sss.length;++j) {
	  var _ss = _sss[j];
	  for (var i=0; i<_ss.cssRules.length;++i) {
	  	if (_ss.cssRules[i].selectorText == selector) {
	  			return _ss.cssRules[i];
	  	}
	  }
	}
}
function registerMediaURLReceiverWithId(id) {
	var element = document.getElementById(id);
	mediaUrlReceiver = element;
}

function propagateMediaURL(href) {
	if (mediaUrlReceiver) {
		mediaUrlReceiver.value = href;
	}
}
function propagateMediaProperties(dict) {
	if (mediaPropertyReceiver) {
		mediaPropertyReceiver(dict);
	}
}

var CSS = {
	load: function (url_, media_ /*optional*/) {
		// load same file only once
		var _links = document.getElementsByTagName("link");
		if (_links.length > 0 && _links["href"] == url_) return;
		var _media = (media_ === undefined || media_ === null)?"all":media_;
		var _elstyle = document.createElement("link");
		_elstyle.setAttribute("rel", "stylesheet");
		_elstyle.setAttribute("type", "text/css");
		_elstyle.setAttribute("media", _media);
		_elstyle.setAttribute("href", url_);
		var _head = document.getElementsByTagName("head")[0];
		_head.appendChild(_elstyle);
	}
};


// Set desired tab- defaults to four space softtab
function checkTab(evt) {
	var tab = "    ";
	if (IE) return; // no IE
    var t = evt.target;
    var ss = t.selectionStart;
    var se = t.selectionEnd;

    // Tab key - insert tab expansion
    if (evt.keyCode == 9) {
        evt.preventDefault();
        
        // Special case of multi line selection
        if (ss != se && t.value.slice(ss,se).indexOf("\n") != -1) {
            // In case selection was not of entire lines (e.g. selection begins in the middle of a line)
            // we ought to tab at the beginning as well as at the start of every following line.
            var pre = t.value.slice(0,ss);
            var sel = t.value.slice(ss,se).replace(/\n/g,"\n"+tab);
            var post = t.value.slice(se,t.value.length);
            t.value = pre.concat(tab).concat(sel).concat(post);
            
            t.selectionStart = ss + tab.length;
            t.selectionEnd = se + tab.length;
        }
        
        // "Normal" case (no selection or selection on one line only)
        else {
            t.value = t.value.slice(0,ss).concat(tab).concat(t.value.slice(ss,t.value.length));
            if (ss == se) {
                t.selectionStart = t.selectionEnd = ss + tab.length;
            }
            else {
                t.selectionStart = ss + tab.length;
                t.selectionEnd = se + tab.length;
            }
        }
    }
    
    // Backspace key - delete preceding tab expansion, if exists
    else if (evt.keyCode==8 && t.value.slice(ss - 4,ss) == tab) {
        evt.preventDefault();
        
        t.value = t.value.slice(0,ss - 4).concat(t.value.slice(ss,t.value.length));
        t.selectionStart = t.selectionEnd = ss - tab.length;
    }
    
    // Delete key - delete following tab expansion, if exists
    else if (evt.keyCode==46 && t.value.slice(se,se + 4) == tab) {
        evt.preventDefault();
        
        t.value = t.value.slice(0,ss).concat(t.value.slice(ss + 4,t.value.length));
        t.selectionStart = t.selectionEnd = ss;
    }
    
    // Left/right arrow keys - move across the tab in one go
    else if (evt.keyCode == 37 && t.value.slice(ss - 4,ss) == tab) {
        evt.preventDefault();
        t.selectionStart = t.selectionEnd = ss - 4;
    }
    else if (evt.keyCode == 39 && t.value.slice(ss,ss + 4) == tab) {
        evt.preventDefault();
        t.selectionStart = t.selectionEnd = ss + 4;
    }
    
}


