function CasualCMS() {}

CasualCMS.Init = function () {
	this.URL,
	this.URIArray = new Array;
	this.URI = new Array;
	
	this.URL = window.location.href;
	//this.URIArray = this.URL.split('/');
	
	this.URI[0] = this.URIArray[3];
	this.URI[1] = this.URIArray[4];
	this.URI[2] = this.URIArray[5];
};

CasualCMS.AddHotkey = function ( Shortcut , Action ) {
	$.hotkeys.add ( Shortcut, Action );
};

CasualCMS.TinyMCE = function ( ContentCSS, id ) {
	tinyMCE.init({
		mode : "none",
		width: 870,
		height: 500,
		theme : "advanced",
		plugins : "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
		//language : "nl",
		theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
        theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
        theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,
        external_link_list_url : "/Website/tinyMCELinkList",
        external_image_list_url : "/Website/tinyMCEImageList",
        media_external_list_url : "/Website/tinyMCEMediaList",
        skin : "o2k7",
		convert_urls : false
	});
	tinyMCE.execCommand("mceAddControl", true, id);
};

function thickboxResize() {

	var boundHeight = 600; // minimum height
	var boundWidth = 800; // minimum width

	var viewportWidth = (self.innerWidth || (document.documentElement.clientWidth || (document.body.clientWidth || 0)));
	var viewportHeight =(self.innerHeight || (document.documentElement.clientHeight || (document.body.clientHeight || 0)));

	$('a.thickbox').each(function(){
		var text = $(this).attr("href");

		//if ( viewportHeight < boundHeight  || viewportHeight < boundWidth)
		//{
			if ( text.search(/height=[0-9]*/) > 0 ) {
				// adjust the height
				text = text.replace(/height=[0-9]*/,'height=' + Math.round(viewportHeight * .8));
				// adjust the width
				text = text.replace(/width=[0-9]*/,'width=' + Math.round(viewportWidth * .9));
			}
			else {
				text += '?height=' + Math.round(viewportHeight * .8) + '&width=' + Math.round( viewportWidth * .9 );
			}
		//}
		//else 
		//{
			//if ( text.search(/height=[0-9]*/) > 0 ) {
				// constrain the height by defined bounds
				//text = text.replace('/height=[0-9]*/','height=' + boundHeight);
				// constrain the width by defined bounds
				//text = text.replace('/width=[0-9]*/','width=' + boundWidth);
			//}
			//else {
				//text += '?height=' + Math.round(viewportHeight * .8) + '&width=' + Math.round( viewportWidth * .8 );
			//}
		//}

		$(this).attr("href", text);
	});
}

$(window).bind('load', thickboxResize );

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

ReactieModule = function() {};

ReactieModule.ProcessCommentForm = function () {
	var paginaModuleReactiesLaden = $('#paginaModuleReactiesLaden');
	var action = $('#paginaModuleReactieFormulier').attr('action');
	var reactie = $('#paginaModuleReactieFormulier').find('#Tekst').val();
	var naam = $('#paginaModuleReactieFormulier').find('#Naam').val();
	var email = $('#paginaModuleReactieFormulier').find('#Email').val();
	var website = $('#paginaModuleReactieFormulier').find('#Website').val();
	var pagina_module_id = $('#paginaModuleReactieFormulier').find('#pagina_module_id').val();
	var mens = $('#paginaModuleReactieFormulier').find('#mens').val();
	var data = "submit=submit&Tekst=" + reactie + "&Naam=" + naam + "&Email=" + email + "&Website=" + website + "&pagina_module_id=" + pagina_module_id;
	var melding = '';
	if (reactie == '') { 
		$('#paginaModuleReactieFormulier').find('#Tekst').css('border', '#c30 2px solid'); 
		melding += 'Uw reactie is leeg.';
	}
	if (naam == '') { 
		$('#paginaModuleReactieFormulier').find('#Naam').css('border', '#c30 2px solid');  
		melding += 'U moet uw naam invullen.';
	}
	if (email == '') { 
		$('#paginaModuleReactieFormulier').find('#Email').css('border', '#c30 2px solid');  
		melding += 'U moet uw emailadres invullen. Deze zal niet worden gepubliceerd.';
	}
	if (melding != '') {
		return false; 
	}
	$("#ReactieOpslaan").attr({ disabled:true, value:"Toevoegen..." });  
	$("#ReactieOpslaan").blur();  
	$.post(
		action, 
		{ 
			submit: 'submit', 
			Tekst: reactie, 
			Naam: naam, 
			Email: email, 
			Website: website, 
			pagina_module_id: pagina_module_id, 
			mens : mens 
		}, 
		function(data) 
		{ 
			$('#paginaModuleReacties').html(data); 
			$("#ReactieOpslaan").attr({ disabled:false, value:"Toevoegen" }); 
			$('#paginaModuleReactieFormulier input, #paginaModuleReactieFormulier textarea').each(function() 
			{ 
			}); 
		}
	);
};

