(function(){

function CustomAnimation(callback, duration, swing, comlete) {
	if ((typeof duration != 'number') || (typeof callback != 'function') || (typeof swing != 'boolean')) {
		return false;
	}
	var _startTime = (new Date()).getTime();

	var _Timer = setInterval(function(){
		var _inWork = (new Date()).getTime() - _startTime;
		var X = _inWork / duration;
		X = X > 1 ? 1 : X;
		if (swing) {
			X = ((-Math.cos(X*Math.PI)/2) + 0.5);
		}
		callback(X);
		if (_inWork >= duration) {
			clearInterval(_Timer);
			if (typeof comlete == 'function') {
				comlete();
			}
		}
	}, 1);
	return true;
}

var AjaxNameSecond = false;
function AjaxNameGeneration(form, force) {
	if ( force || AjaxNameSecond ) {
		$('#table-buttons .refresh').addClass('process');
		$(form).ajaxSubmit({
			url: form.getAttribute('ajax'),
			target: '#table-placer',
			success: function(){
				$('#selector .button').hide();
				$('#table-buttons .refresh').removeClass('process');
				InstallTable(1);

				$('#project-names ins').removeClass('ajax').unbind('click');
				$('#projects, #footer').show();
				setCookie("promouted", "1", (new Date( (new Date()).getTime() + 1000*60*60*24*365 )).toUTCString(), "/");
			},
			error: function() {
				$('#table-buttons .refresh').removeClass('process');
				$('#table').html('&nbsp;');
				InstallTable(1);
			}
		});
		AjaxNameSecond = true;
	}
}

function InstallSelectorForm() {
	var SubmitButton = $('#selector .button button');

	var UpdateDisabled = function() {
		if ($('#selector .options input:checked').length) {
			SubmitButton.removeAttr('disabled');
			return true;
		} else {
			SubmitButton.attr('disabled', 'disabled');
			return false;
		}
	}
	UpdateDisabled();

	$('#selector form').submit(function(){
		AjaxNameGeneration(this, true);
		return false;
	});

	$('#selector .in input').click(function(){
		$(this).siblings('label')[this.checked ? 'addClass' : 'removeClass']('selected');
		if (UpdateDisabled() && ! $(this).parent().hasClass('unique')) {
			AjaxNameGeneration(this.form);
		}
	}).each(function(){
		$(this).siblings('label')[this.checked ? 'addClass' : 'removeClass']('selected');
	});

	$('#selector .in.unique input').click(function(){
		InstallTable(0);
	});
}

function InstallStarsControls() {
	var last_collection = {};

	function updateStars(type, count) {
		var stars = $('#selector .stars .' + type);

		if (typeof count == 'undefined') {
			count = stars.find('input:checked').val();
		} else {
			stars.find("input[value='" + count + "']").click().each(function(){
				AjaxNameGeneration(this.form);
			});
		}

		stars.find('span').each(function(){
			if (parseInt(this.getAttribute('value')) <= count) {
				this.className = 'on';
			} else {
				this.className = '';
			}

			if ($.browser.msie && ($.browser.version == 6)) {
				fixPNG(this);
			}
		});

		last_collection[type] = count;
	}
	updateStars('silver');
	updateStars('gold');
	
	$('#selector .stars input').hide();
	var stars = $('#selector .stars span').mousedown(function(e){
		var type = $(this).parents('#selector .stars tr').get(0).className;
		var last = last_collection[type];
		var current = $(this).attr('value');
		current = (current == last) ? 0 : current;
		updateStars(type, current);
		return false;
	});

	if ($.browser.mozilla) {
		stars.css({display: '-moz-inline-stack'});
	}
	stars.css({display: 'inline-block'});
}

function InstallTable(level) {
	$('#selector .in.unique input').each(function(){
		$('#table span i').text(this.checked ? '-\u041c' : '');
	});
	$('#table div img').each(function(){
		this.style.width = ($(this).parent().find('span').width() + 20).toString() + 'px';
	});
	$('#table').addClass('on');

	if (level > 0) {
		$('#table-buttons .refresh').click(function(){
			AjaxNameGeneration($('#selector form').get(0));
		});
		$('#table-buttons .addname').click(function(){
			$.post($(this).attr('ajax'), {
				unique: 1
			}, function(responce) {
				$('#table-buttons .addname').hide();
				$('#newcomers').html(responce);
				InstallRatings();
			});
			return false;
		});

		if (level > 1) {
			$('body').mousemove(function(e){
				var table = $('#table').get(0);
				if (table && table.offsetWidth < table.scrollWidth){
					table.scrollLeft = (table.scrollWidth - table.offsetWidth) * ((e.clientX / table.offsetWidth)*1.2 - 0.1);
				}
			});
		}
	}
}

function InstallQuickAwardsAdd() {
	$('#projects .awards form.quick-add').submit(function(){
		var value = $('#awards_name').val();
		if (value) {
			$.post(this.getAttribute('action'), {
				awards_name: value
			}, function(responce){
				alert(responce);
				if (responce) {
					$('#awards_name').val('');
				}
			});
		}

		return false;
	});
}
function InstallRatings() {
	$('#projects .awards li a.up, #projects .awards li a.down').click(function(){
		var li = $(this).parents('#projects .awards li');
		$.post(this.href, {}, function(responce){
			li.find('span.votes').removeClass('votes').text(responce);
			li.find('a.up, a.down').hide();
		});
		return false;
	});
	if ($.browser.msie && $.browser.version < 7) {
		$('#projects .awards li').mouseover(function(){
			$(this).addClass('hover');
		}).mouseout(function(){
			$(this).removeClass('hover');
		});
	}
}

function InstallSeeMore() {
//	setCookie("promouted", "", (new Date( (new Date()).getTime() + 1000*60*60*24*365 )).toUTCString(), "/");
	if ( ! getCookie('promouted') && window.location.pathname == '/') {
		$('#projects, #footer, .hide-if-no-promouted').hide();

		$('#project-names ins').click(function(){
			$(this).removeClass('ajax').unbind('click');
			$('#projects, #footer').show();

			var top = $('#project-names .more').offset().top;
			CustomAnimation(function(x){
				document.documentElement.scrollTop = parseInt(x*top);
			}, 500, true);
			
			setCookie("promouted", "1", (new Date( (new Date()).getTime() + 1000*60*60*24*365 )).toUTCString(), "/");
			return false;
		}).addClass('ajax');
	}
}

function InstallRegionList() {
	var list = $('#region-list');
	var region = $('#region');
	if (list.length) {
		var listlist = list.find('.list');
		$('#region option').each(function(){
			var span = $('<span></span>').html(this.text).addClass(this.className);
			span.get(0).value = this.value;
			listlist.append(span);
			if (this.selected) {
				$('#region-name').text(this.text);
			}
		});
		region.hide();
		$('#region-name').click(function(){
			list.show();
			list.focus();
		});
		list.find('.list span').click(function(){
			region.get(0).value = this.value;
			$('#region-name').text($(this).text());
			AjaxNameGeneration(region.get(0).form);
			if ($.browser.msie) {
				list.hide();
			} else {
				list.fadeOut(200);
			}
		});

		if ($.browser.msie && $.browser.version <= 6) {
			list.find('.list span').hover(function(){
				$(this).addClass('hover');
			}, function(){
				$(this).removeClass('hover');
			})
		}
	}
}

function ImagePreloader(srcs) {
	for (var i in srcs) {
		var img = new Image();
		img.src = srcs[i];
	}
}
function InstallPngFix() {
	if ($.browser.msie){
		$('.png').each(function(){
			fixPNG(this);
		});
	}
}
function setCookie(name, value, expires, path, domain, secure) {
	document.cookie = name + "=" + escape(value) +
		((expires) ? "; expires=" + expires : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
}
function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

$(function(){
	InstallSelectorForm();
	InstallStarsControls();
	InstallTable(3);
	InstallQuickAwardsAdd();
	InstallRatings();
	InstallSeeMore();
	InstallPngFix();
	InstallRegionList();
	ImagePreloader(['/ibrendo/stars-gold-on.png','/ibrendo/stars-silver-on.png']);
});

})();