var portfolioSelectedIndex = null;
var logoState = "left";

var ImageRegistry = {
	images : [],

	register : function(name, path, suffix) {
		ImageRegistry.images[name] = new Image();
		ImageRegistry.images[name].src = path;
		if (suffix) {
			ImageRegistry.images[name + suffix] = new Image();
			ImageRegistry.images[name + suffix].src = path.replace(/\.gif$/, suffix + ".gif");
		}
	},
	
	get : function(name) {
		return ImageRegistry.images[name];
	}
}

ImageRegistry.register("att", "/images/clients/att.gif", "-on");
ImageRegistry.register("grid", "/images/clients/grid.gif", "-on");
ImageRegistry.register("pixpulse", "/images/clients/pixpulse.gif", "-on");
ImageRegistry.register("produxs", "/images/clients/produxs.gif", "-on");

/**
 * Usefull funcitons
 */
var Element = {
	getY : function ( oElement ) {
		var iReturnValue = 0;
		while( oElement != null ) {
			iReturnValue += oElement.offsetTop;
			oElement = oElement.offsetParent;
		}
		return iReturnValue;
	},
	
	getX : function ( oElement ) {
		var iReturnValue = 0;
		while( oElement != null ) {
			iReturnValue += oElement.offsetLeft;
			oElement = oElement.offsetParent;
		}
		return iReturnValue;
	}

}

function evalScripts(text) {
	text = text.replace(/\<\!\-\-/g, "");
	text = text.replace(/\-\-\>/g, "");
	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++) {
		try {
			eval((matches[i].match(matchOne) || ['',''])[1]);
		} catch (e) {
			// JS eval failed
		}
	}
}

function setPageTitle(section) {
	var title;
	switch (section) {
		case "services":
			title = "Design, Technology and Business Services";
		break;
		case "portfolio":
			title = "Our Clients and Case Studies";
		break;
		case "company":
			title = "About WebOnyx";
		break;
		case "jobs":
			title = "Find web development jobs at a growing Seattle software firm";
		break;
		case "contact":
			title = "Contact Us";
		break;
		default:
			title = "WebOnyx - Seattle Web Development and Consulting";
		break;
	}
	document.title = title;
}

/**
 * Async page manager
 */
function loadSection(section) {
	// Highlight the tab
	selectTab(section);
	
	// Set the page title
	setPageTitle(section);
	
	var eff = new YAHOO.widget.Effects.Fade("lcol", { delay: true });
	eff.onEffectComplete.subscribe(function() {
		loadLeftPanel(section);
	});
	eff.animate();

	var eff2 = new YAHOO.util.Anim( "rcol" , { width: { from: 370, to: 0 } }, 1);
	eff2.onComplete.subscribe(function() {
		loadRightPanel(section);
	});
	eff2.animate();

}

function loadLeftPanel(section) {
    function successHandler(obj) {
        // Use the response...
        YAHOO.util.Dom.get("lcol").innerHTML = obj.responseText;
        evalScripts(obj.responseText);
        var eff = new YAHOO.widget.Effects.Appear("lcol", {delay: true});
        eff.animate();
    }

    function failureHandler(obj) {
        // Fallback...
        location.href = "/" + section;
    }

    YAHOO.util.Connect.asyncRequest("GET", "/content/" + section + "Main",
        {
            success:successHandler,
            failure:failureHandler
        }
    );

}

function loadRightPanel(section) {

    function successHandler(obj) {
        // Use the response...
        YAHOO.util.Dom.get("rcol").innerHTML = obj.responseText;
        evalScripts(obj.responseText);
		var ropen = new YAHOO.util.Anim( "rcol" , { width: { to: 370 } }, 1);
        ropen.onComplete.subscribe(function() {
        	// Custom stuff for services page
			if (section == "services") {
				document.getElementById("cc-selector").style.visibility = "visible";
			}
        });
        ropen.animate();
    }

    function failureHandler(obj) {
        // Fallback...
        location.href = "/" + section;
    }

    YAHOO.util.Connect.asyncRequest("GET", "/content/" + section + "Side",
        {
            success:successHandler,
            failure:failureHandler
        }
    );
	
}

function getHrefState(href) {
	var state = href.match(/\/(\w+)?$/);
	if (state) {
		return (!state[1] ? "home" : state[1]);
	} else {
		return null;
	}
}

var bookmarkedSection = YAHOO.util.History.getBookmarkedState("navbar");
var querySection = getHrefState(window.location.href);
var initialSection = bookmarkedSection || querySection || "home";

