var ajax_assets_add  = null;
var ajax_assets_del  = null;
var ajax_assets_res  = null;
var ajax_assets_hid  = null;
var ajax_reload_link = null;
var ajax_result_area = null;

var o_add  = null;
var o_del  = null;
var o_hid  = null;
var o_res  = null;
var o_area = null;

var asset_content = '';

//open-/dichtvouwen van bomen
var collapsedStateMap = {};
var EXPANDED	= 1;			// state
var COLLAPSED	= 2;			// state
var EXPAND		= 'expand';		// actie
var COLLAPSE	= 'collapse';	// actie
var CUSTOM		= 'custom';		// actie

//really not important (the first two should be small for Opera's sake)
var PositionX = 10;
var PositionY = 10;
var defaultWidth  = 600;
var defaultHeight = 400;

//kinda important
var AutoClose = true;

/**
 * @desc	Popup-window met preview van een
 * @param {String} imageURL		Url naar de image
 * @param {String} imageTitle	Titel van de image
 */
function popImage(imageURL,imageTitle)
{
  var imgWin = window.open('','_blank','scrollbars=no,resizable=1,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY);
  if( !imgWin ) { return true; } //popup blockers should not cause errors
  imgWin.document.write('<html><head><title>'+imageTitle+'<\/title><script type="text\/javascript">\n'+
    'function resizeWinTo() {\n'+
    'if( !document.images.length ) { document.images[0] = document.layers[0].images[0]; }'+
    'var oH = document.images[0].height, oW = document.images[0].width;\n'+
    'if( !oH || window.doneAlready ) { return; }\n'+ //in case images are disabled
    'window.doneAlready = true;\n'+ //for Safari and Opera
    'var x = window; x.resizeTo( oW + 200, oH + 200 );\n'+
    'var myW = 0, myH = 0, d = x.document.documentElement, b = x.document.body;\n'+
    'if( x.innerWidth ) { myW = x.innerWidth; myH = x.innerHeight; }\n'+
    'else if( d && d.clientWidth ) { myW = d.clientWidth; myH = d.clientHeight; }\n'+
    'else if( b && b.clientWidth ) { myW = b.clientWidth; myH = b.clientHeight; }\n'+
    'if( window.opera && !document.childNodes ) { myW += 16; }\n'+
    'x.resizeTo( oW = oW + ( ( oW + 200 ) - myW ), oH = oH + ( (oH + 200 ) - myH ) );\n'+
    '//var scW = screen.availWidth ? screen.availWidth : screen.width;\n'+
    '//var scH = screen.availHeight ? screen.availHeight : screen.height;\n'+
    '//if( !window.opera ) { x.moveTo(Math.round((scW-oW)/2),Math.round((scH-oH)/2)); }\n'+
    '}\n'+
    '<\/script>'+
    '<\/head><body onload="resizeWinTo();"'+(AutoClose?' onblur="self.close();"':'')+'>'+
    (document.layers?('<layer left="0" top="0">'):('<div style="position:absolute;left:0px;top:0px;display:table;">'))+
    '<img src='+imageURL+' alt="Loading image ..." title="" onload="resizeWinTo();" onclick="self.close()">'+
    (document.layers?'<\/layer>':'<\/div>')+'<\/body><\/html>');
  imgWin.document.close();
  if( imgWin.focus ) { imgWin.focus(); }
  return false;
}


function template_ajax_asset_toevoegen(ajax_link, add_link, del_link, resultarea, assets_res, assets_hid)
{
	ajax_assets_add = add_link;
	ajax_assets_del = del_link;
	ajax_assets_res = assets_res;
	ajax_assets_hid = assets_hid;
	ajax_result_area = resultarea;

	o_res = document.getElementById(resultarea);
	o_res.className = '';

	makeHttpRequest_x_ajax(ajax_link);
	return false;
}

function template_ajax_asset_js_toevoegen(asset_type, asset_id, asset_content, beeldExtra)
{
	o_add  = document.getElementById(ajax_assets_add);
	o_del  = document.getElementById(ajax_assets_del);
	o_hid  = document.getElementById(ajax_assets_hid);
	o_res  = document.getElementById(ajax_assets_res);
	o_area = document.getElementById(ajax_result_area);

	if(asset_type == 'beeld')
	{
		asset_content = '<a href="javascript:;" onclick="popImage(\'figuur_preview.php?type=crop&figuur='+asset_id+'\',\''+beeldExtra.title+'\')"><img src="figuur_preview.php?type=thumb&figuur='+asset_id+'" alt="" onload="resize_image(this,'+beeldExtra.maxWidth+','+beeldExtra.maxHeight+');" /></a>';
	}

	o_add.className  = 'hidden';
	o_del.className  = '';
	o_res.className  = '';
	o_hid.value      = asset_id;
	o_res.innerHTML  = asset_content;
	o_area.className = 'hidden';
}

function template_ajax_asset_verwijderen(confirm_text,del_link, add_link, resultarea, assets_res, assets_hid)
{
	var confirm_boolean = confirm(confirm_text);
	if(confirm_boolean)
	{
		o_add = document.getElementById(add_link);
		o_del = document.getElementById(del_link);
		o_res = document.getElementById(resultarea);
		o_hid = document.getElementById(assets_hid);
		o_res = document.getElementById(assets_res);

		o_add.className = '';
		o_del.className = 'hidden';
		o_res.className = 'hidden';
		o_hid.value 	= '';

		return true;
	}
	else
	{
		return false;
	}
}


/**
 * @desc 	Sluit popup en stuur een ajax-request naar de reload link
 * @param 	{int} 	ajax_reload_link	id van de reload link
 */
function close_popup(ajax_reload_link)
{
	ajax = window.opener.document.getElementById(ajax_reload_link);
	if(ajax)
	{
		ajax.click();
	}
	window.close();
}

/**
 * Print debug naar firebug
 * @param  string	msg		bericht dat je wil tonen
 * @param  string   type    (optioneel) type bericht dat je wil tonen (warn, error, info, debug[=default])
 */
function firebug(msg, type)
{
	//test of de firefox extension 'firebug' is geïnstalleerd
	try
	{
		var apollo = "[apollo] ";
		switch(type)
		{
			case 'warn': 	console.warn(apollo+msg);		break;
			case 'error':	console.error(apollo+msg);		break;
			case 'info':	console.info(apollo+msg);		break;
			default:		console.debug(apollo+msg);
		}

	}catch(error) { /* do nothing */ }
}

/**
 * Een foto verkleinen als die groter is dan een bepaald formaat
 * @param   {Object}	image		figuur die gewijzigd kan worden
 * @param   {int}		max_width   maximale breedte van de foto
 * @param 	{int}		max_height	maximale hoogte van de foto
 * @param	{boolean}	keep_ratio	verhouding bewaren? (default true)
 * @param	{boolean}	scale_up	kleinere foto's vergroten? (default false)
 */
function resize_image(image, max_width, max_height, keep_ratio, scale_up)
{
	// default values for optional arguments
	if (typeof keep_ratio == 'undefined') { keep_ratio = true; }
	if (typeof scale_up   == 'undefined') { scale_up   = false; }

	var image_width  = image.width;
	var image_height = image.height;

	// return if the image doesn't need to be resized
	if (!scale_up && !(image_width > max_width || image_height > max_height)) { return; }

	if (keep_ratio)
	{
		var maxes_ratio = max_width / max_height;
		var image_ratio = image_width / image_height;
		var scale = (image_ratio > maxes_ratio ? max_width / image_width : max_height / image_height);

		image.width  = Math.round(image_width  * scale);
		image.height = Math.round(image_height * scale);
	}
	else
	{
		image.width  = max_width;
		image.height = max_height;
	}
}

function sjabloonSwitch()
{
	var el 		= document.getElementById('sjabloon');
	var unhide	= document.getElementById('sjabloon_'+el.value);

	if (unhide) { unhide.className = ''; }
}

/**
 * Initialiseer een boom voor open-/dichtvouwen
 *
 * Voor actie worden de variabelen EXPAND, COLLAPSE en CUSTOM gebruikt.
 *
 * @param	{string}	actie		te ondernemen actie
 * @param	{string}	boom_id		id van de boom
 * @param	{Array}		expand_ids	id's van te expanden takken bij actie CUSTOM
 */
function boom_init(actie, boom_id, expand_ids)
{
	if (actie == CUSTOM)
	{
		// eerst alles dichtvouwen
		boom_collapse_expand(COLLAPSE, boom_id, "1", true);

		// daarna bepalen wat moet opengevouwen worden
		for (var i = 0; i < expand_ids.length; i++)
		{
			boom_collapse_expand(EXPAND, boom_id, expand_ids[i], false);
		}
	}
	else
	{
		// actie gewoon doorgeven
		boom_collapse_expand(actie, boom_id, "1", true);
	}
}

/**
 * Vouw een tak van een boom dicht
 * @param	{string}	boom_id		id van de boom
 * @param	{string}	hier_uid	uniek hi�rarchisch id van de node waaronder de tak moet dichtvouwen
 */
function boom_collapse(boom_id, hier_uid)
{
	boom_collapse_expand(COLLAPSE, boom_id, hier_uid, false);
}

/**
 * Vouw een tak van een boom open
 * @param	{string}	boom_id		id van de boom
 * @param	{string}	hier_uid	uniek hi�rarchisch id van de node waaronder de tak moet openvouwen
 */
function boom_expand(boom_id, hier_uid)
{
	boom_collapse_expand(EXPAND, boom_id, hier_uid, false);
}


function special_boom_expand(boom_id, hier_uid)
{
	boom_collapse_expand(EXPAND, boom_id, hier_uid, false);
	var min = document.getElementById("min_"+boom_id+'_'+hier_uid);
		min.checked = true;
	var chk = document.getElementById("chk_"+boom_id+'_'+hier_uid);
		chk.checked = true;
}

function special_boom_collapse(boom_id, hier_uid)
{
	boom_collapse_expand(COLLAPSE, boom_id, hier_uid, false);
	var plus = document.getElementById("plus_"+boom_id+'_'+hier_uid);
	plus.checked = false;
	var chk = document.getElementById("chk_"+boom_id+'_'+hier_uid);
		chk.checked = false;
}

/**
 * Vouw een tak van een boom open of dicht
 *
 * Voor actie worden de variabelen EXPAND en COLLAPSE gebruikt.
 *
 * @param	{string}	actie		te ondernemen actie
 * @param	{string}	boom_id		id van de boom
 * @param	{string}	hier_uid	uniek hi�rarchisch id van de node waaronder de tak moet open-/dichtvouwen
 * @param	{boolean}	is_init		eerste oproep om de boom te initialiseren? (default false)
 */
function boom_collapse_expand(actie, boom_id, hier_uid, is_init)
{
	if (is_init === undefined) { is_init = false; }

	if (collapsedStateMap[boom_id] === undefined)
	{
		collapsedStateMap[boom_id] = {};
		collapsedStateMap[boom_id]["1"] = EXPANDED;
	}

	// root kan nooit collapsen
	if (hier_uid != "1")
	{
		collapsedStateMap[boom_id][hier_uid] = (actie == EXPAND ? EXPANDED : COLLAPSED);
		document.getElementById("plus_"+boom_id+"_"+hier_uid).style.display	= (actie == EXPAND ? "none" : "inline");
		document.getElementById("min_"+boom_id+"_"+hier_uid).style.display	= (actie == EXPAND ? "inline" : "none");
	}

	var trs = document.getElementById(boom_id).getElementsByTagName("tr");
	var tr;

	var hier_uid_match = boom_id+"_"+hier_uid+"-";
	var hier_uid_index = boom_id.length + 1;
	var current_uid, parent_uid, do_expand;

	for (var i = 0; i < trs.length; i++)
	{
		tr = trs[i];

		if (tr.id.indexOf(hier_uid_match) == 0)
		{
			current_uid	= tr.id.substring(hier_uid_index);
			parent_uid	= current_uid.substring(0, current_uid.lastIndexOf('-'));

			if (is_init)
			{
				switch (actie)
				{
					case EXPAND :
						collapsedStateMap[boom_id][current_uid] = EXPANDED;
						break;
					case COLLAPSE :
						// root kan nooit collapsen
						if (parent_uid == "1")
						{
							collapsedStateMap[boom_id][current_uid] = EXPANDED;
							continue;	// geen verdere verwerking op deze node
						}
						else
						{
							collapsedStateMap[boom_id][tr.id] = COLLAPSED;
							document.getElementById("plus_"+boom_id+"_"+parent_uid).style.display	= "inline";
							document.getElementById("min_"+boom_id+"_"+parent_uid).style.display	= "none";
						}
						break;
				}
			}

			switch (actie)
			{
				case EXPAND :
					do
					{
						do_expand = (collapsedStateMap[boom_id][parent_uid] == EXPANDED);
						parent_uid = parent_uid.substring(0, parent_uid.lastIndexOf('-'));
					} while (do_expand && parent_uid.length >= hier_uid.length);

					if (do_expand) { tr.style.display = ""; }
					break;
				case COLLAPSE :
					tr.style.display = "none";
					break;
			}
		}
	}
}

/**
 * Check/uncheck all checkboxes with the same name.
 *
 * @param {String} chkName		The name of the checkboxes
 * @param {Boolean} chkChecked	Check (true) or uncheck (false)? (default true)
 */
function check_all(chkName, chkChecked)
{
	if (typeof chkChecked == "undefined") { chkChecked = true; }

	var elements = document.getElementsByName(chkName);
	var element;

	for (var i = 0, l = elements.length; i < l; i++)
	{
		element = elements[i];

		// only checkboxes
		if (element.tagName.toLowerCase() == "input" && element.type == "checkbox")
		{
			element.checked = chkChecked;
		}
	}
}
