var ctrlPressed = false;

// when page loaded
$(function () {

    $('.cpicker').each(function() {

        var default_colors = 
           ['990033', 'ff3366', 'cc0033', 'ff0033', 'ff9999', 'cc3366', 'ffccff', 'cc6699',
            '993366', '660033', 'cc3399', 'ff99cc', 'ff66cc', 'ff99ff', 'ff6699', 'cc0066',
            'ff0066', 'ff3399', 'ff0099', 'ff33cc', 'ff00cc', 'ff66ff', 'ff33ff', 'ff00ff',
            'cc0099', '990066', 'cc66cc', 'cc33cc', 'cc99ff', 'cc66ff', 'cc33ff', '993399',
            'cc00cc', 'cc00ff', '9900cc', '990099', 'cc99cc', '996699', '663366', '660099',
            '9933cc', '660066', '9900ff', '9933ff', '9966cc', '330033', '663399', '6633cc',
            '6600cc', '9966ff', '330066', '6600ff', '6633ff', 'ccccff', '9999ff', '9999cc',
            '6666cc', '6666ff', '666699', '333366', '333399', '330099', '3300cc', '3300ff',
            '3333ff', '3333cc', '0066ff', '0033ff', '3366ff', '3366cc', '000066', '000033',
            '0000ff', '000099', '0033cc', '0000cc', '336699', '0066cc', '99ccff', '6699ff',
            '003366', '6699cc', '006699', '3399cc', '0099cc', '66ccff', '3399ff', '003399',
            '0099ff', '33ccff', '00ccff', '99ffff', '66ffff', '33ffff', '00ffff', '00cccc',
            '009999', '669999', '99cccc', 'ccffff', '33cccc', '66cccc', '339999', '336666',
            '006666', '003333', '00ffcc', '33ffcc', '33cc99', '00cc99', '66ffcc', '99ffcc',
            '00ff99', '339966', '006633', '336633', '669966', '66cc66', '99ff99', '66ff66',
            '339933', '99cc99', '66ff99', '33ff99', '33cc66', '00cc66', '66cc99', '009966',
            '009933', '33ff66', '00ff66', 'ccffcc', 'ccff99', '99ff66', '99ff33', '00ff33',
            '33ff33', '00cc33', '33cc33', '66ff33', '00ff00', '66cc33', '006600', '003300',
            '009900', '33ff00', '66ff00', '99ff00', '66cc00', '00cc00', '33cc00', '339900',
            '99cc66', '669933', '99cc33', '336600', '669900', '99cc00', 'ccff66', 'ccff33',
            'ccff00', '999900', 'cccc00', 'cccc33', '333300', '666600', '999933', 'cccc66',
            '666633', '999966', 'cccc99', 'ffffcc', 'ffff99', 'ffff66', 'ffff33', 'ffff00',
            'ffcc00', 'ffcc66', 'ffcc33', 'cc9933', '996600', 'cc9900', 'ff9900', 'cc6600',
            '993300', 'cc6633', '663300', 'ff9966', 'ff6633', 'ff9933', 'ff6600', 'cc3300',
            '996633', '330000', '663333', '996666', 'cc9999', '993333', 'cc6666', 'ffcccc',
            'ff3333', 'cc3333', 'ff6666', '660000', '990000', 'cc0000', 'ff0000', 'ff3300',
            'cc9966', 'ffcc99', 'ffffff', 'cccccc', '999999', '666666', '333333', '000000',
            '000000', '000000', '000000', '000000', '000000' ];

        var cpickerWrapper = $('<div class="cpickerWrapper" />');
        $(this).wrap(cpickerWrapper);

        var colorBox = $('<div class="colorBox" />');
        colorBox.css('backgroundColor', $(this).val());

        $(this).after(colorBox);

        var colorSelector = $('<div class="colorSelector" />');
        colorSelector.hide();

        var colorSelectorRow = $('<div class="colorSelectorRow" />');

        var counter = 0;
        var cellsPerRow = 10;
        for (var idx in default_colors) {

            var colorSelectorCell = $('<div class="colorSelectorCell" />');
            colorSelectorCell.css('backgroundColor', '#' + default_colors[idx]);
            colorSelectorCell.attr('title', default_colors[idx]);

            colorSelectorCell.click(function() {
                var myBackground = '#' + $(this).attr('title');
                $(this).parent().parent().parent().find('input').val(myBackground);
                $(this).parent().parent().parent().find('input').change();
                $(this).parent().parent().parent().find('.colorBox').css('backgroundColor', myBackground);
                $(this).parent().parent().hide();
            });

            colorSelectorRow.append(colorSelectorCell);

            if (counter++ >= cellsPerRow) {
                colorSelector.append(colorSelectorRow);
                colorSelectorRow = $('<div class="colorSelectorRow" />');
            }
        }
        colorSelector.append(colorSelectorRow);

        colorBox.after(colorSelector);

        $(this).keyup(function() {
            $(this).parent().find('.colorBox').css('backgroundColor', $(this).val());
        });

        function colorSelectorShow(event) {
            $('.colorSelector').not(colorSelector).hide();
            colorSelector.fadeIn('fast');
            $('html').one('click', function() {
                colorSelector.fadeOut('fast');
            });
            event.stopPropagation();
        }

        colorBox.click(colorSelectorShow);
        //$(this).click(colorSelectorShow);
    });

    try {
        $('.colorpicker').simpleColor({
            boxWidth: 70
        });
    }
    catch(e) {
        // colorpicker's js wasn't included
    }

    // header language menu (item click)
    $('#languages_menu .menu_item').click(function(event) {
        document.location.href = $(this).children('.href').html();
        event.stopPropagation();
    });

    // select whole text once text field got focus
    // (uses for text field with popup menus)
    $('input.autoselect').focus(function() {
        this.select();
    });

    $('#descr_menu .menu_item').click(function(event) {
        $('#descr_text').val($(this).children('.text').html());
        $('#descr_menu').hide();
        event.stopPropagation();
    });

    // sentences tab -> pangram popup menu (item click)
    $('#sentence_menu .menu_item').click(function(event) {
        $('#sentence_text').val($(this).children('.text').html());
        $('#sentence_menu').hide();
        event.stopPropagation();
    });

    // waterfall tab -> pangram popup menu (item click)
    $('#wf_menu .menu_item').click(function(event) {
        $('#wf_text').val($(this).children('.text').html());
        $('#wf_menu').hide();
        event.stopPropagation();
    });

    // paragragraph tab -> sample text menu (item click)
    $('#para_menu .menu_item').click(function(event) {
        $('#para_text').val($(this).children('.text').html());
        $('#para_menu').hide();
        event.stopPropagation();
    });

    // close colorpicker on click outside
    $('.simpleColorContainer').click(function(event) {
        // close other choosers
        $('.simpleColorContainer').not($(this)).find('.simpleColorChooser').hide();
        $('html').one('click', function() {
            $('.simpleColorChooser').hide();
        });
        event.stopPropagation();
    });

    $('.popup_menu_btn').click(function(event) {
        $('#login_box').hide();
        showMenu(event, $(this).attr('menu_id'));
    });

    $('.submit').click(function() {
        $(this).closest('form').submit();
    });

    // add font page
    $('#form_addfont input[name=type]').click(function() {
        if ($(this).val() == '1') {
            $('#form_addfont input[name=ttf_file]').attr('disabled', '');
            $('#form_addfont input[name=zip_file]').attr('disabled', 'yes');
        }
        else if ($(this).val() == '2') {
            $('#form_addfont input[name=ttf_file]').attr('disabled', 'yes');
            $('#form_addfont input[name=zip_file]').attr('disabled', '');
        }
    });

    $('#form_addfont').submit(function() {
        $('#form_addfont .row.indicator').show();
        $('button[type=submit]').attr('disabled', 'yes');
    });

    // Ctrl+Arrows events
    $(document).keydown(function(event) {
        // ctrl key
        if (event.which == 17)
            ctrlPressed = true;
        // right arrow key
        if (ctrlPressed && event.which == 0x27 && typeof($('#next_page').attr('href')) != 'undefined')
            document.location.href = $('#next_page').attr('href');
        // left arrow key
        if (ctrlPressed && event.which == 0x25 && typeof($('#prev_page').attr('href')) != 'undefined')
            document.location.href = $('#prev_page').attr('href');
    });

    $(document).keyup(function(event) {
        // ctrl key
        if (event.which == 17)
            ctrlPressed = false;
    });

    $('.copy span').click(function() {
        copyrightDialog();
    });

    $('.fav_in a, .fav_ch a, .fav a').click(function() {
        addToCollection(this, $(this).attr('font_id'));
    });

    $('#descr_form').submit(function() {
        $('#descr_img').attr('height', '80').attr('width', '720');
        updatePreview($(this).attr('font_id'), 'sentence', 'descr_text', 'descr_img', 'descr_fgcolor', 'descr_bgcolor', 'descr_size');
        return false;
    });

    $('#sentence_form').submit(function() {
        updatePreview($(this).attr('font_id'), 'sentence', 'sentence_text', 'sentence_img', 'sentence_fgcolor', 'sentence_bgcolor', 'sentence_size');
        return false;
    });

    $('#paragraph_form').submit(function() {
        updatePreview($(this).attr('font_id'), 'paragraph', 'para_text', 'para_img', 'para_fgcolor', 'para_bgcolor', 'para_size');
        return false;
    });

    $('#waterfall_form').submit(function() {
        updatePreview($(this).attr('font_id'), 'waterfall', 'wf_text', 'wf_img', 'wf_fgcolor', 'wf_bgcolor');
        return false;
    });

    $('#tablink1').click(function() {switchTab(1);});
    $('#tablink2').click(function() {switchTab(2);});
    $('#tablink3').click(function() {switchTab(3);});
    $('#tablink4').click(function() {switchTab(4);});
    $('#tablink5').click(function() {switchTab(5);});
    $('#tablink6').click(function() {switchTab(6);});

    $('#login_link').click(function() {
        $('#languages_menu').hide();
        $('#login_box').fadeIn();
        $('#login_f').focus();
        return false;
    });

    $('#footer_login_link').click(function() {
        $('#languages_menu').hide();
        $(window).scrollTop(0);
        $('#login_box').fadeIn();
        $('#login_f').focus();
        return false;
    });

    $('#login_box .close').click(function() {
        $('#login_box').fadeOut();
    });

    $('#login_box form').submit(function() {
        return loginUser();
    });

    $('#hide_categories').click(function() {
        hideCategories();
    });

    $('#show_categories').click(function() {
        showCategories();
    });

    $('.help .section .title a').click(function() {
        $(this).parent().next().slideToggle('fast');
        return false;
    });

    $('.plusaz .plusone, .font .rate .count .plusone').click(function() {

        var font_id = $(this).attr('font_id');
        var obj = $(this);

        $.ajax({
            type: 'POST',
            url: '/ajax/ratings/up',
            dataType: 'json',
            data: {
                font_id: font_id
            },
            success: function(data) {
                if (data.status == 'error') {
                    //alert(data.text);
                    //if there is failure,
                    //just don't change anything
                } else {
                    var rating = obj.parent().find('.rt span').html();
                    if (rating == '')
                        rating = 1;
                    else if (rating == '9k+')
                        rating = '9k+1';
                    else
                        rating = parseInt(rating) + 1;
                    obj.parent().find('.rt span').html(rating);
                    obj.unbind('click');
                }
            }
        });
    });

    $('.tulz select[name=charset]').change(function() {
        var href = document.location.href; // getting current url
        href = href.replace(/[^\/]*$/, ''); // remove page if it is there
        href += '?sort_by=' + $(this).attr('sort_by') + '&license=' + $(this).attr('license') + '&charset=' + $(this).val();
        document.location.href = href; // go to the new url
    });

    $('.vbutton').val('');
    $('.vbutton').mousedown(function() {
        $(this).addClass('pressed');
    });
    $('.vbutton').mouseup(function() {
        $(this).removeClass('pressed');
    });

    $('.vbutton').each(function() {
        if ($.browser.mozilla) {
            $('input:first', $(this).parent()).css('height', '15px');
        }
    });

    //$('#descr_form').submit();

    $('.captchaimg').click(function() {
        var new_src = $(this).attr('src').replace(/\?.*$/, '');
        $(this).attr('src', new_src + '?rand=' + Math.random());
    });

    $('.placeholder').focus(function() {
        if ($(this).hasClass('placeholder')) {
            $(this).val('');
            $(this).removeClass('placeholder');
        }
    });

});

