/* variables */
var active_switch = new Array();
var active_form = new Array();

/* general helper functions */
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

function setCookie(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    "; path=/" +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

function getById(id) { return document.getElementById(id);}
function crE(t) { return document.createElement(t);}
function crTe(t) { return document.createTextNode(t);}
function sel(t) { return document.selection(t);}

/* benchmark */
var benchmark_sent = false;
function bm() {
    if (benchmark_sent) return false;
    fd = new Date();
    i = document.createElement('img');
    url = '/bm.php?bmb='+(fd.getTime()-st)+'&r='+document.URL;
    url = url + '&bms='+bms+'&bmc='+bmc+'&bmh='+bmh+'&bmwh='+bmwh;
    i.setAttribute('src', url);
    i.setAttribute('alt', '');
    i.style.width = '1px';
    i.style.height = '1px';
    getById('wrapper').appendChild(i);
    benchmark_sent = true;
}
/* textarea controll */
function add_textarea_events(field, counter, maxlimit) {
    check_textarea_length(field, counter, maxlimit);
}


function textCounter(field, counter, maxlimit) {
    if (getById(field) && getById(field).value.length > maxlimit)
        getById(field).value = getById(field).value.substring(0, maxlimit);
    else if (getById(field))
        getById(counter).innerHTML = maxlimit - getById(field).value.length;
}

function check_textarea_length(field, counter, maxlimit) {
    timer = window.setTimeout('check_textarea_length("'+field+'", "'+counter+'", '+maxlimit+');', 10);
    textCounter(field, counter, maxlimit);
}

/* display functions */

function switchsidepanel(panel, screen) {
    getById(panel+'1').style.display = 'none';
    getById(panel+'2').style.display = 'none';
    getById(panel+screen).style.display = 'block';
    setCookie(panel, screen);
}

/* have a look at the thread entries */
function switchactionbox(type, id) {
    if (active_switch[type]) {
        if (getById('ao-'+type+active_switch[type])) getById('ao-'+type+active_switch[type]).style.display = 'none';
        if (getById('ac-'+type+active_switch[type])) getById('ac-'+type+active_switch[type]).style.display = 'block';
    }
    if (id) {
        if (getById('ao-'+type+id)) getById('ao-'+type+id).style.display = 'block';
        if (getById('ac-'+type+id)) getById('ac-'+type+id).style.display = 'none';
        active_switch[type] = id;
    }
    else {
        active_switch[type] = false;
    }
}

function show_ad(community_id, zone, cadid, element, position, width, height, style) {
    var jetzt = new Date();
    src = 'http://adverts.tribax.com/advert.php?ad='+cadid+'&c='+community_id+'&z='+zone+'&t='+jetzt.getTime();
    if (navigator.appName.indexOf("Explorer") != -1) {
        var iframe = document.createElement('iframe');
        if (style) iframe.setAttribute('style', style);
        iframe.setAttribute('frameborder', 0);
        iframe.setAttribute("frameBorder", "0");
        iframe.setAttribute('border', 0);
        iframe.setAttribute('vspace','0');
        iframe.setAttribute('hspace','0');
        iframe.setAttribute('bordercolor', 'white');
        iframe.setAttribute('scrolling', 'no');
        if (zone) iframe.id = 'adzone'+zone;
        iframe.style.padding = '0px';
        iframe.style.margin = '0px';
        iframe.style.marginBottom = '10px';
        iframe.style.border = '0px solid white';
        iframe.src = src;
    }
    else {
        var iframe = document.createElement('object');
        if (style) iframe.setAttribute('style', style);
        iframe.setAttribute('type', 'text/html');
        iframe.style.marginBottom = '10px';
        if (zone) iframe.id = 'adzone'+zone;
        iframe.setAttribute('data', src);
    }
    iframe.style.overflow = 'hidden';
    if (width) {
        iframe.style.width = width;
        iframe.setAttribute('width', width);
    }
    if (height) {
        iframe.style.height = height;
        iframe.setAttribute('height', height);
    }
    if (element) {
        if (position == 'inner_before') getById(element).parentNode.insertBefore(iframe, getById(element));
        else getById(element).appendChild(iframe);
    }
    else getById('jsadzone'+zone).parentNode.insertBefore(iframe, getById('jsadzone'+zone));
}

function switchform(type, form) {
    if (active_form[type]) {
        if (active_form[type] == form){
            if (active_switch[type]) form_id = form + active_switch[type];
            else form_id = form;

            getById(form_id).style.display = 'none';
            active_form[type] = false;
        }
        else {
            if (active_switch[type]) {
                form_id_1 = active_form[type] + active_switch[type];
                form_id_2 = form + active_switch[type];
            }
            else{
                form_id_1 = active_form[type];
                form_id_2 = form;
            }
            getById(form_id_1).style.display = 'none';
            getById(form_id_2).style.display = 'block';
            active_form[type] = form
        }
    }
    else{
        if (active_switch[type]) form_id = form + active_switch[type];
        else form_id = form;

        getById(form_id).style.display = 'block';
        active_form[type] = form;
    }
}

function setheader(screen) {
    getById('img1').style.display = 'none';
    getById('img2').style.display = 'none';
    getById('img'+screen).style.display = 'block';
    getById('open').style.display = 'none';
    getById('close').style.display = 'none';
    if (screen == 2){
        getById('more1').style.display = 'block';
        getById('more2').style.display = 'block';
        getById('more0').style.display = 'none';
        getById('close').style.display = 'block';
        if (getById('headerbx').className.substring((getById('headerbx').className.length - 6), (getById('headerbx').className.length)) == ' small')
            getById('headerbx').className = getById('headerbx').className.substring(0, (getById('headerbx').className.length - 6) );

    }else{
        getById('more1').style.display = 'none';
        getById('more2').style.display = 'none';
        getById('more0').style.display = 'block';
        getById('open').style.display = 'block';
        if (getById('headerbx').className.substring((getById('headerbx').className.length - 6), (getById('headerbx').className.length)) != ' small')
            getById('headerbx').className = getById('headerbx').className + ' small';
    }
    setCookie('header', screen);
}

function getObjInnerText (obj) {
    return (obj.innerText) ? obj.innerText
    : (obj.textContent) ? obj.textContent
    : "";
}

function edit_entry(id, action, txt1, txt2, formaction, txt3) {
    var div = getById('entry-body-'+id);
    if (getById('event_entry'+id)) {
        c = getById('event_entry'+id).value;
        while (div.firstChild) { div.removeChild(div.firstChild);}
        div.innerHTML = c;
    }
    else {
        var div = getById('entry-body-'+id);
        var c = div.innerHTML;
        d = document.createElement('div');
        f = document.createElement('form');
        if (formaction == null) f.setAttribute('action', '.');
        else f.setAttribute('action', formaction);
        f.setAttribute('method', 'post');

        i1  = document.createElement('input');
        i1.setAttribute('type', 'hidden');
        i1.setAttribute('name', 'action');
        i1.value = action;

        i2  = document.createElement('input');
        i2.setAttribute('type', 'hidden');
        i2.setAttribute('name', 'entry_id');
        i2.value = id;


        ta = document.createElement('textarea');
        ta.setAttribute('name', 'body');
        ta.setAttribute('id', 'body_'+id);
        ta.value = c;

        spCP = document.createElement('span');
        spCP.appendChild(document.createTextNode(txt3));

        p = document.createElement('p');
        p.className = 'txtcounter';
        p.appendChild(document.createTextNode(txt1+' '));
        s = document.createElement('span');
        s.setAttribute('id', 'body_'+id+'_count');
        p.appendChild(s);
        p.appendChild(document.createTextNode(' '+txt2));

        scrpt = document.createElement('script');
        scrpt.setAttribute('type', 'text/java'+'script');
        if (null == scrpt.canHaveChildren || scrpt.canHaveChildren) {
            scrpt.appendChild(document.createTextNode('var wysiwyg_'+id+';wysiwyg_'+id+' = new nicEditor().panelInstance("body_'+id+'", null, 21845);'));
        }
        else {
            scrpt.text = 'var wysiwyg_'+id+';wysiwyg_'+id+' = new nicEditor().panelInstance("body_'+id+'", null, 21845);';
        }

        is = document.createElement('input');
        is.setAttribute('type', 'submit');
        is.value = 'speichern';
        is.className = 'btn';
        ih = document.createElement('input');
        ih.setAttribute('type', 'hidden');
        ih.setAttribute('id', 'event_entry'+id);
        ih.setAttribute('value', c);
        while (div.firstChild) { div.removeChild(div.firstChild);}

        f.appendChild(ta);
        f.appendChild(spCP);
        f.appendChild(p);
        //f.appendChild(scrpt);
        f.appendChild(i1);
        f.appendChild(i2);
        f.appendChild(is);
        f.appendChild(ih);
        d.style.height = '275px';
        d.appendChild(f);
        div.appendChild(d);
        div.appendChild(scrpt);
    }
}

function submit_post(target, param_str, confirm_msg){
    form = document.createElement('form');
    form.setAttribute('method', 'POST');
    form.setAttribute('action', target);
    form.setAttribute('id', 'hiddenform');
    form.setAttribute('style', 'display:none;');
    params = param_str.split('&');
    for (i = 0;i < params.length; i++) {
        p = params[i].split('=');
        input = document.createElement('input');
        input.setAttribute('name', p[0]);
        input.setAttribute('type', 'hidden');
        input.value = p[1]
        form.appendChild(input);
    }

    if (confirm_msg == false){
    	document.lastChild.lastChild.appendChild(form);
    	document.getElementById('hiddenform').submit();
    }
    else {
        if (confirm(confirm_msg)) {
        	document.lastChild.lastChild.appendChild(form);
        	document.getElementById('hiddenform').submit();
        }
        else{
            return false;
        }
    }
}

function show_elemnt(id){
    if (getById(id)) getById(id).style.display = 'block'
}
function hide_elemnt(id){
    if (getById(id)) getById(id).style.display = 'none'
}

/**
 * IE has trouble correctly drawing screen elements in stacking order. It always
 * draws form elements last, regardless of their actual z-index, thus obscuring
 * drop downs and other elements.
 */
function compat_ie_dropdowns()
{
    var srch = document.getElementById('header-wrapper').getElementsByTagName('ul');
    for (var i = 0; i < srch.length; i++) {
        if (srch[i].className && srch[i].className == 'subdrop') {
            srch[i].parentNode.onmouseover = compat_dropdown_on;
            srch[i].onmouseout = compat_dropdown_off;
        }
    }
}

var compatIfMenu = false;
var compatEvSrc = false;
var compatIframeTO = false;

function compat_dropdown_on() {
    compatEvSrc = this;
    window.event.cancelBubble = true;
    window.setTimeout('compat_dropdown_on_do();', 100);
}

function compat_dropdown_on_do()
{
    var node = compatEvSrc;
    if (node.parentNode && node.parentNode.nodeName == 'UL' && node.parentNode.className == 'subdrop') {
        node = node.parentNode;
    } else if (node.parentNode.parentNode && node.parentNode.parentNode.nodeName == 'UL'
            && node.parentNode.parentNode.className == 'subdrop') {
        node = node.parentNode.parentNode;
    }

    if (compatIframeTO) {
        window.clearTimeout(compatIframeTO);
        compatIframeTO = false;
    }
    if (compatIfMenu) { // Another menu is open. Close it first
        compat_dropdown_off_do();
    }

    var srch = node.getElementsByTagName('ul');
    for (var i = 0; i < srch.length; i++) {
        if (srch[i].className && srch[i].className == 'subdrop') {
            node = srch[i];
            break;
        }
    }
    node.style.left = '0px';
    node.style.top = '25px';
    node.style.display = 'block';
    node.style.position = 'absolute';

    var iframe = document.createElement('iframe');
    iframe.src = 'about:blank';
    iframe.id = 'drop_iframe';
    iframe.frameborder = 0;
    iframe.style.width = node.offsetWidth.toString() + 'px';
    iframe.style.height = node.offsetHeight.toString() + 'px';
    node.parentNode.insertBefore(iframe, node);
    compatIfMenu = node;
}

function compat_dropdown_off()
{
    if (compatIframeTO) window.clearTimeout(compatIframeTO);
    compatIframeTO = window.setTimeout('compat_dropdown_off_do();', 750);
}

function compat_dropdown_off_do()
{
    var iframe = document.getElementById('drop_iframe');
    try {
        iframe.parentNode.removeChild(iframe);
        compatIfMenu.style.display = 'none';
    } catch (e) {}
    compatIfMenu = false;
    compatIframeTO = false;
}

function chat_add2url(finalURL, srcEle)
{
    var finalURL, bgColor, txtColor, barBgColor, posBarColor;

    if (typeof(srcEle) != 'object') {
        srcEle = document.getElementById(srcEle);
        if (typeof(srcEle) != 'object') return; // Element not found
    }

    bgColor = getStyle(srcEle, 'background-color');
    if (!bgColor) bgColor = getStyle(srcEle, 'background');
    txtColor = getStyle(srcEle, 'color');
    barBgColor = getStyle(srcEle, 'border-top-color');
    if (!barBgColor) barBgColor = getStyle(srcEle, 'border-color');

    finalURL += '&bg=' + chat_rgbHex(txtColor, true);
    finalURL += '&leftbg=' + chat_rgbHex(barBgColor, true);
    finalURL += '&rightbg=' + chat_rgbHex(barBgColor, true);
    finalURL += '&rightbghover=' + chat_rgbHex(barBgColor, true);
    finalURL += '&voltrack=' + chat_rgbHex(bgColor, true);
    finalURL += '&volslider=' + chat_rgbHex(txtColor, true);
    finalURL += '&lefticon=' + chat_rgbHex(txtColor, true);
    finalURL += '&righticon=' + chat_rgbHex(txtColor, true);
    finalURL += '&righticonhover=' + chat_rgbHex(txtColor, true);
    finalURL += '&loader=' + chat_rgbHex(barBgColor, true);

    return finalURL;
}


/**
 * Converts CSS rgb(x,y,z) to classic #xxyyzz notation
 * @param string  CSS rgb(x,y,z) setting
 *[@param bool  Whether to cut the # in front; Default: false (leave it in)]
 * @return  string  either #xxyyzz or xxyyzz (if param 2 is set to true)
 */
function chat_rgbHex(rgb, flash)
{
    if (rgb.match(/^rgb/)) {
        var tmp = /^rgb\((\d+),\s?(\d+),\s?(\d+)\)/;
        tmp.exec(rgb);
        rgb = '#' + chat_decHex(RegExp.$1) + chat_decHex(RegExp.$2) + chat_decHex(RegExp.$3);
    }
    if (flash && rgb.substr(0,1) == '#') rgb = rgb.substr(1);
    return rgb;
}

/**
 * Simple dec -> hex converter
 * @param  int  decimal value; range: 0 ... 255
 * @return  string  hex value. has always two digits!
 */
function chat_decHex(dez)
{
    dez = parseInt(dez);
    var tbl = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F'];
    var H1, H2;
    H1 = parseInt(dez/16);
    H2 = dez - (H1*16);
    return tbl[H1].toString() + tbl[H2].toString();
}


/**
 * Third party code below
 */

// Ermittle Style eines Elements
function getStyle(element, property)
{
    // Beim IE kann man (über currentStyle - IE5+) keine Eigenschaften
    // abfragen, die kombinierte Werte enthalten (border, borderBottom, ...)
    // Andererseits gibt es zu clip hier auch clipTop, clipRight, clipBottom & ClipLeft.
    var result = '';

    obj = getObject(element);

    if (obj) {
        if (window.getComputedStyle) {
            result = window.getComputedStyle(obj, '').getPropertyValue(property);
        } else if (obj.currentStyle) {
            result = obj.currentStyle[propertyToStyle(property)];
        } else if (obj.style) {
            result = obj.style[propertyToStyle(property)];
        }
    }
    return result;
}

// Style-Schreibweise von CSS auf JS ändern
function propertyToStyle(property)
{
    // 1. Eigenschaften mit reserviertem Bezeichner: Unterscheidung nach JScript- bzw. JavaScript-Syntax
    if (property == 'float') {
        property = ((typeof(window.cssFloat) == 'undefined') ? 'style' : 'css') + property.charAt(0).toUpperCase()+property.substring(1);
    } else if (property.indexOf("-") >= 0) { // 2. Eigenschaften mit Bindestrich
        syntax = property.split("-");               // CSS-Syntax am "-" auftrennen, ...
        property = syntax[0];                       // ... ersten Teil übernehmen und ...
        for(var i = 1; i < syntax.length; i++) {    // ... folgende Teile mit großem Anfangsbuchstaben
            property += syntax[i].charAt(0).toUpperCase()+syntax[i].substring(1);
        }
    }
    return property;
}

// Ermittle Objekt (veränderbare Priorität: object/id/name/tagname) 050708
function getObject(element, number)
{
    var obj = false, lastParam, type, types, i;
    if (element) {
        // Letzten, optionalen Parameter ermitteln (type)
        lastParam = getObject.arguments[getObject.arguments.length-1];
        // Erwünschten Abfragetyp sichern: object/id/name/tagname (voreingestellte Typen und Reihenfolge der Abfrage)
        type = (typeof(lastParam) == 'string' && getObject.arguments.length>1)
                ? lastParam.toLowerCase().replace(',', '\/')
                : 'object/id/name/tagname';
        // Wenn element bereits Objekt ist und auch dieser Typ sein darf
        if (typeof(element) == 'object' && type.indexOf('object') >= 0) {
            obj = element;
        } else if (document.getElementById) {
            number = (typeof(number) == 'number')?number:0;
            types = type.split('/');
            for (i in types) {
                if (types[i] == 'id' && document.getElementById(element)) {
                    obj = document.getElementById(element); break;
                } else if (types[i] == 'name' && document.getElementsByName(element) && document.getElementsByName(element)[number]) {
                    obj = document.getElementsByName(element)[number]; break;
                } else if (types[i] == 'tagname' && document.getElementsByTagName(element) && document.getElementsByTagName(element)[number]) {
                    obj = document.getElementsByTagName(element)[number]; break;
                }
            }
        }
    }
    return obj;
}

/**
 * Converts CSS rgb(x,y,z) to classic #xxyyzz notation
 * @param string  CSS rgb(x,y,z) setting
 *[@param bool  Whether to cut the # in front; Default: false (leave it in)]
 * @return  string  either #xxyyzz or xxyyzz (if param 2 is set to true)
 */
function rgb2Hex(rgb, flash) {
    if (rgb.match(/^rgb/)) {
        var tmp = /^rgb\((\d+),\s?(\d+),\s?(\d+)\)/;
        tmp.exec(rgb);
        rgb = '#' + dec2Hex(RegExp.$1) + dec2Hex(RegExp.$2) + dec2Hex(RegExp.$3);
    }
    if (flash && rgb.substr(0,1) == '#') rgb = rgb.substr(1);
    return rgb;
}

/**
 * Simple dec -> hex converter
 * @param  int  decimal value; range: 0 ... 255
 * @return  string  hex value. has always two digits!
 */
function dec2Hex(dez) {
    dez = parseInt(dez);
    var tbl = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F'];
    var H1, H2;
    H1 = parseInt(dez/16);
    H2 = dez - (H1*16);
    return tbl[H1].toString() + tbl[H2].toString();
}

/**
 * adds markup for video player
 * @param  string  jquery selector
 * @param  string  path to flv
 */
function video_include(selector, fileName, width, height, domain) {   
    if ($(selector).count != 0) {
        if (domain != '') domain = 'http://'+domain;       
        bgColor = $(selector).css('background-color');
        fgColor = $(selector).css('color');
        $(selector).empty().append('<object height="'+height+'" width="'+width+'" data="'+domain+'/swf/videoplayer.swf" id="flvplayer" type="application/x-shockwave-flash">'+
        '<param name="quality" value="high" />'+
        '<param name="movie" value="'+domain+'/swf/videoplayer.swf" />'+
        '<param name="wmode" value="opaque" />'+
        '<param name="allowFullScreen" value="true" />'+
        '<param name="flashvars" value="movie='+fileName+'&autoload=on&volume=70&bgcolor=0x' + rgb2Hex(bgColor, true) + '&fgcolor=0x' + rgb2Hex(fgColor, true) + '&postimage=" />'+
        '</object>');    
    }    
}