/** News ticker
 * Author: StillWatersRunDeep 
 * http://codecanyon.net/user/StillWatersRunDeep
 * http://www.sharpnose.eu/
 * Created: 26th June, 2010
 **/

jQuery.fn.newsbox = function(opts) {
    var that = this;
    var itemCount;
    var curItem = 0;
    var elId, tc, ti;
    var changeInterval, resumeTimer;
        var hideAnimTime, showAnimTime;
    
    var refreshItems = function() {
        that.each(function() {
            ti = $('#' + this.id + ' .titem');
            itemCount = ti.length;
            
            var ih = parseInt(opts.height, 10);
            ti.css('height', (ih-10) + "px");
        });
    };
    
    var append_feeds = function (rss_url, try_count) {
        var apiUrl = (opts.proxyUrl || "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=") + rss_url;
        if (opts.limit != null) apiUrl += "&num=" + opts.limit;
        if (opts.apiKey != null) apiUrl += "&key=" + opts.apiKey;
        try_count = try_count || 0;
        
        $.getJSON(apiUrl, function(jsonData) {
            var i = 0, max, content, title, link;
            if (jsonData.responseStatus == 200) {
                max = jsonData.responseData.feed.entries.length;
                for (i=0; i<max; i++) {
                    title = $("<div>"+jsonData.responseData.feed.entries[i].title+"</div>").text();
                    content = $("<div>"+jsonData.responseData.feed.entries[i].content+"</div>").html();
                    link = $("<div>"+jsonData.responseData.feed.entries[i].link+"</div>").text();
                    
                    tc.append("<div class='titem'><a href='" + link + "'>" + title + "</a><p>" + content + "</p></div>");
                }
                refreshItems();
            } else {
                if (try_count < 3 ) {
                    //try again
                    setTimeout(function() {
                        apend_feeds(rss_url, try_count+1);
                    }, 3000);
                }
            }
        });
    };
    
    this.refresh = refreshItems;
    this.feeds = append_feeds;
    
    return this.each(function() {
        elId = this.id;
        tc = $('#' + elId);
        ti = $('#' + elId + ' .titem');
        
        opts = opts || {};
        opts.width = opts.width || '270px';
        opts.height = opts.height || '100px';
        opts.autoChangeTime = opts.autoChangeTime || 3000;
        opts.autoResumeTime = opts.autoResumeTime || 500;
        hideAnimTime = opts.hideAnimTime || 400;
        showAnimTime = opts.showAnimTime || 400;
        
        var changeText = function() {
            var elem = document.getElementById(elId);
            var curPos = elem.scrollTop;
            var h = parseInt(opts.height, 10);
            
            if (curPos >= elem.scrollHeight-h) {
                tc.scrollTop(0);
            } else {
                curPos = Math.floor(curPos/h) * h;
                tc.scrollTop(curPos+h);
            }
        };
        
        var autoChangeText = function() {
            changeInterval = setInterval(changeText, opts.autoChangeTime);
        };
        
        tc.css('width', opts.width);
        tc.css('height', opts.height);
        tc.css('overflow', 'hidden');
        tc.css('position', 'relative');
        tc.css('top', '0px');
        
        refreshItems();
        ti.css('opacity', '0');
        $(ti[0]).css('opacity', '1');
            
        tc.bind('scroll', function() {
            var curPos = document.getElementById(elId).scrollTop;
            var curHeight = parseInt($(ti[curItem]).css('height'), 10);
            var itemH = parseInt(opts.height, 10);
            itemH = itemH - (itemH/10);
            
            if (curPos > (curItem*itemH) + curHeight/2.0 ) {
                $(ti[curItem]).animate({'opacity':'0'}, hideAnimTime);
                curItem = (curItem+1) % itemCount;
                
                if (curItem != 0)
                    $(ti[curItem]).animate({'opacity':'1'}, showAnimTime);
            }
            
            if (curPos < (curItem*itemH) - curHeight/2.0 ) {
                $(ti[curItem]).animate({'opacity':'0'}, hideAnimTime);
                
                if (curItem == (itemCount - 1) && curPos < itemH ) {
                    curItem = (curItem+1) % itemCount;
                    $(ti[curItem]).animate({'opacity':'1'}, showAnimTime);
                } else if (curItem-1 >= 0) {
                    curItem = (curItem-1) % itemCount;
                    $(ti[curItem]).animate({'opacity':'1'}, showAnimTime);
                }
            }
        });
        
        /* Stop auto scrolling, when mouse is over */
        tc.mouseover(function() {
            clearInterval(changeInterval);
            clearTimeout(resumeTimer);
        });
        
        /* Resume auto scrolling, when mouse is out */
        tc.mouseout(function() {
            resumeTimer = setTimeout(function() {
                autoChangeText();
            }, opts.autoResumeTime);
        });
        
        autoChangeText();
    });
}
