WR.util.namespace('WR.bogushtime.trainings');

WR.bogushtime.trainings.training = {
    /**
     * Initialize all JS functionality of the 'training' page
     */
    init: function() {
        // There is a lot of work TODO if you'll uncomment next line
        // (but you may do this - it works!)
        //this.appendAsyncTrainingContent();
        
        this.initClientLogoHover();
        this.initClientsScroller();
//      this.initPriceInfoLoader();
    },
    
    /**
     * Add AJAX to the training contents
     */
    appendAsyncTrainingContent: function() {
        var c = $('#training-contents-menu'),
            self = this;
        
        // Post-process already loaded training content
        $('#training-contents').wrapInner(
            '<div class="trainingSubBlock" id="' + 
                c.find('.menuSub3 li.selected a').attr('content_id') + 
            '"></div>'
        );
        
        c.find('.menuSub3 li a, .trainingsOrder a').click(function(e) {
            // Handling selected LI
            c.find('.selected, .btnSelected').removeClass('selected btnSelected');
            var p = $(this).parent();
            if (p.is('li'))
                p.addClass('selected')
            else
                p.addClass('btnSelected');
            
            // AJAX loading
            var contentBlockID = $(this).attr('content_id');
            if (contentBlockID) {
                // Get or create container 
                var container = $('#' + contentBlockID);
                if (!container.size()) {
                    container = $('<div id="' + contentBlockID + '" style="display:none" class="trainingSubBlock loadingBlock"></div>');
                    container.appendTo('#training-contents');
                }
                
                // Send AJAX request and cache it
                if (!self.pageLoadState[contentBlockID]) {
                    self.pageLoadState[contentBlockID] = 'loading';
                    $.ajax({
                        url: $(this).attr('href'),
                        context: container,
                        success: function(blockHTML) {
                            self.pageLoadState[contentBlockID] = 'loaded';
                            $(this).removeClass('loadingBlock').html(blockHTML);
                        }
                    });
                }
                
                $('#training-contents .trainingSubBlock').hide();
                container.show();
            }
            
            e.preventDefault();
        })
    },
    
    pageLoadState: {},
    
    /**
     * Handle clients logo hover
     */
    initClientLogoHover: function() {
        $('.trainingsWere .trainingClientVisitor a').each(function() {
            var img = $('img', this);
            if (img.attr('colored')) {
                var colored_logo = img.attr('colored'),
                    grayed_logo = img.attr('src');
                $(this).hover(
                    function() { img.attr('src', colored_logo); },
                    function() { img.attr('src', grayed_logo); }
                );
            }
        });
    },
    
    initClientsScroller: function() {
        var cnt = $('#clients-pages-scroller'),
            prevBtn = $('img.prevItem', cnt),
            nextBtn = $('img.nextItem', cnt);
        
        // Wrap navigation buttons 'next' and 'prev' if needed
        if (!prevBtn.parent().is('a')) {
            prevBtn.wrap('<a href="../../bogushtime/js"></a>');
        }
        if (!nextBtn.parent().is('a')) {
            nextBtn.wrap('<a href="../../bogushtime/js"></a>');
        }
        
        $('a', cnt).click(function(e) {
            // Prevent default browser link clicking
            e.preventDefault();
            
            var pageID = $(this).attr('page_id');
            
            // Do something with click only when there is target ID
            if (!pageID)
                return;
            
            pageID = parseInt(pageID, 10);
            
            // Re-set navigation 'prev' and 'next' buttons
            var minus1ID = pageID - 1,
                plus1ID = (pageID < $('.scrollItem', cnt).size()) ? pageID + 1 : false;
            
            if (minus1ID)
                prevBtn.removeClass('disabledItem').parent().attr('page_id', minus1ID);
            else
                prevBtn.addClass('disabledItem').parent().removeAttr('page_id');
            
            if (plus1ID)
                nextBtn.removeClass('disabledItem').parent().attr('page_id', plus1ID);
            else
                nextBtn.addClass('disabledItem').parent().removeAttr('page_id');
            
            // Remove current selected item and create new one
            $('img.scrollItem', cnt).removeClass('selectedItem');
            
            $('#scroll-point-for-clients-page-' + pageID, cnt).addClass('selectedItem');
            
            // Hide old and show new logos
            showLogos: {
                $('#clients-list').animate({ marginLeft: -((pageID - 1) * 432) });
            }
        });
    },

    initPriceInfoLoader: function() {
        // set event handler
        var self = this,
            form = $("#id_amount_of_participants").parents("form");
		
        function evalPrice() {
            var count = $("#id_amount_of_participants").val();
            var training_id = $("#training-id").val();
            
            // Extra params
            var extra_items = form.find('input:checkbox:checked[name=extra_discount]');
            var extra = {};
            extra_items.each(function() {
                extra["extra_discount"] = this.value;
            });
            
            $("#order-prices").addClass("ajaxLoader");
            var container = $("#order-prices");
            container.fadeOut(function () {
                self.loadPriceInfo(training_id, count, extra);
                container.fadeIn();
            });
        }
        
        // Update price on change
        var odlPrice;
        $("#id_amount_of_participants").focus(function() { oldPrice = this.value; });
        $("#id_amount_of_participants").change(function() {
            if (this.value == oldPrice)
                return;
            clearTimeout(updateDelay);
            evalPrice();
        });
        
        // Update price on keyup (i.e. after typing)
        var updateDelay, updateDelayTime = 700;
        $("#id_amount_of_participants").keyup(function() {
            if (this.value == oldPrice)
                return;
            clearTimeout(updateDelay);
            updateDelay = setTimeout(evalPrice, updateDelayTime);
        });

		// Init extra discounts
		var extra_items = form.find('input:checkbox[name=extra_discount]');
        extra_items.removeAttr("checked").click(function() {
            clearTimeout(updateDelay);
            evalPrice();
        });
    },

    loadPriceInfo: function(training_id, count, extra) {
        $.ajax({
            url: "/training/ajax/order_price_info/",
            type: 'GET',
            data: $.extend({ training: training_id, count: count }, extra),
            success: function(data) {
                oldPrice = $("#id_amount_of_participants").val();
                var container = $("#order-prices");
                var container = $("#order-prices").removeClass("ajaxLoader");
                container.html(data);
            },
            error: function(data) {
                alert("Error:" + data);
            }
        });
    }
};

$(function(){
    WR.bogushtime.trainings.training.init();
});
