$(function() {
	
	$('textarea[initValue],input[initValue]').initValue();

	$('div#watIsWiezietBox').click(function() {
		window.location.href = '/over-wieziet/wat-is-wieziet';
	});
	
	//-- form focus
	if ($("input#name").get(0) && $("input#email").get(0)) {
		$("input#name").get(0).focus();
	} else if ($("input#email").get(0)) {
		$("input#email").get(0).focus();
	}
	
	//-- notifications
	$("a[rel=notification]").click(function() {
		var a = $(this);
		var div = a.parent().parent().parent();
		$.ajax({
			url:		a.attr("href"),
			type: 		"GET",
			dataType: 	"html",
			timeout: 	2000,
			error: function() {
				alert("Er is iets fout gegaan.");
			},
			success: function(data) {
				div.effect("transfer", {to : "#notificationtarget", className: "ui-effects-transfer"}, 500);
				
				if (data == 0) {
					setTimeout(
						function() {
							$("div#notificationcontainer").effect("blind", {}, 500)
						}, 
						500
					);
				} else {
					setTimeout(
						function() {
							div.effect("blind", {}, 200);
						},
						500
					);
				}
			}
		});
		
		return false;
	});
	
	//-- calendar
	var cf = $("div#ajaxcalendarform");
	var cd = $("div#calendardetails"); 
	
	cf.hide();
	cf.find("a").click(function(e) {
		e.stopPropagation();
		cf.hide();
		return false;
	});
	
	cd.hide();
	cd.find("a").click(function(e) {
		e.stopPropagation();
		cd.hide();
		return false;
	});
	
	cf.find("form").each(function() {
		form = $(this);
		form.submit(function() {
			$("img#addloader").show();
			form.hide();
			
			$.ajax({
		        url: form.attr("action"),
		        type: 'GET',
		        data: {
					date_from 	: form.find("input[name=date_from]").val(),
					daypart		: form.find("input[name=daypart]").val(),
					text		: form.find("input[name=text]").val()
				},
		        dataType: 'html',
		        timeout: 5000,
		        error: function() {
		            alert('Er is een fout opgetreden');
		        },
		        success: function(html) {
		        	cf.find("form").show();
		        	cf.find("textarea").val("");
		        	cf.find("img").hide();
		        	cf.hide();
		        	
		        	if (html == "[[error]]") {
		        		alert('Er is een fout opgetreden bij het opslaan.');
		        	} else {
			            $("td[rel=" + form.find("input[name=date_from]").val() + "-" 
			            			+ form.find("input[name=daypart]").val() + "]")
			            	.append(
			            		$(html)
			            			.click(function(e) {
			            				e.stopPropagation();
			            				e.preventDefault();
			            				showDetails($(this).find("a"));
			            			})
			            	);
		        	}
		        }
		    });
			
			return false;
		});
	});
	
	$("div[rel=highlight]").effect("highlight", {color: "#afde48"}, 2500);
	$("ul.faq a").click(function() {
		$($(this).attr("href")).effect("highlight", {color: "#afde48"}, 2500);
	});
	
	$("table.tableWraper td.lightGreenBox a.pelle-event").click(function(e) {
		e.stopPropagation();
		e.preventDefault();
		showDetails($(this));
	});
	
	$("table.tableWraper td.lightGreenBox").each(function() {
		var td 		= $(this);
		var parts 	= td.attr("rel").split("-");
		var daypart = parts.pop();
		
		td.data("date", 	parts.join("-"));
		td.data("daypart", 	daypart);
		
	}).click(function(e){
		e.stopPropagation();
		e.preventDefault();
		cd.hide();
		var td = $(this);
		var of = td.offset();
		var of2 = $("#pelle-relcontainer").offset();
		cf.css({
			left : Math.floor(of.left - of2.left) + "px",
			top  : Math.floor(of.top - of2.top) + "px"
		}).show();
		cf.find("input[name=text]").val("");
		cf.find("input[name=text]").get(0).focus();
		cf.find("input[name=date_from]").val(td.data("date"));
		cf.find("input[name=daypart]").val(td.data("daypart"));
	});
	
	function showDetails(link) {
		
		var td = link.parent().parent();
		var of = td.offset();
		var of2 = $("#pelle-relcontainer").offset();
		var of3 = link.offset();
		
		cd.css({
			left : Math.floor(of3.left - of2.left)  + "px",
			top  : Math.floor(of3.top - of2.top) + "px"
		}).toggle();
		cd.find("span#details_name").text(link.text());
		cd.find("span#details_text").text(link.attr("title"));
		
		a = $("a#details_delete");
		a.hide();
		if (link.hasClass("removable")) {
			a.show();
			a.attr("href", a.attr("rel") + link.attr("rel"));
			a.unbind("click");
			a.click(function(e) {
				cd.hide();
				$.ajax({
			        url: $(this).attr("href"),
			        type: 'GET',
			        dataType: 'html',
			        timeout: 2000,
			        error: function() {
			            alert('Er is een fout opgetreden');
			        },
			        success: function(html) {
			        	if (html == "[[error]]") {
			        		alert('Er is een fout opgetreden bij het verwijderen.');
			        	} else {
			        		link.parent().remove();
			        	}
			        }
			    });
				return false;
			});
		}
	}
});

