var ie = document.all ? true : false;
var splitting = false;
var a; 					// left split pane
var s; 					// splitter
var b; 					// right pane
var c; 					// split pane control
var bt; 				// border top
var br; 				// right
var bl; 				// left
var bb; 				// bottom
var cl;					// keep track of click
var lang;				// the current language
var level;				// their level
var ip;					// the current user's ip address
var clipboard;			// for cutting and pasting of folders
var imageclip;			// for pasting images
var currenttitle;		// hoder for image uploads
var tab1 ;
var language;			// language object that holds the translations
var css_urls;			// hold loaded style sheets to not duplicate
var uiconfig;			// hold global ui config
var wym;				// Current editor in edit mode
var notify_options;     // Configuration of jquery notify

function loading(){
	config();
				
	window.onresize = pack;
	document.onmousemove=mv;
	document.onmouseup = dmu;

	a = document.getElementById("pane_a");
	b = document.getElementById("pane_b");
	s = document.getElementById("splitter");
	c = document.getElementById("control");
	pack();
	s.style.left = a.offsetWidth +"px";
	
	css_urls = [];
	
	lang='';
	tab1 = tabs();
	tab1.create(
		{
			name : "demo1",
			target:"tabdiv",
			width : "100%",
			height : "100%",
			info:[
				{label:"Contents" , content: "ctab1",foc : ""},
				{label:"Index" , content: "ctab2",foc : "index"},
				{label:"Search" , content: "ctab3", foc : "keyword"}
			]
		}
	);
		
	if (readCookie('lang')) {
		lang = readCookie('lang');
	} else {
		var langCode = navigator.language || navigator.systemLanguage;
		lang = langCode.toLowerCase(); 
		lang = lang.substr(0,2);				
	}

    notify_options = {
            type: "notice",
            timeout: 3000,
            stick: false,
            fadeSpeed : 800,
            close : "x",
            effect : "fade"
        };


	languages();

	wikilist();
	
	$.getJSON('handlers/getacl.php', loginresponse);
		
	cl="tree";
	clipboard = '';
	imageclip = '';
	crumbs();
	
	$("#toc").contextMenu({
		menu: 'MenuTree'
	},
		function(action, el, pos) {
			switch (action) {
				case 'annotate':
			        $.get("handlers/annotate.php?id="+tree.activenode+"&lang="+lang,getpage);					
					break;
				case 'add':	popup.show('folder_add.php?t=f&lang='+lang, 'treemenu', 'handlers/folder.php?target='+tree.activenode+'&lang='+lang, '220px','folderresponse','validateFolderAdd()');
					break;
				case 'paste':	
					$("#MenuTree").disableContextMenuItems("#paste");				
					popup.show('folder_paste.php?t=f&lang='+lang, 'treemenu', 'handlers/folder.php?target='+tree.activenode+'&lang='+lang+'&clip='+clipboard, '220px','folderresponse','validateFolderPaste()');				
					break;				
				case 'rename':	popup.show('folder_rename.php?t=f&target='+tree.activenode+'&lang='+lang, 'treemenu', 'handlers/folder.php?target='+tree.activenode+'&lang='+lang, '220px','folderresponse','validateFolderRename()');
					break;					
				case 'cut': 
					setclipboard(tree.activenode);
					$("#MenuTree").enableContextMenuItems("#paste");
					break;
				case 'edit':
                    edit(null);
					break;
				case 'delete':	popup.show('folder_delete.php?t=f&lang='+lang, 'treemenu', 'handlers/folder.php?target='+tree.activenode+'&lang='+lang, '220px','folderresponse','validateFolderDelete()');
					break;
				default:
					alert(action+' not yet implemented');				
			}
	});	
	
	
}

function printpage(){
    var content = $('#help').html();
    win = window.open("","mywindow","width=500,height=500");
    self.focus();
    win.document.open();
    win.document.write("<html><head><title>Print Page</title>");
    win.document.write("<link rel='stylesheet' type='text/css' href='theme/default/css/styles.css'><link></head><body id='print'><div id='help'>");
	win.document.write(content);
	win.document.write("</div></body></html>");	    
    win.document.close();
    win.print();
    win.close();
	
}

function setclipboard(id){
	clipboard = id;
}

function dummy(){}

// history related functions
function revert(rev){
	popup.show('revert.php?rev='+rev, 'revform', 'handlers/reverttorev.php?rev='+rev+'&lang='+lang, '220px','revresponse','validaterev()')
}
	
