function statusMsg(msg)
{
    status = msg;
    document.value = true;
}

function cursor_position(e)
{
    document.body.cursor_position_x = e.pageX;
    document.body.cursor_position_y = e.pageY;
}

function get_mouse_x()
{
    var regexp = /MSIE/
    if (regexp.test(navigator.userAgent))
    {
        var pos_x = event.clientX;
    }
    else
    {
        var pos_x = document.body.cursor_position_x;
    }

    return pos_x
}

function get_mouse_y()
{
    var regexp = /MSIE/
    if (regexp.test(navigator.userAgent))
    {
        var pos_y = event.clientY;
    }
    else
    {
        var pos_y = document.body.cursor_position_y;
    }

    return pos_y
}

/*
function cbgc(target, over_color, selected_color, out_color, action)
{
    var regexp = /opera/i;
    if (navigator.userAgent.search(regexp) == -1) {
        var current_color = target.style.backgroundColor;
        if (action == 'over')
        {
            if (current_color != selected_color)
            {
                target.style.backgroundColor = over_color;
            }
        }
        else if (action == 'out')
        {
            if (current_color != selected_color)
            {
                target.style.backgroundColor = out_color;
            }
        }
        else if (action == 'down')
        {
            if (current_color != selected_color)
            {
                target.style.backgroundColor = selected_color;
            }
            else
            {
                target.style.backgroundColor = out_color;
            }
        }
    }
}
*/

/*
function showItems(target)
{
    var obj = document.getElementById(target);
    obj.style.display = (obj.style.display != "inline") ? 'inline' : 'none';
}
*/

/*
function check_form(form)
{
    var elements = document.getElementById(form).elements;
    //alert(elements[1].className);
    //var c = elements.length;
    var c = elements.length
    for (var i = 0; i < c; i++)
    {
        var e = elements[i];
        if ((e.className == 'submitable') && (e.disabled == false))
        {
            return true;
        }
    }
    return false;
}
*/

/*
function mark_checkbox(target, pid)
{
    document.getElementById("del_product_"+ pid +"").click();
}
*/

function confirm_submit(msg)
{
    result = (false != confirm(msg)) ? true : false
    return result;
}

var menu_hold_id;

function open_menu(menu)
{
    clearTimeout(menu_hold_id);

    var nodes = document.getElementById(menu).childNodes;
    for (i in nodes)
    {
        if (has_class(nodes[i], 'links'))
        {
            var element_menu = nodes[i];
        }
    }
    element_menu.onmouseover = cancel_timeout;
    if (menu == 'tables-menu')
    {
        element_menu.onmouseout = hide_tables_menu;
    }
    else if (menu == 'product-groups-menu')
    {
        element_menu.onmouseout = hide_product_groups_menu;
    }
    else if (menu == 'actions-menu')
    {
        element_menu.onmouseout = hide_actions_menu;
    }

    element_menu.style.display = 'block';
}

function timeout_hide_element(eid)
{
    hide_delay = 500;
    clearTimeout(menu_hold_id);
    menu_hold_id = setTimeout('hide_element("'+ eid +'")', hide_delay);
}

function cancel_timeout()
{
    clearTimeout(menu_hold_id);
}

function hide_tables_menu()
{
    timeout_hide_element('tables-menu');
}

function hide_product_groups_menu()
{
    timeout_hide_element('product-groups-menu');
}

function hide_actions_menu()
{
    timeout_hide_element('actions-menu');
}

function hide_element(eid)
{
    var nodes = document.getElementById(eid).childNodes;
    for (i in nodes)
    {
        if (has_class(nodes[i], 'links'))
        {
            var element = nodes[i];
        }
    }
    element.style.display = 'none';
}

function show_image(image, width, height)
{
    var a_width = screen.availWidth;
    var a_height = screen.availHeight;
    var name = image;
    width = width + 20;
    height = height + 20;
    var options = eval("'toolbar=no,location=no,scrollbars=no,status=no,menubar=no,resizable=yes,width="+ width +",height="+ height +",left="+ ((a_width - width - 10)* .5) +", top="+ ((a_height - height - 30)* .5) +"'");
    // TODO: tee kuville yksilöllinen tunniste.
    var popup = window.open(image, '', options);
    popup.document.close();
    popup.focus();
    return;
}

function edit_product(pid, table)
{
    var a_width = screen.availWidth;
    var a_height = screen.availHeight;
    var name = pid;
    var width = 500;
    var height = 250;
    var options = eval("'toolbar=no,location=no,scrollbars=yes,status=yes,menubar=no,resizable=yes,width="+ width +",height="+ height +",left="+ ((a_width - width - 10)* .5) +", top="+ ((a_height - height - 30)* .5) +"'");
    var popup = window.open('edit_product.php?pid='+ pid +'&table='+ table, name, options);
    popup.document.close();
    popup.focus();
    return;
}

