/**
 * $URL: http://10.6.2.181/svn/cms3_frontend/branches/bwin_multimedia/cms3_preview/js/util.js $
 * $Date: 2009-10-30 11:40:41 +0100 (Fr, 30 Okt 2009) $
 * $Revision: 365 $
 * $Author: oliver $
 *
 * Copyright (C) 2009 seso media group <www.seso.at>
 * 
 * This program is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU General Public License as published by the 
 * Free Software Foundation; either version 2 of the License, or 
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details: <http://www.gnu.org/licenses/>
 * 
 * powered by Prototype JavaScript framework <http://www.prototypejs.org/>
 * powered by scriptaculous <http://script.aculo.us/>
 * 
 * @author: gg@seso.at
 */

/*******************************************************************************
	ENVIROMENT
*******************************************************************************/

function env() {

	var self = this;

	this.browser = checkBrowser();
	this.isIE = (self.browser.substr(0,2) == 'ie');
	this.os = checkOS();
	this.flashVer = checkFlash();

	
	function checkOS() {
		
		var agt = navigator.userAgent.toLowerCase();
		
		if (agt.indexOf("macintosh") != -1) return "mac";
		if (agt.indexOf("windows") != -1) return "win";
		if (agt.indexOf("linux") != -1) return "linux";
		
		return 'UNKOWN';
	}


	function checkBrowser() {

		var agt = navigator.userAgent.toLowerCase();
	
		if (agt.indexOf("msie 8.0") != -1) return "ie8";
		if (agt.indexOf("msie 7.0") != -1) return "ie7";
		if (agt.indexOf("msie 6.0") != -1) return "ie6";
		if (agt.indexOf("msie") != -1) return "ie";
	
		if (agt.indexOf("firefox/3") != -1) return "ff3";
		if (agt.indexOf("firefox/2") != -1) return "ff2";
		if (agt.indexOf("firefox/1") != -1) return "ff1";
		if (agt.indexOf("firefox") != -1) return "ff";
		
		if (agt.indexOf("chrome/1") != -1) return "ch1";
		if (agt.indexOf("chrome") != -1) return "ch";
		
		if (agt.indexOf("safari/3") != -1) return "sa3";
		if (agt.indexOf("safari/4") != -1) return "sa4"; 
		if (agt.indexOf("safari") != -1) return "sa";

		if (agt.indexOf("opera/9") != -1) return "op9";
		if (agt.indexOf("opera/8") != -1) return "op8";
		if (agt.indexOf("opera/7") != -1) return "op7";
		if (agt.indexOf("opera") != -1) return "op";

		if (agt.indexOf("netscape/8") != -1) return "ns9";
		if (agt.indexOf("netscape/8") != -1) return "ns8";
		if (agt.indexOf("netscape/7") != -1) return "ns7";
		if (agt.indexOf("netscape") != -1) return "ns";
		
		if (agt.indexOf("camino") != -1) return "ca";
		
		return 'UNKOWN';
	}
		
	
	function checkFlash() {

		if (self.isIE) {
			
			if (typeof window.ActiveXObject != 'undefined') {

				var v = 0,
					d = null,
					a = null,
					crash = false;
				
				try {
					
					a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
				}
				catch(e) {
				
					try { 
						
						a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
						v = [6,0,21];
						a.AllowScriptAccess = "always";
					}
					catch(e) {
						
						if (v[0] == 6) crash = true;
					}
					
					if (!crash) {
						
						try {
							
							a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
						}
						catch(e) {}
					}
				}
				
				if (!crash && a) { 

					try {
						
						d = a.GetVariable("$version");	
						if (d) return parseInt(d.split(" ")[1].split(",")[0]);
					}
					catch(e) {}
				}
			}
		}
		
		else {
			
			for (var i=0; i<navigator.plugins.length; i++) {
				
				if (navigator.plugins[i]['name'] == 'Shockwave Flash') {
				
					return navigator.plugins[i]['description'].split('Shockwave Flash ')[1].split('.')[0];
				}
			}
		}
	
		return null;
	}
}

