function makeRequest( url, targetElementId )
{
    var http_request = false;

    if ( window.XMLHttpRequest )
    { // Mozilla, Safari, ...
        http_request = new XMLHttpRequest( );
        if ( http_request.overrideMimeType )
        {
            // http_request.ocompleted_dateverrideMimeType( 'text/xml' );
            http_request.overrideMimeType( 'text/html' );
        }
    }
    else if ( window.ActiveXObject )
    { // IE
        try
        {
            http_request = new ActiveXObject( "Msxml2.XMLHTTP" );
        }
        catch ( e )
        {
            try
            {
                http_request = new ActiveXObject( "Microsoft.XMLHTTP" );
            }
            catch ( e ) {}
        }
    }

    if ( !http_request )
    {
        alert( "Cannot create an XMLHTTP instance" );
        return false;
    }

    return http_request;
}

function hide_element( id )
{
    if (document.getElementById) { // DOM3 = IE5, NS6
            document.getElementById(id).style.display = 'none';
    }
    else {
            if (document.layers) { // Netscape 4
                    document.id.display = 'none';
            }
            else { // IE 4
                    document.all.id.style.display = 'none';
            }
    }
}

function show_element( id )
{
    if (document.getElementById) { // DOM3 = IE5, NS6
            document.getElementById(id).style.display = '';
    }
    else {
            if (document.layers) { // Netscape 4
                    document.id.display = '';
            }
            else { // IE 4
                    document.all.id.style.display = '';
            }
    }
}

function toggle_element( id )
{
    if (document.getElementById) { // DOM3 = IE5, NS6
        if (document.getElementById(id).style.display == '')
        {
            hide_element(id);
        }
        else
        {
            show_element(id);
        }
    }
    else {
        if (document.layers) { // Netscape 4
            if (document.id.display == '')
            {
                hide_element(id);
            }
            else
            {
                show_element(id);
            }
        }
        else { // IE 4
            if (document.all.id.style.display == '')
            {
                hide_element(id);
            }
            else
            {
                show_element(id);
            }
        }
    }
}

function number2money(n_value) {
    //
    // Original version from: http://www.softcomplex.com/forum/viewthread_2775/
    //

    // validate input
    if ( isNaN( Number(n_value) ) )
    {
        return 'ERROR';
    }

    // save the sign
    var b_negative = Boolean(n_value < 0);
    n_value = Math.abs(n_value);

    // round to 1/100 precision, add ending zeroes if needed
    var s_result = String(Math.round(n_value*1e2)%1e2 + '00').substring(0,2);

    // separate all orders
    var b_first = true;
    var s_subresult;
    while ( n_value > 1 )
    {
        s_subresult = (n_value >= 1e3 ? '00' : '') + Math.floor(n_value%1e3);
        s_result = s_subresult.slice(-3) + (b_first ? '.' : ',') + s_result;
        b_first = false;
        n_value = n_value/1e3;
    }

    // add at least one integer digit
    if ( b_first )
    {
        s_result = '0.' + s_result;
    }

    // apply formatting and return
    return b_negative ? -s_result : s_result;
}

function number_format( number, decimals, dec_point, thousands_sep )
{
    // http://kevin.vanzonneveld.net
    // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // + bugfix by: Michael White (http://crestidg.com)
    // + bugfix by: Benjamin Lupton
    // + bugfix by: Allan Jensen (http://www.winternet.no)
    // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // * example 1: number_format(1234.5678, 2, '.', '');
    // * returns 1: 1234.57

    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), 10) + "", 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 money_format(number)
{
    return number_format(number, 2, ".", " ");
}


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

String.prototype.ltrim = function() {
        return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
        return this.replace(/\s+$/,"");
}

function date_is_valid( date ) // accepted date format: YYYY-MM-DD
{
    if ( date.trim() == "" )
    {
        return false;
    }

    var D = date.split( "-" );

    var month_days = new Array();
    month_days[1] = 31;
    month_days[2] = D[0] % 4 == 0 ? 29 : 28;
    month_days[3] = 31;
    month_days[4] = 30;
    month_days[5] = 31;
    month_days[6] = 30;
    month_days[7] = 31;
    month_days[8] = 31;
    month_days[9] = 30;
    month_days[10] = 31;
    month_days[11] = 30;
    month_days[12] = 31;

    // Check the month
    D[1] = parseInt(D[1], 10);
    if (D[1] < 1 || D[1] > 12)
    {
        alert("bakker");
        return false;
    }
    // Check the day of month
    D[2] = parseInt(D[2], 10);
    if (D[2] < 1 || D[2] > month_days[ D[1] ])
    {
        return false;
    }

    return true;
}

function parse_xml( xml_text )
{
    if ( window.ActiveXObject ) // code for IE
    {
        var doc = new ActiveXObject( "Microsoft.XMLDOM" );
        doc.async = "false";
        doc.loadXML( xml_text );
    }
    else // code for Mozilla, Firefox, Opera, etc.
    {
        var parser = new DOMParser();
        var doc = parser.parseFromString( xml_text,"text/xml" );
    }

    return doc;
}

function parse_date_str( date_str )
{
    var D = date_str.split( "-" );
    return new Date( D[0], D[1] - 1, D[2] );

}

function number_only_field( event )
{
    var key_code;
    var key_char;

    if ( window.event )
    {
        key_code = window.event.keyCode;
    }
    else if ( event )
    {
        key_code = event.which;
    }
    else
    {
        return false; // return true; ??
    }

    key_char = String.fromCharCode( key_code );

    //
    // Handle the control keys
    //
    if ( key_code == null ||
            key_code == 0 ||
            key_code == 8 ||
            key_code == 9 ||
            key_code == 13 ||
            key_code == 27 )
    {
        return true;
    }

    //
    // Now check if an allowed char has been entered
    //
    if ( "0123456789.".indexOf( key_char ) > -1 )
    {
        return true;
    }

    //
    // Any other entered char is considered as invalid.
    //
    return false;
}

