/**
 * Humanique main javascript
 *
 * this contains all the main javascripts
*/

// Please keep the document.ready on top of this file
$(document).ready(initialize);

var website_host = "";
var website_dir = "";
var website_url = "";
var loggedin = false;
var prelogin_url = "";
var tb_dimensions = {height: 420, width: 540}
var production_node = "";
var ticket_node = "";
var use_https = true;

function initialize()
{
	if (!loggedin) {
		setup_secure_links();
	}
	
	// psd2xhtml inits
	//initAutocomplete();
	ieHover('#list > li');
	allHover('div.box:not(.no-hover)');
	//initTabs('.tabset');
	initPopups();
	initSidebar();
	initRadioSwith();
	
	// Search init
	initSearchResults();

	// Setup route-form

	$('#route-form').attr('action', $('#route-form').attr('paaction'));
	
	// initTooltips
	initTooltips();
}
function initRadioSwith(){
	var _radioBt = $('ul.theater-info input');
	var _theaterBlocks = $('div.theater-map > div');
	var _priceBlocks = $('div.seat-number-selector span.platzgruppe');
	_radioBt.each(function(i, radio){
		var _val = '';
		if ($(radio).is(':checked')) {
			_val = $(this).attr("id");
			_theaterBlocks.filter('.'+_val).addClass('active');
		}
		$(radio).click(function(){
			_val = $(this).attr("id");
			_theaterBlocks.removeClass('active');
			_theaterBlocks.filter('.'+_val).addClass('active');
			$('fieldset.step3').attr("class", "step3-inactive");
			_priceBlocks.removeClass('active');
			_priceBlocks.filter('#platzgruppe-'+$(this).val()).addClass('active');
		});
	});
}


function initTooltips()
{
	$("a.info-link").tooltip({ 
		bodyHandler: function() { 
			return $($(this).attr("href")).html(); 
		}, 
		showURL: false 
	});

	$("img.info-link").tooltip({ 
		bodyHandler: function() { 
			return $($(this).attr("href")).html(); 
		}, 
		showURL: false 
	});
	
	$("img.info-link").hover(
		function () {
			$("select.upselling-select").addClass('ie-hidden');
		},
		function () {
			$("select.upselling-select").removeClass('ie-hidden');
		}
	);
}
// end of document ready

function open_thickbox(url)
{
	tb_show('',url,false);
}

function open_parent_window_tb(el,tit,href)
{
	if ($(el).hasClass('busy')) {
		return false;
	}
	window.parent.tb_show(tit, href, false);
	return false;
}

/**
 * Function get's called from the homepage swf, when
 * you click on the kaarten button.
 * 
 * @param url
 * @return
 */
function banner_button_onclick(url)
{
	// just follow it's location
	document.location = url;
}

// @todo implement furthen when new slideshow swf arrives
function set_view_preview(fname)
{
	var objSwf = window.parent.$("#editor_swf").get(0);
	objSwf.set_bg(fname);
}

function initPopups(){
	var _list = $('table.kalender td');
	_list.hover(function(){
		_list.removeClass('active');
		$(this).addClass('active');
	}, function(){
		$(this).removeClass('active');
	});
}
/*--- ie hover ---*/
function ieHover(_list) {
	if ($.browser.msie && $.browser.version < 7) {
		allHover(_list);
	}
}

function allHover(_list) {
	$(_list).hover(function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	});
}

/*--- function Autocomplete ---*/
function initAutocomplete(){
	var _field = $('#search-field');
	var _val = _field.attr('value');
	_field.focus(function(){
		if(this.value == _val) this.value = '';
	}).blur(function(){
		if(this.value == '') this.value = _val;
	}).autocomplete("scripts/search.php", {
		autoFill: true
	});
}

/*--- slide tabs function  ---*/
function initSidebar(){
	$('#buy .link').click(function(){
		// Load cart
		if ($('#buy .drop-list').css('display') == 'none') {
			$('#buy .link').addClass('busy');
			$.ajax({
				type: "GET",
				cache: false,
				url: "ajax/?cmd=cart&act=get_cart_contents",
				success: function(msg) {
					$('#buy .link').removeClass('busy');
					$('#buy .drop-list .list').html(msg);						
					$('#buy .drop-list').slideDown(400);
				}
			});
		}
		else {
			$('#buy .drop-list').slideUp(400);
		}
		return false;
	});
	$('#buy .drop-list .sluiten').click(function(){
		$('#buy .drop-list').slideUp(400);
		return false;
	});
	$('#sidebar ul.links .drop-form').hide();
	$('#sidebar ul.links .btn-routeplanner').click(function(){
		$('#sidebar ul.links .drop-form').slideToggle(400);
		return false;
	});
}
function initTabs(h_list) {
	$(h_list).each(function(_ind, _el) {
		var btn_h = $(_el);
		var _btn = $(_el).find('a.tab');
		var _a = 0;
		_btn.each(function(_ind, _el) {
			this._box = $('#'+_el.href.substr(_el.href.indexOf("#") + 1));
			if($(_el).parent().hasClass('active')) {
				this._box.show();
				_a = _ind;
			}
			else {
				this._box.hide();
			}
			_el.onclick = function() {
				if(!$(this).parent().hasClass('active')){
					_btn.get(_a)._box.hide();
					_btn.eq(_a).parent().removeClass('active');
					this._box.show();
					$(this).parent().addClass('active');
					_a = _ind;
				}
				return false;
			}
		});
	});
}

