/*!
 * To JavaScript Library v1.4.3
 * Depends on the jquery plugin jquery.timer.0.1.0
 *
 * Copyright 2011, Colin Duivis
 *
 * (Plugin for jquery)
 * 
 * Description: 
 * 
 * Version: 0.4
 *
 * Date: Wen Jan 12 12:00:30 2011 -0100
 */
 
(function($){	
	//set the default options
	var defaults = {
			images : [{"name":"no object array set","image":"your/image/path.img"}],
			timeStep : 1000, // refresh speed in milliseconds
			changesInMinute : 4, 
			changeSpeed : 2, // seconds
			altName : 'name',
			imageUrl : 'image',
			autoAnimate : true,
			fillScreen : true,
			randomised : true,
			checkWindowResize: true
		};

    //array containing P classes/elements per item
	if (typeof Privates=="undefined")
    {
    	var Privates = new Array();
    }
	
	// creates a new private container per element
	var P = function(elem) {
        return new Private(elem);
    };
    // creates a private container for the element
    var Private = function(elem) {
        this.elem = jQuery(elem);
    };
    //container of private vars and methods
    Private.prototype = {
    	elem: null,
    	_key: null,
    	_numImages: null,//calculated vars
    	_bgDuration: null,
    	_name: null,
    	_image: null,
    	_iWidth: 0,//preset vars
    	_iHeight: 0,
    	_curImage: -1,
    	_first: true,
    	_options: defaults,
        initImg: function( dateObj ) {
        	if(this._options.randomised){
    			//to calculate when the time is near a treshhold of the
    			var sec = Math.floor(dateObj.getSeconds() / this._bgDuration) * this._bgDuration; 
    			this.setRandomImg(dateObj, sec);
    		} else {
    			this.setImg(++this._curImage);
    		}
            //return this;
        },
        setRandomImg: function( dateObj, sec ) {
        	var randomTime = sec + dateObj.getMinutes() + dateObj.getHours() + dateObj.getDate() + dateObj.getMonth() + dateObj.getFullYear();
    		var imgNum = randomTime % this._numImages;
    		if(imgNum == this._curImage)
    			imgNum++;
    		this.setImg(imgNum);
            //return this;
        },
        setImg: function( imgNum ) {
        	if(this._first){
    			if(imgNum < 0)
    				imgNum = this._numImages-1;
    			else
    				imgNum = imgNum % this._numImages;
    			this._curImage = imgNum;
    			//add the image to the bg-painting. the image contains the onload function, for some reason this works better then the jQuery onload.
    			this.elem.html('<img src="' + eval('this._options.images[imgNum].'+this._image) + '" alt="' + eval('this._options.images[imgNum].'+this._name) + '" onload=" $(this).parent().scaledImageSwap(\'setImageSize\',\''+this._key+'\') "/>');
    			this._first = false;
    		}else{
    			var priv = this;
    			this.elem.children('img').fadeTo(priv._options.changeSpeed/2*1000,0, function(){
    				if(imgNum < 0)
    					imgNum = priv._numImages-1;
    				else
    					imgNum = imgNum % priv._numImages;
    				priv._curImage = imgNum;
    				//add the image to the bg-painting. the image contains the onload function, for some reason this works better then the jQuery onload.
    				priv.elem.html('<img src="' + eval('priv._options.images[imgNum].'+priv._image) + '" alt="' + eval('priv._options.images[imgNum].'+priv._name) + '" onload=" $(this).parent().scaledImageSwap(\'setImageSize\',\''+priv._key+'\') "/>');
    				priv.elem.children('img').fadeTo(0,0);
    			});
    		}
            //return this;
        },
        setImgSize: function() {
        	this._iWidth = this.elem.children('img').width();
        	this._iHeight = this.elem.children('img').height();
        	this.calcSize();
            //return this;
        },
        calcSize: function() {
        	if(this._options.fillScreen)
        		this.calcSpreadBg();
    		else
    			this.calcFittingBg();
            //return this;
        },
        calcSpreadBg: function() {
        	var oWidth = this.elem.width();
    		var oHeight = this.elem.height();
    		
    		var oRatio = oWidth / oHeight;
    		var iRatio = this._iWidth / this._iHeight;
    		
    		var oTop = this.elem.offset().top;
    		var oLeft = this.elem.offset().left;
    		
    		if(oRatio > iRatio)
    		{
    			calcHeight = oWidth / this._iWidth * this._iHeight;
    			calcTop = ((oHeight - calcHeight) / 2) + oTop;
    			this.elem.children('img').css('width','100%').css('height',calcHeight+'px').offset({top: calcTop, left: oLeft});
    		}
    		else
    		{
    			calcWidth = oHeight / this._iHeight * this._iWidth;
    			calcLeft = ((oWidth - calcWidth) / 2) + oLeft;
    			this.elem.children('img').css('height','100%').css('width',calcWidth+'px').offset({top: oTop, left: calcLeft});
    		}
            //return this;
        },
        calcFittingBg: function() {
        	var oWidth = this.elem.width();
    		var oHeight = this.elem.height();
    		
    		var oRatio = oWidth / oHeight;
    		var iRatio = this._iWidth / this._iHeight;
    		
    		var oTop = this.elem.offset().top;
    		var oLeft = this.elem.offset().left;
    		
    		if(oRatio < iRatio)
    		{
    			calcHeight = oWidth / this._iWidth * this._iHeight;
    			calcTop = ((oHeight - calcHeight) / 2) + oTop;
    			this.elem.children('img').css('width','100%').css('height',calcHeight+'px').offset({top:calcTop, left:oLeft});
    		}
    		else
    		{
    			calcWidth = oHeight / this._iHeight * this._iWidth;
    			calcLeft = ((oWidth - calcWidth) / 2) + oLeft;
    			this.elem.children('img').css('height','100%').css('width',calcWidth+'px').offset({top:oTop, left:calcLeft});
    		}
            //return this;
        }
    };
    
	$.fn.scaledImageSwap = function( method ) {		
		// Method calling logic
		if ( methods[method] ) {
			return methods[ method ].apply( $(this), Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( $(this), arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
		}
	};
	
	var methods = {
		init: function( options ) {
			
			//options = $.extend(defaults, options);
			
			// get a new Private settins for this object
			var privates = P(this);
			
			privates._key = $(this).selector;
			//set the this as a key and bind the privates to it
			Privates[privates._key] = privates;
			$(this).data('privates', privates);
			
			privates._options = $.extend(defaults, options);
			
			//calculated vars
			privates._numImages = privates._options.images.length;
			privates._bgDuration = Math.round(60 / privates._options.changesInMinute);
			privates._name = privates._options.altName;
			privates._image = privates._options.imageUrl;
			
				
			privates.initImg(new Date());
							
			$.timer(privates._options.timeStep, function(timer){
				if(privates._options.autoAnimate){
					var now = new Date();
					var sec = now.getSeconds();
					if(sec % privates._bgDuration == privates._bgDuration - Math.round(privates._options.changeSpeed / 2))
					{
						if(privates._options.randomised)
							privates.setRandomImg(now,sec);
						else
							privates.setImg(++privates._curImage);
					}
				}else{
					//timer.stop();
				}
			});
			if(privates._options.checkWindowResize)
			{
				$(window).resize(function(){
					privates.calcSize();	
				});
			}
			return this;
		},
		toggleRatio: function( key ) {
			//get the private data
			var privates = Privates[key];
			
			privates._options.fillScreen = !privates._options.fillScreen;
			privates.setImgSize();
		},
		setImageSize: function ( key ){
			//get the private data
			var privates = Privates[key];
			
			privates.setImgSize();
			this.children('img').css('display','block');
			this.children('img').fadeTo(privates._options.changeSpeed/2*1000,1);
		},
		nextImage: function( key ) {
			//get the private data
			var privates = Privates[key];
			
			privates.setImg(++privates._curImage);
		},
		prevImage: function( key ) {
			//get the private data
			var privates = Privates[key];
			
			privates.setImg(--privates._curImage);
		},
		setImageById: function( key, id ) {
			//get the private data
			var privates = Privates[key];
			
			privates.setImg(id);
		}
	};
	
})(jQuery);
