/**
 * Common functions/objects & page scripts
 * 
 * Also Peppered config (jQuery.ppprd) is defined here 
 * 
 * prereq: jQuery (1.2.x, 1.3.x)
 * load: head
 * 
 * @author AK
 */

/* define p aanroep nodig voor share */
var P = {};

;if (typeof jQuery !== 'undefined') {
(function($){

	/**
	 * various functions and definitions
	 *
	 */
	/**
	 * Peppered config
	 */
	$.ppprd = {
		debug: {
			enabled: true,
			logAlerts: false // alerts for clients that don't have the firebug console (otherwise silent)
		}
	};
	
	
	// share
	P.share = {
		 init: function() {
			  var popWin = null;
			  $('.com-icons .facebook-icon a,  .com-icons .twitter-icon a').click(function(e) {
				   var $this = $(this);
				  
				   popWin = new PopupWindow();
				   popWin.anchor = $this;
				   popWin.width = 550;
				   popWin.height = 436;
				   if (popWin.spawn()) {
						e.preventDefault();
				   }
				  
				  
	
			  });
		 }
	};
		
	
	
	/**
	 * Debug/logging
	 * Uses Firebug (window.console) when present
	 */
	$.log = function(message){
		if (!$.ppprd.debug.enabled) {
			return false;
		}
		if (window.console && window.console.debug) {
			console.debug(message);
		}
		else {
			if ($.ppprd.debug.logAlerts) {
				alert(message);
			}
			else {
				return;
			}
		}
	};
	
	
	/**
	 * Image Replace
	 * Appends some spans to selection, to aid in IR (css)
	 * @author AK|Peppered
	 */
	$.fn.ImageReplace = function(){
		return this.each(function(){
			$(this).addClass('ir');
			$(this).append('<span class="ir-aid"><span></span></span>');
		});
	};
	
	
	/**
	 * autoSelect, jQuery plugin
	 * 
	 * Auto-submit forms when select options have changed
	 * Smoothens out (almost) behavioural differences between browsers.
	 * Inpsired on: http://themaninblue.com/writing/perspective/2004/10/19/
	 * 
	 * usage: $selection.autoSelect({options})
	 * 
	 * @author AK | Peppered
	 * @version 1.0.1
	 */
	(function(a){a.fn.autoSelect=function(){return this.each(function(){var b=a(this);b.validKeyChange=true;b.initValue=a(this).val();b.change(function(){if(b.validKeyChange&&(this.value!=b.initValue)){b.initValue=this.value;this.form.submit()}});b.keydown(function(c){if((c.keyCode==13||c.keyCode==9)&&this.value!=b.initValue){b.validKeyChange=true;b.change()}else{if(c.keyCode==27||((c.keyCode==13||c.keyCode==9)&&this.value==b.initValue)){this.value=b.initValue}else{b.validKeyChange=false}}})})}})(jQuery);


	/**
	 * PopupWindow object
	 * spawns/handles ye classic popup windows
	 *
	 * @author AK
	 *
	 * requires: jQuery 1.2.x, 1.3.x
	 */
	window.PopupWindow = function(){
		this.width = 500;
		this.height = 500;
		this.$container = $(window);
		this.offsetLeft = 0;
		this.offsetTop = 0;
		this.menubar = true;
		this.location = false;
		this.resizable = true;
		this.scrollbars = true;
		this.status = true;
		this.name = 'popupWindow';
		this.url = '';
	};
	window.PopupWindow.prototype.prepare = function(){
		var oAnchor = this.anchor;
		if (typeof oAnchor.data('popWinObject') == 'object') {
			var oPopWin = oAnchor.data('popWinObject');
			if (!oPopWin.closed) {
				oPopWin.close();
			}
		}
		var sHref = oAnchor.attr('href');
		if (sHref.indexOf('?') > -1) {
			sHref += '&';
		} else {
			sHref += '?';
		}
		sHref += 'popup=true';
		this.url = sHref;
	};
	window.PopupWindow.prototype.spawn = function(){
		this.prepare();
		var x = this.$container.width() / 2 - (this.width / 2);
		var y = this.$container.height() / 2 - (this.height / 2);
		
		if (x < 0) { x = 0; }
		if (y < 0) { y = 0; }
		
		if (typeof window.screenX !== 'undefined') {
			x += window.screenX;
			y += window.screenY;
		}
		else if (typeof window.screenLeft !== 'undefined') {
			x += window.screenLeft;
			y += window.screenTop / 2;
		}
		
		this.offsetLeft = x;
		this.offsetTop = y;
		
		var oPopWin = window.open(this.url, this.name, 'width=' + this.width + ',height=' + this.height + ',left=' + this.offsetLeft + ',top=' + this.offsetTop);
		
		if (typeof oPopWin != 'undefined') {
			this.anchor.data('popWinObject', oPopWin);
			return true;
		}
		return false;
	};
	
	
	
	
	/**
	 *** Various page onDOMReady scripts follow ***
	 */
	$(function(){
		// body js/jquery is enabled class
		$('body').removeClass('nojs').addClass('jsfx');
		
		// refresh queue (prevent timeout)
		if (typeof Xajax != 'undefined') 
			window.setInterval("xajax_UpdateActivity()", 270000);
		
		/**
		 * cross browser stuff
		 */
		// correct boxmodel input[type="text"] FF<3
		if ($.browser.mozilla && parseFloat($.browser.version) < 1.9) {
			$("body").addClass("FF2");
		}
		// ie6 workarounds for unsupported css
		if ($.browser.msie && parseFloat($.browser.version) < 7) {
			$("body").addClass("IE6");
			$("acronym[title]").addClass('hasTitle'); /* note: ie6 doesn't support abbr element */
		}
		
		
		/**
		 * Anchors
		 *
		 */
		/** 
		 * hover images for certain anchor types
		 */
		$('a.more').addClass('more-fx').wrapInner('<span class="hoverHelper" />');
		$('a.next').addClass('next-fx').wrapInner('<span class="hoverHelper" />');
		$('a.prev').addClass('prev-fx').wrapInner('<span class="hoverHelper" />');
		
		/**
		 * external (rel="external") and
		 * popup (rel="popup") handling
		 */
		var oPopWin = null;
		$("a[rel='external']").click(function(){
			window.open(this.href);
			return false
		});
		$("a[rel='popup']").click(function(e){
			if (typeof PopupWindow !== 'undefined') {
				popWin = new PopupWindow();
				popWin.anchor = $(this);
				popWin.width = 500;
				popWin.height = 500;
				if (popWin.spawn()) {
					e.preventDefault();
				}
			}
		});
		
		
		/**
		 * Drop-down menu (Superfish)
		 */
		if ($.fn.superfish) {
			$("#menu").superfish({
				speed: 0
			});
		}
		
		// auto-submit genre/maand select
		(function(){
			if ($.fn.autoSelect) {
				var $form = $('#genreMaandForm');
				var $enabled = $form.find('select').autoSelect();
				if ($enabled.length) {
					$form.addClass('autoSelect');
				}
			}
		})();
		
		
		(function(){
			//run the currently selected effect
			function runEffect($element){
				//get effect type from 
				var selectedEffect = "fold";
				
				//most effect types need no options passed by default
				var options = {};
				//check if it's scale, transfer, or size - they need options explicitly set
				if(selectedEffect == 'scale'){  options = {percent: 0}; }
				else if(selectedEffect == 'size'){ options = { to: {width: 1200,height: 60} }; }
				
				//run the effect
				$element.find('.effect').toggle(selectedEffect,options,500);			
				
			};
			
			//set effect from select menu value
			$(".iconSluit").click(function() {
				//var this_id = $(this).parent().parent().attr('id');
				var $element = $(this).closest('div.banner');
				runEffect($element);
				return false;
			});
			
		})();
		
		// To detect native support for the HTML5 placeholder attribute
		var fakeInput = document.createElement("input"),
			placeHolderSupport = ("placeholder" in fakeInput),
			clearValue = function () {
				if (searchField.val() === originalText) {
					searchField.val("");
				}
			};
	
		// Applies placeholder attribute behavior in web browsers that don't support it
		if (!placeHolderSupport) {
			var searchField = $("#search-text"),
				originalText = searchField.attr("placeholder");
	
			searchField.val(originalText);
			searchField.addClass("placeholder");
	
			searchField.bind("focus", function () {
				searchField.removeClass("placeholder");
				clearValue();
			});
	
			searchField.bind("blur", function () {
				if (searchField.val().length === 0) {
					searchField.val(originalText);
					searchField.addClass("placeholder");
				}
			});
	
			// Empties the placeholder text at form submit if it hasn't changed
			searchField.parents("form").bind("submit", function () {
				clearValue();
			});
	
			// Clear at window reload to avoid it stored in autocomplete
			$(window).bind("unload", function () {
				clearValue();
			});
		}

		
		// new menu (check whether jquery cookie function exists):
		if ($.cookie) {
			//handig om 'm cookie effies leeg te maken
			//	$.cookie('bgMenu', '', { expires: -1 });
			
			//read menu cookie, in which are all id's of hidden groups
			var strMenuCookie = $.cookie('bgMenu');
			if (strMenuCookie) {
				arrNewHiddenSubItemIds = strMenuCookie.split(",");
				for (i=0; i < arrNewHiddenSubItemIds.length; i++) {
					// hide group
					//console.log('.' + arrNewHiddenSubItemIds[i] + ' .head' );
					elm = $('#' + arrNewHiddenSubItemIds[i] + ' .head' );
					if (!elm.hasClass("active")) {
						elm.next().toggle();
						elm.find('a span' ).toggleClass('btnToggle');
						elm.toggleClass('subItemClosed'); 
					}
				}
			}
		
			
			//toggle menu left column
			function UpdateMenuCookie() {
				// write cookie, array is not updated, but is newly build every time
				arrNewHiddenSubItemIds = new Array();
				$(".subItem").each( function () {					
					if ($(this).find('.head a span').hasClass('btnToggle'))	{
						//console.log($(this).attr("id"));
						subItemId = $(this).attr("id");				
						arrNewHiddenSubItemIds[arrNewHiddenSubItemIds.length] = subItemId;
					}
				});
				$.cookie('bgMenu', arrNewHiddenSubItemIds.join(), { path: '/', expires: 10 });
			}
			
			$('.inklapmenu .head').click(function() {
				$(this).next().toggle('slow');
				
				// change icon
				$(this).find('a span' ).toggleClass("btnToggle");			
				$(this).toggleClass("subItemClosed");
				
				// store new state in cookie
				// delay updatecookie function, to give toggle(slow) time to finish 
				setTimeout(UpdateMenuCookie, 500);
				return false;			
			});
			
			
			/**
			* Voorstellingen list items
			* 
			*/
			$('.highlight li').hover(function(){
			   $(this).addClass('hover');
			   $(this).find('a.leesMeer').addClass('hover');
			},function(){
			   $(this).removeClass('hover');
			   $(this).find('a.leesMeer').removeClass('hover');
			});
		   
			$('.highlight li').click(function(){
			sHref = $(this).find('a.leesMeer').attr('href');
			window.location.href = sHref;
			});			
		}
		
		// FOTOBOEK PDIALOG		
		$('.btnPdialog').click(function() {
			 $.get("/fotoboek.php?media_item_id="+$(this).attr('id'), 
		    		function(data) {
					$.pDialog({
						debug: false,
						id: 'dialog-modal',
						type: 'message',
						title: 'Concert toegevoegd',
						content: data,
						modal: true,
						keepInDom: false,
						resizable: true,
						draggable: false,
						bringInFocusOnOutsideclick: true,
						width: 523,
						height: 553,
						buttons: {}
					});
				});			 
			return false;
		});		
		
	});
	
	
})(jQuery);
};