function check_form(form, url)
{
    var params = "";
    var element = null;

    // collect all form elements
    for (var i=0; i<form.elements.length; i++)
    {
        element = form.elements[i];

        if (element.name != "")
        {
            if (element.type == "select-multiple")
            {
                for (var j=0; j<element.options.length; j++)
                {
                    params += "&"+element.name+"="+element.options[j].value;
                }
            }
        else if (element.type == "checkbox")
        {
        if (element.checked)
        {
                    params += "&"+element.name+"="+element.value;
        }
        }
            else
            {
                params += "&"+element.name+"="+element.value;
            }
        }
    }

    params = params.substring(1); // drop the leading '&' sign

    return post_url(url, params, process_check_form_result, form);
}

function process_check_form_result(http_request, form)
{
    if ( http_request.readyState == 4 && http_request.status == 200 )
    {
        var response = http_request.responseText;

        if (! response)
        {
            alert("Kiszolgáló hiba: nem sikerült ellenőrizni az űrlapot.\nKérem próbálja újra.");
        }

        response = response.evalJSON(); // evalJSON is provided by Prototype

        if (response.errorCode == "0")
        {
            // OK
            form.submit();
        }
        else if (response.errorCode == "1")
        {
            // WARNING
            if (confirm(response.errorMessage))
            {
                form.submit();
            }
        }
        else
        {
            // ERROR
            alert(response.errorMessage);
        }
    }

    return false;
}

function retrieve_url(method, url, params, callback, callback_param)
{
    var http_request = makeRequest();

    if (method == "GET")
    {
        url += "?"+params;
        params = null;
    }

    http_request.open(method, url, true);

    if (method == "POST")
    {
        http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http_request.setRequestHeader("Content-length", params.length);
        http_request.setRequestHeader("Connection", "close");
    }

    http_request.onreadystatechange = function() { callback(http_request, callback_param); };
    http_request.send(params);

    return false;
}

function get_url(url, params, callback, callback_param)
{
    return retrieve_url("GET", url, params, callback, callback_param);
}

function post_url(url, params, callback, callback_param)
{
    return retrieve_url("POST", url, params, callback, callback_param);
}

function show_loading_icon(element)
{
    return show_processing_icon(element, "Betöltés...");
}

function show_processing_icon(element, text)
{
    var processing_text = "Feldolgozás";

    if (text)
    {
        processing_text = text;
    }

    var loading_icon = '<DIV align="center"> <IMG src="../images/ajax-loader.gif" alt="" style=" vertical-align: middle"> <I> '+processing_text+'... </DIV>';
    document.getElementById(element).innerHTML = loading_icon;
    return false;
}

function empty_form_elements(form)
{
    // walk thru all form elements and set their value to ""
    for (var i=0; i<form.elements.length; i++)
    {
        element = form.elements[i];

        if (element.name != "")
        {
            element.value = "";
        }
    }
}

/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function dump(arr, level)
{
    var dumped_text = "";
    if (!level)
        level = 0;

    //The padding given at the beginning of the line.
    var level_padding = "";
    for (var j = 0; j < level + 1; j++)
        level_padding += "    ";

    if (typeof(arr) == 'object')
    { //Array/Hashes/Objects
        for (var item in arr)
        {
            var value = arr[item];

            if (typeof(value) == 'object')
            { //If it is an array,
                dumped_text += level_padding + "'" + item + "' ...\n";
                dumped_text += dump(value, level + 1);
            }
            else
            {
                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }
    }
    else
    { //Stings/Chars/Numbers etc.
        dumped_text = "===>" + arr + "<===(" + typeof(arr) + ")";
    }
    return dumped_text;
}

function update_chars_left(textarea, max_ch, update_input_field)
{
    if (typeof textarea == "string")
    {
        textarea = document.getElementById("textarea");
    }

    if (typeof update_input_field == "string")
    {
        update_input_field = document.getElementById(update_input_field);
    }

    if (textarea && max_ch > 0 && update_input_field)
    {
        if (textarea.value.length > max_ch) // if too long...trim it!
        {
            textarea.value = textarea.value.substring(0, max_ch);
        }
        else
        {
            update_input_field.value = max_ch - textarea.value.length;
        }
    }
}

function tooltip_on(element)
{
    new Tooltip(element, {backgroundColor: '#333',
                            borderColor: '#333',
                            textColor: '#FFF',
                            textShadowColor: '#000'});
}

function tooltip_red_on(element)
{
    new Tooltip(element, {backgroundColor: '#FF0000',
                            borderColor: '#333',
                            textColor: '#FFF',
                            textShadowColor: '#000'});
}

function show_tab( tab )
{
    if (! tab && tabs)
    {
        // figure out which tab to display
        tab = tabs[0];
        var get_params = window.location.search.substring(1);

        if (typeof get_params == "string" && get_params != "")
        {
            var get_params_tmp = get_params.split("&");

            for (var i=0; i<get_params_tmp.length; i++)
            {
                if (get_params_tmp[i].indexOf("tab=") == 0)
                {
                    var key_value_pair = get_params_tmp[i].substring(1).split("=");
                    tab = key_value_pair[1];
                    break;
                }
            }
        }
    }

    if (tab)
    {
        for (var i=0; i<tabs.length; i++)
        {
            if ($(tabs[i]))
            {
                $(tabs[i]).hide();
                $("tab-"+tabs[i]).className = "tab";
            }
        }

        $("tab-"+tab).className = "active_tab";
        $(tab).show();
    }

    return false;
}