env = new env();



/*******************************************************************************
	LOGGER
*******************************************************************************/

var logger = function() {

	/**
	 * N => disables the debug-display
	 * 0 => all messages
	 * 1 => NOTICE: just an information, nothing ciritcal
	 * 2 => WARNING: the error takes effect localy but doesn't cause a global crash
	 * 3 => FAILURE: a fatal error occures, the script can't work correct any longer
	 */
	var debug = null;
	
	var states = [null,'NOTICE','WARNING','FAILURE'];
	var storeCache = true;
	var container = null;
	var cache = [];
		cache['ALL'] = [];
	var components = [];
		components[0] = 'ALL';
	
	
	this.init = function() {
		
		storeCache = false;
	};

	
	this.addMsg = function(msg, state, component) {

		if (typeof debug === 'number') {
			
			if (typeof msg == 'undefined') msg = 'UNDEFINED';
			if (msg == null) msg = 'NULL';
			if (!state) state = 0;
			
			if (state >= debug) {
				
				var d = new Date();
				var div = document.createElement('DIV');
					div.innerHTML = "["+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds()+":"+d.getMilliseconds()+"] ";
					
				if (component) {

					div.innerHTML += '<strong>'+component+':</strong>&nbsp;';
				} 

				if (state > 0) {
	
					state = states[state];
					div.className = state.toLowerCase();
				}
				
				if (typeof msg == 'object') {
					
					if (msg.message && msg.fileName && msg.lineNumber) {
						
						div.appendChild(printException(msg));
					}
					
					else {
						
						var pre = document.createElement('PRE'); 
			
						for (m in msg) {
							
							try {
							
								pre.innerHTML += m + "\t=>\t" + msg[m]+'<br/>';
							}
							
							catch (e) {
								
								pre.innerHTML += m + '<br/>';
							}
						}
						
						div.appendChild(pre);
					}
	
				}
				
				else {
					
					if (msg == 'HR') msg = "<hr/>";
					div.innerHTML += msg;
				}
				
				cache['ALL'].push(div);
				
				if (component) {
					
					if (!cache[component]) {
						
						components.push(component);
						cache[component] = [];
						drawComponentSelect();
					}
					
					cache[component].push(div);
				}
				

				if (storeCache == false) {

					if (container === null) {
						
						createContainer();
					}
	
					container.appendChild(div);
				}
			}
		}
	};
	
	
	function createContainer() {

		var div = document.getElementById('logger');

		if (!div) {

			if (document.body) {

				div = document.createElement('DIV');
				div.id = 'logger';
			
				document.body.appendChild(div);
				
				var head = document.createElement('DIV');
					head.className = "head";
					head.innerHTML = "<strong>FRINK</strong> &nbsp;";
					
				div.appendChild(head);

				
				var sel = document.createElement('DIV');
					sel.id = 'loggerSelectContainer';

				head.appendChild(sel);
				
				drawComponentSelect();
				
				var a = document.createElement('A');
					a.href = '#';
					a.innerHTML = 'hide';
					
				head.appendChild(a);

				if (env.isIE) {
					
					a.attachEvent("click", logger.hide);
					
				} else {
					
					a.addEventListener("click", logger.hide, false);
				}
				
				var a = document.createElement('A');
					a.href = '#';
					a.innerHTML = 'reset';
					
				head.appendChild(a);
				
				if (env.isIE) {
					
					a.attachEvent("click", logger.reset);
					
				} else {
					
					a.addEventListener("click", logger.reset, false);
				}

				var d = document.createElement('DIV');
					d.className = 'env';
					d.innerHTML = "Browser: "+env.browser.toUpperCase()+" | OS: "+env.os.toUpperCase()+" | Flash: "+env.flashVer+"<br/>";
					d.innerHTML += "Prototype "+Prototype.Version+" // Scriptaculous "+Scriptaculous.Version+" // Frink "+util.Version+"";

				head.appendChild(d);
				
				var body = document.createElement('DIV');
					body.className = "body";
					
				div.appendChild(body);

				storeCache = false;
				container = body;
				
				drawContent();
				
				
				if (Prototype && Scriptaculous) {
					
					new Draggable(div, { 

						zindex: 999998,
						starteffect: null,
						endeffect: null
					});
				}
				
				
				return true;
			}
		}
		
		return false;
	}
	
	
	function drawComponentSelect() {

		var select = document.createElement('SELECT');

		for (var i=0; i<components.length; i++) {
		
			var opt = document.createElement('OPTION');
				opt.value = i;
				opt.innerHTML = components[i];
				
			select.appendChild(opt);
		}
		
		var c = document.getElementById('loggerSelectContainer');
		
		if (c) {
		
			c.innerHTML = '';
			c.appendChild(select);
			
			if (env.isIE) {
				
				select.attachEvent("change", logger.showComponent);
				
			} else {
				
				select.addEventListener("change", logger.showComponent, false);
			}
		}
	};

	
	this.showComponent = function(e) {
		
		e.preventDefault();
		e = e.srcElement || e.target;
		
		drawContent(components[e.value]);
		
	};

	
	function drawContent(component) {
		
		if (!component) component = 'ALL';
		
		container.innerHTML = '';
		
		for (var i=0; i<cache[component].length; i++) {
			
			container.appendChild(cache[component][i]);					
		}
	}

	
	function printException(e) {

	 	var div = document.createElement('DIV');
	 		div.className = 'exception';

	 	var p = document.createElement('P');
	 		div.appendChild(p);
	 		
	 	var str = document.createElement('STRONG');
	 		str.innerHTML = e.name;
	 		p.appendChild(str);
	 		
	 	var p = document.createElement('P');
	 		div.appendChild(p);
	 		
	 	var em = document.createElement('EM');
	 		em.innerHTML = e.message;
	 		p.appendChild(em);
	 		
	 		var p = document.createElement('P');
	 		p.innerHTML = e.fileName + " ["+e.lineNumber+"]";
	 		div.appendChild(p);

	 	var pre = document.createElement('PRE');
	 		pre.innerHTML = e.stack;
	 		div.appendChild(pre);

	 	return div;
	}
	
	
	this.reset = function(e) {
		
		e.preventDefault();
		e = e.srcElement || e.target;
		e.blur();
		
		container.innerHTML = '';
	};
	
	
	this.hide = function(e) {
		
		e.preventDefault();
		e = e.srcElement || e.target;
		e.blur();
		
		if (container.style.display == 'none') {
			
			container.style.display = 'block';
			e.innerHTML = 'hide';
		}
		
		else {
			
			container.style.display = 'none';
			e.innerHTML = 'show';
		}
	};
};