function add_product(group, table)
{
    var a_width = screen.availWidth;
    var a_height = screen.availHeight;
    var name = group;
    var width = 500;
    var height = 250;
    var options = eval("'toolbar=no,location=no,scrollbars=yes,status=yes,menubar=no,resizable=yes,width="+ width +",height="+ height +",left="+ ((a_width - width - 10)* .5) +", top="+ ((a_height - height - 30)* .5) +"'");
    var popup = window.open('add_product.php?group='+ group +'&table='+ table, name, options);
    popup.document.close();
    popup.focus();
    return;
}

function add_product_group(table)
{
    var a_width = screen.availWidth;
    var a_height = screen.availHeight;
    var name = table;
    var width = 300;
    var height = 80;
    var options = eval("'toolbar=no,location=no,scrollbars=yes,status=yes,menubar=no,resizable=yes,width="+ width +",height="+ height +",left="+ ((a_width - width - 10)* .5) +", top="+ ((a_height - height - 30)* .5) +"'");
    var popup = window.open('add_product_group.php?table='+ table, name, options);
    popup.document.close();
    popup.focus();
    return;
}

function modify_product_group(table, old_name)
{
    var a_width = screen.availWidth;
    var a_height = screen.availHeight;
    var name = table;
    var width = 300;
    var height = 80;
    var options = eval("'toolbar=no,location=no,scrollbars=yes,status=yes,menubar=no,resizable=yes,width="+ width +",height="+ height +",left="+ ((a_width - width - 10)* .5) +", top="+ ((a_height - height - 30)* .5) +"'");
    var popup = window.open('modify_product_group.php?table='+ table +'&old_name='+ old_name , name, options);
    popup.document.close();
    popup.focus();
    return;
}

function delete_product_groups(table)
{
    var a_width = screen.availWidth;
    var a_height = screen.availHeight;
    var name = table;
    var width = 300;
    var height = 500;
    var options = eval("'toolbar=no,location=no,scrollbars=yes,status=yes,menubar=no,resizable=yes,width="+ width +",height="+ height +",left="+ ((a_width - width - 10)* .5) +", top="+ ((a_height - height - 30)* .5) +"'");
    var popup = window.open('delete_product_groups.php?table='+ table , name, options);
    popup.document.close();
    popup.focus();
    return;
}

function enable(main, sub)
{
    var element = document.getElementById(main).elements[sub];
    element.disabled = (element.disabled == true) ? false : true;
}

function check_product_edit_form(form)
{
    var inputs = document.getElementById(form).elements;
    var empty = new Array();
    var errors = new Array();
    var valid_inputs;
    var msg = '';
    var node;
    var name;
    var value;

    switch (form)
    {
        case 'edit-form':
            valid_inputs = new Array('product_groups', 'model', 'name', 'sequence', 'price', 'info', 'url', 'image', 'expires', 'count');
            break;
    }

    var disabled = true;
    for (valid in valid_inputs)
    {
        node = inputs[valid_inputs[valid]];
        if (node != undefined)
        {
            name = node.name;

            value = trim(node.value);
            switch (name)
            {
                case 'name':
                    if (node.disabled == false)
                    {
                        disabled = false;

                        if (value.length == 0)
                        {
                            errors[name] = '- Nimi\n';
                        }
                    }
                    break;
                case 'price':
                    if (node.disabled == false)
                    {
                        disabled = false;

                        if ((is_decimal(value) == false) && (value.length > 0))
                        {
                            errors[name] = '- Hinta\n';
                        }
                    }
                    break;
                default :
                    if (node.disabled == false)
                    {
                        disabled = false;
                    }
            }
        }
    }

    if (disabled == true)
    {
        return false;
    }

    msg_title = msg +'Seuraavat tiedot ovat virheellisiä:\n';

    for (err in errors)
    {
        msg = msg + errors[err];
    }

    if (msg != '')
    {
        msg = msg_title + msg;
        alert(msg);
        return false;
    }

    return true;
}

function trim(str)
{
    while (str.substring(0, 1) == ' ')
    {
        str = str.substring(1, str.length);
    }

    while (str.substring(str.length - 1, str.length) == ' ')
    {
        str = str.substring(0, str.length - 1);
    }
    return str;
}