function revresponse(obj){
	if (obj.response == 'ok') {
		tree.click(obj.node);
	}else{
		showError(obj);
	}
}

function validaterev(){
	if( $('#revcomment').val() == ''){
     	$.n.error('Please enter a comment(min 10 characters)!', notify_options);
		return false;
	}
	
	return true;
}
	
function getrev(id,lang){
    $.get("handlers/getrev.php?id="+id+"&lang="+encodeURIComponent(lang),
		function(x){
		    result = jQuery.parseJSON(x);
			if(result.response != 'ok') {
				showError(result);
			} else {
				$('#help').html(result.message);
			}  
		}
    );
}

function gethistory(){
	$('#help').load('handlers/history.php?id='+tree.activenode+'&lang='+lang);
}

function getnodehistory(){	
	$('#help').load('handlers/nodehistory.php?id='+tree.activenode+'&lang='+lang);
}

function profile(){	
    $('#help').load("getprofile.php");
}

function updateprofile()
{
	if(validateprofile()) {

		var params = 'lang=' + encodeURIComponent(lang);
		params += '&email=' + encodeURIComponent(document.getElementById('pemail').value);
		params += '&pass=' + encodeURIComponent(document.getElementById('ppass').value);
		params += '&confirm=' + encodeURIComponent(document.getElementById('pconfirm').value);
		params += '&subscribe=' + encodeURIComponent(document.getElementById('subscribe').value);
		
	    $.post("handlers/updateprofile.php", 
			params, 	    
			function(x){
				result = jQuery.parseJSON(x);
		   		if(result.response != 'ok') {
		   			showError(result);
		   		}
	        }	    
	    );
	}
}

function validateprofile(){
	document.getElementById('subscribe').value= document.getElementById('sub').checked
	return true;
}

function usermanagement()
{
	$.post("handlers/userlist.php",
	       'lang='+lang,
		   function(result){
		   		if(result.response != 'ok') {
		   			showError(result);
		   		} else {
		   			$('#help').html(result.message);
		   		}               
           }
	);
}

function useraction(user_id, action)
{
	switch(action) {
		
		case 'add':
			$.post("handlers/useradd.php",
				       'lang='+lang,
					   function(x){
					   		$('#help').html(x);
			           }
				);				
			break;
			
		case 'edit':
			$.post("handlers/useredit.php",
				       'user_id='+encodeURIComponent(user_id),
					   function(x){
			               $('#help').html(x);
			           }
				);				
			break;
			
		case 'delete':
			$.post("handlers/userdelete.php",
				       'user_id='+encodeURIComponent(user_id),
					   function(x){
			               $('#help').html(x);
			           }
				);		
			break;
	
		case 'view':
			$.post("handlers/userview.php",
				       'user_id='+encodeURIComponent(user_id),
					   function(x){
			               $('#help').html(x);
			           }
				);		
			break;			
	}
}

function useradd()
{
	var params = 'user_name=' + encodeURIComponent(document.getElementById('user_name').value);
	params += '&password=' + encodeURIComponent(document.getElementById('password').value);
	params += '&confirm_password=' + encodeURIComponent(document.getElementById('confirm_password').value);
	params += '&email=' + encodeURIComponent(document.getElementById('email').value);
	params += '&access_level=' + encodeURIComponent(document.getElementById('access_level').value);
	params += '&my_language=' + encodeURIComponent(document.getElementById('my_language').value);
	
	$.post("handlers/useradd.php",
	       params,
		   function(x){
		   		result = jQuery.parseJSON(x);
		   		if(result.response != 'ok') {
		   			showError(result);
		   		} else {
		   			usermanagement();
		   		}
           }
	);
}

function useredit()
{
	var params = 'password=' + encodeURIComponent(document.getElementById('password').value);
	params += '&confirm_password=' + encodeURIComponent(document.getElementById('confirm_password').value);
	params += '&email=' + encodeURIComponent(document.getElementById('email').value);
	params += '&access_level=' + encodeURIComponent(document.getElementById('access_level').value);
	params += '&user_id=' + encodeURIComponent(document.getElementById('user_id').value);
	params += '&my_language=' + encodeURIComponent(document.getElementById('my_language').value);
	
	$.post("handlers/useredit.php",
	       params,
		   function(x){
		   		result = jQuery.parseJSON(x);
		   		if(result.response != 'ok') {
		   			showError(result);
		   		} else {
		   			usermanagement();
		   		}
           }
	);
}

