var menu;

window.onload = function()
{
    if (typeof update_filebrowser!= 'undefined') {
        update_filebrowser();
    }
    menu = make_menu('navigate_stnmenu');
    var el = document.getElementById('messageclosebutton');
    if (el) {
        // el.focus();
        setTimeout("hide('messagebox');", 10000);
    }

	randomHeader('header_img');
}

window.onunload = function()
{
    destroy_menu('navigate_stnmenu'); // voor elk menu dat gebruikt wordt.
}

document.onclick = function()
{
    if (menu) deactivate_menu(menu);
}

function cleanup_separate_tags(value) {
  value = value.replace(new RegExp('><', 'gi'), '>\n<');
  value = value.replace(new RegExp('<p', 'gi'), '\n\n<p');
  value = value.replace(new RegExp('<h1', 'gi'), '\n\n<h1');
  value = value.replace(new RegExp('<h2', 'gi'), '\n\n<h2');
  value = value.replace(new RegExp('<h3', 'gi'), '\n\n<h3');
  value = value.replace(new RegExp('<h4', 'gi'), '\n\n<h4');
  value = value.replace(new RegExp('<h5', 'gi'), '\n\n<h5');
  value = value.replace(new RegExp('<h6', 'gi'), '\n\n<h6');
  value = value.replace(new RegExp('<div', 'gi'), '\n\n<div');
  value = value.replace(new RegExp('<table', 'gi'), '\n\n<table');
  value = value.replace(new RegExp('<code', 'gi'), '\n\n<code');
  value = value.replace(new RegExp('<pre', 'gi'), '\n\n<pre');
  value = value.replace(new RegExp('/p>', 'gi'), '/p>\n');
  value = value.replace(new RegExp('/h1>', 'gi'), '/h1>\n');
  value = value.replace(new RegExp('/h2>', 'gi'), '/h2>\n');
  value = value.replace(new RegExp('/h3>', 'gi'), '/h3>\n');
  value = value.replace(new RegExp('/h4>', 'gi'), '/h4>\n');
  value = value.replace(new RegExp('/h5>', 'gi'), '/h5>\n');
  value = value.replace(new RegExp('/h6>', 'gi'), '/h6>\n');
  value = value.replace(new RegExp('/div>', 'gi'), '/div>\n');
  value = value.replace(new RegExp('/table>', 'gi'), '/table>\n');
  value = value.replace(new RegExp('/code>', 'gi'), '/code>\n');
  value = value.replace(new RegExp('/pre>', 'gi'), '/pre>\n');
  value = value.replace(new RegExp('( )*\n', 'gi'), '\n');
  value = value.replace(new RegExp('\n\n', 'gi'), '\n');
  value = value.replace(new RegExp('\n\n\n', 'gi'), '\n\n');
  value = value.replace(new RegExp('        ', 'gi'), ' ');
  return value;
}

function mce_custom_cleanup(type, value) {
  switch (type) {
    case "get_from_editor":
      value = cleanup_separate_tags(value);
      break;
    case "insert_to_editor":
      value = cleanup_separate_tags(value);
      break;
  }
  return value;
}

function stn_file_browser(field_name, url, type, win) 
{
    editor_id = win.tinyMCE.getWindowArg('editor_id');
    var connector = "/admin/standalone_file_browser.php";
    switch (type) {
        case "image":
            connector += "?linktype=image";
            break;
        case "file":
        default:
            if (url.indexOf('mailto:')===0) {
                connector += "?linktype=mailto";
                break;
            }
            switch (field_name) {
                case "href":
                    connector += "?linktype=page";
                    break;
                case "src":
                default:
                    connector += "?linktype=file";
                    break;
            }
            break;
    }
    connector += "&filepath=" + url;

    var fileBrowserWindow = new Array();
    fileBrowserWindow["file"] = connector; // PHP session ID should be included if necessary!
    fileBrowserWindow["title"] = "File & Link Browser";
    fileBrowserWindow["width"] = "744";
    fileBrowserWindow["height"] = "560";
    fileBrowserWindow["close_previous"] = "no";
    tinyMCE.openWindow(fileBrowserWindow, {
        window : win,
        editor_id : editor_id,
        input : field_name,
        resizable : "yes",
        inline : "yes"
        });
    return false;
}

function get_snippet(snippetid, snippetindex)
{
    var d = loadJSONDoc('/js/jsonaction_get_snippet.php?snippetid=' + snippetid + '&snippetindex=' + snippetindex);
    d.addCallback(partial(_load_snippet, snippetid));
}

var _load_snippet = function(snippetid, data)
{
    var el = document.getElementById('snippets-' + snippetid);
    if (el && data) {
        // FIX: changing the element did not change the edit link
        var editel = document.getElementById('editsnippets-' + snippetid);
        if (editel) {
            for(var i=0; i<editel.childNodes.length; i++) {
                if (editel.childNodes[i].tagName == 'A') {
                    editel.childNodes[i].href = editel.childNodes[i].href.replace(new RegExp("pageid=[0-9]+", 'gi'), "pageid=" + data.edit_id);
                }
            }
        }
        el.innerHTML = data.html;
    }
}

function load_usernames(el)
{
    //alert(el.value);
    var d = loadJSONDoc('jsonactions.php?' + el.name + '=' + el.value + '&' + '');
    d.addCallback(partial(_load_usernames_cb, el));
}

var _load_usernames_cb = function(el, data)
{
    set_combobox_options(el, data.data);
}

