var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])
//if ((version >= 5.5) && (document.body.filters)){
if (version >= 5.5) {
	Behaviour.register({
		'div.trans-png': function(el) {
			var picUrl = $(el).getStyle('backgroundImage');
			if (picUrl != 'none') {
				$(el).style.backgroundImage="url('/images/spacer.gif')";


				// replace url stuff with nothing, supports single, double and no quotes
				picUrl = picUrl.replace(/(url\(["']?|["']?\))/g, '');
				
				$(el).style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'" 
					+ picUrl + "\', sizingMethod='scale');";

			}
		}
	});
};


var _overlayData = {
	lastElement: null
};

function addOverlayElement(title, innerHtml) {

	var closeButton = Builder.node('input', { type: 'button', 'class': 'close_button', value: 'sluiten' });
	var maxButton	= Builder.node('input', { type: 'button', 'class': 'max_button', value: '[]' });
	var revButton	= Builder.node('input', { type: 'button', 'class': 'rev_button', value: '_' });

	var el = Builder.node('div', { 'class': 'overlay_element' }, [
					Builder.node('div', { 'class': 'close_button' }, [ revButton, maxButton, closeButton ]), 
					Builder.node('h2', { 'class': 'drag_handle' }, title),
					Builder.node('div', { 'class': 'content' }, innerHtml),
				]);


	new Draggable(el, { handle: 	'drag_handle', 
					    starteffect: false, 
						endeffect: false,
						revert: function() {
							var pos = Position.page(this);

							return (pos[0] < 0 || pos[1] < 0 
									|| pos[0] > document.body.getWidth()
									) ? true : false;
						}.bind(el)});

	if (maxButton) maxButton.onclick = function() {
		el.maximize();
		maxButton.hide();
		revButton.show();
	}

	if (revButton) revButton.onclick = function() {
		el.revert();
		maxButton.show();
		revButton.hide();
	}

	if (revButton) revButton.hide();

	if (closeButton) closeButton.onclick = function() {
		if (!el.changed || confirm('Weet je het zeker?')) {

			// search for tinyMce's and kill them
			$(el).getElementsBySelector('textarea.tiny_area').each(function(ty) {
				tinyMCE.execCommand('mceRemoveControl', true, ty.id);
			});

			$(el).remove();
		};



		return false;
	}

	el.removeFormatButton = function() {
		try {
			maxButton.hide();
			revButton.hide();
		} catch(e) {};
	}

	el.changed = false;

	el.close = function() {
		$(el).remove();
	}

	el.removeCloseButton = function() {
		try {
			closeButton.remove();
		} catch(e) {};
	}
	el.setContent = function(txt) {

		// before updating content, kill any tinyMce's
		el.down('div.content').getElementsBySelector('textarea.tiny_area').each(function(ty) {
			tinyMCE.execCommand('mceRemoveControl', true, ty.id);
		});

		el.down('div.content').update(txt);

		// after setting some content, we might need to do some 
		// behaviour based event attachments
		Behaviour.applyFrom(el);

		$A(el.getElementsByTagName('form')).each(function(frm) {

			// setup listeners for any form elements, to trigger the question
			// on close button
			frm.getElements().each(function(child) {

				Event.observe(child, 'change', function(evt) {
					el.changed = true;
				});

			});

			// set changed back to false after submit of a form, this might falsely
			// assume that each submit succeeds. But well, I can''t really check
			// anything at this point (yet: 80/20)
			Event.observe(frm, 'submit', function(evt) {
				el.changed = false;
			});
		});
	};
	
	el.fitSize = function(w, h) {
		
		var content = el.getElementsBySelector('div.content').shift();

		if (el.getWidth() < w) {
			content.style.width 	= '' + w + 'px';
		} 
		if (el.getHeight() < h) {
		
			content.style.height	= '' + h + 'px';
			content.style.maxHeight	= '' + h + 'px';
		}
	}

	el.maximize = function(){

		var ctxEl = this.getElementsBySelector('div.content').shift();

		this._origPos = {
			height: ctxEl.offsetHeight,
			width: 	ctxEl.offsetWidth,

			top:	this.offsetTop,
			left: 	this.offsetLeft
		};


		var headerHeight	= _overlayData.lastElement.getElementsBySelector('h2.drag_handle')[0].getHeight();
		var newHeight 		=  Position.page($('refPoint'))[1]- Position.page($('overlay_area'))[1] - 20 - headerHeight;

		Position.clone($('overlay_area'), ctxEl, { setLeft: false, setTop: false, setWidth: true, setHeight: false });
		Position.clone($('overlay_area'), this, { setLeft: true, setTop: true, setWidth: false, setHeight: false });

		ctxEl.style.height 		= newHeight + 'px';
		ctxEl.style.maxHeight 	= newHeight + 'px';

		el.setActive();

	}

	el.setActive = function() {
		el.bringToFront();
		$$('div.overlay_element').each(function(ov) {
			$(ov).removeClassName('active_overlay_element');
		});
		el.addClassName('active_overlay_element');
	}

	el.revert = function() {
		
		if (this._origPos == null) return false;

		this.style.top = this._origPos.top + 'px';
		this.style.left = this._origPos.left + 'px';

		var ctxEl = this.getElementsBySelector('div.content').shift();

		ctxEl.style.height 		= this._origPos.height + 'px';
		ctxEl.style.width 		= this._origPos.width + 'px';
		ctxEl.style.maxHeight	= this._origPos.height + 'px';

	}

	el.setTitle = function(txt) {
		el.getElementsBySelector('h2.drag_handle')[0].update(txt);
	};

	Event.observe(el, 'click', function(evt) {
		el.setActive();
	});

	if (_overlayData.lastElement != null) {

		var change = _overlayData.lastElement.getElementsBySelector('h2.drag_handle')[0].getHeight();
		if (change == 0) change = 30;

		var offsets = Position.positionedOffset(_overlayData.lastElement);
		var eTop     = offsets[1] + change;
		var eLeft    = offsets[0] + change;

		el.style.top = eTop + 'px';
		el.style.left = eLeft + 'px';
	};

	// append and bring to front as the last and final steps
	// otherwise you may see a slight appear - replace effect

	var area = $('overlay_area');
	area.appendChild(el);
	el.bringToFront();

	_overlayData.lastElement = el;
	return el;
}

/* Script by: www.jtricks.com
 * Version: 20060325
 * Latest version:
 * www.jtricks.com/javascript/blocks/ordering.html
 * Integrated with Prototype by Wouter van Vliet
 */

function getAbsoluteDivs() {
    var arr = new Array();
    var all_divs = $$('div');
    var j = 0;

	all_divs.each(function(d) {
		if (d.getStyle('position') == 'absolute') {
			arr.push(d);
			j++;
		}
	});

    return arr;
}

Object.extend(Element.Methods, {

	bringToFront: function(obj) {

		var divs = getAbsoluteDivs();
		var max_index = 0;
		var cur_index;

		// Compute the maximal z-index of
		// other absolute-positioned divs
		for (i = 0; i < divs.length; i++)
		{
			var item = divs[i];
			if (item == obj ||
				item.style.zIndex == '')
				continue;

			cur_index = parseInt(item.style.zIndex);
			if (max_index < cur_index)
			{
				max_index = cur_index;
			}
		}

		obj.style.zIndex = max_index + 1;

	},

	sendToBack: function(obj) {

		var divs = getAbsoluteDivs();
		var min_index = 999999;
		var cur_index;

		if (divs.length < 2) return;

		// Compute the minimal z-index of
		// other absolute-positioned divs
		for (i = 0; i < divs.length; i++)
		{
			var item = divs[i];
			if (item == obj)
				continue;

			if (item.style.zIndex == '')
			{
				min_index = 0;
				break;
			}

			cur_index = parseInt(item.style.zIndex);
			if (min_index > cur_index)
			{
				min_index = cur_index;
			}

		}

		if (min_index > parseInt(obj.style.zIndex))
		{
			return;
		}

		obj.style.zIndex = 1;

		if (min_index > 1)
			return;

		var add = min_index == 0 ? 2 : 1;

		for (i = 0; i < divs.length; i++)
		{
			var item = divs[i];
			if (item == obj)
				continue;

			item.style.zIndex += add;
		}

	}


});
Object.extend(Element, Element.Methods);
Element.addMethods();

// addition to behaviour, to support behav on dynamically 
// loaded elements. Should propose this to the developer
// himself - or do something cooler with state holding
// to know which elements have been behaved already and
// be able to call the basic Behaviour.apply on any DOM
// changes - could we do this as an Event listener?
Behaviour.applyFrom  = function(startEl) {
	var se = startEl ? startEl : document;
	for (h=0;sheet=Behaviour.list[h];h++){
		for (selector in sheet){
			list = se.getElementsBySelector(selector);
			
			if (!list){
				continue;
			}

			for (i=0;element=list[i];i++){
				sheet[selector](element);
			}
		}
	}
};

var Select = {

	removeAllOptions: function (selectbox) {
		var i;
		for(i=selectbox.options.length-1;i>=0;i--) {
			var o = selectbox.options[i];
			selectbox.removeChild(o);
		}
	},

	addOption: function(sb, value, text) {
		
		var opt = document.createElement("OPTION");
		Try.these(
			function() { sb.add(opt); },
			function() { sb.options.add(opt); }
		);

		opt.innerHTML 	= text;
		opt.innerText 	= text;
		opt.value		= value;

		return opt;
	}
};

function refreshStylesheets(loop) {

	var rnd = Math.round(Math.random()*500);
	$$('link').each(function(l) {
		try {
			l.href = l.href.replace(/\?.*$/, '') + '?rnd = ' + rnd;
		} catch(e) { };
	});

	if (loop > 1000) {
		setInterval(refreshStylesheets, loop);
	}
}

function embedDocumentPlayer(documentId, targetId, size, tool, mode) {

	if (!size) size = 'small';
	
	var sizes = { 'small': 200, 'large': 576, 'sound': 320 };
	var width = typeof(sizes[size]) == 'undefined' ? size : sizes[size];

	var flashVars = {
		tool: tool,
		mode: mode,
		user_id: authUserId,
		hash: authHash,
		username: authUsername,
		lang: authLang,
		doc_id: documentId
	};

	var FO = { 	movie:"/studio/ijsfontein/v7/loader.swf", 
				width: width,
				height: (width * 0.75) + 45,
				majorversion:"8", 
				build:"0", 
				xi:"false", 
				wmode: 'transparent',
				/*
				ximovie:"/studio/ijsfontein/v7/ufo/ufo.swf",	
				*/
				base: location.protocol + '//' + location.hostname + '/studio/ijsfontein/v7/',
				scale:"noScale", 
				salign:"TL", 
				menu:true, 
				flashvars: $H(flashVars).toQueryString(),
				play:"true"
				};
	UFO.create(FO, targetId);
}

function maxWindow() {
	top.window.moveTo(0,0);
	if (document.all) {
		top.window.resizeTo(screen.availWidth,screen.availHeight+10);
	} 
	else if (document.layers||document.getElementById) {
		if (top.window.outerHeight<screen.availHeight||top.window.outerWidth<screen.availWidth) {
			top.window.outerHeight = screen.availHeight+10;
			top.window.outerWidth = screen.availWidth;
		}
	}
}
function openStandardPopup(a, width, height) {
	if (a.target == "") a.target = "popup" + Math.round(Math.random() * 1000);
	var newWin = window.open(a.href, a.target, 'height='+height+', width='+width+', menubar=no, scrollbars=yes, location=no, resizable=yes, status=no, titlebar=yes');
	newWin.focus();
}
