
var blog_url;
var theme_url;

var h1Main = '4.5em';
var h2Main = '3em';
var h2Open = h1Main;
var h2OpenSecondary = '2em';
var h2Closed = '1.6em';
var imgThumb = '90px';
var imgThumbSecondary = '4em';
var lineHeight = '1.2em';
var isMobile = false;
var isIE = false;

var projectLoaded = false;
var contentLoaded = new Array();
var recentHash = window.location.hash;
var ignoreHashes = new Array('#top','#cf_field_2','#cf_field_3');
var projectScrollerInitialised = false;
var projectScrollerNecessary = false;

var $j = jQuery;
$j(initPage);
$j(initLinks);

initForIE();

function initForIE() {
	if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}
}


function pollHash() {
	$j('#recentHash').val(recentHash);
	$j('#docHash').val(window.location.hash);
	if(ignoreHashes.indexOf(window.location.hash)>-1) {
		window.location.hash = '';
	}
	if(window.location.hash && recentHash!=window.location.hash) {
		recentHash = window.location.hash;
		window.location.reload();
	}
}


function initUserAgent() {
	var browser=navigator.appName;
	if(navigator.userAgent.indexOf('iPhone')>-1) {
		isMobile = true;
	}
	if(browser=="Microsoft Internet Explorer") {
		isIE = true;
	}
}

function initResizeListener() {
	if(!isIE && !isMobile) {
		$j(window).resize(function() {
			if(projectScrollerInitialised) {
				unloadProjectScroller();
			}
			if($j('#projectList.small').size() > 0) {
				projectScrollerInitialised = false;
				initProjectScroller();
			}
		
		});
	}
}

function initPage() {
	initUserAgent();
	initProjectImages();
	initResizeListener();
	if($j('#projectList.small').size() > 0) {
		initProjectScroller();
	}
	pollHash();
	setInterval(pollHash,500);
	if(isMobile) {
		initForMobile();
	}
	
	var route = (window.location.href.substring(blog_url.length+1));
	if(window.location.hash) {
		if(window.location.hash.substring(1,'showProject='.length)=='showProject') {
			var project = window.location.hash.substring('showProject='.length+1);
			loadContent('projects',project);
		} else if(window.location.hash.substring(1,'newsPage='.length)=='newsPage') {
			var page = window.location.hash.substring('newsPage='.length+1);
			loadContent('news',page);
		} else {
			loadContent(window.location.hash.substring(1));
		}
	}
}

function initLinks() {
	$j('a[onclick]').click(function(event) {
		event.preventDefault();
		return false;
	})
	$j('a[href="#"]').click(function(event) {
		event.preventDefault();
		return false;
	})
	$j('a[href="#top"]').click(function(event) {
		event.preventDefault();
		scroll(0,0);
		$j('a[href="#top"]').fadeOut();  
		return false;
	})
	$j('a[href="#top"]').hide();  
	$j(window).scroll(function () {
		$j('a[href="#top"]').show();  
    });
    $j('.content.news .navigation a').each(function() {
    	var url = $j(this).attr('href');
    	$j(this).attr('href',url.replace('&loader=ajax',''));
    	$j(this).click(function(event) {
    		event.preventDefault();
    		var page = (url.substring((url.indexOf('paged=')+('paged=').length)));
    		if(!Number(page)) {
    			loadNews(1)
    		} else {
    			loadNews(page);
    		}
    		return false;
    	})
    });

}

function initProjectImages() {
	$j('.column.image').each(function() {
		var numImages = 0;
		var id=$j(this).attr('id');
		$j('#'+id+' img').each(function() {
			numImages++;
			$j(this).addClass('stack');
			$j(this).hide();
		});
		$j('#'+id+' img:first').show();
		$j('#'+id+' img:first').addClass('shown');
		$j(this).height($j('#'+id+' img:first').height());
		$j(this).width($j('#'+id+' img:first').width())
		$j(this).css('background-color','white');
		if(numImages>1) {
			$j(this).attr('numImages',numImages);
			$j(this).attr('shownImage',1);
			$j(this).addClass('imageViewer');
			$j(this).prepend('<div class="imgNavigation" id="imgNavigation'+id+'">'+createImgNavLinks($j(this))+'</div>');
			initLinks();
		}
		
	})
}
function initForMobile() {
	isMobile = true;
	h1Main = '3em';
	h2Main = '2.5em';
	h2Open = h1Main;
	h2OpenSecondary = '2em';
	h2Closed = '1.6em';
	lineHeight = '1.4em';
	imgThumb = '6em';
	$j('object').each(function() {
		var altContent = $j(this).attr('alt');
		var type = $j(this).attr('class');
		if(type == 'm4vVideo') {
			$j(this).html('<video id="video" poster="'+altContent+'.png" controls="true" width="300"><source src="'+altContent+'.m4v" type="video/x-m4v"> </video>');
		}
	});
	$j('img').each(function() {
		if($j(this).width()>270) {
			var ratio = 1/$j(this).width()*$j(this).height();
			$j(this).width(270);
			$j(this).height(270*ratio);
		}
	});
	var message = $j('.scf-form-error:first').html();
	if(message) {
		$j('.scf-form-error:first').html('');
		alert(message);
	}
}