function confirmdeleteuser()
{
	var params = 'user_id_confirm=' + encodeURIComponent(document.getElementById('user_id').value);

	$.post("handlers/userdelete.php",
	       params,
		   function(x){
		   		result = jQuery.parseJSON(x);
		   		if(result.response != 'ok') {
		   			showError(result);
		   		} else {
		   			usermanagement();
		   		}
           }
	);	
}

function indexkey(){
	var pane = document.getElementById('indexpane');
	var text = document.getElementById('index').value;
	var pattern='(tag-'+text+'[a-zA-z0-9_-]+)';

	var re = new RegExp(pattern,"i");

	var m = re.exec(pane.innerHTML.replace("/\n/g"),"");
	if (m != null) {
		var s = m[1];
		pane.scrollTop = document.getElementById(s).offsetTop;
	}
}

function getindex(){
	$.get("handlers/getindex.php?lang="+lang,
	       function(x){
	            var xmlDoc=x.documentElement;
	            var tags = xmlDoc.getElementsByTagName('tag');
	            $('#indexpane').html('');
	            for(var t=0;t<tags.length;t++){
	                var tag=tags[t];
	                var lab = tag.getAttribute('label');
	                $('#indexpane').append("<div id='tag-"+lab.replace(' ','_')+"' class='indextag'>"+lab+"</div>");
	                var nodes = tag.getElementsByTagName('node');
	                for (var n = 0; n < nodes.length; n++) {
	                    var anode = nodes[n];
	                    var nlab = anode.getAttribute('label');
	                    var nid = anode.getAttribute('id');
	                    $('#indexpane').append("<div style='margin-left:20px;'><a href='javascript:indexpage("+nid+",\""+lab+"\")'>"+nlab+"</a></div>");
	                }
	            }
	       }
	);
}


function view_translated(lang)
{
        $.get("handlers/getpage.php?id="+tree.activenode+"&lang="+lang,getpage);		
}

function indexpage(id,lab){
        $.get("handlers/getpage.php?id="+id+"&lang="+lang,
               function(html){
                    $('#help').html(html);
                    RedirectLocation("LocationAnchor", id, "#"+id);
               }
        );

		tree.updateNode(id);
		cl="index";	
}

function annotatesave() {
	$.post('handlers/annotatesave.php?id='+tree.activenode,
				'annotation='+encodeURIComponent(document.getElementById('annotation').value)+"&lang="+lang, annotateupdate);	
}

function annotateupdate(result)
{
	if(result.response != 'ok') {
		showError(result);
	} else {
		$.n.success('Your annotation was saved', notify_options);	
		$('#annotation').text('');	
		$('#annotate_list').append('<div>'+result.message+'</div>');
		
	}  
}

function editsave(source){
		if(source==null)
            source='edittext';

        // restore commas saved in hidden element
        text = wym.xhtml();
        path = '';
        if(document.getElementById('path'))
            path="&path="+document.getElementById('path').value;
        
		$.post('handlers/tagsave.php?id='+tree.activenode,
			'tags='+encodeURIComponent( $('#tagstext').val() ));
		getindex();
		
        parms = "text="+encodeURIComponent(text)+"&id="+tree.activenode+"&lang="+lang+path;
        parms += "&comment="+encodeURIComponent(document.getElementById('commente').value);
        $.post("handlers/editsave.php",
               parms,
               function(html){
	                var reload = false; 
					var path = '';
	                if (document.getElementById('path')) {
	                    reload = true;
	                    path = document.getElementById('path').value;
	                }
					if (html != 'error')
						$.n.success('Your modification was saved', notify_options);
					getpage(html);
	                if (reload) {
	                    tree.getTree('handlers/gettree.php?lang=' + lang, 'tree');
	                    pageFromPath(path);
	                }
               }
        );      
		$.get("handlers/gettags.php?id="+tree.activenode,tagsupdate);		
				
}

