//ajax
var curReq;    //global request that is currently processed
var popupGoToUrl; // hack for safari blocking flash popups

function isDOM(){
	return 	(document.getElementById && document.childNodes && document.createElement);
}

function getElement(id){
	if(document.getElementById)	{
		return document.getElementById(id);
	} else {
		return null;
	}
}

// shortcut for getElement
function $(id){
	return getElement(id);
}

function getQueryVariable(variable, def){
	var qs = window.location.search.substring(1);
	var vars = qs.split("&");
	for (var i=0; i < vars.length; i++){
		var pair = vars[i].split("=");
		if (pair[0] == variable){
			return pair[1];
		}
	}
	if(def){ // default value parameter
		return def;
	}
	return null;
}

function createNode(src){
	counter++;

	var iframe = createIframe(1);
	iframe.setAttribute('id', 'frame_' + counter);
	iframe.setAttribute('src', src + '?artworkId=' + artworkId);
	iframe.setAttribute('frameBorder', "no");
	iframe.setAttribute('border', 0);
	
	return iframe;
}

// It's a kind of magic
function createElementWithName(){}
(function(){
  try {
	var el=document.createElement( '<div name="foo">' );
	if( 'DIV'!=el.tagName ||
		'foo'!=el.name ){
	  throw 'create element error';
	}
	createElementWithName = function( tag, name ){
	  return document.createElement( '<'+tag+' name="'+name+'"></'+tag+'>' );
	}
  }catch( e ){
	createElementWithName = function( tag, name ){
	  var el = document.createElement( tag );
	  el.setAttribute('name', name);
	  return el;
	}
  }
})();

// It's a kind of magic
function createElementWithId(){}
(function(){
  try {
	var el=document.createElement( '<div id="foo">' );
	if( 'DIV'!=el.tagName ||
		'foo'!=el.name ){
	  throw 'create element error';
	}
	createElementWithId = function( tag, id ){
	  return document.createElement( '<'+tag+' id="'+id+'"></'+tag+'>' );
	}
  }catch( e ){
	createElementWithId = function( tag, id ){
	  var el = document.createElement( tag );
	  el.setAttribute('id', id);
	  return el;
	}
  }
})();

function createElementWithNameAndId(){}
(function(){
  try {
	var el=document.createElement( '<div id="foo" name="foo">' );
	if( 'DIV'!=el.tagName ||
		'foo'!=el.name ){
	  throw 'create element error';
	}
	createElementWithNameAndId = function( tag, id, name ){
	  id = id.replace(/\s/,'');
	  name = name.replace(/\s/,'');
	  return document.createElement( '<'+tag+' id="'+id+'" name="'+name+'"></'+tag+'>' );
	}
  }catch( e ){
	createElementWithNameAndId = function( tag, id, name ){
	  var el = document.createElement( tag );
	  el.setAttribute('id', id);
	  el.setAttribute('name', name);
	  return el;
	}
  }
})();

// It's a kind of magic
function createIframe(){}
(function(){
  try {
	var el=document.createElement( '<div name="foo">' );
	if( 'DIV'!=el.tagName ||
		'foo'!=el.name ){
	  throw 'create element error';
	}
	createIframe = function(id, borderWidth ){
	  return document.createElement( '<iframe id="' + id + '" frameborder="'+borderWidth+'"></iframe>' );
	}
  }catch( e ){
	createIframe = function(id, borderWidth ){
	  var el = document.createElement('iframe');
	  el.setAttribute('id', id);
	  el.setAttribute('frameborder', borderWidth);
	  return el;
	}
  }
})();

function getFlashMovieObject(movieName){
	if (document.embeds && document.embeds[movieName]){
		return document.embeds[movieName]; 
	} else if (window.document[movieName]){
		return window.document[movieName];
	} else {
		return document.getElementById(movieName);
	}
}

var g_stepDefaults = new Array();
g_stepDefaults[0] = "";
g_stepDefaults[1] = "Maak uw keuze";
g_stepDefaults[2] = "Kies een categorie";
g_stepDefaults[3] = "Kies een type";
g_stepDefaults[4] = "Kies de jury('s)";
g_stepDefaults[5] = "Gegevens invullen";
g_stepDefaults[6] = "Bestanden toevoegen";

function setStep(s, n, noNext){
	var el = getElement('step' + n);
	el.innerHTML = 'Stap ' + n + ': ' + s;
	
	for(var i = n + 1; i <= 6; i++) {
		var x = getElement('step' + i);
		x.innerHTML = 'Stap ' + i + ': ' + g_stepDefaults[i];
	}
	
	cleanSteps();
	if(noNext == undefined && (el2 = getElement('step' + (n + 1))))	{
		el2.className = 'wizardon';
	}
}

