$(function() {
	if (navigator.userAgent.search('MSIE 6.0') != -1) {
		ie6.insertPie().hoverHack().menuHack();
		$('#ie6-popup .close').live('click', ie6.hidePie);
	}
	$('p#a-rond').html(
			'<a' + ' hre' + 'f=' + 'mai' + 'lto:' + 'biro' + '@p' + 'ukka.ro'
					+ '>biro' + '@p' + 'ukka.ro' + '<' + '/a>');
	$.History.bind(function(state) {
		if (state == '') {
			location.href = request.defaultFilter;
		} else {
			window.scrollTo(0, 0);
			// we allways want them scroolbars
			$('html').height('101%');
			$('div.project').remove();
			request.start = 0;
			pageContent.canHasMore = false;
			request.filter = state;
			pageContent.load();
		}
	});
	pageContent.init();
	login.init();
	activeMenu();
});

var request = {
	start : 0,
	count : 5,
	filter : 'all',
	defaultFilter : 'all/projects'
}

var flash = {
	movies : undefined,
	frame : $('#flash-frame'),
	index : 0,
	maxIndex : 0,
	scrollPosition : 0,
	flashIn : function() {
		flash.scrollPosition = window.pageYOffset;
		var p = flash.movies[flash.index];
		flash.frame.addClass(p.flashFrame);
		swfobject.embedSWF(p.flashUrl, 'flash-movie', p.flashX, p.flashY,
				'6.0.0', 'swf/expressInstall.swf', p.flashvars, p.flashParams,
				p.attributes);
		$('#flash-movie').css(p.flashCoords); // .unbind().bind('click',
		// function(event){event.stopPropagation();});
		// $('#flash-frame .jScrollPaneTrack').unbind().bind('click',
		// function(event){event.stopPropagation();});
		$('#flash-frame ul.navigation li').addClass('no-click');
		flash.frame
				.addClass('moving')
				.animate(
						{
							'left' : $('#page').offset().left + 'px'
						},
						250,
						function() {
							$('html').addClass('flash-demo-active').css( {
								'height' : $(window).height() + 'px'
							});
							$('#flash-frame ul.navigation li').removeClass(
									'no-click');
							if (flash.index == 0)
								flash.frame.attr('class',
										'at-first-movie ' + p.flashFrame);
							if (flash.index == flash.maxIndex)
								flash.frame.attr('class',
										'at-last-movie ' + p.flashFrame);
							if (flash.index == flash.maxIndex
									&& flash.index == 0)
								flash.frame
										.attr(
												'class',
												'at-first-movie at-last-movie ' + p.flashFrame);
							flash.frame.removeClass('moving');
						});
		// $('body').unbind().bind('click', flash.off);
	},
	out : function(direction) {
		whereTo = direction == 'left' ? $(window).width() * -1.2 : $(window)
				.width() * 2.2;
		flash.frame.css( {
			left : whereTo + 'px'
		}).attr('class', '');
		flash.frame.find('.scroll-frame').get(0).scrollTo(0);
	},
	showNav : function() {
		var pieRight;
		// ie6 hack, care nu stie position fixed, deci e pe absolute, drept pt.
		// care
		// pozitia .pie se raporteaza la #flash-frame si nu la body
		navigator.userAgent.search('MSIE 6.0') != -1 ? pieRight = 32
				: pieRight = $('#page').offset().left + 32;
		$('#flash-frame .pie').css( {
			right : pieRight + 'px'
		});
	},
	init : function() {
		currentProject = $(arguments[0].target).parents('.project');
		flash.movies = currentProject.data('projectMovies');
		flash.maxIndex = flash.movies.length - 1;
		flash.index = 0;
		if (!currentProject.hasClass('special')) {
			flash.showNav();
			flash.flashIn();
		} else {
			var currentSlide = $(arguments[0].target).parents('li');
			var allSlides = currentProject.children('.multimedia').children(
					'ul.pictures').children('li');
			flash.index = allSlides.index(currentSlide);
			window.open(flash.movies[flash.index].flashUrl);
		}
	},
	prev : function() {
		flash.index--;
		flash.out('left');
		flash.flashIn();
	},
	next : function() {
		flash.index++;
		flash.out();
		flash.flashIn();
	},
	off : function() {
		flash.out();
		$('html').removeClass('flash-demo-active').css( {
			'height' : 'auto'
		});
		// $('body').unbind();
	window.scrollTo(0, flash.scrollPosition);
},
navigate : function(event) {
	event.stopPropagation();
	var $_this = $(arguments[0].target);
	if (!$_this.hasClass('no-click')) {
		if ($_this.hasClass('nextFlash') && (flash.index < flash.maxIndex))
			flash.next();
		else if ($_this.hasClass('prevFlash') && flash.index > 0)
			flash.prev();
		else
			flash.off();
	}
}
};

