/**
 * Some of these scripts were taken from wikipedia.org/dukuwiki and were 
 * modified for Lahak
 */

/**
 * Some browser detection
 */
var clientPC  = navigator.userAgent.toLowerCase(); // Get client info
var is_gecko  = ((clientPC.indexOf('gecko')!=-1) && (clientPC.indexOf('spoofer')==-1)
        && (clientPC.indexOf('khtml') == -1) && (clientPC.indexOf('netscape/7.0')==-1));
var is_safari = ((clientPC.indexOf('AppleWebKit')!=-1) && (clientPC.indexOf('spoofer')==-1));
var is_khtml  = (navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled ));
if (clientPC.indexOf('opera')!=-1) {
    var is_opera = true;
    var is_opera_preseven = (window.opera && !document.childNodes);
    var is_opera_seven = (window.opera && document.childNodes);
}

function cascadedstyle(el, cssproperty, csspropertyNS){
    if (el.currentStyle)
        return el.currentStyle[cssproperty]
    else if (document.defaultView.getComputedStyle){
        var elstyle=document.defaultView.getComputedStyle(el,null)
            return elstyle.getPropertyValue(csspropertyNS)
    }
}

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

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 eraseCookie(name) {
	createCookie(name,"",-1);
}
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest(); //Not IE
    } else if(window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP"); //IE
    } else {
        //Display your error message here. 
        //and inform the user they might want to upgrade
        //their browser.
        alert("Your browser doesn't support the XmlHttpRequest object.  Better upgrade to Firefox.");
    }
}

// Used to show tabbed dialogs
// Thanks to Jonathan Hedley (c) 2004
// http://jon.hedley.net/html-tabbed-dialog-widget
var panes = new Array();

function setupPanes(containerId, defaultTabId) {
    // go through the DOM, find each tab-container
    // set up the panes array with named panes
    // find the max height, set tab-panes to that height
    panes[containerId] = new Array();
    var maxHeight = 0; var maxWidth = 0;
    var container = document.getElementById(containerId);
    var paneContainer = container.getElementsByTagName("div")[1];
    var paneList = paneContainer.childNodes;
    for (var i=0; i < paneList.length; i++ ) {
        var pane = paneList[i];
        if (pane.nodeType != 1) continue;
        if (pane.offsetHeight > maxHeight) maxHeight = pane.offsetHeight;
        //if (pane.offsetWidth  > maxWidth-20 ) maxWidth  = pane.offsetWidth - 20;
        panes[containerId][pane.id] = pane;
        pane.style.display = "none";
    }
    paneContainer.style.height = maxHeight + "px";
    //paneContainer.style.width  = maxWidth + "px";
    document.getElementById(defaultTabId).onclick();
}

function showPane(paneId, activeTab) {
    // make tab active class
    // hide other panes (siblings)
    // make pane visible

    for (var con in panes) {
        activeTab.blur();
        activeTab.className = "tab-active";
        if (panes[con][paneId] != null) { // tab and pane are members of this container
            var pane = document.getElementById(paneId);
            pane.style.display = "block";
            var container = document.getElementById(con);
            var tabs = container.getElementsByTagName("div")[0];
            var tabList = tabs.getElementsByTagName("a")
                for (var i=0; i<tabList.length; i++ ) {
                    var tab = tabList[i];
                    if (tab != activeTab) tab.className = "tab-disabled";
                }
            for (var i in panes[con]) {
                var pane = panes[con][i];
                if (pane == undefined) continue;
                if (pane.id == paneId) continue;
                pane.style.display = "none"
            }
        }
    }
    return false;    
}