var sentenceTabWasActivated = false;
var paragraphTabWasActivated = false;
var waterfallTabWasActivated = false;

function switchTab(tab_id) {

    $(".tab").hide();
    $(".tablink.active").removeClass('active');
    $("#tabcontent" + tab_id).show();
    $("#tablink" + tab_id).addClass('active');

    if (tab_id == 2 && !sentenceTabWasActivated) {
        $('#tabcontent2 form').submit();
        sentenceTabWasActivated = true;
    }

    if (tab_id == 3 && !paragraphTabWasActivated) {
        $('#tabcontent3 form').submit();
        paragraphTabWasActivated = true;
    }

    if (tab_id == 4 && !waterfallTabWasActivated) {
        $('#tabcontent4 form').submit();
        waterfallTabWasActivated = true;
    }
}

function updatePreview(font_id, type, textbox_id, canvas_id, fgcolor_id, bgcolor_id, size_id) {

    $.ajax({
        type: 'POST',
        url: '/draw.php?request=yes',
        data: {
            draw_type: type,
            font_id: font_id,
            text: $('#' + textbox_id).val(),
            fgcolor: $('#' + fgcolor_id).val().replace(/[^0-9]/, ''),
            bgcolor: $('#' + bgcolor_id).val().replace(/[^0-9]/, ''),
            size: $('#' + size_id).val()
        },
        success: function(dr_key) {
            $('#' + canvas_id).attr('src', '/draw.php?key=' + dr_key);
        }
    });
}