function activeMenu() {
	var clientsDiv = document.getElementById('clients');
	// .hover sucks donkey cocks
	clientsDiv.mouseIsOver = false;
	clientsDiv.onmouseover = function() {
		this.mouseIsOver = true;
	};
	clientsDiv.onmouseout = function() {
		this.mouseIsOver = false;
	};
	function openMenu() {
		if (clientsDiv.mouseIsOver == true)
			$('#clients').animate( {
				width : '1000px'
			}, 500, 'easeInSine');
	}
	function closeMenu() {
		if (clientsDiv.mouseIsOver == false)
			$('#clients').animate( {
				width : '420px'
			}, 500, 'easeOutQuint');
	}
	$('#menu .section#clients').mouseenter(function() {
		setTimeout(openMenu, 500)
	});
	$('#menu .section#clients').mouseleave(function() {
		setTimeout(closeMenu, 500)
	});
}

var login = {
	defaultLoginText : 'client',
	redirectBase : 'test/',
	redirectPage : undefined,
	init : function() {
		$('#client').bind('focus', login.focus).bind('blur', login.blur);
		$('#login-form').bind('submit', login.auth);
	},
	focus : function() {
		if ($(this).val() == login.defaultLoginText)
			$(this).val('');
	},
	blur : function() {
		if ($(this).val() == '')
			$(this).val(login.defaultLoginText);
	},
	header : function(req) {
		var auth = Base64.encode($('#client').val() + ':'
				+ $('#password').val());
		req.setRequestHeader('Authorization', 'Basic ' + auth);
	},
	auth : function() {
		login.redirectPage = login.redirectBase + '?' + $('#client').val()
				+ '&' + (new Date).getTime();
		var ajaxOptions = {
			url : login.redirectPage,
			method : 'GET',
			beforeSend : login.header,
			error : login.error,
			success : login.redirect
		}
		$.ajax(ajaxOptions);
		return false;
	},
	error : function(req, error, exception) {
		console.log('error', error, exception);
	},
	redirect : function(data, status) {
		console.log(status);
		// location.href = login.redirectPage;
}
}

