/*
 *     SCRIPT:	Function Definitions
 *    VERSION:	10.24.2009
 *    UPDATED:	01.06.2010


   RUNTIME GLOBALS (DO NOT MODIFY)
 * -------------------------------- */
var working = false;
var featured_loop = null;
var menu_timeoutID = null;
pngfix_elements = "div, a, li, img, input";


/* ENABLE JS FEATURES
 * Enables the user interface elements
 * that provide javascript functionality
 * -------------------------------------- */
function enable_js_features() {
	var selector = "";
	selector += "#content #featured #featured-body #featured-nav-ui" + ", ";
	selector += "#content #featured #featured-body a.nav-left," + ", ";
	selector += "#content #featured #featured-body a.nav-right," + ", ";
	//selector += "" + ", ";
	
	// Trim the last comma and space
	var strLen = selector.length;
	selector = selector.slice(0,strLen-2);

	// Show the elements
	jQuery(selector).css('display', 'block');
}

/* CLICK EVENTS
 * Here JS click() events are defined
 * ------------------------------------ */
function click_events() {
	
	$('#back-to-top').click(function(){
		if ( is_IE6() || is_IE7() ) {
			$('html').animate({scrollTop:0}, 700);
			return false;
		}
		
		if ( !$.browser.opera ) {
			$('html,body').animate({scrollTop:0}, {
				duration: 800,
				easing: 'easeInOutExpo'
			});
		} else {
			$('html').animate({scrollTop:0}, {
				duration: 800,
				easing: 'easeInOutExpo'
			});
		}
		return false;
	});

	$('#featured-body a.nav-left, #featured-body a.nav-right').click(next_featured);

	$('a.close-btn').click(function() {
		
		if ( ! is_IE6() ) {
			$(this).parent().fadeOut(forms_notification_delay);
			return false;
		} 
		
	});

}

/* STYLE ADJUSTMENTS
 * Correct minor rendering inconsistencies
 * across browsers.
 * --------------------------------------- */
function style_adjustments() {
	
	// For some reason, Gecko based browsers add a 10px right margin to .sub-navigation
	if ($.browser.mozilla) {
		$('#content #top-section ul.sub-navigation').css('right', '-10px');
		$('#content #main #left .post .post-contents ul.tags li a').css('padding-right', '0');
	}
	
}


/* HOVER EVENTS
 * Here JS hover() events are defined
 * ------------------------------------ */
function hover_events() {

	if ( stop_featured_cycle_on_hover == true ) {
		$('#featured-content p, #featured-content h1, #featured-content a.button, #featured-body .frame img').hover(function() {
			clearTimeout(featured_loop);
		}, function() {
			if (enable_featured_cycle == true) { featured_cycle(); }
		});
	}
	
	$('#searchform').hover(function() {
		
		$('#search-focus-block').css('display', 'none');
		
	});
	
}

/* IN_ARRAY
 * Implementation of PHP's in_array()
 * --------------------------------------- */
function in_array(needle, haystack) {
	for ( var i=0; i < haystack.length; i++) {
		if ( needle == haystack[i]) { return true; }
	}
	return false;
}

/* FORMS INITIALIZATION
 * Initializes forms, AJAX & Validation
 * --------------------------------------- */
// Initializes forms for Validation
function init_forms() {
	submitted_form = [];

	// Add form submission slots
	$('form.validate').each(function(i) {
		var id = $(this).attr('id');
		submitted_form[id] = false;
		if (id == '') { alert('CHECK: All Forms Must have an ID assigned'); }
	});

	$('form.validate input[type=submit]').click(function() {
		var parent = $(this).parents('form');
		var no_ajax = parent.hasClass('no-ajax');
		var valid = false;
		parent.validate(function() {
			if (submitted_form[parent.attr('id')]) {alert('Uw bericht is al verzonden, wij nemen zo spoedig mogelijk met u contact op.'); return false; }
			valid = true;
			if ( ! no_ajax ) {
				jQuery.ajax({
					type: "POST",
					url: parent.attr('action'),
					data: form_data,
					success: function(response){
						if (response=='success') {
							parent.find('.post-msg').slideDown(400);
							submitted_form[parent.attr('id')] = true;
						}
					}
				});
			}
		});
		if ( valid && no_ajax ) { return true }
		return false;
	});
}