// General support (Start)

function submit_form(element)
{
	$(element).parent('form').get(0).submit();
	
	return false;
}

// General support (End)

// Routes (Start)
var map;
var gdir;
var geocoder = null;
var addressMarker;

function route_change_target(element)
{
	klantpc = $('#route-form input[name=Klantpc]');
	klanthuisnr = $('#route-form input[name=Huisnr]');

	if (element.value == "new") {
		klantpc.val('3072AG');
		klanthuisnr.val('1');
	}
	else {
		klantpc.val('3012EH');
		klanthuisnr.val('10');
	}
}

function route_change(element)
{
	elms = $('#route-form input[name='+ element.name +']');
	
	val = "car";
	
	elms.each(function() {
		if ($(this).attr('checked')) {
			val = this.value;
		}
	});

	if (val == "car") {
		// disable and empty the date and arrival features
		$('#route-form .inputs .date input').each(function(n) {
			$(this).attr('disabled', 'disabled');
			$(this).css('background-color', '#eeeeee');
		});
		
		// Set form action, method and target
		form = $('#route-form');
		form.attr('method', 'get');

		action = form.attr('action');
		form.attr('action', form.attr('caraction'));

		form.removeAttr('target');
	}
	else if (val == "public") {
		// enable the date and arrival features
		$('.inputs .date input').each(function(n) {
			$(this).removeAttr('disabled');
			$(this).css('background-color', '#ffffff');
		});
		
		// Set form action, method and target
		form = $('#route-form');
		form.attr('method', 'post');

		action = form.attr('action');
		form.attr('action', form.attr('paaction'));

		form.attr('target', '_blank');
	}
}

function route_submit()
{
	if (register_node == 1) {
		do_submit = confirm(register_node_text);
	}
	else {
		do_submit = true;
	}

	if (!do_submit) {
		return false;
	}
	
	route_change_target($('#route-form input[name=which]:checked').get(0));
	
	// check if form is filled
	target = $('#route-form input[name=transport-method]:checked').val();
	pc_number = $('#pc_number').val();
	pc_letters = $('#pc_letters').val();
	
	input_day = $('#route-form input[name=Day]').val();
	input_month = $('#route-form input[name=Month]').val();
	input_year = $('#route-form input[name=Year]').val();
	
	input_hour = $('#route-form input[name=Hour]').val();
	input_minute = $('#route-form input[name=Minute]').val();
	
	message = '';
	if (pc_number  == '' || pc_letters == '') {
		message = message + '- Postcode niet volledig ingevuld!\n\n';
	}
	
	if (target == 'public') {
		if (input_day  == '' || input_month == '' || input_year == '') {
			message = message + '- Datum niet volledig ingevuld!\n\n';
		}
		if (input_hour  == '' || input_minute == '') {
			message = message + '- Tijd niet volledig ingevuld!\n\n';
		}
	}
	
	if (message != '') {
		alert(message);
		return false;
	}
	else {
		$('#route-form').get(0).submit();

		if (target == 'public') {
			// Analytics
			if (statistics_enabled) {
				pageTracker._trackPageview('/ajax/route_public?date=' + input_day + '-' + input_month + '-' + input_year + '&time=' + input_hour + ':' + input_minute + '&postal=' + pc_number + pc_letters);
			}
		}
	}
}

function route_init_map(from, to)
{
	if (GBrowserIsCompatible()) {
		var map = new GMap2($("#route_canvas").get(0));
		
		// Centre at the New Luxor
		map.setCenter(new GLatLng(51.907134,4.490662), 15);

		// Controls
		var mapTypeControl = new GMapTypeControl();
		var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
		var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,10));
		map.addControl(mapTypeControl, topRight);
		GEvent.addListener(map, "dblclick", function() {
			map.removeControl(mapTypeControl);
			map.addControl(new GMapTypeControl(), bottomRight);
		});
		map.addControl(new GSmallMapControl());

		// Directions
		directionsPanel = document.getElementById("route_itinerary");
		directions = new GDirections(map, directionsPanel);
		directions.load("from: "+from+" to: "+ to, { "locale" : "nl_NL" } );
	}
	else {
		// Schrijf een foutmelding naar de gebruiker
	}
}

