﻿/*
*   dependencies: 'utility.js'
*   description: $('div').onScreen().
*
*/

//You need an anonymous function to wrap around your function to avoid conflict  
(function ($) {

    $.isOnScreen = function (element) {
        var el = $(element);
        var elOffset = el.viewportOffset();
        var win = $(window);
        if (Math.abs(elOffset.top) > win.height() || Math.abs(elOffset.left) > win.width()) {
            return false;
        }
        if(elOffset.top + el.height() < 0)
    	{
        	//this fixes a bug where if an element has elements within that are being relatively positioned
        	return false;
    	}
        if (elOffset.top + elOffset.left >= 0 || elOffset.top + el.height() >= 0 || elOffset.left + el.width() >= 0) {
            return true;
        }
        return false;
    }

    //Attach this new method to jQuery  
    $.fn.extend({
        //This is where you write your plugin's name  
        onScreen: function () {
            //Iterate over the current set of matched elements  
            return this.filter(function () {
                if (!$.isOnScreen(this)) return false;
                return true;
            });
        },
        offScreen: function () {
            //Iterate over the current set of matched elements  
            return this.filter(function () {
                if (!$.isOnScreen(this)) return true;
                return false;
            });
        },
        viewportOffset: function () {
            var offset = $(this).offset();
            var win = $(window);
            return {
                left: offset.left - win.scrollLeft(),
                top: offset.top - win.scrollTop()
            }
        }
    });

    //pass jQuery to the function,   
    //So that we will able to use any valid Javascript variable name   
    //to replace "$" SIGN. But, we'll stick to $ (I like dollar sign. )         
})(jQuery);  

