var BackgroundSizeFix = function (element) {

    var _backgroundFix = false;
    var _fixDiv = null;
    var _currentImage = null;
    var _element = element;
    var _originalImageAR = null;
    var _imageLoaded = false;
    var _image = null;

    var _getDocHeight = function(){
	    return Math.max(
	            $(document).height(),
	            $(window).height(),
	            /* For opera: */
	            document.documentElement.clientHeight
	        );
    };

    var _preloadImage = function() {
    	_imageLoaded = false;
		var image = new Image();
		image.src = _currentImage;
		if(image.complete) {
			_showImage();
			_resizeImage();
		} else {
			image.onload = function() {
				_showImage();
				_resizeImage();
			};
		}
	};

    var _hasCssProperty = function (prop) {
        var div = document.createElement('div');
        var vendors = 'Khtml Ms O Moz Webkit'.split(' ');
        var len = vendors.length;
        if (prop in div.style) return true;
        prop = prop.replace(/^[a-z]/, function (val) {
            return val.toUpperCase();
        });
        while (len--) {
            if (vendors[len] + prop in div.style) {
                return true;
            }
        }
        return false;
    };

    var _getImageFromElement = function(elem) {
    	var backgroundImage = $(elem).css("backgroundImage") || $(elem).css("background-image");
        backgroundImage = backgroundImage.substr(5);
        return backgroundImage.substr(0, backgroundImage.indexOf("\""));
    };

    var _createStructure = function () {
        _currentImage = _getImageFromElement(element);
        _fixDiv = document.createElement('div');
        _fixDiv.style.width = "100%";
        _fixDiv.style.height = "100%";
        _fixDiv.style.top = 0;
        _fixDiv.style.left = 0;
        _fixDiv.style.position = "fixed";
        _fixDiv.style.zIndex = "-1";
        _fixDiv.className = "backgroundSize";
        var image = document.createElement("img");
        image.style.visibility = "hidden";
        image.style.position = "absolute";
        image.style.top = "0";
        image.src = _currentImage;
        _fixDiv.appendChild(image);


        //alert($(_fixDiv).children().length);
        $(_element).prepend(_fixDiv);
    };

    var _showImage = function() {
    	_image = $("img", _fixDiv)[0];

    	if(_originalImageAR == null) {

    		_originalImageAR = _image.width / _image.height;
    	}
    };

    var _resizeImage = function () {
    	//return;
        try {
        	var win = {
        		height : $(window).height(),
				width : $(window).width()
			};

        	// The current aspect ratio of the window
        	var winAR = win.width / win.height;

        	// Determine if we need to show the image and whether it needs to stretch tall or wide

        	if (!(win.width < _image.width && win.height >= _image.height) && !(winAR < _originalImageAR) && 
        			win.width >= _image.width) {
        		$(_image).css({
                    "left": "0",
                    "width" : "100%",
                    "height": "auto"
                });
        	} else {
        		$(_image).css({
                    "width" : "auto",
                    "height": "100%"
                });

        		// Center the image
        		$(_image).css('left', Math.min(((win.width - _image.width) / 2), 0));
        	}


        	if(!_imageLoaded) {
        		$(_image).css("visibility", "visible");
        		_imageLoaded = true;
        	}

        } catch (e) {
            alert(e)
        }
    };
    (function () {
        if (!_hasCssProperty("BackgroundSize") && navigator.appName != "Netscape") {

            _backgroundFix = true;
            _createStructure();
            _element.style.background = "none";
            _showImage();
            _resizeImage();
            
            // IE desperate bugfix
            setTimeout(function() {		
		_originalImageAR = null;
            	_showImage();
                _resizeImage();
            }, 2000);
            
            $(window).resize(function() {
	                _resizeImage();
	        });
        }
    })();
    return {
        "isBackgroundFix": function () {
            return _backgroundFix;
        },
        "getCurrentImage": function () {
            return _currentImage;
        },
        "getFixDiv": function () {
            return _fixDiv;
        },
        "setImage": function (imageSrc) {
        	if(typeof imageSrc == "object") {
        		imageSrc = _getImageFromElement(imageSrc);
        	}

        	_currentImage = imageSrc;
            if (_backgroundFix) {
                $(_image).attr("src", imageSrc);
                //_resizeImage();
            } else {
            	_imageLoaded = true;
                $(_element).css("background-image", "url('" + imageSrc + "')");
            }
        },
        "isLoaded": function() {
        	return _imageLoaded;
        }
    };
};
var SwapBackgrounds = function(options) {

	var _items = options.elements || []; // Elements to play with
	var _ids = options.ids || []; // Available classes with concrete backgrounds
	var _timeOut = options.timeOut || 4000;
	var _fadeTime = options.fadeTime || 1200;
	var _onSwap = options.onSwap || null;

	var _backgroundFixes = [];
	var _currentInterval = null;
	var _animating = false;
	var _isFirstVisible = true;
	var _currentId = 0;
	var _goTo = -1;
	var _forceReset = false;

	var _getNextId = function() {
		if(_forceReset) {
			return 0;
		}
		var next = _currentId + 1;
		if(next == _ids.length) return 0;
		return next;
	}

	var _loadBackgroundFix = function(elem, index) {
		if(!_backgroundFixes[index]) {
			_backgroundFixes[index] = BackgroundSizeFix(elem);
		}
	};

	var loadIdOnElem = function(elemIndex, id) {
		if(id) {
			var elem = $(_items[elemIndex]);
			elem.attr("id", id)
			    .removeAttr("style")
			    .css({
				    "z-index": 0,
				    "display": "block"
			    });

			if(_backgroundFixes[elemIndex].isBackgroundFix()) {
				_backgroundFixes[elemIndex].setImage(elem);
			}
		}
	};

	var _onFade = function() {
		var currentIdName = _ids[_currentId];

		// update _currentId
		if ( _goTo == -1 ){
			_currentId =  _getNextId();
		}
		else{
			_currentId = _goTo;
			_goTo = -1;
		}

		var nextIdName = _ids[ _currentId ];

		//if(currentIdName == nextIdName) debugger;

		// Change first id to second and make first element visible
		$(_items[1]).attr("id", nextIdName);

		if(_backgroundFixes[0].isBackgroundFix()) {
			var firstImage = _backgroundFixes[0].getCurrentImage();
			_backgroundFixes[1].setImage(firstImage);
		}

		$(_items[1]).show();

		// Load next image on second div

		if(_forceReset) _forceReset = false;
		currentIdName = _ids[_currentId];
		nextIdName = _ids[_getNextId()];
		loadIdOnElem(0, nextIdName);

		if(_onSwap) {
			_onSwap( _currentId );
		}

		_animating = false;
	};

	var _changeBackground = function() {

		// evaluate _goTo var
		if( _goTo != -1 && _goTo > _ids.length-1 ){
			_goTo = -1;
			throw 'The index is grather than the number of backgrounds';
		}

		if(!_animating) {
			_animating = true;
			// Not animate if image is not loaded!!
			if(_backgroundFixes[0].isBackgroundFix() && !_backgroundFixes[0].isLoaded()) {
				_animating = false;
				return;
			}

			if ( $.browser.msie ) {
				$(_items[1]).hide(0, _onFade);
			} else {
				$(_items[1]).fadeOut(_fadeTime, _onFade);
			}

		}
	};

	var _startInterval = function() {
		if(_ids.length > 1) {
			_currentInterval = setInterval(_changeBackground, _timeOut);
		}
	};

	var _stopInterval = function() {
		clearInterval(_currentInterval);
	};

	var _changeIds = function(newIds, forceChange) {
		_stopInterval();

		_ids = newIds;
		_forceReset = true;

		loadIdOnElem(0, _ids[0]);
		if(forceChange) {
			_changeBackground();
		}
		//debugger;
		_startInterval();
	};

	var _swapTo = function( id ) {

		if( id > _ids.length-1 ) throw 'The index is grather than the number of backgrounds';

		// stop swapping
		_stopInterval();
		if( _animating ) {
			$(_items[0]).stop( true, true );
			$(_items[1]).stop( true, true );
		}

		// load image to swap
		loadIdOnElem(0, _ids[id]);

		// change background
		_goTo = id;
		_changeBackground();

		// restart
		_startInterval();
	};

	(function() {
		var i = 0;
		if(_items.length != 2 ) throw "This plugin only works with 2 elements!";
		_items.css("z-index", "0") // Reset z-index so last element is first to be shown
			  .each(function() {
				  _loadBackgroundFix(this, i);
				  ++i;
			  });
		_items.css("visibility","visible");

		// Start interval
		_startInterval();
	})();

	return {
		start: _startInterval,
		stop : _stopInterval,
		changeIds : _changeIds,
		swapTo: _swapTo
	};
};
/***
 * HACK min-height BUG on IE for #main element
 * You must define the 'height' as the min-height in pixels for #main element
 */
var MinHeightFix = function ( height ) {
    (function () {
		if( $.browser.msie ) {
			$(window).resize( function() {
				if( $(window).height() < height ) 	$('#main').css('height', height+'px');
				else								$('#main').css('height', '100%');
			});
			if( $(window).height() < height ) 		$('#main').css('height', height+'px');
		}
    })();
};
