//-----------------------------------------------------
//--- Browser defs ------------------------------------
//-----------------------------------------------------

if (typeof Browser == 'undefined') {
    var Browser = {
        'a' : navigator.userAgent.toLowerCase(),
        'b' : parseInt(navigator.appVersion)
    }
    Browser = {
        'ie' : /*@cc_on true || @*/ false,
        'ie6' : Browser.a.indexOf('msie 6') >= 0,
        'ie7' : Browser.a.indexOf('msie 7') >= 0,
        'ie8' : Browser.a.indexOf('msie 8') >= 0,
        'moz' : ((Browser.a.indexOf('mozilla') >= 0) && (Browser.a.indexOf('spoofer') < 0) && (Browser.a.indexOf('compatible') < 0)
        && (Browser.a.indexOf('opera') < 0) && (Browser.a.indexOf('webtv') < 0) && (Browser.a.indexOf('hotjava') < 0)),
        'opera' : !!window.opera,
        'opera7' : ((Browser.a.indexOf('opera 7') >= 0) || (Browser.a.indexOf('opera/7') >= 0)
        || (Browser.a.indexOf('opera 8') >= 0) || (Browser.a.indexOf('opera/8') >= 0)
        || (Browser.a.indexOf('opera 9') >= 0) || (Browser.a.indexOf('opera/9') >= 0)),
        'opera56' : (Browser.opera && !Browser.opera7),
        'chrome' : Browser.a.indexOf('chrome') >= 0,
        'safari' : (Browser.a.indexOf('safari') >= 0 && Browser.a.indexOf('chrome') < 0),
        'safari3' : Browser.a.indexOf('applewebkit/5') >= 0,
        'win' : ((Browser.a.indexOf("win") >= 0) || (Browser.a.indexOf("16bit") >= 0)),
        'mac' : Browser.a.indexOf('mac') >= 0,
        'ver' : (Browser.a.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1]
    }
}

if (typeof tpl_suppress_veffects == 'undefined') {
    var tpl_suppress_veffects = 0;
}
if (typeof tpl_document_loaded == 'undefined') {
    var tpl_document_loaded = false;
}
if (typeof tpl_feeder == 'undefined') {
    var tpl_feeder = "";
}

if (typeof SWFObject == 'undefined') {
    var SWFObject = false;
}

var have_jQuery = (typeof jQuery != 'undefined') ? 1 : 0;



//-----------------------------------------------------
//--- Event handling ----------------------------------
//-----------------------------------------------------

if (typeof HTMLElement != 'undefined') {
    HTMLElement.prototype.__defineGetter__('innerText', function() {
        var tmp = this.innerHTML;
        tmp = tmp.replace(/<br>/gi, "\n");
        tmp = tmp.replace(/]+>/g, "");
        return tmp;
    });
    HTMLElement.prototype.__defineSetter__('innerText', function(txtStr) {
        var parsedText = document.createTextNode(txtStr);
        this.innerHTML = "";
        this.appendChild(parsedText);
    });
}

var addListener = function() {
    if (window.addEventListener) {
        return function(el, type, fn) {
            el.addEventListener(type, fn, false);
        };
    } else if (window.attachEvent) {
        return function(el, type, fn) {
            var f = function() {
                return fn.call(el, window.event);
            }
            if (!el._listeners) el._listeners = {};
            if (!el._listeners[type]) el._listeners[type] = {};
            el._listeners[type][fn] = f;
            el.attachEvent('on' + type, f);
        };
    } else {
        return function(el, type, fn) {
            el['on' + type] = fn;
        }
    }
} ();

var removeListener = function(el, type, func) {
    if (el.removeEventListener) {
        el.removeEventListener(type, func, false);
    } else if (el.detachEvent && el._listeners && el._listeners[type] && el._listeners[type][func]) {
        el.detachEvent('on' + type, el._listeners[type][func]);
    }
};



//-----------------------------------------------------
//--- Developer functions -----------------------------
//-----------------------------------------------------

function gmt() {
    return (new Date().getTime()) / 1000;
}
if (typeof stm == 'undefined') stm = gmt();


function debug(obj, max_depth, full_debug, sep, depth) {
    var type = typeof(obj);
    var is_object = (type == 'object') ? true : false;
    var is_arr = (is_object ? is_array(obj) : false);
    var is_func = (type == 'function') ? true : false;

    var debug_func = true;
    var sep = (!empty(sep, true) ? sep : "\n<hr>\n");
    var depth = (!empty(depth) ? depth : 0);
    var max_depth = !empty(max_depth) ? Number(max_depth) : 4;
    if (depth > max_depth && is_object) {
        debug_output('[object]');
        return;
    };

    if (!is_object || obj === null || !array_length(obj)) {
        if (type == 'undefined') debug_output('undefined');
        else if (obj === null) debug_output('null');
        else if (obj === "") debug_output('""');
        else if (is_object) debug_output(is_arr ? '[ ]' : '{ }');
        else if (is_func) debug_output(debug_func ? String(obj) : '[funct]');
        else if (is_scalar(obj)) debug_output("'"+htmlentities(String(obj).replace(/\n/g, '%@!BR!@%')).replace(/%@!BR!@%/g, '<br>')+"'");
        else debug_output('empty');
    } else {
        var constr = (obj && !empty(obj.constructor)) ? obj.constructor : false;
        var first = 1;
        debug_output((is_arr ? 'Array' : 'Object') + '(' + array_length(obj) + ') ' + (is_arr ? "[" : "{"));
        debug_output("<ul style='list-style: none; margin: 0; padding: 0 0 0 10;'><li>");
        for (var n in obj) {
            var elm = obj[n];
            if (!full_debug && (empty(elm) || (typeof(elm) == 'function' && !debug_func))) continue;

            debug_output((first ? '' : ", </li><li>") + (is_int(n) ? n : "'"+n+"'") + ' => ');
            try {
                if (empty(elm) || empty(elm.nodeName) || full_debug) {
                    debug(elm, max_depth, full_debug, "", depth+1);
                } else {
                    debug_output("[object]");
                };
            } catch (ex) { debug_output("[event]"); };
            first = 0;
        };
        debug_output("</li></ul>");
        debug_output((is_arr ? "]" : "}") + htmlentities("\n"));
    };
    if (!depth) debug_output(sep);
};

var debug_output_content = "";
var debug_output_timer;
function debug_output(info) {
    if (empty(info)) return;

    debug_output_content = debug_output_content + info;

    if (debug_output_timer) clearTimeout(debug_output_timer);
    debug_output_timer = setTimeout("debug_output_flush()", 100);
};

function debug_output_flush() {
    var debug_div = getEl("debugger");
    if (empty(debug_output_content)) return;
    if (debug_output_timer) clearTimeout(debug_output_timer);
    if (!debug_div) {
        debug_output_timer = setTimeout("debug_output_flush()", 100);
        return;
    }

    debug_div.innerHTML = debug_output_content;
    debug_div.style.display = "block";
    if (getEl('php_debug_info')) {
        hideDiv('sql_debug_info');
        hideDiv('php_debug_info');
        hideDiv('php_debug_details');
    }
};

function customErrorHandler(info, page, line)  {
    debug("JS error: '" + info + "' in '" + page + "' on line " + line);
    return true;
}
window.onerror = customErrorHandler;

function json_dump(obj) {
    var t = typeof(obj);
    if (t != "object" || obj === null) {
        if (t == "string") obj = '"' + obj + '"';
        return String(obj);
    } else {
        var n, v, json = new Array(),
        arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n];
            t = typeof(v);
            if (t == "string") v = '"' + v + '"';
            else if (t == "object" && v !== null) {
                v = (!v.nodeName) ? json_dump(v) : '"' + String(v) + '"';
            }
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
}

function bench(iterations, func, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {
    var start_time = gmt();
    if (typeof iterations == "function") {
        iterations(func, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);
        return gmt() - start_time;
    }

    var is_str = typeof func == 'string';

    for (var i=0; i < iterations; i++) {
        if (is_str) eval(func); else func(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);
    }
    return gmt() - start_time;
}



//-----------------------------------------------------
//--- Object manipulation -----------------------------
//-----------------------------------------------------

function empty(mixed_var, skip_str) {
    if (!exists(mixed_var) || mixed_var === false || (!skip_str && mixed_var === "")) return true;
    if (typeof mixed_var == 'object') {
        for (var key in mixed_var) { return false; }
        return true;
    }
    return false;
}

function exists(mixed_var) {
    if (typeof mixed_var == 'undefined' || mixed_var === null) return false;
    return true;
}

function is_array(mixed_var) {
    try {
        if (typeof mixed_var === "object" && mixed_var !== null && mixed_var.constructor && String(mixed_var.constructor) === String(new Array().constructor)) return true;
        return false;

    } catch (err) { return false; }
}

function is_scalar(mixed_var) {
    return (/boolean|number|string/).test(typeof mixed_var);
}

function is_int(mixed_var) {
    if (typeof mixed_var !== 'number') return false;
    if (parseFloat(mixed_var) != parseInt(mixed_var, 10)) return false;
    return true;
}

function array_length(arr) {
    if (typeof arr != "object") return false;
    var cnt = 0;
    for (var i in arr) { cnt++; }
    return cnt;
}

function array_merge() {
    var args = Array.prototype.slice.call(arguments);
    var retArr, retObj = {}, k, j = 0, i = 0, ct = 0;

    for (i=0, retArr = true; i < args.length; i++) {
        if (!(args[i] instanceof Array)) {
            retArr = false;
            break;
        }
    }
    if (retArr) return args;

    for (i=0, ct=0; i < args.length; i++) {
        if (args[i] instanceof Array) {
            for (j=0; j < args[i].length; j++) {
                retObj[ct++] = args[i][j];
            }
        } else {
            for (k in args[i]) {
                if (this.is_int(k)) {
                    retObj[ct++] = args[i][k];
                } else {
                    retObj[k] = args[i][k];
                }
            }
        }
    }

    return retObj;
}

function array_search(arr, prop, val) {
    var reg_str = "(^|\\s)" + val.replace(/\-/g, "\\-") + "(\\s|$)";
    var matches = new Array(), reg = new RegExp(reg_str);
    if (!exists(val)) {
        val = prop;
        prop = null;
    }
    for (var i = 0; i < arr.length; i++) {
        if (!empty(arr[i])) {
            var cmp_val = (exists(prop) ? arr[i][prop] : arr[i]);
            if (!empty(cmp_val) && (cmp_val == val || reg.test(cmp_val))) {
                matches.push(arr[i]);
            }
        }
    }
    return matches;
}

function array_from_values(obj) {
    var obj = getEl(obj);
    var new_arr = new Object();
    for (var i=0; i < obj.length; i++) {
        new_arr[obj[i]] = obj[i];
    }
    return new_arr;
}

function array_obj2arr(obj, prop, val) {
    if (empty(obj[prop])) {
        obj[prop] = val;
        return 1;
    } else {
        if (!is_array(obj[prop])) obj[prop] = new Array(obj[prop]);
        obj[prop].push(val);
    }
    return 0;
}


//-----------------------------------------------------
//--- String manipulation -----------------------------
//-----------------------------------------------------

function str_replace(obj, src, dst, is_text) {
    if (typeof obj == "object") {
        if (obj.innerHTML) var txt = obj.innerHTML;
    } else {
        var txt = (getEl(obj) && !is_text ? getEl(obj).innerHTML : obj);
    }
    if (empty(txt)) return false;

    if (typeof src == "object") {
        for (var i in src) {
            txt = str_replace(txt, i, src[i], true);
        }
        return txt;
    }

    return txt.replace(new RegExp(src, "g"), dst);
}

function str_prop_replace(obj, props, is_text) {
    if (typeof props != "object") return false;
    if (typeof obj == "object") {
        if (obj.innerHTML) var txt = obj.innerHTML;
    } else {
        var txt = (getEl(obj) && !is_text ? getEl(obj).innerHTML : obj);
    }
    if (empty(txt)) return false;

    return txt.replace(/\%([^%]*)\%/g, function(a, b) {
        var r = props[b];
        return typeof r === 'string' || typeof r === 'number' ? r : a;
    });
}

function htmlentities(s){
    if (empty(s)) return "";
    var my_div = document.createElement('div');
    var text = document.createTextNode(s);
    my_div.appendChild(text);
    var strout = my_div.innerHTML+"";
    delete my_div;
    return strout;
}

function urlencode(str) {
    str = (str+'').toString();
    if (encodeURIComponent) return encodeURIComponent(str);
    if (escape) return escape(str);
}

function aparg(link, arg) {
    if (!arg) return link;
    var splitted = link.split("#");
    return splitted[0] + (link.lastIndexOf('?') >= 0 ? "&" : "?") + arg + (splitted[1] ? "#"+splitted[1] : "");
}

function getAnchor(arg) {
    var str = exists(arg) && is_scalar(arg) ? arg : window.location.href;
    return (str.match(/\#/) ? str.replace(/(.+)#/, "") : "");
}

function trim(s) {
    return s.replace(/^\s+|\s+$/g, "");
}

function regex_quote(str) {
    return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!<>\|\:])/g, "\\$1");
}