function cleanSteps(){
	var stepContainer = getElement('fs_steps');
	var i = 1;
	var step;
	while(step = getElement('step' + i)){
		step.className = 'wizard';
		i++;
	}	
}

function clearSteps(reset){
    var stepContainer = getElement('fs_steps');
    var i = 4;
    var step;
    while(step = getElement('step' + i)){
        stepContainer.removeChild(step);
        i++;
    }

    if(reset){
        setStepPlus();
    }
}

var titelCounter = 0;
var textRendererTitles = new Array;

function prepareTitle(s){
	var re = new RegExp("", "gi"); // DONT REMOVE! It's useless, but has to be here to make it work in IE6
	var s = escape(s);
	s = s.replace(/%EB/, '%C3%AB');
	return s;
}

function createTitle(s, id) {
	titelCounter++;
	textRendererTitles[titelCounter] = {title: escape(s), color:0x0AA5D8};
	s = prepareTitle(s);
	AC_FL_RunContent('codebase','https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0', 'id', 'myTitle' + titelCounter, 'name', 'myTitle' + titelCounter, 'width','100%','height','40','src','titel'+titelCounter,'quality','high','pluginspage','https://www.macromedia.com/go/getflashplayer','bgcolor', '#ffffff', 'wmode', 'transparent', 'movie','swf/titel?&id='+titelCounter + '&titel=' + s); //end AC code
}

function createTitleGray(s, id) {
	titelCounter++;
	textRendererTitles[titelCounter] = {title: escape(s), color:0x666666};
	s = prepareTitle(s);
	AC_FL_RunContent('codebase','https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0', 'id', 'myTitle' + titelCounter, 'name', 'myTitle' + titelCounter, 'width','100%','height','40','src','titel'+titelCounter,'quality','high','pluginspage','https://www.macromedia.com/go/getflashplayer','bgcolor', '#ff0000', 'wmode', 'transparent', 'movie','swf/titel?id='+titelCounter + '&titel=' + s + '&color=0x666666'); //end AC code
}

function createTitleWhite(s, id) {
	s = s.length > 50 ? s.substr(0,50) + '...' : s;
	titelCounter++;
	textRendererTitles[titelCounter] = {title: escape(s), color:0xffffff};
	s = prepareTitle(s);
	AC_FL_RunContent('codebase','https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0', 'id', 'myTitle' + titelCounter, 'name', 'myTitle' + titelCounter, 'width','100%','height','40','src','titel'+titelCounter,'quality','high','pluginspage','https://www.macromedia.com/go/getflashplayer','bgcolor', '#ff0000', 'wmode', 'transparent', 'movie','swf/titel?id='+titelCounter + '&titel=' + s + '&color=0xffffff'); //end AC code
}

function sillyIEtitle(s, id) {
	titelCounter++;
	textRendererTitles[titelCounter] = {title: escape(s), color:0x0AA5D8};
	AC_FL_RunContent('codebase','https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0', 'id', 'myTitle' + titelCounter, 'name', 'myTitle' + titelCounter, 'width','100%','height','40','src','titel'+titelCounter,'quality','high','pluginspage','https://www.macromedia.com/go/getflashplayer','bgcolor', '#ff0000', 'wmode', 'transparent', 'movie','swf/titel?id='+titelCounter + '&titel=' + prepareTitle(s)); //end AC code
	document.getElementById(id).innerHTML = result;
}

function getTextRendererTitle(id) {
	return textRendererTitles[id];
}

function cleanTitle(s)
{
	return unescape(s);	
}

function setTitleSize(w, h, nr)
{
	var div = getElement('titel' + nr);
	
	if(div){
		var objs = div.getElementsByTagName('object');
		var embs = div.getElementsByTagName('embed');
		var o = objs[0];
		var e = embs[0];
	
		if(o){
			o.setAttribute('width', w);
			o.setAttribute('height', h+5);
		}
	
		if(e) {
			e.setAttribute('width', w);
			e.setAttribute('height', h+5);
		}
	}
}

function showPreviewComments(artworkId, materialId, fileId){
	popUpInWindow('/deelname.php?go=previewcomment&artworkId=' + artworkId + '&materialId='+materialId+'&fileId='+fileId, 300, 300, 'fullscreen=0,resizable=1,location=0,statusbar=0,menubar=0,titlebar=1', 'previewComments');
}

function popUpPreview(URL, w, h) {
	w = w ? w : 768;
	h = h ? h : 700; // was 680

	var screenW = screen.width;
 	var screenH = screen.height;

	var top = (screenH - h) / 2;
	var left = (screenW - w) / 2;
	
	var id = new Date().getTime();
	try	{
		var popup = window.open(URL, 'win'+id, 'toolbar=0,scrollbars=no,location=0,statusbar=0,menubar=0,resizable=0,width=' + w + ',height=' + h + ',left = ' + left + ',top = ' + top);
		if(!popup){
			alert('De preview kan niet geopend worden. Indien u Safari als browser gebruikt, kunt u de popupblocker uitzetten. Dit is helaas een fout in de Safari browser.');
		}
		return popup;
	} catch(e) {
		//alert(e.message);
	}
}

