jQuery(function($) {
    var ocs_terminated = false;

    $('#ocs_factor-all').change(function() {
        $('#ocs_admin-input-factors input:checkbox:enabled')
            .attr('checked', $(this).attr('checked')? 'checked' : null);
    });

    $('.ocs_post-all').change(function() {
        $('#ocs_admin-table-posts input:checkbox:enabled')
            .attr('checked', $(this).attr('checked')? 'checked' : null);
    });

    $('.ocs_post-type').change(function() {
        $('#ocs_admin').submit();
    });

    $('.ocs_post_status-link').click(function() {
        $('#post_status').val($(this).attr('data-post_status'));
        $('#ocs_admin').submit();
        return false;
    });

    $('.ocs_paged-link').click(function() {
        $('#paged-hidden')
            .attr('name', 'paged')
            .val($(this).attr('data-paged'));
        $('#paged-text').attr('name', '_paged');
        $('#ocs_admin').submit();
        return false;
    });

    $('.ocs_order-link').click(function() {
        $('#orderby').val($(this).attr('data-orderby'));
        $('#order').val($(this).attr('data-order'));
        $('#ocs_admin').submit();
        return false;
    });

    $('.ocs_keyword').focus(function() {
        $('.ocs_selected[value="' + $(this).attr('data-post_id') + '"]')
            .attr('checked', 'checked');
    });

    $(".ocs_navigation-text").keypress(function(event) {
        if (event.which == 13) {
            $('#ocs_admin').submit();
            return false;
        }
    });

        // mass optimize
    $('.ocs_optimization-submit').click(function() {
        var keywords = [];
        var elems = $('#ocs_admin-table-posts').find('input:checkbox:checked:not(.ocs_post-all)');
        var itemCount =  elems.length;

        if (0 != itemCount) {
            for (var i = 0; i < itemCount; i++) {
                var postId  = $(elems[i]).val();
                var keyword = $(elems[i]).parents('tr.ocs_admin-table-row').find('input.ocs_keyword').val();
                keywords[i] = [postId, keyword];
            };

            ocs_showProgress(null);
            ocs_optimize(keywords, ocs_getFactors(), ocs_getExtraContentMode(),
                itemCount, 0, true);
        } else {
            ocs_message('Please select some posts to process', 'error');
        }
    });

    // single optimize
    $('.tools-column button.ocs_optimizing_item-button').click(function(){
        var keywords = [];
        var postId  = $(this).parents('tr.ocs_admin-table-row').find('input:checkbox').val();
        var keyword = $(this).parents('tr.ocs_admin-table-row').find('input.ocs_keyword').val();
        keywords[0] = [postId, keyword];

        ocs_showProgress($('#ocs_optimizing-' + postId));
        ocs_optimize(keywords, ocs_getFactors(), ocs_getExtraContentMode(),
            0, 0, true);
    });

    $('.ocs_optimizing-cancel').click(function() {
        ocs_terminate();
    });

    // single keyword
    $('button.ocs_set_keyword_item-button').click(function(){
        var title = $(this).attr('data-title');
        var postId = $(this).attr('data-id');
        var elem = $('#ocs_admin-table-row-'+postId);
        ocs_setKeyword(elem, title);
    });

    // mass set keywords
    $('.ocs_set_all_keywords-button').click(function(){
        $('#ocs_admin-table-posts tr.ocs_admin-table-row').each(function(n, elem){
           if ('' == $(elem).find('input.ocs_keyword').val()) {
               var title = $(elem).find('input.ocs_title:hidden').val();
               if ('' != title) {
                    ocs_setKeyword(elem, title);
               }
           }
        })
    });

    function ocs_message(message, type)
	{
        var element = jQuery('<strong />').text(message);
        element = jQuery('<p />').append(element);
        element = jQuery('<div class="' + type + '"  />').append(element);
        jQuery('#messages-container')
            .empty()
            .append(element);
    }

	function ocs_showProgress(elem)
	{
		$('div.updated, div.error').remove();
		if (elem) {
			$('button', $(elem)).hide();
            $('span', $(elem)).show();
            $('img', $(elem)).css({ 'visibility': 'visible'});
		} else {
			$('.ocs_optimization-submit').attr('disabled', 'disabled');
            $('#ocs_optimizing-progress img.ocs_ajax-optimizing').css('visibility', 'visible').show();
            $("#ocs_optimizing-progressbar").progressbar({ value: 0 });
            $("#ocs_optimizing-progressbar").progressbar( 'option', 'value', 0 );
            $('#ocs_optimizing-progress').slideDown();

            //Auto scroll:
            if (!ocs_isScrolledIntoView($('#ocs_optimizing-progress'))) {
                $('html, body').animate({
                    scrollTop: $("#ocs_optimizing-progress").position().top
                }, 1000);
            }
		}
	}

	function  ocs_hideProgress(elem)
	{
		if (elem && -1 != elem) {
            $('span', $(elem)).hide();
            $('img', $(elem)).css({ 'visibility': 'hidden'});
            $('button', $(elem)).show();
        } else {
            $('#ocs_optimizing-progress').slideUp();
            $('.ocs_optimization-submit').removeAttr('disabled');
		}
	}

    function ocs_changePostStatusIcon(result)
    {
        if (result['postId'] > -1) {
            var elem = $('tr#ocs_admin-table-row-' + result['postId']);
            var className = 'ocs_status_optimize-yes';
            if (result['status']) {
                elem.find('.ocs_status').addClass(className);
            } else {
                elem.find('.ocs_status').removeClass(className);
                elem.find('.ocs_selected').attr('checked', false);
            }
        }
    }

    function ocs_optimize(keywords, factors, extraContentMode, itemCount,
        currentItem, saveFactors)
    {
        var single = (0 == itemCount);
        if (keywords.length > 0) {
            var keyword = keywords.shift();
			var postId = keyword[0];
            if (!single) {
                currentItem++;
                $('#ocs_optimizing-current').html(currentItem);
                $('#ocs_optimizing-all').html(itemCount);
            }
            $.ajax({
                type: 'POST',
                url: ajaxurl,
                data: {
                    action:                 'ocs',
                    controller:             'admin',
                    controller_action:      'ajax-optimize',
                    postId:                 postId,
                    keyword:                keyword[1],
                    factors:                factors,
                    extra_content_mode:     extraContentMode,
                    save_factors:           saveFactors
                },
                dataType: 'json',
                context: single ? $('#ocs_optimizing-' + postId) : -1,
                success: function(data) {
                    if ('' != data['error']) {
						ocs_message(data['error'], 'error');
						ocs_hideProgress(this);
					} else {
                        if (itemCount > 0) {
						    $("#ocs_optimizing-progressbar").progressbar('option', 'value', Math.round(100*currentItem/itemCount));
                        }
                        ocs_changePostStatusIcon(data['result']);
                        ocs_optimize(keywords, factors, extraContentMode,
                            itemCount, currentItem, false);
                    }
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    if (!ocs_terminated) {
                        ocs_message('AJAX connection error', 'error');
                        ocs_hideProgress(this);
                    }
                },
                complete: function() {
                    if (-1 != this) {
                        ocs_hideProgress(this);
                    }
				}
            });
        } else {
            if (itemCount) {
                ocs_hideProgress(null);
                ocs_message('Mass Optimize: processed ' + itemCount + ' posts', 'updated');
            }
        }
    }

    function ocs_terminate()
    {
        ocs_terminated = true;
        $('#ocs_admin').submit();
    }

	function ocs_getFactors()
	{
		var factors = [];
        $('li.ocs_admin-factor input:checkbox:checked').each(function(n, elem){
            factors[n] = $(elem).val();
        });
		return factors;
	}

    function ocs_getExtraContentMode()
    {
        return $('input.ocs-extra_content_mode-option:checked').val();
    }

    function ocs_isScrolledIntoView(elem)
    {
        var docViewTop = $(window).scrollTop();
        var docViewBottom = docViewTop + $(window).height();

        var elemTop = $(elem).offset().top;
        var elemBottom = elemTop + $(elem).height();

        return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)
          && (elemBottom <= docViewBottom) &&  (elemTop >= docViewTop) );
    }

    function ocs_setKeyword(elem, title){
        $(elem).find('input.ocs_keyword').val(title);
        $(elem).find('input.ocs_selected').attr('checked', 'checked');
    }

    //
    // Options screen
    //

    $('#auto_optimization_keyword').focus(function() {
        $('#auto_optimization-option-keyword').attr('checked', 'checked');
    });

    $('#default_factors-all').change(function() {
        $('#default_factors input:checkbox:enabled')
            .attr('checked', $(this).attr('checked')? 'checked' : null);
    });

    $('#bing_api_key').change(function() {
        if ('' == $.trim($(this).val())) {
            $('#default_factors-option-RelatedTerms')
                .attr('disabled', 'disabled')
                .removeAttr('checked');
        } else {
            $('#default_factors-option-RelatedTerms')
                .removeAttr('disabled');
        }
    });
});