function regex_match(str, reg, flags) {
    reg = reg.replace(new RegExp('([\\\\]+)'), '\\\\');
    return (new RegExp(reg, flags).test(str));
}

function regex_replace(str, reg, repl, flags) {
    reg = reg.replace(new RegExp("([\\\\]+)"), "\\\\");
    return str.replace(new RegExp(reg, flags), repl);
}



//-----------------------------------------------------
//--- DOM manipulation --------------------------------
//-----------------------------------------------------

function findElCtx(ctx) {
    return (!empty(ctx) ? getEl(ctx) : document);
}

function getEl(id) {
    if (!empty(id) && typeof id == 'string') {
        if (id.substring(0, 1) == '#') return document.getElementById(id.substring(1));
        if (id.substring(0, 1) == '.') return getElByClass(id.substring(1))
        return document.getElementById(id);
    } else {
        return id;
    }
}

function getElByName(klass, ctx, ret_all) {
    var arr = findElCtx(ctx).getElementsByTagName("*");
    var matches = array_search(arr, "name", klass);
    return (ret_all ? matches : matches[0]);
}

function getElByClass(klass, ctx, ret_all) {
    if (klass.substring(0,1) == '.') klass = klass.substring(1);
    return getElByTagClass("*", klass, ctx, ret_all);
}

function getElByTag(tag, ctx, ret_all) {
    var tag = tag || "*";
    var ctx = findElCtx(ctx);
    var matches = ctx.getElementsByTagName(tag);
    return (ret_all ? matches : matches[0]);
}

function getElByTagClass(tag, klass, ctx, ret_all) {
    if (klass.substring(0,1) == '.') klass = klass.substring(1);
    var tag = tag || "*";
    var ctx = findElCtx(ctx);
    var arr = ctx.getElementsByTagName(tag);
    var matches = array_search(arr, "className", klass);
    return (ret_all ? matches : matches[0]);;
}

function getElTags(tag, ctx, ret_all) {
    if (have_jQuery) {
        var matches = $(tag, ctx);
        return (ret_all ? matches : matches[0]);
    }

    if (typeof tag == 'object') return tag;
    if (typeof tag == 'string') {
        var contexts = !empty(ctx) ? getElTags(ctx, null, true) : null;
        if (empty(contexts)) {
            contexts = new Array();
            contexts.push(document);
        }

        var results = new Array();
        for (var i=0; i < contexts.length; i++) {
            var test_obj, ctx_id = contexts[i];

            if (tag.substring(0, 1) == '#' && typeof ctx_id.getElementById) {
                test_obj = ctx_id.getElementById(tag.substring(1));
            } else {
                if (!test_obj) test_obj = ctx_id.getElementsByTagName(tag);
                if (!test_obj) test_obj = ctx_id.getElementById(tag);
                if (!test_obj && document.all) test_obj = document.all[tag];
            }

            if (test_obj) results.push(test_obj);
        }

        return (ret_all ? results : results[0]);
    } else {
        return false;
    }
}

function hasParent(element, ancestor){
    var el = getEl(element);
    var an = getEl(ancestor);
    while (el != document && el != null){
        if (el == an) return true;
        el = el.parentNode;
    }
    return false;
}

function forEachNode(arr, func) {
    if (empty(arr)) return;
    if (typeof arr.length !== "number" || !empty(arr.nodeName)) {
        func(arr, 0);
        return;
    }
    for (var i = 0; i < arr.length; i++) func(arr[i], i);
}

function node_ExecJS(node) {
    var scripts = node.getElementsByTagName('SCRIPT');
    var strExec;
    for (var i=0; i<scripts.length; i++) {
        if (Browser.safari) strExec = scripts[i].innerHTML;
        else if (Browser.opera) strExec = scripts[i].text;
        else if (Browser.moz) strExec = scripts[i].textContent;
        else strExec = scripts[i].text;

        try { evalScript(strExec.split("<!--").join("").split("-->").join(""), scripts[i].src); }
        catch(e) { alert(e); }
    }
}

function evalScript(str, url) {
    var head = getElByTag("head") || getElByTag("*")[0];
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.text = str;
    if (typeof url != 'undefined' && url) script.src = (url ? url : "");
    head.appendChild(script);
    if (empty(url)) {
        head.removeChild(script);
        delete script;
    }
}

