// author : alexander aivars : firstname.lastname at gmail.com
// ToDo	  : clean code, remove quickhax and generalize funcitons / settings 

var Browser = {

    availWidth: screen.availWidth,
    availHeight: screen.availHeight,
    upWin: null,
    
	type: {
		IE:     !!(window.attachEvent && !window.opera),
		Opera:  !!window.opera,
		WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
		Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
				MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
	},
        
    trim: function(str) {

		if (typeof str != "string") {
			return str;
		}

		var ret = str.replace(/^\s*([\S\s]*)$/,'$1');
		ret = str.replace(/\s+$/,'');
		ret = str.replace(/\s\s+/g,' ');

		return ret;
    },
    
	trimUScore: function (str) {
		var ret = Browser.trim(str);
		ret = ret.replace(/\s/g,'_');
		return ret;
	},

    openWindow: function(url, name, w_width, w_height, args, placeWindow) {

		name = Browser.trim(Browser.trimUScore(name));
		args = Browser.trim(args);


		if(args !== ''){
			args = args + ',';
		}
		
		if (!Browser.upWin || Browser.upWin.closed) {
			var center_of_screen_X = Math.floor(Browser.availWidth/2)-Math.floor(w_width/2);
			var center_of_screen_Y = Math.floor(Browser.availHeight/2)-Math.floor(w_height/2);
			placeWindow = (Browser.type.Opera) ? "" : ",left=" + center_of_screen_X + ",top=" + center_of_screen_Y;
		}
		
		Browser.upWin = window.open(url,name, args + 'width='+w_width+',height='+w_height + placeWindow);

		if(Browser.upWin){
			Browser.upWin.focus();
		} else {
			alert("F�nstret som skulle �ppnas blockerades! �ndra inst�llningar f�r i din popup-blockerare.");
		}
	
    },
	
	getViewportHeight: function()
	{
		var myHeight = 0;
		if( typeof( window.innerHeight ) == 'number' )
		{
			//Non-IE
			myHeight = window.innerHeight;
		}
		else if( document.documentElement && document.documentElement.clientHeight )
		{
			//IE 6+ in 'standards compliant mode'
			myHeight = document.documentElement.clientHeight;
		} else if ( document.body && document.body.clientHeight )
		{
			//IE 4 compatible
			myHeight = document.body.clientHeight;
		}
		return myHeight;
	},
	
	getViewportWidth: function()
	{
		var myWidth = 0;
		if( typeof( window.innerWidth ) == 'number' )
		{
			//Non-IE
			myWidth = window.innerWidth;
		}
		else if( document.documentElement && document.documentElement.clientWidth )
		{
			//IE 6+ in 'standards compliant mode'
			myWidth = document.documentElement.clientWidth;
		} else if ( document.body && document.body.clientWidth )
		{
			//IE 4 compatible
			myWidth = document.body.clientWidth;
		}
		return myWidth;
	},
	
	getWindowSize: function()
	{
		var myHeight = 0;
		if( typeof( window.outerHeight ) == 'number' )
		{
			//Non-IE
			myWidth = window.innerWidth;
		}
		else 
		{

		}

	},
	
	
	setViewportSize: function(width,height)
	{
		var size = Browser.getWindowSize();
		//alert("W:" + size.width +" H:" + size.height);
	},
	

	getScrollOffsetY: function()
	{
		var offset=0;
		if(typeof (window.pageYOffset)=="number")
		{
			offset=window.pageYOffset;
		}
		else
		{
			if( document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop) )
			{
				offset=document.documentElement.scrollTop;
			}
			else
			{
				if( document.body && (document.body.scrollLeft || document.body.scrollTop) )
				{
					offset=document.body.scrollTop;
				}
			}
		}
		return offset;
	},
	
	getScrollOffsetX: function()
	{
		var offset=0;
		if(typeof (window.pageXOffset)=="number")
		{
			offset=window.pageXOffset;
		}
		else
		{
			if( document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop) )
			{
				offset=document.documentElement.scrollLeft;
			}
			else
			{
				if( document.body && (document.body.scrollLeft || document.body.scrollTop) )
				{
					offset=document.body.scrollLeft;
				}
			}
		}
		return offset;
	},

	setTitle : function(title)
	{
		try
		{
			document.title=title
		}
		catch(err)
		{
			// trace("setState Exception when trying to set the title "+err)
		}
	}
	
};


