function momentSuccess() {
	window.location.replace(location.hash+'/comments');
}
function loadJavaScript( filename ){ 
	var fileref=document.createElement('script');
	fileref.setAttribute( 'type', 'text/javascript' );
	fileref.setAttribute( 'src', filename );
	if ( typeof fileref != 'undefined' ) {
		document.getElementsByTagName('head')[0].appendChild( fileref );
	}
}
function momentValidate() { 
	var error = 0;
	if($("#name").val() == '' || $("#name").val() == null){
		$("#name").css("border", "1px solid red");
		$("span#name-error").css("color", "#F00");
		$("span#name-error").text('You must write a name.');
		error++;
	}
	if($("#comment").val() == '' || $("#comment").val() == null || $("#comment").val().length < 4 ){
		$("#comment").css("border", "1px solid red");
		$("span#comment-error").css("color", "#F00");
		$("span#comment-error").text('Your comment must be at least four characters.');
		error++;
	}
	if ( error == 0 ) {
		return true;
	} else {
		return false;
	}
}

function get_cookie ( cookie_name )
{
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

  if ( results )
    return ( unescape ( results[2] ) );
  else
    return null;
}

var ks = {
	showcase: $('<div id="showcase"></div>'),
	loadingOverlay: $('<div id="overlay-loading" style="z-index: 99999; background: #fff; opacity: 0.45; position: absolute; width: 100%; height: 100%;"></div>'), 
	loadingDiv: $('<div style="text-align: center;"><img src="http://kitchenstars.prontodev.se/img/animated-ajax-loading.gif" alt="Loading..." /></div>'),
	slideShowTimeoutId: false,
	activateGalleryEffect: function () {
		$('ul.thumb li').hover(function() {
			$(this).find('span').css({
				'z-index': 11,
				'background-image': 'url(http://kitchenstars.prontodev.se/img/graphic-transparent-png-70.png)',
				position: 'absolute',
				left: '90px',
				top: '-10px',
				width: '100px'
			}).fadeIn(200);
			$(this).removeClass('fade');
			if ( $.browser.msie ) {
				//$('ul.thumb li.fade').css('filter', 'alpha(opacity=100)');
			} else {
				$('ul.thumb li.fade').stop()
				.animate({
					opacity: 0.45
				}, 200);
			}
			var offset = $(this).offset();
			$(this).css({'z-index' : '10'});
			$(this).find('img').addClass("hover").stop()
			.animate({
				marginTop: '-35px', 
				marginLeft: '-50px', 
				top: '50%', 
				left: '50%', 
				width: '100px', 
				height: '69px'
			}, 200);
		} , function() {
			$(this).find('span').css({
				'z-index': 11,
				position: 'absolute',
				left: '90px',
				top: '-10px',
				width: '100px'
			}).fadeOut(400);
			$(this).css({'z-index' : '0'});
			$(this).find('img').removeClass("hover").stop()
			.animate({
				marginTop: '0px',
				marginLeft: '0px',
				top: '0%',
				left: '0%',
				width: '60px', 
				height: '40px'
			}, 400);
			if ( $.browser.msie ) {
				
			} else {
				$('ul.thumb li.fade').stop()
				.animate({
					opacity: 1
				}, 400);
			}
			$(this).addClass('fade');
		});
	},
	hashMonitor: function () {
		if (ks.ajaxObjects.length > 0) {
			return false;
		} else if ( ks.washHash(location.hash) != $('#site-content').attr('rel') ) {
			ks.loadPage(location.hash);
		}
	}, 
	wash: {
		regexp: new RegExp(/^#/g)
	},
	handleSuccess: function () {
		if ( typeof pageTracker != 'undefined' ) {
			pageTracker._trackPageview("Become a Kitchen star-success");
		}
		$('#become-a-kitchen-star-right-form').resetForm();
		$.validationEngine.buildPrompt("#become-a-kitchen-star-form-submit","Thank you for your contribution, check your inbox for a status mail.","error");
		//alert('Success');
	},
	ajaxObjects: { },
	checkValidation: function () {
		return ks.validationResult;
	},
	washHash: function ( hash ) {
		return hash.replace(this.wash.regexp, '');
	},
	//pageLoading: false, /* @TODO This is the beginning of an anti-multi-madness-frenzy-clicking function for links. */
	loadPage: function ( hash ) {
		if ( hash == ks.pageLoading) {
			return false;
		}
		if ( typeof( ks.ajaxObjects ) != 'undefined' ) {
			$.each(ks.ajaxObjects, function () {
				//$(this).abort();
				this.onreadystatechange = function () { /* Nothing */ };
				//delete $(this);
			});
		}
		ks.pageLoading = hash;
		$('body .formError').fadeOut(100, function () {
			$(this).remove();
		});
		$('#site-content').fadeTo(200, 1, function(){
			$('#site-content').css({
				position: 'relative'
			}).prepend( ks.loadingOverlay.html( ks.loadingDiv ) )
			.fadeTo(100, 1, function () {
				
				var page_exp = ks.washHash( hash ).split('/');    
				var random_number = Math.random() * 100000;
				$('#site-content').attr('rel', ks.washHash( hash ) );
				ks.ajaxObjects[random_number] = $.get(ks.proxyUrl, {
					page: ks.washHash(hash)
				}, function ( data ) {
					location.hash = hash;
					this.pageLoading = false;
					
					$('#site-content').fadeTo(200, 0.01, function() {
						$('#site-content').html(data);
					
						$('#site-content').fadeTo(400, 1, function () {
							/* IE fix */
							if ( $.browser.msie ) {
								this.style.removeAttribute('filter');
							}
						});
						
						switch ( page_exp[0] ) {
							case 'become-a-kitchen-star':
								if ( $.browser.mozilla ) {
									//console.log('Yep.');
								}
								$('#become-a-kitchen-star-right-form').validationEngine({
									promptPosition: "topRight",
									failure: function () {
										ks.validationResult = false;
									},
									success: function ()  {
										ks.validationResult = true;
									}
								});
								$('#become-a-kitchen-star-right-form').ajaxForm({
									dataType: 'json',
									beforeSubmit: ks.checkValidation,
									success: ks.handleSuccess
								});
								break;
							case 'kitchen-moment':
								if ( page_exp[2] == 'slideshow' && ks.slideShowTimeoutId == 0) {
									ks.slideShowTimeoutId = setTimeout(function () {
										ks.loadPage( '#' + page_exp[0] + '/' + $('#slideshow-next').attr('rel') + '/slideshow' );
										clearTimeout(ks.slideShowTimeoutId);
										ks.slideShowTimeoutId = false;
									}, 10000)
								}
								$('a[rel="slideshow"]').colorbox({
									//open: true,
									slideshow: true,
									transition: 'fade',
									speed: 400,
									initialWidth: 900,
									initialHeight: 600,
									opacity: 0.6,
									slideshowSpeed: 5000
								});
								break;
							case 'user-generated':
								$('a[rel="slideshow"]').colorbox({
									//open: true,
									slideshow: true,
									transition: 'fade',
									speed: 400,
									initialWidth: 900,
									initialHeight: 600,
									opacity: 0.6,
									slideshowSpeed: 5000
								});
								if ( page_exp[2] == 'slideshow' && ks.slideShowTimeoutId == 0) {
									ks.slideShowTimeoutId = setTimeout(function () {
										ks.loadPage( '#' + page_exp[0] + '/' + $('#slideshow-next').attr('rel') + '/slideshow' );
										clearTimeout(ks.slideShowTimeoutId);
										ks.slideShowTimeoutId = false;
									}, 10000)
								}
								if( !get_cookie("eid"+$('#eid').val() ) ){ 
									$('input.star').rating({ 
										required: true,
										callback: function(){ 
											document.cookie = "eid"+$('#eid').val()+"=true; expires=31/12/2009 00:00:00";
											if( get_cookie( "eid"+$('#eid').val() ) ){
												var cookie = true;
											}else{
												var cookie = false;
											}
											$.ajax({
												type: "POST",
												url: $(this.form).attr('action'),
												data: {vote:$(this).val(),cookie:cookie}
											});
											$('input.star').rating('readOnly', true)
										} 
									}); 
								}else{
									$('input.star').rating({readOnly: true});
								}
								break;
							case 'gallery':
								ks.activateGalleryEffect();
								break;
						}
						$('#desc').jScrollPane({dragMaxHeight:50});
						$('#comments').jScrollPane({dragMaxHeight:50});
					});
					setTimeout( function(){
						if (sIFR != '') {
							sIFR.replace(nuehelvetica, {
								selector: 'h2.render',
								css: '.sIFR-root { color: #343434; }',
								bgColor: '#ffffff',
								wmode: 'transparent'
							});
	
						}
					}, 700)
					
				});
			});
		}).attr('rel', ks.washHash( hash ));
		
		ks.monitorId = setInterval(ks.hashMonitor, 500);
		return false;
	},
	init: function () {
		ks.loadPage(location.hash);
		
		$('#addThis')
		.live('mouseover', function(){return addthis_open(this, '', '[URL]', '[TITLE]')})
		.live('mouseout', function(){addthis_close()})
		.live('click', function(){ return addthis_sendto(); });
		
		$('a:not(.link-regular, #addThis, #at16pib a)').live('click', function () {
			clearTimeout(ks.slideShowTimeoutId);
			ks.slideShowTimeoutId = false;
			if ( typeof pageTracker != 'undefined' ) {
				pageTracker._trackPageview($(this).attr('href'));
			}
			if($(this).parents('div:eq(0)').attr('id') == 'top-rest-nav'){
//				$('#top-rest-list').fadeTo(200, 0.01, function(){
						$("#top-rest-list").load(ks.proxyUrl + '?page=top-rest', { 'href': $(this).attr('href') }/*, function(){ $('#top-rest-list').fadeTo(200, 0.01) }*/ );
						if($(this).parents('span:eq(0)').attr('class') == 'sort'){
							$("a").removeClass("active");
							$(this).addClass("active");
						}
						return false;
//				});
			} else if ( $(this).attr('id') == 'slideshow-stop' ){
				location.hash = $(this).attr('href');
				return false;
			} else if ( $(this).attr('rel') == 'slideshow' ){
				return false;
			} else if ( $(this).parents('form:eq(0)').attr('id') != 'rating' ){
				//console.log('Clicked ' + this);
				ks.loadPage($(this).attr('href'));
			} else {
				return false;
			}
		});
		$('#kitchen-moment-form .submit').live('click', function(e) {
			if ( typeof pageTracker != 'undefined' ) {
				pageTracker._trackPageview("comment-submit");
			}
			if(momentValidate()){
				$.ajax({
					type: "POST",
					url: $(this.form).attr('action'),
					data: {name:$('#name').val(),email:$('#email').val(),comment:$('#comment').val()},
					callback: momentSuccess()
				});
			}	return false;
		});
	}
}

ks.proxyUrl = '/kitchenstars/Proxy.ashx';

if ( typeof( location.host ) != 'undefined' && location.host == 'ks.wandborg.com') {
	ks.proxyUrl = '/kitchenstars/proxy.php';
}

$(document).ready( function () {
	ks.init();
});