function popUpJury(URL){
	var tw = 985;
	var th = 692;
	var s = readCookie('adcnpopupsize');
	if(s != null) {
		var dim = s.split('x');
		tw = dim[0];
		th = dim[1];
	}
	popUpInWindow(URL, tw, th, 'fullscreen=0,resizable=1,location=0,statusbar=0,menubar=0,titlebar=1', 'jurypopup');
}

function popUpKijkdagen(URL){
	popUpInWindow(URL, 985, 692, 'fullscreen=0,resizable=1,location=0,statusbar=0,menubar=0,titlebar=1', 'jurypopup');
}

function popUpInWindow(URL, w, h, params, windowName){
	URL = URL.replace(/~~~/, '#');  // voor links uit aanpasbare tekst. # breekt daarin de url
	windowName = windowName || 'adcnpopup';
    w = w || 918;
    h = h || 700;
    params = ',' + params || '';
    
	var screenW = screen.width;
 	var screenH = screen.height;

	var top = 0;
	var left = (screenW - w);
	
	newwindow = window.open(URL, windowName, 'scrollbars=1,width=' + w + ',height=' + h + ',left = ' + left + ',top = ' + top + params);
    if (window.focus) {newwindow.focus()}
}

function getParent(el){
	if (el.parentNode) 
		return el.parentNode;
	else if (el.parentElement) 
		return el.parentElement;
	else
		return null;
}

function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function highlightCode(tbl) {
	var o = document.getElementById(tbl);
	var tds = o.getElementsByTagName("td");
	for(var i = 0; i < tds.length; i++) {
		if(tds[i].className.indexOf('nohighlight') == -1) {
			tds[i].onmouseover = hightlight;
			tds[i].onmouseout = hightlight;
		}
	}
}

function hightlight(e) {
	if (!e) var e = window.event;
	var o = null;
	if (e.target) { 
		o = e.target;
	}else if (e.srcElement) {
		o = e.srcElement;
	}
	if (o.nodeType == 3) o = o.parentNode;
	
	//find the mothernode TR which has the initial onmouse event
	for(var i = 0; i < 10; i++) {
		if(o.nodeName == "TR") {
			break;
		}
		o = o.parentNode;
	}

	if(o.className == "lightson") {
		o.className = "lightsoff";
	}else{
		o.className = "lightson";
	}
}

function processRequestChange(req, returnFunction, argObj)
{
    if(req.readyState == 4)
    {
        if(req.status && req.status == 200)
        {
            curReq = req;
			if(returnFunction)
			{
				returnFunction(argObj);
			}
        }
        else
        {
            //alert("ajax error");
        }
    }
}