var FlashBrowser = {
	initialize: function(){
		this.sizeDiffWidth = 0;
		this.sizeDiffHeight = 0;
		this.minimizeDefaultWidth = 400;
		this.minimizeDefaultHeight = 600;
//		this.minimizeDefaultWidth = 400;
//		this.minimizeDefaultHeight = 600;
		this.maximizeDefaultWidth = 800;
		this.maximizeDefaultHeight = 600;
		this.maximizeSaveWidth = 0;
		this.maximizeSaveHeight = 0;
		this.stageWidth = 300;
		this.stageHeight = 300;
		this.contentId = "flashcontent";
		
		// EVENT HOOKS
		// hookEvent(window,'mousewheel', this.mouseWheelProxy);
		// hookEvent(window,'resize', this.resizeProxy);
		// hookEvent(window,'load', this.resizeProxy);
		// hookEvent(window,'scroll',this.scrollProxy)
		// hookEvent(window,'mousedown',this.mousedownProxy)
	},	
	onStageResize: function(width,height) {
		if(this.stageWidth != width || this.stageHeight != height)
		{
			this.stageWidth = width;
			this.stageHeight = height;
			this.onDisplayResize(Browser.getViewportWidth(), Browser.getViewportHeight());
		}	
	},

	onDisplayResize: function(width,height) {
		var currentHeight = this.stageHeight;
//		var currentWidth = this.stageWidth;
		var currentWidth = Browser.getViewportWidth();
		var displayHeight = height;
		var displayWidth = 675;

		var newHeight = displayHeight;	
		var newWidth = displayWidth;

		if(currentHeight != displayHeight)
		{
			if (currentHeight > displayHeight)
			{
				newHeight = currentHeight + "px";		
			}
			else
			{
				newHeight = displayHeight + "px";	
			}		
	
			this.setDivHeight(newHeight);
		}
		
		if(currentWidth != displayWidth)
		{

			if (currentWidth > displayWidth)
			{
				newWidth = "100%";		
			}
			else
			{
				newWidth = displayWidth + "px";	
			}
			this.setDivWidth(newWidth);
		}

	},


	////////////////////////////////////////
	// SETTERS
	////////////////////////////////////////
	setDivSize: function (w,h)
	{
		var elm = document.getElementById(this.contentId);
		
		if(val != "NaNpx")
		{
			if (elm.style.height != val)
			{
				elm.style.height = val;
			}
			
		}
	},

	setDivHeight: function (val)
	{
		var elm1 = document.getElementById(this.contentId);
		var elm2 = document.getElementById("flashwraper");
		
		if(val != "NaNpx")
		{
//			if (elm1.style.height != val) { elm1.style.height = val; }
			if (elm1.style.height != val) { elm1.style.height = Browser.getViewportHeight(); }
			if (elm2 && elm2.style.height != val) { elm2.style.height = val; }
			trace("Browser.getViewportHeight(); " + Browser.getViewportHeight());
		}
	},
	
	setDivWidth: function (val)
	{
		var elm1 = document.getElementById(this.contentId);
		var elm2 = document.getElementById("flashwraper");
		
		if(val != "NaNpx")
		{
//			if (elm1.style.width != val) { elm1.style.width = val; }
			if (elm1.style.width != val) { elm1.style.width = Browser.getViewportWidth(); }
			if (elm2 && elm2.style.width != val) { elm2.style.width = val; }
		}
	},
	
	sendFlashEvent: function(evt)
	{
		try
		{
			var type=evt.eventName;
			trace("Communication:sendFlashEvent event "+type);
			if(type!=null)
			{
				var swf=this.getSWF();
				if(swf!=null)
				{
					var args=new Array();
					//args.push(type);
						
					for(var i=1; i<arguments.length; i++)
					{
						trace("Communication:sendFlashEvent pushing arg:"+arguments[i]);						
						args.push(arguments[i])
					}
					
					swf.externalJavaScriptEvent(type,args);
				}
				else
				{
					trace("Communication:sendFlashEvent trying to send event "+type+" before flash is initialized");
				}
			}
			else
			{
				trace("Communication:sendFlashEvent trying to send undefined flash event")
			}
		}
		catch(err)
		{
			// alert("Communication:sendFlashEvent exeption thrown "+err);
		}
	},


	////////////////////////////////////////
	// GETERS
	////////////////////////////////////////
	getSWF: function ()
	{
		return document.getElementById(this.contentId);
	},
	

	////////////////////////////////////////
	// PROXY FUNCTIONS TO SCOPE EVENT CALLS
	////////////////////////////////////////
	mouseWheelProxy: function(event){
	        var delta = 0;
	        if (!event)
			{
                event = window.event;
			}
	        if (event.wheelDelta)
			{
				/* IE/Opera. */
	            delta = event.wheelDelta/120;
	            /* In Opera 9, delta differs in sign as compared to IE. */
	            if (window.opera)
				{
                    delta = -delta;
				}
	        } 
			else if (event.detail)
			{ 
				/** Mozilla case. */
	            delta = -event.detail/3;
	        }


	        /** If delta is nonzero, handle it.
	         * Basically, delta is now positive if wheel was scrolled up,
	         * and negative, if wheel was scrolled down.
	         */
	        if (delta)
	                FlashBrowser.handleWheelScroll(delta);
	        /** Prevent default actions caused by mouse wheel.
	         * That might be ugly, but we handle scrolls somehow
	         * anyway, so don't bother here..
	         */
	        if (event.preventDefault)
	                event.preventDefault();
		event.returnValue = false;
	},
	
	resizeProxy: function(event){ FlashBrowser.handleResize(); },
	scrollProxy: function(event) { FlashBrowser.handleScroll()},	


	////////////////////////////////////////
	// EVENT HANDLERS
	////////////////////////////////////////
	handleWheelScroll: function (delta)
	{
		try
		{
			this.getSWF().externalMouseWheelEvent( delta );
		} catch(err) {
			
		}
	},
	
	handleResize: function ()
	{
		this.onDisplayResize(Browser.getViewportWidth(), Browser.getViewportHeight());
		try
		{
			this.sendFlashEvent(JavascriptEvent.WindowResize,Browser.getViewportHeight(),Browser.getViewportHeight());
		} catch(err) {
			
		}
	},
	
	handleScroll: function(offset)
	{
		try
		{
			this.sendFlashEvent(JavascriptEvent.WindowScroll,Browser.getScrollOffsetX(),Browser.getScrollOffsetY());
		} catch(err) {
			
		}
	}
};


