var BrandRibbon = (function () {
	
	var starttimer, frameinterval, ribboninterval, 
		showing = 0, toshow = 0, numframes = 1, 
		framelooping = false, frameshowing = 0, ribbons = [], logos = [], $container;
	
	var options = {
		logosPerRibbon: 5
	};
	
	var animations = {
		next: {
			setup: {left: "760px", opacity: 0},
			show: {left: "0px", height: "100%", top: "0%", opacity: 1},
			hide: {left: "-760px", opacity: 0}
		},
		
		previous: {
			setup: {left: "-760px", opacity: 0},
			show: {left: "0px", height: "100%", top: "0%", opacity: 1},
			hide: {left: "760px", opacity: 0}
		}
	};
	
	if (!$.browser.safari) { // safari isn't handling the top/height animations correctly
		animations.next.setup.height = "0%";
		animations.next.setup.top = "40%";
		animations.previous.setup.height = "0%";
		animations.previous.setup.top = "40%";
		animations.next.hide.height = "0%";
		animations.next.hide.top = "40%";
		animations.previous.hide.height = "0%";
		animations.previous.hide.top = "40%";
	}
	
	function changeRibbon(event, auto) {
		if (ribbons.length < 2) { // there's only one ribbon!
			return false;
		}
		
		if (auto && ribboninterval !== -1) {
			BrandRibbon.animation = window.setInterval(next, ribboninterval);
			return false;
		}
		
		if (event) {
			var mouseX = event.offsetX || event.layerX;
			if (mouseX < 380) {
				previous();
			} else {
				next();
			}
		}
	};
	
	function changeFrame() {
		if (framelooping || frameshowing < numframes - 1) {
			var next = (frameshowing < numframes - 1) ? frameshowing + 1 : 0;
			var $nextframe = $("img:eq(" + next + ")", $container);
			if ($nextframe[0].complete) {
				$("img:eq(" + frameshowing + ")", $container).fadeTo(800, 0);
				frameshowing = next;
				$nextframe.fadeTo(800, 1);
				window.setTimeout(changeFrame, frameinterval);
			} else { // wait for next frame to load
				window.setTimeout(changeFrame, 200);
			}
		}
	};
	
	function next() {
		toshow = (showing + 1 == ribbons.length) ? 0 : showing + 1;
		animate(animations.next);
	};
	
	function previous() {
		toshow = (showing - 1 < 0) ? ribbons.length - 1 : showing - 1;
		animate(animations.previous);
	};
	
	function animate(animation) {
		Callout.hide();
		ribbons[toshow].animate(animation.setup, 1, "", function () {
			ribbons[showing].animate(animation.hide, 800, "swing");
			ribbons[toshow].animate(animation.show, 800, "swing", function () {
				showing = toshow;
				Callout.hide();
			});
		});
	};
	
	function start() {
		var ready = true, $img = $("img:first", $container);
		
		$.each(logos, function () {
			if (this.el[0].complete === false) {
				ready = false;
			}
		});
		
		if ($img[0].complete && ready) {
			window.clearTimeout(starttimer);
			ribbons[showing].css({left: "0px", height: "100%", top: "0%"});
			$("#loading").fadeTo(600, 0, function () {
				$(this).hide();
			});
			$img.fadeTo(1000, 1);
			$container.fadeIn(1000, function () {
				changeRibbon(null, true);
				if (numframes > 1) {
					window.setTimeout(changeFrame, frameinterval);
				}
			});
		} else {
			starttimer = window.setTimeout(start, 200);
		}
	};
	
	return {
		init: function () {
			var that = this, ribbon = -1, stopAnimation, hideCallout;
			
			$.get("/servecontent.aspx?key=HomeBrandRibbon", function (data) {
			//$.get("brandribbon_source.html", function (data) { // use this for easier testing
				var $swf, $frames, $images;
				// show loading animation
				$("<div>")
					.appendTo("#splash")
					.attr("id", "loading")
					.html('<img src="/images/loading.gif" alt="" border="">');
					
				$container = $("<div>")
					.appendTo("#splash")
					.attr("id", "splash-inner")
					.hide();
					
				$swf = $("#swf", data);
				$frames = $("#frames", data);
				$images = $("#images img", data);
				if ($swf.size()) { // swf animation?
					var $img = $("img", $swf);
					$('<img/>').attr("src", $img.attr("url")).css("cursor", "pointer").appendTo($container).click(function () {
						if ($img.attr("target") === "_blank") {
							window.open($img.attr("link"));
						} else {
							location.href = $img.attr("link");
						}
					});
					var so = new SWFObject($swf.attr("url"), "intro", "820", "362", "9");
					so.addParam("wmode", "opaque");
					if (so.write($container.attr("id"))) {
						$("object, embed", $container).hover(function () {
								hideCallout = window.setTimeout(Callout.hide, 1000);
							},
							function () {
								window.clearTimeout(hideCallout);
							});
					}
				} else if ($frames.size()) { // multi-frame animation?
					framelooping = ($frames.attr("loop") === "true") ? true : false;
					frameinterval = parseInt($frames.attr("frameinterval"), 10) || 5000;
					$frames = $(".frame", $frames);
					numframes = $frames.size();
					
					$frames.each(function (i) {
						var url = $(this).attr("url");
						$images = $("img", this);
						var $img = $("<img>")
							.appendTo($container)
							.hover(function () {
									hideCallout = window.setTimeout(Callout.hide, 1000);
								},
								function () {
									window.clearTimeout(hideCallout);
								})
							.attr({src: $images.eq(Math.floor(Math.random() * $images.size())).attr("url"), border: 0, alt: ""})
							.css({opacity: 0, position: "absolute", top: 0, left: 0});
							
						if (url) {
							$img.click(function () {
								location.href = url;
							}).css({cursor: "pointer"});
						}
					});
					
				} else { // else, load a single random image
					$("<img>")
						.appendTo($container)
						.hover(function () {
								hideCallout = window.setTimeout(Callout.hide, 1000);
							},
							function () {
								window.clearTimeout(hideCallout);
							})
						.attr({src: $images.eq(Math.floor(Math.random() * $images.size())).attr("url"), border: 0, alt: ""})
						.css({opacity: 0});
				}
				
				// create brand ribbon containers and load the logos
				ribboninterval = parseInt($("#brands", data).attr("ribboninterval"), 10) || 5000;
				$("<div>")
					.appendTo($container)
					.attr("id", "brandribbon-wrapper");
				$("#brands div", data).each(function (i) {
					if(i == 0 || i % options.logosPerRibbon === 0) {
			  			ribbon += 1;
			  			ribbons[ribbon] = $("<div>")
			  				.appendTo("#brandribbon-wrapper")
			  				.addClass("brandribbon")
			  				.click(function (event) {
									window.clearTimeout(Callout.delay);
									window.clearInterval(BrandRibbon.animation);
									changeRibbon(event);
									event.preventDefault();
								})
							.hover(function () {
									stopAnimation = window.setTimeout(function () {
										window.clearInterval(BrandRibbon.animation);
									}, 250);
								},
								function () {
									window.clearTimeout(stopAnimation);
								});
			  		}

					var $this = $(this);
					logos[i] = new Logo(i - (options.logosPerRibbon * ribbon), options.logosPerRibbon - 1,  $this.attr("id"), $this.attr("logo"), $this.html(), $this.attr("url"), ribbons[ribbon], $container);
				});
				
				// remove prev/next stuff if only one ribbon
				if (ribbons.length == 1) {
					ribbons[0]
						.unbind("click")
						.unbind("hover")
						.css("background-image", "none");
				}
				
				start();
			});
			
		}
			    				
	};
	
}) (); // self-invoking!