function initProjectScroller(id) {
	if(!projectScrollerInitialised && !isIE) {
		$j('body').css('backgroud','red');
		var offset = $j('#projectList').offset();
		var availableWidth = $j('body').width()-offset.left-40;
		
		var itemWidth = $j('#projectList li:first').width()+9;
		var numItems = $j('#projectList li').size();
		var visibleItems = Math.ceil(availableWidth/itemWidth);
		
		if(numItems>visibleItems) {
			if(!id && projectLoaded) {
				id = projectLoaded;
			}
			projectScrollerNecessary = true;
			var count = 0;
			var start = 1;
			if(id) {
				$j('#projectList li').each(function() {
					count++;
					if($j(this).attr('id') == 'project'+id) {
						start = count;
					}
				});
			}
			$j('#projectList').addClass('jcarousel-skin-klfk');
			$j('#projectList').wrap('<div id="projectScroller" style="width:'+availableWidth+'px" />');
			$j('#projectList').addClass('small');
			$j('#projectList').css('left','0px');
			$j('#projectList').jcarousel({
				visible: visibleItems,
				scroll:3,
				start: start,
				easing: 'easeOut' 
			});
		}
		projectScrollerInitialised = true;
	}
}

function unloadProjectScroller() {
	if(projectScrollerInitialised && projectScrollerNecessary) {
		projectScrollerInitialised = false;
		$j('#projectList').removeClass();
		$j('#projectList').css('width','');
		$j('#projectList').css('left','');
		$j('#projectList li').removeClass();
		$j('#projectList li').attr('jcarouselindex','');
		$j('#projectList li').css('width','');
		$j('#projectsContainer').prepend($j('#projectList'));
		$j('#projectScroller').remove();
		$j('#projectsContainer').append('<div class="clear"></div>');
		if(projectLoaded) {
			$j('#projectList').addClass('small');
		}
	}	
}


function nextImage(id) {
	var numImages = $j('#'+id).attr('numImages');
	var shownImage = $j('#'+id).attr('shownImage');
	numImages = Number(numImages);
	shownImage = Number(shownImage);
	if(shownImage<numImages) {
		var transitionDone = false;
		$j('#'+id+' img').each(function() {
			if($j(this).hasClass('shown') && !transitionDone) {
				$j(this).fadeOut(function() {
					$j('#'+id).animate({
						height:$j(this).next().height(),
						width:$j(this).next().width()
					},300,'linear')
					$j(this).next().fadeIn(500);});
				$j(this).removeClass('shown');
				$j(this).next().addClass('shown');
				transitionDone=true;
				shownImage++;
				$j('#'+id).attr('shownImage',shownImage);
				$j('#imgNavigation'+id).html(createImgNavLinks($j('#'+id)));
				initLinks();
			}
		});
		$j('#'+id+' img').each(function() {
			if(!$j(this).hasClass('shown')) {
				$j(this).hide();
			}
		});
	}
}


function prevImage(id) {
	var numImages = $j('#'+id).attr('numImages');
	var shownImage = $j('#'+id).attr('shownImage');	numImages = Number(numImages);
	shownImage = Number(shownImage);
	if(shownImage>1) {
		var transitionDone = false;
		$j('#'+id+' img').each(function() {
			if($j(this).hasClass('shown') && !transitionDone) {
				$j(this).fadeOut(function() {
					$j('#'+id).animate({
						height:$j(this).prev().height(),
						width:$j(this).prev().width()
					},300,'linear')
					$j(this).prev().fadeIn(500);});
				$j(this).removeClass('shown');
				$j(this).prev().addClass('shown');
				transitionDone=true;
				shownImage--;
				$j('#'+id).attr('shownImage',shownImage);
				$j('#imgNavigation'+id).html(createImgNavLinks($j('#'+id)));
				initLinks();
			}
		});
	}
}



function createImgNavLinks(object) {
	var shownImage = object.attr('shownImage');
	var numImages = object.attr('numImages');
	shownImage = Number(shownImage);
	numImages = Number(numImages);
	var id=object.attr('id');
	navLinks = '';
	if(shownImage>1) {
		navLinks += "<span style='float:left;'><a onclick='prevImage(\""+id+"\")'>&nbsp;&lt;</a></span> ";
	}
	navLinks +=shownImage+'/'+numImages;
	if(shownImage<numImages) {
		navLinks += " <span style='float:right;'><a onclick='nextImage(\""+id+"\")'>&gt;&nbsp;</a></span>";
	}
	return navLinks;
}


