/* global */ 

if (top != self) {
	top.location.replace(self.location.href);
}

HTMLElement.prototype.hasClass = function(cls) {
	return this.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
HTMLElement.prototype.addClassName = function(cls) {
	if (!this.hasClass(cls)) this.className += " " + cls;
}
HTMLElement.prototype.removeClassName = function(cls) {
	if (this.hasClass(cls)) {
		var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
		this.className = this.className.replace(reg, ' ');
	}
}

function addLoadEvent(func) { 
	var oldonload = window.onload; 
	
	if (typeof window.onload != 'function') {
		window.onload = func; 
	}
	else { 
		window.onload = function() { 
			if (oldonload) { 
				oldonload(); 
			} 

			func(); 
		} 
	} 
}

/* XMLHttpRequest */

function loadHttpRequest(url, func) {
	var xhr = null;
	
	function xhr_handler() {
	    if (xhr.readyState == 4) {
	        func(xhr);
	    }
	}
	
	if (window.XMLHttpRequest) {
		xhr = new XMLHttpRequest();
		xhr.onreadystatechange = xhr_handler;
		xhr.open("GET", url, true);
		xhr.send(null);
	}
	else if (window.ActiveXObject) {
		xhr = new ActiveXObject("Microsoft.XMLHTTP");
		xhr.onreadystatechange = xhr_handler;
		xhr.open("GET", url, true);
		xhr.send();
	}
}

/* Core */
if (typeof (FC) == "undefined") {
    FC = {}
}

FC.Detector = {
	_supportsThreeD: false,
    supportsThreeD: function () {
        try {
            this._supportsThreeD = false;
            if ("styleMedia" in window) {
                this._supportsThreeD = window.styleMedia.matchMedium("(-webkit-transform-3d)");
            } else {
                if ("media" in window) {
                    this._supportsThreeD = window.media.matchMedium("(-webkit-transform-3d)");
                }
            }
            if (!this._supportsThreeD) {
                if (!document.getElementById("supportsThreeDStyle")) {
                    var a = document.createElement("style");
                    a.id = "supportsThreeDStyle";
                    a.textContent = "@media (transform-3d),(-o-transform-3d),(-moz-transform-3d),(-ms-transform-3d),(-webkit-transform-3d) { #supportsThreeD { height:3px } }";
                    document.querySelector("head").appendChild(a);
                }
                if (!(div = document.querySelector("#supportsThreeD"))) {
                    div = document.createElement("div");
                    div.id = "supportsThreeD";
                    document.body.appendChild(div);
                }
                this._supportsThreeD = (div.offsetHeight === 3);
            }
            return this._supportsThreeD;
        } catch (b) {
            return false;
        }
    }
}
    
HTMLElement.prototype.setVendorPrefixStyle = function(f, e) {
	if (f.match(/^webkit/i)) {
	    f = f.replace(/^webkit/i, "");
	} else {
	    if (f.match(/^moz/i)) {
	        f = f.replace(/^moz/i, "");
	    } else {
	        if (f.match(/^ms/i)) {
	            f = f.replace(/^ms/i, "");
	        } else {
	            if (f.match(/^o/i)) {
	                f = f.replace(/^o/i, "");
	            } else {
	                if (f.match("-")) {
	                    var b = f.split("-"),
	                        d = b.length;
	                    f = "";
	                    for (var a = 0; a < b.length; a++) {
	                        f += b[a].charAt(0).toUpperCase() + b[a].slice(1);
	                    }
	                } else {
	                    f = f.charAt(0).toUpperCase() + f.slice(1);
	                }
	            }
	        }
	    }
	}
	if (e.match("-webkit-")) {
	    e = e.replace("-webkit-", "-vendor-");
	} else {
	    if (e.match("-moz-")) {
	        e = e.replace("-moz-", "-vendor-");
	    } else {
	        if (e.match("-ms-")) {
	            e = e.replace("-ms-", "-vendor-");
	        } else {
	            if (e.match("-o-")) {
	                e = e.replace("-o-", "-vendor-");
	            }
	        }
	    }
	}
	this.style["webkit" + f] = e.replace("-vendor-", "-webkit-");
	this.style["Moz" + f] = e.replace("-vendor-", "-moz-");
	this.style["ms" + f] = e.replace("-vendor-", "-ms-");
	this.style["O" + f] = e.replace("-vendor-", "-o-");
	this.style[f] = e;
	f = f.charAt(0).toLowerCase() + f.slice(1);
	this.style[f] = e;
};
HTMLElement.prototype.setVendorPrefixTransform = function(a, c) {
    if (a == "none") {
        this.setVendorPrefixStyle("transform", "none");
        return;
    }
    if (a == null) {
        a = 0;
    }
    if (c == null) {
        c = 0;
    }
    if (FC.Detector.supportsThreeD()) {
        this.setVendorPrefixStyle("transform", "translate3d(" + a + ", " + c + ", 0)");
    } else {
        this.setVendorPrefixStyle("transform", "translate(" + a + ", " + c + ")");
    }
};

/*
function getChildren(n, skipMe) {
    var r = [];
    var elem = null;
    for ( ; n; n = n.nextSibling) 
       if ( n.nodeType == 1 && n != skipMe)
          r.push(n);        
    return r;
};
function getSiblings(n) {
    return getChildren(n.parentNode.firstChild, n);
}
*/

function setActiveClass(e) {
	var a = e.parentNode.parentNode.getElementsByClassName('hero-gallery');
	
	for (var i = 0 ; i < a.length; i++) {
		var n = a[i];
		
		if (n.nodeType == 1) {
			n.removeClassName('active');
		}
	}
	
	e.addClassName('active');
}

/* twitter and facebook buttons */

function share_button() {
/*
	if (document.getElementById('tweetmeme_button')) {
		document.getElementById('tweetmeme_button').innerHTML = "<iframe src=\"http://api.tweetmeme.com/button.js?url=http%3A//www.falkor.com/&amp;style=compact\" height=\"20\" width=\"90\" frameborder=\"0\" scrolling=\"no\" style=\"margin-top: 1px; margin-left: 4px;\"></iframe>";
	}
*/
	
	if (document.getElementById('facebook_button')) {
		document.getElementById('facebook_button').innerHTML = "<iframe src=\"http://www.facebook.com/plugins/like.php?href=http://www.falkor.com/&amp;layout=button_count&amp;show-faces=true&amp;width=260&amp;action=like&amp;font=lucida+grande&amp;colorscheme=light\" scrolling=\"no\" frameborder=\"0\" allowtransparency=\"true\" style=\"border:none; overflow:hidden; width:90px; height:28px; margin:-1px 0 0 -8px;\"></iframe>";
	}
}

addLoadEvent(share_button);

/* canvas */

function _newCanvas(width, height) {
	var canvas = document.createElement('canvas');
	canvas.width = width;
	canvas.height = height;
	return canvas;
}

function _renderToCanvas() {
	return function (width, height, renderFunction) {
	    var canvas = document.createElement('canvas');
	    canvas.width = width;
	    canvas.height = height;
	    renderFunction(canvas.getContext('2d'));
	    return canvas;
	};
}

/*
Dc' = Sc·(1 - Da) + Dc·(1 - Sa) + Sc·Dc
Da' = Sa + Da - Sa·Da
*/
function doImagePressed(canvas, input) {
	var context = canvas.getContext('2d');
	var output = context.createImageData(canvas.width, canvas.height);
	var w = input.width;
	var h = input.height;
	var inputData = input.data;
	var outputData = output.data;
	for (var y = 0; y < h; y += 1) {
		for (var x = 0; x < w; x += 1) {
			var pixel = (y * w + x) * 4;
			if (inputData[pixel + 3]) {
				var a = inputData[pixel + 3] / 255;
				var da = a * 0.2;
				var da1 = (1.0 - da);

				outputData[pixel] = inputData[pixel] * a * da1;
				outputData[pixel + 1] = inputData[pixel + 1] * a * da1;
				outputData[pixel + 2] = inputData[pixel + 2] * a * da1;
				outputData[pixel + 3] = (a + da - (a * da)) * 255;
			}
		}
	}
	return output;
}

function renderImagePressed(src, width, height) {
	var image = new Image();
	image.src = src;
	
	var canvas = _newCanvas(width, height);
	var context = canvas.getContext('2d');
	context.clearRect(0, 0, canvas.width, canvas.height);
	context.drawImage(image, 0, 0, canvas.width, canvas.height);
	
	var input;
	try {
		input = context.getImageData(0, 0, canvas.width, canvas.height);
	}
	catch (e) {
		netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
		input = context.getImageData(0, 0, canvas.width, canvas.height);
	}
	var output = doImagePressed(canvas, input);
	context.putImageData(output, 0, 0);
	return canvas;
}

/* download pop up */

var downloadPopUpHideTimer = '';
var downloadOverflowHiddenTimer = '';

function hideDownloadPopUp() {
	downloadPopUpHideTimer = setTimeout('_hideDownloadPopUp()', 50);
}

function __hideDownloadPopUp() {
	if (downloadOverflowHiddenTimer != '') {
	    clearTimeout(downloadOverflowHiddenTimer);
	    downloadOverflowHiddenTimer = '';
	}
	
	var p = document.getElementById('dpup');
	p.className = 'move-fade up transparent overflow-hidden';
/*
	p.removeEventListener('transitionend', __hideDownloadPopUp, true);
	p.removeEventListener('webkitTransitionEnd', __hideDownloadPopUp, true);
*/
}

function _hideDownloadPopUp() {
	if (downloadPopUpHideTimer != '') {
		var d = document.getElementById('dmenu');
		d.className = null;
		var p = document.getElementById('dpup');
		p.className = 'move-fade up transparent';
/*
		p.addEventListener('transitionend', __hideDownloadPopUp, true);
		p.addEventListener('webkitTransitionEnd', __hideDownloadPopUp, true);
*/
		downloadOverflowHiddenTimer = setTimeout('__hideDownloadPopUp()', 501);
		var b = document.getElementById('dbox');
		b.onmouseover = function(){};
		b.onmouseout = function(){};
		
		downloadPopUpHideTimer = '';
	}
}

function showDownloadPopUp() {
	var p = document.getElementById('dpup');
/*
	p.removeEventListener('transitionend', __hideDownloadPopUp, true);
	p.removeEventListener('webkitTransitionEnd', __hideDownloadPopUp, true);
*/
		
	if (downloadPopUpHideTimer != '') {
		clearTimeout(downloadPopUpHideTimer);
		downloadPopUpHideTimer = '';
	}
	
	if (downloadOverflowHiddenTimer != '') {
		clearTimeout(downloadOverflowHiddenTimer);
		downloadOverflowHiddenTimer = '';
	}
	
	var d = document.getElementById('dmenu');
	d.className = 'hover';
	p.className = 'move-fade opaque';
	var b = document.getElementById('dbox');
	b.onmouseover = function() {
		showDownloadPopUp();
	};
	b.onmouseout = hideDownloadPopUp;
}

function showMenuBackground(e) {
	if (e.className == 'last') {
		e.className = 'last hover';
	}
	else {
		e.className = 'hover';
	}
}

function hideMenuBackground(e) {
	if (e.className == 'last hover') {
		e.className = 'last';
	}
	else {
		e.className = null;
	}
}

function hideZoom(e) {
	e.className = 'zoom-fade small transparent'
}

function showZoom(e) {
	e.className = 'zoom-fade opaque'
}

/* normal pop-up */

function getAbsolutePosition(obj) {
	var curleft = curtop = 0;
	
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	
	return [curleft, curtop];
}

var pTimer = null;
var activePopUp = null;

function showPopUp(id) {
/* 	console.log('showPopUp ' + id); */
	clearTimeout(pTimer);
	pTimer = setTimeout('_showPopUp(\'' + id + '\')', 50);
}

function _showPopUp(id) {
/* 	console.log('_showPopUp ' + id); */
	if (id == activePopUp) {
		return;
	}
	
	_hidePopUp();
	setTimeout('__showPopUp(\'' + id + '\')', 1);
}

function __showPopUp(id) {
/* 	console.log('__showPopUp ' + id); */
	var o = document.getElementById(id);

	var left = o.offsetLeft;
	var top = o.offsetTop;
	var element = document.getElementById(id + '-popup');
	
	left += (o.clientWidth - element.clientWidth) / 2;
	top += o.clientHeight - 40; 
	
	element.style.left = left + 'px';
	element.style.top = top + 'px';
	element.className = 'pbox n unhide';
	element.style.visibility = 'visible';
	element.style.zIndex = 997;
	
	activePopUp = id;
}

function hidePopUp() {
/* 	console.log('hidePopUp ' + activePopUp); */
	clearTimeout(pTimer);
	pTimer = setTimeout('_hidePopUp()', 50);
}

function _hidePopUp() {
/* 	console.log('_hidePopUp ' + activePopUp); */
	if (activePopUp == null) {
		return;
	}
	
	var w = document.getElementById(activePopUp + '-popup');
	
	w.className = 'pbox n';

	setTimeout('__hidePopUp(\'' + activePopUp + '\')', 501);
	activePopUp = null;
}

function __hidePopUp(id) {
/* 	console.log('__hidePopUp ' + id); */
	var w = document.getElementById(id + '-popup');
	
	if (activePopUp != id) {
		w.className = 'pbox n';
		w.style.visibility = 'hidden';
		w.style.zIndex = 0;
	}
}

/* features pop-up */

var fpTimer = null;
var mpTimer = null;
var activeFPopUp = null;

function showFPopUp(id) {
	clearTimeout(fpTimer);
	fpTimer = setTimeout('_showFPopUp(\'' + id + '\')', 100);
	
	clearTimeout(mpTimer);
	
	for (var _id in mps) {
		if (_id != id) {
			document.getElementById(_id).style.zIndex = 9;
			document.getElementById(_id + '-blip').style.zIndex = 8;
		}
	}
}

function _showFPopUp(id) {
	if (id == activeFPopUp) {
		return;
	}
	
	_hideFPopUp();
	setTimeout('__showFPopUp(\'' + id + '\')', 1);
}

function __showFPopUp(id) {
	document.getElementById(id).style.zIndex = 999;
	document.getElementById(id + '-blip').style.zIndex = 998;
	
	var mp = document.getElementById(id);
	var left = mp.style.left.replace(/[^0-9\-]/g, '');
	var top = mp.style.top.replace(/[^0-9\-]/g, '');
	var element = document.getElementById(id + '-p');
	
	left -= (element.clientWidth / 2) - 21;
	top -= element.clientHeight + 8; 
	
	element.style.left = left + 'px';
	element.style.top = top + 'px';
	element.className = 'pbox f unhide';
	element.style.visibility = 'visible';
	element.style.zIndex = 997;
	
	activeFPopUp = id;
}

function hideFPopUp() {
	clearTimeout(fpTimer);
	fpTimer = setTimeout('_hideFPopUp()', 100);
	
	clearTimeout(mpTimer);
	mpTimer = setTimeout('restoreMPs()', 501);
}

function _hideFPopUp() {
	if (activeFPopUp == null) {
		return;
	}
	
	document.getElementById(activeFPopUp).className = 'mp visited';
	document.getElementById(activeFPopUp + '-blip').className = 'mp blip visited';
	
	var w = document.getElementById(activeFPopUp + '-p');
	
	w.className = 'pbox f';
	
/*
	w.addEventListener('transitionend', function() {
		__hideFPopUp(id);
		w.removeEventListener('transitionend', arguments.callee, true);
		w.removeEventListener('webkitTransitionEnd', arguments.callee, true);
	}, true);
	w.addEventListener('webkitTransitionEnd', function() {
		__hideFPopUp(id);
		w.removeEventListener('transitionend', arguments.callee, true);
		w.removeEventListener('webkitTransitionEnd', arguments.callee, true);
	}, true);
*/
	
	// for browsers that don't support animation
	setTimeout('__hideFPopUp(\'' + activeFPopUp + '\')', 501);
	activeFPopUp = null;
}

function __hideFPopUp(id) {
	var w = document.getElementById(id + '-p');
	
	if (activeFPopUp != id) {
		w.style.visibility = 'hidden';
		w.style.zIndex = 0;
	}
}

function restoreMPs() {
	for (var _id in mps) {
		document.getElementById(_id).style.zIndex = 100;
		document.getElementById(_id + '-blip').style.zIndex = 99;
	}
}

/* activation code lookup */

function findActivationCode() {
	document.getElementById('activation-result').className = 'hidden';
	document.getElementById('activation-progress').className = 'ipbar';
	loadHttpRequest('http://www.falkor.com/lookup.php?email=' + document.lookup.email.value, function(xhr){
		document.lookup.email.value = null;
		document.getElementById('activation-progress').className = 'hidden';
		
		if (xhr.status == 200) {
			var json_object = JSON.parse(xhr.responseText);
			
			if (json_object) {
				if (json_object.error == 0) {
					document.getElementById('activation-result').className = 'good';
					document.getElementById('activation-result').innerHTML = json_object.message;
				}
				else {
					document.getElementById('activation-result').className = 'bad';
					document.getElementById('activation-result').innerHTML = json_object.message;
				}
				
				return;
			}
		}
		
		document.getElementById('activation-result').className = 'bad';
		document.getElementById('activation-result').innerHTML = 'Error';
	});
}