function Logo(index, maxindex, id, logo, text, url, parent, grandparent) {
	this.id = "logo-" + id;
	this.logo = logo;
	this.url = url;
	this.container = parent;
	this.callout = new Callout(index, maxindex, "callout-" + id, text, url, grandparent);
	return this.create();
};

Logo.prototype.create = function () {
	var that = this;
	this.el = $("<img>")
		.appendTo(this.container)
		.hover(function () {
				var img = this;
				Callout.delay = window.setTimeout(function () {
					that.callout.el[0].style.left = img.offsetLeft + "px";
					Logo.stickyHighlight(that.el);
					that.callout.show();
				}, 250);
				that.highlight();
			},
			function () {
				window.clearTimeout(Callout.delay);
				that.unhighlight();
			})
		.click(function (event) {
				window.clearTimeout(Callout.delay);
				event.stopPropagation();
				event.preventDefault();
				window.setTimeout(function () {
					location.href = that.url;
				}, 300); // delay this slightly to prevent "Callout.delay" undefined errors when loading the new page
			})
		.attr({src: this.logo, border: 0, alt: ""});
	
	return this;
};

Logo.stickyHighlight = function ($img) {
	var logos = $(".brandribbon img");
	if ($img) {
		logos = logos.not($img);
		$img.addClass("on");
	}
	logos.each(function () {
		$(this).removeClass("on");
		this.src = this.src.replace(/_on/, "_off");
	});
};

Logo.prototype.highlight = function () {
	var img = this.el[0];
	if (img.className.indexOf("on") == -1) {
		img.src = img.src.replace(/_off/, "_on");
	}
};

Logo.prototype.unhighlight = function () {
	var img = this.el[0];
	if (img.className.indexOf("on") == -1) {
		img.src = img.src.replace(/_on/, "_off");
	}
};

function Callout(index, maxindex, id, text, url, container) {
	this.index = index;
	this.maxindex = maxindex;
	this.id = id;
	this.text = text;
	this.url = url;
	this.container = container;
	return this.create();
};

Callout.hide = function(show) {
	var callouts = $(".callout");
	if (show) {
		callouts = callouts.not("#" + show);
	} else {
		Logo.stickyHighlight(); // hiding all the callouts, so unhighlight all the logos
	}
	callouts.fadeTo(100, 0, function () {
			$(this).css("left", "-300px");
		});
};

Callout.delay = null;

Callout.prototype.create = function () {
	this.el = $("<div>")
		.appendTo(this.container)
		.addClass("callout")
		.attr("id", this.id)
		.fadeTo(1, 0)
		.html("<div>" + this.text + "</div>")
		.find("a")
		.attr("href", this.url)
		.click(function (event) {
				var that = this;
				window.clearTimeout(Callout.delay);
				event.stopPropagation();
				event.preventDefault();
				window.setTimeout(function () {
					location.href = that.href;
				}, 300); // delay this slightly to prevent "Callout.delay" undefined errors when loading the new page
			})
		.end();
	if (this.index == this.maxindex) {
		this.el.addClass("callout-right");
	}
	return this;
};

Callout.prototype.show = function () {
	window.clearInterval(BrandRibbon.animation);
	window.clearTimeout(Callout.delay);
	Callout.hide(this.id);
	$(this.el).fadeTo(250, .9);
	return this;
};

$(document).ready(function () {
	BrandRibbon.init();
});