// Routes (End)

function setup_form_action(frmid)
{
	$('form#'+frmid+' fieldset').hide();
	
	$('form#$name input[name=picture_only]').each(function(n) {
		if (this.checked) {
			$('form#$name fieldset').eq(n).show();
		}
		$(this).click(function() {
			$('form#$name fieldset').hide();
			$('form#$name fieldset').eq(n).show();
		});
	});
}

function setup_secure_links()
{
	var url = "http"+(use_https?"s":"")+"://" + website_host + website_dir + "/" + prelogin_url;
	
	$("a.require_auth").each(function(n) {
		var h = this.href;
		var tb_url = url + "&url=" + escape(h);
		
		$(this).click(function() {
			tb_url += "&TB_iframe=true&height="+tb_dimensions.height+"&width="+tb_dimensions.width;
			tb_show("Inloggen",tb_url,false);
			this.blur();
			return false;
		});
	});
	
	$("form.require_auth").each(function(n) {
		var a = this.action;
		var frm_url = url + "&url=" + escape(a);
		
		$(this).submit(function() {
			tb_url = "#?TB_iframe=true&height="+tb_dimensions.height+"&width="+tb_dimensions.width;
			tb_show("Inloggen",tb_url,false);

			// get iframe name of the thickbox we just opened
			target = $("#TB_iframeContent").attr("name");

			$(this)
				.attr("action", frm_url)
				.attr("target", target);
			
			this.submit();
			
			return false;
		});
	});
}

function get_postdata_object_from_form(formelement)
{
	var data = {}
	$(formelement).find("input,select,textarea").each(function(n) {
		type = $(this).attr("type");
		name = $(this).attr("name");
		val = $(this).val();
		
		switch(type) {
			case "checkbox":
			case "radio":
				if ($(this).get(0).checked) {
					data[name] = val;
				}			
				break;
			default:
				data[name] = val;
				break;
		}
	});
	
	return data;
}

// Ticket functionality (Start)

function detect_error(msg) {
	retval = false;
	if (msg.match('error') != null) {
		retval = true;
	}
	if (msg.match('Exception') != null) {
		retval = true;
	}
	return retval;
}

function loadranks(select)
{
	event_id = $(select).val();
	
	if (event_id > 0) {
		// Set busy
		$('div.busy').removeClass('notbusy');
		$('#event-choose-seat .map-link').addClass('busy');

		// Find production_id.
		production_id = $('input[name=production_id]', $(select).parents('form').get(0)).val();
		
		$.ajax({
			type: "GET",
			cache: false,
			url: "ajax/?cmd=ticket&act=get_ranks&production=" + production_id + "&event="+ event_id,
			success: function(msg) {
				$('#event-seat-select').html(msg);
	
				// Get max num-tickets and set them in the selectbox
				max_tickets = $('#event-seat-select input[name=maxseats]').val();
				
				select = $('#num-tickets');
				
				// Get first option (and copy it!)
				
				firstOpt = $('option', select.get(0)).get(0);
				selected = select.val();
				
				select.empty();
				opts = '<option value="'+ firstOpt.value +'">'+ firstOpt.innerHTML +'</option>';
				for (i=1;i<=max_tickets;i++) {
					if (i == selected) {
						opts += '<option value="'+ i +'" selected=\"selected\">' + i + '</option>';
					}
					else {
						opts += '<option value="'+ i +'">' + i + '</option>';
					}
				}
				select.html(opts);
	
				// Set production_id, event_id and selected number of tickets
				$('#event-seat-select input[name=production_id]').val(
					$('#event-date-select input[name=production_id]').val()
				);
				$('#event-seat-select input[name=event_id]').val(
					$('#event-date-select select[name=event]').val()
				);
				$('#event-seat-select input[name=num_tickets]').val(
					$('#num-tickets').val()
				);
				
				$('#event-seat-select input[name=TB_iframe]').val(
					$('#event-date-select input[name=tb_iframe]').val()
				);
	
				// Copied, calling the function does not work (?)
				var _radioBt = $('ul.theater-info input');
				var _theaterBlocks = $('div.theater-map > div');
				
				_radioBt.each(function(i, radio) {
					if ($(radio).is(':checked')) {
						_val = $(this).attr('id');
						_theaterBlocks.filter('.'+_val).addClass('active');
					}
	
					$(radio).click(function(){
						_val = $(this).attr('id');
						_theaterBlocks.removeClass('active');
						_theaterBlocks.filter('.'+_val).addClass('active');
					});
				});

				// Unset the busyness
				$('div.busy').addClass('notbusy');
				$('#event-choose-seat .map-link').removeClass('busy');
			}
		});
	}
	else {
		$('#event-seat-select').html("");
	}
}