function execCallback(funct, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) {
    if (typeof funct == 'string') {
        return evalScript(funct);
    } else if (typeof funct == 'function') {
        return funct(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
    }
}

function execSafe(funct, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) {
    if (typeof funct == 'string') {
        try { eval(callback); }
        catch (c) { return false; }
    } else if (typeof funct == 'function') {
        try { funct(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); }
        catch (c) { return false; }
    }
    return true;
}


function hookEvent(obj, evt, new_fn, prepend) {
    var cur_fn = obj[evt];

    obj[evt] = function(e) {
        if (!e) e = window.event;

        if (prepend && new_fn.call(obj, e) === false) return false;
        try {
            if (typeof cur_fn != 'undefined' && cur_fn != null && cur_fn.call(obj, e) === false) return false;
        } catch(c) { }
        if (!prepend && new_fn.call(obj, e) === false) return false;

        return null;
    }

//    if (!obj._hooks) obj._hooks = new Object();
//    if (!obj._hooks[evt]) obj._hooks[evt] = new Array();
//    var f = function() {
//        debug('hook');
//        new_fn.call(obj, window.event);
//        return true;
//    };
//    obj._hooks[evt].push(f);
//    return addListener(obj, evt.replace(/^on/g, ''), f);

//    return addListener(obj, evt.replace(/^on/g, ''), new_fn);
}

var zzzaddListener = function() {
    if (window.addEventListener) {
        return function(el, type, fn) {
            el.addEventListener(type, fn, false);
        };
    } else if (window.attachEvent) {
        return function(el, type, fn) {
            var f = function() {
                fn.call(el, window.event);
            }
            if (!el._listeners) el._listeners = {};
            if (!el._listeners[type]) el._listeners[type] = {};
            el._listeners[type][fn] = f;
            el.attachEvent('on' + type, f);
        };
    } else {
        return function(el, type, fn) {
            el['on' + type] = fn;
        }
    }
} ();



//-----------------------------------------------------
//--- CSS / Style manipulation ------------------------
//-----------------------------------------------------

function hasClass(element,_className){
    if (!element) return;

    var upperClass = _className.toUpperCase();
    if (element.className){
        var classes = element.className.split(' ');
        for (var i=0; i<classes.length; i++) if (classes[i].toUpperCase() == upperClass) return true;
    }
    return false;
}
function addClass(element,_class){
    if (!element) return;
    if (!hasClass(element, _class)) element.className += element.className ? (" "+_class) : _class;
}
function insertClass(element,_class){
    if (!element) return;
    if (!hasClass(element, _class)) element.className = _class + (element.className ? (" " + element.className) : "");
}
function setClass(element,_class){
    if (!element) return;
    element.className = _class;
}
function removeClass(element,_class){
    if (!element) return;

    var upperClass = _class.toUpperCase();
    var remainingClasses = new Array();
    if (element.className){
        var classes = element.className.split(' ');
        for (var i=0; i<classes.length; i++){
            if (classes[i].toUpperCase() != upperClass){
                remainingClasses[remainingClasses.length] = classes[i];
            }
        }
        element.className = remainingClasses.join(' ');
    }
}

function getCSSValue(obj_id, css_name) {
    var obj = getEl(obj_id);

    var js_name = css_name.replace(/\-(\w)/g, function(all, letter){ return letter.toUpperCase(); });
    var css_name = css_name.replace(/([A-Z])/g, "-$1" ).toLowerCase();

    var prop = (Browser.ie ? obj.currentStyle[js_name] : obj.ownerDocument.defaultView.getComputedStyle(obj,"").getPropertyValue(css_name));
    if (prop.match(/^rgb/g, '')) prop = "#"+convertRGB(prop);
    prop = prop.replace(/(\d+)px/g, "$1");
    prop = parseInt(prop) || prop;
    return prop;
}

function setCSSValue(obj_id, css_name, css_value) {
    var obj = getEl(obj_id);
    if (typeof obj.style == 'undefined') return false;

    var js_name = css_name.replace(/\-(\w)/g, function(all, letter){ return letter.toUpperCase(); });
    if (obj.style[js_name] != 'undefined') {
        obj.style[js_name] = css_value;
        return true;
    }
    return false;
}

function getCSSColor(obj_id, ie_name, moz_name) {
    var obj = getEl(obj_id);
    var ret = "";
    if (Browser.ie) {
        ret = eval("obj.currentStyle."+ie_name);
    } else {
        var ret = obj.ownerDocument.defaultView.getComputedStyle(obj,"").getPropertyValue(moz_name);
        if (ret.match(/^rgb/g, '')) {
            ret = "#"+convertRGB(ret);
        }
    }
    return ret;
}

function convertRGB(z) {
    var newfcS = "", splitter = "";
    splitter = z.split(",");
    splitter[0] = parseInt(splitter[0].substring(4, splitter[0].length));
    splitter[1] = parseInt(splitter[1]);
    splitter[2] = parseInt(splitter[2].substring(0, splitter[2].length-1));
    for (var q = 0; q < 3; q++) {
        splitter[q] = splitter[q].toString(16);
        if (splitter[q].length == 1) splitter[q] = "0" + splitter[q];
        newfcS += splitter[q];
    }
    return newfcS;
}


function isVisible(obj_name) {
    var obj = getEl(obj_name);
    if (obj == document) return true;
    if (!obj || !obj.parentNode) return false;
    if (obj.style && (obj.style.display == 'none' || obj.style.visibility == 'hidden')) return false;

    if (window.getComputedStyle) {
        var style = window.getComputedStyle(obj, "");
        if (style && (style.display == 'none' || style.visibility == 'hidden')) return false;
    } else {
        var style = obj.currentStyle;
        if (style && (style['display'] == 'none' || style['visibility'] == 'hidden')) return false;
    }

    return isVisible(obj.parentNode);
}

function showDiv(divName){
    var tempDiv = getEl(divName);
    if (!tempDiv) return;

    if (hasClass(tempDiv, "wasinline")){
        tempDiv.style.display = "inline";
        removeClass(tempDiv, "wasinline");
    } else if (hasClass(tempDiv, "wasblock")){
        tempDiv.style.display = "block";
        removeClass(tempDiv, "wasblock");
    } else {
        var n = tempDiv.nodeName.toLowerCase();
        tempDiv.style.display = (n=="span" || n=="img" || n=="a") ? "inline" : (n=='tr' || n=='td' ? "" : "block");
    }
}

function hideDiv(divName){
    var tempDiv = getEl(divName);
    if (!tempDiv) return;

    if (tempDiv.style.display == "inline") {
        addClass(tempDiv, "wasinline");
    } else if (tempDiv.style.display == "block") {
        addClass(tempDiv, "wasblock");
    }
    tempDiv.style.display = "none";
}

function toggleVisible() {
    var args = Array.prototype.slice.call(arguments);
    var value_flag;
    if (is_scalar(args[0])) value_flag = (args[0] ? true : false);

    for (var i=0; i < args.length; i++) {
        if (is_scalar(args[i])) continue;
        var state = (exists(value_flag)) ? value_flag : (isVisible(args[i]) ? false : true);
        if (state) showDiv(args[i]); else hideDiv(args[i]);
    }
}


function parseAnchorParams(arg) {
    var hashString = getAnchor(arg);
    if (!hashString) return new Array();

    var key_values = hashString.split("&");
    var result = new Array();
    for (var i = 0; i < key_values.length; i++) {
        result.push(key_values[i].split("="));
    }
    return result;
}

function findPos(obj) {
    obj = getEl(obj);
    var curleft = curtop = 0;
    if (obj.parentNode && obj.parentNode != document.body) {
        do {
            curleft += obj.offsetLeft - obj.scrollLeft;
            curtop += obj.offsetTop - obj.scrollTop;
        } while ((obj = obj.offsetParent) != document.body);
    }
    return [curleft,curtop];
}

function stopPropagation(e){
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
}

function mouseEventValid(e, handler) {
    if (e.type != 'mouseout' && e.type != 'mouseover') return false;
    var reltg = e.relatedTarget ? e.relatedTarget : (e.type == 'mouseout' ? e.toElement : e.fromElement);

    while (reltg && reltg != handler) {
        reltg = reltg.parentNode;
    }
    return (reltg != handler);
}



//-----------------------------------------------------
//--- Form input manipulation -------------------------
//-----------------------------------------------------

function formInputValue(field) {
    field = getEl(field);
    if (!field) return null;
    if (field.nodeName == "SELECT") {
        if (!field.options.length) return false;
        return field.options[field.selectedIndex].value;
    }
    if (field.nodeName == "INPUT") {
        if (field.type == "checkbox") {
            return field.checked;
        } else {
            return field.value;
        }
    }
    if (field.nodeName == "TEXTAREA") {
        return field.value;
    }
}

function formInputCheck(obj, proto, required, false_on_unknown) {
    var str = formInputValue(obj);
    if (!str.length) return (required ? false : true);
    var reg = "";

    switch (proto) {
        case "ufloat":  reg = "^[0-9\.]+$";     break;
        case "float":   reg = "^-?([0-9\.]*?)$"; break;
        case "uint":    reg = "^[0-9]+\%?$";    break;
        case "int":     reg = "^-?([0-9]*?)$";  break;
        case "degree":  reg = "^-?([0-9]{1,3}\\.?[0-9]*)$"; break;
        case "color":   reg = "^(0x|#|0)([a-fA-F0-9]{0,6})$"; break;
        case "string":  reg = "([^\n\t\r]+)";   break;
        default:
            return (false_on_unknown ? false : true);
            break;
    }
    var re = new RegExp(reg);
    if (!re.test(str)) {
        obj.value = str.substring(0, str.length-1);
        return false;
    }
    return true;
}

function formInputValidate(obj, proto, return_value, false_on_unknown, min_length, max_length) {
    var str = formInputValue(obj);
    var is_valid = false;
    var reg = "";
    if (typeof str == 'undefined') return true; // radio
    if (!str.length) return false;

    // format check
    switch (proto) {
        case "float":   reg = "^-?([0-9]+)(\\.[0-9]+)?$";   break;
        case "ufloat":  reg = "^([0-9]+)(\\.[0-9]+)?$";     break;
        case "int":     reg = "^-?([0-9]+)$";           break;
        case "uint":    reg = "^([0-9]+)$";             break;
        case "degree":  reg = "^-?([0-9]{1,3})(\\.[0-9]+)?$"; break;
        case "color":   reg = "^(0x|#)([a-fA-F0-9]{3}|[a-fA-F0-9]{6})$"; break;
        case "bool":    reg = "^(true|false|[01])$";    break;
        case "string":  reg = "([^\\n\\t\\r]+)";           break;
        case "email":   reg = "^([^\\s]+)\\@([^\\s]+)\\.([a-z]{2,5})$";    break;
        case "name":    reg = "([^\\n\\t\\r]{3,})";        break;

        default:
            is_valid = (false_on_unknown ? false : true);
            break;
    }

    if (is_valid) return (return_value ? str : true);

    if (reg) {
        var re = new RegExp(reg);
        if (!re.test(str)) return (return_value ? null : false);
    }

    // value check
    is_valid = true;
    switch (proto) {
        case "bool":
            str = (typeof str == 'string') ? (str.toLowerCase() == "true" ? true : false ) : !!str;
            break;
        case "float":
        case "ufloat":
        case "degree":
            str = parseFloat(str);
            if (proto == "degree" && (str < -360 || str > 360)) {
                str = 0;
                is_valid = false;
            }
            break;
        case "int":
        case "uint":
            str = parseInt(str);
            break;

        case "name":
        case "string":
        case "email":
            if (str.length < 3) is_valid = false;
            break;

        case "color":
        case "text":
        default:
            break;
    }
    if (min_length && str.length < parseInt(min_length)) is_valid = false;
    if (max_length && str.length > parseInt(max_length)) is_valid = false;

    return (return_value ? str : is_valid);
}

function selectAdd(obj, vars, val) {
    var sel = getEl(obj);
    var items = new Array();
    if (typeof vars == 'object') {
        if (vars.constructor == Array) {
            items = vars;
        } else if (!empty(vars.nodeName) && vars.nodeName == "OPTION") {
            items.push(vars);
        } else {
            for (var i in vars) {
                var tmp = document.createElement("option");
                tmp.text = i; tmp.value = vars[i];
                items.push(tmp);
            }
        }
    } else {
        var tmp = document.createElement("option");
        tmp.text = vars;
        tmp.value = (!empty(val, true) ? val : vars);
        items.push(tmp);
    }
    for (var i=0; i<items.length; i++) {
        try { sel.add(items[i], null);
        } catch (ex) { sel.add(items[i]); }
    }
}

function selectChange(obj, val) {
    var sel = getEl(obj);
    for (var i = 0; i < sel.length; i++) {
        if (sel[i].value == val) {
            sel.selectedIndex = i;
            return true;
        }
    }
    return false;
}

function txtSel(elm) {
    if (isVisible(elm)) {
        getEl(elm).focus();
        getEl(elm).select();
    }
}

function checkSel(obj, checked, prefix) {
    var elm = getEl(obj);

    if (elm.nodeName.toLowerCase() == 'form') var frm = elm;
    else if (elm.form) var frm = elm.form;
    else return false;

    if (typeof prefix == 'undefined' || !prefix) prefix = "";
    if (typeof checked == 'undefined' || checked == null) checked = null;

    for (var i=0; i<frm.length; i++) {
        if (frm[i].type == 'checkbox' && frm[i] != obj) {
            if ((prefix && frm[i].name.indexOf(prefix) == 0) || !prefix) {
                frm[i].checked = (checked != null) ? checked : !frm[i].checked;
            }
        }
    }
    return true;
}




//-----------------------------------------------------
//--- Cookies manipulation ----------------------------
//-----------------------------------------------------

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);
}



//-----------------------------------------------------
//--- asyncQuery --------------------------------------
//-----------------------------------------------------

var aQuery_requests = new Array();
var aQuery_requests_counter = 0;

function aQuery(asyncUrl, asyncCallback, asyncNoCache, asyncMethod) {
    if (typeof asyncUrl == 'undefined' || asyncUrl == '') return false;

    var req_id = aQuery_requests_counter;
    aQuery_requests_counter++;

    if (asyncNoCache) asyncUrl = aparg(asyncUrl, "ts=" + new Date().getTime());

    asyncMethod = (typeof asyncMethod == 'string' && asyncMethod.toLowerCase() == "post") ? "POST" : "GET";

    aQuery_requests[req_id] = new Object();
    aQuery_requests[req_id].request = false;
    aQuery_requests[req_id].url = asyncUrl;

    if (asyncCallback) {
        aQuery_requests[req_id].callback = asyncCallback;
    }

    var async_req = null;
    if (typeof ActiveXObject != 'undefined') {
        try { async_req = new ActiveXObject("Msxml2.XMLHTTP"); }
        catch(e) {
            try { async_req = new ActiveXObject("Microsoft.XMLHTTP"); }
            catch (oc) { async_req = null; }
        }
    }
    if (!async_req && typeof XMLHttpRequest != "undefined") {
        try { async_req = new XMLHttpRequest(); }
        catch (oc) { async_req = null; }
    }

    if (async_req) {
        aQuery_requests[req_id].request = async_req;
        async_req.onreadystatechange = function() { aQuery_onLoad(req_id); };

        if (asyncMethod == "POST") {
            var parts = asyncUrl.split("\?");
            var asyncUrl = parts[0];
            var asyncUrlParams = parts[1];
        }

        async_req.open(asyncMethod, asyncUrl, true);

        if (asyncMethod == "POST") {
            async_req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            async_req.setRequestHeader("Content-length", asyncUrlParams.length);
            async_req.setRequestHeader("Connection", "close");
            async_req.send(asyncUrlParams);
        } else {
            async_req.send(null);
        }

        return true;
    } else {
        delete aQuery_requests[req_id];
        return false;
    }
}

function aQuery_onLoad(req_id) {
    if (!aQuery_requests[req_id]) return;

    var async_req = aQuery_requests[req_id].request;

    if (async_req && async_req.readyState == 4) {
        var req_success = false;
        var req_response = "";
        if (async_req.status == 200 || async_req.status == 304) {
            req_response = async_req.responseText;
            req_success = true;
        } else {
            debug("aQuery error:\n" + async_req.statusText + ", status=" + async_req.status);
        }

        if (aQuery_requests[req_id].callback) {
            execCallback(aQuery_requests[req_id].callback, req_response, req_success, async_req.statusText);
        }

        async_req = null;
        delete aQuery_requests[req_id];
    }
}



//-----------------------------------------------------
//--- AHAH --------------------------------------------
//-----------------------------------------------------

var ahah_requests = new Array();
var ahah_requests_counter = 0;

function ahahLoad(ahahObj, ahahUrl, ahahCallback, ahahNoCache, ahahSkipPost, ahahSkipJS, ahahMethod) {
    if (typeof ahahUrl == 'undefined' || !ahahUrl) return false;

    var req_target = getEl(ahahObj);
    var req_id = ahah_requests_counter;
    ahah_requests_counter++;

    if (!req_target) {
        req_target = document.createElement("DIV");
        req_target.is_dynamic = 1;
    }

    if (!ahahNoCache && req_target.ahahDone && req_target.ahahUrl && req_target.ahahUrl == ahahUrl) {
        return true;
    }

    req_target.ahahUrl = ahahUrl;
    if (!req_target.innerHTML) {
        req_target.innerHTML = "<table border='0' cellpadding'0' cellspacing='0' width='100%' height='250'><tr><td align='right' width='45%'><img src='"+tpl_image_url+"/loading.gif' border='0'></td><td align='left' width='55%' class='title'>Loading</td></tr></table>";
    }

    ahah_requests[req_id] = new Object();
    ahah_requests[req_id].target = req_target;
    ahah_requests[req_id].url = ahahUrl;
    ahah_requests[req_id].skip_post = ahahSkipPost;
    ahah_requests[req_id].skip_js = ahahSkipJS;
    if (ahahCallback) {
        ahah_requests[req_id].callback = ahahCallback;
    }

    return aQuery(ahahUrl, function (req_response, req_success, req_status_text) {
        ahah_onLoad(req_id, req_response, req_success, req_status_text);
    }, ahahNoCache, ahahMethod);

}

