var animating = false;
var inMargin = '74px';
var outMargin = '570px';
var firstLoad = true;
var easingOut = 1;
// var easingIn = 'easeOutElastic';
var easingIn = 'easeOutBack';


function contestInit() {
	var current = 1, validator;
	
	if($('#contest_form').size() > 0) {
		$.validator.addMethod("is_required", function(value, element) {
			
			var $element = $(element)
			function match(index) {
				return current == index && $(element).parents("#contest_step_" + (index)).length;
			}
			if (match(1) || match(2)) {
				return !this.optional(element);
			}
			return "dependency-mismatch";
		}, $.validator.messages.required)		
		
		validator = $('#contest_form').validate({
			submitHandler: function(form) {
				$('#submit').attr('disabled', 'disabled').css({opacity : 0.5});
				$('.to_contest').hide();
				jQuery(form).ajaxSubmit({
					target: "#contest_form",
					success : function() {
						s.pageName= "Kampanj/Tävling/Tacksida"
						void(s.t());
					}
					
				});
			}
		});
		$('.text input').placeholder({
			blankSubmit : true
		});
	}
	
	$('#next').click(function() {
		if (validator.form()) {
			$("#contest_step_1").fadeOut(function() {
				s.pageName= "Kampanj/Tävling/Kontaktuppgifter"
				void(s.t());
				
				$("#contest_step_2").fadeIn();
			});
			current++;
		}
	});
}





function animateIn(href) {
	$('#menu .active').removeClass('active');
	$('#menu a[href="' + href + '"]').addClass('active');
	
	if (href.match('site')) {
		var width = $('body').width() > 1380 ? 1380 : $('body').width();
		$('#content').append('<div class="iframe"><iframe src="' + href + '" width="' + width + '" height="527" frameborder="0"></iframe></div>')
		$('#content .iframe').css({top: outMargin, left : '50%', marginLeft : '-'+parseInt(width/2)+'px'});
		$('#content .iframe').show().delay(500).animate({top: '40px'}, 2500, easingIn, function() {}).addClass('current');
		$('#footer').fadeOut();
	} else {
		if ($('#content').find('div[data-url="' + href + '"]').size() > 0) {
			var content = $('#content').find('div[data-url="' + href + '"]');
			beforeAnimate();
			content.delay(500).show().animate({top: inMargin}, 1500,easingIn, function() {
				afterAnimate();
			}).addClass('current');
			
		} else {
			$("<div>").load(href + ' .content', function() {
				var content = $(this).find(".content");
				$("#content").append(content);
				beforeAnimate();
				content.css({top: outMargin})
				content.delay(500).animate({top: inMargin}, 1500, easingIn, function() {
					 afterAnimate()
				}).addClass('current').attr('data-url', href);
			}).ajaxError(function() {
				var content = $('#content .content');
				beforeAnimate();
				content.delay(500).show().animate({top: inMargin}, 1500,easingIn, function() {
					afterAnimate();
				}).addClass('current');
			});;
		}
		if ($('#footer:hidden').size()) {
			$('#footer').fadeIn();
		}
	}
}

function beforeAnimate() {
	contestInit();
	$("body").fixPng();
	animating = true;
	$("#content .content .part").hide().removeClass('active');
	$("#contest_intro").show().addClass('active').css({left:'0'});
	
	if ($('.slideshow').size() > 0) {
		$('.slideshow').cycle({
			fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
		});		
	}
	$('#resfeber_puff').hide();
}
var overlay;
function afterAnimate() {
	animating = false;
	$('#resfeber_puff').fadeIn();
	
	
	overlay = $(".view_video").overlay({
		color: '#ccc',
		top: 50,
		fixed: false,
		mask: {
			color: '#000000',
			loadSpeed: 0,
			opacity: 0.7
		},
		onBeforeLoad : function(e) {
			
			var id = $(this.getTrigger()).data('id');
			$('#video'+id+'_flash').append('<div id="video_holder"></div>')
			swfobject.embedSWF('swf/videoplayer_' + id + '.swf', "video_holder", "512", "326", "9.0.0");
		},
		onClose : function() {
			$('#video_holder').remove();
		}
	});
	
	$("textarea[maxlength]").keypress(function(event){
        var key = event.which;
 
        //all keys including return.
        if(key >= 33 || key == 13) {
            var maxLength = $(this).attr("maxlength");
            var length = this.value.length;
            if(length >= maxLength) {
 
                event.preventDefault();
            }
        }
    });
	$(".view_video").click(function() {
		overlay.load();
	}) 
}