function loadapplet(select)
{
	var event_id = $(select).val();
	
	// Find production_id.
	production_id = $('input[name=production_id]', $(select).parents('form').get(0)).val();
	
	// Set current selected event
	
	// Load the actual applet
	$.ajax({
		type: 'GET',
		cache: false,
		url: 'ajax/?cmd=ticket&act=get_applet_html&event='+ event_id,
		success: function(msg) {
			$('#event-seat-select').html(msg);
			
			// Analytics
			if (statistics_enabled) {
				pageTracker._trackPageview('/ajax/applet?event='+ event_id);
			}
		}
	});
	
	return false;
}

function change_ticket_count(source)
{
	$('#event-seat-select input[name=num_tickets]').val(
		$(source).val()
	);
}

function remove_ticket_sidebar(ticketid)
{
	$("div#buy p a.link").addClass('busy');
	
	$.ajax({
		type: "GET",
		cache: false,
		url: "ajax/?cmd=cart&act=remove_ticket&ticketid="+ escape(ticketid),
		success: function(msg) {
			// Here we could also do something fancy: fade the HTML block out, remove it, and replace HTML with incoming text
			$('#buy .drop-list .list').html(msg);
			
			// Update text / style of shoppingcartinfo
			
			// get_total_events
			$.ajax({
				type: "GET",
				cache: false,
				url: "ajax/?cmd=cart&act=get_total_events",
				success: function(msg) {
					// Update total events in cart
					if (msg > 1) {
						$('#buy p a.link span').html(msg + " bestellingen");
						$("div#buy p a.link").removeClass('busy');
					}
					else if (msg > 0) {
						$('#buy p a.link span').html(msg + " bestelling");
						$("div#buy p a.link").removeClass('busy');
					}
					else {
						$('div#buy').fadeOut();
						$("div#buy p a.link").removeClass('busy');
					}
				}
			});
			
			// Analytics
			if (statistics_enabled) {
				pageTracker._trackPageview('/ajax/cart?remove_ticket='+ escape(ticketid));
			}
		}
	});
	
	return false;
}

function save_upselling(element,event_id,edit)
{
	$(element).parent().find("span.price-box").html("...");

	parent_block = $(element).parents('li#event_'+event_id).eq(0);
	number_upselling = $(element).val(); //parent_block.find('select').eq(0).val();
	//event_id = parent_block.find('input[name=event_id]').eq(0).val();
	
	dataStr = 'num_upselling='+ number_upselling +'&event_id='+ event_id;
	
	if (edit) {
		dataStr += '&edit=1';
	}
	
	$.ajax({
		type: 'POST',
		url: 'ajax/?cmd=cart&act=save_upselling',
		data: dataStr,
		success: function(msg) {
			if (detect_error(msg)) {
				alert("Het arrangement kan niet geboekt worden. Neem aub contact op met de kassa via telefoonnummer: 010-4843333  (elke dag van 12: 00 uur tot 18:00 uur).");
				// Analytics
				if (statistics_enabled) {
					pageTracker._trackPageview('/ajax/cart/fail?save_upselling=l'+ event_id);
				}
			}
			else {
				parent_block.html(msg);

				// Update total price
				get_cart_total_price();
				
				// Analytics
				if (statistics_enabled) {
					pageTracker._trackPageview('/ajax/cart?save_upselling='+ event_id );
				}
			}
		}
	});
	
	return false;
}

function remove_tickets(element)
{
	core = $(element).parents('li').eq(0);
	event_id = core.attr('id').match(/event_([\d]+)/)[1];
	
	$(element).addClass('busy');
	
	// Request through ajax to remove (Site must remove related upselling too!)
	$.ajax({
		type: 'GET',
		url: 'ajax/?cmd=cart&act=cart_remove_tickets&event_id='+ event_id,
		success: function(msg) {
			// Remove the item from the cart-view
			core.fadeOut(300);
			core.remove();

			// Update cart total
			get_cart_total_price();
			
			// Analytics
			if (statistics_enabled) {
				pageTracker._trackPageview('/ajax/cart?cart_remove_tickets='+ event_id );
			}
			
			// If there is nothing left to buy, remove 'verder' button and show message
		}
	});

	return false;
}

function get_cart_total_price()
{
	// Set temporary price
	$('.total-holder .price-box').html('<b>...</b>');

	// Request total price
	$.ajax({
		type: 'GET',
		url: 'ajax/?cmd=cart&act=get_price_html',
		success: function(msg) {
			// Replace HTML
			$('.total-holder .price-box').html(msg);
		}
	});
}

