/**
 * Developed by Adam Coogan
 * Built on top of the jQuery library
 * http://jquery.com
**/

(function($) {

     /**
     * Creates a news reader from an unordered list
     **/
     
    var e;

    $.fn.newsReader = function(o) {               
        return this.each(function() {
            new $nr(this, o);
        });      
    };

    // Default configuration properties.
    var defaults = {
        speed: 3,
        start: 0,
        rtl: true,
        focusOnHover: true,
        textOnHover: false,
        fade: true,
        fadeInSpeed: "fast",
        effect: "none",
        autoStart: true,
        mouseOver: true,
        carouselSpeed: 800,
        leftAlign: "-79px",
        carouselImagesPerRow: 7
        
    };

    $.newsReader = function(e, o) {
        
        // Stylesheet should be set to display so browsers can render without javascript - AS
        $(e).show();
        
        // Combine the default and user configurations together        
        this.settings = $.extend({}, defaults, o || {});
        s = this.settings;
        
        // TODO: Implement a lock function that disables mouse overs when an effect is happening
        this.lock = false;
        
        // The default position of News Reader
        var current = s.start;
        
        // Count the length of items
        var count = $(e).children().length-1;
        
        // Check that the count isn't less than the start position
        count < current ? current = 0 : current = s.start;
        
        // Default vars
        var changeItemsInterval;
        var lastToBeAppended;
        
        // Clone the UL to create the thumbnails
        //$("#newsReader").clone().attr("id","thumbnails").insertBefore('#newsReader');
        /*Assign Ids to the Newsreader and Thumbnails li's - this way we can acess the elements alot easier and quicker.*/
        var perRow=s.carouselImagesPerRow;
        howManyLi = $("#thumbnails li").size();
        middleImage=Math.ceil((s.carouselImagesPerRow/2));
        if (($("#newsReader li").size()>0)&&($("#thumbnails li").size()>perRow))
        {// This is our safety net to check if carousel meets the correct requirements before it starts
            for (var i=0;i<$("#newsReader li").size();i++)
            {
                var chk=$($("#newsReader").children("li")[i]).attr("id").split("_");
                var isOnPage = $('#thumbnails_'+chk[1]).get();
                if (isOnPage=="")
                {// If it is not on our HTML page.. We can then clone the li AND Append to the page.
                   $("#newsReader_"+chk[1]).clone().attr("id","thumbnails_"+chk[1]).appendTo('#thumbnails');
                   var hlTag=$($($("#newsReader_"+chk[1]).children("div")[0]).children("h1")[0]).html();
                   $($($("#thumbnails_"+chk[1]).children("a")[0]).children("img")[0]).attr('title',hlTag);
                   lastToBeAppended=chk[1];
                }
            }
            
    
            // Remove the text from the cloned UL      
            if(!s.textOnHover) {        
                $("#thumbnails div").remove();
            } else {
                $("#thumbnails div p").remove();
                $("#thumbnails div h1").hide();
            }
            
         }
         else
         {
             //There are no images and therefore must be a problem - Lets end the Script
             return;
         }
         
        /* START Add class to the li on JS loading.. */
        $($($($("#thumbnails").children("li")[middleImage]).children("a")[0]).children("img")[0]).addClass("thumbSel");
        $($("#thumbnails").children("li")[middleImage]).addClass("liSel");
        $(".MainCarousel").css('margin-left','0px');
        /* END Add class to the li on JS loading.. */
        
        // Bind the onMouseOver and onMouseOut to the anchor tags
        $("#thumbnails a").each(function(index){
            
            if (parseInt(jQuery.fn.jquery)>=1.3) {
                $(this).live("hover",function(){jQuery.newsReader.onHoverIn(index);},function(){jQuery.newsReader.onHoverOut(index);});
            } else {
                if (s.mouseOver)
                {
                    // Bind onMouseOver function to anchor tag
                    $(this).bind("mouseenter",function() { 
                        jQuery.newsReader.onHoverIn(index); 
                    });
                    // Bind onMouseOut function to anchor tag
                    $(this).bind("mouseleave",function() { 
                        jQuery.newsReader.onHoverOut(index); 
                    });
                }
            }
        });
        
        /* 
            Carousel effect Begins
            LAST Update 25/5/10 09:35 - Richard Smith
        
        */
        if(s.effect=="carousel") 
        {
            //$('#thumbnails li:first').before($('#thumbnails li:last')); // Puts the last item infront of the first to create infinate loop
            howManyLi = $("#thumbnails li").size();
            middleImage=Math.ceil((s.carouselImagesPerRow/2));
            
            var isFunctionLocked; // This is our LOCK variable, we will check this upon running a click event to not cause mutliple clicks [ERRORS]
            
            if (s.autoStart)
            {// if auto start is true then we will setInterval which will run untill cleared..
                if (s.rtl) {direc="right"} else {direc="left"} // if rtl is set to true then it will run from right to left.
                changeItemsInterval = setInterval(function () {carouselChange(middleImage,direc,1);}, s.speed*1000);
            }
            
            function fadePicInAndOut(ImageFrom,ImageTo)
            {// function that will fade in the the Big image, params are index arrays of the li's.
                if (s.fade){
                    // will fade in the Big image into if fade is set to TRUE
                    $($(e).children()[ImageFrom]).fadeOut(s.fadeInSpeed,function(){
                    $($(e).children()[ImageTo]).fadeIn(s.fadeInSpeed);
                });
                }else{
                    // No fade if the fade setting is set to FALSE
                    $($(e).children()[ImageFrom]).hide();
                    $($(e).children()[ImageTo]).show();
                }
            }

            function changeBigImage(direction,thumbId)
            { 
                if (($("#newsReader_"+thumbId).prevAll().length==0)||($("#newsReader_"+thumbId).prevAll().length==($("#newsReader li").size()-1)))
                {
                    if (direction=="left")
                    {
                        if ($("#newsReader_"+thumbId).prevAll().length==0){
                            ImageFrom=($("#newsReader li").size()-1); 
                        }else if($("#newsReader_"+thumbId).prevAll().length==($("#newsReader li").size()-1)){
                            ImageFrom=($("#newsReader li").size()-2);
                        }
                     }
                     else if (direction=="right")
                     {
                         if ($("#newsReader_"+thumbId).prevAll().length==0){
                             ImageFrom=1;
                         }else if($("#newsReader_"+thumbId).prevAll().length==($("#newsReader li").size()-1)){
                             ImageFrom=0;
                         }
                     }
                }
                else
                {
                   if (direction=="left"){
                       ImageFrom=($("#newsReader_"+thumbId).prevAll().length-1);
                   }else if (direction=="right"){
                       ImageFrom=($("#newsReader_"+thumbId).prevAll().length+1);
                   }
                }
                return ImageFrom;
            }
            
            function carouselChange(midImage,direction,increment)
            {
                isFunctionLocked = true;    
                var caroSpeed = s.carouselSpeed;
                var ballanceUpLeft_Indent = (increment-1)*80;
                $($($($("#thumbnails").children("li")[midImage]).children("a")[0]).children("img")[0]).removeClass("thumbSel");
                $($("#thumbnails").children("li")[midImage]).removeClass("liSel");
                var item_width = $('#thumbnails li').outerWidth() + 0;
                
                if (direction=="left"){
                    var left_indent = (parseInt($('#thumbnails').css('left')) - item_width)*increment;
                    if (increment!=1){
                        var left_indent = (left_indent+ballanceUpLeft_Indent);
                    }
                    $($($($("#thumbnails").children("li")[middleImage+increment]).children("a")[0]).children("img")[0]).addClass("thumbSel");
                    $($("#thumbnails").children("li")[middleImage+increment]).addClass("liSel");
                    var ThumbId=$($("#thumbnails").children("li")[middleImage+increment]).attr("id").split("_");
                    var ImageTo=$("#newsReader_"+ThumbId[1]).prevAll().length;
                }else if(direction=="right"){
                    var left_indent = (parseInt($('#thumbnails').css('left')) + item_width)*increment;
                    if (increment!=1){
                        var left_indent = (left_indent+ballanceUpLeft_Indent);
                    }
                    $($($($("#thumbnails").children("li")[middleImage-increment]).children("a")[0]).children("img")[0]).addClass("thumbSel");
                    $($("#thumbnails").children("li")[middleImage-increment]).addClass("liSel");
                    var ThumbId=$($("#thumbnails").children("li")[middleImage-increment]).attr("id").split("_");
                    var ImageTo=$("#newsReader_"+ThumbId[1]).prevAll().length;
                }
                if (increment==1){
                    var ImageFrom=changeBigImage(direction,ThumbId[1]);
                    fadePicInAndOut(ImageFrom,ImageTo);
                }else{
                    caroSpeed=700; // Make the carousel faster when increment more than 1
                }
                
                //alert(left_indent); 
                $('#thumbnails:not(:animated)').animate({'left' : left_indent,queue: true,"duration": "fast","easing": "easeInBounce"},caroSpeed,function(){ 
                    for (var i=1;i<=increment;i++)
                    {
                        if (direction=="left"){
                            $('#thumbnails li:last').after($('#thumbnails li:first'));
                        }else if (direction=="right"){
                            $('#thumbnails li:first').before($('#thumbnails li:last'));
                        }
                    }
                    $('#thumbnails').css({'left' : s.leftAlign}); // sets the UL to have the same left alignment that it had at the begining.
                    isFunctionLocked = false; // Lock will only become active once the carousel has finished.
                });
            }
            
            function checkIfFunctionIsLocked()
            {// check LOCK and see if it is set to TRUE OR FALSE
                var locked;
                if (isFunctionLocked){
                    locked = true;
                }else{
                    locked = false;
                }
                return locked;
            }
            
            // Add Previous Button
            $(".prev").html('<a class="prevButton"></a>');
            $('.prevButton').click(function(){ // CLICK LEFT ARROW
                var lock=checkIfFunctionIsLocked();
                if (lock==false){
                    clearInterval(changeItemsInterval); // clears the setInterval
                    carouselChange(middleImage,"right",1);
                }
            })
            
            // Add next button
            $(".next").html('<a class="nextButton"></a>');
            $('.nextButton').click(function(){ // CLICK RIGHT ARROW
                var lock=checkIfFunctionIsLocked();
                if (lock==false){
                    clearInterval(changeItemsInterval); // clears the setInterval
                    carouselChange(middleImage,"left",1);
                }
            })
            
            $('#thumbnails li').hover(
                function () {//First param does the onhover event
                    clearInterval(changeItemsInterval);
                }, 
                function () {// Second param does the onhoverout event
                    changeItemsInterval = setInterval(function () {carouselChange(middleImage,direc,1);}, s.speed*1000);
                }
            );

            
            
            
            $('#thumbnails li a').click(function(event){ // CLICK ON IMAGE
            	event.preventDefault();
				// middle Image middleImage
                var lock=checkIfFunctionIsLocked();
                if (lock==false)
                {
                    clearInterval(changeItemsInterval); // changeItemsInterval
                    IndexOfImageClicked=$(this).parent("li").prevAll().length;
                    ImageClickedFrom=$($("#thumbnails").children("li")[middleImage]).attr("id").split("_");
                    ImageClickedTo=$($("#thumbnails").children("li")[IndexOfImageClicked]).attr("id").split("_");
                    if (IndexOfImageClicked!=middleImage)
                    {
                        if (IndexOfImageClicked>middleImage)
                        {// We go from Left to right to get to middle
                            var difference=(IndexOfImageClicked-middleImage);
                            carouselChange(middleImage,"left",difference);
                            
                            ImageTo=$("#newsReader_"+ImageClickedTo[1]).prevAll().length; 
                            ImageFrom=$("#newsReader_"+ImageClickedFrom[1]).prevAll().length;
                            fadePicInAndOut(ImageFrom,ImageTo);
                            
                        }
                        else
                        {// We go from right to left to get to the middle image
                            var difference=(middleImage-IndexOfImageClicked);
                            carouselChange(middleImage,"right",difference);
                            
                            ImageTo=$("#newsReader_"+ImageClickedTo[1]).prevAll().length; 
                            ImageFrom=$("#newsReader_"+ImageClickedFrom[1]).prevAll().length;
                            fadePicInAndOut(ImageFrom,ImageTo);
                        }
                    }
                 }
				 
            })
            // End of Carousel.
        }
        
        // Hide all the li items apart the starting position
        $(e).children().each(function(i){
            i != current ? $(this).hide() : false;
        });
        
        // Function onHoverIn, this stops the looping and changes the selected item to the one the mouse is hovering on
        $.newsReader.onHoverIn = function (index) {
            
            // clear the set interval
            clearInterval(changeItemsInterval);
            
            // call the function to change the item to the hovered item            
            changeItem(e,current,index,count);
            
            // If the textOnHover is true show the h1 tag
            s.textOnHover ? $($("#thumbnails div").children("h1")[index]).show() : false; 
            
            // Give selected class to li that is currently hovered over
            $($("#thumbnails").children("li")[index]).attr("class","selected");
            $($($($("#thumbnails").children("li")[index]).children("a")[0]).children("img")[0]).addClass("thumbSel");
            $($("#thumbnails").children("li")[index]).addClass("liSel");

        };
        
        // Function onHoverOut, this starts the looping again
        $.newsReader.onHoverOut = function (index) {
            
            // clear the set interval
            clearInterval(changeItemsInterval);
            
            // Set the current item to the last item hovered over
            current=index;
            
            // restart up the setInterval to call the function changeItem
            changeItemsInterval = setInterval(function () {changeItem(e,current,setDirection(current),count)}, s.speed*1000);
            
            // If the textOnHover is true hide the h1 tag
            s.textOnHover ? $($("#thumbnails div").children("h1")[index]).hide() : false; 
            
            // Remove selected class
            $($("#thumbnails").children("li")[index]).removeClass();
            $($($($("#thumbnails").children("li")[index]).children("a")[0]).children("img")[0]).removeClass("thumbSel");
            $($("#thumbnails").children("li")[index]).removeClass("liSel");
            
        };
        
        // set interval to call the function changeItem  @@RS Starts the AUTO Carousel
        if (s.autoStart)
        {
            //changeItemsInterval = setInterval(function () {changeItem(e,current,setDirection(current),count)}, s.speed*1000);
        }
        
        function GetCurrent(nxtPre)
        {//Get Current News Item and then change to the next Item.. NEXT and PREV Button on CLICK EVENT
            clearInterval(changeItemsInterval);
            var direction="";
            if (nxtPre=="next") {direction=(current-1)}else{direction=(current+1)}
            changeItem(e,current,direction,count);
        }
        
        // set the direct of the rotation : default is right to left
        function setDirection(current) {
           return s.rtl ? current+1 : current-1;
        }
       
        // Change one LI to another
        function changeItem(e,from,to,count) {

            // Check if the 'to' is less than the from
            if(to<from) {
                to < 0 ? to=count : false; // If 'to' is less then 0 then set it to the count of items
            } else {
                to > count ? to=0 : false; // If 'to' is greater then the count set it to zero
            }  
            
            //TODO: change to a case statement to allow loads of effects (fade/slide/zoom etc etc)
            
            // If effect, do effect otherwise just hide() the current item
            if(s.fade) {
                $($(e).children()[from]).fadeOut(s.fadeInSpeed,function(){
                    $($(e).children()[to]).fadeIn(s.fadeInSpeed);
                });
            } else if (s.effect=="carousel"){
               $($(e).children()[from]).hide();
               $($(e).children()[to]).show();
            }else {
            }
            // set the current var to change item
            current=to;

        }
               
    }
    
    // Create shortcut for internal use
    var $nr = $.newsReader;

})(jQuery);


