/*==================================================*
 octeportal.js,v 1.1 
 *==================================================*/

/*===============================
	Open Help Window
================================*/
//Name        :  openHelp
//purpose     :  opens a url in a separate window
//               primarily used to open help pages from help.octeportal.co.uk
//Created by  :  Wilan P. Bigay
//Created Date:  22 March 2005 
function openHelp(url) { 
   var win = window.open(url, 'OctUserGuide', 'height=450, width=600, left=25, top=25, resizable=yes, scrollbars=yes');
   win.focus();
}

/*==================================
	Default button
====================================*/	
//Name				:	Enter2Click
//Purpose			:	Convert Enter to key to a button click
//Created by	:	MJR
//Create Date	: 15 Dec 05
function Enter2Click(btnId) {
	//Only process if the enter key has been pressed
	if (event.keyCode == 13) {
		// cancel the default submit
    event.returnValue=false;
    event.cancel = true;
    
    // submit the form by programmatically clicking the specified button
    var btn =  document.getElementById(btnId);
    if (btn && btn.click) {btn.click();}
	}
}

/*===============================
	Event Handlers
=================================*/

// Attach an event
function addEvent(obj, evType, fn, useCapture) {
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} 
}

function removeEvent(obj, evType, fn, useCapture){
	if (obj.removeEventListener){
		obj.removeEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.detachEvent){
		var r = obj.detachEvent("on"+evType, fn);
		return r;
	}
}

// Returns the browser independent target element 
function getEventTarget(eventHandler)
{
	var ev = eventHandler ? eventHandler : window.event;
	return (ev.target ? ev.target : ev.srcElement);
}

/*======================================
 Browser Type
 ======================================*/
var browserType;

function fql_browserType()
{
	if (browserType == null)
	{
		var ua=navigator.userAgent.toLowerCase();

		if (ua.indexOf('konqueror') != -1) 
			browserType = 'kq';
		else if (ua.indexOf('opera') != -1) 
			browserType = 'op';
		else if (ua.indexOf('netscape') != -1) 
			browserType = 'ns';
		else if (ua.indexOf('msie') != -1)
			browserType = 'ie';
		else if (ua.indexOf('safari') != -1)
			browserType = 'safari';
	  
		if (browserType == null)
			browserType = 'mo';  
	}
	//window.status = browserType;
	return browserType;
}


/*================================
	Manage element positioning
=================================*/	

// Add two sets of coords
function posXY_add(c) {
	this.x += c.x;
	this.y += c.y;
	return this;
}

// subtract two sets of coords
function posXY_subtract(c) {
	this.x -= c.x;
	this.y -= c.y;
	return this;
}

// The basic coordinate object
function posXY(x, y) {
	this.x = x;
	this.y = y;
	this.add = posXY_add;
	this.subtract = posXY_subtract;
	return this;
}

// Returns the absolute position relative to the window as posXY
// elem is the element to checked
// if refTo is not present it returns the position relative to its positional parent
// if refTo is an element it returns the elements position in relation to that element
function getAbsolutePosition(elem, refTo) {

// Search back through the parents adding up the offsets as we go
// This stops when there are no more parents
// This makes sure we do not stop at the current elem if it is a position reference
	if (elem==null)
		return new posXY(0, 0);
	else
	{
		var elemRefTo;
		
		var parent = elem.offsetParent;
		var elemPos = new posXY(0,0);
		while (elem && parent)
		{
			var parentStyle = (parent.currentStyle ? parent.currentStyle : window.getComputedStyle(parent,null));
			if (refTo ? elem !== refTo : !(parentStyle.position=='absolute' || parentStyle.position=='relative')) 
			{
				elemPos.add(new posXY(elem.offsetLeft, elem.offsetTop));
				elem = elem.offsetParent;
				parent = elem.offsetParent;
			}
			else
				break;
		}
		return elemPos;
	}
}

