(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);
/**
 * Initializes the main program menu
 */
$(function() {
	// the "TODAY!" icon
	$(".program_billeter_icon").click(mainMenuToday);
	
	// The date selector dropdown
	$("#jumpMenu").val("").change(mainMenuChooseDate);
	
	// Initialize mentometer
	var mentoId = $("#mentometerId");
	if( mentoId.length > 0) {
		blockVoting(false);
	}
	
	// Initialize program on filmomtale
	if($("#omtaleProg").length == 1) {
		loadProgramForOneMovie(null);
	}
	
	initImgGallery();
	
	$(".text .link").click(readMore);
	
	$(".menuExpander a").click(expandMainMenu);
	
	initListViewIcons();
	
	newsletterValidation();
	
	searchPlaceholder();
	
	initOmtaleTrailer();
	
	initKinosonen();
	
	initInitialProgHash();
});

/**
 * Sets a cookie value
 * @param c_name the name of the cookie
 * @param value the value of the cookie
 * @param expiredays the how long until expiration
 */
function setCookie(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : "; expires="+exdate.toGMTString()+"; path=/; domain="+document.location.hostname.substr(document.location.hostname.indexOf('.')+1));
}

/**
 * Gets a cookie val
 * @param c_name the cookie 
 * @returns
 */