function check_payment_form(form)
{
	return (check_av(form) && check_PM(form) && set_PM(form));
}

function check_av(form)
{
	avok = $('#avok').attr('checked');
	
	if (!avok) {
		alert("U moet akkoord gaan met de algemene voorwaarden om de betaling af te ronden.");
	}
	
	return avok;
}

function check_PM(form)
{
	select = $('input[name=payment-method]:checked', form);

	val = select.val();
	if (val) {
		// We don't need a PMLIST now, because a payment-method is checked. So we remove the PMLIST (issue #1872)
		$('input[name=PMLIST]', form).remove();
		return true;
	}
	else {
		alert("U moet een betaalmethode kiezen om verder te gaan.");
		return false;
	}
}

function set_PM(form)
{
	// set Payment method
	select = $('input[name=payment-method]:checked', form);

	val = select.val();
	if (val) {
		data = val.split(';');
	
		$('input[name=PM]', form).val(data[0]);
		$('input[name=BRAND]', form).val(data[1]);
	}
	
	return true;
}

function try_add_ticket(form)
{
	// Hide the notice
	$('#notice').hide();
	$('div.busy').removeClass('notbusy');

	// if form is not a form, but the 'verder' link, find the form
	if (form.tagName == 'A') {
		form = $(form).parents('form').get(0);
	}

	// Post the form, manually.
	dataStr = '';
	inputs = $('input,select', form);

	hadNumTickets = false; 
	hadRank = false;

	for (i=0;i<inputs.size();i++) {
		if (inputs.get(i).type != 'radio' || inputs.get(i).checked) {
			dataStr += inputs.get(i).name +'='+ escape(inputs.get(i).value) +'&';
		}
	}

	valRank = $('input[name=rank]:checked').val();
	hadRank = (valRank && valRank != '');
	
	hadNumTickets = false;
	$('select[name^=tickets]').each(function() {
		if ($(this).val() > 0) {
			hadNumTickets = true;
			return false;
		}
	});

	if (!hadRank || !hadNumTickets) {
		$('#notice').html('<p style="margin: 4px 0px; color: #CA003A;">U moet zowel een rang als het aantal kaarten kiezen.</p>').hide();
		$('#notice').slideDown();
		$('div.busy').addClass('notbusy');
		return false;
	}

	$.ajax({
		type: 'POST',
		cache: false,
		url: 'scripts/save.php',
		data: dataStr,
		success: function(msg) {
			//try {
				code = msg.match(/<code>([^<]+)<\/code>/)[1];
			
				redir = '';
	
				if (code > 0) {
					redir = msg.match(/<redirect>([^<]+)<\/redirect>/)[1];
				}
				else {
					if (msg.indexOf('message') > 0) {
						message = msg.match(/<message>([^<]+)<\/message>/)[1];

						tb_show('', "?act=error&message="+escape(message)+"&"+dataStr+"TB_iframe=true&height=370&width=590&modal=false", false);
						
						//$('#notice').html(message).hide();
						//$('#notice').slideDown();
					}
					if (msg.indexOf('redirect') > 0) {
						redir = msg.match(/<redirect>([^<]+)<\/redirect>/)[1];
					}					
				}
	
				if (redir != '') {
					window.location = redir;
				}
			//}
			//catch(e) {
			//	alert(msg);
			//}
		}
	});
	
	return false;
}

function submit_checkout_form()
{
	form = $("form[name=form1]").get(0);

	retval = check_payment_form(form);
	
	if (retval) {
		form.submit();
	}
	
	return false;
}

// Ticket functionality (Stop)

/**
 * Classic support functions
 */

function help_open(helpid)
{
	el = document.getElementById(helpid);
	el.style.display = "block";
}

function help_close(helpid)
{
	el = document.getElementById(helpid);
	el.style.display = "none";
}