function preview_reST(frame_id) {
    var req = getXmlHttpRequestObject()

    req.onreadystatechange = function() {
        if (req.readyState ==4) {
            if (frame_id) {
                w = window.frames[frame_id]
            }
            else {
                w = window.open("about:blank","rest_preview","status=no,toolbar=no,scrollbars=yes,resizable=yes")
            }
            // if completed, we redirect with GET operation to
            // get the preview
            w.document.location.replace("/rest/preview/")
        }
    }

    req.open('POST','/rest/preview/','true')
    req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    if (typeof(to_reST) != "undefined") {
        // to_reST should be defined in each doc
        rest_doc = to_reST()
    }
    else {
        // default to content and title
        rest_doc = { 
            'title':document.getElementById('id_title').value,
            'content':document.getElementById('id_content').value
        }
    }

    post_str = ""
    fields = ["title","content"]
    for (field in fields) {
        if (fields[field] !="title") { post_str+="&" }
        post_str += fields[field] + "=" + encodeURIComponent(rest_doc[fields[field]])
    }
    req.send(post_str)

}

var editor_textarea = null
function getEditor() {
    // if not found, let's try to get it accroding to the rest-toolbar div
    if (!editor_textarea) {
        try { editor_textarea = $$(".editor_container")[0].getElement('textarea');}
        catch (err) { editor_textarea = null}
    }

    return editor_textarea
}
/**
 * Does our editor has any text selected ? if so return it, otherwise, an empty string
 */
function getEditorSelection() {
    txtarea = getEditor(); if (!txtarea) return

    var txt = ''

    if (txtarea.selectionStart || txtarea.selectionStart == '0') {
        var startPos = txtarea.selectionStart
        var endPos   = txtarea.selectionEnd
        if (endPos - startPos > 0) { txt =  (txtarea.value).substring(startPos, endPos) }
        txtarea.selectionStart = startPos
        txtarea.selectionEnd = endPos
    }
    else if (document.getSelection) {
        txt = document.getSelection()
    }
    else if (document.selection) {
        range = document.selection.createRange()
        if (range.parentElement() == txtarea) {
            txt = range.text
        }
    }
    txtarea.focus()
    return txt
}


/**
 * apply tagOpen/tagClose to selection in textarea, use sampleText instead
 * of selection if there is none copied and adapted from phpBB
 *
 * @author phpBB development team
 * @author MediaWiki development team
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author Jim Raynor <jim_raynor@web.de>
 * @author Meir Kriheli <meir@mksoft.co.il>
 */
function insertTags(tagOpen, tagClose, sampleText, replace_selection) {
    txtarea = getEditor(); if (!txtarea) return

  // IE
  if(document.selection  && !is_gecko) {
    var theSelection = document.selection.createRange().text
    var replaced = true
    if(!theSelection){
      replaced = false
      theSelection=sampleText
    }
    txtarea.focus()
 
    if (replace_selection) theSelection = sampleText
    // This has change
    text = theSelection

    if(theSelection.charAt(theSelection.length - 1) == " "){// exclude ending space char, if any
      theSelection = theSelection.substring(0, theSelection.length - 1);
      r = document.selection.createRange();
      r.text = tagOpen + theSelection + tagClose + " ";
    } else {
      r = document.selection.createRange();
      r.text = tagOpen + theSelection + tagClose;
    }
    if(!replaced){
      r.moveStart('character',-text.length-tagClose.length);
      r.moveEnd('character',-tagClose.length);
    }
    r.select();
  // Mozilla
  } else if(txtarea.selectionStart || txtarea.selectionStart == '0') {
    var replaced = false;
    var startPos = txtarea.selectionStart;
    var endPos   = txtarea.selectionEnd;
    if(endPos - startPos) replaced = true;
    var scrollTop=txtarea.scrollTop;
    var myText = (txtarea.value).substring(startPos, endPos);
    if(!myText || replace_selection) { myText=sampleText;}
    if(myText.charAt(myText.length - 1) == " "){ // exclude ending space char, if any
      subst = tagOpen + myText.substring(0, (myText.length - 1)) + tagClose + " ";
    } else {
      subst = tagOpen + myText + tagClose;
    }
    txtarea.value = txtarea.value.substring(0, startPos) + subst +
                    txtarea.value.substring(endPos, txtarea.value.length);
    txtarea.focus();
 
    //set new selection
    if(replaced){
      var cPos=startPos+(tagOpen.length+myText.length+tagClose.length);
      txtarea.selectionStart=cPos;
      txtarea.selectionEnd=cPos;
    }else{
      txtarea.selectionStart=startPos+tagOpen.length;   
      txtarea.selectionEnd=startPos+tagOpen.length+myText.length;
    }
    txtarea.scrollTop=scrollTop;
  // All others
  } else {
    var copy_alertText=alertText;
    var re1=new RegExp("\\$1","g");
    var re2=new RegExp("\\$2","g");
    copy_alertText=copy_alertText.replace(re1,sampleText);
    copy_alertText=copy_alertText.replace(re2,tagOpen+sampleText+tagClose);
    var text;
    if (sampleText) {
      text=prompt(copy_alertText);
    } else {
      text="";
    }
    if(!text) { text=sampleText;}
    text=tagOpen+text+tagClose;
    //append to the end
    txtarea.value += "\n"+text;

    // in Safari this causes scrolling
    if(!is_safari) {
      txtarea.focus();
    }

  }
  // reposition cursor if possible
  if (txtarea.createTextRange) txtarea.caretPos = document.selection.createRange().duplicate();
}