function setupAjax(returnFunction, argObj)
{
	var req;    //req object for each connection
    if(window.XMLHttpRequest)
    {
        req = new XMLHttpRequest();
    }
    else if(window.ActiveXObject)
    {
        try
        {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e)
        {
            req = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    
    if(req != null)
    {
        req.onreadystatechange = function()
        {
        	processRequestChange(req, returnFunction, argObj);
        }
    }
    
    return req;
}

// GET method
function openAjaxUrl(url, returnFunction, argObj)
{
	var req = setupAjax(returnFunction, argObj);
    if(req != null)
    {
        req.open("GET", url, true);
        req.send("");
    }
}

// POST method
function ajax(url, query, returnFunction, argObj)
{
	var req = setupAjax(returnFunction, argObj);
    if(req != null)
    {
        req.open("POST", url, true);
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");    
        req.send(query);
    }
}

/* GETS THE ELEMENT POSITION ON THE SCREEN, x, y */

function getElementPosition(o) {
    var offsetTrail = o;
    var offsetLeft = 0;
    var offsetTop = 0;
    while (offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 && 
        typeof document.body.leftMargin != "undefined") {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
    return {left:offsetLeft, top:offsetTop};
}

function getElementsByClassName(className, tag, elm){
	var testClass = new RegExp("(^|\\\\s)" + className + "(\\\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
}

function getRealChildNode(node){
	var l = node.childNodes.length;
	for(var i = 0; i < l; i++){
		if(node.childNodes[i].nodeType == 1){
			return node.childNodes[i];
		}
	}
}

function zebraTable(tableId, rowsPer, css, skip) {
	var o = document.getElementById(tableId);
	
	if(o) {
		var rowsContainer = o;

		while(getRealChildNode(rowsContainer).tagName != 'TR'){
			rowsContainer = getRealChildNode(rowsContainer);
		}

		var trs = new Array;
		var l = rowsContainer.childNodes.length;
		for(var i = 0; i < l; i++){
			if(rowsContainer.childNodes[i].nodeName == 'TR'){
				trs.push(rowsContainer.childNodes[i]);
			}
		}

		var start = rowsPer+skip;
		for(var i = start; i < trs.length; i = i + (2*rowsPer)) {
			trs[i].className = css + "Top";	
			for(var j = 1; j < rowsPer; j++) {
				if(i + j < trs.length) {
					if(j == rowsPer - 1) {
						trs[i+j].className = css + "Bottom";
					}else{
						trs[i+j].className = css;
					}
				}

			}
		}
	}
}

function turnOn(o) {
	var src = o.src.split(".gif");
	if(src.length > 0) {
		o.src = src[0] + "_on.gif";
	}
}

function turnOff(o) {
	var src = o.src.split("_on.gif");
	if(src.length > 0) {
		o.src = src[0] + ".gif";
	}
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

function refreshWindow() {
	window.location = window.location;
}

/*
	delegate the a function
*/
function delegate(that, thatMethod, arg1, arg2, arg3)
{
	return function() { return thatMethod.call(that, arg1, arg2, arg3); }
}

/*
**  Returns the caret (cursor) position of the specified text field.
**  Return value range is 0-oField.length.
*/
function doGetCaretPosition (oField) {

 // Initialize
 var iCaretPos = 0;

 // IE Support
 if (document.selection) { 

   // Set focus on the element
   oField.focus ();

   // To get cursor position, get empty selection range
   var oSel = document.selection.createRange ();

   // Move selection start to 0 position
   oSel.moveStart ('character', -oField.value.length);

   // The caret position is selection length
   iCaretPos = oSel.text.length;
 }

 // Firefox support
 else if (oField.selectionStart || oField.selectionStart == '0')
   iCaretPos = oField.selectionStart;

 // Return results
 return (iCaretPos);
}


/*
**  Sets the caret (cursor) position of the specified text field.
**  Valid positions are 0-oField.length.
*/
function doSetCaretPosition (oField, iCaretPos) {

 // IE Support
 if (document.selection) { 

   // Set focus on the element
   oField.focus ();

   // Create empty selection range
   var oSel = document.selection.createRange ();

   // Move selection start and end to 0 position
   oSel.moveStart ('character', -oField.value.length);

   // Move selection start and end to desired position
   oSel.moveStart ('character', iCaretPos);
   oSel.moveEnd ('character', 0);
   oSel.select ();
 }

 // Firefox support
 else if (oField.selectionStart || oField.selectionStart == '0') {
   oField.selectionStart = iCaretPos;
   oField.selectionEnd = iCaretPos;
   oField.focus ();
 }
}

function getMousePosition(e) {
	var cursor = {x:0, y:0};
	if(!e) {
		e = window.event;
	}
	
	if (e.pageX || e.pageY) {
		cursor.x = e.pageX;
		cursor.y = e.pageY;
	} else {
		cursor.x = e.clientX + 
			(document.documentElement.scrollLeft || 
			document.body.scrollLeft) - 
			(document.documentElement.clientLeft || 
			document.body.clientLeft);
		cursor.y = e.clientY + 
			(document.documentElement.scrollTop || 
			document.body.scrollTop) - 
			(document.documentElement.clientTop || 
			document.body.clientTop);
	}
	return cursor;
}

function array_cleanup(a){
	var l = a.length;
	var r = new Array;
	for(var i = 0; i < l; i++){
		if(a[i] != undefined){
			 r.push(a[i]);
		}
	}
	return r;
}

var toggleObjects = new Array;

function toggleSetup(){
	var toggleables = getElementsByClassName('toggleable');
	var l = toggleables.length;
	
	for(var i = 0; i < l; i++){
		var id = toggleables[i].id;
		if(!toggleObjects[id]){
			toggleObjects[id] = new ActiveObject(getElement(id));
			toggleObjects[id].easing = 5;
			toggleObjects[id].foldIn(0);
			toggleObjects[id].onFoldIn = function(){
				this.item.style.display = 'none';
			}
			toggleObjects[id].onFoldOut = function(){
			}
		}
	}
}

function toggle(toggledId, toggler, max){
	var toggled = getElement(toggledId);
	var ao = toggleObjects[toggledId];
	if(ao.folded){
		toggled.style.display = 'block';
		//toggled.style.border = '1px solid green';
		toggler.className = toggler.className.replace(/\btoggler\b/, 'togglerOn');
		ao.foldOut(50, max);
	} else {
		toggler.className = toggler.className.replace(/\btogglerOn\b/, 'toggler');
		ao.foldIn();
	}
}

function checkWordMax(el, max){
	return el.value.split(/\s+/).length <= max ? true : false;
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