function help_move(event,helpid)
{
	var scrollTop = 0;
	if (document.body.scrollTop > 0) {
		scrollTop = document.body.scrollTop;
	}
	else {
		scrollTop = document.documentElement.scrollTop;
	}

	if (event.pageX) {
		// !msie
		xPos = event.pageX;
		yPos = event.pageY;
	}
	else {
		// msie
		xPos = window.event.clientX;
		yPos = window.event.clientY;


		xPos += document.body.scrollLeft;
		yPos += scrollTop;
	}

	el = document.getElementById(helpid);

	var right = xPos + 20 + el.offsetWidth;
	var bottom = yPos + 20 + el.offsetHeight;
	var up = false;
	var left = false;

	if (typeof(window.innerWidth) == "number") {
		if (right > window.innerWidth && window.innerWidth > el.offsetWidth) {
			left = true;
		}
		
		if (bottom > (window.innerHeight + scrollTop) && window.innerHeight > el.offsetHeight) {
			up = true;
		}
	}
	else {
		if (right > document.documentElement.clientWidth && document.documentElement.clientWidth > el.offsetWidth) {
			left = true;
		}
		if (bottom > (document.documentElement.clientHeight + scrollTop) && document.documentElement.clientHeight > el.offsetHeight) {
			up = true;
		}
	}

	if (left) {
		el.style.left = (xPos - 20 - el.offsetWidth) + "px";
	}
	else {
		el.style.left = xPos + 20 + "px";
	}
	if (up) {
		if (typeof(window.innerHeight) == "number") {
			el.style.top = ((window.innerHeight - 10 - el.offsetHeight) + scrollTop) + "px";
		}
		else {
			el.style.top = ((document.documentElement.clientHeight - 10 - el.offsetHeight) + scrollTop) + "px";
		}
	}
	else {
		el.style.top  = yPos + 10 + "px";
	}
}

/**
 * Validate an emailaddress
 *
 * uses http://en.wikipedia.org/wiki/E-mail_address as reference
 */
