var transition = false;


/** enables $ for getelementbyid
*********************************************************************************/
function $(id) {return document.getElementById(id)}


/** checks if int
*********************************************************************************/
function intval(text)   {var zahl = parseInt(text,10);if (isNaN(zahl)) {zahl = 0;}return zahl;}


/** deactivates the propagation
*********************************************************************************/
function noBubble(event) {
    if (event) {
        if(event.preventDefault)
            event.preventDefault();
        event.returnValue = false;
        if (event.stopPropagation) event.stopPropagation();
        else event.cancelBubble = true;
    }
    return false;
};


/** interpolator klasse
----------------------------------------------------------------------------------
Ruft einen callback auf von 0-100% in einem gewissen Zeitraum
*********************************************************************************/
var CInterpolator;
(function() {
    if(!CInterpolator)
        CInterpolator = new Object();
    CInterpolator.mCallbacks=   {};

    CInterpolator.interpolate =   function (id, duration, callback)
    {
        if(CInterpolator.mCallbacks[id]) {
            if(CInterpolator.mCallbacks[id].timer)
                clearInterval(CInterpolator.mCallbacks[id].timer);
            var percent = Math.min(CInterpolator.mCallbacks[id].duration, new Date().getTime() - CInterpolator.mCallbacks[id].start) / CInterpolator.mCallbacks[id].duration;
            var start = new Date().getTime() + (percent*CInterpolator.mCallbacks[id].duration)-CInterpolator.mCallbacks[id].duration;
        } else {
            var start = new Date().getTime();
        }
        CInterpolator.mCallbacks[id]   =   {"duration": duration, "timer": setInterval(function(){CInterpolator._interpolate(id)}, 25), "start":start, "callback": callback};
    };
    CInterpolator._interpolate =   function (id) {
      try {
        var _this   =   CInterpolator.mCallbacks[id];
        var percent =   100*Math.min(_this.duration, new Date().getTime() - _this.start) / _this.duration;
        if (percent < 100) {
            _this.callback(percent);
        } else {
            if(_this.timer) {clearInterval(_this.timer);_this.timer=0;}
            _this.callback(100);
            delete(CInterpolator.mCallbacks[id]);
        }
      } catch(e) {};
    };
})();


/** checks if the browser has transition and background size support
*********************************************************************************/
function hasProperty( prop, callback ) {
    var uc_prop = prop.charAt(0).toUpperCase() + prop.substr(1);
    var m_style = document.createElement("DIV").style;
    function test_props( props, callback ) {
        for ( var i in props ) {
            if ( m_style[ props[i] ] !== undefined && ( !callback || callback( props[i] ) ) ) {
                return true;
            }
        }
    }
    var props = [
        prop,
        'Webkit' + uc_prop,
        'Moz' + uc_prop,
        'O' + uc_prop,
        'ms' + uc_prop,
        'Khtml' + uc_prop
    ];
    return !!test_props( props, callback );
};


/** former background animation...  comes back... maybe... 
*********************************************************************************/
var ani=null;
var angle = 0;
var flag=false;
function bgAnimation() {
	flag=!flag;
	var p = $('ms2012').style;
	var s = 0;
	var c = 0;	
	var y1=0,y2=0,y3=0;
	if(flag) {
		clearInterval(ani);
		$('js_bgAni').innerHTML = 'Animation: off';
		ani=null;
	} else {
		  if(ani)clearInterval(ani);
			$('js_bgAni').innerHTML = 'Animation: on';
		  ani = setInterval(function(){
		   s = Math.sin(angle);
		   c = Math.cos(angle);
		   angle += 0.0002;
		   x1 = s * 1560;
		   y1 = c * 300;
		   x2 = s * 560;
		   y2 = c * 300;
		   x3 = s * 2560;
		   y3 = c * 1600;
		   p.backgroundPosition=x1+"px "+y1+"px,"+x2+"px "+y2+"px,"+x3+"px "+y3+"px,0 0";
		  },24); 
	}
};


/** jumps to the specific sheet of the website via url hash
*********************************************************************************/
function jumpToArea() {
	setTimeout(function(){
		switch(location.hash) {
			case "#!/home" : 		showIntro();
									break;	
			case "#!/lab" :  		showSheet(1);
									break;
			case "#!/portfolio" :  	showSheet(2);
									break;
			case "#!/about" :		showSheet(3);
									break;
			default : showIntro();
		}
	},800);
		
};