function loadContent(href) {
	href == '' ? 'index.html' : '';
		
	if (firstLoad ) {
		firstLoad = false;
		if (href.match('http')) {
			var url = location.href.split('/')
		
			url = url[url.length-1];
		} else {
			var url = location.href;
		}
		var hash = url.split('#');
		$('.content').css({top: outMargin});
		if (hash.length > 1) {
			$('#menu a.active').removeClass('active');
			$('#menu a[href="'+ hash[1] +'"]').addClass('active');
		}
		$('.content').attr('data-url', hash[0]);
		
		beforeAnimate();

		if (href && hash[0] != hash[1]) {
			animateIn(href)
		} else {
			$('.content').delay(500).animate({top: inMargin}, 1000, easingIn, function() {
				 afterAnimate()
			}).addClass('current');
		}
	} else {
	
		if ($('#content .current').size()) {
			$('#content .current').animate({top: '600px'}, 700, 'easeInExpo', function() {
				$('#content .iframe').remove();
				$(this).hide().removeClass('current');
				animateIn(href)
			});
		} else {
			animateIn(href);
		}
	}
}


function resizeStuff() {
	var h = ($(window).height()-548) < 200 ? 200 : ($(window).height()-548);
	$('#footer_inner').css({height : h + 'px'});
	var bodyH = $(window).height() < 650 ? 650 : $(window).height();
	$('body, html').css({height : bodyH + 'px'});
}

$(function() {
	var tracking = {
		'index.html' : 'Kampanj/Hem',
		'tavling.html' : 'Kampanj/Tävling',
		'quiz.html' : 'Kampanj/Quiz',
		'produkt.html' : 'Kampanj/Produkt'
	}
	
	
	$('html').removeClass('no-js');

	resizeStuff();
	$(window).resize(function() {
		resizeStuff();
	})
	
	$('#close').click(function(e) {
		e.preventDefault();
		$('#contest_ended').fadeOut(function() {
			$(this).remove();
		});
	})
	
	// if (jQuery.browser.webkit || jQuery.browser.opera || jQuery.browser.mozilla || (jQuery.browser.msie && jQuery.browser.version > 7)) {
	// 	history = true;
	$.history.init(loadContent);
	// }
	
	
	$('textarea[maxlength]').keyup(function(){
		var max = parseInt($(this).attr('maxlength'));
		if($(this).val().length > max){
			$(this).val($(this).val().substr(0, $(this).attr('maxlength')));
		}

		$(this).parent().find('.charsRemaining').html('You have ' + (max - $(this).val().length) + ' characters remaining');
	});
	
	
	$("#content .content .part").hide();
	$("#contest_intro").show();
	$('a[rel="page"], #menu a').live('click',function(e) {
		
		e.preventDefault();
		
		if (animating) {
			return false;
		}
		var url = $(this).attr('href');
		var base = window.location.href.substring(0, window.location.href.lastIndexOf("/") + 1);
		url = url.replace(base, "");
		url = url.replace(/^.*#/, '');

		// tracking
		if (tracking[url]) {
			s.pageName = tracking[url];
			void(s.t());
		}
		
		$.history.load(url);
	});	
	$('a[rel="part"]').live('click', function(e) {
		e.preventDefault();
		var href = $(this).attr('href').split('#');
		href = '#'+href[1];
		
		if (href == '#contest_step_1') {
			s.pageName= "Kampanj/Tävling/Frågor"
			void(s.t());
		}
		
		if ($(href).size() > 0) {
			//console.log('Start fadeOut');
			$('.part.active').fadeOut(function() {
				//console.log('hide');
				$(this).hide().css({left:'10000px'});
				//console.log('fadeIn');
				$(href).css({left:'0'}).fadeIn().addClass('active');
			}).removeClass('active');
			return;
		}
	});
})

