/*******************************************************************************
** Constants                                                                  **
*******************************************************************************/

openc.BANNER_IMAGE_INTERVAL = 5000;




/*******************************************************************************
** BannerFlash class	                                                      **
*******************************************************************************/

/**
 * This class is instantiated by openc.registerObject, the first time an object
 * asks to be registered against a specific DOM object with this class. Any 
 * number of objects may subsequently be registered. The final object will have 
 * an isLast boolean of true.
 *
 * @param target - the DOM object this class has been instantiated for
*/
openc.BannerFlash = function(target) {

	this.items = new Array();
	this.target = target;

}


/**
 * Called when the last item is added, render a random choice in place of the 
 * banner image
*/
openc.BannerFlash.prototype.renderRandomItem = function() {
	
	// Pick an item at random
	var obj = this.items[Math.round((this.items.length-1) * Math.random())];

	// If the required version of flash is not available
	if(!swfobject.hasFlashPlayerVersion(obj.version)) {
		return;
	}
	
	var movie = obj.src + '/download'; //'http://dev.open/butterfly.swf';//
	
	// Render the flash banner in place of the BannerImage inside the target
	swfobject.embedSWF(
		movie,
		this.target.attr('id'),
		obj.width,
		obj.height,
		/* TODO - GET VERSION FROM OBJECT - IMPORTANT!!!! */
		obj.version,
		{},
		{},
		{wmode:'transparent'}
	)
}



/**
 * Called by openc.registerObject, a new object is added as an item to this 
 * instance
*/
openc.BannerFlash.prototype.append = function(obj) {

	
	// Add to the collection
	this.items.push(obj);
	
	// If this is the last item
	if(obj.isLast) {
		this.renderRandomItem();
	}
}

/*******************************************************************************
** BannerImage class                                                          **
*******************************************************************************/

/**
 * This class is instantiated by openc.registerObject, the first time an object
 * asks to be registered against a specific DOM object with this class. Any 
 * number of objects may subsequently be registered.
 *
 * @param target - the DOM object this class has been instantiated for
*/

openc.BannerImage = function(target) {
	this.target = target;
	this.items = new Array();
	this.visibleItemIndex = 0;
	this.imageCache = new Array();
	this.linkTo = '';
	this.existingHasLoaded = false;
	
	// Find the mask and image
	var existing = target.find("div.mask, img");
	// Add a handler to the image, nothing should start until it's loaded
	var closeBannerImage = this;
	existing.load(function(){
		closeBannerImage.existingHasLoaded = true;
	})
	// Make them the first children in the div, this will unwrap them if needed
	target.prepend(existing);
	
	// Stack the stacking for the mask and first image (assume max 100 images)
	target.find("div.mask").css("z-index",101);
	target.find("img").css("z-index",100);
	
	// Get a reference to the href (if any)
	var href = target.find("a").attr("href");
	// If there is an href
	if(href != undefined) {
		this.setLinkTo(href);
		target.find("img").attr("alt",href).attr("title",href);
	}
	// Set click handler
	var bannerImage = this;
	this.target.click(
		function() {
			bannerImage.onClick();
		}
	);
	
	// Add image as the first child of the items collection
	this.items.push(
		new openc.BannerImageItem(this, target.find("img"),href)
	);
	
	this.timer = setInterval(this.getNextTickerItteration(this), openc.BANNER_IMAGE_INTERVAL);
	
}


/*******************************************************************************
** BannerImage class methods                                                  **
*******************************************************************************/

/**
 * setLinkTo makes the entire div a link to the url specified
*/
openc.BannerImage.prototype.setLinkTo = function(url) {
	this.linkTo = url;
	this.target.css("cursor","pointer");
}

/**
 * Remove link returns the entire div to inactive
*/
openc.BannerImage.prototype.removeLinkTo = function() {
	this.linkTo = '';
	this.target.css("cursor","default");
	this.target.removeAttr("title");

}

/**
 * onClick is called when the div is clicked
*/
openc.BannerImage.prototype.onClick = function() {
	if(this.linkTo.length > 0) {
		window.location.href = this.linkTo;
	}
}