/** sets the hover in the main navigation 
*********************************************************************************/
function setHover(id) {	
	location.hash = [null,"#!/lab","#!/portfolio","#!/about","#!/blog"][id];
	switch (location.hash) {
		
		case '#!/lab' : 		$('js_nav_lab').className = 'active';
								$('js_nav_port').className = '';
								//$('js_nav_blog').className = '';
								$('js_nav_about').className = '';
								break;
								
		case '#!/portfolio' : 	$('js_nav_lab').className = '';
								$('js_nav_port').className = 'active';
								//$('js_nav_blog').className = '';
								$('js_nav_about').className = '';
								break;
								
		case '#!/blog' : 		$('js_nav_lab').className = '';
								$('js_nav_port').className = '';
								//$('js_nav_blog').className = 'active';
								$('js_nav_about').className = '';
								break;
								
		case '#!/about' : 	$('js_nav_lab').className = '';
								$('js_nav_port').className = '';
								//$('js_nav_blog').className = '';
								$('js_nav_about').className = 'active';
								break;
	}
};


/** shows a sheet by id or the intropage
*********************************************************************************/
function showSheet(id) {	
	if(transition == true) {
		$('js_slider').style.top = [null,"-100%","-200%","-300%","-400%"][id];
		setHover(id);
		$('js_header').className = 'header loaded mini';
		$('js_content').style.opacity = '1';
	} else {
		sheetAnimation(id);
		setHover(id);
		$('js_header').className = 'header loaded mini';
		$('js_content').style.opacity = '1';
	}
};
function showIntro() {
	location.hash = '#!/home';
	$('js_slider').style.top = '0%';
	$('js_content').style.opacity = '0';
	$('js_header').className = 'header loaded';
};


/**  vertical sheet animation for all browsers without css transition support!
*********************************************************************************/
var arr = [0,-100,-200,-300,-400];
var currentIndex = 0;
function sheetAnimation(id) {
	CInterpolator.interpolate("slider_animation" + intval(Math.random() * 10000), 1000, function(w){
		var e = Math.sin(Math.PI / 2 / 100 * w);
		$("js_slider").style.top =  ((1-e)*arr[currentIndex]) + (e*arr[id]) + "%";
		if (w == 100) {
			currentIndex = id;
		}
	});
};


/** sets all important margins for a vertically centered sheet-content
*********************************************************************************/
function setMargin() {
	var heightLab =  ~~($('js_lab').offsetHeight/2);
	var heightPort =  ~~($('js_port').offsetHeight/2);
	var heightAbout =  ~~($('js_about').offsetHeight/2);
	var iMaxMargin = document.getElementsByTagName("body")[0].offsetHeight/2;
	$('js_lab').style.marginTop= '-'+Math.min(iMaxMargin,heightLab)+'px';
	$('js_port').style.marginTop= '-'+Math.min(iMaxMargin,heightPort)+'px';
	$('js_about').style.marginTop= '-'+Math.min(iMaxMargin,heightAbout)+'px';
};


/** horizontal animation for all browsers (css transitions or js workaround) 
----------------------------------------------------------------------------------
-> page = 1 (0), 2 (-200), 3(-400), 4(-600), 5(-800), 6(-1000)
-> id = js_id which should be animated
*********************************************************************************/
var arrPage = [0,0, -200,-400,-600,-800,-1000];
var currentPageIndex = 1;
function horPageAnimation(page, id) {
	CInterpolator.interpolate("slider_pageing" + intval(Math.random() * 10000), 1000, function(w){
		var e = Math.sin(Math.PI / 2 / 100 * w);
		$(id).style.left =  ((1-e)*arrPage[currentPageIndex]) + (e*arrPage[page]) + "%";
		if (w == 100) {
			currentPageIndex = page;
		}
	});
};
function horPage(page, id) {
	if(transition == true) {
		$(id).style.left = [null,0 ,-200,-400,-600,-800,-1000][page] + "%";
	} else {
		horPageAnimation(page, id);
	}
}


