var hint_target, ajax_request_obj;
//========================================================================

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

//========================================================================

function ajax_abort() {
    if (typeof(ajax_request_obj) == 'object') {
        ajax_request_obj.abort();
    }
}

//========================================================================

function ajax_request(controller, params, callback) {
    ajax_abort();
    ajax_request_obj = $.ajax({
        url: controller,
        dataType: 'json',
        type: 'POST',
        data: params,
        success: function(data){
            if (typeof(callback) == 'function') {
                callback(data);
            }
        }
    });
}

function rating_vote(rating_category, rating_value) {
    $('input[name="ratings[' + rating_category + '][rating]"]').val(rating_value);
    if (rating_value > 0) {
        $('.js-checkbox.rating-category-' + rating_category).addClass('js-checkbox-active');
    } else {
        $('.js-checkbox.rating-category-' + rating_category).removeClass('js-checkbox-active');
    }
    var index = $('#rating_star_' + rating_category + '_' + rating_value).index() + 1;
    $('#rating_' + rating_category + ' a.rating-star').addClass('nonactive');
    $('#rating_' + rating_category + ' a.rating-star:lt(' + index + ')').removeClass('nonactive');
}

// ========================================================================

// Create hint for any input field
// controller - url for processing on the server side
// target - "input" object under which show hint
// callback - function is called when a response is received from the server
function get_hint(controller, target, event, callback) {
    keys = {
        13: enter_key_callback, // Enter
        27: close_hint, // Escape
        38: key_up_callback, // KeyUp
        40: key_down_callback // KeyDown
    };
    
    if ($('.hint').length == 0 || !($('.hint').length > 0 && event.keyCode in keys)) {
        hint_target = target;
        $(hint_target).attr('autocomplete', 'off');
        $(hint_target).keydown(function(event){
            if (event.keyCode == 13) {
                event.preventDefault();
            }
        });
        ajax_request('/hint/'+controller, {
            'request': $(hint_target).val()
        }, function(data){
            $(hint_target).parent().children('.hint').remove();
            if (typeof(data.hint_text) == 'object') {
                var hint = '';
                $.each(data.hint_text, function(id){
                    hint += '<div class="sub-option item_id_'+ id +'">'+data.hint_text[id]+'</div>';
                });
                if (hint.length > 0) {
                    var target_offset = $(hint_target).position();
                    var $hint = $('<div class="hint" id="'+$(hint_target).attr('id')+'_hint"><div class="sub-top"><div class="sub-top-inner"></div></div><div class="sub-center"><div class="sub-center-inner">'+hint+'</div></div><div class="sub-bot"><div class="sub-bot-inner"></div></div></div>').css({
                        left: target_offset.left,
                        top: target_offset.top + $(target).height()
                    });
                    $(hint_target).after($hint);
                }
            }
            if (typeof(callback) == 'function') {
                callback(data);
            }
        });
    }
    if (event.keyCode in keys) {
        if(typeof(keys[event.keyCode]) == 'function') {
            keys[event.keyCode]();
        }
    }
}

function enter_key_callback() {
    $('.hint .sub-option.active').click();
}

function close_hint() {
    $('.hint, .hint_hidden').remove();
}

function key_up_callback() {
    option_index = $('.hint .sub-option.active').index();
    option_index = option_index > 0 ? --option_index : option_index;
    set_active_hint_option_by_index(option_index);
}

function key_down_callback() {
    option_index = $('.hint .sub-option.active').index();
    option_index = option_index < ($('.hint .sub-option').length-1) ? ++option_index : option_index;
    set_active_hint_option_by_index(option_index);
}

function set_active_hint_option_by_index(index) {
    if (index >= 0) {
        $('.hint .sub-option').removeClass('active');
        $('.hint .sub-option:eq('+ index +')').addClass('active');
    }
}


//========================================================================

