var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{	// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 	// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

function power (a, b) {
	var p = 1;
	for (var i = 0; i < b; ++i) {
		p *= a;
	}
	return p;
}

function floor_prec (val, precision) {
	var p = power (10, precision);
	return Math.ceil(val*p)/p;
}

function ceil_prec (val, precision) {
	var p = power (10, precision);
	return Math.ceiling(val*p)/p;
}

function round_prec (val, precision) {
	var p = power (10, precision);
	return Math.round(val*p) / p;
}

function subscribeInit() {
	var element = document.getElementById('text-email')
	if( element ){
		inputPlaceholder( element, element.value )
	}
}

function highlightInit() {
	var element = document.getElementById('highlight-top-needle')
	if( element ){
		inputPlaceholder( element, 'Type in your search words')
	}
}

function inputPlaceholder( element, text ) {
	element.onfocus = function() {
		if( element.value.length && element.value == text ){ element.value = ''; }
		element.select();
		cmnRemove_class( element, "passive" );
	}
	element.onblur = function() {
		if( !element.value.length ) {
			cmnSet_class( element, "passive" );
			element.value = text;
		}
	}
	element.value = '';
	element.onblur();
}

function hideSelectScreensaverButton () {
	var select = document.getElementById ('select-find-screensaver');
	var button = document.getElementById ('button-find-screensaver');
	if (button) {button.style.display="none"}
	if (select) {select.style.width="100%"}
}

var ie = (document.all)? true : false
var nn6 = (!ie && document.getElementById)? true : false
var nn4 = (document.layers)? true : false

function popupWin(uri, wdt, hgt, scrollbars) {
   if (!scrollbars) scrollbars = "no"
   var posCode = ''
   if ( nn4 || nn6 || ie) {
      if ( (screen.height < 481) && (hgt > 400) ) { hgt = 400 }
      if ( hgt > screen.height-80) {hgt = screen.height-80}
      if ( wdt > screen.width) {wdt = screen.width}
      posX = Math.round((screen.width - wdt) / 2)
      posY = Math.round((screen.height - hgt) / 2)
      posCode = (nn4 || nn6)? ",screenX="+posX+",screenY="+posY : ",left="+posX+",top="+posY
   }
   popupedWin = window.open(uri, "", "status=no,menubar=no,toolbar=no,resizable=yes,scrollbars=" + scrollbars + ",location=no,width="+wdt+",height="+hgt+posCode)
   popupedWin.focus()
}

function getCookie(name) {
  var p = name + "=";
  var si = document.cookie.indexOf(p);
  if (si == -1) return null;
  var ei = document.cookie.indexOf(";", si + p.length);
  if (ei == -1) ei = document.cookie.length;
  return unescape(document.cookie.substring(si + p.length, ei));
}


function cmnSwitch_class( eOn, sClass_name, sInstead ){
	if( cmnMatch_class( eOn, sClass_name ) ){
		cmnSet_class( eOn, sInstead, sClass_name );
	}else{
		cmnSet_class( eOn, sClass_name, sInstead );
	}
}

function cmnRemove_class( eOn, sClass_name ){
	cmnSet_class( eOn, "", sClass_name );
}

function cmnSet_class( eOn, sClass_name, sInstead ){
	if( eOn ){
		sClass_name = ( sClass_name.length ) ? sClass_name.replace( /(^\s+|\s+$)/, "" ) : "";
		if( eOn.className.length ){
			var sOld = sClass_name;
			if( sInstead && sInstead.length ){
				sInstead = sInstead.replace( /\s+(\S)/g, "|$1" );
				if( sOld ){
					sOld += "|";
				}
				sOld += sInstead;
			}
			eOn.className = eOn.className.replace( new RegExp("(^|\\s+)(" + sOld +")($|\\s+)", "g"), "$1" );
		}
		eOn.className += ( eOn.className.length && sClass_name ? " " : "" ) + sClass_name;
	}
}

function cmnMatch_class( eOn, sClass_name ){
	return ( sClass_name && eOn.className && eOn.className.length && eOn.className.match( new RegExp("(^|\\s+)(" + sClass_name +")($|\\s+)") ) );
}

function mouseout(anchor)
{
	return;
	if (normalbg[anchor.id]==null) return;
	anchor.style.backgroundImage = "url('" + normalbg[anchor.id] + "')";
}


String.prototype.padding = function(n, c)
{
	var val = this.valueOf();
	if ( ! n ) {
		return val;
	}
	if ( ! c ) {
		c = " ";
	}
	var pad = String(c).charAt(0).repeat(Math.abs(n) - this.length);
	return (n < 0) ? pad + val : val + pad;
}


function sprintf()
{
	var args = arguments;
	var frmt = arguments[0].replace(/%%/g, "\0\0");
	var result = "", prev = 0, index = 0;
	var re = /%(\d+[\$#])?([+-])?('.|0| )?(\d*)(\.\d*)?([bcdfosuxX])/g;
	var x;
	while (x = re.exec(frmt)) {
		for (var i = 0; i < x.length; i++) if (x[i] == undefined) x[i] = "";
		index++;
		var ins = (x[1]) ? args[x[1].substring(0, x[1].length - 1)] : args[index];
		switch (x[6]) {
		case "b":
			ins = Number(ins).bin();
			break;
		case "c":
			ins = String.fromCharCode(ins);
			break;
		case "d":
		case "u":
			ins = Number(ins).dec();
			break;
		case "f":
			ins = Number(ins);
			if (x[5]) {
				ins = ins.toFixed(x[5].substr(1));
			} else if (x[4]) {
				ins = ins.toExponential(x[4]);
			} else {
				ins = ins.toExponential();
			}
			break;
		case "o":
			ins = Number(ins).oct();
			break;
		case "s":
			ins = String(ins);
			break;
		case "x":
			ins = Number(ins).hexl();
			break;
		case "X":
			ins = Number(ins).hex();
			break;
		}
		result += frmt.substring(prev, x.index);
		prev = x.index + x[0].length;
		result += ins.padding(x[2] + x[4], x[3].substr(x[3].length - 1));
	}
	if ( prev < frmt.length ) {
		result += frmt.substr(prev);
	}
	result = result.replace(/\0\0/g, "%");
	return result;
}

function switchVisibility (element) {
	element = document.getElementById('requirements-body');
	if (element.style.display == "block") {
		element.style.display = "none";
	}
	else {
		element.style.display = "block";
	}
	cmnSwitch_class(document.getElementById("requirements-anchor"), "expanded", "collapsed");
	return false;
}

if(typeof deconcept == "undefined") var deconcept = new Object();
if(typeof deconcept.util == "undefined") deconcept.util = new Object();
if(typeof deconcept.SWFObjectUtil == "undefined") deconcept.SWFObjectUtil = new Object();
deconcept.SWFObject = function(swf, id, w, h, ver, c, useExpressInstall, quality, xiRedirectUrl, redirectUrl, detectKey){
	if (!document.getElementById) { return; }
	this.DETECT_KEY = detectKey ? detectKey : 'detectflash';
	this.skipDetect = deconcept.util.getRequestParameter(this.DETECT_KEY);
	this.params = new Object();
	this.variables = new Object();
	this.attributes = new Array();
	if(swf) { this.setAttribute('swf', swf); }
	if(id) { this.setAttribute('id', id); }
	if(w) { this.setAttribute('width', w); }
	if(h) { this.setAttribute('height', h); }
	if(ver) { this.setAttribute('version', new deconcept.PlayerVersion(ver.toString().split("."))); }
	this.installedVer = deconcept.SWFObjectUtil.getPlayerVersion();
	if(c) { this.addParam('bgcolor', c); }
	var q = quality ? quality : 'high';
	this.addParam('quality', q);
	this.setAttribute('useExpressInstall', useExpressInstall);
	this.setAttribute('doExpressInstall', false);
	var xir = (xiRedirectUrl) ? xiRedirectUrl : window.location;
	this.setAttribute('xiRedirectUrl', xir);
	this.setAttribute('redirectUrl', '');
	if(redirectUrl) { this.setAttribute('redirectUrl', redirectUrl); }
}
deconcept.SWFObject.prototype = {
	setAttribute: function(name, value){
		this.attributes[name] = value;
	},
	getAttribute: function(name){
		return this.attributes[name];
	},
	addParam: function(name, value){
		this.params[name] = value;
	},
	getParams: function(){
		return this.params;
	},
	addVariable: function(name, value){
		this.variables[name] = value;
	},
	getVariable: function(name){
		return this.variables[name];
	},
	getVariables: function(){
		return this.variables;
	},
	getVariablePairs: function(){
		var variablePairs = new Array();
		var key;
		var variables = this.getVariables();
		for(key in variables){
			variablePairs.push(key +"="+ variables[key]);
		}
		return variablePairs;
	},
	getSWFHTML: function() {
		var swfNode = "";
		if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { // netscape plugin architecture
			if (this.getAttribute("doExpressInstall")) { this.addVariable("MMplayerType", "PlugIn"); }
			swfNode = '<embed type="application/x-shockwave-flash" src="'+ this.getAttribute('swf') +'" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'"';
			swfNode += ' id="'+ this.getAttribute('id') +'" name="'+ this.getAttribute('id') +'" ';
			var params = this.getParams();
			 for(var key in params){ swfNode += [key] +'="'+ params[key] +'" '; }
			var pairs = this.getVariablePairs().join("&");
			 if (pairs.length > 0){ swfNode += 'flashvars="'+ pairs +'"'; }
			swfNode += '/>';
		} else { // PC IE
			if (this.getAttribute("doExpressInstall")) { this.addVariable("MMplayerType", "ActiveX"); }
			swfNode = '<object id="'+ this.getAttribute('id') +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'">';
			swfNode += '<param name="movie" value="'+ this.getAttribute('swf') +'" />';
			var params = this.getParams();
			for (var key in params) {
			 swfNode += '<param name="'+ key +'" value="'+ params[key] +'" />';
			}
			var pairs = this.getVariablePairs().join("&");
			if(pairs.length > 0) {swfNode += '<param name="flashvars" value="'+ pairs +'" />';}
			swfNode += "</object>";
		}
		return swfNode;
	},
	write: function(elementId){
		if(this.getAttribute('useExpressInstall')) {
			// check to see if we need to do an express install
			var expressInstallReqVer = new deconcept.PlayerVersion([6,0,65]);
			if (this.installedVer.versionIsValid(expressInstallReqVer) && !this.installedVer.versionIsValid(this.getAttribute('version'))) {
				this.setAttribute('doExpressInstall', true);
				this.addVariable("MMredirectURL", escape(this.getAttribute('xiRedirectUrl')));
				document.title = document.title.slice(0, 47) + " - Flash Player Installation";
				this.addVariable("MMdoctitle", document.title);
			}
		}
		if(this.skipDetect || this.getAttribute('doExpressInstall') || this.installedVer.versionIsValid(this.getAttribute('version'))){
			var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId;
			n.innerHTML = this.getSWFHTML();
			return true;
		}else{
			if(this.getAttribute('redirectUrl') != "") {
				document.location.replace(this.getAttribute('redirectUrl'));
			}
		}
		return false;
	}
}

/* ---- detection functions ---- */
deconcept.SWFObjectUtil.getPlayerVersion = function(){
	var PlayerVersion = new deconcept.PlayerVersion([0,0,0]);
	if(navigator.plugins && navigator.mimeTypes.length){
		var x = navigator.plugins["Shockwave Flash"];
		if(x && x.description) {
			PlayerVersion = new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split("."));
		}
	}else{
		// do minor version lookup in IE, but avoid fp6 crashing issues
		// see http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
		try{
			var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		}catch(e){
			try {
				var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
				PlayerVersion = new deconcept.PlayerVersion([6,0,21]);
				axo.AllowScriptAccess = "always"; // throws if player version < 6.0.47 (thanks to Michael Williams @ Adobe for this code)
			} catch(e) {
				if (PlayerVersion.major == 6) {
					return PlayerVersion;
				}
			}
			try {
				axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			} catch(e) {}
		}
		if (axo != null) {
			PlayerVersion = new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
		}
	}
	return PlayerVersion;
}
deconcept.PlayerVersion = function(arrVersion){
	this.major = arrVersion[0] != null ? parseInt(arrVersion[0]) : 0;
	this.minor = arrVersion[1] != null ? parseInt(arrVersion[1]) : 0;
	this.rev = arrVersion[2] != null ? parseInt(arrVersion[2]) : 0;
}
deconcept.PlayerVersion.prototype.versionIsValid = function(fv){
	if(this.major < fv.major) return false;
	if(this.major > fv.major) return true;
	if(this.minor < fv.minor) return false;
	if(this.minor > fv.minor) return true;
	if(this.rev < fv.rev) return false;
	return true;
}
/* ---- get value of query string param ---- */
deconcept.util = {
	getRequestParameter: function(param) {
		var q = document.location.search || document.location.hash;
		if(q) {
			var pairs = q.substring(1).split("&");
			for (var i=0; i < pairs.length; i++) {
				if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
					return pairs[i].substring((pairs[i].indexOf("=")+1));
				}
			}
		}
		return "";
	}
}
/* fix for video streaming bug */
deconcept.SWFObjectUtil.cleanupSWFs = function() {
	if (window.opera || !document.all) return;
	var objects = document.getElementsByTagName("OBJECT");
	for (var i=0; i < objects.length; i++) {
		objects[i].style.display = 'none';
		for (var x in objects[i]) {
			if (typeof objects[i][x] == 'function') {
				objects[i][x] = function(){};
			}
		}
	}
}
// fixes bug in fp9 see http://blog.deconcept.com/2006/07/28/swfobject-143-released/
deconcept.SWFObjectUtil.prepUnload = function() {
	__flash_unloadHandler = function(){};
	__flash_savedUnloadHandler = function(){};
	if (typeof window.onunload == 'function') {
		var oldUnload = window.onunload;
		window.onunload = function() {
			deconcept.SWFObjectUtil.cleanupSWFs();
			oldUnload();
		}
	} else {
		window.onunload = deconcept.SWFObjectUtil.cleanupSWFs;
	}
}
/*
if (typeof window.onbeforeunload == 'function') {
	var oldBeforeUnload = window.onbeforeunload;
	window.onbeforeunload = function() {
		deconcept.SWFObjectUtil.prepUnload();
		oldBeforeUnload();
	}
} else {
	window.onbeforeunload = deconcept.SWFObjectUtil.prepUnload;
}
*/	
/* add Array.push if needed (ie5) */
if (Array.prototype.push == null) { Array.prototype.push = function(item) { this[this.length] = item; return this.length; }}

/* add some aliases for ease of use/backwards compatibility */
var getQueryParamValue = deconcept.util.getRequestParameter;
var FlashObject = deconcept.SWFObject; // for legacy support
var SWFObject = deconcept.SWFObject;

function flashExists()
{
	return deconcept.SWFObjectUtil.getPlayerVersion().major > 6;
}

function getFlashMajorVersion()
{
	return deconcept.SWFObjectUtil.getPlayerVersion().major;
}

	//alert (deconcept.SWFObjectUtil.getPlayerVersion().major + "." + deconcept.SWFObjectUtil.getPlayerVersion().minor + "." + deconcept.SWFObjectUtil.getPlayerVersion().rev);
	arTopScreensaverIdents = new Array();
	arTopScreensaverFilenames = new Array();
	arScreenshotAlts = new Array();
	arActivatedFlashes = new Array();
	
	curTopScreensaver = 0;
	countTopScreensavers = 0;
	function prevTopScreensaver()
	{
		nextTop = (curTopScreensaver + countTopScreensavers - 1) % countTopScreensavers
		switchNextTopScreensaver()
	}

	function nextTopScreensaver()
	{
		nextTop = (curTopScreensaver + 1) % countTopScreensavers
		switchNextTopScreensaver()
	}
	
	function switchNextTopScreensaver()
	{
		for (k=0; k<countTopScreensavers; ++k) {
			if (k == nextTop) {
				document.getElementById("flash" + k).style.display = "block"
				activateFlash(k);
			} else {
				document.getElementById("flash" + k).style.display = "none"
			}
		}
		curTopScreensaver = nextTop;
	}
	
	function activateFlash (count)
	{
		if (arActivatedFlashes[count]) return;
		swfObject = new SWFObject();
		swfNode = '';
		if (getFlashMajorVersion() > 6) {
			flashvars = 'URLlink=/data/screensavers/' + arTopScreensaverIdents[count] + '/' + 'main-de' + '.' + 'swf' + '&url=/' + arTopScreensaverFilenames[count] + '.html&amp;onclick=trackAction&amp;clickparam=top-screensaver/1/flash-click/' + arTopScreensaverFilenames[count];
			flash = '/swf/loading.swf';
			//flash = '/swf/loading.swf?' + flashvars;
			swfNode += '<object type="application/x-shockwave-flash" data="' + flash + '" name="object">';
			swfNode += '<param name="movie" value="' + flash + '">';
			swfNode += '<param name="flashvars" value="' + flashvars + '">';
			swfNode += '<div class="flash-alt-text">Loading...</div>';
			swfNode += '</object>';
		} else {
			flashvars = 'url=/' + arTopScreensaverFilenames[count] + '.html&amp;onclick=trackAction&amp;clickparam=top-screensaver/1/flash-click/' + arTopScreensaverFilenames[count];
			flash = '/data/screensavers/' + arTopScreensaverIdents[count] + '/' + 'main-de' + '.swf';
			swfNode += '<object type="application/x-shockwave-flash" data="' + flash + '" name="object">';
			swfNode += '<param name="movie" value="' + flash + '">';
			swfNode += '<param name="flashvars" value="' + flashvars + '">';
			swfNode += '<a href="/' + arTopScreensaverFilenames[count] + '.html" class="flash-alt-image" onclick="trackAction(\'top-screensaver/1/image-click/' + arTopScreensaverIdents[count] + '\')"><img width="391" height="179" src="/data/screensavers/' + arTopScreensaverIdents[count] + '/' + 'alt-flash-de.' + 'jpg" alt="' + arScreenshotAlts[count] + '"/></a>';
			swfNode += '</object>';
		} 
		document.getElementById("flash" + count).innerHTML = swfNode;
		arActivatedFlashes[count] = true;
	}
	function doHighlightUp() {
		if (timeout) clearTimeout(timeout);
		timeout = setTimeout(doHighlight, 10);
	}
	
	function doHighlight() {
		CountMatches(document.getElementById('highlight-top-needle').value, true);
	}
		
	function CountMatches(needle, bHighlight) {
		if (needle == "") {
			//document.getElementById("highlight-top-info").innerHTML = "";
			//cmnRemove_class(document.getElementById("highlight-top-needle"), "emptySet");
		}
		var nMatches = 0;
		for (var i in arLabelIds) {
			var reg = new RegExp("(" + needle + ")", "ig");
			if (i.search(reg) != -1) {
				nMatches ++;
				if (bHighlight) {
					document.getElementById(arLabelIds[i]).innerHTML = i.replace(reg, "<span class='highlight'>$1</span>" );
				} else {
					document.getElementById(arLabelIds[i]).innerHTML = i;
				}
			} else {
				document.getElementById(arLabelIds[i]).innerHTML = i;
			}
		}
	
		if (bHighlight) {
			if (nMatches) {
				cmnRemove_class(document.getElementById("highlight-top-needle"), "emptySet");
				document.getElementById("highlight-top-info").innerHTML = (needle=="") ? "" : " &mdash; <strong>"  + nMatches + "</strong>" + " screensaver" + (nMatches>1?"s":"") + " found";
			} else {
				cmnSet_class(document.getElementById("highlight-top-needle"), "emptySet");
				document.getElementById("highlight-top-info").innerHTML = "";
			}
		}
		return nMatches;
	}