function has_class(element, needle)
{
    var classes = element.className;
    if (classes != null)
    {
        classes = classes.split(' ');
        for (cls in classes)
        {
            if (classes[cls] == needle)
            {
                return true;
            }
        }
    }
    return false;
}

function is_decimal(value)
{
    if (value.length > 0)
    {
        regexp = /^\d+(\.\d{1,2})?$/
        if (regexp.test(value) == true)
        {
            return true;
        }
    }
    return false;
}

function is_name(value)
{
    if (value.length > 0)
    {
        regexp = /\d/
        if (regexp.test(value) == false)
        {
            return true;
        }
    }
    return false;
}

function is_phone_number(value)
{
    if (value.length > 0)
    {
        regexp = /[^-\d\s]/
        if (regexp.test(value) == false)
        {
            return true;
        }
    }
    return false;
}

function is_email(value)
{
    if (value.length > 0)
    {
        regexp = /^[-_.\w]+@((([\w]|[\w][\w-]*[\w])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/gi
        if (regexp.test(value) != false)
        {
            return true;
        }
    }
    return false
}

function row_hover(row, color)
{
    cells = row.parentNode.childNodes;
    for (i in cells)
    {
        cell = cells[i];
        if (has_class(cell, 'hoverable'))
        {
            cell.style.background = color;
        }
    }
}

function load_page(url)
{
    window.location.href = url;
}
/*
function open_node(id)
{
    var node = document.getElementById('p_'+ id);
    node.style.display = (node.style.display == 'none') ? 'block' : 'none';
}
*/
function open_info(self, id, name, info)
{
    var shift_x = 15;
    var shift_y = 20;
    var popup_id = 'info-popup-'+ id;
    var pos_x = get_mouse_x() + shift_x
    var pos_y = get_mouse_y() - shift_y;

    // If <div> with the same id is not found.
    var popup = document.getElementById(popup_id);
    if (popup == null)
    {
        popup = document.createElement('div');
        document.body.appendChild(popup);
        popup.className = 'info-popup';
        popup.id = popup_id;
        popup.style.left = pos_x +'px';
        popup.style.top = pos_y +'px';

        var name_node = popup.appendChild(document.createElement('div'));
        name_node.className = 'name';
        name_node.appendChild(document.createTextNode(name));

        var info_node = popup.appendChild(document.createElement('div'));
        info_node.className = 'info';
        info_node.appendChild(document.createTextNode(info));
    }
    else
    {
        popup.style.left = pos_x +'px';
        popup.style.top = pos_y +'px';
        popup.style.display = 'block';
    }
}

function close_info(id)
{
    document.getElementById('info-popup-'+ id).style.display = 'none';
}

function check_form(form)
{
    var empty = new Array();
    var errors = new Array();
    var valid_inputs;
    var msg = '';
    var node;
    var name;
    var value;

    switch (form)
    {
        case 'client_information':
            valid_inputs = new Array('name', 'street_address', 'postal_code', 'post_office', 'phone_number', 'email', 'message');
            break;
    }

    for (valid in valid_inputs)
    {
        node = document.getElementById(valid_inputs[valid]);

        if (node != null)
        {
            id = node.id;
            value = trim(node.value);

            if ((value.length == 0) && (has_class(node, 'required') == false))
            {
                break;
            }

            switch (id)
            {
                case 'name':
                    if (is_name(value) == false)
                    {
                        errors[id] = '- Nimi.\n';
                    }
                    break;
                case 'street_address':
                    if (value.length == 0)
                    {
                        errors[id] = '- Lähiosoite.\n';
                    }
                    break;
                case 'postal_code':
                    if (is_decimal(value) == false || value.length < 5)
                    {
                        errors[id] = '- Postinumero.\n';
                    }
                    break;
                case 'post_office':
                    if (is_name(value) == false)
                    {
                        errors[id] = '- Postitoimipaikka.\n';
                    }
                    break;
                case 'phone_number':
                    if (is_phone_number(value) == false)
                    {
                        errors[id] = '- Puhelinnumero.\n';
                    }
                    break;
                case 'email':
                    if (is_email(value) == false)
                    {
                        errors[id] = '- Sähköposti.\n';
                    }
                    break;
                case 'message':
                    if (value.length == 0)
                    {
                        errors[id] = '- Viesti.\n';
                    }
                    break;
            }
        }
    }

    msg_title = msg +'Seuraavat tiedot ovat virheellisiä:\n';

    for (err in errors)
    {
        msg = msg + errors[err];
    }

    if (msg != '')
    {
        msg = msg_title + msg;
        alert(msg);
        return false;
    }

    return true;
}

