/***Global variables***/
var is_expanded = false;
var currentPreviewProject = 0;
var currentPage = "home";

var previews = [];
var currentPreviewIndex = 0;
var previewTimerId = -1;
var pauseTimerId = -1;

$(function(){

	//init ajax
	initOverlayAjax();
	initContentAjax();

	//detect user browser
	detectBrowser();
	
	//fill portfolio links
	createPortfolioLinks();
	
	//home page preview project
	sendPreviewRequest(currentPreviewProject);
	
	//top_nav links
	$('.top_nav').hover(function(){
		$(this).children('.top_nav_over').stop().animate({'top' : '0px', 'opacity' : 1}, 200);
		$(this).children('.top_nav_up').stop().animate({'top' : '50px'}, 100);
		}, function(){
			$(this).children('.top_nav_over').stop().animate({"top" : '60px', 'opacity' : 1}, 100);
			$(this).children('.top_nav_up').stop().animate({'top' : '0px'}, 200);
	});
	
	//portfolio overlay
	$('#portfolio_toggle').click(function(){
		togglePortfolioOverlay();
		return false;
	});

	//to_top button
	$('#to_top').hover(function(){
		$(this).children('#to_top_over').stop().animate({'top' : '7px', 'opacity' : 1}, 200);
		$(this).children('#to_top_up').stop().animate({'top' : '40px'}, 200);
		}, function(){
			$(this).children('#to_top_over').stop().animate({"top" : '40px', 'opacity' : 1}, 100);
			$(this).children('#to_top_up').stop().animate({'top' : '7px'}, 100);
	});
	$('#to_top').click(function(){
		goToTop();
		return false;
	});
	
	//bot_nav links
	$('.bot_nav').hover(function(){
		$(this).children('.bot_nav_over').stop().animate({'top' : '0px', 'opacity' : 1}, 200);
		$(this).children('.bot_nav_up').stop().animate({'top' : '40px'}, 100);
		}, function(){
			$(this).children('.bot_nav_over').stop().animate({"top" : '40px', 'opacity' : 1}, 100);
			$(this).children('.bot_nav_up').stop().animate({'top' : '0px'}, 200);
	});
	
	//init browser history
	//$.historyInit(browserCallback, "index.php");
	
	$.address.init(function(event) {
        //console.log("jQuery address API initialized");
    }).change(function(event) {
        var names = $.map(event.pathNames, function(n) {
            return (n.substr(0, 1) + n.substr(1));
        }).concat(event.parameters.id ? event.parameters.id.split('.') : []);
		var links = names.slice();
		var hash = links.length ? links.shift() + '/' + links.join('.') : 'home';
		browserCallback(hash);
    });
	
});

function goToTop(){
	$('html, body').animate({scrollTop:0}, 'slow');
}

function goTo(target){
	//console.log(target);
	if(target == 'top' || $("#" + target).length == 0)
		goToTop();
	else
		$('html, body').scrollTo('#' + target, 550);
	return false;
}

function togglePortfolioOverlay(){
	if(is_expanded){
		is_expanded = false;
		$("#portfolio_toggle img").attr({src : 'assets/images/ui/portfolio_overlay/tab_expand.gif'});
		$('#portfolio_overlay').stop().animate({'top':'-180px'}, 200);
	}
	else{
		is_expanded = true;
		$("#portfolio_toggle img").attr({src : 'assets/images/ui/portfolio_overlay/tab_shrink.gif'});
		$('#portfolio_overlay').stop().animate({'top':'0px'}, 200);
	}
}

function openPortfolioOverlay(){
	if(!is_expanded){
		is_expanded = true;
		$("#portfolio_toggle img").attr({src : 'assets/images/ui/portfolio_overlay/tab_shrink.gif'});
		$('#portfolio_overlay').stop().animate({'top':'0px'}, 200);
	}
}

function closePortfolioOverlay(){
	if(is_expanded){
		is_expanded = false;
		$("#portfolio_toggle img").attr({src : 'assets/images/ui/portfolio_overlay/tab_expand.gif'});
		$('#portfolio_overlay').stop().animate({'top':'-180px'}, 200);
		hidePreview();
	}
}

function detectBrowser(){
	var browser = navigator.appName;
	var b_version = navigator.appVersion;
	var is_qualified = false;
	
	var searchIndex = b_version.indexOf("MSIE");
	var version = parseInt(b_version.substr(searchIndex+5, 2));

	if(version >= 7 || version.toString() == Number.NaN.toString())
		is_qualified = true;

	if ((browser != "Netscape" || browser.toLowerCase().indexOf('microsoft') != -1) && (!is_qualified)){
		var upgrade_browser = confirm("Sorry, this website utilizes CSS and javascript that is not supported by this version of your browser. For a better experience of the web, you should really upgrade to the newest version. \n\nUpgrade your browser now?");
		
		if(upgrade_browser == true){
			window.location = "http://www.google.com/chrome";
		}
		
		else{
			//changeStylesheet('ie6');
		}
	}
}

