function purchase(url) {
	window.open(url, "Billetter", "width=1024,height=768,scrollbars=yes,resizable=yes,top=0");
} 

function showDropDown(event, dropDownId) {
	event.preventDefault?event.preventDefault():event.returnValue=false;
	$(event.currentTarget).hide();
	$(event.srcElement).hide();
	$("#"+dropDownId).data("showDropDown", true);
	$("#"+dropDownId).show();
	
	
}

function showDelayedDropDown(dropDownId) {
	$("#"+dropDownId).data("showDropDown", true);
	window.setTimeout(function(){
		var okFlag = $("#"+dropDownId).data("showDropDown");
		if( okFlag ) {
			$("#"+dropDownId).show();
		}
	}, 500);
}

function clearDelayedDropDown(dropDownId) {
	$("#"+dropDownId).data("showDropDown", false);
	window.setTimeout(function(){
		var okFlag = $("#"+dropDownId).data("showDropDown");
		if( !okFlag ) {
			$("#"+dropDownId).hide();
		}
	}, 500);
}

function clearDropDownFlag(dropDownId) {
	$("#"+dropDownId).data("showDropDown", false);
}

function forceDropDown(event, dropDownId) {
	event.preventDefault?event.preventDefault():event.returnValue=false;
	if( $("#"+dropDownId).is(":visible")) {
		$("#"+dropDownId).hide();
	} else {
		$("#"+dropDownId).show();
	}
	
}

function showAll(event, cssSelector) {
	event.preventDefault?event.preventDefault():event.returnValue=false;
	$(event.currentTarget).hide();
	$(cssSelector).show().css({height: 'auto'});
}

/* Submit mentometer */
function submitvote(score) {
	$("#vote").val(score);
	if( window.location.search) {
		$("#redirectTo").val(window.location.pathname+window.location.search+"&voted=true&key="+Math.floor(Math.random()*1001));	
	} else {
		$("#redirectTo").val(window.location.pathname+"?voted=true&key="+Math.floor(Math.random()*1001));
	}
	setCookie("mentoval"+$("#mentometerId").val(), score.substring(4), 100);
	$("#pollForm").submit();
}

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));
}

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 initPoll() {
	if( $("#publicOpinion").length > 0) {
		var mentoVal = getCookie("mentometer");
		var idx = -1;
		if( mentoVal ) {
			idx = mentoVal.indexOf($("#mentometerId").val()+'M');
		}
		if( idx == -1) {
			$("#votedControls").remove();
			$("#voteControls").show();
		} else {
			var votedValue = getCookie("mentoval"+$("#mentometerId").val());
			if( votedValue != "" ) {
				$(".terning_"+votedValue+"_fade")
					.removeClass("terning_"+votedValue+"_fade")
					.addClass("terning_"+votedValue);
			}
			$("#voteControls").remove();
			$("#votedControls").show();
		}
	}
}

function displayLikeCount(fbProfId) {
	if( FB ) {
		FB.api('/'+fbProfId, function(response) {
			if (!response || response.error) {
				$("#fbLikeCount")
					.hide()
					.text("Klarte ikke koble til Facebook");
			} else {
				$("#fbLikeCount").show();
				$("#fbLikeCount a")
					.attr("href", response.link)
					.append(response.likes + " liker "+response.name);
			}
			
		});
	} 	
}

function startMediaElement() {
	if( $("#mediaElement").length == 1) {
		$("#mediaElement")
			.data("isRunning", true)
			.data("currentIndex", 0);
		$("#posters a, #icons a").each(function(index) {
			$(this)
				.data("myIndex", index)
				.click(function(event){
					event.preventDefault?event.preventDefault():event.returnValue=false;
					$("#mediaElement").data("isRunning", false);
					$("#mediaElement .article").clearQueue();
					var myIndex = $(this).data("myIndex");
					$("#posters a, #icons a").removeClass("selected");
					$(this).addClass("selected");
					$("#mediaElement .article:visible").hide();
					$($("#mediaElement .article")[myIndex]).show();
					
				});
		});
		// no images in filmomtale
		if( $("#mediaElement>.article").length == 0 ) {
			$("#mediaElement").height($("#mediaElement>.textContainer").height());
		}
		animateMediaElement();
		
	}
}

