var scriptBaseUrl = null;

function getScriptBaseUrl()
{
    if (null === scriptBaseUrl) {
        var list = document.getElementsByTagName("script");
        for (i = 0; i < list.length; i++) {
            if (list[i].src.match(/functions\.js$/)) {
                scriptBaseUrl = list[i].src.replace('/functions.js', '');
                break;
            }
        }
    }
    return scriptBaseUrl;
}

function includeBodyScript(src)
{
    var scriptNode = document.createElement('script');
    scriptNode.type = 'text/javascript';
    scriptNode.src = getScriptBaseUrl() + '/' + src;
    document.body.appendChild(scriptNode);
}

var wzTooltipIncluded = false;
function includeWzTooltip()
{
    if (wzTooltipIncluded) {
        return false;
    }
    includeBodyScript('wz_tooltip.js');
    includeBodyScript('tip_balloon.js');
    wzTooltipIncluded = true;
    return true;
}

function in_array(search_phrase, array)
{
    for( var i = 0; i < array.length; i++ ) {
        if( search_phrase == array[i] ){
            return true;
        }
    }
    return false;
}

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

Object.extend = function(destination, source) {
  for (var property in source)
    destination[property] = source[property];
  return destination;
};

function getParentTag(obj, tag)
{
    var tmp = obj;
    while (tmp = tmp.parentNode) {
        if (tmp.nodeName == tag) {
            return tmp;
        }
    }
    return null;
}

function getPreviousTag(obj, tag)
{
    var tmp = obj;
    while (tmp = tmp.previousSibling) {
        if (tmp.nodeName == tag) {
            return tmp;
        }
    }
    return null;
}

function getNextTag(obj, tag)
{
    var tmp = obj;
    while (tmp = tmp.nextSibling) {
        if (tmp.nodeName == tag) {
            return tmp;
        }
    }
    return null;
}

function openPopupByLocation(location, target, width, height)
{
    if (typeof width != 'number') {
        if (width == 'MAX') {
            width = screen.width;
        } else {
            width = screen.width/2;
        }
    }
    if (typeof height != 'number') {
        if (height == 'MAX') {
            height = screen.height;
        } else {
            height = screen.height - screen.height/3;
        }
    }
    var top = screen.height/2-height/2;
    var left = screen.width/2-width/2;
    var params = 'toolbar=0,location=0,menubar=0,resizable=1,status=0,scrollbars=yes,screenX='
               + left + ',screenY=' + top + ',top=' + top + ',left=' + left
               + ',width=' + width + ',height=' + height;
    var wnd = window.open(location, target, params);
        wnd.opener = self;
        wnd.focus();
}

function openPopup(a, width, height)
{
    openPopupByLocation(a.href, a.getAttribute('target'), width, height);
    return false;
}

function getElementPos(obj)
{
    var l = 0;
    var t = 0;
    var w = obj.offsetWidth;
    var h = obj.offsetHeight;
    while (obj) {
        l += obj.offsetLeft;
        t += obj.offsetTop;
        if ((obj.tagName != "TABLE") && (obj.tagName != "BODY")) {
            l += (obj.clientLeft)?obj.clientLeft:0;
            t += (obj.clientTop)?obj.clientTop:0;
        }
        obj = obj.offsetParent;
    }
    var res = new Object();
    res.x = l;
    res.y = t;
    res.left = l;
    res.top = t;
    res.w = w;
    res.h = h;
    res.width = w;
    res.height = h;
    return res;
}

function vdie()
{
    var __getType = function( inp ) {
        var type = typeof inp, match;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            if (match = cons.match(/(\w+)\(/)) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var content = '';
    for (var i =0; i < arguments.length; i++) {
        content += (i + 1) + ') [' + __getType(arguments[i]) + '] ' + print_r(arguments[i], true) + '\n';
    }
    alert(content);
}

// php.js

function urlencode( str )
{
    var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];
    var ret = str.toString();

    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };

    // The histogram is identical to the one in urldecode.
    histogram['!']   = '%21';
    histogram['%20'] = '+';

    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);

    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }

    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });

    return ret;
}

function number_format( number, decimals, dec_point, thousands_sep )
{
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}


function ucfirst( str )
{
    str += '';
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1, str.length-1);
}

function in_array(needle, haystack, strict)
{
    var found = false, key, strict = !!strict;
    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }
    return found;
}

