var currentPage;
var currentCode;
var json;
var hashFilter = {"/Featured/":0, "/Identity/":1, "/Print/":2, "/Interactive/":3, "/Multimedia/":4, "/Archviz/":5, "/Show-All/":9};
var hashFilterTitle = {"/Featured/":"Featured", "/Identity/":"Identity", "/Print/":"Print", "/Interactive/":"Interactive", "/Multimedia/":"Multimedia", "/Archviz/":"Architectural Vizualizations", "/Show-All/":"Show All"};
var mapFilter = {"/Featured/":"featured", "/Identity/":"identity", "/Print/":"print", "/Interactive/":"interactive", "/Multimedia/":"multimedia", "/Archviz/":"archviz", "/Show-All/":"showall"};
var project_type =new Array("Null", "Identity", "Print", "Interactive", "Multimedia", "Archviz");

$(function(){	
	$("div.scrollable").scrollable({
		onSeek: function() {         
			change_navigator();
		},  
		size: 4,
		clickable: false
	});
	
	// read the xml
	read_xml();
	
	$('.prev-item').addClass('first-item');
	
	$('.prev-item img').click(function(){
		var api = $("div.scrollable:first").scrollable();
		if (api.getIndex()<4) api.prevPage();
		else api.move(-4);		
		change_navigator();
		$("#tooltip4").fadeOut();
	});
	
	$('.next-item img').click(function(){
		var api = $("div.scrollable:first").scrollable();
		if ((api.getIndex()+8)>api.getSize()) api.nextPage();
		else api.move(4);
		change_navigator();
		$("#tooltip5").fadeOut();
	});

	$("#submit").click(function() {
		//var ajaxOptions = {success: showResponse}; 	
		if ($("#newsletterform").valid()) {
			$('#newsletterform').ajaxForm({success: showResponse});
		}
	});
	
	simple_tooltip("#Map area, .prev-item, .next-item, #sup-nav a","tooltip");
	$("body").find("div.tooltip p").each(function(){
		var newToolTip = $(this).text();
		newToolTip = newToolTip.replace(/\^/g,'<br />');	
		newToolTip = newToolTip.replace('*!','</strong>');
		newToolTip = newToolTip.replace('*','<strong>');
		newToolTip = newToolTip.replace('~!','</u>');
		newToolTip = newToolTip.replace('~','<u>');	
		$(this).html(newToolTip);
	});
	
	$('a[href^="http://"]')
	  .attr({
    	target: "_blank"
	});
});

function fix1024() {
	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;
	}
	if (myWidth <=1024 && myWidth >900)
	{
		$('#navi-item .navi-item-container').css('width', (myWidth-20)+'px');
		$('#navi-item .navi-item-container ul').css('width', (myWidth-20)+'px');
	} 
	else
	{

	}
}

function showResponse(responseText, statusText)  { 
	$("div.newsletter").append("<label class='error'>"+responseText+"</label>")
}

function show_gallery_scrollable()
{
	$("#gallery").scrollable({
		size: 1,
		loop: true,
		items: '.gallery',
		onSeek: function() {         
			change_scrollable_navigator();
		}
	});
	
	$(".next-image").live('click', function(){
		var api = $("div#gallery:first").scrollable();
		api.next();			
		change_scrollable_navigator();	
		return false;
	});

	$(".prev-image").live('click', function(){
		var api = $("div#gallery:first").scrollable();
		api.prev();			
		change_scrollable_navigator();
		return false;
	});
}

function change_scrollable_navigator()
{
	var api = $("div#gallery:first").scrollable();
	var text = (api.getIndex()+1) + ' of ' + api.getSize();
	$('#navi-gallery span').html(text);
}

function read_xml()
{
	$.get('xml/projects_en.xml', function(xml){
		json = $.xml2json(xml);
		
		if (document.location.href.split('#')[1] && IsNumeric(document.location.href.split('#')[1])) 
		{
			currentCode = getVal(document.location.href.split('#')[1]);
			currentPage = "/Show-All/";
			show_project_by_code(currentCode);			
			$('body').attr('class',mapFilter[currentPage]);
			filter_json(currentPage);			
		};
		
		$('body').everyTime(100, 'timer', function(i) {
			historycheck();
		});		
	})
}

function detect_filter(new_page)
{
	var page;
	if (new_page) page = new_page;
	else if (document.location.href.split('#')[1]) 
	{ 
		if (!IsNumeric(document.location.href.split('#')[1])) page = document.location.href.split('#')[1];
		else if (currentPage) page = currentPage;
		else page = "/Featured/";
	}
	else page = "/Featured/";
	return page;
}

function getVal(inputVal)
{
	return inputVal.replace('/','').split('/')[0];
}

function IsNumeric(inputVal, outputVal) {
    if (isNaN(parseFloat(getVal(inputVal)))) {
        return false;
    };
    return true;
}


