/**
*	object promoImage
*	manages the background image
**/

window.promoImage = {
	//string url: path to the image\
	imgUrl : 'images/OMAlogo.gif',
	
	//object imgObj: the image object
	imgObj : new Image(),
	
	//object canvasObj: the canvas object
	canvasObj : null,
	
	//boolean homepage: should be set to true if on the homepage
	homepage : false,
	
	//object loaderImage: used for the homepage loading
	loaderImg : null,
	
	//time waitTime : timestamp at load, used on homepage
	onloadTime : null,
	
	//boolean debug: enable debugging
	debug : 0,
	
	writeImage : function() {
		
		try {
			w = mainframe.innerWidth();
			h = mainframe.innerHeight();
			
			canvasW = w;
			scale = canvasW/w;
			canvasH = h;
			
			//this.canvasObj.style.width = canvasW+"px";
//		  	this.canvasObj.style.height = canvasH+"px";
//		  	this.canvasObj.width = canvasW;
//		  	this.canvasObj.height = canvasH;
			
			ctx = this.canvasObj.getContext("2d");
			ctx.clearRect(0, 0, w, h);
			
			ctx.scale(canvasW/w, canvasH/h);
			
			
			imgScale = Math.max(canvasW/this.imgObj.width, canvasH/this.imgObj.height);
			if(mainframe.isSafari()){
				//Safari needs an extra push...
				this.doDebug('draw Safari');
				var self = this;
				//doDraw = function(){ctx.drawImage(self.imgObj, 0, 0, self.imgObj.width*imgScale, self.imgObj.height*imgScale)};
				//window.setTimeout(doDraw, 20);
			}
			
			else if(mainframe.isIE6()){
				//IE6 needs an extra push...
				//ctx.drawImage(this.imgObj, 0, 0, this.imgObj.width*imgScale, this.imgObj.height*imgScale);
				//var vml = document.getElementById('bgcanvas').childNodes;
				//document.getElementById('overlay').style.position = 'absolute';
			}
			else {
				
				//ctx.drawImage(this.imgObj, 0, 0, this.imgObj.width*imgScale, this.imgObj.height*imgScale);
			}
			
			//clear the OMA logo from the background
			document.body.style.backgroundImage = "none";
			
			//console.log(this.imgObj.width);
			//console.log(this.imgObj.height);
			var image_scale = this.imgObj.width/this.imgObj.height;
			var window_scale = canvasW/canvasH;
			//alert(this.imgObj.width+" et "+this.imgObj.height);
			//console.log(canvasW);
			//alert('test');
			
			if (image_scale>window_scale){
				var wid = Math.floor(canvasH*image_scale);
				document.getElementById('image_fix').innerHTML="<img src=\""+this.imgObj.src+"\" width=\""+wid+"\" height=\""+canvasH+"\" />";
				//var offset = Math.floor((canvasH-hei)/2);
				document.getElementById('image_fix').style.top = "0px";
				document.getElementById('image_fix').style.left = "0px";
			}
			else{
				var hei = Math.floor(canvasW/image_scale);
				//var offset = (canvasW-wid)/2;
				document.getElementById('image_fix').innerHTML="<img src=\""+this.imgObj.src+"\" width=\""+canvasW+"\" height=\""+hei+"\" />";
				document.getElementById('image_fix').style.top = "0px";
				document.getElementById('image_fix').style.left = "0px";
			
			}
			//document.body.style.backgroundImage = "url("+this.imgObj.src+")";
		}
		catch(err) {
			this.doDebug('error in writeImage method: ' + err);
		}
	},
	
	/** function imgOnload
	*	
	**/
	imgOnload : function() {
		//if on the homepage do some animation logic
		if(this.homepage){			
			var timeNow = new Date();
			deltaTime = timeNow - this.onloadTime;
			
			this.doDebug("deltaTime: " + deltaTime);
			if(deltaTime >= 2000) {
				this.writeImage();
				this.animateMenu();
			}
			else {
				var self = this;
				window.setTimeout(function(){self.writeImage();self.animateMenu();}, 2000 - deltaTime);
			}
		}
		else {
			this.writeImage();
		}
	},
	
	animateMenu : function() {
		var leftmenu = document.getElementById("leftmenu");
		
		//start leftmenu animation
		endPos = mainframe.getElementTop(leftmenu);
		startPos = mainframe.innerHeight();
		currPos = Math.max(startPos, 1000);
		stepSize = (startPos - endPos)/8;
		
		leftmenu.style.top = startPos + 'px';
		
		//determine the animation
		var menuAnimInt = null;
		var doMenuAnim = function(){
			//var step = 50;
			delta = (currPos - endPos)/(startPos - endPos);
			step = Math.max(Math.ceil(delta*stepSize), 3);
			currPos -= step;
			
			if(currPos <= endPos){
				window.clearInterval(menuAnimInt);
				currPos = endPos;
				leftmenu.style.top = currPos + 'px';
				overlayAnimInt = window.setInterval(doOverlayAnim, 50);
			}
			else {
				leftmenu.style.top = currPos + 'px';
			}
			//promoImage.doDebug("step: "  + step);
		}
		
		
		var overlay = document.getElementById("overlay");
		menuStartOpacity = 0;
		menuEndOpactity = 60;
		currOpacity = 0;
		
		mainframe.setOpacity(overlay, menuStartOpacity);
		overlay.style.visibility = 'visible';
		
		var overlayAnimInt = null;
		var doOverlayAnim = function() {
			var step = 15;
			delta = (currOpacity - menuEndOpactity)/(menuStartOpacity - menuEndOpactity);
			step = Math.max(Math.ceil(delta*step), 3);
			currOpacity += step;
			
			if(currOpacity >= menuEndOpactity){
				window.clearInterval(overlayAnimInt);
				currOpacity = menuEndOpactity;
				mainframe.setOpacity(overlay, currOpacity);
			}
			else {
				mainframe.setOpacity(overlay, currOpacity);
			}
			//promoImage.doDebug("step: "  + step);					
		}
		
		//start the animation
		promoImage.loaderImg.style.display = "none";
		leftmenu.style.visibility = "visible";
		menuAnimInt = window.setInterval(doMenuAnim, 50);
	},
	
	init : function() {
		
		if(document.getElementById("bgcanvas")){
			this.canvasObj = document.getElementById("bgcanvas");
			
			if(this.homepage){
				//start waitTime
				this.onloadTime = new Date();
				
				//visitor sees OMA logo for a minimum timespan with loader
				document.body.style.backgroundImage = "url(images/OMAlogo.gif)";
				
				this.loaderImg = document.createElement("IMG");
				this.loaderImg.src = "images/loader3.gif";
				this.loaderImg.style.position = "absolute";
				leftAlign = mainframe.innerWidth()/2 - 16;
				topAlign = mainframe.innerHeight()/2 - 16 + 130;
				this.loaderImg.style.top = topAlign + "px";
				this.loaderImg.style.left = leftAlign + "px";
				document.body.appendChild(this.loaderImg);
				
				
				//adjust the styles for the overlay
				var overlay = document.getElementById("overlay");
				var leftmenu = document.getElementById("leftmenu");
				mainframe.setOpacity(overlay, 0);
				overlay.style.width = '160px';
				
				//optimize:
				linkArr = leftmenu.getElementsByTagName("A");
				newTop = mainframe.getElementTop(linkArr[0]);
				newBottom = mainframe.getElementTop(linkArr[linkArr.length-1]) + linkArr[linkArr.length-1].offsetHeight + 16 - newTop; 
				overlay.style.top = newTop + 'px';
				overlay.style.height = newBottom + 'px';
				
			}
			
			this.imgObj.onload = function() {promoImage.imgOnload()};
			this.imgObj.src = this.imgUrl;
			
		}
		else {
			
			this.doDebug('No canvas object found on page');
		}
	},
	
	/** private function doDebug
	*	simple debug output message
	**/
	doDebug : function(msg) {
		if(this.debug){
			try {
				window.console.log(msg);
			}
			catch(err) {
				if(!document.getElementById('debugConsole')){
					debugDiv = document.createElement("DIV");
					debugDiv.id = 'debugConsole';
					document.body.appendChild(debugDiv);
				}
				document.getElementById('debugConsole').innerHTML += '<br />promoImage: ' + msg;
			}
		}
	}
}

