/*######################################################*\
||                                                      ||
||                  S N E L S I T E                     ||
||                                                      ||
||       Media Design Content Management System         ||
||           Copyright 2002-2007 Media Design           ||
\*######################################################*/


function $(id)
{	
	var i, elements = [];

	if (id.constructor == Array)
	{
		for(i = 0; i < id.length; i++)
		{
			elements.push(document.getElementById(id[i]));
		}
		return elements;
	}

	return document.getElementById(id);
}

// #######################################################################################
// #########################   START AJAX HANDLING CODE   ################################
// #######################################################################################

var AJAX = {

	xmlhttp : null,
	type    : null,
	notice  : '',

	// create a new AJAX object
	create : function()	
	{
		try {
			xmlhttp = new XMLHttpRequest(); // Gecko's
		} catch (failed) {
			try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // IE
			} catch(failed) {
				xmlhttp = null; // 
				return false;
			}
		}

		if ($('response-notice'))
		{
			notice = $('response-notice');
		}
	},

	running : function()
	{
		// check for running connections
		xmlhttp.abort();
	},

	state : function(execute)
	{
		if (xmlhttp.readyState != 4) {
			return false; // do not go further on till the request is complete
		}

		if (xmlhttp.status != 200) {
			return false; // 404 or 0 status (IE sometimes returns 0)
		} 

		if (type.toLowerCase() == 'xml')
		{
			if (xmlhttp.reponseXML == '')
			{
				return false;
			}
		}
		else
		{
			if (xmlhttp.responseText == '')
			{
				return false;
			}
		}
	
		eval(execute);
	},

	request : function(kind, file, execute, responsetype)
	{
		type = responsetype;

		if ($('response-notice'))
		{
			notice.firstChild.innerHTML = arguments[4];
		}

		xmlhttp.onreadystatechange = function() { AJAX.state(execute); };

		xmlhttp.open(kind, file, true);
		xmlhttp.send(null);
	},

	response : function()
	{
		return (type.toLowerCase() == 'xml' ? xmlhttp.responseXML : xmlhttp.responseText);
	},

	raise_notice : function(text)
	{
		if ($('response-notice'))
		{
			notice.firstChild.innerHTML = text;
		}
	}
}

var Construct = {
	node: function(element)
	{
		element = document.createElement(element.toLowerCase());
		if (!element) return; // failed to create element, no use to continue

		if (arguments[1]) 
		{
			if (typeof(arguments[1])=='object') {			
				if (arguments[1].constructor==Array) {	
					this.children(element, arguments[1]);
				} else {
					this.attributes(element, arguments[1]);
				}
			}
			
			if (typeof(arguments[1])=='string') {
				element.appendChild(this.text(arguments[1]));
			}
		}

		if (arguments[2])
		{
			if (typeof(arguments[2])=='string')
				element.appendChild(this.text(arguments[2]));
			if (typeof(arguments[2])=='object') 
				this.children(element, arguments[2]);	
		}

		if (arguments[3]) 
			this.children(element, arguments[3]);
		
		return element;
	},

	children: function(el, childs)
	{
		for (var i = 0; i < childs.length; i++)
		{
			el.appendChild(childs[i]);
		}
	},

	attributes: function(el, attribute)
	{
		for(attribu in attribute)
		{
			el[attribu] = attribute[attribu];
		}
	},

	text: function(string) 
	{
		return document.createTextNode(string);
	}
}

function getElementsByClassName(tag, className)
{
	var tmp, elements = [];

	elements = [];
	tmp = (arguments[2] ? arguments[2].getElementsByTagName(tag) : document.getElementsByTagName(tag));
	for(i = 0; i < tmp.length; i++)
	{
		if (tmp[i].className == className)
		{
			elements.push(tmp[i]);
		}
	}

	return elements;
}

function create_cookie(name, value, kill) {
	var date, expires;
	
	if (kill)
	{
		date = new Date("January 1, 1970");
	}
	else
	{
		date = new Date();
		date.setTime(date.getTime()+(365*24*60*60*1000));
	}

	expires = "; expires="+date.toGMTString();	
    document.cookie = name+"="+ value + expires + "; path=/";
}

function get_cookie(type) {
	var info, cookies, title, i;
	
	info = type + "=";
	cookies = document.cookie.split(';');

	for(i = 0; i < cookies.length; i++) {
		title = cookies[i].replace(/^\s+/, '');

		if (title.indexOf(info) == 0) {
			if (title.substring(info.length, title.length) == "null") {
				return '';
			}
			return title.substring(info.length, title.length);
		}
	}
	return '';
}

if (document.createElementNS == null)
{
	document.createElementNS = function(ns, tn){ return document.createElement(tn) }
}

// ARRAY EXTENSIONS