function copyrightDialog() {

    $.ajax({
        type: 'get',
        url: '/ajax/contacts/report_copyright',
        dataType: 'html',
        success: function(data) {
            var content = $('<div id="report_dialog" />').hide();
            $('body').append(content);
            content.html(data);
            content.dialog({
                modal: true,
                width: 480,
                resizable: false,
                open: function() {
                    $('#report_dialog a.close img').click(closeReportDialog);
                },
                close: function() {
                    content.remove();
                }
            });
        }
    });
}

function closeReportDialog() {
    $('#report_dialog').dialog('close');
}

function submitReport() {

    $('form.report button').attr('disabled', 'yes');

    var indicator = $('<img src="/images/indicator1.gif" style="position: relative; top: 2px; left: 2px;" />');
    $('form.report .row.submit').append(indicator);

    $.ajax({
        type: 'post',
        url: '/ajax/contacts/report_copyright',
        data: $('form.report').serialize() + '&url=' + escape(document.location.href),
        dataType: 'json',
        success: function(result) {
            indicator.remove();
            $('form.report button').attr('disabled', '');
            alert(result.text);
            if (result.status == 'ok')
                closeReportDialog();
        }
    });

    return false;
}

function addToCollection(obj, font_id) {

    if ($(obj).hasClass('clicked'))
        return;

    $.ajax({
        type: 'POST',
        url: '/ajax/account/add_to_collection',
        dataType: 'json',
        data: {
            font_id: font_id
        },
        success: function(data) {
            if (data.status == 'error') {
                alert(data.text);
            } else {
                $(obj).addClass('clicked');
                $(obj).html($('#msg_added').html());
                //$(obj).hide();
            }
        }
    });
}