logger = new logger();


function log(msg, state, component) {

	logger.addMsg(msg, state, component);
}



/*******************************************************************************
	UTIL
*******************************************************************************/

function util() {
	
	this.Version = '2.1';
	this.fired = false;

	this.init = function() {
		
		if (this.fired === false) {
		
			this.fired = true;
			
			logger.init();
			
			this.fixPNGs(document.body);
			this.fixMainNav();
	
			for (observer in this) {
				
				if (typeof util[observer].startUp == 'function') {
					
					try {
	
						log("STARTING ("+observer+")", 1, util[observer].toString());
						util[observer].startUp();
					}
					
					catch (e) {
						
						log(e);
					}
				}
			}
		}
	};
	
	
	this.fixPNGs = function(node) {

		if (env.browser == 'ie6') {
			
			var blank = "imgs/blank.gif";
		
			var imgs = node.getElementsByTagName('IMG');
			
			for (var i=0; i<imgs.length; i++) {
	
				if (imgs[i].src.indexOf('.png') != -1) {

					imgs[i].runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+imgs[i].src+"', sizingMethod='scale')";
					imgs[i].src = blank;
				}
			}
			
			var inp = node.getElementsByTagName('INPUT');
			
			for (var i=0; i<inp.length; i++) {

				if (inp[i].type == 'image' && inp[i].src.indexOf('.png') != -1) {

					inp[i].runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+inp[i].src+"', sizingMethod='crop')";
					inp[i].src = blank;
				}
			}
		}
	};
	
	this.fixMainNav = function() {

		if (env.browser == 'ie6') {
			
			var nav = document.getElementById('mainNav');
			
			if (nav) {
				
				var links = nav.getElementsByTagName('A');
				
				for (var i=0; i<links.length; i++) {
					
					if (links[i].parentNode.className != 'act') {
						
						links[i].attachEvent("onmouseover", function(e){e.srcElement.style.backgroundPosition='bottom left';});
						links[i].attachEvent("onmouseout", function(e){e.srcElement.style.backgroundPosition='top left';});
					}
				}
			}
		}
	};
};