function animateMediaElement() {
	var isRunning = $("#mediaElement").data("isRunning");
	if( isRunning ) {
		var caroSize = $("#mediaElement .article").length;
		var currIdx = $("#mediaElement").data("currentIndex");
		if( caroSize > 1) {
			var mediaArts =$("#mediaElement .article"); 
			var posters = $("#posters a, #icons a");
			$(mediaArts[currIdx]).delay(6000).fadeOut("slow");
			
			currIdx = currIdx == caroSize-1?0:currIdx+1;
			$(mediaArts[currIdx]).delay(6000).fadeIn("slow", function() {
				if( currIdx == 0) {
					$(posters[caroSize-1]).removeClass('selected');
				} else {
					$(posters[currIdx-1]).removeClass('selected');
				}
				$(posters[currIdx]).addClass('selected');
				animateMediaElement();
			});
			$("#mediaElement").data("currentIndex", currIdx);
		}
	}
}
$(startMediaElement);

$(function() {
	// init image gallery and trailer

	if(!swfobject.hasFlashPlayerVersion("10.0.0")) {
		$("[fallbackTrailer]").each(function(idx){
			$(this).attr("rel", "shadowbox;width=640;height=360;");
			$(this).attr("href", $(this).attr("fallbackTrailer"));
		});
	} 
	Shadowbox.init({
		continuous: true,
		overlayOpacity: 0.8
	});
});

$(initPoll);

$(function() {
	if($(".bodytext .dropDownLink").length >0 ) {
		if( $(".bodytext .bodytextContent>div").height() < $(".bodytext .bodytextContent").height() ) {
			$(".bodytext .bodytextContent").css({height: 'auto'});
			$(".bodytext .dropDownLink").hide();
		}
	}
});

/* 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);
	}
});

$(function(){
	if( $("#upcomingEvents .kommendeSpesialvisning").length > 0 ) {
		$("#upcomingEvents").show();
	}
});

// nyhetsbrev
$(function() {
	var nsForm =$("#newsletterForm"); 
	$("#email").focus(function(){
		if($(this).val() == 'Din epostadresse') {
			$(this).val("");
		}
	});
	if( nsForm.length > 0) {
		nsForm.validate({
			rules: {
				email: {required: true, email: true }
			},
			messages: {
				email: {
					email: "Ikke gyldig epost",
					required: "Vennligst fyll ut epost"
				}
			},
			errorPlacement: function(error, element) {
				error.appendTo( element.parent() );
			}
		});
	}
});

$(function(){
	$("#locMenu a").click(function() {
		setCookie("sf_cinema", $(this).attr("rel"), 100);
	});
});




/* BERGEN KINO STUFF */

function initProgNav() {
	
	$(".progNavigation").each(function(idx) {
		
		
		var ths = $(this);
		
		var containerIdExpr = /\[(.*)\]/;
		var forwardButton = ths.find(".forward"); 
		var backButton = ths.find(".back");
		
		// find how wide the reticle should be
		var vp = ths.prev().find(".progViewport");
		var vpW = vp.width();
		var table = $(vp.children()[0]); 
		
		var tW = table.width();
		var reticle = ths.find(".reticle"); 
		var reticlePercentage = vpW / tW;
		var recwidth = 116;
		var reticleWidth = Math.round(reticlePercentage * recwidth);
		var maxRetPos = (recwidth-2) - reticleWidth; //(width-border)-retWidth
		var maxTablePos = tW-vpW;
		var tableScrollPer = maxRetPos/maxTablePos;
		
		reticle.css("width", reticleWidth+"px");
		var reticleAnimUnit = 127 /tW*127;
		
		
		
			reticle.draggable({
				axis: 'x',
				containment: "parent",
				drag: function(event, ui) {
					
					if( ui.position.left >= maxRetPos) {
						forwardButton.addClass("disabled");
					} else if(ui.position.left <= 0 ) {
						backButton.addClass("disabled");
					} else {
						backButton.removeClass("disabled");
						forwardButton.removeClass("disabled");
					}
					table.css("left", (-ui.position.left/tableScrollPer)+"px");
				},
				stop: function(event, ui) {
					// determine wether or not to shift the table so no partial dates are showing
				}
			});
			
		
		
		forwardButton.click(function(event){
			event.preventDefault();
			if( !forwardButton.is(".disabled") && !table.is(":animated")) {
				var viewPortId = containerIdExpr.exec($(this).attr("rel"))[1];
				var viewPort = $("#"+viewPortId);
				
				
				var rightEdge = table.position().left +table.width();
				if( rightEdge >= viewPort.width() ) {
					
					
					if( rightEdge - 141 <= viewPort.width()+1 ) {
						forwardButton.addClass("disabled");
					} 
					table.animate({
						left: '-=141'
					}, {duration: 'slow', complete: function() {
						backButton.removeClass("disabled");
					}});
					
					reticle.animate({
						left: '+='+reticleAnimUnit
					});
				}
			}
		});
		
		backButton.click(function(event){
			event.preventDefault();
			var viewPortId = containerIdExpr.exec($(this).attr("rel"))[1];
			var tbl =$("#"+viewPortId+" table");
			if( !backButton.is(".disabled") && !table.is(":animated")) {
				if(tbl.position().left < 0 ) {
					if( tbl.position().left + 141 >= 0) {
						backButton.addClass("disabled");
					}
					tbl.animate({
						left: '+=142'
					},{
						duration: 'slow',
						complete: function(){
							forwardButton.removeClass("disabled");
						}
					});
					
					reticle.animate({
						left: '-='+reticleAnimUnit
					});
				}
			}
		});
	});
}