function edit(path){
		var pathinfo;
		var nodeid = tree.activenode;
		if (path == null) {
			pathinfo = '';
		}else {
			pathinfo = "&path="+path;
			//nodeid = -1;
		}			
		
	    $.get("handlers/editpage.php?id="+nodeid+pathinfo+"&lang="+lang+"&clip="+encodeURIComponent(imageclip),
	           function(x){
	                var html=x;    
	                var id=tree.activenode;
	                document.getElementById('help').innerHTML = html;
	                RedirectLocation("LocationAnchor", id, "#"+id);
				    jQuery(".wymeditor").wymeditor({
						 stylesheet: 'theme/default/css/styles.css',
						 lang: lang,								
						postInit: function(wym1) {
							wym =  wym1;
							jQuery(wym._box).find(wym._options.containersSelector)
								.removeClass('wym_dropdown')
								.addClass('wym_panel')
								.find('h2 > span')
								.remove();
							jQuery(wym._box).find(wym._options.iframeSelector)
								.css('height', '250px');
						}
					});				
	           }
	    );
}

function sysclipboard(clip){
	imageclip = clip;
}

function validateupload(title){
	currenttitle = title;
	setTimeout(imagepage, 2000);
}

function insertimage(){
	var edittext = document.getElementById('edittext');
	//IE
	if (document.selection) {
		edittext.focus();
		var sel = document.selection.createRange();
		sel.text = "uri/"+imageclip;
	}
	//Mozilla
	else if (edittext.selectionStart || edittext.selectionStart == '0') {
		var startPos = edittext.selectionStart;
		var endPos = edittext.selectionEnd;
		edittext.value = edittext.value.substring(0, startPos)
	              + "uri/"+imageclip
	              + edittext.value.substring(endPos, edittext.value.length);
	} else {
	
		edittext.value += imageclip;
	 
	}
	
}