/**
 * Pop a reST editing feature.
 *
 * @param type: window type (list, code, block etc)
 * @param width: window width
 * @oaram height: window height
 * @param list_window_type: optional. In case of list window, which type
 *                          is it (bullets or enumerated
 */
function restWindow(type, width, height, list_window_type) {
	window_url = '/rest/window/'+type+'/'

	if (list_window_type) {
		list_type = list_window_type
		window_url += list_type + '/'
	}
	window_attribs = "status=no,toolbar=no,width=" + width + ",height=" + height
	window.open(window_url, 'rest_'+type, window_attribs)
}

function insertList(list_type) {
    var list_content = getEditorSelection()

    if (list_type=='bullets') { item_prefix="*" }
    else if (list_type=='enumerated') { item_prefix="#." }
    else { alert("Invalid list type"); return }

    var new_line = ''
    if (list_content == "") {
        list_content = "item 1\nitem 2"
        new_line = '\n'
    }

    the_text = list_content.replace(/^(.+)$/mg, item_prefix+" $1")

    insertTags(new_line, new_line, the_text , true)
}

function indentSelection() {
    var list_content = getEditorSelection()

    if (list_content == "") {
        return;
    }

    the_text = list_content.replace(/^(.+)$/mg, "  $1")

    insertTags('', '', the_text , true)
}

function unindentSelection() {
    var list_content = getEditorSelection()

    if (list_content == "") {
        return;
    }

    the_text = list_content.replace(/^(  )(.+)$/mg, "$2")

    insertTags('', '', the_text , true)
}

function insertBlock(block_type, block_content, keep_lines) {
    lines_prefix = keep_lines ? "  | " : "  "
    the_text = block_content.replace(/^(.*)$/mg, lines_prefix+"$1")
    insertTags('\n.. ' + block_type + '::\n\n', '\n\n', the_text)
}

function insertUrl(desc, url) {
    if (!desc.getValue() || !url.getValue()) return;
    insertTags(' `', '`_ ', desc.getValue() + ' <' + url.getValue() + '>', true)
    desc.setProperty('value','')
    url.setProperty('value','')
}

function insertInternalUrl(protocol, label) {
    if (!protocol.getValue() || !label.getValue()) return;

    insertTags('|', '| ', protocol.getValue() + '|' + label.getValue(), true)
    label.setProperty('value','')

}

function insertTable(cols, rows, header_text, row_text) {
    var arr = new Array()
    var col_arr = new Array()
    var row_arr = new Array()

    for (i=0; i< cols; i++)  { arr[i] = '======='; col_arr[i]=header_text; row_arr[i]=row_text}

    sep_line = arr.join("  ")
    col_line = col_arr.join("  ")
    row_line = row_arr.join("  ")

    the_text = sep_line + "\n" + col_line+ "\n" + sep_line+"\n"

    for (i=0; i<rows; i++) { the_text += row_line+"\n" }
    the_text += sep_line+"\n"

    insertTags("\n","\n", the_text)
}