/**
 * Initializes controls on program page.
 */
$(function(){
	if( $("#programMainSection").length > 0) {
		$("#daySelector>li>a").click(function(event){
			event.preventDefault();
		});
		$("#daySelector ul a").click(function(event) {
			event.preventDefault();
			$("#dayTab").show();
			$("#presaleTab").hide();
			$("#allDaysTab").hide();
			var showDate = $(this).attr("data-showdate");
			if( window.location.hash == '#timeline') {
				initTimeline(showDate);
			} else {
				initProgram(showDate);
			}
			$("#oneDayAllShowsButton, #timelineButton").data("showDate", showDate);
			$("#selectedDateLabel").show().text($(this).attr("data-datelabel"));
			$("#allDaysButton").removeClass("programActiveElement").addClass("programDefaultElement");
			$(".showsViewControls").show();
		});
		// initial configuration
		if( window.location.hash == '#timeline') {
			$("#timelineButton").removeClass("programDefaultElement").addClass("programActiveElement");
			$("#oneDayAllShowsButton").removeClass("programActiveElement").addClass("programDefaultElement");
			initTimeline(null);
		} else {
			$("#oneDayAllShowsButton").removeClass("programDefaultElement").addClass("programActiveElement");
			$("#timelineButton").removeClass("programActiveElement").addClass("programDefaultElement");
			initProgram(null);
		}
	}
});

function initProgram(dato) {
	$(".showsContainer, .ajaxLoader").hide();
	$("#selectedDateLabel").show();
	$("#oneDayAllShows, #oneDayAllShows .ajaxLoader").show();
	$(".showsViewControls").show();
	$.get('/sfkino/template/components/prog_2011_ajax_oneDayAllShows.jsp',
		{startDate: dato==null?$("#startDate").val():dato , fid: $("#fid").val(), cin: $("#cin").val() },
		function(data) {
			
			$("#oneDayAllShows .ajaxLoader").hide();
			$("#oneDayAllShows>div")
				.html(data);
			initProgNav();
		//	initTimeLinks();
		//	initTrailerButtons();
		});
}

function initTimeLinks() {
	$("a.time").click(function(event) {
		event.preventDefault();
		window.open($(this).attr("href"),'purchase','location=0,toolbar=0,status=0,width=626,height=436,scrollbars=1');
	});
}