/**
 * Return a closed function for setInterval
*/
openc.BannerImage.prototype.getNextTickerItteration = function(bannerImage) {
	return function() {
	
		// If the existing image has not loaded - return
		if(!bannerImage.existingHasLoaded) {
			return;
		}
	
		var nextItemIndex = bannerImage.visibleItemIndex + 1;
		
		// While the next image does not exist, or exists and is not loaded
		while(!(bannerImage.items[nextItemIndex] && bannerImage.items[nextItemIndex].imgLoaded)) {
			// Incremembet the next item index through stack
			nextItemIndex = nextItemIndex == bannerImage.items.length ? 0 : bannerImage.visibleItemIndex + 1;
		}
		
		// Prepare the next image
		bannerImage.items[nextItemIndex].onBeforeReveal();
		
		// Fade out current visible
		bannerImage.items[bannerImage.visibleItemIndex].fadeOutOver(bannerImage.items[nextItemIndex]);
		
		// Set current visible to revealed image
		bannerImage.visibleItemIndex = nextItemIndex;
		
		//jq('body').prepend('<p>' + nextItemIndex +  '</p>');
		
	}
}

/**
 * Append a new image to the banner
*/
openc.BannerImage.prototype.append = function(obj) {

	// Create new element
	var img = jq('<img style="z-index:1" src="' + obj.src + '" width="' + obj.width + '" height="' + obj.height + '" alt="' + (obj.link != '' ? obj.link : obj.alt) + '" title="' + (obj.link != '' ? obj.link : obj.alt) + '"/>');
	// Add it to the main div
	this.target.append(img);

	// Sort out reference to link (if any)
	var href = (obj.link.length > 0) ? obj.link : undefined;
	
	// Add image as the next child of the items collection
	this.items.push(
		new openc.BannerImageItem(this, img, href)
	);
	
}




/*******************************************************************************
** BannerImageItem class                                                      **
*******************************************************************************/

openc.BannerImageItem = function(parent, img, link) {
	this.parent = parent;
	this.img = img;
	this.link = link || '';
	this.imgLoaded = false;
	
	// Cache the image
	var src = img.attr("src");
	var cache = new Image();
	parent.imageCache.push(cache);
	// Create a reference for closure
	var bannerImageItem = this;
	cache.onload = function(){
		// When the cache is filled, set this instances imgLoaded to true
		bannerImageItem.imgLoaded = true;
	};
	// Start loading
	cache.src = img.attr("src");
	
}

/*******************************************************************************
** BannerImageItem class  methods                                             **
*******************************************************************************/

/**
 * Called before the item is revealed by the top item fading out
*/
openc.BannerImageItem.prototype.onBeforeReveal = function() {

	// Place directly underneath the top image
	this.img.css("z-index",99);
}

/**
 * Fade out over the top of the item underneath. Responsible for calling methods
 * of this item and the revealed item when finished.
*/
openc.BannerImageItem.prototype.fadeOutOver = function(itemUnderneath) {

	// Place directly underneath the top image
	var bannerImageItem = this;
	// Close a calls to after fade/reveal methods
	var closure = function() {
		bannerImageItem.onAfterFadeOutOver();
		itemUnderneath.onAfterReveal();
	}
	// Fade out and then call after fade out
	this.img.animate({opacity:0}, 2000, closure);
}

/**
 * Called by BannerImageItem.fadeOutOver, tidy up item when faded out
*/
openc.BannerImageItem.prototype.onAfterFadeOutOver = function() {

	// Put at bottom of stack and set opacity to full (but not totally full, 
	// firefox has issues)
	this.img.css("z-index",1)
	this.img.css('opacity',0.99);
}

/**
 * Called by BannerImageItem.fadeOutOver, tidy up item when revealed
*/
openc.BannerImageItem.prototype.onAfterReveal = function() {

	// Place at top of stack
	this.img.css("z-index",100)
	
	// if this has a link
	if(this.link != '') {
		this.parent.setLinkTo(this.link);
	} else {
		this.parent.removeLinkTo();
	}
}






















