/*
 * jQuery Backstretch
 * Version 1.1.2
 * http://srobbin.com/jquery-plugins/jquery-backstretch/
 *
 * Add a dynamically-resized background image to the page
 *
 * Copyright (c) 2010 Scott Robbin (srobbin.com)
 * Dual licensed under the MIT and GPL licenses.
*/
Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

(function($) {
    $.backstretch = function(options, callback) {
        var base = this;
        var settings = {
            centeredX: true,     // Should we center the image on the X axis?
            centeredY: true,     // Should we center the image on the Y axis?
            speed: 800,          // fadeIn speed for background after image loads
            duration: 10000
        },
        rootElement = ("onorientationchange" in window) ? $(document) : $(window), // hack to acccount for iOS position:fixed shortcomings
        bgWidth, bgHeight, bgOffset, bgCSS, container, bgTimeout, navimages,
        bgId = 0;
        if (options == 'reload')
          return base._reload();
        
        // Extend the settings with those the user has provided
        if(options && typeof options == "object")
            $.extend(settings, options);
    
        // Initialize
        base._init = function() {            
            container = $("<div />").attr("id", "backstretch");
            // add reference
            container.data('backstretch', base);
            navimages = $("#navimages ul");
            $('<li><a class="recharge"></a></li>')
            .bind("click", function(e){
              base._loadImg();
            })
            .appendTo(navimages);
            
	    $(".dmcblocc").live("click", function(){
              base._loadImg($(this).attr('id').split('_')[1]);
            })

            $("body").prepend(container);
            base._loadImg();
            // Adjust the background size when the window is resized or orientation has changed (iOS)
            $(window).resize(base._adjustBG);
        }
        base._reload = function() {
          clearTimeout(base.bgTimeout);
          bgId = 0;
          $("#backstretch").html('');
          $("#navimages ul li:gt(0)").remove();
          base._loadImg();
        }
            
        base._loadImg = function(id) {
          if (toplevel_oid == undefined || bgImgs[toplevel_oid] == undefined || !Object.size(bgImgs[toplevel_oid]) || container == undefined)
              return false;
          clearTimeout(base.bgTimeout);
          if (id == undefined)  {
            id = bgId;
            base.bgTimeout = setTimeout(function(){
                base._loadImg();
            }, settings.duration);
            bgId = bgId == Object.size(bgImgs[toplevel_oid]) -1 ? 0 : bgId +1;
          }
          src = bgImgs[toplevel_oid][id];
          if (!container.find("#bgimg_" + id).length) {
            img = $("<img />")
                .attr('id', "bgimg_" + id)
                .css({position: "fixed",  opacity: 0.01, zIndex: -9998})
                .bind("load", function(e) {
                    var self = $(this);

                    setTimeout(function(){
                      base._adjustBG(function() {
                        container.find("img[id!='bgimg_"+id+"']").animate({opacity: '0.25', zIndex: '-9999'}, settings.speed);
                        self.animate({opacity: 1, zIndex: '-9998'}, settings.speed);
                      });
                    },10);
                })
                .appendTo(container);
            img.attr("src", src); // Hack for IE img onload event
            // add nav link
            navimages.find(".dmcblocc").removeClass('current');
            $('<li><a class="dmcblocc current" id="bg_'+id+'"></a></li>')
            .appendTo(navimages);
          } else {
            container.find("#bgimg_" + id).animate({opacity:1, zIndex:'-9998'}, settings.speed);
            container.find("img[id!='bgimg_"+id+"']").animate({opacity:'0.25', zIndex:'-9999'}, settings.speed);
            navimages.find(".dmcblocc").removeClass('current');
            navimages.find("#bg_"+id).addClass('current');
          }
        }

        base._adjustBG = function(fn) {
          try {
            container.find("img").each(function(i, elt) {
              
                bgCSS = {left: 0, top: 0}
                bgWidth = rootElement.width();
                imgRatio = this.width / this.height,
                bgHeight = bgWidth / imgRatio;

                // Make adjustments based on image ratio
                // Note: Offset code provided by Peter Baker (http://ptrbkr.com/). Thanks, Peter!
                if(bgHeight >= rootElement.height()) {
                    bgOffset = (bgHeight - rootElement.height()) /2;
                    if(settings.centeredY) $.extend(bgCSS, {top: "-" + bgOffset + "px"});
                } else {
                    bgHeight = rootElement.height();
                    bgWidth = bgHeight * imgRatio;
                    bgOffset = (bgWidth - rootElement.width()) / 2;
                    if(settings.centeredX) $.extend(bgCSS, {left: "-" + bgOffset + "px"});
                }

                $(elt).width( bgWidth ).height( bgHeight ).css(bgCSS);
            });
          } catch(err) {
              // IE7 seems to trigger _adjustBG before the image is loaded.
              // This try/catch block is a hack to let it fail gracefully.
          }

          // Executed the passed in function, if necessary
          if (typeof fn == "function") fn();
        }
        $(document).ready(function(){
          base._init();
        });
        
        // For chaining
        return this;
        
    };
  
})(jQuery);
