/**
 * Peppered js extensions 
 * 
 * Image Replace, PopupWindow, Calendar, slideMenu
 * 
 * @author AK
 * 
 * @version 1.0.0
 * 
 * Suitable for minifying
 * Use compressed version for production!
 * 
 */

$.ppprd = {
	debug: {
		enabled: true,
		logAlerts: false	// alerts for clients that don't have the firebug console (otherwise silent)
	},
	sifr: {
		enabled: true,
		version: 2
	},
	niceSelects: {
		enabled: false
	}
};

/**
 * debug/logging
 */
jQuery.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;
		}
	}
};

Array.prototype.in_array = function(needle, strict) {
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    var found = false, key, strict = !!strict; 
    for (key in this) {
        if ((strict && this[key] === needle) || (!strict && this[key] == needle)) {
            found = true;
            break;
        }
    } 
    return found;
};

/**
 * override jQuery's fade function for better support IE
 * Also set explicit bgcolor on elements (IE6)
 * http://malsup.com/jquery/fadetest.html * 
 */

jQuery.fn.fadeIn = function(speed, callback) { 
    return this.animate({opacity: 'show'}, speed, function() { 
        if (jQuery.browser.msie) {
			this.style.removeAttribute('filter');
		}
        if (jQuery.isFunction(callback)) {
			callback();
		}
    }); 
}; 
 
jQuery.fn.fadeOut = function(speed, callback) { 
    return this.animate({opacity: 'hide'}, speed, function() { 
        if (jQuery.browser.msie) {
			this.style.removeAttribute('filter');
		}
        if (jQuery.isFunction(callback)) {
			callback();
		}
    }); 
}; 
 
jQuery.fn.fadeTo = function(speed,to,callback) { 
    return this.animate({opacity: to}, speed, function() { 
        if (to == 1 && jQuery.browser.msie) {
			this.style.removeAttribute('filter');
		}
        if (jQuery.isFunction(callback)) {
			callback();
		}
    }); 
}; 



/**
 * Image Replace
 * Appends some spans to selection, so with css nice IR can happen)
 * @author AK|Peppered
 */

jQuery.fn.ImageReplace = function() {	
	this.each(function() {
		$(this).addClass('ir');		
		$(this).append('<span class="ir-aid"><span></span></span>');	
	});
};


/**
 * PopupWindow object
 * spwans/handles popup windows
 * 
 * @author AK
 * 
 * dependancies: jQuery 1.2.6
 */

function PopupWindow() {
	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 = ''; 
}
PopupWindow.prototype.prepare = function () {
	oAnchor = this.anchor;
	if (typeof oAnchor.data('popWinObject') == 'object') {
		oPopWin = oAnchor.data('popWinObject');
		if (!oPopWin.closed) {
			oPopWin.close();
		}
	}
	sHref = oAnchor.attr('href');		
	if (sHref.indexOf('?')) {
		sHref += '&';
	}
	else {
		sHref += '?';
	}
	sHref += 'popup=true';
	this.url = sHref;
};
PopupWindow.prototype.spawn = function() {
	this.prepare();
	var x = this.container.width() / 2 - (this.width/2);
    var y = this.container.height() / 2 - (this.hegiht/2);
	if (x < 0) { x = 0;	}
	if (y < 0) { y = 0; }
	this.offsetLeft = x;
	this.offsetTop = y;
	
	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;
};


/**
 * Calendar object
 * @author AK
 * 
 * remember:
 *   months & days of week are zero-indexed;
 *   1st day of week (0) is sunday
 *   
 *  requires: jQuery 1.2.6, hoverIntent plugin
 */

function Calendar(){
	this.monthLabels = ['Januari', 'Februari', 'Maart', 'April', 'Mei', 'Juni', 'Juli', 'Augusust', 'September', 'Oktober', 'November', 'December'];
	this.currentDate = new Date();
	this.firstDayOfWeek = 1;
	this.shows = {};
	this.activeMonthDay = 0;
	this.caption = '';
	this.$calendar = {};		// the jQuery object
	this.$form = {};			// associated form
	this.monthsType = 'browse';	// 'writeOut' or 'browse'
	this.initiated = false;
	this.tables = [];
}

/**
 * Calendar.setActiveDay
 * @param {Object} date
 */
Calendar.prototype.setActiveDay = function(date){
	var dayDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
	if (this.monthsType == 'writeOut') {
		for (var i=0; i<this.tables.length; i++) {
			this.tables[i].find('td').removeClass('active');
		}
		this.shows[dayDate.getTime()/1000].$td.addClass('active');
	}
};

/**
 * Calendar.init
 * properties that should be set: $form
 * 
 */