var pageContent = {
	// load more? not if we're done or just loading
	canHasMore : true,
	// fetches the projects from the tubes
	load : function() {
		pageContent.setTitle('loading...');
		if (!arguments[0])
			$('#loading').show();
		// $.getJSON('json/?filter=' + request.filter + '&start=' +
		// request.start + '&count=' + request.count, pageContent.parseJSON);
		$.getJSON('?filter=' + request.filter + '&start=' + request.start
				+ '&count=' + request.count + '&ajax=1', pageContent.parseJSON);
	},
	// the user is anxious to see our work
	scrollDown : function(event) {
		var loadAnyway = arguments[1];
		var hideLoading = arguments[2];
		if (($(window).scrollTop() + 3 * $(window).height() >= $(document)
				.height() || loadAnyway)
				&& pageContent.canHasMore) {
			pageContent.canHasMore = false;
			pageContent.load(hideLoading);
		}
	},
	setTitle : function(newTitle) {
		var titleHTML = '<span>' + newTitle.split(':')[0] + '</span> '
				+ newTitle.split(':')[1];
		newTitle == 'loading...' ? $('h2#location').html(newTitle) : $(
				'h2#location').html(titleHTML);
		document.title = "PUKKA | " + newTitle.replace(':', ' > ');
	},
	parseJSON : function() {
		$('#page p.eof').remove();
		var newTitle = request.filter.replace(/_/g, ' ').replace('/', ": ")
				.ucfirst();
		pageContent.setTitle(arguments[0].filter.type + ':'
				+ arguments[0].filter.value);
		$('#loading').hide();
		var projects = arguments[0].projects;
		if (!projects.length) {
			pageContent.canHasMore = false;
			request.start = 0;
			$('#page').append('<p class="eof">THE END.</p>');
		} else {
			for (i = 0; i < projects.length; i++) {
				var projectIndex = request.start + i;
				thisProject = '#project-' + projectIndex;
				var slides = '';
				for (p = 0; p < projects[i].slides.length; p++) {
					var slidesTemplate = '<li id="project-' + i + '-slide-' + p
							+ '"><img src="' + projects[i].slides[p].slideUrl
							+ '" alt="' + projects[i].slides[p].slideTitle
							+ '"></li>';
					slides += slidesTemplate;
				}
				if (projects[i].linkURL != undefined) {
					var goWWW = '<a class="go-www removable out" href="out?query=' + projects[i].linkURL + '">VISIT<br>WEBSITE</a>';
					var liWWW = '<li class="link"><a class="out" href="out?query='
							+ projects[i].linkURL
							+ '">'
							+ projects[i].linkText
							+ '</a></li>';
					var navWWW = '<li class="go-to-site">Go to site</li>';
				} else {
					var goWWW = liWWW = navWWW = '';
				}
				var projectTemplate = '<div style="display:none" class="project clearfix '
						+ projects[i].type
						+ '" id="project-'
						+ projectIndex
						+ '">'
						+ '<ul class="project-details"><li><h3>Project Name</h3><h4>'
						+ projects[i].name
						+ '</h4></li><li><h3>Client</h3><h4>'
						+ projects[i].client
						+ '</h4></li>'
						+ '<li class="description"><h3>Case Description</h3>'
						+ projects[i].caseDescription
						+ '</li>'
						+ liWWW
						+

						'<li class="permalink last"><h3>Project link:</h3><form><input type="text" value="'
						+ location.href.replace(location.hash,
								'#project/' + projects[i].alias.replace('&',
										'+'))
						+ '"></form></li></ul>'
						+ '<div class="multimedia">'
						+ goWWW
						+ '<ul class="pictures">'
						+ slides
						+ '</ul>'
						+ '<ul class="navigation"><li class="prevImage">Previous</li><li class="nextImage">Next</li>'
						+ navWWW
						+ '</ul></div>'
						+ '<span class="jump" title="Jump to top">Jump to top</span>'
						+ '</div>';
				$('#page').append(projectTemplate);
				$(thisProject).fadeIn('slow')
				$('.flash' + thisProject).data('projectMovies',
						projects[i].movies);
				$('.flash' + thisProject + ' ul.pictures li')
						.each(
								function() {
									$(this)
											.append(
													'<span class="clicker">VIEW<br>BANNER</span>');
								});
				$(thisProject + ' ul.pictures li:first').addClass('current');
				$(thisProject + ' ul.pictures li:last').hasClass('current') ? $(
						thisProject + ' .multimedia').addClass('single-image')
						: $(thisProject + ' .multimedia').addClass(
								'at-first-image');
			}
			$('.project').removeClass('last');
			$('.project:last').addClass('last');
			// track to Google Analytics
			if (request.start == 0)
				pageTracker._trackPageview("/" + request.filter);
			// re-enable loadable page
			pageContent.canHasMore = true;
			// reset start
			request.start += projects.length;
		}
	},
	showGoWWW : function() {
		thisClicked = arguments[0].target;
		if ($(thisClicked).parents('.multimedia').children('a.go-www')
				.hasClass('visible')) {
			$(thisClicked).parents('.multimedia').children('a.go-www').slideUp(
					200, function() {
						$(this).removeClass('visible');
					});
		} else {
			$(thisClicked).parents('.multimedia').children('a.go-www')
					.slideDown(200, function() {
						$(this).addClass('visible');
					});
		}
		;
	},
	navigateImages : function() {
		var $_this = $(arguments[0].target);
		var pictures = $_this.parents('.multimedia').children('.pictures');
		var picturesLeft = pictures.position().left;
		var direction = $_this.hasClass('nextImage') ? -1 : 1;
		var ending = $_this.hasClass('nextImage') ? pictures
				.children('li:last') : pictures.children('li:first');
		var noMore = $_this.hasClass('nextImage') ? 'at-last-image'
				: 'at-first-image';
		var following = $_this.hasClass('nextImage') ? pictures.children(
				'li.current').next() : pictures.children('li.current').prev();
		if (!pictures.hasClass('moving') && !ending.is('.current')) {
			pictures.parents('.multimedia').attr('class', 'multimedia');
			pictures.addClass('moving').animate( {
				'left' : picturesLeft + (direction * 555) + 'px'
			}, 500, function() {
				pictures.removeClass('moving')
			}).children('li').removeClass('current');
			following.addClass('current');
			if (ending.is('.current'))
				$_this.parents('.multimedia').addClass(noMore);
		}
		if ($_this.parents('.multimedia').children('a.go-www').hasClass(
				'visible'))
			$_this.parents('.multimedia').children('a.go-www').slideUp(200,
					function() {
						$(this).removeClass('visible');
					})
	},
	init : function() {
		if (!location.hash)
			location.hash = request.defaultFilter;
		$(window).scroll(pageContent.scrollDown);
		$('#menu ul li a').click(
				function() {
					$('#menu ul li a.active').removeClass('active').addClass(
							'visited');
					$(this).addClass('active');
					location.href = '#' + $(this).attr('href');
					return false;
				});
		$('a.out').live('click', function() {
			$(this).attr('target', '_blank');
			return true;
		});
		$('ul.navigation li.go-to-site').live('click', dispatchEvents);
		$('#page .project.flash ul.pictures li .clicker').live('click',
				dispatchEvents);
		$('.project .multimedia .navigation li:not(.go-to-site)').live('click',
				dispatchEvents);
		$('#flash-frame .navigation li').live('click', dispatchEvents);
		$('.project .jump').live('click', dispatchEvents);
		$('li.permalink input').live('click', function() {
			$(this).select();
		});
		$('li.permalink input').live('dblclick', function() {
			window.open($(this).attr('value'));
		});
		$('#flash-frame .scroll-frame').jScrollPane( {
			scrollbarWidth : 10,
			wheelSpeed : 120
		});

	}
}