function print_r( array, return_val )
{
    var output = "", pad_char = " ", pad_val = 4;
    var formatArray = function (obj, cur_depth, pad_val, pad_char) {
        if (cur_depth > 0) {
            cur_depth++;
        }

        var base_pad = repeat_char(pad_val*cur_depth, pad_char);
        var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
        var str = "";

        if (obj instanceof Array || obj instanceof Object) {
            str += "Array\n" + base_pad + "(\n";
            for (var key in obj) {
                if (obj[key] instanceof Array) {
                    str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char);
                } else {
                    str += thick_pad + "["+key+"] => " + obj[key] + "\n";
                }
            }
            str += base_pad + ")\n";
        } else if(obj == null || obj == undefined) {
            str = '';
        } else {
            str = obj.toString();
        }

        return str;
    };

    var repeat_char = function (len, pad_char) {
        var str = "";
        for(var i=0; i < len; i++) {
            str += pad_char;
        };
        return str;
    };
    output = formatArray(array, 0, pad_val, pad_char);

    if (return_val !== true) {
        document.write("<pre>" + output + "</pre>");
        return true;
    } else {
        return output;
    }
}

var Qs_Message = Class.create();

Qs_Message.prototype = {

    initialize: function (messages)
    {
        this.messages = messages;
    },

    get: function (name, language)
    {
        if (typeof language == 'undefined') {
            language = CURRENT_LANGUAGE;
        }
        if (typeof this.messages[language] == 'undefined') {
            return '';
        }
        if (typeof this.messages[language][name] == 'string') {
            return this.messages[language][name];
        }
        if (typeof this.messages[DEFAULT_LANGUAGE][name] == 'string') {
            return this.messages[DEFAULT_LANGUAGE][name];
        }
        return '';
    }
}