function filter_json(new_page)
{
	if (json.prj.lenght==0) return;
	
	var section = detect_filter(new_page);
	$('body').attr('class',mapFilter[section]);
	
	var filter = hashFilter[section];
	
	var api = $("div.scrollable:first").scrollable();
	
	$('#lst').css('width',(json.prj.length*250)+'px');
	$('#lst').html('');

	if ($('#current-project').css('display')=='none') changeTitle(hashFilterTitle[section]);
	//Tracker
	pageTracker._trackEvent(hashFilterTitle[section], 'View Category');
	
	// filter type
	if (filter >= 1 && filter <= 5)
	{	
		$.each(json.prj, function(i, item){
			if (item.tid == filter)
			{
				var text = '<div class="item" id="project_'+i+'"><a href="' + generate_link(item.id, item.c, item.n) + '">';
				text += '<img src="'+item.f+'/project_thumb.jpg" alt="' + item.c + ' : ' + item.n + '" width="220" height="370" />';
				text += '<span class="client-name">' + '<b>' + item.c + '</b>' + '<br /><em>' + item.n + '</em><br /><span class="date">' + item.dt + ' / ' + project_type[item.tid] + '</span></span>';
				if (item.ft == "F" && item.flv !="0") text += '<span class="featured">&#9733; &#9658;</span>';
				else if (item.ft == "F") text += '<span class="featured">&#9733;</span>';
				else if (item.flv !="0") text += '<span class="featured">&#9658;</span>';
				text += '</a></div>';
				api.getItemWrap().append(text);
			}
		});	
	}
	// all
	else if (filter == 9)
	{
		$.each(json.prj, function(i, item){
			var text = '<div class="item" id="project_'+i+'"><a href="' + generate_link(item.id, item.c, item.n) + '">';
			text += '<img src="'+item.f+'/project_thumb.jpg" alt="' + item.c + ' : ' + item.n + '" width="220" height="370" />';
			text += '<span class="client-name">' + '<b>' + item.c + '</b>' + '<br /><em>' + item.n + '</em><br /><span class="date">' + item.dt + ' / ' + project_type[item.tid] + '</span></span>';
			if (item.ft == "F" && item.flv !="0") text += '<span class="featured">&#9733; &#9658;</span>';
			else if (item.ft == "F") text += '<span class="featured">&#9733;</span>';
			else if (item.flv !="0") text += '<span class="featured">&#9658;</span>';
			text += '</a></div>';
			api.getItemWrap().append(text);
		});
	} 
	// featured 
	else 
	{
		$.each(json.prj, function(i, item){
			if (item.ft == "F")
			{
				var text = '<div class="item" id="project_'+i+'"><a href="' + generate_link(item.id, item.c, item.n) + '">';
				text += '<img src="'+item.f+'/project_thumb.jpg" alt="' + item.c + ' : ' + item.n + '" width="220" height="370" />';
				text += '<span class="client-name">' + '<b>' + item.c + '</b>' + '<br /><em>' + item.n + '</em><br /><span class="date">' + item.dt + ' / ' + project_type[item.tid] + '</span></span>';
				if (item.ft == "F" && item.flv !="0") text += '<span class="featured">&#9733; &#9658;</span>';				
				else if (item.flv !="0") text += '<span class="featured">&#9658;</span>';
				else text += '<span class="featured">&#9733;</span>';
				text += '</a></div>';
				api.getItemWrap().append(text);
			}
		});
	
	}
	
	api.reload().begin();
	change_navigator();
	atach_events_to_item();
}
function generate_link(id, client, name)
{
	return "#/" + id + "/" + filterInput(client) + "/" + filterInput(name) + "/";
}