// Returns the positional parent of a given element
function getPositionParent(elem)
{
	if (elem==null) return null;
	while (elem.offsetParent)
	{
		var style = (elem.currentStyle ? elem.currentStyle : window.getComputedStyle(elem, null));
		if (style.position=='absolute' || style.position=='relative') break;
		elem = elem.offsetParent;
	}
	return elem;
}

// Reposition the given element to the position given in posXY
function repositionElement(elem, xy) {
	elem.style.left = xy.x + 'px';
	elem.style.top = xy.y + 'px';
}

// Overlay one element on top of the other
// Also optionally clips the overlaid element
function overlayElements(elemID, targetID, offsetTop, offsetLeft, clipHeight, clipWidth, makeVisible) {
	var elem = document.getElementById(elemID);
	var target = document.getElementById(targetID);
	if (elem && target) {
		var pos = getAbsolutePosition(target);
		
		// make sure element is absolutely positioned and above the target
		elem.style.position = 'absolute';
		if (target.currentStyle)
			elem.style.zIndex = target.currentStyle.zIndex;
		else
			elem.style.zIndex = window.getComputedStyle(target, null).zIndex;
		
		elem.style.top = pos.y + offsetTop + 'px';
		elem.style.left = pos.x + offsetLeft + 'px';
		
		// clip to the element if required
		if ( !(isNaN(clipHeight) || isNaN(clipWidth))) {
			if (clipHeight == -1) {
				// Use target size for clipping
				elem.style.clip = 'rect(0, ' + (target.offsetWidth - offsetLeft) + ', ' + (target.offsetHeight - offsetTop) + ', 0)';
			} else {
				elem.style.clip = 'rect(0, ' + clipWidth + ', ' + clipHeight + ', 0)';
			}
		}
		
		// If the element is to be made visible at the same time do this here after it has been moved.
		if (makeVisible) elem.style.visibility = 'visible';
	}
}

// Reads the array of elements to overlay (overlaidElements)
// and allpies all overlays
function overlayAllElements(makeVisible) {
	
	// Only go if the array exists
	if (typeof(overlaidElements) != 'undefined') {
		if (typeof(makeVisible) == 'undefined') makeVisible = true;
		for (entry in overlaidElements) {
			overlayElements(overlaidElements[entry].elemId, overlaidElements[entry].targetId, overlaidElements[entry].offsetTop, overlaidElements[entry].offsetLeft, overlaidElements[entry].clipHeight, overlaidElements[entry].clipWidth, makeVisible);
		}
	}
}


/*===================================
 Expand/Fill Containers
 ====================================*/
// Expands the container of any element with a class which includes "ExpandContainer" so that the container fully contains the height of the element
function adjustContainers()
{
	var elems = document.getElementsByTagName('DIV');
	for(var i=0;i<elems.length;i++)
	{
		if (elems[i].className.toLowerCase().indexOf('expandcontainer') != -1)
			expandContainer(elems[i]);
	}
	for(var i=0;i<elems.length;i++)
	{
		if (elems[i].className.toLowerCase().indexOf('fillcontainer') != -1)
			fillContainer(elems[i]);
	}
}

function expandContainer(elem)
{
	// Find the container of this element and at the same time add up to get the relative position within the container
	var elemTop = elem.offsetTop;
	var elemContainer = elem.offsetParent;
	
	// If the conatiner is the body there is no adjustment to make
	if (elemContainer.tagName.toLowerCase() == 'body') return;
	
	// The client height must be enough to hold our element
	var elemBottom = elem.offsetTop + elem.offsetHeight
	if (elemBottom > elemContainer.clientHeight) 
	{
		if (fql_browserType() == 'ie')
			// Adjust for the box quirk if the client height is given
			elemContainer.style.height = elemBottom + elemContainer.offsetHeight - elemContainer.clientHeight;
		else
			elemContainer.style.height = elemBottom;
	}
	
}

