/* callback order is:
 *
 * click prev / next --> set animating = true --> prefillPrev/Next --> set animating = false || getNewNikurabe
 *
 * in otherwords, we must reset g_animating only after prefill callback has completed.
 * getNewNikurabe can be called sooner since the new pairId is set before
 * prefill is called anyways
 */

jQuery.fn.slideNews = function(settings) {
    settings = jQuery.extend({
        headline: "Nikurabe Viewer",
        newsWidth: 190,
        newsSpeed: "fast"
    }, settings);
    return this.each(function(i){
        newsContainerWidth = 5 * settings.newsWidth;
        jQuery(".nikstrip",this).css("width",newsContainerWidth + "px");

				startLeft = 0 - settings.newsWidth;
				jQuery(".nikstrip",this).css("left",startLeft + "px");
				
				jQuery(".prev",this).css("display","block");
				jQuery(".next",this).css("display","block");
        g_animating = false;

        jQuery(".next",this).click(function(){
            thisParent = jQuery(this).parent();
            if (g_animating == false) {
                g_animating = true;
                animateLeft = parseInt(jQuery(".nikstrip",thisParent).css("left")) - settings.newsWidth;
                jQuery(".nikstrip",thisParent).animate({left: animateLeft}, settings.newsSpeed, function() {
	                jQuery(this).css("left",animateLeft);

									//get ID of 4th element in list; to the right of center
									newPairId = jQuery('.nikstrip > div:eq(3)').attr('id');
									jQuery("#pairId").attr("value", newPairId);

									// get one after this id
									oneBeforePairIdToGet = $('.nikstrip > div:eq(4)').attr('id');
									$.post( topdir + "/nikurabe/aj_getNikurabePreview",
													{ pairId: oneBeforePairIdToGet, direction: "next" },
													function(data) {prefillNikurabe(data);}
												);

									getNewNikurabe();
                });

                return false;
            }
        }); //next click

        jQuery(".prev",this).click(function() {
            thisParent = jQuery(this).parent();
            if (g_animating == false) {
                g_animating = true;
                animateRight = parseInt(jQuery(".nikstrip",thisParent).css("left")) + settings.newsWidth;
                jQuery(".nikstrip",thisParent).animate({left: animateRight}, settings.newsSpeed, function() {
	                jQuery(this).css("left",animateRight);

									//get ID of 2nd element in list
									newPairId = jQuery('.nikstrip > div:eq(1)').attr('id');
									jQuery("#pairId").attr("value", newPairId);
								
									// get one before this id
									oneAfterPairIdToGet = $('.nikstrip > div:eq(0)').attr('id');
									$.post( topdir + "/nikurabe/aj_getNikurabePreview",
													{ pairId: oneAfterPairIdToGet, direction: "prev" },
													function(data) {prefillNikurabe(data);}
												);

									getNewNikurabe();
                });

								return false;
            }
        }); // prev click
    }); // extend
};