function ahahQuery(ahahObj, ahahUrl, ahahCallback) {
    return ahahLoad(ahahObj, ahahUrl, ahahCallback, 1, 1, 1);
}

function ahah_onLoad(req_id, req_response, req_success, req_status_text) {
    var req_target = ahah_requests[req_id].target;

    if (req_success) {
        req_target.innerHTML = req_response;

        if (!ahah_requests[req_id].skip_js)   node_ExecJS(req_target);
        if (!ahah_requests[req_id].skip_post) onLoad_fix(req_target);
    } else {
        req_target.innerHTML = "ahahLoad error:\n" + req_status_text + "\n<br>";
    }

    if (ahah_requests[req_id].callback) {
        execCallback(ahah_requests[req_id].callback, req_response, req_success, req_status_text);
    }

    if (req_target.is_dynamic) delete req_target;
    delete ahah_requests[req_id];
}




//-----------------------------------------------------
//--- AJAQ --------------------------------------------
//-----------------------------------------------------

var ajaq_requests = new Array();
var ajaq_requests_counter = 0;

function ajaq(ajaqUrl, ajaqCallback, ajaqMethod) {
    if (typeof ajaqUrl == 'undefined' || !ajaqUrl) return false;

    var req_id = ajaq_requests_counter;
    ajaq_requests_counter++;

    ajaq_requests[req_id] = new Object();
    ajaq_requests[req_id].url = ajaqUrl;
    if (ajaqCallback) {
        ajaq_requests[req_id].callback = ajaqCallback;
    }

    return aQuery(ajaqUrl, function (req_response, req_success, req_status_text) {
        ajaq_onLoad(req_id, req_response, req_success, req_status_text);
    }, true, ajaqMethod);
}

function ajaq_onLoad(req_id, req_response, req_success, req_status_text) {
    if (req_success) {
        try { evalScript(req_response.replace(new RegExp('<\\/?SCRIPT>', 'gi'), '')); }
        catch(e) { alert(e); return; }
    }
    if (ajaq_requests[req_id].callback) {
        execCallback(ajaq_requests[req_id].callback, req_response, req_success, req_status_text);
    }

    delete ajaq_requests[req_id];
}



//-----------------------------------------------------
//--- XML ---------------------------------------------
//-----------------------------------------------------

function xml2array(txt, is_url, callback) {
    if (!is_url) {
        if (txt.length < 1024) return xakopXML(txt);
        return dom2array(xml2object(txt));
    } else {
        return aQuery(txt, function (req_response, req_success, req_status_text) {
            if (req_success) {
                execCallback(callback, dom2array(xml2object(req_response), req_response, req_success, req_status_text));
            }
        });
    }
}

function xml2object(txt, skip_fix) {
    if (!txt.length) return new Object();
    var xmlDom, parser;
    var is_ax = false;

    txt = "<generated_root_object>"+txt+"</generated_root_object>";

    if (typeof ActiveXObject != 'undefined') {
        try {
            xmlDom = new ActiveXObject("Microsoft.XMLDOM");
            xmlDom.async = "false";
            xmlDom.loadXML(txt);
            is_ax = true;
        } catch(e) { }
    }
    if (!xmlDom) {
        try {
            parser = new DOMParser();
            xmlDom = parser.parseFromString(txt, "text/xml");
        } catch(e) { }
    }

    if (xmlDom && xmlDom.childNodes && xmlDom.childNodes.length > 0) return xmlDom;
    return new Object();
}

function dom2array(obj, attr_suffix) {
    if (!obj || !obj.nodeName) return new Object();
    if (obj.nodeType == 9) return dom2array(obj.childNodes[0], attr_suffix); // #document

    var arr = new Object(), cur = obj, tags_count = 0;

    while (cur) {
        //debug('process '+cur.nodeName+' '+cur.nodeType);
        var tag = cur.nodeName, elm = new Object();

        if (cur.nodeType == 3) { // text node
            elm = cur.nodeValue;
            if (elm.length <= 128 && elm.replace(/\s/g, '') == "") elm = "";
        } else { // dom node
            for (var j = 0; j < cur.attributes.length; j++) { // process attributes first
                if (cur.attributes[j].nodeName) elm[cur.attributes[j].nodeName + (attr_suffix ? ' attr' : '')] = cur.attributes[j].nodeValue;
            }

            if (cur.childNodes.length) { // process child nodes
                var childs = dom2array(cur.childNodes[0], attr_suffix);
                if (is_scalar(childs)) { // single element text objects
                    elm = childs;
                } else {
                    for (i in childs) { elm[i] = childs[i]; }
                }
            }
        }

        if (!empty(elm)) {
            tags_count = tags_count + array_obj2arr(arr, tag, elm);
        }
        cur = cur.nextSibling;
    }

    if (tags_count == 1) {
        if (arr['#document']) arr = arr['#document'];
        if (arr['generated_root_object']) arr = arr['generated_root_object'];
        if (arr['#text']) arr = arr['#text'];
    } else {
        //if (arr['#text']) delete arr['#text'];
    }
    return arr;
}

function xakopXML(xml) {
    xml = xml.replace(/[\r\n\t]/g, "").replace(/<(\w*)([^>]*)\/>/g, "<$1 $2></$1>");
    var buf = new Object();
    var re_tag = new RegExp("<(\\w*)([^>]*)>(.*?)<\\/\\1>");

    while (!empty(xml) && (arr = re_tag.exec(xml))) {
        xml = xml.replace(arr[0], "");
        if (empty(arr)) {
            if (arr.length < 3) break;
            if (arr.length <= 2) continue;
        }

        var tag_name = trim(arr[1]);
        var attrs = trim(arr[2]);
        var content = trim(arr[3]);

        if (!empty(attrs)) {
            if (empty(buf[tag_name])) {
                buf[tag_name] = new Object();
                xakopXML.putAttributes(buf[tag_name], attrs);
            } else if (is_array(buf[tag_name])) {
                buf[tag_name].push(new Object());
                xakopXML.putAttributes(buf[tag_name][buf[tag_name].length - 1], attrs);
            } else {
                buf[tag_name] = new Array(buf[tag_name]);
                buf[tag_name].push(new Object());
                xakopXML.putAttributes(buf[tag_name][buf[tag_name].length - 1], attrs);
            }
        }

        if (!empty(content)) {
            var simple_content = false;
            if (content.match(re_tag)) content = xakopXML(content); else simple_content = true;

            if (simple_content)  {
                buf[tag_name] = content;
            } else {
                if (empty(buf[tag_name])) {
                    buf[tag_name] = new Object();
                    xakopXML.putAttributes(buf[tag_name], content);
                } else if (is_array(buf[tag_name])) {
                    if (empty(attrs)) buf[tag_name].push(new Object());
                    xakopXML.putAttributes(buf[tag_name][buf[tag_name].length - 1], content);
                } else if (empty(attrs)) {
                    buf[tag_name] = new Array(buf[tag_name]);
                    buf[tag_name].push(new Object());
                    xakopXML.putAttributes(buf[tag_name][buf[tag_name].length - 1], content);
                } else {
                    xakopXML.putAttributes(buf[tag_name], content);
                }
            }
        }

        if (empty(xml)) break;
    }

    return buf;
}

xakopXML.putAttributes = function(obj, attrs) {
    if (typeof attrs === "object") {
        for (var prop in attrs) {
            array_obj2arr(obj, prop, attrs[prop]);
        }
        return;
    }

    var re_attrs = new RegExp('\\w*="[^"]*"', "g");
    var re_attr = new RegExp('(\\w*)="([^"]*)"');
    var m = attrs.match(re_attrs);

    if (empty(m)) return;

    for (var i=0; i < m.length; i++) {
        var var_m = m[i].match(re_attr);
        array_obj2arr(obj, var_m[1], var_m[2]);
    }
}



//-----------------------------------------------------
//--- Image functions ---------------------------------
//-----------------------------------------------------

var scaleImg_calc_height = 0;

function scaleImg(obj, newWidth, newHeight, is_callback){
    var what = getEl(obj);
    if (!what) return;

    var holder = getEl('image_holder');
    var placer = getEl('image_placer');
    var holder_mode = (holder ? 1 : 0);
    var padding = 5;

    var de = document.documentElement;
    var screen_width = document.body.clientWidth || (de && de.clientWidth) || window.innerWidth || self.innerWidth;
    var screen_height = document.body.clientHeight || (de && de.clientHeight) || window.innerHeight || self.innerHeight;

    screen_width = screen_width - 2 * padding - 1;
    screen_height = screen_height - 2 * padding - 1;

    if (empty(what.scale_info)) {
        what.scale_info = new Object();
        what.scale_info['in_progress'] = true;

        if (holder_mode) {
            what.scale_info['holder_position'] = holder.style.position;
            what.scale_info['holder_zindex'] = holder.style.zIndex;
            if (placer) {
                placer.style.width = placer.offsetWidth;
                placer.style.height = placer.offsetHeight;
            }

            scroll(0, 0);
            holder.style.zIndex = '100';
            holder.style.position = 'absolute';
            holder.style.left = holder.style.top = padding;

            if (newWidth > screen_width) {
                newHeight = newHeight * (screen_width / newWidth);
                newWidth = screen_width;
            }
            if (scaleImg_calc_height && newHeight > screen_height) {
                newWidth = newWidth * (screen_height / newHeight);
                newHeight = screen_height;
            }
            if (newWidth <= screen_width) {
                holder.style.left = (screen_width - newWidth) / 2 + padding;
            }
            if (newHeight <= screen_height) {
                holder.style.top = (screen_height - newHeight) / 2 + padding;
            }
            if (!is_callback) showBlackScreen(null, function() {scaleImg(obj, newWidth, newHeight, true);});
        }
        what.scale_info['image_width'] = what.width; what.scale_info['image_height'] = what.height;
        what.scale_info['style_width'] = getCSSValue(what, 'width'); what.scale_info['style_height'] = getCSSValue(what, 'height');
        what.style.width = newWidth; what.style.height = newHeight;
        what.scale_info['in_progress'] = false;
    } else {
        if (!empty(what.scale_info['in_progress'])) return;
        what.scale_info['in_progress'] = true;
        if (holder_mode) {
            if (placer) {
                placer.style.width = "";
                placer.style.height = "";
            }
            holder.style.position = "relative";
            holder.style.position = what.scale_info['holder_position'];
            holder.style.zIndex = what.scale_info['holder_zindex'];
            holder.style.left = holder.style.top = 0;
            if (!is_callback) showBlackScreen(null, null, true);
        }
        what.width = what.scale_info['image_width'];        what.height = what.scale_info['image_height'];
        what.style.width = what.scale_info['style_width'];  what.style.height = what.scale_info['style_height'];
        what.scale_info = null;
    }
}

function showBlackScreen(opc, click_callback, hide) {
    if (empty(opc) || !parseFloat(opc)) opc = 0.9;

    var div = getEl('tpl_black_screen');
    if (!div) {
        var div = document.createElement('DIV');
        div.id = 'tpl_black_screen';
        div.style.position = 'absolute';
        div.style.zIndex = '99';
        div.style.top = '0px';
        div.style.left = '0px';
        div.style.width = '100%';
        div.style.height = (window.innerWidth ? document.height : document.body.scrollHeight);
        div.style.backgroundColor = '#000000';
        div.onclick = function() { this.style.display = 'none'; if (click_callback) click_callback(); }
        document.body.appendChild(div);
    }
    div.style.filter = "alpha(opacity="+(opc * 100)+")";
    div.style.opacity = opc;
    div.style.display = 'block';
    if (hide) div.onclick();
    return false;
}