Calendar.prototype.init = function(){
	
	this.$form.wrap('<div class="calendar"/>');
	
	var lastSelectedIndex;
	var $select = this.$form.find('select[name="voorstelling"]');
	this.$datesSelect = $select;
	var submit = this.$form.find('input.submit');
	var orderbutton = this.$form.find('input.orderbutton');
	submit.attr('disabled', 'disabled').removeClass('submit-enabled').addClass('submit-disabled');
	orderbutton.attr('disabled', 'disabled').removeClass('submit-enabled').addClass('submit-disabled');
	var cal = this;
	var shows = {};
	cal.shows = shows;	
	
	var $option = $('<option class="dummy">kies een dag</option>').prependTo($select);
	$select.children('.dummy' ).attr('selected', 'selected'); // execute seperate/this way 4 IE
	
	// onchange showsSelect
	$select.change(function(){
		$("#stoelkeuze"+$(this).val().split('|')[3]).attr("href", "/winkelmandje/?action=add&id="+$(this).val().split('|')[0]+"&a_id="+$(this).val().split('|')[2]+"&e_id="+$(this).val().split('|')[3])
		orderbutton.data('url', "/winkelmandje/?action=add&id="+$(this).val().split('|')[0]+"&a_id="+$(this).val().split('|')[2]+"&e_id="+$(this).val().split('|')[3]);
		orderbutton.data('event_id', $(this).val().split('|')[3]);
		var selectedOption = $(this).children('option:selected');
		if ($(this).val() !== '' && !selectedOption.hasClass('disabled') && !selectedOption.hasClass('dummy')) {
			submit.removeAttr('disabled').removeClass('submit-disabled').addClass('submit-enabled');
			orderbutton.removeAttr('disabled').removeClass('submit-disabled').addClass('submit-enabled');
			var timeString = $(this).val().split('|')[1]; // IETF
			var date = new Date(Date.parse(timeString));
			
			if (cal.monthsType == 'writeOut') {
				cal.setActiveDay(date);
			}
			else {
				cal.activeMonthDay =  date.getDate();
				cal.activeTime =  date.getTime()/1000;
				cal.drawMonth(date.getFullYear(), date.getMonth());
			}
			
			lastSelectedIndex = selectedOption[0].index;
		}
		else {
			$(this)[0].selectedIndex = lastSelectedIndex;
		}
	});
	
	
	// process options, fill shows object	
	$select.children().not('.dummy').each(function(){
		var timeString = $(this).val().split('|')[1]; // IETF	
		var date = new Date(Date.parse(timeString));
		var time = date.getTime()/1000;
		var dayDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
		var dayTime = dayDate.getTime()/1000;

		// new object for every unique day
		if (!(dayTime in shows)) {
			shows[dayTime] = {};
			shows[dayTime].times = {};
		}
		
		// time(s) in a day
		shows[dayTime].times[time] = {
			time: time,
			disabled: $(this).attr('disabled'),
			selectIndex: this.index
		};
				
	});		
	
	var months = [];
	cal.months = months;
	var yearNMonth;
	
	// loop days, check for those with all disabled shows and create array containing months
	for (var dayTime in shows) {
		if (typeof dayTime == 'string') {
			var day = shows[dayTime].times;
			var disabledCount = 0;
			var itemCount = 0;
			
			var date = new Date(dayTime*1000);
			yearNMonth = date.getFullYear() + '-' + date.getMonth();
			if (!months.in_array(yearNMonth)) {
				months.push(yearNMonth);
			}
			
			for (var showTime in day) {		
				if (typeof day[showTime] == 'object') {
					itemCount++;
					var show = day[showTime];
					if (show.disabled) {
						disabledCount++;
					}
				}
			}
			if (itemCount == disabledCount) {
				shows[dayTime].disabled = true;			
			}
		}
	}
	
	var year, month;
	
	if (this.monthsType == 'writeOut') {
		// write out all months
		for (var i=0; i<months.length; i++) {
			yearNMonth = months[i].split('-');
			year = yearNMonth[0];
			month = yearNMonth[1];		
			cal.drawMonth(year, month);
		}
	}
	else {
		// show 1 month, browsable
		if (months.length) {
			yearNMonth = months[0].split('-');
			year = yearNMonth[0];
			month = yearNMonth[1];
			cal.drawMonth(year, month);
		}
	}
	this.initiated = true;
};

Calendar.prototype.setElements = function(){
	this.$caption = this.$calendar.find('caption');
	this.$tds = this.$calendar.find('tbody td');
};

Calendar.prototype.getDaysInMonth = function () {
	var dd = new Date(this.year, this.month, 32);
	return 32 - dd.getDate();
};