function initTimeline(dato) {
	$(".showsContainer, .ajaxLoader").hide();
	$("#timeline, #timeline .ajaxLoader").show();
	
	$.get('/sfkino/template/components/prog_2011_ajax_timeline.jsp',
		{dato: dato==null?$("#startDate").val():dato, fid: $("#fid").val(), cin: $("#cin").val()},
			function(data) {
				$("#timeline .ajaxLoader").hide();
				$("#timeline>div")
					.html(data);
				layoutTimeline();
				initProgNav();
				//initTimeLinks();
				//initTrailerButtons();
				var offset = $("#timelineContainer").offset();
				var leftLimit = -1*$("#timeStrip").width()+($("#timelineContainer").width() + offset.left);
				var limits = 
				$("#timeStrip>div").draggable({
					axis: 'x',
					containment: [leftLimit,
					              offset.top,
					              offset.left+1,
					              offset.top
					              ],
						drag: function(event, ui) {
							$("#rowContainer").css("left", (ui.offset.left-$(this).parent().offset().left)+"px");
						},
					stop: function(event, ui) {
						if( ui.offset.left-$(this).parent().offset().left >= 0) {
							$("#timeStrip .navButton.left").hide();
						} else {
							if( ui.offset.left <= leftLimit) {
								$("#timeStrip .navButton.right").hide();
							} else {
								$("#timeStrip .navButton.right").show();
							}
							$("#timeStrip .navButton.left").show();
						}
					}
					              
				});
				$("#timeStrip .navButton.left").click(function(event) {
					event.preventDefault();
					var left = parseInt( $("#rowContainer").position().left );
					var distance = "280";
					if( Math.abs(left)%280 != 0) {
						distance = Math.abs(left)%280; 
					}
					$("#rowContainer, #timeStrip>div").animate({left: "+="+distance});
					$("#timeStrip .navButton.right").show();
					if( $("#timeStrip>div").position().left+280 >= 0 ) {
						$(this).hide();
					}
				});
				
				$("#timeStrip .navButton.right").click(function(event) {
					event.preventDefault();
					var left = $("#rowContainer").position().left;
					var distance = "280";
					if( Math.abs(left)%280 != 0) {
						distance = 280-Math.abs(left)%280; 
					}
					if((($("#timeStrip>div").width() - $("#timeline").width())+$("#timeStrip>div").position().left) <=560) {
						$(this).hide();
					}
					$("#rowContainer, #timeStrip>div").animate({left: "-="+distance});
					$("#timeStrip .navButton.left").show();
				});
				
			});
}

function layoutTimeline() {
	var nowTime = $("#timelineContainer").attr("data-now");
	var labelStart = $("#timeStrip").attr("data-labelstart");
	
	// layout the time labels
	var timeLabels = $(".timeLabel"); 
	$("#timeStrip").css("width", (timeLabels.outerWidth(true)*timeLabels.length)+"px");
	
	// layout the bgColumns
	var bgCols = $(".bgColumn");
	var hourInPixels = bgCols.outerWidth(true);
	var leftOffset = hourInPixels - bgCols.outerWidth(false);
	
	bgCols.parent().css("width", (bgCols.length*hourInPixels)+"px");
	bgCols.each(function(idx) {
		$(this).css("left", (idx*hourInPixels)+"px");
	});
	
	// layout the individual show
	var milliSecsInHour = 3600000;
	var pixelsPrMillisec = hourInPixels/milliSecsInHour;
	$("#timelineContainer .show").each(function(idx) {
		var showStart = $(this).attr("data-starttime");
		var timeSpan = $(this).attr("data-timespan");
		
		$(this).css({
			left: (leftOffset + (showStart-labelStart)*pixelsPrMillisec)+"px",
			width: (timeSpan*pixelsPrMillisec)+"px"
		});
	});
	
	// layout the now indicator
	if( "true" == $("#timelineContainer").attr("data-istoday") ) {
		var nowIndicatorTop = $("#timeStrip .nowIndicator");
		var nitLeftOffset = (leftOffset + $("#screenCol").outerWidth(true)) - (nowIndicatorTop.outerWidth(true)/2);
		var leftPos = (nitLeftOffset + (nowTime - labelStart)*pixelsPrMillisec);
		nowIndicatorTop.css("left", leftPos+"px");
		
		var nowIndicatorBottom = $("#rowContainer .nowIndicator");
		nowIndicatorBottom.css({
			height: $("#rowContainer").css("height"),
			left: (((nowTime - labelStart)*pixelsPrMillisec+leftOffset) - (nowIndicatorBottom.outerWidth(true)/2))+"px"
		});
		
		// start animating the 'now' indicator
		
		/*var distance = (timeLabels.outerWidth(true)*timeLabels.length) - nowIndicatorTop.position().left;
		var dur = (distance/(pixelsPrMillisec))+"ms";
		$(".nowIndicator").animate({right: 0}, {duration: dur});
		
		$(".nowIndicator").css("-webkit-transition-duration", dur);
		$(".nowIndicator").css("-ms-transition-duration", dur);
		$(".nowIndicator").css("-o-transition-duration", dur);
		$(".nowIndicator").css("-moz-transition-duration", dur);
		$(".nowIndicator").css("transition-duration", dur);
		
		$(".nowIndicator").css("left", ((timeLabels.outerWidth(true)*timeLabels.length)-(nowIndicatorTop.outerWidth(true)/2))+"px");
		*/
	}
	
	// offset the strip 
	if( "true" == $("#timelineContainer").attr("data-istoday") ) {
		// offset to the now mark
		var offset = -1 * ($("#timeStrip .nowIndicator").position().left - 200);
		if( offset < 0) {
			$("#timeStrip>div, #rowContainer").css("left", (offset)+"px");
			$("#timeStrip .navButton.left").show();
		}
	} else {
		// offset to the offsetMarker
		console.log("labelstart :"+labelStart);
		console.log("offsetmarker :"+$("#timelineContainer").attr("data-offsetmarker"));
		var offset = ($("#timelineContainer").attr("data-offsetmarker")-labelStart)*-1*pixelsPrMillisec;
		console.log(offset);
		if( offset<0) {
			$("#timeStrip>div, #rowContainer").css("left", (offset)+"px");
			$("#timeStrip .navButton.left").show();
		}
	}
}