function getCookie(c_name) {
	if (document.cookie.length>0) {
		var c_start=document.cookie.indexOf(c_name + "=");
	  	if (c_start!=-1) { 
			c_start=c_start + c_name.length+1; 
			var c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}

function loadProgramForOneMovie(dte) {
	if( !dte ) {
		dte = "";
	}
	$.get('/trondheimkino/template/components/program_oneMovie_oneDay.jsp', {edi: $("#edi").val(), dato: dte}, function(data, textStatus, jqXHR) {
		$(".forestillinger_omtale .ajaxLoad").hide();
		// registert event handlers for view change
		$("#omtaleProg").html(innerShiv(data, false));
		
		$("#omtaleJumpMenu").change(function(event) {
			var td = $(this).val();
			$(".forestillinger_omtale .ajaxLoad").show();
			$("#omtaleProg").html("");
			loadProgramForOneMovie(td);
		});
		
	});
}

function loadProgramDay(date) {
	window.location.hash = "prog-"+date;
	$("#jumpMenu").val(date);
	$("#programContainer").show();
	$("#programContainer .ajaxLoad").show();
	$("#programContent").html("");
	
	$.ajax({
		url: '/trondheimkino/template/components/program_oneDay.jsp', 
		data: {dato: date}, 
		success: function(data, textStatus, jqXHR) {
			
			$("#programContainer .ajaxLoad").hide();
			$("#programContent").html(innerShiv(data, false));
			// registert event handlers for view change
			$(".programmet_container_ikon_visninger .ikon").click(programViewChange);
		},
		error: function(jqXHR, textStatus, errorThrown) {
			$("#programContainer .ajaxLoad").hide();
			$("#programContent").html(innerShiv("<div class='error'>Det oppstod en feil</div><!--"+errorThrown+"-->", false));
		}
	});
}

function initInitialProgHash() {
	var hsh = window.location.hash;
	if( hsh ) {
		var idx = hsh.indexOf("prog-");
		if( idx != -1) {
			loadProgramDay(hsh.substring(idx+5));
		}
	}
	$(window).bind("hashchange", function() {
		var hsh = window.location.hash;
		if( hsh ) {
			var idx = hsh.indexOf("prog-");
			if( idx != -1) {
				loadProgramDay(hsh.substring(idx+5));
			}
		}
	});
}

/**
 * Fired when the user changes the program view (poster vs list)
 * @param event DOM event
 */
function programViewChange(event) {
	event.preventDefault();
	if( !$(this).is(".active") ) {
		$(".programmet_container_ikon_visninger .ikon.active").removeClass("active");
		$(this).addClass("active");
		$("#programContainer").removeClass().addClass($(this).attr("data-class"));
	}
}

/**
 * Handler for the "Idag!" icon
 * @param event DOM event
 */
function mainMenuToday(event) {
	event.preventDefault();
	if( $("#programContainer").is(":visible") ) {
		$("#programContainer").hide();
		window.location.hash = "";
	} else {
		loadProgramDay($(this).attr("data-today"));
	}
}

/**
 * Handler for the date chooser dropdown
 * @param event DOM event
 */
function mainMenuChooseDate(event) {
	if( $(this).val() != '') {
		loadProgramDay($(this).val());
	} else {
		$("#programContainer").hide();
	}
}

function initOmtaleTrailer() {
	$(".showTrailer").click(function(event) {
		event.preventDefault();
		$(this).hide();
		$(".trailer").show();
		//var turl = $("#trailerPlaceholder").data("trailerurl");
		//var flashUrl = $("#trailerPlaceholder").data("flashurl");
		//swfobject.embedSWF(flashUrl, 'trailerPlaceholder', '620', '390', '10', '', 'movie='+turl+'&autoplay=true', 
		//		{allowScriptAccess: 'always', allowfullScreen: 'true', wmode: 'opaque'}, {allowScriptAccess: 'always', allowfullScreen: 'true', wmode: 'opaque'});
	});
}

function submitvote(event, vote) {
	if( event && event.preventDefault) {
		event.preventDefault();
	} else {
		event.returnValue=false;
	}
	setCookie("mentoval"+$("#mentometerId").val(), vote, 100);
	$("#vote").val("svar"+vote);
	$.post("/trondheimkino/poll/vote.do", $("#pollForm").serialize(), function(data){
		if( data && data.totalVotes ) {
			$("#totalVotes").text(data.totalVotes);
			$("#avgVotes").text(data.roundedAvg);
		}
	});
	blockVoting(vote);
}

function blockVoting(vote) {
	var mentoVal = getCookie("mentoval"+$("#mentometerId").val());
	if( vote ) {
		mentoVal = vote;
	} else if( !mentoVal ) {
		mentoVal = 0;
	}
	
	if( mentoVal ) {
		$("#userDice a").remove();
		var dice = $("#userDice div.terninger_small");
		dice.show();
		dice.not(dice[mentoVal-1]).addClass("disabled");
	}
}

function initImgGallery() {
	var galleryImgs = $(".filmomtale  .bildegalleri .thumbs>div>a");
	galleryImgs.click(function(event) {
		event.preventDefault();
		var mainImg = $("#mainImg");
		mainImg.attr("src", $(this).attr("href"));
		var smallImg =$($(this).children()[0]); 
		mainImg.attr("title", smallImg.attr("alt"))
			.attr("alt", smallImg.attr("alt")).
			attr("class", $(this).attr("data-cssClass"));
		
	});
	
	$(".filmomtale  .bildegalleri .thumbs .left").click(function(event){
		event.preventDefault();
		$(".filmomtale  .bildegalleri .thumbs .right").show();
		var strip = $(".thumbs>div"); 
		var pos = strip.position();
		if( pos.left >= -120) {
			$(this).hide();
		}
		strip.animate({left: '+=120'});
	});
	
	$(".filmomtale  .bildegalleri .thumbs .right").click(function(event){
		event.preventDefault();
		$(".filmomtale  .bildegalleri .thumbs .left").show();
		var strip = $(".thumbs>div"); 
		var pos = strip.position();
		if( pos.left <= -1*(strip.width()-600)) {
			$(this).hide();
		}
		strip.animate({left: '-=120'});
	});
}

function readMore(event) {
	event.preventDefault();
	$(this).remove();
	$(".bodyText").show();
} 

function initListViewIcons() {
	$(".kommer_container_ikon_visninger .ikon").click(function(event) {
		event.preventDefault();
		if( !$(this).is(".active") ) {
			$(".kommer_container_ikon_visninger .ikon.active").removeClass("active");
			$(this).addClass("active");
			$("#filmkategoriseksjon_container").removeClass().addClass($(this).attr("data-class"));
		}
	});
}

function expandMainMenu(event) {
	event.preventDefault();
	$(".menuExpander a").hide();
	$(".movielist_category_container li:hidden").show();
}

function newsletterValidation() {
	// newsletter validation
	if( $("#newsletterForm").length > 0) {
		if( !Modernizr.input.placeholder ) {
			if( $("#email").length != 0) {
				var focusFunc = function(event) {
					$("#email").prop("value", "")
						.unbind("focus", focusFunc);
				};
				
				$("#email")
					.prop("value", $("#email").attr("placeholder"))
					.focus(focusFunc);
			}
		}
		if( !Modernizr.inputtypes.email ) {
			var opts = {
				rules: {
					email: {required: true, email: true}
				},
				messages: {
					email: {
						required: "Dette feltet er påkrevd",
						email: "Ikke gyldig epost"
					}
				},
				errorPlacement: function(error, element) {
					$("#newsletterValidation").append(error);
				}
			};
			
			$("#newsletterForm").validate(opts);
		}
	}
}

function searchPlaceholder() {
	if( !Modernizr.input.placeholder ) {
		if( $("#search").length != 0) {
			var focusFunc = function(event) {
				$("#search").prop("value", "")
					.unbind("focus", focusFunc);
			};
			$("#search")
				.prop("value", $("#search").attr("placeholder"))
				.focus(focusFunc);
		}
	}
}

function initKinosonen() {
	$("nav.kinosonen a.external").on("click", function(event) {
		event.preventDefault();
		if( $(this).hasClass("secure")) {
			window.open($(this).attr("href"), "tksecure", "location=yes,resizable=yes,width=1000,height=570,status=yes");
		} else {
			$("#kinosonenContent").html(innerShiv("<iframe src='"+$(this).attr("href")+"' height='1100' width='638' scrolling='auto' seamless='seamless' frameborder='0' allowtransparency='true'></iframe>", false));
		}
	});
}

/* Konkurranser */
$( function() {
	var compForm = $("#compForm");
	if( compForm.length > 0) {
		var opts = {
			rules: {
				txtAdress: {required: true},
				txtEmail: {required: true, email: true},
				txtName: {required: true}
			},
			messages: {
				txtName: "Dette feltet er påkrevd",
				txtEmail: {
					required: "Dette feltet er påkrevd",
					email: "Ikke gyldig epost"
				},
				txtAdress: "Dette feltet er påkrevd"
		
			},
			errorPlacement: function(error, element) {
				if ( element.is(":radio") ) {
					error.appendTo( element.parent().parent() );
				} else {
					error.appendTo( element.parent() );
				}
			}
		};
		$("#compForm :radio").each(function(index, elem){
			if( !opts['messages'][$(elem).attr('name')] ) {
				opts['messages'][$(elem).attr('name')] = 'Et svaralternativ må velges.';
				opts['rules'][$(elem).attr('name')] = {};
				opts['rules'][$(elem).attr('name')]['required'] = true;
			}
		});
		
		compForm.validate(opts);
	}
});
