String.prototype.parseUsername = function() {
	return this.replace(/[@]+[A-Za-z0-9-_]+/, function(u) {
		var username = u.replace("@","")
		return u.link("http://twitter.com/"+username);
	});
};

String.prototype.parseURL = function() {
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(url) {
		return url.link(url);
	});
};

String.prototype.parseHashtag = function() {
	return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
		var tag = t.replace("#","%23")
		return t.link("http://search.twitter.com/search?q="+tag);
	});
};

String.prototype.pad = function(l, s){
	return (l -= this.length) > 0
		? (s = new Array(Math.ceil(l / s.length) + 1).join(s)).substr(0, s.length) + this + s.substr(0, l - s.length)
		: this
	;
};

function formatDuration(seconds) {
	return Math.floor(seconds / 60) + ":" + (seconds % 60).toFixed().pad(2, "0");
}

function loadScript(file) {
	var script  = document.createElement("script");
	script.type = "text/javascript";
	script.src  = file;
	$("head")[0].appendChild(script);
}

function getLang() {
	return $("meta[http-equiv='content-language']").attr("content");
}

$(function () {
	
	// category slider home page
    $("#featured").tabs({fx:{opacity: "toggle"}}).tabs("rotate", 5000, true); 
	
    // category slider clickable divs
	$("div.clickable").click(
		function() {
			window.location = $(this).attr("url");
		}
	);
    
	// Subcategories on subcategory page
	if( $("#subcategories .block_inner ul li").length ) {
		var colHeightFirst = 0;
		var colHeightSecond = 0;
		var colHeightThird = 0;
		
		$(".block_inner ul li.col_first").each(function() {
			colHeightFirst += $(this).outerHeight(true);
		});
		
		$(".block_inner ul li.col_second").each(function() {
			colHeightSecond += $(this).outerHeight(true);
		});
		
		$(".block_inner ul li.col_last").each(function() {
			colHeightThird += $(this).outerHeight(true);
		});
		
		var maxColHeight = Math.max(colHeightFirst,colHeightSecond,colHeightThird);
		
		$(".block_inner ul li.col_first").parent("ul").height( maxColHeight );
	}
	
	$("#subcategories .block_inner ul li.first_row").each(function(){
		var offsetHeightRow = $(this).offset().top;
		var offsetHeightUl =  $(this).parent("ul").offset().top;
		var offsetHeight = (offsetHeightRow - offsetHeightUl) * -1;
		
		$(this).css( "margin-top", offsetHeight);
	});
	
	// handle placeholders in input fields
	$("input:hasPlaceholder").m3Placeholder();
	
	// open clickouts in new window
	$(".button.clickout").attr({
		target: "_blank"
	});
	
	// convert panels to tabs
	$(".panels").tabs({
		show: function() {
			if( window.location.hash != '') {
				$("html,body").scrollTop(0);
			}
			
			$(".panels li").css("font-size", "12px");
		}
	});
	
	// handle hovers
	$("input.button, .category_products tbody > tr, ol.chart li").hover(
		function () {
			$(this).addClass('hover');
		},
		function () {
			$(this).removeClass('hover');
		}
	);
	
	if ($(".slider_content").length) {
		
		var sliderContent = $(".slider_content");
		
		sliderContent.width(  $(".top_categories").find("li").length * 150 );
	}
	
	/*
	 * Validation
	 */
	 
	// set date format: dd-mm-yyyy
	$.validator.addMethod("isDateMMDDYYYY", function (value, element) {
        return value.match(/^\d\d?-\d\d?-\d\d\d\d$/);
      },
      "Please enter a date in the format dd-mm-yyyy"
    );
	 
	// search form
	$("#form_search").validate({
		rules: {
			keyword: "required"
		},
		errorPlacement: function(error, element) {},
		submitHandler: function(form) { form.submit(); }
	});
	
	// agenda picker (block)
	$("#block_agenda form").validate({
		rules: {
			date_start: { isDateMMDDYYYY: true }
		},
		errorPlacement: function(error, element) {},
		submitHandler: function(form) {
			//window.location.href = '/agenda/#/?fragment=true&' + $(form).serialize();
			$(form).attr('action', "/agenda/#/?fragment=false&" + $(form).serialize() );
			form.submit();
		}
	});
	
	// contact form
	$("#form_contact").validate({
		rules: {
			name: 'required',
			email: {
				required: true,
				email: true
			},
			phone: 'required',
			message: 'required'
		},
		errorPlacement: function(error, element) {},
		submitHandler: function(form) { form.submit(); }
	});
	
	$("#form_newsletter").validate({
		rules: {
			EMAIL: {
				required: true,
				email: true
			}
		},
		errorPlacement: function(error, element) {},
		submitHandler: function(form) {
			form.submit();
		}
	});
	
	/*
	 * Calendar pickers
	 *
	 * NOTE: date format has to correspond with the validator
	 */
	
	$.datepicker.setDefaults($.datepicker.regional[getLang()]);
	
	$("#agenda_date_start, #agenda_date_end, #search_filter_date_start, #search_filter_date_end, #filter_date_start, #filter_date_end").livequery(function() {
		var date = new Date();
		var currentMonth = date.getMonth();
		var currentDate = date.getDate();
		var currentYear = date.getFullYear();
		
		if( $("input[id $= '_start']").length && $("input[id $= '_end']").length ) {
			var startDate = $("input[id $= '_start']");
			var endDate = $("input[id $= '_end']");
			
			//There is a start- / end date. Make sure the start date is ALWAYS before the end date.
			var dates = $( "#" + startDate.attr('id') + ", #" + endDate.attr('id') ).datepicker({
				showOn: 'both',
				buttonImage: '/tiqets/templates/default/images/icons/datepicker.gif',
				buttonImageOnly: true,
				dateFormat: 'dd-mm-yy',
				beforeShow: function() {
					if( this.id == endDate.attr('id') ) {
						return {
							minDate: $(startDate).datepicker("getDate")
						};
					} else {
						return {
							minDate: new Date(currentYear, currentMonth, currentDate)
						};
					}
				},
				onSelect: function( selectedDate ) {
					var option = this.id == startDate.attr('id') ? "minDate" : "maxDate",
						instance = $( this ).data( "datepicker" ),
						date = $.datepicker.parseDate(
							instance.settings.dateFormat ||
							$.datepicker._defaults.dateFormat,
							selectedDate, instance.settings );
							
					date.setDate(date.getDate() + 21);
					
					dates.not( this ).datepicker( "option", option, date );
					
					$(this).change();
				}
			});
		} else {
			//There is no start- / end date. This means the date picker is just for one specific date, so transform the textarea to a datepicker.
			$(this).datepicker({
				showOn: 'both',
				buttonImage: '/tiqets/templates/default/images/icons/datepicker.gif',
				buttonImageOnly: true,
				minDate: new Date(currentYear, currentMonth, currentDate),
				dateFormat: 'dd-mm-yy'
			});
		}
		
		$("#ui-datepicker-div").hide();
	});
	
	/*
	 * Advanced search
	 */
	$("#container_search .trigger").m3Toggle({
		panelSelector: '#advanced_search',
		labelOpen: $("#label_trigger_close").text(),
		//opened: true,
		onOpen: function() {
			$(this).hide().css('opacity', 0).slideDown('normal').animate({ opacity: 1.0 }, 'normal');
		},
		onClose: function() {
			$(this).show().css('opacity', 0).slideUp('normal').animate({ opacity: 0 }, 'normal');
		}
	});
	
	/*
	 * Newsletter (footer)
	 */
	$("#form_newsletter").validate({
		rules: {
			email: {
				required: true,
				email: true
			}
		},
		errorPlacement: function(error, element) {},
		submitHandler: function(form) { form.submit(); }
	});
	
	/*
	 * Categorie archief
	 */
	$(".category_archive .container ul").m3ColumnizeList(3);
	
	/*
	 * Productcategorie
	 */
	$(".category_products").each(function() {
		
		// handle table sorting
		$(this).tablesorter({
			headers: {
				6 : { sorter: false }
			}
		});
		
		// link the entire row to the product page, except when the clickout button is clicked
		$(this).find("tbody > tr").click(function(e) {
			
			if ($(e.target).is(".clickout")) {
				return;
			}
			
			window.location.href = $(this).find("a[rel='product_url']").attr("href");
		})
	});
	
	/*
	 * Artist mashup
	 */
	 
	if ($("#mashup").length) {
		loadScript("/tiqets/templates/default/scripts/mashup.js");
		
		setTimeout(function() {
			loadScript("/tiqets/templates/default/scripts/tiqets_mashup.js");
		}, 200);
	}
	
	/*
	 * Agenda Sitemap
	 */
	$(".block_agenda_sitemap .block_inner ul, .block_agenda_sitemap .container ul").m3ColumnizeList(3);
	
	/*
	 * Productpagina
	 */
	/*
	if ($("#block_related").length) {
		$("#block_related").scrollable({
			vertical: true,
			size: 2
		});
	}
	*/
	
	/*
	 * Maak het hele resultaatblok aanklikbaar
	 */
	
	$(".product_result").livequery("click", function(e) {
		
		window.location.href = $(this).find(".product_title > h3 > a").attr('href');
	});
	
	/*
	 * Results: Agenda / Search
	 */
	
	$("#filter_all").m3MasterCheckbox({
		isDisabled: true
	});
	
	/*
		convert agenda links into "ajax" link (#)
	 */
	
	if ($("a[href^='/agenda/']").length) {
		
		$("a[href^='/agenda/']").each(function() {
			
			this.href = this.href.replace(/\/agenda\//, '/agenda/#/');
		});
	}
	
	/*
		Center footer
	*/
	if( $("#nav_footer").length ) {
		var totalFooterWidth = 0;
		
		$("#nav_footer li").each(function() {
			totalFooterWidth += $(this).outerWidth(true);
		});
		
		totalFooterWidth += 5;
		
		$("#nav_footer").width(totalFooterWidth);
	}
	
	/**
	 * Lang switch
	 */
	
	// check for langswitch element
	if ($("#langswitch").length) {
		
		var langswitch = $("#langswitch");
		var langMenu = $("#nav_lang");
		var langSelected = langMenu.find(".current");
		var langTimer = 0;
		var timeOut = 400;
		
		// remove the anchor element so the current language is not clickable
		langSelected.find("span").unwrap("a");
		
		// create a paragraph to store the selected language element in
		// before we remove it from the language list
		$("<div />", {
			"id"    : "current_lang",
			"class" : "lang current"
		})
		.html( langSelected.html() )
		.prependTo(langswitch)
		;
		
		langSelected.remove();
		
		function showLangMenu() {
			if (langTimer) {
				window.clearTimeout(langTimer);
				langTimer = null;
			}
			
			langMenu.show();
			langMenu.css("z-index", "9999");
		}
		
		function hideLangMenu() {
			
			// set a timeout
			langTimer = window.setTimeout(function() {
				
				langMenu.slideUp("fast");
				
			}, timeOut);
			
		}
		
		// bind the show/hide functions to the langswitch element
		langswitch.hover(
			showLangMenu,
			hideLangMenu
		);
		
		// hide the menu when a new language is selected
		$("body").click(function(e) {
			hideLangMenu();
		})
		
		// hide the language menu
		langMenu.hide();
	}
});
