/**
* jQuery plugin: Lazy Image Loader
* version: 3.0
* Author: Vivek Pohre,Shon Thomas
* Website: (http://www.vivekpohre.com)
* Example: call lzload() at or after document ready
*/

function lzload() {
    var w = window, adv = 30, vph, tmpLD, nowView, collImg, imgTop, scrTop, ci;
    function getVPH() {
        //DETERMINE WINDOW VIEWPORT HEIGHT ALWAYS TO AVOID RESIZING BROWSER ERROR
        if (typeof (vph = w.innerHeight ? w.innerHeight : $(w).innerHeight()) != "Number")
            vph = document.documentElement.clientHeight;
    };

    //SAVE THE Y AXIS IN TOP ATTRIB
    getVPH(); //GET THE VIEWPORT HEIGHT
    imgTop = 0; //INIT IMGTOP TO ZERO--TEMP VAR
    collImg = $("img").filter(':[longdesc]'); //COLLECT ALL IMAGES HAVING longdesc ATTR
    collImg.each(function () {
        imgTop = $(this).offset().top;
        $(this).attr("top", imgTop);
    });
    $(w).bind("scroll", function () { loadImgs() }).bind("resize", function () { getVPH(); loadImgs() }); //ATTACH SCROLL & RESIZE EVENT TO WINDOW
    $.loadImgs = loadImgs = function (imgSet) {//MAKE loadImgs FUNCTION PUBLIC
        ci = (imgSet) ? imgSet.show() : collImg; //DECIDE COLLECTION FROM PASSED OR ALL DOM IMAGES
        scrTop = $(w).scrollTop();
        //DETERMINE THE Y-AXIS IN THE VIEWABLE AREA
        nowView = (scrTop + vph + adv);
        ci.filter(':[longdesc]').filter(':visible').each(function (i) {
            if ($(this).attr("top") < nowView) {
                tmpLD = $(this).attr("longdesc");
                if (typeof tmpLD != 'undefined')
                    $(this).attr("src", tmpLD)[0].removeAttribute("longdesc", 0);
            }
        });
        ci = collImg;
    };
    loadImgs();
    $("img").error(function () {
        $(this).attr("src", "http://www.optoma.co.uk/uploads/pressimages/blank.jpg");
    });
}