$(document).ready(function(){
    
    // ========================================================================
    // Survey page logic
    // Must be placed before common hint click event initialization
    $('.survey_form .service-input').keyup(function(event) {
        var category_id = $(this).attr('name').match(/ratings\[(\d+)\]/)[1];
        get_hint('services/' + category_id, $(this), event);
    });
    
    $('.survey_form .hint .sub-option').live('click', function() {
        var id = $(this).attr('class').match(/item_id_(\d+)/)[1];
        $(this).parents('.service-category').find('input[name$="[service_id]"]').val(id);
    });
    
    $('.b-rating').mouseleave(function() {
        var rating_category = $(this).attr('id').match(/^rating_(\d+)$/)[1];
        var rating_value = $(this).parents('.service-category').find('input[name$="[rating]"]').val();
        rating_vote(rating_category, rating_value);
    });
    $('.b-rating a.rating-star').mouseover(function() {
        var index = $(this).index();
        $(this).parents('.b-rating').find('a.rating-star').removeClass('nonactive');
        $(this).parents('.b-rating').find('a.rating-star:gt(' + index + ')').addClass('nonactive');
    });
    
    
    
    // ========================================================================
    
    // ========================================================================
    // Common hint events
    
    // setup CSRF token for ajax requests
    $.ajaxSetup({
        data: csrf_token_data
    });
    
    $('.hint .sub-option').live('click',function(){
        $(this).parents('.hint').prev('input').val($(this).html().replace(/<span>.*<\/span>|<br>/g, ""));
        close_hint();
    });
    $('.hint .sub-option').live('hover', function() {
        $('.hint .sub-option').removeClass('active');
        $(this).addClass('active');
    });
    $('form').keyup(function(event){
        if (event.keyCode == 9) {
            close_hint();
        }
    });
    $(document).click(function(event){
        if ($(event.target).hasClass('hint') || $(event.target).parents('.hint').length > 0) return;
        close_hint();
    });
    
    // ========================================================================
    
    // ========================================================================
    // Signup form logic
    $('.signup_form #storefront_url').keyup(function(event){
        get_hint('company_storefronts', $(this), event, function(data) {
            if (data.hint_equal) {
                hide_company_name()
            } else {
                $('.signup_form .company_name').show();
            }
        });
    });
    
    $('#storefront_url_hint .sub-option').live('click', function() {
        hide_company_name();
    });
    
    function hide_company_name() {
        $('.signup_form .company_name').hide();
        $('.signup_form input[name="company_name"]').val('');
        $('.signup_form input[name="company_id"]').val('');
    }
    
    $('.signup_form #company_name').keyup(function(event){
        get_hint('companies', $(this), event, function(data){
            if (data.hint_equal) {
                $('.signup_form input[name="company_id"]').val(data.hint_equal);
            } else {
                $('.signup_form input[name="company_id"]').val('');
            }
            
        });
    });
    
    $('.terms button.accept').live('click', function() {
        $('.signup_form').submit();
    });
    
    $('.terms button.decline').live('click', function() {
        closePopup();
    });
    
    $('.signup_form button[name="sign"]').click(function(){
        ajax_request('/signup', $('.signup_form').serialize(), function(data){
            if (data.status == 1) {
                showPopup('Terms and Conditions', $('.signup_form .terms').clone());
            } else {
                var messages = '';
                $.each(data.error, function(id){
                    messages += data.error[id];
                });
                showPopup('Errors Occured', messages);
            // captcha_src = $('img.captcha').attr('src').replace(/get_image.*/, 'get_image/'+ getRandomInt(1000, 9999));
            // $('img.captcha').attr('src', captcha_src);
            // $('.signup_form input[name="captcha_word"]').val(''); 
            }
        });
    });
    $('.signup_form').submit(function(event){
        if (!$('.terms').is(':visible')) {
            return false;
        }
    });
    $('.signup_form button[name="decline"]').click(function(){
        $('.signup_form .terms').hide();
    });
    $('.signup_form #storefront_url_hint li').live('click',function(){
        $('.signup_form .company_name').hide();
        $('.signup_form input[name="company_name"]').val('');
        $('.signup_form input[name="company_id"]').val('');
    });
    $('.signup_form #company_name_hint .sub-option').live('click',function(){
        $('.signup_form input[name="company_id"]').val($(this).attr('class').match(/item_id_(\d+)/)[1]);
    });
    // ========================================================================
    
    // ========================================================================
    // Profile form logic
    $('.update_profile_form .add_storefront_btn').click(function() {
        var $form = $('#new_storefront_form').clone().removeAttr('id');
        var id = new Date().getTime();
        
        $('.update_profile_form ul.company_storefronts').append($('<li />').html($form.show()));
        
        $form.find('input, select').each(function(){
            $(this).attr('name', $(this).attr('name').replace('{_id}', id));
        });
        
        $('.update_profile_form .custom_storefronts_msg').show();
    });
    
    $("#company-revenue").keydown(function(event) {
        var available_char_keys = [
            8, 46, // backspace and delete
            35, 36, // home and end keys
            37, 38, 39, 40, // cursor navigation keys
            48, 49, 50, 51, 52, 53, 54, 55, 56, 57, // numbers
            96, 97, 98, 99, 100, 101, 102, 103, 104, 105 // calc numbers
        ]
        
        if (available_char_keys.indexOf(event.keyCode) < 0) {
            event.preventDefault();
        }
    });
    
    $('.update_profile_form button.cancel_storefront').live('click', function() {
        $(this).parents('li').remove();
    });
    // ========================================================================
    
    // ========================================================================
    // Current ratings page logic
    $('select[name="revenue_categories"]').live('change', function(){
        ajax_request('/current_ratings', {
            revenue_category: $(this).val()
            }, function(data){
            $('.center-main').empty().append(data);
            if (typeof(google) == 'object') {
                $('.charts a:first').click();
            }
        });
    });
    $('.charts a:first').click();
    $('input[name="subscribe"]').live('change', function(){
        subscribe = $(this).attr('checked') ? 1 : 0;
        ajax_request('/current_ratings/change_subscibe', {
            subscribe: subscribe
        }, function(data){
            $('.messages').remove();
            $('table').before('<div class="messages">'+data+'</div>');
        });
    });
    
    // ========================================================================
    
    var $popup = $('#popup1');
    
    function showPopup(title, content) {
        $popup.find('.b-top h1').text(title);
        $popup.find('.b-center').html('').append(content);
        
        centerPopup();
        $popup.add('#overlay').show();
    }
    
    function centerPopup() {
        $popup.css({
            top: (($(window).height() - $popup.height()) * 0.5) + 'px',
            left: (($(window).width() - $popup.width()) * 0.5) + 'px'
        });
    }
    
    function closePopup() {
        $('.popup-wrapper, #overlay').hide();
    }
    
    $popup.find('a.close').click(closePopup);
    
    $(window).resize(centerPopup);

});

// JS Checkbox inputs
function jsCheckboxes() {
    $('input[type=checkbox]:not(.normal)').before('<div class="js-checkbox"></div>').hide();
    $('.js-checkbox').each(function(){
        var js_check = $(this),
        orig_check = $(this).next('input');

        if (orig_check.is(":checked"))
            js_check.addClass('js-checkbox-active');

        orig_check.click(function() {
            if (!orig_check.is(":checked")) {
                js_check.addClass('js-checkbox-active')
            } else {
                js_check.removeClass('js-checkbox-active')
            }
        })

        js_check.click(function(){
            orig_check.click()
        })
        orig_check.parent("label").click(function(){
            orig_check.click();
            return false;
        })
        orig_check.next("label").click(function(){
            orig_check.click();
            return false;
        })
    })
}