function copy_content(from, to) {
    newvalue = from.value;
    newvalue = newvalue.replace(new RegExp('<br/>', 'gi'), '\n');
    newvalue = newvalue.replace(new RegExp('<br/>', 'gi'), '\n');
    to.value = newvalue;
}

function switch_tab(stripid, tabid) {
    var tabstrip = document.getElementById(stripid);

    var node, id, content_el;
    var name_el = document.getElementById('name_' + tabid);
    var d = loadJSONDoc('jsonactions.php?tab='+stripid+'&tabname=' + name_el.attributes['name'].value);

    var zi = 99;
    for(var i=0;i<tabstrip.childNodes.length;i++){
        node = tabstrip.childNodes[i];

        if (node.tagName == 'DIV' && node.className.substr(0,3)=='tab') {
            id = node.id.replace('name_', '');
            content_el = document.getElementById('content_'+id);
            name_el = document.getElementById('name_'+id);

            if (id==tabid) {
                name_el.className += " selected";
                name_el.style.zIndex = 101;
                content_el.style.display="block";
            }
            else {
                name_el.className = name_el.className.replace(' selected', '');
                name_el.style.zIndex = zi;
                content_el.style.display="none";
                zi--;
            }
        }
    }
}

function use_file_browser(inputname, type) 
{
    var input = document.getElementById('input_'+inputname);
    var url = input.value;
    var connector = "/admin/standalone_file_browser.php";
    connector += "?linktype=" + type;
    connector += "&filepath=" + url;

    var fileBrowserWindow = new Array();
    fileBrowserWindow["file"] = connector; // PHP session ID should be included if necessary!
    fileBrowserWindow["title"] = "File & Link Browser";
    fileBrowserWindow["width"] = "744";
    fileBrowserWindow["height"] = "560";
    fileBrowserWindow["close_previous"] = "no";
    tinyMCE.openWindow(fileBrowserWindow, {
        window : window,
        input : 'input_'+inputname,
        preview : 'img_'+inputname,
        resizable : "yes",
        inline : "yes"
        });
    return false;
}

function _update_filebrowser(fbid)
{
    if (window.frameElement && window.parent.fb_page_select) {
        var purl = new Poly9.URLParser(document.location.href);
        var strippedurl = purl.getPathname();
        var qs = purl.getQuerystring();
        var fragment = purl.getFragment();
        if (qs) {
            qsparts = qs.split('&');
            var n = qsparts.length;
            var cleanqs = '';
            var amp = '';
            for(var i =0; i<n; ++i) {
                namevalue = qsparts[i].split('=');
                if (namevalue[0]!='fbid') {
                    cleanqs += amp+namevalue[0]+'='+namevalue[1];
                    amp = '&';
                }
            }
            if (cleanqs) strippedurl+= '?'+cleanqs;
        }
        if (fragment) strippedurl+= '#'+fragment;
        window.parent.fb_page_select(fbid, strippedurl);
    }
}

/** 
* @projectDescription 	Poly9's polyvalent URLParser class
*
* @author	Denis Laprise - denis@poly9.com - http://poly9.com
* @version	0.1 
* @namespace	Poly9
*
* Usage: var p = new Poly9.URLParser('http://user:password@poly9.com/pathname?arguments=1#fragment');
* p.getHost() == 'poly9.com';
* p.getProtocol() == 'http';
* p.getPathname() == '/pathname';
* p.getQuerystring() == 'arguments=1';
* p.getFragment() == 'fragment';
* p.getUsername() == 'user';
* p.getPassword() == 'password';
*
* See the unit test file for more examples.
* URLParser is freely distributable under the terms of an MIT-style license.
*/

if (typeof Poly9 == 'undefined')
 var Poly9 = {};

/**
 * Creates an URLParser instance
 *
 * @classDescription	Creates an URLParser instance
 * @return {Object}	return an URLParser object
 * @param {String} url	The url to parse
 * @constructor
 * @exception {String}  Throws an exception if the specified url is invalid
 */
Poly9.URLParser = function(url) {
 this._fields = {'Username' : 4, 'Password' : 5, 'Port' : 7, 'Protocol' : 2, 'Host' : 6, 'Pathname' : 8, 'URL' : 0, 'Querystring' : 9, 'Fragment' : 10};
 this._values = {};
 this._regex = null;
 this.version = 0.1;
 this._regex = /^((\w+):\/\/)?((\w+):?(\w+)?@)?([^\/\?:]+):?(\d+)?(\/?[^\?#]+)?\??([^#]+)?#?(\w*)/;
 for(var f in this._fields)
  this['get' + f] = this._makeGetter(f);
 if (typeof url != 'undefined')
  this._parse(url);
}
 
/**
 * @method 
 * @param {String} url	The url to parse
 * @exception {String} 	Throws an exception if the specified url is invalid
 */
Poly9.URLParser.prototype.setURL = function(url) {
  this._parse(url);
}

Poly9.URLParser.prototype._initValues = function() {
   for(var f in this._fields)
   this._values[f] = '';
}

Poly9.URLParser.prototype._parse = function(url) {
  this._initValues();
  var r = this._regex.exec(url);
  if (!r) throw "DPURLParser::_parse -> Invalid URL"
  for(var f in this._fields) if (typeof r[this._fields[f]] != 'undefined')
   this._values[f] = r[this._fields[f]];
}

Poly9.URLParser.prototype._makeGetter = function(field) {
 return function() {
  return this._values[field];
 }
}