function validate_email(email)
{
	var parts = email.split(/@/);

	if (parts.length != 2) {
		// not composed of local part and domain part
		return false;
	}

	var local_part = parts[0];
	var domain_part = parts[1];


	// check the local part

	var reg = /^([A-Za-z0-9!#\$%\*\/\?\|\^\{\}`~&'+\-=_.]+)$/;

	if (reg.test(local_part)) {
		if (local_part.indexOf("..") >= 0) {
			// double dot in local part
			return false;
		}
		if (local_part.indexOf(".") == 0) {
			// dot at start of local part
			return false;
		}
		if (local_part.lastIndexOf(".") == local_part.length-1) {
			// dot at end of local part
			return false;
		}
	}
	else {
		reg = /^\"([^\"]+)\"$/;

		if (!reg.test(local_part)) {
			// failed escaped local part
			return false;
		}
	}


	// check the domain part

	reg = /^[[]([0-9:.]+)[]]$/;
	
	if ((domain_part == "") || (domain_part == "[]")) {
		// invalid domain part
		return false;
	}
	else if (reg.test(domain_part)) {
		// check the ip address

		// (still missing)
	}
	else {
		// check the labels

		var labels = domain_part.split(/[.]/);
		reg = /^([A-Za-z0-9-]+)$/;

		var i;
		for(i=0; i < labels.length; i++) {
			var label = labels[i];

			if (label == "") {
				// empty label
				return false;
			}
			if (!reg.test(label)) {
				// invalid characters
				return false;
			}
			if (label.indexOf("-") == 0) {
				// hyphen at start of label
				return false;
			}
			if (label.lastIndexOf("-") == label.length-1) {
				// hyphen at end of label
				return false;
			}
		}
	}

	return true;
}

function form_remove_file(iname, no_previous_text)
{
	$("#" + iname + "_previous").html(no_previous_text);
	$("#" + iname + "_delete_id").attr("value","yes");
	$('#' + iname + '_remove').hide();

	return false;
}

function form_add_file(iname)
{
	$("#" + iname + "_delete_id").attr("value","no");

	return false;
}

function outgoing_link(href, target, name)
{
	if (target != '') {
		window.open(href, target);
		return false;
	}

	if (name == '') {
		name = escape(href);

		if (name.indexOf("http%3A//") == 0) {
			name = name.substring(9);
		}
		else if (name.indexOf("https%3A//") == 0) {
			name = name.substring(10);
		}
	}

	if (pageTracker) {
		pageTracker._trackPageview('/outgoing/' + name);
	}

	return true;
}

// search
function initSearchResults() 
{
	var _field = $('#search-field');
	var _val = _field.attr('value');
	t = 0;
	
	_field.focus(function(){
		if(this.value == _val) {
			this.value = '';
		}
	}).blur(function(){
		if(this.value == '') {
			this.value = _val;
		}
	}).autocomplete();
	
	searchfield = $('#search-field');
	searchfieldValue = searchfield.attr('value');
	
	searchfield.keyup(startSearch);
	
	$("a#link-dropdown-close").click(function() {
			$("input#search-field").val(_val);
			$("div.drop-down").slideUp(
				function () {
					$("ul#search-results").empty();
					$("ul#production-results").empty();
				}
			);
		}
	);
	
	$("a#link-dosearch").click(
		function() {
			$("div.search-form form").submit();
		}
	);
}

function startSearch () 
{
	if (t) {
		clearTimeout(t);
	}
	
	t=setTimeout("doSearch()",1000);
}

function doSearch () 
{
	if (searchfieldValue != searchfield.attr('value')) {
		$("input.btn-search").attr("src","img/loading_16x16.gif");
		
		searchfieldValue = searchfield.attr('value');
		searchfieldValue = searchfieldValue.toLowerCase();
		
		searchWords = searchfieldValue.split(' ');
		found_productions = '';
		
		//alert ("words: " + searchWords);
		
		if (searchfieldValue != '' && searchfieldValue.length > 1) {
			$("ul#search-results").empty();
			$("ul#production-results").empty();
			
			// maak een array met alle producties
			production_ids = new Array();
			$.each(productions, function() {
				if (this.production_id) {
					production_ids[production_ids.length] = this.production_id;
				}
			});
			
			total_terms = terms.length;
			
			// loop door alle zoek woorden
			$.each(searchWords, function () {
				if (this != "") {
					found_productions = new Array();
					for (i=0; i < total_terms; i++) {
						// kijk of het zoek woord in de terms array zit
						if (terms[i]==this) {
							// loop door de producties die bij deze term horen
							// en filter degene die niet meer in production_ids array zitten
							// eruit.
							$.each(term_productions[i], function(tp) {
								if ($.inArray(this, production_ids)) {
									found_productions[found_productions.length] = this;
								}
							});
						}
					}
					production_ids = found_productions;
				}
			});
			
			// loop door alle zoek woorden
			$.each(searchWords, function () {
				if (this != "") {
					for (i=0; i < total_terms; i++) {
						// kijk of we het gedeeltelijk vinden
						if (terms[i] != this && terms[i].indexOf(this)!=-1) {
							// dan voegen we ze toe aan de production_ids
							$.each(term_productions[i], function(tp) {
								production_ids[production_ids.length] = this;
							});
						}
					}
				}
			});
			
			// production_ids bevat nu alleen de gevonden production_id's
			
			added_productions = new Array();
			if ($.isArray(production_ids)) {
				$("div#production-results-title").css("display","block");
				$.each(production_ids, function() {
					num_added = added_productions.length;

					if (!in_array(this,added_productions) && num_added < 3) {
						added_productions.push(productions[this].production_id);
						prod_id = productions[this].production_id;
						title = productions[this].title;
						url = productions[this].url;
						link_title = title.replace(/'/,"\\'");
						alert_title = productions[this].alert_title;
						date_start = '';
						date_end = '';
						if (productions[this].date_start > 0 && productions[this].date_end > 0) {
							date_start = showLocalDate(productions[this].date_start);
							date_end = showLocalDate(productions[this].date_end);
						}
						sales_started = productions[this].sales_started;
						sold_out = productions[this].sold_out;
						is_disabled = 0;
						if (productions[this].disabled == "1") {
							is_disabled = 1;
						}
						if (productions[this].thumb == 1) {
							img = '<img src ="data/productions/'+prod_id+'.jpg" alt="'+title+'" style="width: 57px; height: 57px;" />';
						}
						else {
							img = '<img src ="img/image_holder_71x71.jpg" alt="'+title+'" style="width: 57px; height: 57px;" />';
						}
						buy_link = '';
						alert_html = '';
						//url = production_node + '-' + prod_id + '-'+link_title;
						date_str = '';
						
						if (is_disabled == 0) {
							if (sales_started == 1 && sold_out == 0) {
								buy_link = '<a class="kaarten" href="'+ticket_node+'-'+prod_id+'-Ticket">Kaarten</a>'
							}
							else if (sold_out == 1) {
								buy_link = '<span class="soldout">uitverkocht</span>';
							}
						}
						if (alert_title != '') {
							alert_html = '<span><span class="color">' +alert_title+ '</span></span>';
						}
						
						if (date_start && date_end) {
							date_str = date_start+' - '+date_end;
						}
						
						$("ul#production-results").append('<li onclick="window.location.assign(\'' +url+ '\')">\n'+img+'<p><strong>' + title + '</strong>'+date_str+'</p>\n <p>' +buy_link+ ''+alert_html+'</p></li>');
					}
				});
			}
			else {
				$("div#production-results-title").css("display","none");
			}
			
			// Zoeken in nieuws & content
			$.ajax({ type: "GET", url: "scripts/search.php", data: "q=" + searchfieldValue, dataType: "xml", success: function(xml){
					$(xml, "results").find("item").each(function() {
						title = $("title", this).text();
						url = $("url", this).text();
						pdate = $("pdate", this).text();
						
						if (pdate != "") {
							pdate = "<span>" + pdate + "</span>";
						}
						
						$("ul#search-results").append('<li>\n<p><strong>' + title + '</strong></p>\n <p><a class="link" href="'+ url +'">Lees meer</a> ' + pdate + ' </p></li>');
					});
				},
				complete: 
					function () {
						$("input.btn-search").attr("src","img/btn-search.gif");
						if (statistics_enabled && pageTracker) {
							pageTracker._trackPageview("/searchbox?q="+ searchfieldValue );
						}
					}
			});

			$("div.drop-down").slideDown();
			tb_init('a.thickbox, area.thickbox, input.thickbox'); // reinit thickbox for just created thickbox links
			
		}
		else if (searchfieldValue == '' || searchfieldValue.length < 2) {
			// Search results verbergen, boxje 'vernietigen'
			$("div.drop-down").slideUp();
			
			$("ul#search-results").empty();
			$("ul#production-results").empty();
			$("input.btn-search").attr("src","img/btn-search.gif");
		}
	}
}

function showLocalDate(timestamp)
{
	var mmToMonth = new Array("januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december");
	
	var dt = new Date(timestamp * 1000);
	var mm = mmToMonth[dt.getMonth()];
	return dt.getDate() + " " + mm;
}

function in_array(needle, haystack, argStrict) {
    var found = false, key, strict = !!argStrict;
 
    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }
 
    return found;
}


/* ticket form */

function ticket_form_date_onchange(el, event)
{
	if (!event) event = window.event;
	
	if ($(el).val() != "") {
		active_method_el = $("input[class^=seat-type-button]:checked");
		if (active_method_el.val()) {
			set_method(active_method_el, active_method_el.val(), $("input[name=production_id]").val(), $(el).val());
			return;
		}
		
		$("fieldset.step2-inactive").attr("class", "step2");
		$("fieldset.step1").attr("class", "step1-inactive");
		
		$("input[class^=seat-type-button]").attr("disabled", "");
		$("input[class^=seat-type-button]").attr("checked", "");
	}
	else {
		$("fieldset.step1-inactive").attr("class", "step1");
		$("fieldset.step2-inactive").attr("class", "step2");
		
		$("input[class^=seat-type-button]").attr("disabled", "disabled");
		$("input[class^=seat-type-button]").attr("checked", "");
	}
	
	// jquery throws error when removing an element that has an applet-tag as child
	// so we do it ourself
	elem = document.getElementById("event-seat-select");
	if (elem) {
		elem.parentNode.removeChild(elem);
	}
	
	// now remove the rest using jquery
	$("fieldset.stepapplet,fieldset.step3,fieldset.step3-inactive,fieldset.step4,fieldset.step4-inactive,fieldset.stepfinal").remove();
}

function ticket_form_tickets_onchange(event)
{
	if (!event) event = window.event;
	
	total_tickets = 0;
	$('select[name^=tickets]').each(function() {
		if ($(this).val() && $(this).val() > 0) {
			total_tickets += $(this).val();
		}
	});
	
	if (total_tickets > 0) {
		$("fieldset.step4").attr("class", "step4-inactive");
	}
	else {
		$("fieldset.step4-inactive").attr("class", "step4");
	}
}

function set_method(el, method,production_id,event_id)
{
	if (!$(el).hasClass("disabled")) {
		document.location = 'scripts/act.php?on=ticket_form&act=set_method&method='+method+'&production_id='+production_id+'&event_id='+event_id;
	}
	return false;
}

function initCheckUrl()
{
	$("input#in_urlname_id").keyup(startCheckUrl);
}
function startCheckUrl()
{
	if (t) {
		clearTimeout(t);
	}
	
	t=setTimeout("checkUrl()",1000);
}
function checkUrl()
{
	this_urlname = $("input#in_urlname_id").val();
	this_discountpage_id = $("input[name=discountpage_id]").val();
	if (this_urlname != '') {
		$.get("ajax/index.php", { cmd: "discountpage", act: "urlname_available", urlname: this_urlname, discountpage_id: this_discountpage_id },
			function(data){
				if (data == 'false') {
					$("label[for=in_urlname_id]").parent().parent().addClass("type_error");
					$("span#urltext_error").remove();
					$("label[for=in_urlname_id]").append(' <span id="urltext_error">Url niet beschikbaar</span>');
					$("input[type=submit]").attr("disabled","disabled");
				}
				else {
					$("span#urltext_error").remove();
					//$("label[for=in_urlname_id]").parent().parent().removeClass("type_error");
					$("input[type=submit]").removeAttr("disabled");
				}
			}
		);
	}
	else {
		$("span#urltext_error").remove();
		//$("label[for=in_urlname_id]").parent().parent().removeClass("type_error");
		$("input[type=submit]").removeAttr("disabled");
	}
}

function checkDiscountForm()
{
	if ($("input[type=submit]").attr("disabled")) {
		return false;
	}
	return true;
}