function loadContent(content,id) {
	transition(content);
	if(contentLoaded.indexOf(content)==-1) {
		$j('#'+content+'Container').html('<img class="loader" src="'+theme_url+'/images/ajax-loader.gif">');
	}
	if(content == 'projects' && contentLoaded.indexOf(content)==-1) {
		$j('#projectsContainer').load(blog_url+'?cat=3&loader=ajax',function() {
			if(id) {
				loadProject(id);
			}
			initLinks();
		});
	} else if (content == 'projects' && id) {
		loadProject(id);
		initLinks();
	} else if(content == 'news' && contentLoaded.indexOf(content)==-1) {
		$j('#newsContainer').load(blog_url+'?cat=4&loader=ajax&paged='+id,function() {
			if(id) {				
				window.location.hash = 'newsPage='+id;
				recentHash = window.location.hash;
			}
			initLinks();
		});
	} else if(content == 'about' && contentLoaded.indexOf(content)==-1) {
		$j('#aboutContainer').load(blog_url+'?p=2&loader=ajax',function() {
			initLinks();
		});
	} else if(content == 'contact' && contentLoaded.indexOf(content)==-1) {
		$j('#contactContainer').load(blog_url+'?p=10&loader=ajax',function() {
			initLinks();
		});
	}
	contentLoaded.push(content);
}

function loadProject(id,title) {
	window.location.hash = 'showProject='+id;
	recentHash = window.location.hash;
	if(!projectLoaded) {
		transitionLoadProject(id);
		projectLoaded = id;
	}
	$j('#projectContent').fadeOut('300',function() {
		if(title) {
			$j('#projectContent').html("<h3>"+title+"</h3>");	
		} else {
			$j('#projectContent').html('');	
		}
		$j('#projectContent').append('<img class="loader" src="'+theme_url+'/images/ajax-loader.gif">');
		$j('#projectContent').show();
		$j('#projectContent').load(blog_url+'?p='+id+'&loader=ajax',function() {
			$j('#projectContent').fadeIn('300');
			initLinks();
			if(isMobile) {
				initForMobile();
			}
			initProjectImages();
			
		});
	});
}


function loadNews(page) {
	window.location.hash = 'newsPage='+page;
	recentHash = window.location.hash;
	$j('#newsContent').fadeOut('300',function() {
		$j('#newsContent').html('<img class="loader" src="'+theme_url+'/images/ajax-loader.gif">');
		$j('#newsContent').show();
		$j('#newsContent').load(blog_url+'?cat=4&paged='+page+'&loader=ajax',function() {
			$j('#newsContent').fadeIn('300');
			initLinks();
			if(navigator.userAgent.indexOf('iPhone')>-1) {
				initForMobile();
			}
		});
	});
}

function unloadProject() {
	$j('#projectContent').slideUp('300');
	projectLoaded = false;
	window.location.hash = 'projects';
	recentHash = window.location.hash;
		$j('#projectList img').animate({
			height: imgThumb,
			width: imgThumb
		},300,'linear');
		$j('#page').animate({
			top:'12%'
		},300,'linear');
		$j('#projectsTitle').animate({
			fontSize: h2Open
		},300,'linear');
	unloadProjectScroller();
}

function transition(focus) {
	window.location.hash = focus;
	recentHash = window.location.hash;
	if(focus != 'main') {
		$j.each($j('#page > h1,#page > h2'), function() {
			if($j(this).hasClass(focus) && !$j(this).hasClass('open')) {
				if(focus=='projects' && projectLoaded) {						
					transitionLoadProject();
				} else {
					$j(this).animate({
						fontSize: h2Open
					}, 300,'linear');
				}
				$j(this).next().slideDown(300);
				$j(this).addClass('open');
			} else  {
				if($j(this).hasClass(focus) && focus=='projects' && projectLoaded) {
					unloadProject();
				} else {
					$j(this).next().slideUp(200);				
					$j(this).animate({
						fontSize: h2Closed,
						lineHeight: lineHeight
					}, 300,'linear');
					$j(this).removeClass('open');
				}
			}		
		})
	} 
	var isOpen = false;
	$j.each($j('#page > h1,#page > h2'), function() {
		if($j(this).hasClass('open')) {	
			isOpen = true;
		}
	});
	if(!isOpen || focus=='main') {
		$j('#page').animate({
			top:'12%'
		},300,'linear');
		$j('#page h1').animate({
			fontSize: h1Main
		},100,'linear');
		$j('#page h2').animate({
			fontSize: h2Main,
			lineHeight: lineHeight
		},100,'linear');
		$j.each($j('#page > h1,#page > h2'), function() {
			$j(this).next().slideUp(300);
			$j(this).removeClass('open');
		});
	}
	if(projectLoaded && focus!='projects') {		
		$j('#page').animate({
			top:'12%'
		},300,'linear');

	}
}

function transitionLoadProject(id) {
	$j('#projectList').addClass('small');
	$j('#projectList img').animate({
		height: imgThumbSecondary,
		width: imgThumbSecondary
	},300,'linear',function() {initProjectScroller(id);});
	$j('#page').animate({
		top:'1%'
	},300,'linear');
	$j('#projectsTitle').animate({
		fontSize: h2OpenSecondary,
		lineHeight: h2OpenSecondary
	},300,'linear');
}

jQuery.easing['easeOut'] = function (x, t, b, c, d) {
	return c * Math.sin(t/d * (Math.PI/2)) + b;
}