/** sets lab and portfolio menus to active
*********************************************************************************/
var a=[
	"js_menu_portfolio_page_1",
	"js_menu_portfolio_page_2",
	"js_menu_portfolio_page_3",
	"js_menu_portfolio_page_4",
	"js_menu_portfolio_page_5",
	"js_menu_portfolio_page_6"
];
var b=[
	"js_menu_lab_page_1",
	"js_menu_lab_page_2",
	"js_menu_lab_page_3",
	"js_menu_lab_page_4",
	"js_menu_lab_page_5",
	"js_menu_lab_page_6"
];
function setPortfolioMenu(e){
	for(var i=0;i<a.length;i++){
		var d=(a[i])?$(a[i]):null;
		if(d)d.className = d.className.replace("active"," "); 
	}
	e.className+=" active";
};
function setLabMenu(e){
	for(var i=0;i<b.length;i++){
		var d=(b[i])?$(b[i]):null;
		if(d)d.className = d.className.replace("active"," "); 
	}
	e.className+=" active";
};


/** portfolio & lab height 
*********************************************************************************/
var pHeight = '';
function portfolioHeight() {
	pHeight = (function(){
		var a = [
			"js_portfolio_page_1",
			"js_portfolio_page_2",
			"js_portfolio_page_3"];
		for(var i=0;i<a.length;i++){
			if(a[i]&&$(a[i]))with($(a[i])) {
					if(offsetHeight&&offsetHeight!=0)return offsetHeight+"px"
				}
			}
		}
	)();
	try {
		$('js_hor_slider_portfolio_wrapper').style.height = pHeight;
	} catch (e) {};
}
var lHeight = '';
function labHeight() {
	lHeight = (function(){
		var a = [
			"js_lab_page_1",
			"js_lab_page_2",
			"js_lab_page_3"];
		for(var i=0;i<a.length;i++){if(a[i]&&$(a[i]))with($(a[i])){if(offsetHeight&&offsetHeight!=0)return offsetHeight+"px"}}}
	)();
	try {
		$('js_hor_slider_lab_wrapper').style.height = lHeight;
	} catch (e) {};
}


/** shows and closes the default overlays
*********************************************************************************/
function showOverlay(content) {
	//  XMLObject erstellen:
    var request  =   null;
    if (window.XMLHttpRequest)
        request = new window.XMLHttpRequest;
    else try {
        request = new ActiveXObject("MSXML2.XMLHTTP.3.0");
        } catch(ex) {}
    if (!request)   return alert('Unfortunatelly your browser doesn\'t support AJAX.');
    //  Request absetzen:
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status==404) return alert("File not found - 404\n"+url);
            if (request.status==200) {
                $('js_darkscreen').style.display = 'block';
				$('js_overlay').innerHTML = request.responseText;
				$('js_overlay').style.marginLeft = '-'+~~($('js_overlay').offsetWidth/2)+'px';
				if(transition == true) {					
					setTimeout(function(){
						$('js_darkscreen').style.opacity = '1';
					},50);
					$('js_overlay').style.top =  '50%';
					$('js_overlay').style.marginTop = '-'+~~($('js_overlay').offsetHeight/2)+'px';
				} else {
					setTimeout(function(){
						$('js_darkscreen').style.opacity = '1';
					},50);
					openOverlayJS();
					$('js_overlay').style.marginTop = '-'+~~($('js_overlay').offsetHeight/2)+'px';
				}
            } else {
                alert("NetworkError#"+request.status+"\n"+content);
			}
		}
    }
    request.open('GET', content+".tpl", true);
    request.send(null);
};
function closeOverlay() {
	$('js_darkscreen').style.opacity = '0';
	$('js_overlay').style.top = '-80%';
	if(transition == true) {
		setTimeout(function(){
			try {
				$("js-sendmail-name").value="";
				$("js-sendmail-mail").value="";
				$("js-sendmail-msg").value="";
				$("js-sendmail-name").className=cssNormalBorder;
				$("js-sendmail-mail").className=cssNormalBorder;
				$("js-sendmail-msg").className=cssNormalBorder;
			} catch (e) {};
			$('js_darkscreen').style.display = 'none';			  
		},800);
	} else {

		closeOverlayJS();
		try {
			$("js-sendmail-name").value="";
			$("js-sendmail-mail").value="";
			$("js-sendmail-msg").value="";
			$("js-sendmail-name").className=cssNormalBorder;
			$("js-sendmail-mail").className=cssNormalBorder;
			$("js-sendmail-msg").className=cssNormalBorder;
		} catch (e) {};
		$('js_darkscreen').style.display = 'none';	
	}
};