function wsld() {
    window.status="Image Loaded";
}

var image_origs = new Array();
var image_swap_filter = "progid:DXImageTransform.Microsoft.GradientWipe(GradientSize=1.0 Duration=0.5)";

function image_swap(code, src) {
    obj = getEl(code);
    if (Browser.ie && !tpl_suppress_veffects && image_swap_filter != "") {
        obj.style.filter = image_swap_filter;
        obj.filters[0].Apply();
    }
    if (!image_origs[code]) {
        image_origs[code] = new Image();
        image_origs[code].src = getEl(code).src;
    }
    if (Browser.ie && !tpl_suppress_veffects && image_swap_filter != ""){
        obj.filters[0].Play();
    }
    obj.src = src;
}

function image_restore(code) {
    obj = getEl(code);
    if (image_origs[code]) {
        obj.src = image_origs[code].src;
    }
}

function image_open(url, width, height) {
    if (typeof tb_show != 'undefined' && typeof eval('tb_show') == 'function' && tb_initialised) {
        tb_show("Image Preview", url);
        return false;
    }
    if (typeof olInfo != "undefined") {
        overlib("<img src='"+url+"' border='1' width='"+width+"' height='"+height+"' style='cursor: pointer' onClick='nd(100);' onMouseOut='nd(300);'>", TIMEOUT, 10000, RIGHT, BELOW, OFFSETX, 0 - (width /2), OFFSETY, 0 - (height /2), CLOSECLICK);
        return false;
    } else {
        var childW = window.open(url, 'imageview', 'scrollbars=yes,toolbar=no,status=no,resizable=no,width='+(width+40)+',height='+(height+40));
        childW.focus();
        return false;
    }
}



//-----------------------------------------------------
//--- Simple panes ------------------------------------
//-----------------------------------------------------

var panes = new Array();
var panes_queue = new Array();
var panes_pageLoaded = 0;
var panes_isSetup = 0;

function initPanes(containerId, defaultTabId, size_dims, unsized_height, forced) {
    var timeout_delay = 300;

    if (panes_pageLoaded) {
        timeout_delay = 0;
    } else {
        if (forced || !size_dims) {
            setupPanes(containerId, defaultTabId, size_dims, unsized_height);
        } else {
            var cnt = panes_queue.length;
            panes_queue[cnt] = new Object();
            panes_queue[cnt]['containerId'] = containerId;
            panes_queue[cnt]['defaultTabId'] = defaultTabId;
            panes_queue[cnt]['size_dims'] = size_dims;
            panes_queue[cnt]['unsized_height'] = unsized_height;
        }
    }

    setTimeout(function () {
        setupPanes(containerId, defaultTabId, size_dims, unsized_height);
    }, timeout_delay);
}

function initLoadPanes() {
    panes_pageLoaded = 1;
    for (var i=0; i < panes_queue.length; i++) {
        setupPanes(panes_queue[i]['containerId'], panes_queue[i]['defaultTabId'], panes_queue[i]['size_dims'], panes_queue[i]['unsized_height']);
    }
}

function setupPanes(main_contId, defaultTabId, size_dims, unsized_height) {
    if (panes[main_contId]) return;

    if (!(unsized_height>0)) unsized_height = 0;
    size_dims = (size_dims > 0);

    panes[main_contId] = new Array();
    var maxHeight = 0, maxWidth = 0;
    var resize_always = 1;
    var main_cont = getEl(main_contId), pane_cont;
    var div_cont = getElByTag("div", main_cont, true);
    var ul_cont = getElByTag("ul", main_cont, true);
    var activeTab, anchor = getAnchor();

    for (var i=0; i <= div_cont.length; i++) {
        if (div_cont[i].id == "panes") {
            pane_cont = div_cont[i];
            break;
        }
    }
    if (!pane_cont) return;

    var paneList = pane_cont.childNodes;
    for (var i=0; i < paneList.length; i++ ) {
        var pane = paneList[i];
        if (pane.nodeType != 1) continue;
        panes[main_contId][pane.id] = pane;

        if (size_dims) {
            var mw = parseInt(getCSSValue(pane, "margin-left")) + parseInt(getCSSValue(pane, "margin-right"));
            var mh = parseInt(getCSSValue(pane, "margin-top")) + parseInt(getCSSValue(pane, "margin-bottom"));
            mw = mw ? mw : 0; mh = mh ? mh : 0;
            if (pane.offsetWidth + mw  > maxWidth)  maxWidth  = pane.offsetWidth + mw;
            if (pane.offsetHeight + mh > maxHeight) maxHeight = pane.offsetHeight + mh;
        }
    }

    if (maxHeight && maxWidth) {
        if (Browser.ie) {
            var bw = parseInt(getCSSValue(pane_cont, 'border-left-width')) + parseInt(getCSSValue(pane_cont, 'border-right-width'));
            var bh = parseInt(getCSSValue(pane_cont, 'border-top-width')) + parseInt(getCSSValue(pane_cont, 'border-bottom-width'));
            maxWidth += bw;
            maxHeight += bh;
        }

        pane_cont.style.width = (pane_cont.offsetWidth < maxWidth || resize_always) ? maxWidth + "px" : pane_cont.offsetWidth;
        if (pane_cont.offsetHeight < maxHeight || resize_always) {
            pane_cont.style.height = (unsized_height) ? (maxHeight + (Browser.moz ? 14 : 8)) + "px" : maxHeight + "px";
        } else {
            pane_cont.style.height = pane_cont.offsetHeight;
        }
    }

    panes_isSetup = 1;
    var tabList = getPaneTabs(main_cont);

    // get from fn arg
    if (defaultTabId) {
        if (typeof defaultTabId == 'string') {
            var def_tabs = defaultTabId.replace(/ /g, '').split(',');
            for (i in def_tabs) {
                if (getEl(def_tabs[i])) {
                    activeTab = getEl(def_tabs[i]);
                    break;
                }
            }
        } else {
            if (getEl(defaultTabId)) {
                activeTab = getEl(defaultTabId);
            }
        }

    }

    // get from anchor
    if (!activeTab && tabList && anchor) {
        for (var i = 0; i < tabList.length; i++) {
            var attr = tabList[i].getAttribute("tab");
            if (attr && attr == anchor) {
                activeTab = tabList[i];
                break;
            }
        }
    }

    // first tab default
    if (!activeTab && tabList) activeTab = tabList[0];

    if (activeTab) activeTab.onclick();
    panes_isSetup = 0;
}

