var nextX = 10;
var nextY = 40;
var maxZ = 1;
var scrolledRight = false;
var widgetRegistry = new Array();
var activeWidgetInfo = null;

function init() {
	$.each(widgetRegistry,function() {
		this.init();
	});
	$('.maillink').each(function() {insertLink($(this));});
	window.setTimeout(function() {startupAnimation()},300);
}

function insertLink(e) {
	var str = String.fromCharCode(109,97,105,108,64,105,100,101,101,110,103,101,115,116,97,108,116,117,110,103,46,100,101,10);
	var href = String.fromCharCode(109,97,105,108,116,111,58)+str;
	var a = $("<a/>", { "class": "maillink", "text": str, "href" : href });
	e.replaceWith(a);
}

function startupAnimation() {
	window.scrollTo(0,0);
	var desktop = $('#desktop');
	desktop.css('left',-2140);
	desktop.show();
	desktop.animate({left:0},1000,'easeInOutExpo');
}

function WidgetManager(wid,width,height,infoWidth) {
	this.wid=wid;
	this.width=width;
	this.height=height;
	this.infoWidth=infoWidth;
	this.widget=null;
	this.heading=null;
	this.thumbnail=null;
	this.initialized=false;
	this.widgetInitialized=false;
	this.loadingImages=new Array();
	this.onFinishInitWidget=null;
	this.activePage=0;
	this.pageCount=0;

	this.init=function() {
		var widgetManager = this;
		if (!this.initialized) {
			this.widget=$('#'+wid);
			this.thumbnail=$('#index'+wid);
			this.thumbnail.each(function() { widgetManager.createClickTarget($(this));});
			this.heading=$('#head'+wid);
			this.heading.each(function() { widgetManager.createClickTarget($(this));});
			this.initalized = true;
		}
	}

	this.createClickTarget=function(target) {
		var widgetManager = this;
		target.click(function() {
				widgetManager.showWidget();
			});
		target.css('cursor','pointer');
	}

	this.finishInitWidget=function() {
		var widgetManager = this;
		if (!this.widgetInitialized) {
			var maxLeft = $('#contentarea').width();
			var maxTop = $('#contentarea').height()+200;
			this.widget.draggable({containment: [-100, -100, maxLeft+200, maxTop+200],
						start:function() {widgetManager.widget.css('zIndex',maxZ++);},
						/*drag:function(event,ui) {
						  if (maxLeft<ui.position.left) {
						  return false;
						  }
						  if (maxTop<ui.position.top) {
						  return false;
						  }},*/
						stop:function(event,ui) {
						if (maxLeft<ui.position.left) {
							widgetManager.widget.css('left',maxLeft);
						}
						if (maxTop<ui.position.top) {
							widgetManager.widget.css('top',maxTop);
						}
					}});
			this.widget.mousedown(function() {widgetManager.widget.css('zIndex',maxZ++);});
			widgetManager.thumbnail.css('opacity',1);
			this.widgetInitialized = true;
		}
		if (this.onFinishInitWidget != null) {
			this.onFinishInitWidget();
			this.onFinishInitWidget = null;
		}
	}

	this.showOverlay=function() {
		var widgetManager = this;
		$('.widgetoverlay',this.widget).fadeIn(200);
	}

	this.hideOverlay=function(immediately) {
		var widgetManager = this;
		if (immediately) {
			$('.widgetoverlay',this.widget).hide();
		} else {
			$('.widgetoverlay',this.widget).fadeOut(200);
		}
	}

	this.initWidget=function() {
		var widgetManager = this;
		if (!this.widgetInitialized) {
			this.initOverlay();
			$('.imageplaceholder',this.widget).each(function(){
					var e = $(this);
					var n = $("<img alt='' src='"+e.text()+"' width='"+widgetManager.width+"' height='"+widgetManager.height+"'>");
					e.replaceWith(n);
					imgElem = n.get(0);
					if (!imgElem.complete && imgElem.readyState !== 4) {
						//alert(''+imgElem.nodeType+' '+imgElem.tagName+' '+imgElem.src+' '+imgElem.complete+' '+imgElem.readyState);
						n.load(function() {
								widgetManager.loadingImages.splice($.inArray(widgetManager.loadingImages,imgElem),1);
								if(0==widgetManager.loadingImages.length) {
									widgetManager.finishInitWidget();
								}});
						widgetManager.loadingImages.push(imgElem);
					}
				});
		}
		if(0==widgetManager.loadingImages.length) {
			widgetManager.finishInitWidget();
		} else {
			widgetManager.thumbnail.css('opacity',0.7);
		}
	}
	
	this.newWidgetPosition=function() {
		var widgetManager = this;
		if (scrolledRight && this.thumbnail.length>0) {
			this.widget.css('left',this.thumbnail.first().offset().left-$('#main').position().left);
		} else {
			this.widget.css('left',nextX);
			nextX = (nextX+this.width+20)%($('#contentarea').width()-20);
		}
		this.widget.css('top',30+nextY);
		//nextY = (nextY+133)%233;
	}

	this.showWidget=function() {
		var widgetManager = this;
		if (!this.onFinishInitWidget) {
			if (this.widget.is(':hidden')) {
				this.onFinishInitWidget=function() {
					widgetManager.newWidgetPosition();
					widgetManager.widget.show();
					widgetManager.showWidgetDo();
				};
				this.initWidget();
			} else {
				this.showWidgetDo();
			}
		}
	}

	this.widenForInfo=function() {
		var widgetManager = this;
		this.widget.css('width',function(e,o){return o+widgetManager.infoWidth});
	}

	this.narrowForInfo=function() {
		var widgetManager = this;
		this.widget.css('width',function(e,o){return o-widgetManager.infoWidth});
	}

	this.toggleWidgetInfo=function(immediately) {
		var widgetManager = this;
		if (this===activeWidgetInfo) {
			if (immediately) {
				$('.widgetinfo',this.widget).hide();
				this.narrowForInfo();
			} else {
				$('.widgetinfo',this.widget).hide('blind',{direction:'horizontal',duration:200},function() {widgetManager.narrowForInfo();});
			}
			activeWidgetInfo=null;
		} else {
			if (activeWidgetInfo!==null) {
				activeWidgetInfo.toggleWidgetInfo(false);
			}
			this.widenForInfo();
			$('.widgetinfo',this.widget).show('blind',{direction:'horizontal',duration:200});
			activeWidgetInfo=this;
		}
	}

	this.hideWidget=function() {
		var widgetManager = this;
		if (this===activeWidgetInfo) {
			this.toggleWidgetInfo(true);
		}
		var pages = $('.widgetpage',this.widget);
		this.widget.hide();
		pages.eq(this.activePage).hide();
		this.activePage = 0;
	}

	this.previousPage=function() {
		var widgetManager = this;
		var pages = $('.widgetpage',this.widget);
		pages.eq(--this.activePage).fadeIn(300);
		pages.eq(this.activePage+1).fadeOut(300);
		this.updateOverlay();
	}

	this.nextPage=function() {
		var widgetManager = this;
		var pages = $('.widgetpage',this.widget);
		pages.eq(++this.activePage).fadeIn(300);
		pages.eq(this.activePage-1).fadeOut(300);
		this.updateOverlay();
	}

	this.updateOverlay=function() {
		var widgetManager = this;
		var prev = $('.widgetoverlayprev',this.widget);
		if (0<this.activePage) {
			prev.show();
		} else {
			prev.hide();
		}
		var next = $('.widgetoverlaynext',this.widget);
		if (this.activePage<this.pageCount-1) {
			next.show();
		} else {
			next.hide();
		}
	}

	this.initOverlay=function() {
		var widgetManager = this;
		this.widget.hover(function() {widgetManager.showOverlay();},function() {widgetManager.hideOverlay();});
		var info = $('.widgetoverlayinfo',this.widget);
		if (this.infoWidth!==undefined && 0<this.infoWidth) {
			info.click(function() {widgetManager.toggleWidgetInfo();});
			info.css('cursor','pointer');
			info.show();
		}
		var close = $('.widgetoverlayclose',this.widget);
		close.click(function() {widgetManager.hideWidget();});
		close.css('cursor','pointer');
		var prev = $('.widgetoverlayprev',this.widget);
		prev.click(function() {widgetManager.previousPage();});
		prev.css('cursor','pointer');
		var next = $('.widgetoverlaynext',this.widget);
		next.click(function() {widgetManager.nextPage();});
		next.css('cursor','pointer');
	}

	this.showWidgetDo=function() {
		var widgetManager = this;
		var pages = $('.widgetpage',this.widget);
		pages.eq(this.activePage).show();
		this.pageCount=pages.length;
		this.hideOverlay(true);
		this.updateOverlay();
		this.widget.css('zIndex',maxZ++);
		var pos = this.widget.position();
		var jwindow = $(window);
		var jdoc = $(document);
		var body = $('body');
		var targetOffset = 50;
		var viewPortWidth = jwindow.width();
		var currentScrollPos = scrollX();
		var positionOffset = $('#main').position().left;
		var rightBorder = $('#main').width()-$('#contentarea').width();
		var widgetPos = pos.left+positionOffset;
		var maxScrollPos = $('#contentarea').width()-viewPortWidth+positionOffset+rightBorder;
		var targetScrollPos = Math.max(Math.min(widgetPos-targetOffset,maxScrollPos),0);
		var scrolledLeft = false;
		//alert('targetOffset: '+targetOffset+'; viewPortWidth: '+viewPortWidth+'; currentScrollPos: '+currentScrollPos+'; positionOffset: '+positionOffset+'; rightBorder: '+rightBorder+'; widgetPos: '+widgetPos+'; maxScrollPos: '+maxScrollPos+'; targetScrollPos: '+targetScrollPos);
		if ((currentScrollPos<targetScrollPos && viewPortWidth<300+widgetPos-targetOffset-currentScrollPos)
			|| (targetScrollPos<currentScrollPos)) {
			if (currentScrollPos<targetScrollPos) {
				scrolledRight = true;
			}
			scrolledLeft=true;
			body.animate({scrollLeft:targetScrollPos},300,'swing');
		}
		var viewPortHeight = jwindow.height();
		var offTop = this.widget.offset().top;
		var sY = scrollY();
		//alert('viewPortHeight: '+viewPortHeight+'; offTop: '+offTop)
		if (viewPortHeight<offTop+30) {
			var targetTop = offTop-viewPortHeight+60;
			body.animate({scrollTop:targetTop},300,'swing',function() {window.scrollTo(scrolledLeft?targetScrollPos:currentScrollPos,targetTop);});
		} else if (sY!=0) {
			body.animate({scrollTop:0},300,'swing',function() {window.scrollTo(scrolledLeft?targetScrollPos:currentScrollPos,0);});
		} else if (scrolledLeft) {
			window.scrollTo(targetScrollPos,sY);
		}
	}
}

function scrollX() {
	if (window.pageXOffset !== undefined) {
		return window.pageXOffset;
	}
	return (((t = document.documentElement) || (t = document.body.parentNode)) && typeof t.ScrollLeft == 'number' ? t : document.body).ScrollLeft;
}

function scrollY() {
	if (window.pageYOffset !== undefined) {
		return window.pageYOffset;
	}
	return (((t = document.documentElement) || (t = document.body.parentNode)) && typeof t.ScrollTop == 'number' ? t : document.body).ScrollTop;
}