/*******************************************************************************
	IMAGE-LOADER
*******************************************************************************/

var imageLoader = Class.create({
	
	img : null,
	int : null,
	successor : null,
	
	initialize : function() {},

	load : function(src, successor) {
		
		this.img = new Image();
		this.img.src = src;
		this.successor = successor;
		this.int = setInterval("util.imageLoader.checkState();", 100);		
	},
	
	checkState : function() {

		if (util.imageLoader.img.complete) {

			clearInterval(util.imageLoader.int);
			
			return util.imageLoader.successor(util.imageLoader.img);
		}
	}
});

util.prototype.imageLoader = new imageLoader();



/*******************************************************************************
	OBSERVER BASE-CLASS
*******************************************************************************/

var Observer = Class.create({
	
	name : '',
	cache : [],
	p : [],
	container : null,

	
	initialize : function(name) {

		this.name = name || 'OBSERVER';
		this.cache = [];
		this.container = null;
		
		// default properties
		this.p = [];
		this.p.duration = 0.5;
		this.p.transition = 'linear';
	},
	
	
	setProperty : function(key, value) {

		this.p[key] = value;
	},
	

	
	createContainer : function() {

		var prefix = this.p.prefix;
		
		if (!prefix) {			
			
			log("missing property 'prefix' - auto-generated", 1, this.name);
			prefix = 'prefix'+this.name;
		}
		
		this.container = new Element('DIV', {
			id: prefix+'_container'
		});
		
		// this.container.style.display = 'none';

		document.body.appendChild(this.container);
		return true;
	},
	
	
	toString : function() {

		return this.name;
	},
	
	
	startUp : function() {

		log("startup observer", 3);
	},
	
	update : function() {
		
		log("update observer", 3);
	},
	

	getDefaultConfig : function() {
		
		log("getDefaultConfig observer", 3);

		return {};
	},

	
	add : function(item) {
		
		var base = this.getDefaultConfig();

		for (key in base) {

			if (typeof base[key] == 'object' && base[key] !== null) {
				
				if (typeof item[key] == 'undefined') {
	
					item[key] = {};
				}
				
				for (sub in base[key]) {
					
					if (typeof item[key][sub] == 'undefined') {
						
						item[key][sub] = base[key][sub];
					}
				}

			} else {

				if (typeof item[key] == 'undefined') {

					item[key] = base[key];
				}
			}
		}

		var cid = this.cache.push(item)-1;
			item.cid = cid;	

		log("added item ["+cid+"]", 1, this.name);
		
		if (util.fired) {
			
			log("perform update", 1, this.name);
			this.update();
		}

		return cid;
	},
	
	
	remove : function(cid) {
		
		delete this.cache[cid];
		log("removed item ["+cid+"]", 1, this.name);
		
		if (util.fired) {
			
			log("perform update", 1, this.name);
			this.update();
		}
	}

});