Calendar.prototype.setMonth = function (year, month){
	this.year  = (isNaN(year) || year === null) ? this.currentDate.getFullYear() : year;
	this.month = (isNaN(month) || month === null) ? this.currentDate.getMonth() : month;
};

Calendar.prototype.goToNextMonth = function(year, month){
	month++;
	if (month > 11) {
		year++;
		month = 0;
	}

	this.drawMonth(year, month);
};

Calendar.prototype.goToPrevMonth = function(year, month){
	month--;
	if (month < 0) {
		year--;
		month = 11;
	}
	this.drawMonth(year, month);
};

Calendar.prototype.drawMonth = function(year, month){
	var x;
	var date = new Date(year, month, 32);
	var monthLength = 32 - date.getDate();
	
	date = new Date(year, month, 1);
	var startingDay = date.getDay();
	
	// correct startingDay if first day of week is monday
	if (this.firstDayOfWeek == 1) {
		startingDay--;
		if (startingDay == -1) {
			startingDay = 6;
		}
	}
	
	var $table = $('<table/>').addClass('calendar');
	var $caption = $('<caption/>').text(this.monthLabels[month] + ' ' + year).appendTo($table);
	var $thead = $('<thead/>').appendTo($table);
	$tr = $('<tr/>').appendTo($thead);
	var weekdayLabels = ['ma','di','wo','do','vr','za','zo'];

	for (x = 0; x < 7; x++) {
		var $td = $('<th/>').text(weekdayLabels[x]);
		$td.appendTo($tr);
	}
	var $tbody = $('<tbody/>').appendTo($table);
	
	// draw table content (days)
	 
	var day = 1;
	var numRows = Math.ceil((monthLength + startingDay)/7);
	
	for (var i=0; i<numRows; i++) {
		$tr = $('<tr/>');
		for (var j=0; j<7; j++) {
			var index = (i * 7) + j;
			$td = $('<td/>');			
			if ((i === 0 && j < startingDay) || (i == (numRows-1) && day > monthLength)) {				
				$td.text('').addClass('lead');
			}
			else {
				date = new Date(year, month, day);
				var time = date.getTime()/1000;
				
				if (time in this.shows) {
					//$.log(this.shows)
					this.shows[time].$td = $td;
					if (this.shows[time].disabled) {
						$td.addClass('notAvailable').html('<span>' + day + '</span>');	
					}
					else {
						$td.html('');
						var times = [];
						for (x in this.shows[time].times) {
							times.push(x);
						}
						
						var $a;
						
						if (times.length > 1) {	
							// multiple times, create list
							var $ul = $('<ul/>');
							$('<a href="#" class="day">' + day + '</a>').appendTo($td);

							for (x=0; x<times.length; x++) {
								var time2 = times[x];
								var $li = $('<li/>');
								
								date = new Date(times[x] * 1000);
								var timeString = date.getHours() + '.' + (date.getMinutes() < 10 ? '0'+date.getMinutes() : date.getMinutes()) + 'u';
									
								if (this.shows[time].times[time2].disabled) {
									$($li)
										.addClass('notAvailable')
										.attr('title', 'uitverkocht');
									$('<span>' + timeString + '</span>').appendTo($li);
								}
								else {
									$a = $('<a/>').attr('href', '#').text(timeString);
									$a.data('selectIndex', this.shows[time].times[time2].selectIndex);
									$a.appendTo($li);
								}								
								$li.appendTo($ul);
								
								if (time2 == this.activeTime) {
									$li.addClass('active');
								}
								else {
									$li.removeClass('active');
								}
							}
							$div = $('<div/>');
							$ul.appendTo($div);
							$div.appendTo($td);
							$td.addClass('multiple');
							
							if (day == this.activeMonthDay) {
								$td.addClass('multiple-active');
							}
							else {
								$td.removeClass('multiple-active');
							}
						}
						else {
							$a = $('<a/>').attr('href', '#').text(day);
							$a.data('selectIndex', this.shows[time].times[times[0]].selectIndex);
							$a.appendTo($td);
							if (day == this.activeMonthDay) {
								$td.addClass('active');
							}
							else {
								$td.removeClass('active');
							}
						}
			
					}
				}
				else {
					$td.text('');
				}								
				day++;	
			}
			$td.appendTo($tr);
		}
		$tr.appendTo($tbody);
	}
	
	if (this.initiated) {
		this.$calendar.next().andSelf().remove();
	}
	else {
		this.tables.push($table);
	}
	
	$table.insertBefore(this.$form);
	
	if (this.monthsType == 'browse') {
		// month browse
		$table.after('<p class="monthBrowse"><a class="prev" href="#" title="toon vorige maand">vorige</a><span class="noscreen"> | </span><a class="next" href="#" title="toon volgende maand">volgende</a></p>');
	}
	
	this.$calendar = $table;
	
	//  events:
	
	// click day
	var cal = this;
	$tbody.find('a').click(function(){
		cal.activeMonthDay = parseInt($(this).text(), 0);
		cal.$datesSelect.get(0).selectedIndex = $(this).data('selectIndex');
		cal.$datesSelect.change();
		
		// remove notice when just added a showdate to basket
		cal.$form.children('#acMsg').remove();
		cal.$form.children('fieldset').show();
				
		return false;
	});
	

	// hover multiple
	$tbody.find('td').filter('.multiple').hoverIntent(
		{  
			sensitivity: 9,
			interval: 100,
			over: function(){$(this).addClass('multiple-hover');},
			timeout: 300,
			out: function(){$(this).removeClass('multiple-hover');}
		}
	);
	
	if (this.monthsType == 'browse') {
		// click events
		var $prev = $table.next().find('a.prev');
		var $next = $table.next().find('a.next');

		if (this.months.length > 1) {
			var firstMonth = this.months[0];
			var lastMonth = this.months[this.months.length-1];

			if ((year+'-'+month) == firstMonth) {
				$prev.hide();
				$next.show();
			}
			else if ((year+'-'+month) == lastMonth) {
				$prev.show();
				$next.hide();
			}
			else {
				$prev.show();
				$next.show();
			}
		}
		else {
			$prev.hide();
			$next.hide();
		}
		
		$prev.click(function(){
			cal.goToPrevMonth(year, month);
			return false;
		});
		
		$next.click(function(){
			cal.goToNextMonth(year, month);
			return false;
		});
		
		cal.$button_next = $next;
		cal.$button_prev = $prev;		
	}
}