BlogModule = function () {};

BlogModule.ProcessSearchForm = function () {
	var q = $('#q').val(); 
	var action = $(this).attr('action'); 
	window.location = action + q; 
	return false;
};

Pagina = function () {};

Pagina.BestandenUploaden = function() {};

Pagina.BestandenUploaden.ProcessFileClick = function(File, WebsiteID, Type) {
	var url = '/User/' + WebsiteID + '/Documenten/' + File;
	opener.jQuery('#' + Type).val(url);
	window.close();
	return false;
};

$(document).ready(function()
{	
	CasualCMS.Init();
	
	$(window).bind('resize', thickboxResize );
	
	var url = CasualCMS.URL;
	var uri0 = CasualCMS.URI[0];
	var uri1 = CasualCMS.URI[1];
	var uri2 = CasualCMS.URI[2];
	
	$('#mens').hide();
	
	$('#paginaModuleReactieFormulier').submit(function() {
		ReactieModule.ProcessCommentForm();
		return false; 
	});
	
	$('#blogZoekFormulier').submit(function() {
		BlogModule.ProcessSearchForm();
	});
	
	$('.verwijder').click(function(){
		return confirm('Weet je zeker dat je dit item wilt verwijderen?');
	});
	
	CasualCMS.AddHotkey('Ctrl+l', function() { window.location.href = '/Login?ref=' + window.location.pathname; });
	CasualCMS.AddHotkey('Ctrl+n', function() { tb_show('Nieuwe pagina', '/Pagina/Nieuw'); });
	CasualCMS.AddHotkey('Ctrl+i', function() { tb_show('Pagina instellingen', '/Pagina/Bewerk/' + CasualCMS.URI[0]); });
	CasualCMS.AddHotkey('Ctrl+del', function() { if (confirm('Weet je zeker dat je deze pagina wilt verwijderen?')) { tb_show('Pagina verwijderen', '/Pagina/Verwijder/' + CasualCMS.URI[0]); } });
	CasualCMS.AddHotkey('Ctrl+f1', function() { tb_show('Inhoud bewerken', '/Pagina/Inhoud/' + CasualCMS.URI[0] + '/1/?width=800'); });
	CasualCMS.AddHotkey('Ctrl+f2', function() { tb_show('Inhoud bewerken', '/Pagina/Inhoud/' + CasualCMS.URI[0] + '/2/?width=800'); });
	CasualCMS.AddHotkey('Ctrl+f3', function() { tb_show('Inhoud bewerken', '/Pagina/Inhoud/' + CasualCMS.URI[0] + '/3/?width=800'); });
	CasualCMS.AddHotkey('f1', function() { window.open('/User/Handleiding.pdf'); });
	CasualCMS.AddHotkey('Ctrl+s', function() { $('input[value="Opslaan"]').click(); });
	CasualCMS.AddHotkey('Ctrl+e', function() { tb_remove(); });
});

// Compatible with old functions
function TinyMCESetup(contentCSS, id) { CasualCMS.TinyMCE(contentCSS, id); }

var GoogleTrackEvent = function (category, action, opt_label, opt_value) {
    if (typeof (pageTracker) !== 'undefined') {
        pageTracker._trackEvent(category, action, opt_label, opt_value);
    }
    else if (typeof (_gaq) !== 'undefined') {
        _gaq.push(['_trackEvent', category, action, opt_label, opt_value]);
    }
    else {
        return false;
    }
};