if (!Array.prototype.push) Array.prototype.push = function() {
    for (var i=0; i<arguments.length; i++) this[this.length] = arguments[i];
    return this.length;
}

Array.prototype.find = function(value, start) {
    start = start || 0;
    for (var i=start; i<this.length; i++)
        if (this[i]==value)
            return i;
    return -1;
}

Array.prototype.has = function(value) {
    return this.find(value)!==-1;
}

// FUNCTIONAL

function map(list, func) {
    var result = [];
    func = func || function(v) {return v};
    for (var i=0; i < list.length; i++) result.push(func(list[i], i, list));
    return result;
}

function filter(list, func) {
    var result = [];
    func = func || function(v) {return v};
    map(list, function(v) { if (func(v)) result.push(v) } );
    return result;
}


// DOM

function getElem(elem) {
    if (document.getElementById) {
        if (typeof elem == "string") {
            elem = document.getElementById(elem);
            if (elem===null) throw 'cannot get element: element does not exist';
        } else if (typeof elem != "object") {
            throw 'cannot get element: invalid datatype';
        }
    } else throw 'cannot get element: unsupported DOM';
    return elem;
}

function hasClass(elem, className) {
    return getElem(elem).className.split(' ').has(className);
}

function getElementsByClass(className, tagName, parentNode) {
    parentNode = !isUndefined(parentNode)? getElem(parentNode) : document;
    if (isUndefined(tagName)) tagName = '*';
    return filter(parentNode.getElementsByTagName(tagName),
        function(elem) { return hasClass(elem, className) });
}


// DOM EVENTS

function listen(event, elem, func) {
    elem = getElem(elem);
    if (elem.addEventListener)  // W3C DOM
        elem.addEventListener(event,func,false);
    else if (elem.attachEvent)  // IE DOM
        elem.attachEvent('on'+event, function(){ func(new W3CDOM_Event(elem)) } );
        // for IE we use a wrapper function that passes in a simplified faux Event object.
    else throw 'cannot add event listener';
}

function mlisten(event, elem_list, func) {
    map(elem_list, function(elem) { listen(event, elem, func) } );
}

function W3CDOM_Event(currentTarget) {
    this.currentTarget  = currentTarget;
    this.preventDefault = function() { window.event.returnValue = false }
    return this;
}


function isUndefined(v) {
    var undef;
    return v===undef;
}


function add_onclicks()
{
	var contentDiv = document.getElementById('content');
	var imgpopups = getElementsByClass('imgpopup', 'a', contentDiv);
	for (var i = 0; i < imgpopups.length; i++)
	{
		var sendurl = imgpopups[i];
		eval('imgpopups[i].onclick = function () { popup_inline_img(this, "' + sendurl + '"); return false; };');
		
	}
}

function clear_inline_img(elemid)
{
	var existPopup = document.getElementById(elemid);
	if (existPopup != false && existPopup != null && existPopup != undefined)
	{
		existPopup.parentNode.removeChild(existPopup);
	}
	add_onclicks();
}

function popup_inline_img(elem, url)
{

	clear_inline_img('popupimg');

	var imgPopup = document.createElement('img');

	imgPopup.setAttribute('src', url);
	imgPopup.setAttribute('alt', 'popup');
	imgPopup.setAttribute('id', 'popupimg');
	imgPopup.className = 'imgpopup';

	imgPopup.src = url;

	elem.onclick = function () { clear_inline_img('popupimg'); return false; };

	elem.appendChild(imgPopup);
}


function externalLinks()
{
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName('a');
	for (var i=0; i<anchors.length; i++)
	{
		var anchor = anchors[i];
		if (anchor.getAttribute("rel") == "external") anchor.target = "_blank";
	}
}

function gallery_init()
{
	// is getElementById supported by this browser
	if (!document.getElementById) return false;
		
	// do not proceed if there isn't a gallery
	if (!document.getElementById('gallery-thumbs')) return false;

	var gallery, thumbs, i, first = true;

	gallery = document.getElementById('gallery-thumbs');
	
	// give each thumb a onclick event handler
	thumbs = gallery.getElementsByTagName('img');
	for (i = 0; i < thumbs.length; i++)
	{
		if (thumbs[i].className == 'gthumb')
		{
			thumbs[i].onclick = function() { view_thumb(this); return false; };
		}
	}

	thumbs = null;
}

function userform_init()
{
	if (!document.getElementById) return false;

	if ($('userform'))
	{	
		form = $('userform');
		form.onsubmit = function() { return validate_form(this) };
	}
}

