/** Google Analytics **/
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-17110419-3']);
_gaq.push(['_trackPageview']);

$(function(){
	/** Google Analytics **/
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	ga.src = 'http://www.google-analytics.com/ga.js'; document.getElementsByTagName('head')[0].appendChild(ga);
	
/** Menu **/
	$(".menu td").click(function(){
		location.href = $("> a", this).attr('href');
	});
	
	/** Validate forms **/
	$("form").submit(function(){
		var ok = true;
		$(":input:not([type=submit]):not([type=reset])", this).each(function(){
			if(!($(this).hasClass('opt') || $(this).closest(".CodeMirror-wrapping").length) && !$(this).val()) {
				$(this).css('border-color','#db001b').focus(function(){
					$(this).css('border-color','').unbind('focus');
				});
				ok=false;
			}
			else if($(this).attr('name') == 'lme') {
				var regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
				if(!regex.test($(this).val())) {
					alert(text.invalidemail);
					$(this).css('border-color','#db001b').focus(function(){
						$(this).css('border-color','').unbind('focus');
					});
					ok=0;
				}
			}
		});
		if(ok===false) alert(text.js_allfields);
		if(ok) keeponpage = false;
		
		return !!ok;
	});
	
	/** Add behavior to channel 'checkboxes' **/
	$("label.channel").click(function(){
		if((obj = $(this).closest('form').find('button')).length == 1) {
			obj.click();
		}
		
		var cl;
		if($(this).hasClass("d0") || $(this).hasClass("d1")) 
			cl = 'o0';
		else if($(this).hasClass("o0")) 
			cl = 'o1';
		else if($(this).hasClass("o1")) 
			cl = 'd'+$('input', this).attr('data-default');
		
		// Set input value
		$('input', this).val(cl.charAt(0)=='d' ? '' : (cl.charAt(1)));
		
		$(this).removeClass().addClass('channel '+cl).attr('title', text[cl]);
	}).find("input").click(false);
	
	/** Add style to checkboxes **/
	$("label:has(input[type=checkbox])").addClass("checkbox").click(function() {
		$("input", this).click();
		return false;
	}).find("input").click(function(e){
		$(this).parent().toggleClass('checked');
		e.stopPropagation();
	}).hide().each(function(){
		if($(this).attr('checked')) $(this).parent().addClass('checked');
	});
	
	/** Open album **/
	$("a[href$=#album]").click(function() {
		var href = $(this).attr('href').length > 8 ? $(this).attr('href') : location.href + '#album';
		var hashpos = href.indexOf('#');
		if((pos = href.indexOf('forte.eu')) > 0)
			openalbum(href.substring(pos+8, hashpos));
		else 
			openalbum(href.substring(0, hashpos));
		
		return false; //location.href.indexOf(href.substring(0, hashpos)) != -1;
	});
	if(window.location.href.indexOf('#album')>0) {
		$("a[href$=#album]:first").click();
	}
	$("#showalbum a[href=/]").live('click', hidealbum);
	
	/** Open external link **/
	$("#lane").delegate("a[rel~=external]", 'click', function(){
		window.open(this.href);
		return false;
	});
	
	/** Blog rotation on home **/
	/*
	$("ul.rotate").each(function() {
		var obj = $(this);
		$("li:first", this).show();
		setTimeout(function(){
			window.setInterval(function(){
				var next = $("li:visible", obj).next();
				if(!next.size()) next = $("li:first", obj);
				$("li:visible", obj).fadeOut(function(){next.fadeIn();});
			}, 5750);
		}, 2500);
	});
	*/
	
	// edit form
	var keeponpage = false;
	$(".contentform form:has(textarea)").submit(function(){
		if(!validateXML('<div>'+$("textarea", this).val()+'</div>')) {
			return !confirm("Deze code is geen geldige XHTML. \n\nSluit alle tags correct af, ook <br/> en <img/>. \nVervang < > & door &lt; &gt; &amp;. \n\nWilt u het niettemin toch opslaan? Klik dan 'Cancel'. ");
		}
	}).each(function(){
		//var editor = CodeMirror.fromTextArea($("textarea", this)[0], {mode: "text/html", tabMode: "indent"});
		var editor = CodeMirror.fromTextArea(
			$("textarea", this).attr('id', 'test123').attr('id'),
			{
				height: "365px",
				parserfile: ["parsexml.js", "parsecss.js", "tokenizejavascript.js", "parsejavascript.js", "parsehtmlmixed.js"],
				stylesheet: ["http://fyt.be/codemirror/xmlcolors.css", "http://fyt.be/codemirror/jscolors.css", "http://fyt.be/codemirror/csscolors.css"],
				path: "http://fyt.be/codemirror/"
			});
		var orig = $("textarea", this).val(), last=orig;
		setInterval(function(){
			//$(".contentform textarea").val(editor.getCode());
			//console.log(editor.getCode());
			var code = editor.getCode();
			if(code != last) {
				if(!keeponpage && orig != code) {
					$(".contentform .left [type=submit]").css('background-color', '#0b0');
					keeponpage = true;
				}
				$("#content, #aboveform").last().html(code);
				last = code;
			}
		},1000);
	});
	/*
	var orig = $(".contentform textarea").keyup(function(){
		$("#content, #aboveform").last().html($(this).val());
		if(!keeponpage && orig != $(this).val()) {
			$("[type=submit]", this.form).css('background-color', '#0b0');
			keeponpage = true;
		}
	}).val();
	*/
	window.onbeforeunload = function() {
		if(keeponpage) return '';
	};
	
	
	// In case two colums have different heights
	var obj = $(".content");
	if(obj.length > 1) {
		var min=999, max=0;
		obj.each(function(){
			min = Math.min(min, $(this).height());
			max = Math.max(max, $(this).height());
		});
		if(min != max) obj.css({height: max});
	}
	// Contact form buttons
	$("p > button").click(function(){
		location.href = location.href + 'contactform/';
	});
	// overwritten buttons
	$("a > button").click(function(){
		location.href = $(this).parent().attr('href');
		return false;
	});
});
function validateXML(xmlString) {
	try {
		if (document.implementation.createDocument) {
			var parser = new DOMParser();
			var myDocument = parser.parseFromString(xmlString, "text/xml");
			with (myDocument.documentElement) {
				if (tagName=="parseerror" || namespaceURI=="http://www.mozilla.org/newlayout/xml/parsererror.xml") {
					//alert("Failed the test of well-formedness.");
					return false
				}
			}
		} else if (window.ActiveXObject) {
			var myDocument = new ActiveXObject("Microsoft.XMLDOM")
			myDocument.async = false
			var nret=myDocument.loadXML(xmlString);
			if (!nret) {
				//alert("Failed the test of well-formedness.");
				return false
			}
		}
	} catch(e) {
		//alert(e);
		return true    //maybe the user-agent does not support both, then it should be submitted and let server-side validation does the job
	}
	//alert("Passed the test of well-formedness.")
	return true
}
function openalbum(path) {
	if(!$("#showalbum").size()) {
		$("body").append('<div id="showalbum"><div id="fog"></div><div id="closer"><a href="/">close</a></div><iframe src="" allowtransparency="allowtransparency" frameborder="0"></iframe></div>');
	}
	$("#showalbum div#fog").css('opacity', 0).animate({opacity: 0.7}).parent().show();
	if(!$('#showalbum iframe').attr('src'))
		$('#showalbum iframe').attr('src', path+'album/'); 
	
	//return path == ;
}
function hidealbum() {
	$("#showalbum").fadeOut();
	if(window.location.hash) window.location.hash = '';
	return false; 
}