YAHOO.util.History.register("navbar", initialSection, function (section) {
    // Load the appropriate section:
    if (section == "home" && logoState == "right") {
    	animateLogo("left");
    } else if (section != "home" && logoState == "left") {
    	animateLogo("right");
    }

    loadSection(section);
});

function selectTab(tabname) {
	var anchors = YAHOO.util.Dom.get("menu").getElementsByTagName("a");
	var state = "";
	for(var i=0; i<anchors.length; i++) {
		if (anchors[i].innerHTML != 'Blog') {
			anchors[i].className = "";
			state = getHrefState(anchors[i].href);
			if (state == tabname) {
				anchors[i].className = "selected";
			}
		}
	}
}

function goTo(section) {
    var currentSection = YAHOO.util.History.getCurrentState("navbar");
    if (section != "home" && currentSection == "home") {
    	animateLogo("right");
    } else if (section == "home" && currentSection != "home") {
    	animateLogo("left");
    }

	if (currentSection == "contact" && section != "contact") {
		new YAHOO.util.Anim( "rcol" , { height: { from: 100, to: 490 } }, 1).animate();
	} else if (section == "contact" && currentSection != "contact") {
		new YAHOO.util.Anim( "rcol" , { height: { from: 490, to: 100 } }, 1).animate();
	}

	if (currentSection == "services" && section != "services") {
		document.getElementById("cc-selector").style.visibility = "hidden";
	}
	
    try {
        YAHOO.util.History.navigate("navbar", section);
    } catch (e) {
        loadSection(section);
    }
}

function animateLogo(direction) {
	var logo, rcont, lcont, rx, lx, anim, margin, tp;
	logo = document.getElementById("logo");
	rcont = document.getElementById("rcont");
	lcont = document.getElementById("lcont");
	rx = Element.getX(rcont);
	lx = Element.getX(lcont);
	tp = Element.getY(logo);
	
	logo.style.position = "absolute";
	logo.style.top = tp + "px";
	
	if (direction == "right") {
		logoState = "right";
		anim = new YAHOO.util.Anim( "logo" , { left: { to: rx } }, 1);
		anim.animate();
		new YAHOO.util.Anim( "lcont" , { minHeight: { from: 727, to: 795 } }, 1).animate();
		new YAHOO.util.Anim( "lcont" , { paddingTop: { from: 58, to: 0 } }, 1).animate();
		new YAHOO.util.Anim( "rcont" , { paddingTop: { from: 0, to: 58 } }, 1).animate();
	} else {
		logoState = "left";
		anim = new YAHOO.util.Anim( "logo" , { left: { to: lx } }, 1);
		anim.animate();
		new YAHOO.util.Anim( "lcont" , { paddingTop: { from: 0, to: 58 } }, 1).animate();
		new YAHOO.util.Anim( "lcont" , { minHeight: { from: 795, to: 727 } }, 1).animate();
		new YAHOO.util.Anim( "rcont" , { paddingTop: { from: 58, to: 0 } }, 1).animate();
	}
}

function initializeNavigationBar() {
    // Process links
    var anchors, i, len, anchor, href, section, currentSection;
    anchors = YAHOO.util.Dom.get("menu").getElementsByTagName("a");
    for (i = 0, len = anchors.length; i < len; i++) {
        anchor = anchors[i];
        if (YAHOO.util.Dom.hasClass(anchor, 'subscribe')) {
	        YAHOO.util.Event.addListener(anchor, "click", function (evt) {
	            href = this.getAttribute("href");
	            section = getHrefState(href) || "home";
	            
	            goTo(section);
	            YAHOO.util.Event.preventDefault(evt);
	        });
        }
    }

    currentSection = YAHOO.util.History.getCurrentState("navbar");
	section = getHrefState(location.href) || "home";
    if (section != currentSection) {
	    if (section != "home" && currentSection == "home") {
	    	animateLogo("left");
	    } else if (section == "home" && currentSection != "home") {
	    	animateLogo("right");
	    }
	    loadSection(currentSection);
    }
}

YAHOO.util.History.onReady(function () {
    initializeNavigationBar();
});

YAHOO.util.Event.onDOMReady(function() {
	confPanel = new YAHOO.widget.Panel("confirm-modal",  
		{ 
		  fixedcenter:true, 
		  close:false, 
		  draggable:false, 
		  zindex:4,
		  modal:true,
		  visible:false,
		  underlay:"none",
		  height:"148px",
		  width:"400px"
		}
	);
	//render it over the body
	confPanel.render(document.body);

});

