//
// MoinMoin commonly used JavaScript functions
//

// We keep here the state of the search box
searchIsDisabled = false;

function searchChange(e) {
    // Update search buttons status according to search box content.
    // Ignore empty or whitespace search term.
    var value = e.value.replace(/\s+/, '');
    if (value == '' || searchIsDisabled) { 
        searchSetDisabled(true);
    } else {
        searchSetDisabled(false);
    }
}

function searchSetDisabled(flag) {
    // Enable or disable search
    document.getElementById('fullsearch').disabled = flag;
    document.getElementById('titlesearch').disabled = flag;
}

function searchFocus(e) {
    // Update search input content on focus
    if (e.value == search_hint) {
        e.value = '';
        e.className = '';
        searchIsDisabled = false;
    }
}

function searchBlur(e) {
    // Update search input content on blur
    if (e.value == '') {
        e.value = search_hint;
        e.className = 'disabled';
        searchIsDisabled = true;
    }
}

function actionsMenuInit(title) {
    // Initialize action menu
    for (i = 0; i < document.forms.length; i++) {
        var form = document.forms[i];
        if (form.className == 'actionsmenu') {
            // Check if this form needs update
            var div = form.getElementsByTagName('div')[0];
            var label = div.getElementsByTagName('label')[0];
            if (label) {
                // This is the first time: remove label and do buton.
                div.removeChild(label);
                var dobutton = div.getElementsByTagName('input')[0];
                div.removeChild(dobutton);
                // and add menu title
                var select = div.getElementsByTagName('select')[0];
                var item = document.createElement('option');
                item.appendChild(document.createTextNode(title));
                item.value = 'show';
                select.insertBefore(item, select.options[0]);
                select.selectedIndex = 0;
            }
        }
    }
}