function insertCode(code_text) {
    the_text = code_text.replace(/^(.*)$/mg, "  $1")
    insertTags("\n::\n\n","\n", the_text)
}


/**
 * Change reST editor's direction.
 *
 * @param the_dir: Editor's direction ('rtl' or 'ltr')
 */
function restDirection( the_dir ) {
    try {
        var txtarea = document.getElementById('rest-toolbar').parentNode.getElementsByTagName('textarea')[0]
    }
    catch (err) { return }

    if ( the_dir == 'ltr' || the_dir == 'rtl' ) {
        txtarea.style.direction = the_dir
    }
}

function restEditorResize(operation) {
    txtarea = getEditor(); if (!txtarea) return

    var minheight=200
    var maxheight=1000
    var resize_step = 50

    var editor_height = $(txtarea).getSize()['size']['y']
    switch (operation) {
        case 'increase': 
            editor_height += resize_step
            break
        case 'decrease': 
            editor_height -= resize_step
            break
        case 'cookie':
            var tmp_editor_height = parseInt(readCookie('lahak_doc_editor_height'))
            if (tmp_editor_height) editor_height = tmp_editor_height
            break
    }
    
    if (editor_height > maxheight) { editor_height = maxheight }
    if (editor_height < minheight) { editor_height = minheight }
    txtarea.setStyle('height', editor_height+'px');
    createCookie('lahak_doc_editor_height', editor_height, 30 );

    // resize the panels
    panel_height = editor_height - $("rest-legend-select-container").getSize()['size']['y'];
    rest_panels.setStyle('height', panel_height + 'px');
}


function reparentChild( child, new_parent) {
    try {
        old_node = child.parentNode.removeChild(child)
        new_parent.appendChild(old_node)
    }
    catch (err) {return}
}

var rest_panels = null;
var protocol_completer = null;

function setupRestEditor() {

    rest_panels = $$(".rest-legend-panel");
    // set editor height from the cookie
    restEditorResize('cookie');
    $('rest-legend-select-container').setStyle('width', rest_panels[1].getSize()['size']['x']+'px');
    

    // hide all panels
    rest_panels.setStyle('display','none');

    $('rest-legend-select').addEvent('change', function() {
        getEditor().removeEvents();

        rest_panels.setStyle('display','none');
        rest_panels[this.selectedIndex].setStyle('display','block');

        if (this.getValue()=='1') {
            selected = getEditorSelection();
            if (selected) {
                $('link_description').setProperty('value',selected);
            }
            getEditor().addEvent('select', function(ev) {
                ev = new Event(ev).stop();
                $('link_description').setProperty('value', getEditorSelection());
            });
        }
    }).fireEvent('change');

    // lahak protocol auto completer
    protocol_completer = new Autocompleter.Ajax.Json($('rest-protocol-content'), '/rest/protocol_lookup/', {
        postVar : 'q',
        onRequest: function() {
            $('rest-protocol-loading').setStyle('visibility', 'visible');
            this.options['postData'] = {'protocol':$('rest-protocol-type').getValue() }
        },
        onComplete: function() {
            $('rest-protocol-loading').setStyle('visibility', 'hidden');
        },
        onFailure: function() {
            $('rest-protocol-loading').setStyle('visibility', 'hidden');
        }
    });

    // set images objects and events
    var image_uploaded = $("rest-legend-images-uploaded");
    if (image_uploaded) {
        image_uploaded.getElements('.rest-legend-image-row').uploadedImage();
    }

    var audio_uploaded = $("rest-legend-audio-uploaded");
    if (audio_uploaded) {
        audio_uploaded.getElements('.rest-legend-audio-row').uploadedAudio();
    }

    // set sepcial protocoles help text
    $("rest-special-protocol-type").addEvent('change', specialProtocolChanged).fireEvent('change');
}

