﻿var current_emailvalues;

textbox_keydown = function(event)
{
    var eventKey = String.fromCharCode(event.keyCode);
    var allowedChars = "0123456789" + "abcdefghi"+String.fromCharCode(96) /*numeric keypad...*/;

    var allowedEventKeys = 
        [Event.KEY_BACKSPACE, Event.KEY_TAB, Event.KEY_LEFT, Event.KEY_UP, Event.KEY_RIGHT, Event.KEY_DOWN, 
        Event.KEY_DELETE, Event.KEY_HOME, Event.KEY_END, Event.KEY_PAGEUP, Event.KEY_PAGEDOWN];

    var eventKeyIdx = allowedEventKeys.indexOf(event.keyCode);
    var charIdx = allowedChars.indexOf(eventKey);

    var currLength = Event.element(event).getValue().length;

    // check if the key is allowed and if the resulting length of the field is below limit (9)
    if ( eventKeyIdx >= 0 || (charIdx >= 0 && currLength + 1 < 9) )
    {
        // all is good
        return true;
    }
    else
    {
        Event.stop(event);
        new Effect.Highlight(Event.element(event), {startcolor: '#ff9999', endcolor:'#e2e7ee', duration: 0.1, queue: 'end' });
        return false;
    }
}

checkbox_click = function(event)
{
    var checkbox = Event.element(event);
    var ids = checkbox.identify().split('_');
    if ( ids.length > 1 ) { // could be "jatak" checkbox..
    
        var id = ids[1]+'_'+ids[2];
        
        var txtbox = $('txt_'+id);
        var placeholder = $('txtph_'+id);
        subcat = subs.get('id_'+id);
        
        if ( checkbox.checked )
        {
            placeholder.hide();
            txtbox.show();
            $('disc_'+id).show();
            if ( subcat.changeable )
            {
                txtbox.enable();
                txtbox.activate();
                new Form.Element.Observer(txtbox, 0.1, update_formstate);
                txtbox.observe('keydown', textbox_keydown);
            }
            else
            {
                txtbox.disable();
                txtbox.value = subcat.base;
            }
        }
        else
        {
            txtbox.hide();
            placeholder.show();
            $('disc_'+id).hide();
        }
        
        update_formstate();
    }
}

emailform_submit = function(event)
{
    var validations = new Hash();
    
    validations.set('navn', '.+');
    validations.set('email', '[^@]+@[^\\.]+(\\.[^\\.]+)+');
    validations.set('postnr', '^\\d{4,4}$');
    
    var errorfields = [];
    
    validations.each(
        function(pair) {
            if ( !($(pair.key).getValue().strip().match(new RegExp(pair.value, "i"))) )
            {
                errorfields.push(pair.key);
            }
        }
    );
    
    if ( errorfields.length > 0 )
    {
        errorfields.each(
            function(field) {
                new Effect.Highlight(field, {startcolor: '#ff9999', endcolor:'#ffffff', duration: 0.25, queue: 'end' });
            }
        );
        
        $(errorfields[0]).activate();
        
    }
    else
    {
        // gather data from calculator
        var data = "";
        $('beregner').getInputs('checkbox').each(
            function(checkbox) {
                if ( checkbox.checked )
                {
                    var ids = checkbox.identify().split('_');
                    var id = ids[1]+'_'+ids[2];
                    
                    data += (data != '')?"|":"";
                    data += id + "=" + $('txt_'+id).getValue();
                }
            }
        );
        
        //$('beregnerdata').value = data;
        
        current_emailvalues = $('beregner').serialize(true);
        
        // do submit
        
        $('emailform').request(
            {
                method: 'post',
                parameters: {beregnerdata: data} ,
                onSuccess: email_success,
                onFailure: email_fail 
            }
        );
    }
    
    Event.stop(event);
    return false;
}

email_success = function()
{
    $('emailpopup').hide();
    
    var popup = $('emailmsgpopup');
    popup.show();
    
    $('msgheader').update('E-mail blev afsendt');
    $('msgbody').update('E-mailen blev afsendt. Du vil modtage den inden længe i din mailbox.');
    
    center_popup(popup);
    
    $('msgok').observe('click', emailform_close);
}

email_fail = function() 
{
    $('emailpopup').hide();
    
    var popup = $('emailmsgpopup');
    popup.show();
    
    $('msgheader').update('Der opstod en fejl');
    $('msgbody').update('E-mailen blev desværre ikke afsendt. Prøv igen lidt senere.');
    
    center_popup(popup);
    
    $('msgok').observe('click', retry_email);
}

retry_email = function()
{
    $('emailmsgpopup').hide();
    $('emailpopup').show();
    
    new Hash().update(current_emailvalues).each(
        function(key, value) {
            Form.Element.update(key, value);
        }
    );
}

emailform_close = function()
{
    // clear form fields
    $('navn').clear();
    $('email').clear();
    $('postnr').clear();
    $('jatak').checked = true;

    $('overlay').hide();
    $('emailpopup').hide();
    $('emailmsgpopup').hide();
}

center_popup = function(popup)
{
    popup.absolutize();
    dim = popup.getDimensions();
    
    popup.setStyle({
        top: ((document.viewport.getHeight() - dim.height) / 2) + 'px',
        left: ((document.viewport.getWidth() - dim.width) / 2) + 'px'
    });
}

show_emailpopup = function()
{
    // overlay
    var overlay = $('overlay');
    overlay.show();
    overlay.absolutize();
    
    overlay.setStyle({
        top: '0px',
        left: '0px',
        width: document.viewport.getWidth() + 'px',
        height: document.viewport.getHeight() + 'px'
    });
    
    overlay.setOpacity(0.5);

    // popup
    var popup = $('emailpopup');
    popup.show();
    center_popup(popup);
    
    Event.observe('emailform', 'submit', emailform_submit);
    $('emailcancel').observe('click', emailform_close);
    
    $('navn').activate();
}

update_formstate = function()
{
    var total = 0;
    
    $('beregner').getInputs('checkbox').each(
        function(checkbox) {
            if ( checkbox.checked )
            {
                var ids = checkbox.identify().split('_');
                if ( ids.length > 1 ) // could be "jatak" checkbox
                {
                    var id = ids[1]+'_'+ids[2];
                    subcat = subs.get('id_'+id);
                    
                    var discount = 0;
                    var useramount = $('txt_'+id).getValue() * 1;
                    useramount = ( isNaN(useramount) ) ? 0 : useramount;
                    
                    switch ( subcat.discounttype )
                    {
                        case 'DISCOUNT_PERUSE':
                            discount = useramount * subcat.amount;
                        break;
                        
                        case 'DISCOUNT_PERCENTAGE':
                            discount = useramount * ( subcat.amount / 100 );
                        break;
                    }
                    
                    $('disc_'+id).update(discount.round() + ",-");
                    total = total + discount.round();
                }
            }
        }
    );
    
    $('calculationtotal').update(total.round() + ",-");
}

init = function()
{
    $('beregner').getInputs('checkbox').each(
        function(checkbox) {
            checkbox.observe('click', checkbox_click);
        }
    );   
}