String.prototype.ucfirst = function() { // v1.0
	return this.replace(/\w+/g, function(a) {
		return a.charAt(0).toUpperCase() + a.substr(1);
	});
};

// dispatch events
function dispatchEvents(event) {
	var classes = event.target.className;
	switch (event.type) {
	case 'click':
		if (classes.indexOf('clicker') != -1)
			flash.init(event);
		else if (classes.indexOf('nextImage') != -1
				|| classes.indexOf('prevImage') != -1)
			pageContent.navigateImages(event);
		else if (classes.indexOf('nextFlash') != -1
				|| classes.indexOf('prevFlash') != -1
				|| classes.indexOf('closeFlash') != -1)
			flash.navigate(event);
		else if (classes.indexOf('go-to-site') != -1)
			pageContent.showGoWWW(event);
		else if (classes.indexOf('jump') != -1)
			window.scrollTo(0, 0);
		break;
	}
};

ie6 = {
	interval : undefined,
	insertPie : function() {
		var ie6PopUpTemplate = '<div id="ie6-popup">'
				+ '<marquee><div class="inner">'
				+ '<img class="close" src="img/ico-dead-head.gif" alt="close" />'
				+ '<p>20% of our CSS development time is wasted on Internet Explorer 6 hacks and workarounds.</p>'
				+ '<p>This affects our rates and sanity.</p>'
				+ '<p>Choose a different browser by following the links below:</p>'
				+ '<ul>'
				+ '<li><a class="out" href="http://www.mozilla.com/en-US/firefox/personal.html">Firefox</a></li>'
				+ '<li><a class="out" href="http://www.microsoft.com/windows/Internet-explorer/default.aspx">Latest Internet Explorer</a></li>'
				+ '<li><a class="out" href="http://www.google.com/chrome">Chrome</a></li>'
				+ '<li><a class="out" href="http://www.apple.com/safari/download">Safari</a></li>'
				+ '<li><a class="out" href="http://www.opera.com/download">Opera</a></li>'
				+ '</ul>' + '</div></marquee>' + '</div>';
		$('body').append(ie6PopUpTemplate);
		ie6.interval = window.setInterval('ie6.showPie()', 45000);
		return this;
	},
	showPie : function() {
		pageContent.canHasMore = false;
		$('#ie6-popup').show();
		return this;
	},
	hidePie : function() {
		pageContent.canHasMore = true;
		$('#ie6-popup').hide();
		window.clearInterval(ie6.interval);
		ie6.interval = window.setInterval('ie6.showPie()', 45000);
		return this;
	},
	hoverHack : function() {
		$('.project.flash .multimedia .pictures li.current').live('mouseover',
				function() {
					$(this).addClass('hover');
				});
		$('.project.flash .multimedia .pictures li.current').live('mouseout',
				function() {
					$(this).removeClass('hover');
				});
		return this;
	},
	menuHack : function() {
		$('#menu').wrap('<div id="menu-wrapper-fix"></div>')
		return this;
	}
};

/**
 * 
 * Base64 encode / decode http://www.webtoolkit.info/
 * 
 */

var Base64 = {
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
	// public method for encoding
	encode : function(input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
		input = Base64._utf8_encode(input);
		while (i < input.length) {
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
			output = output + this._keyStr.charAt(enc1)
					+ this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3)
					+ this._keyStr.charAt(enc4);
		}
		return output;
	},
	// public method for decoding
	decode : function(input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
		while (i < input.length) {
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
		}
		output = Base64._utf8_decode(output);
		return output;
	},
	// private method for UTF-8 encoding
	_utf8_encode : function(string) {
		string = string.replace(/\r\n/g, "\n");
		var utftext = "";
		for ( var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			} else if ((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			} else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
		}
		return utftext;
	},
	// private method for UTF-8 decoding
	_utf8_decode : function(utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		while (i < utftext.length) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			} else if ((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i + 1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			} else {
				c2 = utftext.charCodeAt(i + 1);
				c3 = utftext.charCodeAt(i + 2);
				string += String.fromCharCode(((c & 15) << 12)
						| ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
}