function showImageUploadForm(content_type, object_id) {
    var the_url = '/uploads/form/?ct='+content_type + '&amp;oid='+object_id;
    $("rest-legend-images-uploaded").setStyle('display','none');
    $("rest-legend-images-upload-form").setStyle('display','block');
    $("rest-legend-images-upload-frame").setProperty('src',the_url);

}

function hideImageUploadForm() {
    $("rest-legend-images-uploaded").setStyle('display','block');
    $("rest-legend-images-upload-form").setStyle('display','none');
}

function refreshImages(content_type, object_id) {
    var url="/uploads/images_list/";

    hideImageUploadForm();
    $('uploaded_images').empty();
    $("rest-legend-images-spinner").setStyle('visibility','visibile');

    var uploaded_ajax = new Ajax( url, {
        method:'get',
        data: {
            ct: content_type,
            oid: object_id,
            random: Math.random()
        },
        update: $('uploaded_images'),
        onComplete: function() {
            $("rest-legend-images-uploaded").getElements('.rest-legend-image-row').uploadedImage();
            $("rest-legend-images-spinner").setStyle('visibility','hidden');
        },
        onFailure: function() {
            $("rest-legend-images-spinner").setStyle('visibility','hidden');
        }
    }).request();

    
}

function showAudioUploadForm(content_type, object_id) {
    var the_url = '/uploads/audio_form/?ct='+content_type + '&amp;oid='+object_id;
    $("rest-legend-audio-uploaded").setStyle('display','none');
    $("rest-legend-audio-upload-form").setStyle('display','block');
    $("rest-legend-audio-upload-frame").setProperty('src',the_url);

}

function hideAudioUploadForm() {
    $("rest-legend-audio-uploaded").setStyle('display','block');
    $("rest-legend-audio-upload-form").setStyle('display','none');
}


function refreshAudio(content_type, object_id) {
    var url="/uploads/audio_list/";

    hideAudioUploadForm();
    $('uploaded_images').empty();
    $("rest-legend-audio-spinner").setStyle('visibility','visibile');

    var uploaded_ajax = new Ajax( url, {
        method:'get',
        data: {
            ct: content_type,
            oid: object_id,
            random: Math.random()
        },
        update: $('uploaded_audio'),
        onComplete: function() {
            $("rest-legend-audio-uploaded").getElements('.rest-legend-audio-row').uploadedAudio();
            $("rest-legend-audio-spinner").setStyle('visibility','hidden');
        },
        onFailure: function() {
            $("rest-legend-audio-spinner").setStyle('visibility','hidden');
        }
    }).request();

}

function specialProtocolChanged() {
    var selected = $("rest-special-protocol-type").selectedIndex;

    help_lines = $("special-protocol-help-container").getElements(".special-protocol-help");
    help_lines.setStyle('display', 'none');
    help_lines[selected].setStyle('display','block');
}

Element.extend({
    uploadedImage: function() {
        this.image_id = this.getProperty('id').substring(18);
        var image_desc = this.getElements('.rest-legend-image-description')[0].getText();
        if (!image_desc) { image_desc=this.image_id; }
        this.getElements("a.rest-legend-image-add").addEvent('click', function(ev) {
            var ev = new Event(ev).stop()
            var the_content = '.. ' + gettext('image') +':: '+ this.image_id +'\n  :'+ 
                gettext('height')+': 120\n  :'+
                gettext('alt') + ': '+ image_desc;
            insertTags('\n\n','\n\n', the_content, true);
        }.bindWithEvent(this));
    },
    uploadedAudio: function() {
        this.audio_id = this.getProperty('id').substring(18);
        this.audio_desc = this.getElements('.rest-legend-audio-description')[0].getText();

        this.getElements("a.rest-legend-audio-add").addEvent('click', function(ev) {
            var ev = new Event(ev).stop();
            var the_content = this.audio_desc + ' |' + gettext('audio') +'|'+ this.audio_id+ '| '; 
            insertTags('',' ', the_content, true);
        }.bindWithEvent(this));
    }
});