/**
 * slideMenu
 * jQuery plugin
 * usage: $selection.slideMenu({options})
 * 
 * @author AK | Peppered
 * @version 1.0.0.dkk.1-pre
 * 
 */
;(function($) {
	
	$.fn.slideMenu = function(options) {
		options = $.extend({
			test: 'testvalue'
		}, options);
	
		this.removeClass('nofx').addClass('menufx');
		_setTriggers(this);
		
		this.children().each(function(){
			$(this).children().not('a').wrapAll('<div class="contentWrap"></div>');
		});		
	};
	
	
	/**
	 * _setActive, private
	 */
	function _setActive($obj, $menuItem) {
				
		$obj.children('li').children('a').unbind('click').click(function(){ return false; }).addClass('inactive');
	
		$menuItem.siblings().children('a').andSelf().removeClass('active');
			
		if ($menuItem.is('.active')) {
			$menuItem.children('a').andSelf().removeClass('active');
			_setTriggers($obj);
			return;
		}
		else if ($menuItem.is(':last-child')) {
			$menuItem.children('a').andSelf().addClass('active');
			$menuItem.children('.contentWrap').slideDown(300, function(){ _setTriggers($obj); });
			return false;
		}
		
		// animate items that move up in DOM tree
		var offsetTop = $menuItem.offset().top;
		var topAddjustment;
		if ($menuItem.prev().length) {
			topAddjustment = $menuItem.prev().offset().top - offsetTop;
		}
		else {
			topAddjustment = offsetTop - $menuItem.next().offset().top;
		}		
		var $nextItems = $menuItem.nextAll();
		$nextItems.animate({top: topAddjustment}, 400);
		
		
		// fadeOut menuItem, 
		$menuItem.animate({opacity: 0}, 400, null, function(){
			// clone menuItem, append & fadeIn
			$clone = $menuItem.clone(true);			
			$clone.appendTo($obj);
	
			// reset animated items top pos.
			$nextItems.css({top: 0});
			$menuItem.remove();
			$clone.animate({opacity: 1}, 400, null, function(){
				$clone.children('a').andSelf().addClass('active');	
				// show submenu
				$clone.children('.contentWrap').slideDown(300);
				_setTriggers($obj);
			});
		});
	}
	
	
	/**
	 * _setTriggers, private
	 */
	function _setTriggers($obj) {
		$obj.children('li').children('a').unbind('click').click(function(){
			var $menuItem = $(this).parent();		
			
			if ($obj.children('li.active').children('.contentWrap:visible').length) {
				$obj.children('li.active').children('.contentWrap:visible').slideUp(300, function(){				
					_setActive($obj, $menuItem);			
				});
			}
			else {
				_setActive($obj, $menuItem);
			}
			return false;
		})
		.removeClass('inactive');
	}	
	
})(jQuery);