function imagepage(){
	// save editor content
	if(document.getElementById('edittext')){
		var pre = document.getElementById('edittext').value;
	
		// commas get lost if we don't convert them first
		document.getElementById('previewtext').value = pre.replace(/'/g,"&#39;");		
	}
	
	$.get("handlers/imagepage.php?id="+tree.activenode+"&lang="+lang+"&title="+encodeURIComponent(tree.activetitle),
		   function(x){
			   	$('#help').html(x);
                var id=tree.activenode;
                RedirectLocation("LocationAnchor", id, "#"+id);		   	
		   }
	);
}

function treedblclk(src,t){ // t = type folder or leaf
/*		var type='folder';
		type = t == 0 	? 'folder' : 'page';
		if (level != 'reader') {
			popup.show('foldermenu.php?t='+type+'&lang='+lang, 'treemenu', 'handlers/folder.php?target='+src+'&lang='+lang+'&clip='+clipboard, '220px','folderresponse','validateFolder()');
		} */
}

function folderresponse(obj){
	if(obj.response=='ok'){
		if(clipboard == ''){
			if(obj.node==-1){ // removed node
				tree.getTree('handlers/gettree.php?lang='+lang,'tree');				
			}else{
				tree.getTree('handlers/gettree.php?lang='+lang,'tree',obj.node);				
			}
			
		}
	}else{
 		showError(result);
 	}
	
}

function home(x) {
	tree.click(tree.home)	
}

function getpage(x) {
	$('#help').html(x);
    $("#help img[title]").each(function(){
		var image = $(this);
		image.wrap("<div class='caption'></div>");
		var div = $(this).parent().append('<p>' + image.attr('title') + '</p>');
	});
	RedirectLocation("LocationAnchor", tree.activenode, "#"+tree.activenode);		
}

function logout(){
	    $.getJSON("handlers/logout.php", loginresponse);
		getip();	
        $.get("handlers/getpage.php?id="+tree.activenode+"&lang="+lang,getpage);
		$.n.warning(language.login.logged_out + '.', notify_options);
		
}

function loginform(){
	popup.show('login.php?lang='+lang, 'login', 'handlers/login.php', '400px','loginresponse', 'validateLogin()', true);
}

function registerform(){
	popup.show('register.php?lang='+lang, 'register', 'handlers/register.php', '400px','registerresponse','validateRegister()')
}

function loginresponse(obj){
	if (obj.response == 'ok') {
		$('#status').html(obj.user+'@'+obj.ip);
	
		if (obj.user == 'anonymous') {
			$('#logoutmenu').hide();
			$('#profilemenu').hide();			
			$('#menuseparator1').show();						
			$('#menuseparator2').show();	
			$('#loginmenu').show();
			$('#registermenu').show();														
		} else {
			$('#logoutmenu').show();
			$('#profilemenu').show();
			$('#loginmenu').hide();
			$('#registermenu').hide();				
		}
		
        $('#adminmenu').hide();	
		$('#usermanagementmenu').hide();					
		$('#editmenu').hide();			
		$("#MenuTree").disableContextMenuItems(null);			
		
		switch (obj.level) {
			case 'admin':			
				$('#adminmenu').show();
				$('#usermanagementmenu').show();			
				$("#MenuTree").enableContextMenuItems("#delete");
			case 'author':
				$("#MenuTree").enableContextMenuItems("#add,#edit,#rename,#cut");
				$('#editmenu').show();						
			case 'contributor':
				$("#MenuTree").enableContextMenuItems("#annotate");				
			case 'reader':
		
		}
		level = obj.level;
		$.n.success(language.login.login_as + ' ' + obj.user + '.' +  language.login.security_level + ' ' + level + '.', notify_options);		

	}else{
		showError(obj);
	}
}

function registerresponse(obj){
	loginresponse(obj);
}

function getip(){
    $.get("handlers/ip.php",
          function(x){
                var obj = eval('(' + x + ')');
                document.getElementById('status').innerHTML += obj.ip;
		  }
	);
	return false;	
}

function changelanguage(langsel){
	$('.langsel').fadeTo("slow", 0.5);
	$('#langsel_'+langsel).fadeTo("slow", 1);
	lang = langsel;
	var date = new Date();
	date.setTime(date.getTime()+(30*24*60*60*1000)); // expire in 30 days
	document.cookie = "lang="+lang+"; expires="+date.toGMTString();

    $.getJSON("language/"+lang+".json",
          function(obj){
			    // Translating main menu
				$('#logina').html(obj.menu.login);
				$('#logouta').html(obj.menu.logout);
				$('#registera').html(obj.menu.register);
				$('#profila').html(obj.menu.profile);
				$('#edita').html(obj.menu.edit);
				$('#historya').html(obj.menu.history);
				$('#printa').html(obj.print);
				$('#usermanagementmenu').html(obj.menu.usermanagement);
				
				// Context menu
				$('#cm_add').html(obj.node.add);
				$('#cm_annotate').html(obj.node.annotate);
				$('#cm_delete').html(obj.node.remove);
				$('#cm_cut').html(obj.node.cut);
				$('#cm_paste').html(obj.node.paste);
				$('#cm_edit').html(obj.node.edit);
				$('#cm_rename').html(obj.node.rename);
				// powered_by
				$('#powered_by').html(obj.powered_by);
				// Treeview
                tab1.setLabel(0,obj.tabs.contents);
                tab1.setLabel(1,obj.tabs.index);
                $('#indextype').html(obj.tabs.type);
                tab1.setLabel(2,obj.tabs.search);
				$('#searchtype').html(obj.tabs.type);
				
                $('#searchlist').val(obj.tabs.list);
                language = obj;

				// Tree and page
                tree.getTree('handlers/gettree.php?lang='+lang,'tree');
                getindex();
                crumbs();
                search();		  	
		  }
    );
	return false;
}

function languages()
{
    $.getJSON("language/languages.json",
         function(obj){             
            for ( var i=0; i < obj.languages.length; i++ ){
				$('#lang').append('<img class="langsel" id="langsel_'+obj.languages[i].symbol+ '" src="images/flags/'+obj.languages[i].symbol+".png\" onclick=\"javascript:changelanguage('"+obj.languages[i].symbol+"');\" title=\""+obj.languages[i].text+"\" /> ") ;
            }  
	        changelanguage(lang);
		 }
	);
}


function wikilist(){
/*	
    $.get("handlers/wikilist.php",
          function(x){		  
                var obj = eval('(' + x + ')');
	            var html = '';
	            for ( var i=0; i < obj.wikilist.length; i++ ){
	                 html+= "<option value='"+obj.wikilist[i].id+"'>"+obj.wikilist[i].name+"</option>" ;
	            }  			
				var wlist = document.getElementById('wikilist');
	            wlist.innerHTML = '<select id="wiki" onchange="dummy();">'+html+'</select>'; // ie hack									
		  }
	);
	*/
	return false;	
}


function config(){
    $.get("handlers/config.php",
          function(x){		  
                var obj = eval('(' + x + ')');
				uiconfig = obj;
				if (!uiconfig.can_register) {
					document.getElementById('registermenu').style.display = 'none';		
				}
				if (!uiconfig.can_login) {
					document.getElementById('loginmenu').style.display = 'none';		
				}
				if (!uiconfig.can_login && !uiconfig.can_register) {
					document.getElementById('menuseparator2').style.display = 'none';						
				}
				if (!uiconfig.can_switch_lang) {
					document.getElementById('lang').style.display = 'none';
					document.getElementById('menuseparator1').style.display = 'none';						
				}		
				if (uiconfig.title != '') {
					document.getElementById('wiki_title').innerHTML = uiconfig.title;
				}											
		  }
	);
	return false;	
}

// Resize

function pack(){
	
	c.style.height = "auto";
	s.style.height = "auto";
	b.style.height = "auto";
	a.style.overflow = "hidden"; // prevents flicker
	b.style.overflow = "hidden";
	
	
    if (c.currentStyle) {
		bt = parseInt(c.currentStyle.borderTopWidth);
		br = parseInt(c.currentStyle.borderRightWidth);
		bb = parseInt(c.currentStyle.borderBottomWidth);
		bl = parseInt(c.currentStyle.borderLeftWidth);
	}
	else if (window.getComputedStyle) {
		bt = parseInt(document.defaultView.getComputedStyle(c, null).getPropertyValue('border-top-width'));
		br = parseInt(document.defaultView.getComputedStyle(c, null).getPropertyValue('border-right-width'));
		bb = parseInt(document.defaultView.getComputedStyle(c, null).getPropertyValue('border-bottom-width'));
		bl = parseInt(document.defaultView.getComputedStyle(c, null).getPropertyValue('border-left-width'));
	}
	
	b.style.width = Math.max(0,c.offsetWidth - a.offsetWidth - s.offsetWidth-bl-br) + "px";
	c.style.height = (Math.max(document.body.clientHeight, document.documentElement.clientHeight)
			- c.offsetTop - 38 -bt-bb ) +"px";

	var h = c.offsetHeight -bt-bb;
	
	b.style.height = h+"px";
	a.style.height = h+"px";
	s.style.height = h+"px";
	
	// nudge
	c.style.width = (Math.max(document.body.clientWidth, document.documentElement.clientWidth)-16-bl-br) +"px";
	b.style.width = Math.max(0,c.offsetWidth - a.offsetWidth - s.offsetWidth-bl-br) + "px";

	a.style.overflow = "hidden";
	b.style.overflow = "auto";
}

// Split Pane Control

function md(e){
	splitting = true;
	document.body.onselectstart = function(){return false;};
	a.style.overflow = "hidden";
	b.style.overflow = "hidden";
}

function mv(e){
	if(!splitting) return;
	var l = ie ? event.clientX + document.body.scrollLeft : e.pageX;
	l = Math.max(Math.min(l -c.offsetLeft - s.offsetWidth, c.offsetWidth - 15), 0);
	s.style.left = Math.max(0,l) + "px";
	a.style.width = Math.max(0,l) + "px";
	b.style.width = (c.offsetWidth - a.offsetWidth - s.offsetWidth-bl-br) + "px";
}

function mu(e){
	splitting = false;
	document.body.onselectstart = function(){return true;};
	b.style.overflow = "auto";
}

function dmu(e){
	if(!splitting) return true;
	var l = ie ? event.clientX + document.body.scrollLeft : e.pageX;
	if(s.offsetLeft > l) mu(e); 
}

// Search functions

function search(){
    $.post("handlers/search.php?lang="+lang,
          "search="+encodeURIComponent( $('#keyword').val() ),
          function(x){
            var list = '';
            $(x).find('file').each(function(){
				$("#searchresult").append("<div class='list' onclick='searchClick(\""
                             + $(this).attr('name') +"\")'>"
                             + $(this).attr('title') +"</div>");
			 });		  	
          }
    );
	return false;
}

function searchClick(file){
		$.get("handlers/getpage.php?id="+file+"&lang="+lang,
			  function(html){
                    var words = $('#keyword').val().split(" ");
                    for (var i=0;i<words.length;i++){
                        var word=words[i];
                        // highlight the word ignoring elements
                        pattern = "(" + word + ")(?=[^>]*<)";
                        html = html.replace(new RegExp(pattern,"gi"), "<span style='background:#ffff00;display:inline-block;'>$1</span>")
                    }
                    $('#help').html(html);
                    RedirectLocation("LocationAnchor", file, "#"+file);			  	
			  }
		);
		tree.updateNode(file);
		cl = "search";
}


// Navigation functions

var last='';
function CheckForHash(){
	if(document.location.hash){ 
		var HashLocationName = document.location.hash;
		HashLocationName = HashLocationName.replace("#","");
		if(last==HashLocationName) return;
		
		if(HashLocationName != tree.activenode) tree.click(HashLocationName);
		crumbs();
		last=HashLocationName;
	}
}

function RenameAnchor(anchorid, anchorname){
	document.getElementById(anchorid).name = anchorname; //this renames the anchor
}

function RedirectLocation(anchorid, anchorname, HashName){
	RenameAnchor(anchorid, anchorname);
	document.location.hash = HashName;
}

// validation


function validateLogin(){
	 // email
    $("#user").removeClass('error');			 
    $("#pass").removeClass('error');		

	var element = document.getElementById('user');
	if (element.value=='') {
	  $("#user").addClass('error');		
   	  $.n.error('Please provide a username.', notify_options);
	  element.focus()
	  element.select();
	  return false;
	}
	
    element = document.getElementById('pass');
	if (element.value=='') {
	  $("#pass").addClass('error');			
   	  $.n.error('Please provide a password.', notify_options);
	  element.focus()
	  element.select();
	  return false;
	}

	return true;
}


function validateRegister(){
	 // email
    $("#user").removeClass('error');			 
    $("#pass").removeClass('error');			 
    $("#confirm").removeClass('error');			 	
    $("#email").removeClass('error');			 	  
	var element = document.getElementById('user');
	if ((element.value=='') || (element.value.length < 6) || (element.value.length > 32)) {
	  $("#user").addClass('error');		
   	  $.n.error('Please provide a user name (lenght must be between 6 and 32 characters)', notify_options);
	  element.focus();
	  element.select();
	  return false;
	}
	
	element = document.getElementById('pass');
	if ((element.value=='') || (element.value.length < 6) || (element.value.length > 32)) {
	  $("#pass").addClass('error');			
   	  $.n.error('Please provide a password (lenght must be between 6 and 32 characters)', notify_options);
	  element.focus();
	  element.select();
	  return false;
	}
	
	element = document.getElementById('confirm');
	if(element.value=='' || element.value != document.getElementById('pass').value){
	  $("#pass").addClass('error');			
	  $("#confirm").addClass('error');					
   	  $.n.error('Password and Confirmation must match.', notify_options);
	  element.focus();
	  element.select();
	  return false;
	}
	
	element = document.getElementById('email');
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (element.value=='' || !filter.test(element.value)) {
   	  $.n.error('Please provide a valid email address', notify_options);
	  $("#email").addClass('error');						  
	  element.focus();
	  element.select();
	  return false;
	}
	
	return true;
}

function validateFolderDelete(){
	var comment = document.getElementById("commentf");
	
	if(comment.value.length < 10){
      $.n.error('Please enter reason for deletion (min 10 characters)', notify_options);			
	  comment.focus()
	  comment.select();
	  return false;		
	}
	return true;	
}

function validateFolderAdd(){
	
	var pos = document.getElementById('position');
	if(document.getElementById('before').checked) pos.value = "before";
	if(document.getElementById('after').checked) pos.value = "after";
	if(document.getElementById('in').checked) pos.value = "in";	
	return true;
	
}

function validateFolderRename(){	
	var n = document.getElementById("fname");
	return true;	
}

function validateFolderPaste(){
	var n = document.getElementById("fname");
	if(n.value==''){
	  $.n.error('please enter a name', notify_options);			
	  n.focus();
	  n.select();
	  return false;
	}		
	
	var pos = document.getElementById('position');
	if(document.getElementById('before').checked) pos.value = "before";
	if(document.getElementById('after').checked) pos.value = "after";
	if(document.getElementById('in').checked) pos.value = "in";	
	clipboard = '';
	return true;
	
}

function validateFolder(){
	var n = document.getElementById("fname");
	
	var ap = document.getElementById("faddpage");
	var p = document.getElementById("fpaste");
	
	var r = document.getElementById("fremovefolder");
	var rn = document.getElementById("frename");
	var c = document.getElementById("fcut");
	
	var comment = document.getElementById("commentf");

	if(ap.checked || rn.checked){
		if(n.value==''){
		  $.n.error('please enter a name', notify_options);			
		  n.focus();
		  n.select();
		  return false;
		}		
	}
	
	if(r.checked && user=='anonymous'){
	$.n.error('You do not have permission to remove folders!', notify_options);			
	  return false;		
	}
	
	if(r.checked && comment.value.length < 10){
      $.n.error('Please enter reason for deletion (min 10 characters)', notify_options);			
	  comment.focus()
	  comment.select();
	  return false;		
	}
	
	var action = document.getElementById('action');
	
	if(ap.checked) action.value = "addpage";
	if (p.checked) {
		if (clipboard == '') {
			$.n.error('Clipboard is empty!', notify_options);			
			return false;
		}
		action.value = "paste";
	}
	
	if(r.checked) action.value = "remove";
	if(rn.checked) action.value = "rename";
	if (c.checked) {
		action.value = "cut";
		clipboard = tree.activenode;
	}else{
		if(action.value == 'paste') clipboard = ''; // clipboard parameter already set in treedblckl()
	}
	
	var pos = document.getElementById('position');
	if(document.getElementById('before').checked) pos.value = "before";
	if(document.getElementById('after').checked) pos.value = "after";
	// $('#in').is(':checked')
	if(document.getElementById('in').checked) pos.value = "in";		
	
	return true;
}

// utility

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function pageFromPath(path){

    $.post("handlers/pageFromPath.php",
           'lang='+lang+"&path="+encodeURIComponent(path),
           function(x){
	            var id=x.replace(/^\s+|\s+$/g, ''); //trim
	
	            if(id > 0){
	                tree.click(id);
	            }else{
	                if(id==-1){
	                    edit(path);
	                }
	            }
           }
    );    
}

function adminpage(){
    $.post("handlers/adminpage.php",
	       'lang='+lang+"&page="+tree.activenode,
		   function(x){
				$('#help').html(x);			   
           }
	);    
}

function show_about(){
	$('#help').load('about.'+lang+'.php');
}

function lockpage(box){

    var lock = box.checked;
    $.post("handlers/lockpage.php",'lock='+lock+"&page="+tree.activenode, lockupdate);
}

function lockall(lock){

    $.post("handlers/lockpage.php",'lock='+lock+"&page="+tree.activenode+"&all=true",adminpage);
}

function clearhistory(all){
    var pages = all ? "all pages" : "the current page" ;
    if(!confirm("This will clear all history for "+pages+"!!! This can not be undone.  Are you sure?"))
       return;
	   
	$.post("handlers/clearhistory.php","page="+tree.activenode+"&all="+all,adminpage);       
}

function purge(){
    if(!confirm("This will purge all deleted pages. This can not be undone.  Are you sure?"))
       return;
       
    $.post("handlers/purge.php",null,adminpage);       
}

function crumbs(){
	var c = tree.crumbs;
	if(c.length==0) setTimeout("crumbs()",50);
	var html = '';
	for(var i=0; i< c.length; i++){
		var crumb = c[i];
		if(i>0) html+="<div class='crumbsep'>:</div>";
		var click = i==(c.length-1) ? "" : "onclick='tree.click(\""+crumb.ref+"\")'";
		var cls = i==(c.length-1) ? "endcrumb" : "crumb";
		
		html+="<div class='"+cls+"'"+click+">"+crumb.label+"</div>";
	}
	html += "<div id='tagscrumb' class='tagscrumb'></div>";
	$("#crumbs").html(html);

	if (tree.activenode != '') {
		$.get("handlers/gettags.php?id="+tree.activenode,tagsupdate);
	}
}

function tagsupdate(result)
{
	if(result.response != 'ok') {
		showError(result);
	} else {
		$('#tagscrumb').html(result.message);
	}  
}

function lockupdate(result)
{
    if(result.response != 'ok') {
		showError(result);
	} else {
	    $.n.success(result.message, notify_options);
	}
}

/*
$.n("", options) - to show a notifice notification
$.n.success("", options) - to show a success notification
$.n.warning("", options) - to show a warning notification
$.n.error("", options) - to show an error notifcation
*/
function showError(result)
{
	switch(result.response) {
		case 'error':
			$.n.error(result.message, notify_options);
			break;
		case 'notice':
			$.n.warning(result.message, notify_options);
			break;
		case 'message':
			$.n.success(result.message, notify_options);
			break;
	}
}

var HashCheckInterval = setInterval("CheckForHash()", 250);