function changeStylesheet(title) {
	var lnks = document.getElementsByTagName('link');
	for (var i = lnks.length - 1; i >= 0; i--) {
		if (lnks[i].getAttribute('rel').indexOf('style')> -1 && lnks[i].getAttribute('title')) {
			lnks[i].disabled = true;
			if (lnks[i].getAttribute('title') == title) 
				lnks[i].disabled = false;
		}
	}
} 

function createPortfolioLinks(){
	var categories = "design|development|recent";
	sendCategoryRequest(categories);
}

//browser history hash handler function
function browserCallback(hash){
	if(hash) {
		// restore ajax loaded state
		if($.browser.msie) {
			// jquery's $.load() function does't work when hash include special characters like aao.
			hash = encodeURIComponent(hash);
			hash = hash.replace("%2F", "");
		}
		show(hash);
	} else {
		show('home');
	}
}

function show(page){
	//TODO bad code right here
	if(Blog){
		Blog.removeAll();
	}
	
	if(currentPage != page){
		hideInformatics();
		currentPage = page;
		
		if($.browser.msie) {
			page = encodeURIComponent(page);
			page = page.replace("%252F", "/");
		}
		var pageDetail = page.split("/");
		var section = pageDetail[0].toLowerCase();
		var id = pageDetail[1];

		if(section == "home"){
			sendPreviewRequest(currentPreviewProject);
		}
		else{
			sendContentRequest(page);
		}
	}
	else{
		closePortfolioOverlay();
		goToTop();
	}
	return false;
}

function getBrowserSize(){
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} 
	else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} 
	else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}

	return [myWidth, myHeight];
}

function getResolution(){
	var screenW = window.screen.width;
	var screenH = window.screen.height;
	var response = screenW + "|" + screenH;
	return response;
}

function showInformatics(e){
	$("<div id='informatics'>").appendTo("body");
	var onshow = function(){
		enableSmallX();
		var x = e.pageX + 25;
		var w = $("#informatics").width();
		var h = $("#informatics").height();
		var screenW = window.screen.width;
		var y = e.pageY - 100;
		if(x+w+25 > screenW){
			x -= (w + 25);
		}
		$("#informatics").css("left", x).css("top", y);
		$("#informatics").draggable({cursor: 'move'});
		hideLoader();
	};
	showLoader();
	$("#informatics").load("com/informatics.php", onshow).show();
}

function hideInformatics(){
	$("#informatics").remove();
}

function showLoader(){
	$('#preloader').fadeIn(100);
}

function hideLoader(){
	$('#preloader').fadeOut(250);
}

function getPreview(id){
	$.ajax({
		 type: "GET",
		 url: "assets/xml/projects/" + id + ".xml",
		 cache: true,
		 success: function(data){
		 	setPreview(data);
		 }
	 });
}

function setPreview(data){
	previews = [];
	currentPreviewIndex = 0;
	var projId = $(data).find("project").attr("id");
	$(data).find("asset").each(function(){
		var type = $(this).attr("type");
		if(type == "video"){
			var source = $(this).find("source").text();
			source = "../assets/vp_images/vid_thumbs/" + source + ".jpg";
			previews.push(source);
		}
		else if(type == "image"){
			var source = $(this).find("source").text();
			source = "assets/images/projects/" + projId  + "/" + source;
			previews.push(source);
		}
	});
	
	clearInterval(previewTimerId);
	previewTimerId = setInterval(function(){
		$("#preview .image").attr("src", previews[currentPreviewIndex]);
		$("#preview .loader").hide();
		$("#preview .image").show();
		currentPreviewIndex++;
		if(currentPreviewIndex >= previews.length){
			currentPreviewIndex = 0;
		}
	}, 1000);
}

function showPreview(e, id){
	clearInterval(pauseTimerId);
	pauseTimerId = setTimeout(function(){
		getPreview(id);
		$("<div id='preview'><div class='background'></div><div class='imageContainer'><img class='image'/></div><div class='loader'></div></div>").appendTo("body");
		$("#preview .loader").show();
		$("#preview .image").hide();
		movePreview(e);
	}, 500);
}

function hidePreview(){
	$("#preview").remove();
	clearInterval(previewTimerId);
	clearInterval(pauseTimerId);
}

function movePreview(e){
	var x = e.pageX - $("#preview").width() - 10;
	var y = e.pageY - $("#preview").height()/3;
	$("#preview").css("left", x).css("top", y);
}




