JAME.Package('JAME.Dimensions');

JAME.Dimensions = {

        windowScroll : function() {
                var d  = document,
                        db = d.body,
                        dd = d.documentElement,
                        w  = window;
                return {
                        x: w.pageXOffset || db.scrollLeft || dd.scrollLeft, 
                        y: w.pageYOffset || db.scrollTop  || dd.scrollTop
                };
        },
        windowSize : function() {
                var d  = document,
                        db = d.body,
                        dd = d.documentElement,
                        w  = window;
                return {
                        height: w.innerHeight || dd.clientHeight || db.offsetHeight,
                        width : w.innerWidth  || dd.clientWidth || db.offsetWidth
                };
        },
        pageSize : function() {

                var xScroll, yScroll,height,width,windowHeight,windowWidth;

                windowHeight = JAME.Dimensions.windowSize().height;
                windowWidth  = JAME.Dimensions.windowSize().width;

                if (document.body.scrollHeight > document.body.offsetHeight){ 
                        xScroll = document.body.scrollWidth;
                        yScroll = document.body.scrollHeight;
                } else { 
                        xScroll = document.body.offsetWidth;
                        yScroll = document.body.offsetHeight;
                }

                if (window.innerHeight && window.scrollMaxY) {  
                        yScroll = windowHeight + window.scrollMaxY;
                }
                if (window.innerWidth && window.scrollMaxX) {   
                        xScroll = windowWidth + window.scrollMaxX;
                }

                return {
                        height:Math.max(yScroll,JAME.Dimensions.windowSize().height),
                        width:Math.max(xScroll,JAME.Dimensions.windowSize().width)
                };
        }
};