function filterInput(input)
{
	input = input.replace(/'/g,'');	
	input = input.replace(/&/g,'');	
	input = input.replace(/  /g,' ');	
	input = input.replace(/ /g,'-');	
	return input;
}

function simple_tooltip(target_items, name){
	$(target_items).each(function(i){
		$("body").append("<div class='"+name+"' id='"+name+i+"'><p>"+$(this).attr('title')+"</p></div>");
		var my_tooltip = $("#"+name+i);
		if($(this).attr("title") != ""){ // checks if there is a title
			$(this).removeAttr("title").mouseover(function(){
					my_tooltip.css({display:"none"}).fadeIn(200);
			}).mousemove(function(kmouse){
					if ($(this).attr('class') == "next-item") {
						my_tooltip.css({left:kmouse.pageX-45, top:kmouse.pageY+15})
					}
					else if ($(this).hasClass('sided')) {
						my_tooltip.css({left:kmouse.pageX-(my_tooltip.width()+15), top:kmouse.pageY+15})
					}
					else if ($(this).attr('href') == "http://blog.x3studios.ro/") my_tooltip.css({left:kmouse.pageX-155, top:kmouse.pageY+15});
					else my_tooltip.css({left:kmouse.pageX+15, top:kmouse.pageY+15});
			}).mouseout(function(){
					my_tooltip.fadeOut(200);
			});		
		}				
	});
}

function change_navigator()
{
	var api = $("div.scrollable:first").scrollable();
	var text = (api.getIndex()+1) + ' - ' + (api.getIndex()+4) + ' of ' + api.getSize();
	$('span.navi-perpage').html(text);
	
	if (api.getIndex() != 0) 
	{
		$('.prev-item').removeClass('first-item').fadeTo(0.5, 1);
		
		$('.prev-item').hover(function(){
			$('#tooltip4').show();			
		});
	}
	else 
	{
		$('.prev-item').addClass('first-item').fadeTo(1, 0.5);
		
		$('.prev-item').hover(function(){
			$('#tooltip4').hide();			
		});
	}
	
	if (api.getIndex()+4 != api.getSize()) 
	{
		$('.next-item').removeClass('last-item').fadeTo(0.5, 1);
		
		$('.next-item').hover(function(){
			$('#tooltip5').show();			
		});
	}
	else 
	{
		$('.next-item').addClass('last-item').fadeTo(1, 0.5);
		
		$('.next-item').hover(function(){
			$('#tooltip5').hide();			
		});
	}
	
}

function atach_events_to_item(){
	$("div.item").hover(function(){
		$(this).addClass("hover");
	}, function(){
		$(this).removeClass("hover");
	});
}

function show_project(id)
{
	var section = detect_filter();
	changeTitle(json.prj[id].c + ' / ' + json.prj[id].n);

	//Tracker
	pageTracker._trackEvent(hashFilterTitle[section], 'Open Project', json.prj[id].c + ' / ' + json.prj[id].n);
	
	var text = '<div id="project-details">';
	text += '<div class="project-details-area"> <a href="#' + currentPage + '" class="close-window"><img src="img/icn-close.png" alt="Close window" /></a>';
	text += '<div id="gallery">';
	text += '<ul class="gallery itm">';
	
	var total1 = json.prj[id].flv;
	for (var i=1; i<=total1; i++)
	{
		// calea = json.prj[id].f + '/'+ ((i<10)?"0"+i:i) +'.flv
		// descriere = json.prj[id].c + ' - ' + json.prj[id].n
		text += '<li>';
		text += '<object width="650" height="552">';
		text += '<param name="movie" value="swf/player.swf">';
		text += '<param name="wmode" value="opaque">';
		text += '<param name="flashvars"  value="flv=../' + json.prj[id].f + '/'+ ((i<10)?"0"+i:i) +'.flv' + '">';
		text += '<embed src="swf/player.swf" width="650" height="552" wmode="opaque" flashvars="flv=../' + json.prj[id].f + '/'+ ((i<10)?"0"+i:i) +'.flv' + '">';
		text += '</embed>';
		text += '</object>';
		text += '</li>';
	}	
	
	var total2 = json.prj[id].img;
	for (var i=1; i<=total2; i++)
	{
		text += '<li><img src="' + json.prj[id].f + '/'+ ((i<10)?"0"+i:i) +'.jpg" width="650" height="552" alt="' + json.prj[id].c + ' - ' + json.prj[id].n + '" /></li>';
	}	
	text += '</ul>';
	
	var total = parseInt(total1) + parseInt(total2);
	
	if (total <=1) text += '<div id="navi-gallery" class="oneimage noimages"> <span>1 of ' + total + '</span>';
	else text += '<div id="navi-gallery"> <span>1 of ' + total + '</span>';
	
	text += '<ul>';
	text += '<li><a href="#" class="prev-image">Previous image</a></li>';
	text += '<li><a href="#" class="next-image">Next image</a></li>';
	text += '</ul>';
	text += '</div>';
	text += '</div>';
	
	text += '<div class="proj-info"><h4><span>' + json.prj[id].c + '</span></h4><h3><span>' + json.prj[id].n + '</span></h3>';
	text += '<p>';
	text += json.prj[id].dsc;
	text += '</p></div>';
	text += '</div>';
	text += '</div>';
	$('#current-project').html(text).hide().show();
	
	$('#navi-item').hide();
	
	show_gallery_scrollable();		
}

function show_project_by_code(code)
{
	var id=-1;
	
	for (var j=0; j<json.prj.length;j++)
	{
		if (json.prj[j].id == code) id = j;
	}
	
	if (id!=-1) 
	{
		show_project(id);		
	}
}


function historycheck()
{		
	var section;
	if (document.location.href.split('#')[1]) {
		section = document.location.href.split('#')[1];			
		if (IsNumeric(document.location.href.split('#')[1])) 
		{
			if (currentPage) section = currentPage;
			else section = "/Show-All/";

			var code = getVal(document.location.href.split('#')[1]);
			if (currentCode!=code)
			{				
				currentCode=code;		
				show_project_by_code(currentCode);
			}
		}
		else if ($('#current-project').css('display')=='block')
		{			
			$('#current-project').hide();			
			$('#navi-item').show();
			changeTitle(hashFilterTitle[section]);			
			currentCode="";				
		}
	} else 
	{
		section = "/Featured/";
	}
	
	
	if (section != currentPage) 
	{
		$('body').attr('class',mapFilter[section]);
		currentPage = section;				
		currentCode = "";
		filter_json(section);
	}	
	
	fix1024();
	
}

function changeTitle(title) { 
	if (title!='') document.title = 'We are X3 Studios / ' + title; 
	else document.title = 'We are X3 Studios'; 
}