function hookEvent(element, eventName, callback)
{
	if(typeof(element) == "string")
	{
		element = document.getElementById(element);
	}
	
	if(element == null)
	{
		return;
	}
	
	if(element.addEventListener)
	{
		if(eventName == 'mousewheel')
		{
			element.addEventListener('DOMMouseScroll', callback, false);
		}
		
		element.addEventListener(eventName, callback, false);
	}
	else if(element.attachEvent)
    {
    	element.attachEvent("on" + eventName, callback);
	}
}

function unhookEvent(element, eventName, callback)
{
	if(typeof(element) == "string")
	{
		element = document.getElementById(element);
	}
	
	if(element == null)
	{
		return;
	}
	
	if(element.removeEventListener)
	{
		if(eventName == 'mousewheel')
		{
			element.removeEventListener('DOMMouseScroll',callback, false);  
		}
		
		element.removeEventListener(eventName, callback, false);
  	}
	else if(element.detachEvent)
	{
		element.detachEvent("on" + eventName, callback);
	}
}



function trace(str)
{
//	document.getElementById("out").innerHTML = str;
//	Browser.setTitle(str);
	try
	{
		FlashBrowser.getSWF().externalTrace(str.toString());
	} catch(err) {
		
	}
}

function JavascriptEvent(type) { this.eventName=type; }
JavascriptEvent.WindowResize=new JavascriptEvent("WindowResize");
JavascriptEvent.WindowScroll=new JavascriptEvent("WindowScroll");


FlashBrowser.initialize();