// use this instead of assigning to window.onload directly:
function addLoadEvent(func) {
  // alert("addLoadEvent " + func)
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function can_use_gui_editor() {
    var sAgent = navigator.userAgent.toLowerCase() ;

    // Internet Explorer
    if ( sAgent.indexOf("msie") != -1 && sAgent.indexOf("mac") == -1 && sAgent.indexOf("opera") == -1 )
    {   
        var sBrowserVersion = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
        return ( sBrowserVersion >= 5.5 ) ;
    }
    
    // Gecko
    if ( navigator.product == "Gecko" && navigator.productSub >= 20030210 )
        return true ;

    // Opera
    if ( this.EnableOpera )
    {   
        var aMatch = sAgent.match( /^opera\/(\d+\.\d+)/ ) ;
        if ( aMatch && aMatch[1] >= 9.0 )
            return true ;
    }
    
    // Safari
    if ( this.EnableSafari && sAgent.indexOf( 'safari' ) != -1 )
        return ( sAgent.match( /safari\/(\d+)/ )[1] >= 312 ) ;  // Build must be at least 312 (1.3)

    return false ;

}


function update_edit_links() {
    // Update editlink according if if the browser is compatible
    if (can_use_gui_editor() == false){
        //alert("update_edit_links: can't use gui editor");
        return;
    }
    var editlinks = document.getElementsByName("editlink");
    for (i = 0; i < editlinks.length; i++) {
        var link = editlinks[i];
        href = link.href.replace('editor=textonly','editor=guipossible');
        link.href = href;
        //alert("update_edit_links: modified to guipossible");
    }
}


function add_gui_editor_links() {
    // Add gui editor link after the text editor link
    
    // If the variable is not set or browser is not compatible, exit
    try {gui_editor_link_href}
    catch (e) {
        //alert("add_gui_editor_links: gui_editor_link_href not here");
        return
    }
    if (can_use_gui_editor() == false){
        //alert("add_gui_editor_links: can't use gui_editor");
        return;
    }
    var all = document.getElementsByName('texteditlink');
    for (i = 0; i < all.length; i++) {
        var textEditorLink = all[i];
        // Create a list item with a link
        var guiEditorLink = document.createElement('a');
        guiEditorLink.href = gui_editor_link_href;
        var text = document.createTextNode(gui_editor_link_text);
        guiEditorLink.appendChild(text);
        var listItem = document.createElement('li')
        listItem.appendChild(guiEditorLink);
        // Insert in the editbar
        var editbar = textEditorLink.parentNode.parentNode
        var nextListItem = textEditorLink.parentNode.nextSibling;
        editbar.insertBefore(listItem, nextListItem);
        //alert("add_gui_editor_links: added gui editor link");
    }
}
 

function show_switch2gui() {
    // Show switch to gui editor link if the browser is compatible
    if (can_use_gui_editor() == false) return;
    
    var switch2gui = document.getElementById('switch2gui')
    if (switch2gui) {
        switch2gui.style.display = 'inline';
    }
}

function toggleComments() {
    // Toggle visibility of every tag with class == *comment*
    var all = document.getElementsByTagName('*');
    for (i = 0; i < all.length; i++){
        el = all[i];
        if ( el.className.indexOf('comment') >= 0 ){
            if ( el.style.display != 'none' ) {
                el.style.display = 'none';
            } else {
                el.style.display = '';
            }
        }
    }
}

function load() {
    // Do not name this "onload", it does not work with IE :-)
    // TODO: create separate onload for each type of view and set the
    // correct function name in the html. 
    // e.g <body onlod='editor_onload()'>

    // login focus
    if (document.forms['loginform']) {
    	document.forms['loginform'].elements['name'].focus();
    }
    
    // Page view stuff
    update_edit_links();
    add_gui_editor_links();
    
    // Editor stuff
    show_switch2gui();
}


function before_unload(evt) {
    // TODO: Better to set this in the editor html, as it does not make
    // sense elsehwere.
    // confirmleaving is available when editing
    try {return confirmleaving();}
    catch (e) {}
}

// Initialize after loading the page
addLoadEvent(load)

// Catch before unloading the page
window.onbeforeunload = before_unload

/* ----- Sidebar -------- */
function sidebarToggle()
{
    this.rightarrow = new Image();
//        "/moinmoin/ls_stardust/img/2rightarrow.png";
    this.rightarrow.src = 'data:image/png;base64,' +
		'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/' +
		'oL2nkwAAAAlwSFlzAAALCwAACwsBbQSEtwAAAAd0SU1FB9cMGRcvOAh5RiUAAAL6SURBVDjLfZNfaFNX' +
		'HMc/99ybm5s0cc2/rZ0kjTYsFGoRpDJltKy+jLpZyxSHUPClThF88EHwTcSHPZQ++CDIBV86xmTDrWzC' +
		'HgZqN+ZDS1uqi3RtfSgxpEmapjVJe9vkHh9ubTfQ/eDAOQc+v/P9nnO+Cm+pUjhs2NBpQ0JKqdQVZWHV' +
		'7R4f6u2tmqbJO6sUDvvWgsFv1kOhkty7V9YOH5aVY8ekbG6W5WCwtBSJ3HkajcYGBwd3GOVfcJOAR/5o' +
		'NGldGES0fgSAvfAPAOr7zWjDwxRTqcJiY+Pp2z09j0zTRAVYCYV8qpR/+bu6kvV793B9fITaw9+RK8to' +
		'x0/g+rSHrbGHyP4vcdfrXs/09BeBYnHEOHmyLACkolz3t7Qkty5dQo1EQNdxnR34jz33+YuOmnPnCBw4' +
		'EEouL18HdDUfChmGlN+5BgaMWiCAzOVQ43EUXUfsa6U2eh8lFkc0NKAd6qT22wM2WmIYf/yZfIX9rQA6' +
		'G9zu96ymCOSz2LMprNFRAEQwiOtEP7WffqT+8uWOEt9iGr/L5evIZI8KIEE4jMwsITNL2PkC9rMZrJER' +
		'p0lTE67PjqNeuwbT046fW7fA60WDhAYo2DaeuTkwDNB1KJehr3/HvxgagsZGOHjQ2dhuZAshtLqiLFAq' +
		'QaGwe2PDw9De7swvX949FWBmBq5cgWqVyp49abHqdo9X1tdXEQKEcOCOjv+HNY1XW1uViVhsSgz19lYr' +
		'qnqXXM6R+Qa+cQOyWej6xFmnUnDzJgSDkMuRNYxfUvF4RgF4Go0GPrCscX93d6vW7QAyNbv7Xfv6kNsv' +
		'U8/nWRsbS3/f3v7Vs/37x1WA2pkzG4lM5oFnfv5zNjYDqteH4vWCx+OMxUWkYWDNz1N+8iT9a1vb11OJ' +
		'xARQVQEmJyfh1KmVUKHwQ8PcnF/OziYty9JltUqtWKT64gWbjx9X8un0/Z/b2q5uw2umae6GCWA7ZfqR' +
		'539/2JHJHtUgYQshKqqanojFplLxeAZYBjbfxPo1shgu8H619DUAAAAASUVORK5CYII=';

    this.leftarrow = new Image();
//        "/moinmoin/ls_stardust/img/2leftarrow.png";
    this.leftarrow.src = 'data:image/png;base64,' +
		'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/' +
		'oL2nkwAAAAlwSFlzAAALCQAACwkBEvpHPgAAAAd0SU1FB9cMGRcxLMbirYcAAAL0SURBVDjLdZNdaJtl' +
		'FMd/7/MmfZOuWds0o+k0sXPZsoKfFy3odDilKgPdGHo1RLx4t4vBQISiF4JsyvyoHQynzhcGs34xYQgK' +
		'gowyN9FtLe26dinOZd1q1qVJm6bNkrT5eI8XWZsN6v/mcM5zfufAOc/RWEHpFp/LhnYbQiKilTUtOmcY' +
		'/d2d23KWZfG/Srf46uabvR/m/U1pab1PSps7JPvCcyLBFrnd7E1PrV1zdGRdIGia5jKj3QX7FZz2BAJh' +
		'9u6jvHUr9pWr1cR8BsehHlJjkemJ1Q2vfr7l2dOWZaEDzPqb6nSRPz1PbwkXP/4UwpsofN+L8/kX0VZ7' +
		'0LyNFPtOoX/Ug/NmrNZ96eJLjalUr2v7jtsApFp83dLxuBT6Tknx3F+SO7hflrTklzMZEREpTVwXu/MZ' +
		'uXF/81HTNGv0pL/J5RL5zrnrNVfJ20i5/xzut98FoJxMUjx5AmP3XlR9fSU2PIwugrpwPpwp2984gPZV' +
		'hlGfr3FAZLQKT96k8PUxjDdMlNcLQL73OO7r4wB4nM66RxLxJx1ACJ8PYBm2/52g8O1xjF2vo5r9lSke' +
		'eA/33SurrcVhS8gBaNg27o1ty2/qxA+4Z2YhEKwEhi+uuHZbKaXKmhYlnYavvqwmvtVVsW/uq9hHH4OX' +
		'd1TJs2cglyOr6zE1Zxj92Xx+DqXgnS4YuVRJ+qRn5SKpFDgcZIrF7EAgOKS6O7flsrp+jGQCGhrg4Psw' +
		'FqlAhw7DVBw+2F8tsvkpSCaIG66fI4HWSWVZFgnDdSB561Z0ASj61lD84ggyHkXGoxV/aorSkcMALFwe' +
		'JRGPx34Nhz8DZjQA0zTZfaZv/QO57G+u9o4HjYceRtO0ewYmIiyOjpDrvxD7ZcOmPefXb/gDmNcBBgcH' +
		'Yecrs03T0z+uiv7jkSt/hxcXFmskn6M0myJ37RqFs79nk7HYyZ/a2rqG1oUGgHnLsrinzZ0rq3li7PLa' +
		'O58kZCulsroeGwgEhyKB1klgBigsnfV/TYhQd6dK9y0AAAAASUVORK5CYII=';

    this.sidebar = document.getElementById("ls_sidebar");
    this.sidebar.style.overflow = "hidden";
    this.sidebar.style.whiteSpace = "nowrap";

    this.wrapper = document.getElementById("ls_wrapper");
    this.content = document.getElementById("ls_content");
    this.button  = document.getElementById("toggleButton");
    this.link    = document.getElementById("toggleLink");

    this.slideTime = 300;
    this.sidebarWidth = 270;

    // "out" or "in", based on cookie value;
    this.cookie = sidebarToggle.getCookie("wikisidebar");

    var my = this;
    sidebarToggle.dotask(window, function()
                         {sidebarToggle.setCookie("wikisidebar", my.cookie)}, "unload")
    sidebarToggle.dotask(window, function()
                         {sidebarToggle.setCookie("wikisidebar", my.cookie)}, "beforeunload")
}

sidebarToggle.prototype.toggle = function()
{
    if (this.cookie == "out") {
        this.sidebar.style.width = this.sidebarWidth+"px";
        this.slidein();
    } else {
        this.sidebar.style.width = 0;
        this.slideout();
    }
    this.link.blur();
}

sidebarToggle.prototype._slideengine = function(direction)
{
    //get time animation has run
    var elapsed = new Date().getTime() - this.startTime;
    var my = this;
    var gap = 30;

    if (elapsed > this.slideTime/2.0) { 
        if (direction == "out") {
            this.button.src = this.rightarrow.src;
        } else {
            this.button.src = this.leftarrow.src;
        }
    }

    if (elapsed < this.slideTime) { 
        var distancepercent = sidebarToggle.curveincrement(elapsed / 
                                                           this.slideTime);
        if (direction == "in") {
            distancepercent = 1.0 - distancepercent;
        }
        var distance = distancepercent * this.sidebarWidth;

        this.sidebar.style.width  = distance +"px";
        this.wrapper.style.marginLeft = -distance - gap +"px";
        this.content.style.marginLeft =  distance + gap +"px";

        this.runtimer = setTimeout(function() {my._slideengine(direction)}, 10);

    } else { 
        // animation is finished
        if (direction == "out") {
            this.wrapper.style.marginLeft = "-300px";
            this.content.style.marginLeft = "300px";
            this.sidebar.style.width      = this.sidebarWidth+"px";
        } else {
            this.wrapper.style.marginLeft = -gap+"px";
            this.content.style.marginLeft = gap+"px";
            this.sidebar.style.width      = "0px";
//            this.sidebar.style.visibility = "hidden";
        }

        //remember whether content is expanded or not
        this.cookie   = direction;
        this.runtimer = null;
    }
}

sidebarToggle.prototype.slideout = function()
{
    if (typeof this.runtimer == "undefined" || this.runtimer == null) { 
        if (parseInt(this.sidebar.style.width) == 0) { 
            //if content is collapsed
            this.startTime = new Date().getTime();
            this._slideengine("out");
        }
    }
}

sidebarToggle.prototype.slidein = function()
{
    if (typeof this.runtimer == "undefined" || this.runtimer == null) { 
        if (parseInt(this.sidebar.style.width) == this.sidebarWidth) { 
            //if content is expanded
            this.startTime = new Date().getTime();
            this._slideengine("in");
        }
    }
}

// -------------------------------------------------------------------
// A few utility functions below:
// -------------------------------------------------------------------

sidebarToggle.curveincrement = function(percent) 
{
    //return cos curve based value from a percentage input
    return (1 - Math.cos(percent*Math.PI)) / 2; 
}

//assign a function to execute to an event handler (ie: onunload)
sidebarToggle.dotask = function(target, functionref, tasktype)
{ 
    var tasktype = (window.addEventListener) ? tasktype : "on"+tasktype;

    if (target.addEventListener) {
        target.addEventListener(tasktype, functionref, false);
    } else if (target.attachEvent) {
        target.attachEvent(tasktype, functionref);
    }
}

sidebarToggle.getCookie = function(name)
{ 
    //construct RE to search for target name/value pair
    var re = new RegExp(name+"=[^;]+", "i"); 
    if (document.cookie.match(re)) {
        return document.cookie.match(re)[0].split("=")[1];
    } else {
        return ""
    }
}

sidebarToggle.setCookie = function(name, value)
{
    document.cookie = name + "=" + value + "; path=/";
}