/* temp */
function validate_form(form)
{
	var i, string, error, is_filled, checked_names, exists, text, tmp, target;

	error = [];
	checked_names = [];
	for(i = 0; i < form.elements.length; i++)
	{
		string = form.elements[i].className;
		this_el = form.elements[i];
		if (string.indexOf('required') != -1)
		{
			el = this_el;
			if (el.nodeName.toLowerCase() == 'input')
			{
				if (el.type == 'text' || el.type == 'file')
				{
					if (el.value == '')
					{
						el = crawl_to_span(el);
						error.push('Verplicht veld niet ingevuld: ' + el.lastChild.nodeValue);
					}

				}
				else if (el.type == 'checkbox' || el.type == 'radio')
				{
					exists = false;
					for(k = 0; k < checked_names.length; k++)
					{
						if (checked_names[k] == el.name)
						{
							exists = true;
						}
					}

					if (exists == true)
					{
						continue;
					}

					checked_names.push(el.name);

					while(el.nodeName.toLowerCase() != 'p' && el.parentNode)
					{
						el = el.parentNode;
					}

					text = crawl_to_span(el);
					is_filled = false;
					inputs = el.getElementsByTagName('input');
					for (j = 0; j < inputs.length; j++)
					{						
						if (inputs[j].checked == true)
						{
							is_filled = true;
						}
					}

					if (is_filled == false)
					{
						error.push('Verplicht veld niet ingevuld: ' + text.lastChild.nodeValue);
					}
				}
			}
			else if (el.nodeName.toLowerCase() == 'textarea' && el.value == '')
			{
				el = crawl_to_span(el);
				error.push('Verplicht veld niet ingevuld: ' + el.lastChild.nodeValue);
			}
			else if (el.nodeName.toLowerCase() == 'select' && el.value == '')
			{
				el = crawl_to_span(el);
				error.push('Verplicht veld niet ingevuld: ' + el.lastChild.nodeValue);
			}
		}
		
		if (string.indexOf('email') != -1 && this_el.value != '')
		{
			if (!this_el.value.match(/^[a-z0-9.!\#$%&'*+-\/=?^_`{|}~]+@([0-9.]+|([a-z0-9._-]+\.+[a-z]{2,4}))$/i))
			{
				tmp = crawl_to_span(this_el);
				error.push('Ongeldige waarde ingevoerd bij: ' + tmp.lastChild.nodeValue + '```' + 'Dit veld moet een geldig e-mailadres zijn');
			}
		}
		
		if (string.indexOf('text_only') != -1 && this_el.value != '')
		{
			if (!this_el.value.match(/^[+a-z,.! -]+$/i))
			{
				tmp = crawl_to_span(this_el);
				error.push('Ongeldige waarde ingevoerd bij: ' + tmp.lastChild.nodeValue + '```' + 'Dit veld mag alleen tekst bevatten');
			}
		}

		if (string.indexOf('digits_only') != -1 && this_el.value != '')
		{
			if (!this_el.value.match(/^[0-9]+$/))
			{
				tmp = crawl_to_span(this_el);
				error.push('Ongeldige waarde ingevoerd bij: ' + tmp.lastChild.nodeValue + '```' + 'Dit veld mag alleen cijfers bevatten');
			}
		}
	}

	if (error.length)
	{
		target = document.getElementById('form-errorbox');

		if (document.getElementById('form-errors'))
		{		
			tmp = document.getElementById('form-errors');
			tmp.parentNode.removeChild(tmp);
		}

		ul = Construct.node('ul', {className:'content warn', id:'form-errors'});

		for(i = 0; i < error.length; i++)
		{			
			tmp = error[i].split('```');
			if (tmp.length == 2)
			{
				//alert(tmp[1]);
				ul.appendChild(Construct.node('li', tmp[0], [
					Construct.node('p',	[
						Construct.node('small', tmp[1])
						])
					])
				);
			}
			else
			{
				ul.appendChild(Construct.node('li', error[i]));
			}
		}

		target.appendChild(ul);
		window.scrollTo(0,-4000); // bah!

		return false;
	}

	return true;
}

function crawl_to_span(el)
{
	while(el.nodeName.toLowerCase() != 'p' && el.parentNode)
	{
		el = el.parentNode;
	}

	return el.getElementsByTagName('span')[0];
}

function view_thumb(thumb)
{
	var target, tmp, p, text;

	target = document.getElementById('current_picture');

	tmp = target.getElementsByTagName('img')[0];
	tmp.src = thumb.parentNode.href;

	p = document.getElementById('selected-thumb-desc');

	// remove old description
	if (p.firstChild) {
		p.removeChild(p.firstChild);
	}
	
	// add new description
	if (thumb.alt) {	
		text = document.createTextNode(thumb.alt);
		p.appendChild(text);
	}
}

// change this with addevent stuff
window.onload = function () {
	externalLinks();
	gallery_init();
	userform_init();
}

/*######################################################*\
||                   S N E L S I T E                    ||
||										                ||
||           Copyright 2002-2007 Media Design           ||
\*######################################################*/