JAME.DOM.Ready(function() {

	(function() {

		var 
		   naviLinks = parse("#menu li a"),
		   head      = $('header'),
		   menu      = $('menu'),
		   subhead   = wrapNode(menu,'div'),
		   timer     = false;

		naviLinks.each(

			function(link,i) {

				link.onmouseover=function() {

					if(timer) clearTimeout(timer);
					timer = setTimeout(function() {
						anim[i]["backgroundPosition"]["start"]=sub.style.backgroundPosition || '0px 0px';
						new JAME.FX.T({duration:800}).Tween2(sub,anim[i]);
					},400);
				}
			}
		);

	})();

	var 
		ua        = navigator.userAgent.toLowerCase(),
	    match     = /(webkit)[ \/]([\w.]+)/.exec( ua )              ||
                            /(opera)(?:.*version)?[ \/]([\w.]+)/.exec( ua ) ||
                            /(msie) ([\w.]+)/.exec( ua )                    ||
                            !/compatible/.test( ua ) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec( ua ) || [],

        browser   = match[1] || "",
        version   = match[2] || "0",
		isTrident = (/msie/.test(browser)),
		bar           = $("sub-menu-bg"),
	    logo          = $("header-top");
	    naviLinksList = parse("#menu li a");

	bar.fullHeight =getHeight(bar);

	bar.style.width=(JAME.Dimensions.pageSize().width-2)+'px';

	naviLinks=[];
	for(var i=0,ln=naviLinksList.length;i<ln;i++){
		var id = naviLinksList[i].href.split(/#/)[1];
		if($(id))
			naviLinks.push(naviLinksList[i])
	}
	var subLinks  = parse("#sub-menu>div");

	var head = $('header');
	var h= getHeight(head);



	var subhead = head.cloneNode(true);
	head.appendChild(subhead);
	subhead.style.height=h+'px';
	subhead.style.backgroundRepeat='no-repeat';	

	//too slow, too ugly in older IE
	if(!isTrident || (isTrident && version>7)) {
		collapseHeader(head,subhead);
	}

	var css = new JAME.E4CSS();
	
	var fromCSS = css['.sub-default'];
	var overed=0;

	if(document.body.className.match(/category_2_94/)){
	     fromCSS = css['.sub-about'];
	     overed=1;
	}
	if(document.body.className.match(/category_2_98/)){
	     fromCSS = css['.sub-services'];
		 overed=2;
	}
	if(document.body.className.match(/category_2_96/)){
	     fromCSS = css['.sub-beyond'];
		 overed=4;
	}
	if(document.body.className.match(/category_2_100/)){
	     fromCSS = css['.sub-home'];
		 overed=0;
	}
	if(document.body.className.match(/category_2_101/)){
	     fromCSS = css['.sub-portfolio'];
		 overed=3;
	}

	var torgb = toRGBString(fromCSS.backgroundColor);

    new JAME.FX.T({duration:350}).Tween2(naviLinks[overed],{color:{end:torgb,start:"rgb(255,255,255)"}});
	new JAME.FX.T({easing:JAME.FX.Transition.Expo.Out,duration:400}).Tween2(bar,{backgroundColor:{end:torgb,start:"rgb(255,255,255)"}});
	var timerOver=false;

	var bgInterpolation ={backgroundPosition:{start:'0px -290px',end:'0px 0px'}};
	var subLinksOver={position:{start:'relative',end:'absolute'},top:{start:"-40px",end:'0px'},left:{start:0,end:0},visibility:{start:'hidden',end:'visible'}};

	naviLinks.each(

		function(link,i) {
			var pos = i+1;

			var cssClass = '.'+link.href.split('#')[1];
			var toCSS = css[cssClass];
			var interpolate={};
			for(var prop in toCSS) {
				interpolate[prop]={};
				interpolate[prop].start= fromCSS[prop];
				interpolate[prop].end  = toCSS[prop];
			}
			link.interpolate=interpolate;
			link.onmouseover=function(e) {

				var time=(overed==0) ? 200 : 450;

				if(timerOver) clearTimeout(timerOver);
				if(overed==i) return;

				timerOver = setTimeout(function() {	

					subLinks[overed].style.visibility='hidden';

					new JAME.FX.T({duration:350}).Tween2(naviLinks[overed],{color:{start:toRGBString(naviLinks[overed].interpolate.backgroundColor.end),end:"rgb(255,255,255)"}})
					new JAME.FX.T({duration:350}).Tween2(link,{color:{end:toRGBString(interpolate.backgroundColor.end),start:"rgb(255,255,255)"}})
					new JAME.FX.T({duration:50}).Tween2(bar,{height:{end:0,start:bar.fullHeight}}).queue(
						function() {
							subLinks[overed].style.position='relative';
							subLinks[overed].style.top='0px';
							overed=i;
							subhead.style.backgroundPosition='0px -290px';
							subhead.style.backgroundImage='url(/img/headerbg'+pos+'.jpg)';
							new JAME.FX.T({easing:JAME.FX.Transition.Expo.Out,duration:400}).Tween2(subhead,bgInterpolation).queue(
								function() { 
									head.style.backgroundImage='url(/img/headerbg'+pos+'.jpg)'; 
								}
							)
							new JAME.FX.T({easing:JAME.FX.Transition.Bounce.Out,duration:400}).Tween2(subLinks[i],subLinksOver);	
							new JAME.FX.T({easing:JAME.FX.Transition.Expo.Out,duration:400}).Tween2(bar,interpolate);
						}
					);
	
				},time);
			}

			link.onclick=function(e) {
				if(i==0){
					link.href="/";
				}
				else {
				stopDefault(e);
				}
			}

		}
	);


});



function wrapNode(elm,wrapper) {
		var oWrapper = document.createElement(wrapper);
		var elmClone = elm.cloneNode(true);
		oWrapper.appendChild(elmClone);
		oparent = elm.parentNode;
		insertAfter(oWrapper,elm);
		oparent.removeChild(elm);
		return oWrapper;
}

function stopDefault(e) {
	if(e && e.preventDefault) 
		e.preventDefault();
	else
        window.event.returnValue = false;
	return false;
}


var normalizeEvent = function(event) {

    event = event || window.event;
    
	if(window.event) {

    	event.preventDefault = function() {
     	     this.returnValue= false;
    	};
    	event.stopPropagation = function() {
      		this.cancelBubble = true;
    	};
        event.target = event.srcElement;       

        if (event.target.nodeType == 3) event.target = event.target.parentNode;

        event.relatedTarget = (event.fromElement == event.target) 
							? event.toElement 
						    : event.fromElement;
	}


    if ( event.pageX == null && event.clientX != null ) {
        var e = document.documentElement, b = document.body;
        event.pageX = event.clientX + (e && e.scrollLeft || b.scrollLeft || 0);
        event.pageY = event.clientY + (e && e.scrollTop || b.scrollTop || 0);    
	}

    if ( !event.which && (event.charCode || event.keyCode) )
      event.which = event.charCode || event.keyCode;
    
    if ( !event.metaKey && event.ctrlKey )
      event.metaKey = event.ctrlKey;

    if ( !event.which && event.button )
      event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
      
    return event;
}


function nextNode( elem ) {
   if (!elem.nextSibling) return false;
   do {
      elem = elem.nextSibling;
   } while (elem && (elem.nodeType == 3 && !/\S/.test(elem.nodeValue)));
   return elem;
}

function insertAfter( elem, targetElem ) {

   var oparent = targetElem.parentNode;
   if (targetElem == oparent.lastChild)
     oparent.appendChild(elem);
   else
     oparent.insertBefore(elem,nextNode(targetElem));
}

function getHeight(elm){
		if(elm.style.display!='none'&& elm.style.display!='')
			return elm.offsetHeight;
		viz = elm.style.visibility;
		elm.style.visibility = 'hidden';
		o = elm.style.display;
		elm.style.display='block';
		r = parseInt(elm.offsetHeight);
		elm.style.display=o;
		elm.style.visibility = viz;
		return r;
}


function collapseHeader(head,subhead) {

	var collapse = $("header-wrap");
		collapse.status=false;
		collapse.maxH=getHeight(collapse);

		collapse.onclick=function(e) {
			var e = normalizeEvent(e);
			if(e.target.tagName.toLowerCase()=='a'){
					return;
			}
			if(!this.status) {
				new JAME.FX.T({duration:1350,easing:JAME.FX.Transition.Expo.Out}).Tween2(head,{opacity:{start:1,end:0.5}});
				new JAME.FX.T({duration:1350,easing:JAME.FX.Transition.Expo.Out}).Tween2(subhead,{opacity:{start:1,end:0.5}});
				new JAME.FX.T({duration:350,easing:JAME.FX.Transition.Expo.Out}).Tween2(this,{height:{end:120,start:getHeight(this)}});
				this.status=true;
			}
			else {
				new JAME.FX.T({duration:1350,easing:JAME.FX.Transition.Expo.Out}).Tween2(head,{opacity:{start:0.5,end:1}});
				new JAME.FX.T({duration:1350,easing:JAME.FX.Transition.Expo.Out}).Tween2(subhead,{opacity:{start:0.5,end:1}});
				new JAME.FX.T({duration:350,easing:JAME.FX.Transition.Expo.Out}).Tween2(this,{height:{end:this.maxH,start:120}});
				this.status=false;
			}
		}

}

function toRGBString(color) {
	return 'rgb('+JAME.Util.Color.cssColor2rgb(color).join(',')+')';
}