/** Program section initializer */
$(function(){
	// tab change
	$("#programMainSection .ui-buttonset>a").click(function(event) {
		event.preventDefault();
		
		$(".showsContainer, .ajaxLoader").hide();
		$(this).removeClass("programDefaultElement").addClass("programActiveElement")
			.siblings("a").removeClass("programActiveElement").addClass("programDefaultElement");
		
		switch($(this).attr("data-value")) {
		case 'oneDayAllShows':
			initProgram(null);
			break;
		case 'allDaysAllShows':
			//$("#daySelector").hide();
			$("#dayTab").hide();
			$("#presaleTab").hide();
			$("#allDaysTab").show();
			$(".showsViewControls, .ajaxLoader").hide();
			$("#selectedDateLabel").hide();
			$("#allDaysAllShows,#allDaysAllShows .ajaxLoader").show();
			if(!$("#allDaysAllShows>div").data("initialized")) {
				$.get('/sfkino/template/components/prog_2011_ajax_allShowsAllDays.jsp',
						{ lastShowDate: $("#lastShowDate").val() , fid: $("#fid").val(), cin: $("#cin").val()} ,
						function(data) {
							$("#allDaysAllShows .ajaxLoader").hide();
							$("#allDaysAllShows>div")
								.data("initialized", true)
								.html(data);
							initProgNav();
							//initTimeLinks();
							//initTrailerButtons();
						});
			} else {
				
				$("#allDaysAllShows .ajaxLoader").hide();
			}
			break;
		case 'presale':
			//$("#daySelector").hide();
			$("#dayTab").hide();
			$("#presaleTab").show();
			$("#allDaysTab").hide();
			$("#selectedDateLabel").hide();
			$("#presale,#presale .ajaxLoader").show();
			if(!$("#presale>div").data("initialized")) {
				$.get('/sfkino/template/components/prog_2011_ajax_presaleShows.jsp',
						{lastShowDate: $("#lastShowDate").val(), fid: $("#fid").val()},
						function(data) {
							$("#presale .ajaxLoader").hide();
							$("#presale>div")
								.data("initialized", true)
								.html(data);
							initProgNav();
							//initTimeLinks();
							//initTrailerButtons();
						});
			} else {
				$("#presale .ajaxLoader").hide();
			}
			break;
		}
	});
	
	$(".showsViewControls a").click(function(event) {
		event.preventDefault();
		$(".showsContainer").hide();
		var showDate = $(this).data("showDate");
		switch($(this).attr("data-view")) {
		case 'timeline':
			window.location.hash="#timeline";
			initTimeline(showDate!=null?showDate:null);
			break;
		case 'normal':
			window.location.hash ="";
			initProgram(showDate!=null?showDate:null);
			break;
		}
	});
});