function addFamilyToFavorites(family_id) {
    alert("Ajax method performs (" + family_id + ")")
}

function showMenu(event, menu_div_id) {

    var obj = $('#' + menu_div_id);
    obj.css('position', 'absolute');
    obj.fadeIn('fast');

    $('html').one('click', function() {
        obj.fadeOut('fast');
    });

    event.stopPropagation();
}

function hideCategories() {
    //$('.categories').hide('fade');
    $('.catblock').slideToggle();
    $('.hide').hide();
    $('.show').show();
}

function showCategories() {
    //$('.categories').show('fade');
    $('.catblock').slideToggle();
    $('.show').hide();
    $('.hide').show();
}

function loginUser() {
    
    $.ajax({
        type: 'POST',
        url: '/ajax/auth/login_ajax',
        data: {
            email: $('#login_f').val(),
            password: $('#pwd_f').val(),
            remember_me: $('#remember_me_f').val()
        },
        dataType: 'json',
        success: function(auth_result) {
            if (typeof(auth_result.error) != 'undefined') {
                $('.floatholder .message').hide();
                $('.floatholder .message').html(auth_result.error);
                $('.floatholder .message').fadeIn();
                $('#pwd_f').val('');
                $('#login_f').select();
            } else {
                if (document.location.href.indexOf('/404.html') != -1)
                    document.location.href = '/account.html';
                else
                    document.location.reload();
                // Если мы хотим аяксовый вход, надо делать и аяксовый выход. Старинная китайская мудрость.
                //var obj = '<a href="/account/">' + auth_result.nickname + '</a> [ <a href="/index.php?key=auth&action=logout">Exit</a> ]';
                //$('.loginbox .loginbut, .loginboxdown .loginbut').html(obj);
                //$('.loginbox .signup, .loginboxdown .signup').hide();
                //$('#login_box').fadeOut();
            }
        }
    });

    // prevent submitting form
    return false;
}

function toggleAgreeCheckbox(chkbox) {
    if ($(chkbox).is(':checked')) {
        $('button[type=submit]').attr('disabled', '');
    } else {
        $('button[type=submit]').attr('disabled', 'yes');
    }
}