function sprintf( )
{
    var regex = /%%|%(\d+\$)?([-+#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;
    var a = arguments, i = 0, format = a[i++];

    // pad()
    var pad = function(str, len, chr, leftJustify) {
        var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
        return leftJustify ? str + padding : padding + str;
    };

    // justify()
    var justify = function(value, prefix, leftJustify, minWidth, zeroPad) {
        var diff = minWidth - value.length;
        if (diff > 0) {
            if (leftJustify || !zeroPad) {
                value = pad(value, minWidth, ' ', leftJustify);
            } else {
                value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
            }
        }
        return value;
    };

    // formatBaseX()
    var formatBaseX = function(value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
        // Note: casts negative numbers to positive ones
        var number = value >>> 0;
        prefix = prefix && number && {'2': '0b', '8': '0', '16': '0x'}[base] || '';
        value = prefix + pad(number.toString(base), precision || 0, '0', false);
        return justify(value, prefix, leftJustify, minWidth, zeroPad);
    };

    // formatString()
    var formatString = function(value, leftJustify, minWidth, precision, zeroPad) {
        if (precision != null) {
            value = value.slice(0, precision);
        }
        return justify(value, '', leftJustify, minWidth, zeroPad);
    };

    // finalFormat()
    var doFormat = function(substring, valueIndex, flags, minWidth, _, precision, type) {
        if (substring == '%%') return '%';

        // parse flags
        var leftJustify = false, positivePrefix = '', zeroPad = false, prefixBaseX = false;
        var flagsl = flags.length;
        for (var j = 0; flags && j < flagsl; j++) switch (flags.charAt(j)) {
            case ' ': positivePrefix = ' '; break;
            case '+': positivePrefix = '+'; break;
            case '-': leftJustify = true; break;
            case '0': zeroPad = true; break;
            case '#': prefixBaseX = true; break;
        }

        // parameters may be null, undefined, empty-string or real valued
        // we want to ignore null, undefined and empty-string values
        if (!minWidth) {
            minWidth = 0;
        } else if (minWidth == '*') {
            minWidth = +a[i++];
        } else if (minWidth.charAt(0) == '*') {
            minWidth = +a[minWidth.slice(1, -1)];
        } else {
            minWidth = +minWidth;
        }

        // Note: undocumented perl feature:
        if (minWidth < 0) {
            minWidth = -minWidth;
            leftJustify = true;
        }

        if (!isFinite(minWidth)) {
            throw new Error('sprintf: (minimum-)width must be finite');
        }

        if (!precision) {
            precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : void(0);
        } else if (precision == '*') {
            precision = +a[i++];
        } else if (precision.charAt(0) == '*') {
            precision = +a[precision.slice(1, -1)];
        } else {
            precision = +precision;
        }

        // grab value using valueIndex if required?
        var value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];

        switch (type) {
            case 's': return formatString(String(value), leftJustify, minWidth, precision, zeroPad);
            case 'c': return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
            case 'b': return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'o': return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'x': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'X': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
            case 'u': return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'i':
            case 'd': {
                        var number = parseInt(+value);
                        var prefix = number < 0 ? '-' : positivePrefix;
                        value = prefix + pad(String(Math.abs(number)), precision, '0', false);
                        return justify(value, prefix, leftJustify, minWidth, zeroPad);
                    }
            case 'e':
            case 'E':
            case 'f':
            case 'F':
            case 'g':
            case 'G':
                        {
                        var number = +value;
                        var prefix = number < 0 ? '-' : positivePrefix;
                        var method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
                        var textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
                        value = prefix + Math.abs(number)[method](precision);
                        return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
                    }
            default: return substring;
        }
    };

    return format.replace(regex, doFormat);
}

function reset ( array )
{
    var first_elm, key;

    if (array.constructor == Array){
        first_elm = array[0];
    } else {
        for (key in array){
            first_elm = array[key];
            break;
        }
    }
    return first_elm;
}

function array_key ( array )
{
    for (key in array){
        return key;
    }
    return null;
}

function popupImage(url)
{
    var startW = 150;
    var startH = 100;
    var top = screen.height/2-startH;
    var left = screen.width/2-startW/2;
    var params = 'Toolbar=0,location=0,Menubar=0,resizable=0,Scrollbars=no';//,screenX='+left+',screenY='+top+',top='+top+',left='+left;
    var wnd = window.open('', 'ppimg', params);
    wnd.resizeTo(300, 450);
    wnd.document.writeln('<html>');
    wnd.document.writeln('<head>');
    wnd.document.writeln('<style>');
    wnd.document.writeln('html, body {margin:0px; padding:0px;}');
    wnd.document.writeln('</style>');
    wnd.document.writeln('<script type="text/javascript">');
    wnd.document.writeln('function myResize(w,h){');
    wnd.document.writeln('window.resizeTo(w,h);');
    wnd.document.writeln('}');
    wnd.document.writeln('var img = new Image(); ');
    wnd.document.writeln('window.onload = function(){');
    wnd.document.writeln('img.onload=function(){');
    wnd.document.writeln('document.getElementById(\'id_image\').src=this.src; ');
    wnd.document.writeln('window.resizeBy(this.width-document.body.clientWidth, this.height-document.body.clientHeight);');
    wnd.document.writeln('var top = screen.height/2-this.height/2; ');
    wnd.document.writeln('var left = screen.width/2-this.width/2; ');
    wnd.document.writeln('window.moveTo(left, top)');
    wnd.document.writeln('}');
    wnd.document.writeln('img.src=\''+url+'\'; ');
    wnd.document.writeln('}');
    wnd.document.writeln('</script>');
    wnd.document.writeln('</head>');
    wnd.document.writeln('<body>');
    wnd.document.writeln('<img id="id_image" src="images/loading-arrow-16x16.gif" onclick = "window.close();" alt="Click to close window.">');
    wnd.document.writeln('</body>');
    wnd.document.writeln('</html>');
    wnd.document.close();
    return false;
}

function getPageSize(){

    var xScroll, yScroll;

    if (window.innerHeight && window.scrollMaxY) {
        xScroll = window.innerWidth + window.scrollMaxX;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }

    var windowWidth, windowHeight;

//  console.log(self.innerWidth);
//  console.log(document.documentElement.clientWidth);

    if (self.innerHeight) { // all except Explorer
        if(document.documentElement.clientWidth){
            windowWidth = document.documentElement.clientWidth;
        } else {
            windowWidth = self.innerWidth;
        }
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }

    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }

//  console.log("xScroll " + xScroll)
//  console.log("windowWidth " + windowWidth)

    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){
        pageWidth = xScroll;
    } else {
        pageWidth = windowWidth;
    }
//  console.log("pageWidth " + pageWidth)

    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
    return arrayPageSize;
}

function is_string (/*anything*/ it)
{
    return !!arguments.length && it != null && (typeof it == "string" || it instanceof String); // Boolean
}

function is_array (/*anything*/ it)
{
    return it && (it instanceof Array || typeof it == "array"); // Boolean
}

function intval(mixed_var, base)
{
    // Get the integer value of a variable using the optional base for the conversion
    //
    // version: 905.412
    // discuss at: http://phpjs.org/functions/intval
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: stensi
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: intval('Kevin van Zonneveld');
    // *     returns 1: 0
    // *     example 2: intval(4.2);
    // *     returns 2: 4
    // *     example 3: intval(42, 8);
    // *     returns 3: 42
    // *     example 4: intval('09');
    // *     returns 4: 9
    var tmp;

    var type = typeof( mixed_var );

    if(type == 'boolean'){
        if (mixed_var == true) {
            return 1;
        } else {
            return 0;
        }
    } else if(type == 'string'){
        tmp = parseInt(mixed_var * 1, 10);
        if(isNaN(tmp) || !isFinite(tmp)){
            return 0;
        } else{
            return tmp.toString(base || 10);
        }
    } else if(type == 'number' && isFinite(mixed_var) ){
        return Math.floor(mixed_var);
    } else{
        return 0;
    }
}

