/**
 * Humanique main javascript
 *
 * this contains all the main javascripts
*/
$(document).ready(initPage);

var production_node = "";


function initPage()
{
	initBoxHeight();
	initPseudoLinks();

	// Search init
	initSearchResults();	
	
	$('ul.foyerphotos-list a').lightBox({
		imageLoading: website_url + '/img/lightbox-ico-loading.gif',
		imageBtnClose: website_url + '/img/lightbox-btn-close.gif',
		imageBtnPrev: website_url + '/img/lightbox-btn-prev.gif',
		imageBtnNext: website_url + '/img/lightbox-btn-next.gif'
	});
}

function initPseudoLinks()
{
	var lis = document.getElementsByTagName("li");
	for (var i = 0; i < lis.length; i++ )
	{
		if(lis[i].className.indexOf("pseudo-link") != -1)
		{
			lis[i].onclick = function ()
			{
				var a = this.getElementsByTagName("a");
				if(a.length > 0)
				{
					window.location.assign(a.item(0).href);
				}
				return false;
			}
			lis[i].onmouseover = function ()
			{
				var a = this.getElementsByTagName("a");
				if(a.length > 0)
				{
					window.status = a.item(0).href;
				}
				this.className += " hover";
			}
			lis[i].onmouseout = function ()
			{
				window.status = "";
				this.className = this.className.replace("hover", "");
			}
		}
	}
}
function initBoxHeight()
{
	var box = document.getElementById("box");
	var box2 = document.getElementById("content-box");
	var mainBox = document.getElementById("content");
	if(box && mainBox)
	{
		box.style.minHeight = mainBox.clientHeight - findPosY(box) - 69 + "px";
		if (typeof document.body.style.maxHeight == 'undefined')
		{
			box.style.height = mainBox.clientHeight - findPosY(box) - 69 + "px";
		}
	}
	if(box2 && mainBox)
	{
		box2.style.minHeight = mainBox.clientHeight - findPosY(box2) - 97 + "px";
		if (typeof document.body.style.maxHeight == 'undefined')
		{
			box2.style.height = mainBox.clientHeight - findPosY(box2) - 97 + "px";
		}
	}
	function findPosY(obj)
	{
		var posTop = 0;
		while (obj.offsetParent) {posTop += obj.offsetTop; obj = obj.offsetParent;}
		return posTop;
	}
}

if (window.addEventListener)
	window.addEventListener("load", initPage, false);
else if (window.attachEvent)
	window.attachEvent("onload", initPage);

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

/**
 * Sets the uploaded slide image to the swf.
 */
function set_view_preview(fname)
{
	var objSwf = window.parent.$("#editor_swf").get(0);
	objSwf.set_bg(fname);
}

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;
}


//Start package functions

function get_package_productions(element, date_year, date_month, date_day)
{
	// Request form
	$.ajax({
		type: 'GET',
		url: 'ajax/?cmd=productions&act=get_productions_html&date_year='+ date_year + '&date_month='+ date_month +'&date_day='+ date_day+'&type=arrangement',
		success: function(msg){
			$("#voorstellingen").html('<h3>Voorstelling <span>(optioneel)</span></h3>'+msg);
			
			// Analytics
			if (statistics_enabled) {
				pageTracker._trackPageview('ajax/?cmd=productions&act=get_productions_html&date_year='+ date_year + '&date_month='+ date_month +'&date_day='+ date_day+'&type=arrangement');
			}
		}
	});

}

function get_package_productions_default(element)
{
	// Request form
	$.ajax({
		type: 'GET',
		url: 'ajax/?cmd=productions&act=get_productions_default_html&type=arrangement',
		success: function(msg){
			$("#voorstellingen").html('<h3>Voorstelling <span>(optioneel)</span></h3><p>Voor een passende voorstelling op de door u gekozen datum nemen wij contact met u op.<p>Of u kunt de datum van uw evenement veranderen zodat u meteen een van onderstaande voorstellingen kunt boeken:</p>' +msg);

			// Analytics
			if (statistics_enabled) {
				pageTracker._trackPageview('ajax/?cmd=productions&act=get_productions_default_html&type=arrangement');
			}
		}
	});
}

// end Package functions


//Start foyer functions

function get_foyer_productions(element, date_year, date_month, date_day)
{

	// Request form
	$.ajax({
		type: 'GET',
		url: 'ajax/?cmd=productions&act=get_productions_html&date_year='+ date_year + '&date_month='+ date_month +'&date_day='+ date_day+'&type=evenement',
		success: function(msg){
		$("#voorstellingen").html('<h3>Evenementen koppelen aan een voorstelling <span>(optioneel)</span></h3>'+msg);
			
			// Analytics
			if (statistics_enabled) {
				pageTracker._trackPageview('ajax/?cmd=productions&act=get_productions_html&date_year='+ date_year + '&date_month='+ date_month +'&date_day='+ date_day+'&type=evenement');
			}
		}
	});

}

function get_foyer_productions_default(element)
{
	// Request form
	$.ajax({
		type: 'GET',
		url: 'ajax/?cmd=productions&act=get_productions_default_html&type=evenement',
		success: function(msg){
			$("#voorstellingen").html('<h3>Evenementen koppelen aan een voorstelling <span>(optioneel)</span></h3><p>Voor een passende voorstelling op de door u gekozen datum nemen wij contact met u op.<p>Of u kunt de datum van uw evenement veranderen zodat u meteen een van onderstaande voorstellingen kunt boeken:</p>' +msg);

			// Analytics
			if (statistics_enabled) {
				pageTracker._trackPageview('/ajax/?cmd=productions&act=get_productions_default_html&type=evenement');
			}
		}
	});
}

// end foyer functions


// tour functions

$(document).ready(function() {
	$('#gewenste-opstelling:input').change(function() {
		$('#foyer_select_update').html($('#gewenste-opstelling:input').val());
	});
});
// end tour functions


// start route functions
var map;
var gdir;
var geocoder = null;
var addressMarker;

function route_change(element)
{
	elms = $('#route-form input[name=transport-method]');
	
	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;
	}
	
	// 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_form_init()
{
	target = $('#route-form input[name=transport-method]:checked').val();
	if (target == 'public') {
		$('#route-form').attr('action', $('#route-form').attr('paaction'));
	}
	else {
		$('#route-form').attr('action', $('#route-form').attr('caraction'));
	}
	route_change();
}

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
	}
}

// end route functions

// start search function
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
	});
}

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() {
			$("form#search-form").submit();
		}
	);
}

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

function doSearch () 
{
	if (searchfieldValue != searchfield.attr('value')) {
		$("input.btn-submit").attr("src","img/loading_16x16.gif");
		
		searchfieldValue = searchfield.attr('value');
		searchfieldValue = searchfieldValue.toLowerCase();
		
		searchWords = searchfieldValue.split(' ');
		//found_productions = '';
		
		if (searchfieldValue != '' && searchfieldValue.length > 1) {
			$("ul#search-results").empty();
	
			// 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><a href="'+ url +'">' + title + '</a></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;
}
// end search function