/* VALIDATION FRAMEWORK (EXTENSION)
 * AJAX & Validation
 * --------------------------------------- */
// EXTENSION: Validation Framework
$.fn.validate = function(callback) {
	var regexp_types = [ 'name', 'email', 'reden', 'url' ]
	var regexps = {
		'name' 	: /[a-zA-Z ]{2,30}/i,
		'email' : /[\w-+]+(?:\.[\w-+]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}/i,
		'url': /http:\/\/[A-Za-z0-9\.-]?[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/
	}

	// Add missing regexps and types
	$(this).find('input.required, textarea.required').each(function() {
		var n = $(this).attr('name');
		if ( !in_array(n, regexp_types) && n != 'submit' ) { regexp_types.push(n); }
		if ( regexps[n] == null ) { regexps[n] = /.+/; }
	});

	var valid = true;
	form_data = "ajax=true&";
	for ( var i=0; i < regexp_types.length; i++ ) {
		var name = regexp_types[i];
		var rx = regexps[name];

		var input = $(this).find('input[name=' + name + ']');
		var textarea = $(this).find('textarea[name=' + name + ']');

		if ( input.length == 1 ) {
			if ( input.val().match(rx) == input.val() ) {
				input.removeClass('invalid');
				form_data += input.attr('name') + '=' + input.val() + '&';
			} else {
				// if not required and empty, let go
				if ( ! input.hasClass('required') && $.trim(input.val()) == '' ) {}
				else { valid = false; input.addClass('invalid'); }
			}
		}

		if ( textarea.length == 1 ) {
			if ( textarea.val().match(rx) == textarea.val() || $.trim(textarea.val()) != '' ) {
				textarea.removeClass('invalid');
				form_data += textarea.attr('name') + '=' + textarea.val().replace('&','&amp;') + '&';
			} else {
				// if not required and empty, let go
				if ( ! textarea.hasClass('required') && $.trim(textarea.val()) == '' ) {}
				else { valid = false; textarea.addClass('invalid'); }
			}
		}
	}

	if (valid) {
		form_data = form_data.substring(0, form_data.length-1);
		callback();
	}
}

/* LIGHTBOX INITIALIZATION
 * Prettyphoto Lightbox configuration. 
 * --------------------------------------- */
function init_lightbox() {
	
	if ( enable_lightbox == true ) {

		$("a[rel^='lightbox']").prettyPhoto({
			animationSpeed: lightbox_animation_speed, /* fast/slow/normal */
			padding: lightbox_padding, /* padding for each side of the picture */
			opacity: lightbox_opacity, /* Value betwee 0 and 1 */
			showTitle: lightbox_showtitle, /* true/false */
			allowresize: lightbox_allowresize, /* true/false */
			counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
			theme: lightbox_theme, /* light_rounded / dark_rounded / light_square / dark_square */
			hideflash: lightbox_hideflash, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
			modal: lightbox_modal_state, /* If set to true, only the close button will close the window */
			changepicturecallback: function(){}, /* Called everytime an item is shown/changed */
			callback: function(){} /* Called when prettyPhoto is closed */
		});

	}
	
}

/* MENU INITIALIZATION
 * 
 * Initializes the menu and makes sure
 * it is cross platform and cross browser.
 * 
 * On IE6, the dropdown menu will only
 * work with JS enabled, since IE lacks
 * support for CSS's > selector, which is
 * used to unhide the unordered list.
 * --------------------------------------- */
function init_menu() {
	
	if ( is_IE6() ) {
		
		// Apply Blue Theme Fixes
		var bg = $('#content').css('background-image');
		if ( bg.indexOf('/blue/') != -1 ) {
				$('#header .container ul#navigation li ul').css({
					'background-image' : 'none',
					'background-color' : '#E1E1E1'
				});	
				
				$('#header .container ul#navigation li ul li a').css({'border-color' : 'E1E1E1'	}).hover(function() {
					$(this).css('border-color', '#cacaca');
				}, function() {
					$(this).css('border-color', '#E1E1E1');
				});
		}
		
		
		$('#header .container ul#navigation li').hover(function() {

			if ( $(this).children().length > 1 ) { 

				var _this = $(this);
				
				clearTimeout(menu_timeoutID);
				menu_timeoutID = setTimeout(function() {

					_this.find('ul:first').css({ visibility: "visible", display: "none" }).slideDown(menu_dropdown_duration, menu_ease_equation);

				},menu_show_delay);

			}			
			
		}, function() {

			clearTimeout(menu_timeoutID);
			$(this).find('ul:first').css({visibility: "hidden"});
			
		});
		
	} else {
		
		if ( is_IE7() ) {
			$('#header .container ul#navigation li ul').css('margin-left', '0');
		}
		
		$('#header .container ul#navigation li').hover(function() {
			
			$(this).find('ul:first').css({'visibility': 'hidden', 'display': 'none'});
			
			var _this = $(this);
		
			clearTimeout(menu_timeoutID);
			menu_timeoutID = setTimeout(function() {
				$('#search-focus-block').css('display', 'block');
				_this.find('ul:first').css({ visibility: "visible", display: "none" }).slideDown(menu_dropdown_duration, menu_ease_equation);
			},menu_show_delay);
				
		}, function() {
			
			clearTimeout(menu_timeoutID);
			$(this).find('ul:first').css({visibility: "hidden"});
				
		});
	}
}

/* FEATURED HOME INITIALIZATION
 * Configures, Retrieves and Creates elements
 * needed for this section to work. The cache
 * class is used here. 
 * --------------------------------------- */
function init_featured_home() {

	var featured_cache = $('#featured-items');
	var featured_nav = $('#featured-nav-ui');
	var items = featured_cache.children().length;

	for ( var i=1; i < items; i++ ) {
		featured_nav.append('<li><a rel="' + (i+1) + '" href="#"></a></li>');
	}

	featured_nav_click();
	
	if (enable_featured_cycle == true) { featured_cycle(); }
	
}

/* FEATURED CYCLE
 * Cycles the featured items an interval
 * defined by featured_cycle_interval. 
 * --------------------------------------- */
function featured_cycle() {

	if ( featured_cycle_interval < 60 ) { featured_cycle_interval *= 1000 }

	featured_loop = setInterval(function() {
		
		next_featured();
		
	},featured_cycle_interval);

}

/* NEXT FEATURED
 * Smart & Multipurpose function that 
 * changes the featured items. Also serves
 * as the click() event handler for the
 * featured content switchers. 
 * --------------------------------------- */
function next_featured() {
	var increment = 1;
	if ( $(this).hasClass('nav-left') ) { increment = -1; clearInterval(featured_loop); featured_loop = null; }
	if ( $(this).hasClass('nav-right') ) { increment = 1; clearInterval(featured_loop); featured_loop = null; }
	
	var items = $('#featured-items').children().length;
	var current = $('#featured-nav-ui li.active a').attr('rel');
	var next = cycle(parseInt(items), parseInt(current), increment );

	var selector = '#featured-nav-ui li a[rel=' + next + ']';
	$(selector).parent().click();

	return false;

}

/* PRECACHE
 * Preloads the slideshow images
 * --------------------------------------- */
function precache() {
	var images = $('ul#featured-items li img');
	images.each(function(i) {
		var src = $(this).attr('src');
		$.cacheImage(src, {
			load: function() { 
				cached_images[src] = $(this); 
				if (i+1 == images.length) { init_featured_home() }
			}
		});
	});
}

/* FEATURED NAV ELEMENTS CLICK
 * Handles the switching when the featured
 * items navigation (bottom right) elements
 * are clicked.
 * --------------------------------------- */
function featured_nav_click() {
	$('#featured-nav-ui li').click(function() {
		if ( $(this).hasClass('active') || working == true ) { return false; }
		
		working = true;

		var featured_cache = $('#featured-items');
		
		var num = $(this).children().eq(0).attr('rel') - 1;
		var block = featured_cache.children().eq(num);
		var h1 = block.children().eq(0).text();
		var img = block.children().eq(1).attr('src');
		var p = block.children().eq(2).text();
		var href = block.children().eq(3).attr('href');
		
		var duration = 900;
		
		var text_fade_duration = duration*0.4

		$('#featured-nav-ui li').removeClass('active');
		$(this).addClass('active');

		// Get the next image from cache
		var new_backImage = cached_images[img]; new_backImage.addClass('back');

		// Remove old image
		$('#featured-body img.back').remove();
		new_backImage.appendTo('#featured-body').attr('style','position:absolute; top: 30px; left: 56px;');

		// Get Elements
		backImage = $('#featured-body img.back');
		frontImage= $('#featured-body img.front');
		
		// Fade Out front image
		frontImage.animate({'opacity':'0'},duration);

		setTimeout(function() {
			// Swap Classes, bring FrontImage to back, and set opacity back to 1 again.
			backImage.removeClass('back'); frontImage.removeClass('front');
			backImage.addClass('front'); frontImage.addClass('back').css('opacity','1');

			working = false;
			if ( featured_loop == null ) { 
				if (enable_featured_cycle == true) { featured_cycle(); }
			}
		},duration+30);

		if ( !$.browser.msie || disable_text_fade_on_ie == false ) {
			$('#featured-content h1, #featured-content p').stop().animate({
				'opacity' : '0'
			},text_fade_duration);
		}

		setTimeout(function() {
			$('#featured-content h1').text(h1);
			$('#featured-content p').text(p);
			$('#featured-content a.button').attr('href', href);
			
			if ( !$.browser.msie || disable_text_fade_on_ie == false ) {
				$('#featured-content h1, #featured-content p').animate({
					'opacity' : '1'
				},text_fade_duration);
			}
	
		},text_fade_duration+30);

		return false;
	});
}

/* CYCLE
 * Cycling Algorithm
 * --------------------------------------- */
function cycle(range, current, increment) {
	var item = current + increment;
	if ( item == 0 ) { item = range; }
	if ( item > range ) { item = 1;	}
	return item;
}

/* TARGET _BLANK SUPPORT IN JS
 * The XHTML 1.0 Strict doctype, doesn't
 * support the target="_blank" attribute,
 * so it's added on JS in order to validate.
 * --------------------------------------- */
function setup_external_links() {
	$('a[rel=_blank]').attr('target', '_blank');
}

/* IE6 DETECTION
 * Detects Internet Explorer 6
 * --------------------------------------- */
function is_IE6() {
	return (navigator.appVersion.indexOf("MSIE 6.")==-1) ? false : true;
}

/* IE7 DETECTION
 * Detects Internet Explorer 7
 * --------------------------------------- */
function is_IE7() {
	return (navigator.appVersion.indexOf("MSIE 7.")==-1) ? false : true;
}

/* IE6/7 DETECTION
 * Detects Internet Explorer 6 and/or 7
 * --------------------------------------- */
function is_IE67() {
	if ( is_IE6() || is_IE7() ) {
		return true;
	} else {
		return false;
	}
}

/* JQUERY EXTENSIONS ----------------------------------------------------*/

/*
 * cacheImage: a jQuery plugin
 *
 * cacheImage is a simple jQuery plugin for pre-caching images.  The
 * plugin can be used to eliminate flashes of unstyled content (FOUC) and
 * improve perceived page load time.  Callbacks for load, error and abort
 * events are provided.
 *
 * For usage and examples, visit:
 * http://github.com/alexrabarts/jquery-cacheimage
 *
 * Licensed under the MIT:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright (c) 2008 Stateless Systems (http://statelesssystems.com)
 *
 * @author   Alex Rabarts (alexrabarts -at- gmail -dawt- com)
 * @requires jQuery v1.2 or later
 * @version  0.2.1
 */

(function ($) {
  $.extend($, {
    cacheImage: function (src, options) {
      if (typeof src === 'object') {
        $.each(src, function () {
          $.cacheImage(String(this), options);
        });

        return;
      }

      var image = new Image();

      options = options || {};

      $.each(['load', 'error', 'abort'], function () { // Callbacks
        var e = String(this);
        if (typeof options[e] === 'function') { $(image).bind(e, options[e]); }

        if (typeof options.complete === 'function') {
          $(image).bind(e, options.complete);
        }
      });

      image.src = src;

      return image;
    }
  });

  $.extend($.fn, {
    cacheImage: function (options) {
      return this.each(function () {
        $.cacheImage(this.src, options);
      });
    }
  });
})(jQuery);

/* EOF */