function fillContainer(elem)
{
	// Adjusts the height of the element so its bottom edge touches the bottom edge of its container
	
	// First find the element's container
	var elemTop = elem.offsetTop;
	var elemContainer = elem.offsetParent;
	
	// Calculate the bottom of the contained element
	var elemBottom = elem.offsetTop + elem.offsetHeight
		
	// Calculate the internal height of the container
	var contHeight
	if (elemContainer.clientHeight && elemContainer.clientHeight > 0)
	{
		// Adjust for the box quirk if the client height is given
		contHeight = elemContainer.clientHeight;
	}
	else
	{
		contHeight = elemContainer.offsetHeight;
	}
	
	// Adjust the element height if it is too small
	if (elemBottom < contHeight) 
	{
		if (fql_browserType() == 'ie' || !(elem.clientHeight && elem.clientHeight > 0))
			elem.style.height = contHeight - elemTop - (elem.offsetHeight - elem.clientHeight)
		else 
			elem.style.height = contHeight - elemTop;
	}
	
}

/*===============================
	UnObfuscate
=================================*/
function UnObfuscate(sText){
	var sLink = '';
	for (var i = sText.length; i >= 0; i=i-2){
		sLink = sLink + sText.substring(i,i+1);
	}
	document.write(sLink);
}

/*===============================
	Redirect Page
=================================*/
function RedirectPage(loc,delay){
	setTimeout("location.href ='"+loc+"'",delay);
}

/*==============================
	Image Refresh
================================*/
function imageRefresh(imageId, period)
{
	this.name = 'ir_' + imageId;
	this.img = document.getElementById(imageId);
	this.period = period;
	this.origSrc = this.img.src;
	
	this.start = function() {
	// Starts the refresh cycle
	this.refreshCount = 0;
	this.intervalId = window.setInterval(this.name + '.loop()', period * 1000);
	
	}
	
	this.stop = function() {
	//Stops the refresh
	if (this.intervalId && this.intervalId != 0) 
		window.clearInterval(this.intervalId);
	}
	
	this.loop = function() {
		// This function is called from the timeout to reload the image
		// and restart the time for the next loop
		
		// Check if the image has been loaded.  
		// If not increment a counter
		// If the image fails to load in 10 cycles it is refreshed anyway.
		this.refreshCount++;
		if (this.img.complete == true || this.refreshCount >= 10) {
			var now = new Date();
			this.img.src = this.origSrc + '&' + now.getTime()
			this.refreshCount = 0;
		}
	}
}

function imageRefreshInit() {
	var ctr = 0;
	var elems = document.getElementsByTagName('img');
	for(var i=0;i<elems.length;i++) {
		if (elems[i].id == null || elems[i].id == '') {
			var valid='false';
			while (valid=='false') {
				var img = document.getElementById('image_' + ctr);
				if (img == null) {
					elems[i].id = 'image_' + ctr;
					valid='true';
				}
				ctr = ctr + 1;
			}
		}

		var re = new RegExp('refresh=([0-9]*.?[0-9]*)');
		var m = re.exec(elems[i].src);
		if (m != null && m[1] != null){
			if (m[1] != '' && m[1] != 0) {
				eval('ir_' + elems[i].id + '= new imageRefresh(elems[i].id, m[1]);');
				eval('ir_' + elems[i].id + '.start();');
			}
		}
	}
	
	
}

/*==================================
	Toggle Visibility
	==================================*/
function toggleVisible(ctlId)
{
	var ctl = document.getElementById(ctlId);
	if (ctl)
	{
		if (ctl.style.display == 'none' || ctl.style.display == '')
			ctl.style.display = 'block';
		else
			ctl.style.display = 'none';
	}
}

/*===================================
	Telerik Editor Functions
	===================================*/
function OnClientPasteHtml(editor, args) {

	var cmdName = args.get_commandName();
	var v = args.get_value();

	switch (cmdName) {
		case 'ImageManager':
			var div = document.createElement('DIV');
			Telerik.Web.UI.Editor.Utils.setElementInnerHtml(div, v);
			var img = div.firstChild;
			if (img.style.border == '') {
				img.style.border = 'none';
				v = div.innerHTML;
			}
			break;
	}
	args.set_value(v);
}