/**
*	Mainframe parameters
**/
window.mainframe = {
	
	/**	function innerWidth
	* returns the innerWidth of the window, crossbrowser
	**/
	innerWidth : function() {
		if(window.innerWidth){
			return window.innerWidth;
		}
		else if(document.documentElement.clientWidth){
			return document.documentElement.clientWidth;
		}
	},
	
	/**	function innerHeight
	* returns the clientHeight of the window, crossbrowser
	**/
	innerHeight : function() {
		if(window.innerHeight){
			return window.innerHeight;
		}
		else if(document.documentElement.clientHeight){
			return document.documentElement.clientHeight;
		}
	},
	
	/** function getElementTop
	*	gets the real top position of an element in pixels
	*	object obj : object to get the top position from
	**/
	getElementTop : function(obj){
		yPos = obj.offsetTop;
		tmpObj = obj;
		
		while(tmpObj.offsetParent){
			tmpObj = tmpObj.offsetParent;
			yPos += tmpObj.offsetTop;
		}
		return yPos;
	},
	
	/** function addEvent
	* attaches an event to an object
	* object obj : object to attach to
	* string evtType : type of the event, i.e. resize, click, mouseout, etc.
	* boolean trigger : typically false
	**/
	addEvent : function (obj, evtType, trigger){
		if(window.addEventListener){ // Mozilla, Netscape, Firefox
			obj.addEventListener(evtType, trigger, false);
		} else { // IE
			obj.attachEvent('on' + evtType, trigger);
		}
	},
	
	/** function removeEvent
	* removes an event from an object
	* object obj : object to remove to
	* string evtType : type of the event, i.e. resize, click, mouseout, etc.
	* function trigger : function to call
	**/
	removeEvent : function (obj, evtType, trigger){
		if(window.removeEventListener){ // Mozilla, Netscape, Firefox
			obj.removeEventListener(evtType, trigger, false);
		} else { // IE
			obj.detachEvent('on' + evtType, trigger);
		}
	},
	
	preloadImage : function(imgSrc){
		var newImg = new Image();
		newImg.src = imgSrc;
	},
	
	/** function setOpacity
	* 	set the opacity for a given object, crossbrowser solution
	*	object obj : object on which to set the opacity level
	*	int value : percentage of opacity
	**/
	setOpacity : function(obj, value){
		if(typeof(obj.style.filter) != "undefined"){
			var obj = obj;
			//Don't ask... had something to do with VML layers and IE not updating filter UNLESS you set a timeout (at 0ms!?)
			window.setTimeout(function(){obj.style.filter = 'alpha(opacity=' + value + ')';}, 0)
		}
		else {
			obj.style.opacity = (value/100);
		}
	},
	
	/** function isSafari
	* returns true or false
	**/
	isSafari : function(){	
		return (navigator.userAgent.toLowerCase().indexOf("safari") != -1);	
	},
	
	/** function isIE6
	* returns true or false
	**/
	isIE6 : function(){	
		return (navigator.userAgent.toLowerCase().indexOf("msie 6") != -1);	
	},
	
	/** function isIE
	* returns true or false
	**/
	isIE : function(){	
		return (navigator.userAgent.toLowerCase().indexOf("msie") != -1);	
	},
	
	getCookie : function(cookiename){
		var cookiestring=""+document.cookie;
	 	var index1=cookiestring.indexOf(escape(cookiename));
		if (index1==-1 || cookiename=="") return ""; 
			var index2=cookiestring.indexOf(';',index1);
		if (index2==-1) index2=cookiestring.length; 
			return cookiestring.substring(index1+cookiename.length+1,index2);
	},

	setCookie : function(name, value, expires, path, domain, secure){
		document.cookie= name + "=" + escape(value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
	    ((path) ? "; path=" + path : "") +
	    ((domain) ? "; domain=" + domain : "") +
	    ((secure) ? "; secure" : "");
		
	}
}

//initialize the objects and set the events
var doOnLoad = function(){
	
	promoImage.init();
	
	//add events for the printer icon IE < 7
	if(mainframe.isIE6() && document.getElementById("printericon")){
		var printerIcon = document.getElementById("printericon").getElementsByTagName("IMG")[0];
		var printerLabel = document.getElementById("printlabel");
		mainframe.addEvent(document.getElementById("printericon"), 'mouseover', function(){printerIcon.style.background = 'url(images/printer_on.gif)'; printerLabel.style.display = 'inline';});
		mainframe.addEvent(document.getElementById("printericon"), 'mouseout', function(){printerIcon.style.background = 'url(images/printer.gif)'; printerLabel.style.display = 'none';});
	}
	

	
	if(document.getElementById('new_overlay')){
		if(mainframe.innerWidth() < document.getElementById("new_overlay").offsetWidth){
		document.body.style.width = document.getElementById("new_overlay").offsetWidth + 'px';
		document.body.style.overflowX = 'scroll';
		}
		else {
			document.body.style.overflowX = 'hidden';
		}
		var scrollHeight = 0;
		// giulio - fixed safari bug
		if(mainframe.isSafari())        {
			 scrollHeight = document.body.scrollHeight;
		}
		else	{
			scrollHeight = document.documentElement.scrollHeight;
		}
		document.getElementById('new_overlay').style.height = scrollHeight+"px";
		document.getElementById('new_overlay').style.minHeight = scrollHeight+"px";
	}
		
	
	var images = document.getElementsByTagName("IMG");
	for(i=0; i<images.length; i++){
		images[i].oncontextmenu = function() {return false;};
	}
}

var resizeInt = null;
var doOnResize = function(){
	//create a little delay to "unstress" IE and Opera during resizing
	try {
		window.clearTimeout(resizeInt);
		resizeInt = null;
	}
	catch (err){
		//nice catch
	}
	resizeInt = window.setTimeout("promoImage.writeImage()", 200);
	
	if(mainframe.innerWidth() < document.getElementById("overlay").offsetWidth){
		document.body.style.width = '800px'; //document.getElementById("overlay").offsetWidth + 'px';
		document.body.style.overflowX = 'scroll';
	}
	else {
		document.body.style.overflowX = 'hidden';
	}
}


mainframe.addEvent(window, 'load', doOnLoad);
mainframe.addEvent(window, 'resize', doOnResize);