/** shows and closes the portfolio and lab overlays
*********************************************************************************/
function showProject(content) {
	//  XMLObject erstellen:
    var request  =   null;
    if (window.XMLHttpRequest)
        request = new window.XMLHttpRequest;
    else try {
        request = new ActiveXObject("MSXML2.XMLHTTP.3.0");
        } catch(ex) {}
    if (!request)   return alert('Unfortunatelly your browser doesn\'t support AJAX.');
    //  Request absetzen:
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status==404) return alert("File not found - 404\n"+url);
            if (request.status==200) {
                $('js_darkscreen_p').style.display = 'block';
                $('js_overlay_p').innerHTML = request.responseText;
				$('js_overlay_p').style.display = 'block';
				$('js_overlay_p').style.marginLeft = '-'+~~($('js_overlay_p').offsetWidth/2)+'px';
				
				if(transition == true) {					
					setTimeout(function(){
						$('js_darkscreen_p').style.opacity = '1';
					},50);
					$('js_overlay_p').style.top =  '50%';
					$('js_overlay_p').style.marginTop = '-'+~~($('js_overlay_p').offsetHeight/2)+'px';
				} else {
					setTimeout(function(){
						$('js_darkscreen_p').style.opacity = '1';
					},50);
					openProjectJS();
					$('js_overlay_p').style.marginTop = '-'+~~($('js_overlay_p').offsetHeight/2)+'px';
				}
            } else {
                alert("NetworkError#"+request.status+"\n"+content);
			}
		}
    }
    request.open('GET', content+".tpl", true);
    request.send(null);
};
function closeProject() {
	$('js_overlay_p').style.top = '-80%';
	$('js_darkscreen_p').style.opacity = '0';
	if(transition == true) {
		setTimeout(function(){
			$('js_darkscreen_p').style.display = 'none';	  
		},800);
	} else {
		closeProjectJS();
		setTimeout(function(){
			$('js_darkscreen_p').style.display = 'none';	  
		},800);	
	}	
};


/** alternative JS project-overlay animation for browsers without css transitions
*********************************************************************************/
function openProjectJS() {
	CInterpolator.interpolate("overlay_project_ani_down" + intval(Math.random() * 10000), 800, function(w){
		var e = Math.sin(Math.PI / 2 / 100 * w);
		$('js_overlay_p').style.top =  -80 + (e * 130) + "%";
		$('js_darkscreen_p').style.filter = "alpha(opacity='" + (0 + (e * 100)) + "')";
		$('js_darkscreen_p').style.opacity =  0 + (e);	
	});
}
function closeProjectJS(id) {
	CInterpolator.interpolate("overlay_project_ani_up" + intval(Math.random() * 10000), 800, function(w){
		var e = Math.sin(Math.PI / 2 / 100 * w);		
		$('js_overlay_p').style.top = 50 - (e * 130) + "%";
		$('js_darkscreen_p').style.filter = "alpha(opacity='" + (100 - e * 100) + "')";
		$('js_darkscreen_p').style.opacity =  1 - e;	
	});
}


/** alternative JS overlay animation for browsers without css transitions
*********************************************************************************/
function openOverlayJS() {
	CInterpolator.interpolate("overlay_ani_down" + intval(Math.random() * 10000), 800, function(w){
		var e = Math.sin(Math.PI / 2 / 100 * w);
		$('js_overlay').style.top =  -80 + (e * 130) + "%";
		$('js_darkscreen').style.filter = "alpha(opacity='" + (0 + (e * 100)) + "')";
		$('js_darkscreen').style.opacity =  0 + (e);	
	});
}
function closeOverlayJS() {
	CInterpolator.interpolate("overlay_ani_up" + intval(Math.random() * 10000), 800, function(w){
		var e = Math.sin(Math.PI / 2 / 100 * w);		
		$('js_overlay').style.top = 50 - (e * 130) + "%";
		$('js_darkscreen_p').style.filter = "alpha(opacity='" + (100 - e * 100) + "')";
		$('js_darkscreen_p').style.opacity =  1 - e;			
	});
}




/** hides the warning panel
*********************************************************************************/
function hideWarning() {
	$('js_warning').style.display = 'none';	
}








/** onload and resize stuff
*********************************************************************************/
window.onload=function(){	
	if(hasProperty("transition")&&hasProperty("backgroundSize")) {
		$('ms2012').className="";
		transition = true;
	} else {
		document.getElementById('ms2012').className="notransition";
		transition = false;
	}
	$('wrapper').className='loaded';
	portfolioHeight();
	labHeight();
	setMargin();
	jumpToArea();
	//bgAnimation();
};
window.onresize=function() {
	setMargin();
	labHeight();
	portfolioHeight();
}