function showPane(paneId, activeTab, classBase, ahahUrl) {
    if (empty(classBase)) classBase = 'tab';
    var paneFader = (typeof paneSwitchFader != 'undefined' && paneSwitchFader);
    var cur_url = window.location.href.replace(/#.*/, "");

    for (var contId in panes) {
        if (panes[contId][paneId] == null) continue;

        for (var i in panes[contId]) {
            var pane = panes[contId][i];
            if (pane == undefined) continue;
            if (!empty(pane.style)) {
                if (pane.id == paneId) {
                    if (paneFader) fadeIn(pane); else showDiv(pane);
                    if (ahahUrl) ahahLoad(pane, ahahUrl);
                } else {
                    if (paneFader) fadeHide(pane); else hideDiv(pane);
                }
            }
        }

        var container = getEl(contId);
        tabList = getPaneTabs(container);
        for (var i = 0; i < tabList.length; i++) {
            var tab = tabList[i];
            if (tab.className != 'undefined' && tab.className != classBase + '_sep') {
                if (!hasClass(tab, classBase)) addClass(tab, classBase);
                removeClass(tab, classBase+"_OVER");
            }
        }
        if (!panes_isSetup) window.location.href = cur_url + "#" + activeTab.getAttribute("tab");
    }

    activeTab.blur();
    addClass(activeTab, classBase+"_OVER");

    return false;
}

function getPaneTabs(container) {
    var tabs, tabs_method;

    if (!tabs) { // div container method
        var div_containers = getElByTag("div", container, true);
        for (var i = 0; i <= div_containers.length; i++) {
            if (div_containers[i] && div_containers[i].id == "tabs") {
                tabs = div_containers[i];
                tabs_method = 1;
                break;
            }
        }
    }

    if (!tabs) { // ul container method
        var ul_containers = getElByTag("ul", container, true);
        for (var i = 0; i <= ul_containers.length; i++) {
            if (ul_containers[i] && ul_containers[i].id == "tabs") {
                tabs = ul_containers[i];
                tabs_method = 2;
                break;
            }
        }
    }

    if (tabs) {
        var tabList = new Array();
        if (tabs_method == 1) {
            if (!tabList.length) tabList = getElByTag("div", tabs, true);
            if (!tabList.length) tabList = getElByTag("td", tabs, true);
        } else if (tabs_method == 2) {
            if (!tabList.length) tabList = getElByTag("li", tabs, true);
        }
        if (tabList.length) {
            for (var i = 0; i < tabList.length; i++) {
                if (!tabList[i].getAttribute("tab")) tabList[i].setAttribute("tab", "def_"+tabList[i].getAttribute("id"));
            }
            return tabList;
        }
    }
    return new Array();
}





//-----------------------------------------------------
//--- Multilevel dropdown -----------------------------
//-----------------------------------------------------

var dropdowns_queue = new Array();
var dropdowns_pageLoaded = 0;

function initDropdown(parent, child, showtype, position, cursor, forced) {
    var timeout_delay = 300;

    if (dropdowns_pageLoaded) {
        timeout_delay = 0;
    } else {
        if (forced) {
            setupDropdown(parent, child, showtype, position, cursor)
        } else {
            var cnt = dropdowns_queue.length;
            dropdowns_queue[cnt] = new Array();
            dropdowns_queue[cnt]['parent'] = parent;
            dropdowns_queue[cnt]['child'] = child;
            dropdowns_queue[cnt]['showtype'] = showtype;
            dropdowns_queue[cnt]['position'] = position;
            dropdowns_queue[cnt]['cursor'] = cursor;
        }
    }

    setTimeout(function () {
        setupDropdown(parent, child, showtype, position, cursor)
    }, timeout_delay);
}

function initLoadDropdowns() {
    dropdowns_pageLoaded = 1;
    for (var i=0; i < dropdowns_queue.length; i++) {
        setupDropdown(dropdowns_queue[i]['parent'], dropdowns_queue[i]['child'], dropdowns_queue[i]['showtype'], dropdowns_queue[i]['position'], dropdowns_queue[i]['cursor']);
    }
}

function setupDropdown(parent, activator, showtype, position, cursor, dd_root) {
    var a = getEl(activator), p = getEl(parent);
    if (!a || !p) return;
    if (typeof position == 'undefined' || (position != "x" && position != "y")) position = "y";

    p.ddm = true;
    p["dd_children"] = new Array();
    p.setAttribute('dd_rel', (typeof dd_root == 'undefined' ? 'root' : activator));

    if (typeof dd_root == 'undefined') dd_root = p;
    p.setAttribute('dd_root', dd_root);

    var children = p.getElementsByTagName("li");
    for (var i = 0; i < children.length; i++) {
        p["dd_children"].push(children[i]);
        children[i].ddm = true;
        children[i].setAttribute('dd_rel', p);
        children[i].setAttribute('dd_root', dd_root);

        children[i].onmouseover = function(e) {
            clearTimeout(this["dd_timeout"]);
            clearTimeout(this.parentNode["dd_timeout"]);
            addClass(this, "selected");
        }
        children[i].onmouseout = function(e) {
            var tgt = this;
            tgt["dd_timeout"] = setTimeout(function () {
                removeClass(tgt, "selected");
            }, 10);
        }

        // recursively process submenu if there is one with id="(thisnode)-link"
        var submenuid = children[i].id.match(/(.*)-link/);
        var submenu;

        if (submenuid && submenuid[1] && (submenu = getEl(submenuid[1]))) {
            children[i].innerHTML = children[i].innerHTML + "<span class='submenu'>&nbsp;&nbsp;&nbsp;&nbsp;</span>";
            setupDropdown(submenu.id, children[i].id, showtype, "x", cursor, dd_root);
            children[i].setAttribute('dd_sub', submenu);
        }
    }

    a["dd_activator"] = p["dd_activator"] = a.id;
    a["dd_parent"] = p["dd_parent"] = p.id;
    a["dd_position"] = p["dd_position"] = position;

    p.style.position = "absolute";
    hideDiv(p);

    a.style.cursor = (cursor == undefined) ? "pointer" : cursor;
    p.onmouseover = ddShow;
    a.onmouseout = p.onmouseout = ddHide;

    switch (showtype) {
        case "click":
            a.onclick = ddClick;
            break;
        case "hover":
        default:
            a.onmouseover = ddShow;
            break;
    }
}

function ddShow(parent, activator) {
    if (typeof activator == "undefined" || typeof parent == "undefined") {
        var a = getEl(this["dd_activator"]), p = getEl(this["dd_parent"]);

        ddShow(p.id, a.id);
        clearTimeout(p["dd_timeout"]);

        while (a.nodeName == "LI") {
            clearTimeout(a.parentNode["dd_timeout"]);
            addClass(a, "selected");
            a = getEl(a.parentNode["dd_activator"]);
        }
        return;
    }

    var a = getEl(activator), p = getEl(parent);

    if (empty(p.possed)) {
        var top = (p["dd_position"] == "y") ? a.offsetHeight : 0;
        var left = (p["dd_position"] == "x") ? a.offsetWidth - 1 : 0;
        var pos = null;

        for (; a; a = a.offsetParent) {
            pos = getCSSValue(a, 'position');
            if (pos == 'absolute' && empty(a.dd_parent)) break;
            top += a.offsetTop;
            left += a.offsetLeft;
        }

        p.style.position = "absolute";
        p.style.top = top + "px";
        p.style.left = left + "px";
        p.possed = true;
    }


    if (have_jQuery) $(p).bgiframe(); // fix ie6 z-index bug
    showDiv(p);
}

function ddHide(caller, forced) {
    if (forced) {
        var a = getEl(caller["dd_activator"]);
        var p = getEl(caller["dd_parent"]);
    } else {
        var a = getEl(this["dd_activator"]);
        var p = getEl(this["dd_parent"]);
    }

    p["dd_timeout"] = setTimeout(function() {
        removeClass(a, "selected");
        hideDiv(p);

        while (a.nodeName == "LI") {
            if (isMouseOver(a.parentNode)) {
                break;
            } else {
                hideDiv(a.parentNode);
                a = getEl(a.parentNode['dd_activator']);
            }
        }
    }, (forced ? 0 : 100));
}

function ddForceHide(caller) {
    ddHide(caller, 1);
}

function ddClick() {
    var a = getEl(this["dd_activator"]);
    var p = getEl(this["dd_parent"]);

    if (!isVisible(p)) {
        ddShow(p.id, a.id);
    } else {
        hideDiv(p);
    }

    return false;
}


//-----------------------------------------------------
//--- Mouse position tracking -------------------------
//-----------------------------------------------------
addListener(document, "mousemove", function(event) {
    e = (typeof event != 'undefined' ? event : window.event);
    if (typeof e == 'undefined' || !e) return;

    if (e.pageX || e.pageY) {
        mouseX = e.pageX;
        mouseY = e.pageY;
    } else if (e.clientX || e.clientY) {
        mouseX = e.clientX + document.body.scrollLeft;
        mouseY = e.clientY + document.body.scrollTop;
    }
});

function isMouseOver(obj) {
    obj = getEl(obj);
    var pos = findPos(obj);
    var e = window.event;
    return !(mouseX < pos[0] || mouseX > pos[0] + obj.offsetWidth || mouseY < pos[1] || mouseY > pos[1] + obj.offsetHeight);
}


//-----------------------------------------------------
//--- Hint --------------------------------------------
//-----------------------------------------------------

var hint_mouseover = false;
var hint_hide_timeout = false;
var hint_div;

function hint(obj, content, options) {
    if (hint_mouseover) return;

    hint_div = getEl("hintbox");
    if (!hint_div) {
        try {
            hint_div = document.createElement("div");
            if (!hint_div) return;
            hint_div.id ="hintbox";
            document.body.appendChild(hint_div);
        } catch (e) { return; }
    }

    var sticky = true, width = "auto", height = "auto", hoffset = "0px", voffset = "0px";

    if (options && typeof options.sticky != "undefined") sticky = options.sticky;
    if (options && options.width) width = options.width;
    if (options && options.height) height = options.height;
    if (options && options.hoffset) hoffset = options.hoffset;
    if (options && options.voffset) voffset = options.voffset;

    if (hint_hide_timeout) clearTimeout(hint_hide_timeout);

    if (sticky) {
        hint_div.onmouseover = function() {
            hint_mouseover = true;
        }
        hint_div.onmouseout = function() {
            hint_mouseover = false;
            if (hint_hide_timeout) clearTimeout(hint_hide_timeout);
            hint_hide_timeout = setTimeout(hintForceHide, 300);
        }
    } else {
        hint_div.onmouseover = null;
        hint_div.onmouseout = null;
    }

    var iecompattest = function() {
        return (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
    }

    var clearbrowseredge = function(obj, whichedge) {
        var edgeoffset = (whichedge == "rightedge") ? parseInt(hoffset) * -1 : parseInt(voffset) * -1;
        if (whichedge == "rightedge") {
            var windowedge = Browser.ie ? iecompattest().scrollLeft + iecompattest().clientWidth - 30 : window.pageXOffset + window.innerWidth - 40;
            hint_div.contentmeasure = hint_div.offsetWidth;
            if (windowedge - hint_div.x < hint_div.contentmeasure) edgeoffset = hint_div.contentmeasure + obj.offsetWidth + parseInt(hoffset);
        }
        else {
            var windowedge = Browser.ie ? iecompattest().scrollTop + iecompattest().clientHeight - 15 : window.pageYOffset + window.innerHeight - 18;
            hint_div.contentmeasure = hint_div.offsetHeight;
            if (windowedge - hint_div.y < hint_div.contentmeasure) edgeoffset = hint_div.contentmeasure - obj.offsetHeight;
        }
        return edgeoffset;
    }

    var hidetip = function() {
        removeListener(this, "mouseout", hidetip);
        if (hint_hide_timeout) clearTimeout(hint_hide_timeout);
        if (sticky) hint_hide_timeout = setTimeout(hintForceHide, 300); else hint_hide_timeout = setTimeout(hintForceHide, 0);
    }

    var pos = findPos(obj);
    hint_div.innerHTML = content;
    hint_div.style.left = hint_div.style.top = -500;
    hint_div.x = pos[0];
    hint_div.y = pos[1];
    hint_div.style.width = width;
    hint_div.style.height = height;
    hint_div.style.left = hint_div.x - clearbrowseredge(obj, "rightedge") + obj.offsetWidth + "px";
    hint_div.style.top = hint_div.y - clearbrowseredge(obj, "bottomedge") + "px";
    hint_div.style.visibility = "visible";
    addListener(obj, "mouseout", hidetip);
}

function hintForceHide() {
    if (hint_mouseover) return;
    hint_div.style.visibility = "hidden";
    hint_div.style.left = "-500px";
}




//-----------------------------------------------------
//--- Simple content switching ------------------------
//-----------------------------------------------------

function contSwitch() {
    this.ObjectID, this.Object = "SlideShow";
    this.Count = 0, this.Speed = 0;
    this.FirstRun = true, this.MouseIsOver = false;
    this.Timer, this.NextSwitch = 0;
    this.Pos = 0;
    this.Randomize = 0, this.Fader = 1;

    this.timer_run = function(time_ms){
        if (!this.Speed) return 0;
        if (this.Timer) clearTimeout(this.Timer);

        var _self = this;
        return setTimeout(
            function() {
                if (_self.FirstRun) {
                    _self.FirstRun = false;
                } else {
                    if (_self.Timer) clearTimeout(_self.Timer);
                    if (!_self.MouseIsOver) _self.run();
                }
                _self.run();
            }, (time_ms || _self.Speed)
        );
    }

    this.run = function (mo) {
        if (mo) this.MouseIsOver = true;
        var unixtime = parseInt((new Date().getTime()) / 1000);

        if (this.NextSwitch > unixtime) {
            this.Timer = this.timer_run();
            return;
        } else {
            this.NextSwitch = unixtime + 1;
        }

        if (!this.Count) {
            this.Count = 0;
            var subList = this.ObjectID.childNodes;
            for (var i = 0; i < subList.length; i++) {
                if (subList[i].nodeType != 1) continue;
                this.Count++;
            }
        }

        if (!this.ObjectID) this.ObjectID = getEl(this.Object);

        if (this.Randomize && this.Count > 1) {
            while (1) {
                var tester = Math.ceil(this.Count * Math.random());
                if (tester != this.Pos) {
                    this.Pos = tester;
                    break;
                }
            }
        } else {
            this.Pos = (this.Pos + 1 > this.Count) ? 1 : this.Pos + 1;
            //debug('new pos'+this.Pos);
        }

        var cnt = 0;
        var subList = this.ObjectID.childNodes;
        for (var i = 0; i < subList.length; i++) {
            if (subList[i].nodeType != 1) continue;
            cnt++;
            if (cnt == this.Pos) {
                if (this.Fader && !tpl_suppress_veffects) fadeIn(subList[i]); else showDiv(subList[i]);
            } else {
                if (this.Fader && !tpl_suppress_veffects) fadeHide(subList[i]); else hideDiv(subList[i]);
            }
        }
        this.Timer = this.timer_run();
    }
}




//-----------------------------------------------------
//--- Dropdown ----------------------------------------
//-----------------------------------------------------

var dropdownMenu={};
function dropdown(e, menuId, parentId, eventType) {
    prntId = parentId || getEl(menuId).parentNode.id;
    if (hasClass(getEl(prntId), 'show-dropdown')) return;

    hideDropdown();
    dropdownMenu.id = menuId;
    dropdownMenu.parentId = prntId;
    dropdownMenu.eventType = eventType || "click";

    stopPropagation(e);
    showDiv(dropdownMenu.id);
    addClass(getEl(dropdownMenu.parentId), 'show-dropdown');
}
function hideDropdown(){
    if (dropdownMenu.id){
        hideDiv(dropdownMenu.id);
        removeClass(getEl(dropdownMenu.parentId), 'show-dropdown');
        dropdownMenu={};
    }
}

if (have_jQuery) {
    $(document).click(function() {
        hideDropdown();
    })
    .mouseover(function(e) {
        var el = e.target || e.srcElement;
        if (dropdownMenu && dropdownMenu.eventType && dropdownMenu.parentId){
            if (e.type.indexOf(dropdownMenu.eventType)!=-1 && !hasParent(el, dropdownMenu.parentId)) {
                hideDropdown();
            }
        }
    })
}




//-----------------------------------------------------
//--- Fader -------------------------------------------
//-----------------------------------------------------

var fadersVisible = new Array();
var fadersTimers = new Array();
var fadersMouseOver = new Array();

function fadeId(obj, ctx) {
    var obj_id = getElTags(obj, ctx);
    if (!obj_id) return -1;

    if (typeof obj_id.fader_id == 'undefined') {
        obj_id.fader_id = fadersVisible.length;
        if (obj_id.style && (obj_id.style.display == 'none' || obj_id.style.visibility == 'hidden' || getCSSValue(obj_id, "display") == 'none')) {
            fadersVisible[obj_id.fader_id] = 0;
        } else {
            fadersVisible[obj_id.fader_id] = 1;
        }
    }
    return obj_id.fader_id;
}

function fadeAnimator(obj, ctx, dir) {
    obj_id = getElTags(obj, ctx);
    if (dir == "out" && obj_id.style && obj_id.style.display == 'none') return;

    if (have_jQuery) {
        if (dir == "in") $(obj, ctx).fadeIn("fast"); else $(obj, ctx).fadeOut("def");
    } else {
        if (dir == "in") showDiv(obj_id); else hideDiv(obj_id);
    }
}

function fadeFader(obj, ctx, dir, mouse_track) {
    var obj_id = getElTags(obj, ctx);
    if (!obj_id) return -1;
    var fader_id = fadeId(obj, ctx);
    if (fader_id < 0) return;

    if (mouse_track) {
        if (dir == "in" && !fadersMouseOver[fader_id]) return;
        if (dir == "out" && fadersMouseOver[fader_id]) return;
        if (dir == "out" && fadersMouseOver[fader_id]) return;
    }

    if (dir == "in") {
        if (!fadersVisible[fader_id]) {
            fadeAnimator(obj, ctx, dir);
            fadersVisible[fader_id] = 1;
        }
    } else {
        if (fadersVisible[fader_id]) {
            fadeAnimator(obj, ctx, dir);
            fadersVisible[fader_id] = 0;
        }
    }
}

function fadeIn(obj, ctx, mouse_track) {
    if (!tpl_document_loaded) return;
    fadeFader(obj, ctx, "in", mouse_track);
}

function fadeOut(obj, ctx, mouse_track) {
    if (!tpl_document_loaded) return;
    fadeFader(obj, ctx, "out", mouse_track);
}

function fadeHide(obj, ctx) {
    var obj_id = getElTags(obj, ctx);
    if (!obj_id) return -1;
    var fader_id = fadeId(obj, ctx);
    if (fader_id < 0) return;

    fadersVisible[fader_id] = 0;
    hideDiv(obj_id);
}

function mouseFadeIn(obj, ctx) {
    var fader_id = fadeId(obj, ctx);
    fadersMouseOver[fader_id] = true;
    if (fadersTimers[fader_id]) clearTimeout(fadersTimers[fader_id]);
    fadersTimers[fader_id] = setTimeout(function() { fadeIn(obj, ctx, 1); }, 50);
}

function mouseFadeOut(obj, ctx) {
    var fader_id = fadeId(obj, ctx);
    fadersMouseOver[fader_id] = false;
    if (fadersTimers[fader_id]) clearTimeout(fadersTimers[fader_id]);
    fadersTimers[fader_id] = setTimeout(function() { fadeOut(obj, ctx, 1); }, 250);
}




//-----------------------------------------------------
//--- HTML tags ---------------------------------------
//-----------------------------------------------------

var blink_array = new Array();

function doBlink() {
    if (!blink_array.length) blink_array = getElByTag("blink", null, true);
    for (var i = 0; i < blink_array.length; i++) {
        blink_array[i].style.visibility = (blink_array[i].style.visibility == "") ? "hidden" : "";
    }
}

function startBlink() {
    if (document.all) { var blink_timer = setInterval("doBlink()", 500); }
}




//-----------------------------------------------------
//--- Misc stuff --------------------------------------
//-----------------------------------------------------

function window_open(url, width, height, target_win, new_win) {
    var width = (width != '' && width != undefined) ? width : 0;
    var height = (height != '' && height != undefined) ? height : 0;
    var my_url = url+(url.indexOf("?")!=-1 ? "&" : "?")+"in_window=1";

    if (target_win === null || target_win == undefined || target_win == 'undefined') {
        var caption = "<b>Window</b>";
    } else {
        var caption = target_win;
    }

    if (!width || !height) {
        return link_open(url, width, height, target_win, new_win);
    }

    if (!new_win && typeof tb_show != 'undefined' && typeof eval('tb_show') == 'function') {
        tb_show(caption, my_url+(my_url.indexOf("?")!=-1 ? "&" : "?")+"TB_iframe=true&width="+width+"&height="+height);
        return false;
    } else {
        var win = (target_win && target_win.length >= 3 && target_win.indexOf(" ") < 0) ? target_win : "_winopen";
        var wh_arg = (width && height) ? ',width='+(width+10)+',height='+(height+10) : '';
        var childW = window.open(my_url, win, 'scrollbars=yes,toolbar=no,status=no,resizable=no'+wh_arg);
        childW.focus();
        return false;
    }
}

function window_close(obj) {
    if (typeof obj == 'undefined' || !obj) obj = null;
    var win = window;
    var url = '';

    if (obj) {
        if (getEl(obj)) {
            var win = getEl(obj);
        } else {
            var url = obj;
        }
    }

    if (typeof parent != 'undefined' && parent) {
        if (!obj && typeof parent.tb_show != 'undefined' && parent.tb_showing) {
            parent.tb_remove();
            return false;
        }
    }

    if (typeof win.opener != 'undefined' && win.opener) {
        if (url) {
            win.opener.location.href = url;
        }
        win.opener.focus();
    }
    win.close();

    return false;
}

function link_open(url, width, height, target_win, new_win) {
    var width = (width != '' && width != undefined) ? width : 0;
    var height = (height != '' && height != undefined) ? height : 0;
    if (width && height) {
        window_open(url, width, height, target_win, new_win);
    } else {
        var fakeLink = document.createElement("a");
        if (typeof fakeLink.click == 'undefined') {
            location.href = url;  // sends referrer in FF, not in IE
        } else {
            fakeLink.href = url;
            if (target_win && new_win) fakeLink.target = target_win;
            document.body.appendChild(fakeLink);
            fakeLink.click();   // click() method defined in IE only
        }
    }
    return false;
}

function link_open_confirm(url, text, width, height, target_win, new_win) {
    if (confirm(text)) {
        link_open(url, width, height, target_win, new_win);
    }
    return false;
}

function link_open_timer(url, timeout, width, height, target_win, new_win) {
    width = (width != '' && width != undefined) ? width : '';
    height = (height != '' && height != undefined) ? height : '';
    target_win = (target_win != '' && target_win != undefined) ? target_win : '';
    new_win = (new_win != '' && new_win != undefined) ? new_win : '';
    timeout = (timeout != '' && timeout != undefined) ? parseInt(timeout) : 5000;
    setTimeout("link_open('"+url+"', '"+width+"', '"+height+"', '"+target_win+"', '"+new_win+"');", timeout);
}

function link_reflect(url) {
    return link_open(url+(url.indexOf("?")!=-1 ? "&" : "?")+"return="+urlencode(window.location.href));
}

function get_window_parent(obj) {
    var win = window;
    if (typeof obj != 'undefined' && obj && getEl(obj)) win = getEl(obj);

    if (typeof win.parent != 'undefined' && win.parent && win.parent != window) {
        return win.parent;
    }

    if (typeof win.opener != 'undefined' && win.opener && win.opener != window) {
        return win.opener;
    }

    return false;
}

function swf_mouseOut(code) {
    obj = getEl(code);
    if (obj) {
        obj.SetVariable("mouse_is_out", 1);
    }
}

function change_bgcolor(obj, clr) {
    var obj_id = getEl(obj);
    if (obj_id) {
        obj_id.style.backgroundColor=clr;
    }
}


function upload_progress_bar(the_form, the_progress, the_url) {
    var prg_bar = getEl(the_progress);

    if (document.forms[the_form]) {
        var upload_uid = document.forms[the_form].UPLOAD_IDENTIFIER.value;
        var iframe_url = the_url + "&u_id=" + upload_uid + "&ts=" + (new Date().getTime());
        prg_bar.style.height = 50;
        showDiv(prg_bar);
        prg_bar.innerHTML = '<iframe id="'+the_progress+'_ifrm" width="100%" height="50" frameborder="0" marginwidth="0" marginheight="0" scrolling="NO"><html><head></head><body>Uploading...</body></html></iframe>';
        setTimeout(function() { var prg_bar_ifrm = getEl(the_progress+'_ifrm'); prg_bar_ifrm.src = iframe_url; }, 500);

        if (getEl('async_iframe')) {
            //document.forms[the_form].target = 'async_iframe';
        }
        if (document.forms[the_form].submiter) {
            document.forms[the_form].submiter.disabled = true;
        }
        if (document.forms[the_form].submitter) {
            document.forms[the_form].submitter.disabled = true;
        }
        if (document.forms[the_form].more_files) {
            document.forms[the_form].more_files.disabled = true;
        }
    }
    return true;
}

function moreFields(counter_arg, src_arg, dst_arg) {
    if (!have_jQuery) return;

    counter = getElTags(counter_arg);
    src_div = getElTags(src_arg);
    dst_div = getElTags(dst_arg);


    fixFormsIDs();
    counter.value++;
    var newFields = src_div.cloneNode(true);
    newFields.id = src_div.id + counter.value;

    $("#delete_row_div", newFields).css("display", "block");
    $("#delete_row_button", newFields).attr("prnt_id", newFields.id);

    var src = $(src_div).contents().find("textarea, input, select");
    var dst = $(newFields).contents().find("textarea, input, select");
    for (var i=0; i<src.length; i++) {
        if (src[i].id == 'undefined' || src[i].id == '') {
            src[i].id = src[i].name;
        }
        if (src[i].name != 'delete_row_button') {
            dst[i].value = '';
        }
        if (src[i].name) {
            dst[i].name = src[i].name + '_' + counter.value;
        }
        if (src[i].id) {
            dst[i].id = src[i].id + '_' + counter.value;
        }
    }

    $(newFields).insertBefore(dst_div);
    $(newFields).css("display", "none");
    $(newFields).slideDown("fast");
    onLoad_fix(newFields);
}

function removeFields(obj) {
    if (!have_jQuery) return;

    var parentId = "#" + $(obj).attr("prnt_id");
    $(parentId).slideUp("fast");
    setTimeout('$("' + parentId + '").remove()', 500);
}



function setEditable(obj, i) {
    if (!have_jQuery) return;

    $(obj).click(function() {
        if ($(obj).attr('expanded') == 'yes') return;

        var form = '<div><textarea rows="2" cols="60" style="width: 90%">'+$(this).html()+'</textarea><div><input type="button" value="OK" class="button saveButton"> <input type="button" value="Cancel" class="button cancelButton"></div></div>';
        var revert = $(obj).html();
        $(obj).attr('expanded', 'yes').css('display', 'none');
        $(obj).after(form);
        $('.saveButton').click(function(){saveEditable(this, false, i);});
        $('.cancelButton').click(function(){saveEditable(this, revert, i);});

        // focus field
        var txtarea = $(obj).next().children(0).get(0);
        var txtlen = txtarea.value.length;
        if (txtarea.setSelectionRange)  {
            txtarea.focus();
            txtarea.setSelectionRange(txtlen,txtlen);
        } else if (txtarea.createTextRange) {
            var range = txtarea.createTextRange();
            range.collapse(true);
            range.moveEnd('character', txtlen);
            range.moveStart('character', txtlen);
            range.select();
        }
        txtarea.focus();

        onLoad_fix(obj);
        return false;
    })
    .mouseover(function() {
        $(obj).addClass("editable_hover");
    })
    .mouseout(function() {
        $(obj).removeClass("editable_hover");
    });
}

function saveEditable(obj, cont, n) {
    if (!have_jQuery) return;

    var ajax_action = $(obj).parent().parent().prev().attr('dest_action');
    var ajax_type = $(obj).parent().parent().prev().attr('dest_type');
    var ajax_id = $(obj).parent().parent().prev().attr('dest_id');

    if (!cont) {
        var txt_val = $(obj).parent().siblings(0).val();
        $.post("/ajax_ctl.php", {
            action: ajax_action,
            type: ajax_type,
            id: ajax_id,
            content: txt_val,
            n: n
        }, function(txt){
            if (txt.toLowerCase() != 'ok') {
                alert(txt);
            }
        });
    } else {
        var txt_val = cont;
    }
    if (txt_val=='') txt_val='(click to add text)';

    $(obj).parent().parent().prev().html(txt_val).attr('expanded', 'no').css('display', 'block');
    setEditable($(obj).parent().parent().prev(), n);
    $(obj).parent().parent().remove();
}


var animatedButtons = new Array();
function animateButton(obj, klass) {
    var cnt = animatedButtons.length;
    animatedButtons[cnt] = new Array();
    animatedButtons[cnt]['obj'] = obj;
    animatedButtons[cnt]['klass'] = klass;
}


function tb_controls_template() {
    var div = document.createElement('div');
    div.innerHTML = div.innerHTML + "<div class='tb_top'><div class='tb_top_left'></div><div class='tb_top_right'></div></div>";
    div.innerHTML = div.innerHTML + "<div class='tb_bottom'><div class='tb_bottom_left'></div><div class='tb_bottom_right'></div></div>";

    return div;
}

function tb_controls(obj, e, props) {
    stopPropagation(e);

    if (!empty(obj.tb_ctl)) {
        mouseFadeIn(obj.tb_ctl);
        return;
    }

    var holder = tb_controls_template();
    var box = getElByClass("tb_box", obj);
    if (!box) box = obj;

    addClass(holder, "tb_ctl");
    if (Browser.ie) {
        holder.style.width = box.offsetWidth;
        holder.style.height = box.offsetHeight;
    }

    getElByClass("tb_bottom", holder).style.top = box.offsetHeight;
    var sub_divs = getElByTagClass("div", "tb_(\\w+)", holder, true);
    for (var i=0; i<sub_divs.length; i++) {
        sub_divs[i].style.width = box.offsetWidth;
    }

    for (var vpos in props) {
        if (vpos != 'top' && vpos != 'bottom') {
            if (typeof props['bottom'] == 'undefined') props['bottom'] = new Array();
            props['bottom'][vpos] = props[vpos]; delete props[vpos];
        }
    }
    for (var vpos in props) {
        for (var hpos in props[vpos]) {
            var defpos = (vpos == "bottom" ? "left" : "right");
            if (hpos != 'left' && hpos != 'right') {
                if (typeof props[vpos][defpos] == 'undefined') props[vpos][defpos] = new Array();
                props[vpos][defpos][hpos] = props[vpos][hpos]; delete props[vpos][hpos];
            }
        }
    }

    for (var vpos in props) {
        for (var hpos in props[vpos]) {
            for (var elm in props[vpos][hpos]) {
                if (elm == 's' || elm == 'e' || elm == 'fake') continue;
                var prop = props[vpos][hpos][elm];

                if (elm.indexOf('custom') == 0) {
                    var tmp_elm = document.createElement('div');
                    tmp_elm.innerHTML = prop['content'];
                    getElByClass("tb_"+vpos+"_"+hpos, holder).appendChild(tmp_elm);
                    continue;
                }

                var link = document.createElement('a');
                if ((prop['w'] && prop['h']) || prop['win']) {
                    link.dest_link = prop['link']; link.dest_title = (prop['title'] ? prop['title'] : prop['text']);
                    link.dest_w = (prop['w'] ? prop['w'] : 450); link.dest_h = (prop['h'] ? prop['h'] : 170);
                    link.onclick = function() { return link_open(this.dest_link, this.dest_w, this.dest_h, this.dest_title); }
                    link.href = '#';
                } else if (prop['confirm']) {
                    link.dest_link = prop['link']; link.dest_title = (prop['title'] ? prop['title'] : prop['text']);
                    link.onclick = function() { return link_open_confirm(this.dest_link, this.dest_title); }
                    link.href = '#';
                } else {
                    link.href = prop['link'];
                }

                var img = document.createElement('img');
                img.src = tpl_image_url+"/spacer.gif";
                addClass(img, elm);
                //img.width = img.height = 20;
                img.alt = img.title = prop['text'];
                img.style.borderWidth = 0;
                if (prop['overlib']) {
                    img.dest_link = prop['link']; img.dest_title = (prop['title'] ? prop['title'] : prop['text']);
                    img.dest_image = prop['image'];
                    img.onmouseover = function() { overlib("<a href='"+this.dest_link+"'><img src='"+this.dest_image+"' border='0'><br><center><b>"+this.dest_title+"</b></center></a>"); }
                    img.onmouseout = function() { nd(); }
                }
                link.appendChild(img);

                getElByClass("tb_"+vpos+"_"+hpos, holder).appendChild(link);
            }
        }
    }

    hideDiv(holder);
    box.appendChild(holder);
    obj.tb_ctl = holder;
    mouseFadeIn(obj.tb_ctl);
}

function tb_out(obj) {
    if (!empty(obj.tb_ctl)) {
        stopPropagation(e);
        mouseFadeOut(obj.tb_ctl);
    }
}


//-----------------------------------------------------
//--- onLoad handlers ---------------------------------
//-----------------------------------------------------

function fixIEdivs() {
    if (!have_jQuery) return;
    if (!Browser.ie) return;

    var divs = $("div").get();
    for (i in divs) {
        var brd_w = 0;
        var brd_h = 0;
        brd_w = brd_w + (parseInt(getCSSValue(divs[i], "border-left-width")) || 0);
        brd_w = brd_w + (parseInt(getCSSValue(divs[i], "border-right-width")) || 0);
        brd_h = brd_h + (parseInt(getCSSValue(divs[i], "border-top-width")) || 0);
        brd_h = brd_h + (parseInt(getCSSValue(divs[i], "border-bottom-width")) || 0);

        debug(divs[i].style.width+' - '+divs[i].offsetWidth+' -> '+brd_w);
        if (divs[i].offsetWidth >= brd_w) {
            //divs[i].style.width = divs[i].offsetWidth - brd_w;
        }
        if (divs[i].offsetHeight >= brd_h) {
            //divs[i].style.height = divs[i].offsetHeight - brd_h;
        }
    }
}

function fixPNG() {
    if (!Browser.ie) return false;

    for (var i=0; i < document.images.length; i++) {
        var img = document.images[i];
        var imgName = img.src.toUpperCase();
        if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
            var imgID = (img.id) ? "id='" + img.id + "' " : "";
            var imgClass = (img.className) ? "class='" + img.className + "' " : "";
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
            var imgStyle = "display: inline-block;" + img.style.cssText;
            if (img.align == "left" || img.align == "right") imgStyle = "float: "+img.align+";" + imgStyle;
            if (img.parentElement.href) imgStyle = "cursor: hand;" + imgStyle;
            var strNewHTML = '<span ' + imgID + imgClass + imgTitle+' style="' + 'width:' + img.width + 'px; height:' + img.height + 'px;' + imgStyle + "; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
            img.outerHTML = strNewHTML;
            i = i-1;
        }
    }
    return true;
}

function fixFormsIDs() {
    if (!have_jQuery) return;

    var inputs = $("textarea, select, input").get();
    for (i in inputs) {
        if (typeof inputs[i].name != 'undefined') {
            if (inputs[i].id == 'undefined' || inputs[i].id == '') {
                inputs[i].id = inputs[i].name;
            }
        }
        if (typeof inputs[i].id != 'undefined') {
            if (inputs[i].name == 'undefined' || inputs[i].name == '') {
                inputs[i].name = inputs[i].id;
            }
        }
    }
}

function fixCSS(context) {
    if (!have_jQuery) return;

    // input fields

    $("textarea, input", context)
        .bind("focus", function(e) { $(this).addClass("fakefocus"); })
        .bind("blur", function(e) { $(this).removeClass("fakefocus"); });

    $('input[type="text"], input[type="password"], input[type="file"]', context).addClass('input_text');

    $('input[type="button"], input[type="submit"], input[type="reset"], input[type="image"]', context)
        .css('cursor', 'pointer')
        .unbind('focus');

    //$('input[type="checkbox"]').addClass('checkbox');
    //$('input[type="radio"]').addClass('radio');
    //$("a").hover(function(){$(this).fadeOut(100);$(this).fadeIn(500);});
    //$(".tb_fade").css('display', 'none');
}

function fixUI(context) {
    if (!have_jQuery) return;

    if (Browser.moz) {
        if (context) {
            $("img", context).each( function(i) { $(this).attr('title', $(this).attr('alt')); } );
        } else {
            onLoadExec(function() { $("img", context).each( function(i) { $(this).attr('title', $(this).attr('alt')); } ); }, 1000);
        }
    }

    $(".editable", context).each( function(i) { setEditable(this, i); } );

    // generic buttons
    $('button, .button, .button_big, .bbcbutton', context)
        .mouseenter(function() { $(this).addClass('button_hover'); })
        .mouseleave(function() { $(this).removeClass('button_hover'); $(this).removeClass('button_click'); })
        .mousedown(function() { $(this).addClass('button_click'); })
        .mouseup(function() { $(this).removeClass('button_click'); });

    // animated buttons
    for (var i=0; i < animatedButtons.length; i++) {
        $(animatedButtons[i]['obj'], context)
            .attr('klass', animatedButtons[i]['klass'])
            .mouseenter(function() {
                $(this).addClass($(this).attr('klass')+'_OVER');
            })
            .mouseleave(function() {
                $(this).removeClass($(this).attr('klass')+'_OVER');
                $(this).removeClass($(this).attr('klass')+'_CLICK');
            })
            .mousedown(function() {
                $(this).addClass($(this).attr('klass')+'_CLICK');
            })
            .mouseup(function() {
                $(this).removeClass($(this).attr('klass')+'_CLICK');
            });
    }
}

var onLoadExec_list = new Array();
function onLoadExec(fn, delay) {
    if (!fn) return;
    for (var i=0; i < onLoadExec_list.length; i++) {
        if (fn == onLoadExec_list[i]) return;
    }
    var cnt = onLoadExec_list.length;
    onLoadExec_list[cnt] = new Array();
    onLoadExec_list[cnt]['fn'] = fn;
    onLoadExec_list[cnt]['delay'] = delay || 0;
}

function onLoad_first() {
    //debug('dom done '+(gmt() - stm));
    onLoad_fix(null, true);
    initLoadPanes();
    if (!tpl_suppress_veffects) startBlink();
}

function onLoad_exec() {
    for (var i=0; i < onLoadExec_list.length; i++) {
        if (onLoadExec_list[i]) {
            setTimeout(onLoadExec_list[i]['fn'], onLoadExec_list[i]['delay']);
        }
    }
}

function onLoad_fix(ctx, initial) {
    if (!tpl_document_loaded) return;
    fixCSS(ctx);
    fixUI(ctx);
}

function onLoad_init(timer_call, ctx) {
    have_jQuery = (typeof jQuery != 'undefined') ? 1 : 0;

    if (tpl_document_loaded) {
        if (timer_call) {
            //debug('dom post '+(gmt() - stm));
            return;
        }
        onLoad_fix(ctx);
    } else {
        tpl_document_loaded = true;
        onLoad_first();
        onLoad_exec();
    }
}

if (Browser.moz && document.addEventListener) {
    document.addEventListener("DOMContentLoaded", function () { onLoad_init(1); }, false);
}

if (have_jQuery) {
    $(function () { onLoad_init(1); });
} else {
    setTimeout("onLoad_init(1)", 2000);
}
