/*
 * Theme Picker
 */
var Theme = {
	posX : 0,
	posY : 0,
	displayTimeout : null,

	panel : null,
	picker : null,
	
	init : function () {
		this.picker = document.getElementById('theme-picker');
		this.panel = document.getElementById('theme-panel');
		this.posX = this.picker.offsetLeft;
		this.posY = Element.getY(this.picker);
		
		this.panel.onmouseover = Theme.show;
		this.panel.onmouseout = Theme.hide;
		this.picker.onmouseover = Theme.show;
		this.picker.onmouseout = Theme.hide;
	},
	
	show : function () {
		document.getElementById('theme-image').src = '/themes/grassy_soon.gif';
		return;
		Theme.posY = Element.getY(Theme.picker);
		Theme.panel.style.left = Theme.posX + 30;
		Theme.panel.style.top = Theme.posY - 100;
		Theme.panel.style.display = '';
		if (Theme.displayTimeout != null) {
			clearTimeout(Theme.displayTimeout);
		}
	},
	
	hide : function () {
		document.getElementById('theme-image').src = '/themes/grassy.gif';
		return;
		Theme.displayTimeout = setTimeout('Theme.close()', 1000);
	},
	
	close : function () {
		Theme.panel.style.display = 'none';
	},
	
	select : function () {
	
	}
}

var Services = {

	url : null,

	curtab : null,
	
	viewstate : 'hidden',

	timeout : null,
	
	loadData : function (obj) {
		var tab = obj.getAttribute('content');
		if (tab == Services.curtab && Services.viewstate != 'hidden') {
			return;
		}
		Services.curtab = tab;
		Services.url = "pages/services/" + tab + ".php"; 
		
		var pos = YAHOO.util.Dom.getXY(obj);
		if (tab == 'integration' || tab == 'implementation') {
			pos[0] = pos[0] - 400;
		} else {
			pos[0] = pos[0] + 300;
		}
		pos[1] = pos[1] - 300;
		YAHOO.util.Dom.setXY('service-detail', pos);
	    YAHOO.util.Connect.asyncRequest( "GET", Services.url, 
			{
				success:Services.successHandler, 
				failure:Services.failureHandler 
			}
	    );

	},
	
	successHandler : function( r ) {
        // Use the response... 
		if (Services.viewstate == 'hidden') {
			new YAHOO.widget.Effects.Appear('service-detail', {seconds: 0.5, delay: false});
		}
		Services.viewstate = 'visible';
		var content = YAHOO.util.Dom.get( "service-detail" );
        content.innerHTML = r.responseText;
	},
	
	hide : function () {
		Services.viewstate = 'hidden';
		new YAHOO.widget.Effects.Fade('service-detail', {seconds: 0.5, delay: false} );
	},
	
	startTimeout : function () {
		Services.timeout = setTimeout("Services.hide()", 1000);
	},
	
	endTimeout : function () {
		clearTimeout(Services.timeout);
	}

}

var Work = {
	url : null,
	
	autoLoad : "",
	
	goToClient : function (client) {
		Work.autoLoad = client;
		window.location.href = '#app=work';
		loadSection('work');
	},
	
	loadClient : function (client) {
		if (client == '') {
			return;
		}
		var attributes = {
			width : { to : 0 }
		};
		
		Work.url = "pages/work/" + client + ".php"; 
		
		var anim = new YAHOO.util.Anim('work-client', attributes, 0.5, YAHOO.util.Easing.easeOut);
		anim.animate();
		anim.onComplete.subscribe(function() {
		    YAHOO.util.Connect.asyncRequest( "GET", Work.url, 
		    	{ 
					success:Work.successHandler, 
					failure:Work.failureHandler 
		        }
		    );
		});
		
	},
	
	loadPic : function(elem, pic) {
		var pics = YAHOO.util.Dom.get('work-client-left').getElementsByTagName('a');
		for (var i=0; i<pics.length; i++) {
			YAHOO.util.Dom.replaceClass(pics[i], 'bigbox-on', 'bigbox-off');
		}
		var bigpic = YAHOO.util.Dom.get(pic);
		YAHOO.util.Dom.replaceClass(pic, 'bigbox-off', 'bigbox-on');

		var buttons = YAHOO.util.Dom.get('client-pic-selectors').getElementsByTagName('div');
		for (var i=0; i<buttons.length; i++) {
			buttons[i].className = 'smallbox-off';
		}
		elem.className = 'smallbox-on';
	},
	
	successHandler : function( r ) {
        // Use the response... 

		var attributes = {
			width : { to : 950 }
		};

		var anim = new YAHOO.util.Anim('work-client', attributes, 0.5, YAHOO.util.Easing.easeOut);
		anim.delay = 1;
		anim.animate();

        var content = YAHOO.util.Dom.get( "work-client" );
        content.innerHTML = r.responseText;
	},
	
	failureHandler : function() {
		alert('There was an error loading the client profile');
	},
	
	showFullWorkList : function() {
		var pos = YAHOO.util.Dom.getXY("work-list-anchor");
		pos[0] -= 570;
		pos[1] -= 28;
		new YAHOO.widget.Effects.Appear('worked-with-detail', {seconds : 1, delay : false} );
		YAHOO.util.Dom.setXY("worked-with-detail", pos);
		new YAHOO.widget.Effects.Appear('ww-arrow', {seconds : 1, delay : false} );
		YAHOO.util.Dom.setXY("ww-arrow", [pos[0]+409, pos[1]+10 ] );		
	},
	
	closeFullWorkList : function() {
		new YAHOO.widget.Effects.Fade('worked-with-detail');
		new YAHOO.widget.Effects.Fade('ww-arrow');
	}
	
	
}

