$(document).ready(function(){

    // fix png images
    $(document).pngFix();

    // set default value
    var speedFadeOut = 30;
    var speedFadeIn = 20;
    var defaultValue = '';
    var decimal = 2;
    var maxdecimal = 3;
    var cookieoptions = {
        path: '/',
        expires: 30
    };
    var KEY_LEFT = 37;
    var KEY_UP = 38;
    var KEY_RIGHT = 39;
    var KEY_DOWN = 40;
    var balloon_speed = 800;

    /*
     *      First step
     *      check cookie and 
     *      clean input text if page reloaded
     */
    if($.cookie('decimal') != null && isValidNumber($.cookie('decimal')) && $.cookie('decimal') <= maxdecimal){
        decimal = $.cookie('decimal');
    }
    defaultValue = '0.' + makeDecNull();
    $('#decimalplace').val(decimal);

    // if not set convert
    if(is_convert == 0){
        $('#amount').val(defaultValue);
        $('#euro2usdvalue').text(defaultValue);
        $('#usd2eurovalue').text(defaultValue);
    }

    /*
     *      Now set show hide on clik and blur
     */

    $('#amount').bind('click',function(){
        if($(this).val() == defaultValue)
            $(this).val('');
    });

    $('#amount').bind('blur',function(){
        var vl = $(this).val();
        if(vl == '')
            $(this).val(defaultValue);
        else{
            if(isValidNumber(vl)){
                if($.inArray('.',vl) == -1){
                    $(this).fadeOut(speedFadeOut,function(){
                        $(this).val(vl+'.'+makeDecNull()).fadeIn(speedFadeIn);
                    });
                }else{
                    if(parseInt(vl.length - 1) == $.inArray('.',vl)){
                        $(this).fadeOut(speedFadeOut,function(){
                            $(this).val(vl+makeDecNull()).fadeIn(speedFadeIn);
                        });
                    }
                }
                $('#amount').trigger('keyup');
            }else
                $(this).val(defaultValue);
        }
    });

    /*
     *      ADD DBLClick func
     */
    $('#amount').bind('dblclick',function(){
        $(this).val('');
    });

    // Set logo info hover
    var logo_posiotion = $('#h1-title').position();
    var logo_width = $('#h1-title').width();
    $('#h1-info').css({
        'left':logo_posiotion.left + logo_width,
        'top':logo_posiotion.top - 25
    });
    
    // Set hover on logo
    $('#h1-title').hover(function(){
        $('#h1-info').show();
    },function(){
        $('#h1-info').hide();
    });

    // set key up
    $('#amount').live('keyup',function(e){
        if(e.keyCode != KEY_DOWN && e.keyCode != KEY_LEFT && e.keyCode != KEY_RIGHT && e.keyCode != KEY_UP){
            var amount = $('#amount').val();
            if(isValidNumber(amount)){
                invalidNumber('hide'); // first hide invalid number message
                var calc2euro = (amount * (1/rate)).toFixed(decimal);
                var calc2usd = (amount * rate).toFixed(decimal);
                $('#usd2eurovalue').fadeOut(speedFadeOut,function(){
                    $(this).html(calc2euro).fadeIn(speedFadeIn);
                });
                $('#euro2usdvalue').fadeOut(speedFadeOut,function(){
                    $(this).html(calc2usd).fadeIn(speedFadeIn);
                });
            }else
                invalidNumber('show'); // show invalid number message
        }
    });

    // set invalid number div
    var amount_position = $('#amount').position();
    var amount_width = $('#amount').outerWidth();

    $('#invalid-number').css({
        'left':amount_position.left + amount_width + 8,
        'top':amount_position.top - 40
    });

    // click on options show/hide
    $('#showoptions').live('click',function(){
        optionsInfo('', 'hide');
        $('.additionalbox').not('#options').hide();
        
        if($('#options').is(':visible'))
            $('#options').fadeOut('slow');
        else
            $('#options').fadeIn('slow');
        
    });

    // save options
    $('#saveoptions').live('click',function(){
        optionsInfo('', 'hide');
        if(isValidNumber($('#decimalplace').val()) && $('#decimalplace').val() > 0){
            if(parseInt($('#decimalplace').val()) > maxdecimal)
                optionsInfo('Maximum decimal places is '+maxdecimal+'.');
            else{
                decimal = $('#decimalplace').val();
                $.cookie('decimal',decimal,cookieoptions);
                $('#amount').trigger('keyup');
                $('#options .xclose').trigger('click');
                if(parseFloat($('#amount').val()) == 0){
                    $('#amount').val('0.'+makeDecNull());
                }
            }
        }else{
            $('#decimalplace').val(decimal);
            optionsInfo('Oh, this is invalid number!','show');
        }
    });

    // click on who show/hide
    $('#showho').live('click',function(){
        $('.additionalbox').not('#who').hide();
        
        if($('#who').is(':visible'))
            $('#who').fadeOut('slow');
        else
            $('#who').fadeIn('slow');
    });

    // click on who show/hide
    $('#showhy').live('click',function(){
        $('.additionalbox').not('#why').hide();
        
        if($('#why').is(':visible'))
            $('#why').fadeOut('slow');
        else
            $('#why').fadeIn('slow');
    });

    // click on what show/hide
    $('#showhat').live('click',function(){
        $('.additionalbox').not('#what').hide();
        
        if($('#what').is(':visible'))
            $('#what').fadeOut('slow');
        else
            $('#what').fadeIn('slow');
    });

    //click on rate show/hide
    $('#showrate').live('click',function(){
        $('.additionalbox').not('#rate').hide();
        
        if($('#rate').is(':visible'))
            $('#rate').fadeOut('slow');
        else
            $('#rate').fadeIn('slow');
    });

    function invalidNumber(type){
        type = (type == null) ? 'show' : type;
        if(type == 'show')
            $('#invalid-number').show();
        if(type == 'hide')
            $('#invalid-number').hide();
    }

    function isValidNumber(nmb){
        return !isNaN(nmb);
    }

    function makeDecNull(){
        var str = '';
        for(var i = 0; i < decimal; i++)
            str += '0';
        defaultValue = '0.'+str;
        return str;
    }

    function optionsInfo(message, type, callback){
        type = (type == null) ? 'show' : type;
        
        if(type == 'show')
            $('#optionsinfo').html(message).fadeIn(speedFadeIn,callback);
        else if('hide')
            $('#optionsinfo').html(message).fadeOut(speedFadeOut,callback);
    }

    // xClose
    $('.xclose').bind('click',function(){
        $(this).parent().fadeOut('slow');
    });
    
    var current_inc = 1;
    $('html').live('keydown',function(e){

        var currentvalue = $('#amount').val();
        // ako nije validan odmah da izbacimo
        if(!isValidNumber(currentvalue)){
            return;
        }

        if(e.keyCode == KEY_UP){
            samount = (parseFloat(currentvalue) + current_inc);
            add = (samount.toString().split('.').length - 1 != 1) ? '.'.concat(makeDecNull()) : '';
            $('#amount').val(samount.toString().concat(add));
            $('#amount').trigger('keyup');
            
            makeBalloon(e);
        }

        if(e.keyCode == KEY_DOWN){
            samount = (parseFloat(currentvalue) - current_inc);
            if(samount > 0){
                add = (samount.toString().split('.').length - 1 != 1) ? '.'.concat(makeDecNull()) : '';
                $('#amount').val(samount.toString().concat(add));
                $('#amount').trigger('keyup');
            }else{
                $('#amount').val('0'+'.'+makeDecNull());
                $('#amount').trigger('keyup');
            }

            makeBalloon(e);
        }

        if(e.keyCode == KEY_RIGHT){
            if(current_inc < 10000)
                current_inc *= 10;
            
            makeBalloon(e);
        }

        if(e.keyCode == KEY_LEFT){
            if(current_inc >= 0.0001)
                current_inc /= 10;

            makeBalloon(e);
        }

    });

    function makeBalloon(e){
        balloon = $('<div>');
        balloon.addClass('balloon').appendTo('#wrap');

        if(e.keyCode == KEY_DOWN){
            balloon
            .html('-'+current_inc)
            .css({
                top: amount_position.top + 7 +'px',
                left: amount_position.left + amount_width + 20 + 'px',
                backgroundColor: '#B02B2C'
            })
            .show()
            .animate({
                top: amount_position.top + 30 + 'px',
                opacity: 0.1
            },balloon_speed,function(){
                $(this).remove();
            });
        }

        if(e.keyCode == KEY_RIGHT || e.keyCode == KEY_LEFT){
            balloon
            .html(current_inc)
            .css({
                top: amount_position.top + 7 +'px',
                left: amount_position.left + amount_width + 20 + 'px',
                backgroundColor: '#C79810'
            })
            .show()
            .fadeOut(balloon_speed,function(){
                $(this).remove();
            });
        }

        if(e.keyCode == KEY_UP){
            balloon
            .html('+'+current_inc)
            .css({
                top: amount_position.top + 7 +'px',
                left: amount_position.left + amount_width + 20 + 'px',
                backgroundColor: '#73880A'
            })
            .show()
            .animate({
                top: amount_position.top - 30 + 'px',
                opacity: 0.1
            },balloon_speed,function(){
                $(this).remove();
            });
        }
        
    }

});