function insertUBB(tag) {
	switch (tag) {
		case "bold" :
			insertTags("[b]", "[/b]", "Vette tekst");
			break;
		case "italic" :
			insertTags("[i]", "[/i]", "Schuine tekst");
			break;
		case "list" :
			insertTags("[list]", "[/list]", "Punt 1\r\nPunt 2");
			break;
		case "url" :
			insertTags("[url]", "[/url]", "http://");
//	    	var txt = 'Voer link in: <br><input type="text" id="url" name="url" value="http://" />';
//
//	    	function getURL(v, m, f) {
//	    		$("#text").get(0).focus();
//	    	    insertTags("[url=" + f.url + "]", "[/url]", (f.url).replace("http://", ""));
//	    	}
//
//	    	$.prompt(txt, {
//	    	      callback: getURL,
//	    	      show: 'slideDown',
//	    	      overlayspeed: 'fast',
//	    	      promptspeed: 'fast'
//	    	});
			break;
	}
}

function insertTags(tagOpen, tagClose, sampleText) {
	var txtarea = $("#text").get(0);
	var selText, isSample = false;

	if (document.selection  && document.selection.createRange) { // IE/Opera

		//save window scroll position
		if (document.documentElement && document.documentElement.scrollTop)
			var winScroll = document.documentElement.scrollTop
		else if (document.body)
			var winScroll = document.body.scrollTop;
		//get current selection
		txtarea.focus();
		var range = document.selection.createRange();
		selText = range.text;
		//insert tags
		checkSelectedText();
		if (tagOpen == "[list]") {
			range.text = tagOpen + "\r\n[*]" + selText.split(/\r?\n/).join("\r\n[*]") + "\r\n" + tagClose;
		} else {
			if (tagOpen == '[url]' && !/^http:\/\//.test(selText)) {
			    selText = 'http://' + selText;
			}
			range.text = tagOpen + selText + tagClose;
		}
		//mark sample text as selected
		if (isSample && range.moveStart) {
			if (window.opera)
				tagClose = tagClose.replace(/\n/g,'');
			range.moveStart('character', - tagClose.length - selText.length);
			range.moveEnd('character', - tagClose.length);
		}
		range.select();
		//restore window scroll position
		if (document.documentElement && document.documentElement.scrollTop)
			document.documentElement.scrollTop = winScroll
		else if (document.body)
			document.body.scrollTop = winScroll;

	} else if (txtarea.selectionStart || txtarea.selectionStart == '0') { // Mozilla

		//save textarea scroll position
		var textScroll = txtarea.scrollTop;
		//get current selection
		txtarea.focus();
		var startPos = txtarea.selectionStart;
		var endPos = txtarea.selectionEnd;
		selText = txtarea.value.substring(startPos, endPos);
		//insert tags
		checkSelectedText();
		if (tagOpen == "[list]") {
			txtarea.value = txtarea.value.substring(0, startPos)
				+ tagOpen + "\r\n[*]" + selText.split(/\r?\n/).join("\r\n[*]") + "\r\n" + tagClose
				+ txtarea.value.substring(endPos, txtarea.value.length);
		} else {
			if (tagOpen == '[url]' && !/^http:\/\//.test(selText)) {
				    selText = 'http://' + selText;
			}
			txtarea.value = txtarea.value.substring(0, startPos)
				+ tagOpen + selText + tagClose
				+ txtarea.value.substring(endPos, txtarea.value.length);
		}
		//set new selection
		if (isSample) {
			txtarea.selectionStart = startPos + tagOpen.length;
			txtarea.selectionEnd = startPos + tagOpen.length + selText.length;
		} else {
			txtarea.selectionStart = startPos + tagOpen.length + selText.length + tagClose.length;
			txtarea.selectionEnd = txtarea.selectionStart;
		}
		//restore textarea scroll position
		txtarea.scrollTop = textScroll;
	}

	function checkSelectedText(){
		if (!selText) {
			selText = sampleText;
			isSample = true;
		} else if (selText.charAt(selText.length - 1) == ' ') { //exclude ending space char
			selText = selText.substring(0, selText.length - 1);
			tagClose += ' '
		}
	}
}

function addLink() {
	var visible = [];
	$("div.pelle-formvts").each(function() {
		if ($(this).is(":visible")) {
			visible.push($(this).attr("id"));
		}
	});
	
	$("div#invite-container-" + visible.length).show();
	
	if (visible.length >= 9) {
		$("div#invite-link-container").hide();
	}
}

$.fn.initValue = function () {
	return this.each(function(){
		if ($(this).val() == '')
			$(this).val($(this).attr('initValue'));
		$(this).focus(function(){
			if ($(this).val() == $(this).attr('initValue'))
				$(this).val('');
		}).blur(function(){
			if ($(this).val() == '')
				$(this).val($(this).attr('initValue'));
		});
	});
};

function clearInitValues() {
    $("input,textarea").each(function() {
        var ta = $(this);
        if (ta.attr("initValue") == ta.val()) {
            ta.val("");
        }
    });
}