/**
 * Usefull funcitons
 */
var Element = {
	getY : function ( oElement ) {
		var iReturnValue = 0;
		while( oElement != null ) {
			iReturnValue += oElement.offsetTop;
			oElement = oElement.offsetParent;
		}
		return iReturnValue;
	}

}


var bookmarkedSection = YAHOO.util.History.getBookmarkedState( "app" );
var querySection = YAHOO.util.History.getQueryStringParameter( "section" ); 
var initialSection = bookmarkedSection || querySection || "home";

YAHOO.util.History.register( "app", initialSection, function( state ) {
	loadSection( state );
} );

function selectTab( section, animations ) {
	var nav = YAHOO.util.Dom.get( "nav" );
	var tabs = nav.getElementsByTagName( "a" );
	var side = YAHOO.util.Dom.get( "page-side" );
	var masterDuration = 0.3;

	// Hack for client list positioning..
	YAHOO.util.Dom.setStyle('worked-with', 'display', 'none');

	for ( var i=0; i<tabs.length; i++ ) {
		if (tabs[i].href.split('=')[1] == section) {
		    tabs[i].className = "tab-on";
		    if (animations) {
			    if (tabs[i].getAttribute( "sidebar" ) == 'hidden' && side.style.width != '0px') {
					var sideClose = new YAHOO.util.Anim( "page-side" , { width: { to: 0 } }, 1);
					sideClose.duration = masterDuration;
					sideClose.animate();
					var bodyExpand = new YAHOO.util.Anim( "page" , { width: { from: 650, to: 900 } }, 1);
					bodyExpand.duration = masterDuration;
					bodyExpand.animate();
					delete sideClose;
					delete bodyExpand;
			    } else if (tabs[i].getAttribute( "sidebar" ) != 'hidden' && side.style.width == '0px') {
					var sideOpen = new YAHOO.util.Anim( "page-side" , { width: { to: 300 } }, 1);
					sideOpen.animate();
			    	sideOpen.duration = masterDuration;
			    	YAHOO.util.Dom.get( "page" ).style.width = '650px';
			    	delete sideOpen;
			    }
			}
		} else {
			tabs[i].className = 'tab-off';
		}
    }
    
	
}

function loadSection( section ) {

	selectTab (section, true);
    var url = "pages/" + section + ".php"; 
    function successHandler( obj ) { 
        // Use the response... 
        var content = YAHOO.util.Dom.get( "dyn-content" );
        content.innerHTML = obj.responseText;
        evalScripts( obj.responseText );
    } 
	
    function failureHandler( obj ) { 
        // Fallback... 
        location.href = "?section=" + section; 
    } 

	function evalScripts(text) {
	    var match = '<script[^>]*>([\\S\\s]*?)<\/script>';
	    var matchAll = new RegExp(match, 'img');
		var matchOne = new RegExp(match, 'im');
		var matches = text.match(matchAll) || [];
		for (var i=0; i<matches.length; i++) {
			eval((matches[i].match(matchOne) || ['',''])[1]);
		}
	}
	
    YAHOO.util.Connect.asyncRequest( "GET", url, 
    	{ 
			success:successHandler, 
			failure:failureHandler 
        }
    );
}

function initializeNavigationBar() {
    // Process links
    var anchors = YAHOO.util.Dom.get( "nav" ).getElementsByTagName( "a" );
    for ( var i=0, len=anchors.length ; i<len ; i++ ) {
        var anchor = anchors[i];
        YAHOO.util.Event.addListener( anchor, "click", function( evt ) {
            var href = this.getAttribute( "href" );
            var section = YAHOO.util.History.getQueryStringParameter( "section", href ) || "home";
            // If the Browser History Manager was not successfuly initialized,
            // the following call to YAHOO.util.History.navigate will throw an
            // exception. We need to catch it and update the UI. The only
            // problem is that this new state will not be added to the browser
            // history.
            //
            // Another solution is to make sure this is an A-grade browser.
            // In that case, under normal circumstances, no exception should
            // be thrown here.

			selectTab( section, false );
			var fadeout = new YAHOO.widget.Effects.Fade('dyn-content', { delay: false });
			fadeout.duration = 0.3;
			fadeout.onEffectComplete.subscribe(function() {
				try {
		        	YAHOO.util.History.navigate( "app", section );
				} catch ( e ) {
		        	loadSection( section );
				}
				
				setTimeout("YAHOO.widget.Effects.Appear('dyn-content', { delay: false })", 400);

			});
			fadeout.animate();
			
	        YAHOO.util.Event.preventDefault( evt );

        } );
    }

    // This is the tricky part... The window's onload handler is called when the
    // user comes back to your page using the back button. In this case, the
    // actual section that needs to be loaded corresponds to the last section
    // visited before leaving the page, and not the initial section. This can
    // be retrieved using getCurrentState:
    var currentSection = YAHOO.util.History.getCurrentState( "app" );
    if ( location.hash.substr(1).length > 0 ) {
        // If the section requested in the URL fragment is different from
        // the section loaded in index.php, we have an unpleasant refresh
        // effect because we do an asynchronous XHR call. Instead of doing
        // a synchronous XHR call, we can fix this by erasing the initial
        // content of bd:
        if ( currentSection != querySection )
            YAHOO.util.Dom.get( "dyn-content" ).innerHTML = "";
        loadSection( currentSection );
    }
}


// Subscribe to this event before calling YAHOO.util.History.initialize,
// or it may never get fired! Note that this is guaranteed to be fired
// after the window's onload event.
YAHOO.util.History.onLoadEvent.subscribe( function() {
    initializeNavigationBar();
    //Theme.init();
} );




