/* Timestamp: 02.07.2009 07:59:44 */
// JavaScript Document

var _progress = 0;
var _selectType = 0;
 
var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-53103-6']);
  _gaq.push(['_trackPageview']);

var submenu_open = false;
var publicationUrl = "http://www.filmweb.no/";
if( window.location.hostname && window.location.hostname == "test.filmweb.no" ) {
	publicationUrl = "http://test.filmweb.no/";
}


document.domain="filmweb.no";

/** Convertert til jQuery */
function skyscraperJoinTop() {
	$("firstSkyscraper").setStyle({
		paddingTop: 0
	});
 
}
/**
 * Convertert til jQuery 
 * Initializes the slider for program.
 */
function initSlider() {
	var track = $("progSlider");
 	var con = $("progContainer");
	if( con != null && track != null ) {
		var conHeight = con.getHeight();
		if( conHeight <= 400 ) {
			track.hide();
			$("progClipper").setStyle({height: "auto"});
			$("progClipperSub").setStyle({height: "auto"});
		} else {
			var scrollRange = conHeight - 320;
			con.up().makePositioned();
			con.makePositioned();
			new Control.Slider(track.down(".handle"), track, {
					axis: "vertical",
					maximum: scrollRange,
					range: $R(0, scrollRange),
					onSlide: function(value) {
						var newVal = "-"+Math.round(value)+"px";
						con.style.top = newVal;
						},
					onChange: function(value) {
						var newVal = "-"+Math.round(value)+"px";
						con.style.top = newVal;
						} });
		}
	}
}

/** Converted to jQuery!
 * Switches content in the tab panels at the bottom of the page
 * @param {Object} tabNum the tab number ot select
 * @param {Object} settings the tab settings
 * @param {Object} puburl the publication url
 */
function selectTab(tabNum, settings, puburl) {
	// set the correct tab
  	var lis = $$("#flippemeny div.active");
	if( lis != null ) {
		var first = lis.first();
		if( first != null ) {
			first.removeClassName("active");
		}
	}
 	var newSelected = $("flippemeny").down();
	if( tabNum > 1 ) {
		newSelected = newSelected.next(tabNum-2);
	}
	newSelected.addClassName("active");
	
	// set the correct content
	var contents = $("tabcontrol_contents");
	contents.childElements().each(function(item) {item.hide();});
	var newContent = $("tabcontrol_content_"+tabNum);
	newContent.show();
	if( newContent.down().match("img.ajaxwait") ) {
		new Ajax.Request(puburl+"template/components/tabcontrol/tabcontent.jsp", {
			method: 'post',
			encoding: 'ISO-8859-1',
			requestHeaders: {'settings': settings},
			/*onComplete: function(response) {
					alert(response.responseText);
				},*/
			onFailure: function(response) {
					newContent.innerHTML = "Feil";
				},
			onSuccess: function(response) {
					newContent.innerHTML = response.responseText;
				}
			});
	}
	
	
}

function initProgram(pubUrl) {
	var progElem = $("omtale_ajax_program");
	if( progElem != null && progElem.down().match("img.ajaxwait") ) {

		var numDays = $("omtale_ajax_program_numDays").value;
		var filmId = $("omtale_ajax_program_filmId").value;
		var premDate = $("omtale_ajax_program_premDate").value;
		var userCookie = getCookie("Kino");
		var paramString = "filmId="+filmId;
		if( numDays != null && numDays != "") {
			paramString += "&numDays="+numDays;
		}
		if( userCookie != null && userCookie != "") {
			paramString += "&userCookie="+userCookie;
		}
		if( premDate != null && premDate != "") {
			paramString += "&premDate="+premDate;
		}
		new Ajax.Request("/template/art/art_filmomtale_program.jsp", {
			method: 'get',
			encoding: 'ISO-8859-1',
			parameters: paramString,
			/*onComplete: function(response) {
					alert(response.responseText);
				},*/
			onFailure: function(response) {
					progElem.innerHTML = response.responseText;
				},
			onSuccess: function(response) {
					progElem.innerHTML = response.responseText;
					initSlider();
					
				//	alert('.' + response.responseText);
					
					var alertButton = $$("#alertMeForm_0 .send");
					if( alertButton != null && alertButton.length == 1) {
						alertButton[0].observe("click", productAlertMe);
					}
					
					progress();
				}
			});
	}
}

function initProgramMobil(pubUrl) {
	var progElem = $("omtale_ajax_program");
	if( progElem != null && progElem.down().match("img.ajaxwait") ) {

		var numDays = $("omtale_ajax_program_numDays").value;
		var filmId = $("omtale_ajax_program_filmId").value;
		var premDate = $("omtale_ajax_program_premDate").value;
		var userCookie = getCookie("Kino");
		var paramString = "filmId="+filmId;
		if( numDays != null && numDays != "") {
			paramString += "&numDays="+numDays;
		}
		if( userCookie != null && userCookie != "") {
			paramString += "&userCookie="+userCookie;
		}
		if( premDate != null && premDate != "") {
			paramString += "&premDate="+premDate;
		}
		new Ajax.Request("/template/art/art_filmomtale_program_mobil.jsp", {
			method: 'get',
			encoding: 'ISO-8859-1',
			parameters: paramString,
			/*onComplete: function(response) {
					alert(response.responseText);
				},*/
			onFailure: function(response) {
					progElem.innerHTML = response.responseText;
				},
			onSuccess: function(response) {
					progElem.innerHTML = response.responseText;
					initSlider();
					
				//	alert('.' + response.responseText);
					
					progress();
					
					var programContent = $("ajaxTarget");
					if(programContent == null)
					{
						var header = $("program-omtale");
						if(header != null)
						{
							header.style.display = "none";
						}
					}
				}
			});
		
		
	}
}


// check that both cinema and dvd calls are finished, then check for cinemashows
function progress(){
	_progress += 1;
	
	if(_progress == 2){	
		
		
		if($('noShows') != null && $('noShows').value == 'true'){
			
			var customerAlertTemplate = $("customerAlertTemplate");
			var cat = new Template(customerAlertTemplate.innerHTML);
			$('container_program_dvd_bolk').innerHTML = cat.evaluate({videoProductTypeId: 0});
			
			var i = 0;
			
			$('progressFeedback'+ i).hide();
			
			// feedback
			if($('signupFeedback' + i) != undefined)
				$('signupFeedback' + i).hide();

			// form elements
			if( $("dl_ProdCount").innerHTML != 0 ){
				$('dlFeedback' + i).hide();
			}

			if($("dvd_ProdCount").innerHTML != 0){
				$("dvdFeedback" + i).hide();
			}
			
			if($("stream_ProdCount").innerHTML != 0){
				$("olFeedback" + i).hide();
			}
			if($("bd_ProdCount").innerHTML != 0){
				$("brFeedback" + i).hide();
			}
			
		}
		else {
			var prodArr = ["dvd", "bd", "stream", "dl"];
			// if film on cinema even if released on dvd
			$("flappKinoprogram").removeClassName("flapp");
			$("flappKinoprogram").addClassName("flapp_valgt");
			
			
			for( var c = 0; c <prodArr.length; c++ ) {
				$("flapp_"+prodArr[0]+"_Kjopinfo").removeClassName("flapp_valgt");
				$("flapp_"+prodArr[0]+"_Kjopinfo").addClassName("flapp");
			}
			showBuyCinemaTicketInfo("http://"+window.location.hostname, false, 'kino');
		}
		
		// remove the blueprint...
		customerAlertTemplate.remove();
		var lc = $$("input[name='loc_cookie']");
		if( lc ) {
			for( var i = 0; i < lc.length; i++) {
				lc[i].setValue(getCookie("location"));
			}
		}
		var cc = $$("input[name='cin_cookie']");
		if( cc ) {
			for( var i = 0; i < cc.length; i++) {
				cc[i].setValue(getCookie("Kino"));
			}
		}
	}
	
//	hideStuffUglyHack();
	
	
	if($('noShows') == null && _progress == 1){
		hideKinoAlert();
	}
	else {
		showKinoAlert();
	}
	
}

/**
 * Converted to jQuery!
 * Dice for filmomtale
 */
function initPoll(pollId) {
	new Ajax.Request("/template/art/art_filmomtale_poll.jsp", {
			method: 'get',
			encoding: 'ISO-8859-1',
			parameters: {'pollId': pollId, 'userCookie': getCookie("mentometer"), 'mentoVal': getCookie("mentoval"+pollId) },
			onFailure: function(response) {
				},
			onSuccess: function(response) {
					$("pollPlaceholder").update(response.responseText);
				}
			});
}

/**
 * Converted to jQuery!
 * @param imgId
 * @param newImg
 */
function mouseOverDice(imgId, newImg) {
	var img = $(imgId);
	img.src = newImg;
}

/**
 * Converted to jQuery! 
 * @param score
 * @param artTitle
 */
function submitvote(score, artTitle) {
	$("vote").value=score;
	var numScore = score.charAt(4);
	setCookie("mentoval"+$("mentometerId").value, numScore, 100);
	var oldCookie = getCookie("mentometer");
	if( oldCookie ) {
		oldCookie = $("mentometerId").value+"M"+oldCookie;
		setCookie("mentometer", oldCookie, 100);
	} else {
		setCookie("mentometer", $("mentometerId").value+"Mnull", 100);
	}
	
	if (FB && $("postPollToFacebookCheck").checked) {
		try {
			FB.login(function(response){
				try {
					if (response.authResponse) {
						// user is logged in and granted some permissions.
						FB.api('/me/feed', 'post', {
							message: 'ga \'' + artTitle + '\' terningkast ' + numScore + ". Er du enig?",
							link: window.location.href,
							icon: 'http://www.filmweb.no/template/static/gfx/terninger/small_' + numScore + '_o.png'
						}, function(response){
							sendPollForm();;
						});
					} else {
						sendPollForm();
					}
				} catch(e) {
					sendPollForm();
				}
			}, {
				scope: 'publish_stream'
			});
			
		} catch(e) {
			sendPollForm();
		}
	} else {
		sendPollForm();
	}	
}

function sendPollForm() {
	var pollForm = $("pollForm");
	pollForm.request({
		method: 'post',
		encoding: 'ISO-8859-1',
		onComplete: function (response) {
			initPoll($("mentometerId").getValue());
		}
	});
}	

// mentometerId can either be the id of the mentometer article or the article which has it as related
function initMentometer(mentometerId, loc) {
	var paramString = "mentometerId="+mentometerId;
	var placeholder = $("mentoPlaceholder");
	var cookie = getCookie("mentometer");
	paramString +="&loc="+loc+"&mentometer="+escape(cookie);
	new Ajax.Request("/template/art/art_mentometer.jsp", {
			'method': 'post',
			'encoding': 'ISO-8859-1',
			'parameters': paramString,
			/*onComplete: function(response) {
					alert(response.responseText);
				},*/
			'onFailure': function(response) {
					$("mentoWait").hide();
					placeholder.insert(response.responseText);
				},
			'onSuccess': function(response) {
					$("mentoWait").hide();
					placeholder.insert(response.responseText);
				}
			});
}

function mentoVote() {
	var mentoForm = $('mentoPollForm');
	var serialized = mentoForm.serialize({hash: true});
	if( serialized["vote"] == null) {
		alert("Ingen av alternativene er valgt!");
	} else {
		$("mentoWait").show();
		new Ajax.Request("/template/components/pollAjaxProxy.jsp", {
			'method': 'post',			  
			'encoding': 'ISO-8859-1',
			'parameters': mentoForm.serialize(),
			'onSuccess': function(response) {
				$("mentoPlaceholder").innerHTML = response.responseText;
				var oldCookie = getCookie("mentometer");
				var input = mentoForm['mentometerId'];
				if( oldCookie ) {
					oldCookie = $F(input)+"M"+oldCookie;
					setCookie("mentometer", oldCookie, 100);
				} else {
					setCookie("mentometer", $F(input)+"Mnull", 100);
				}
			}
		});
	}
}

function showMentoResults() {
	$("mentoPollForm").hide();
	$("mentoShowResults").hide();
	$("mentoResults").show();
	target.hide();
}

function init() {
	/* Malverk genererer pubUrl, som igjen hentes inn gjennom <body onload="init()"> */
	
	initProgram(publicationUrl);
  	showBuyVideoInfo(publicationUrl, true, null );
  	
	//initIFrameAds();
	
}

function toggle_submenu() {
	if (submenu_open) {
		submenu_open = false;	
		hide('fw_submenu');
	} else {
		submenu_open = true;
		show('fw_submenu');
	}
	$('a_til_aa').blur();
}


function show(id) {
	$(id).style.display = "block";
}

function hide(id) {
	$(id).style.display = "none";
}

function show_visibility(id) {
	$(id).style.visibility = "visible";
}

function hide_visibility(id) {
	$(id).style.visibility = "hidden";
}

function toggle(id) {
	if ($(id).style.display == "none") {
		$(id).style.display = "block";
	} else {
		$(id).style.display = "none";
	}
}

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=filmweb.no");
}

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 printPage(url) {
	window.open(url, "printable", "width=800,height=600,resizable=yes,scrollbars=yes,toolbar=yes");
}

function init_gallery() {
	$('gallery_container').onmouseover = function (e) {
		showGalleryTools();	
	};
	$('gallery_container').onmouseout = function (e) {
		hideGalleryTools();	
	};
	$("gallery_imagetext").update($("gallery_img0").alt);
	showGalleryTools();	
	window.fw_galleryImgs =  $$(".gallery_container_box img");
}


function showGallery() {
	hideGalleryTools();
	$('gallery_container_box').hide();
	$('gallery_thumbs').show();
}

/** Converted to jQuery */
function showImage(thumbIdx) {
	$('gallery_thumbs').hide();
	$('gallery_container_box').show();
	for( var idx = 0; idx < window.fw_galleryImgs.length; idx++) {
		if( idx == thumbIdx ) {
			window.fw_galleryImgs[idx].show();
		} else {
			window.fw_galleryImgs[idx].hide();
		}
	}
	$('gallery_currImg').update(thumbIdx+1);
	$("gallery_imagetext").update(window.fw_galleryImgs[thumbIdx].alt);
	showGalleryTools();
}


function showGalleryTools() {
	show('gallery_thumbsicon');
	show('gallery_arrowleft');
	show('gallery_arrowright');
	$('gallery_imagenumber').style.display = "block";
	$('gallery_imagetext').style.display = "block";
}

function hideGalleryTools() {
	hide('gallery_thumbsicon');
	hide('gallery_arrowleft');
	hide('gallery_arrowright');
	hide('gallery_imagenumber');
	hide('gallery_imagetext');
}

function gallery_next() {
	
	if( window.fw_galleryImgs != null ) {
		var showNext = false;
		for(var imgIdx = 0; imgIdx < window.fw_galleryImgs.length; imgIdx++ ) {
			if( showNext ) {
				window.fw_galleryImgs[imgIdx].show();
				$('gallery_currImg').update(imgIdx+1);
				$("gallery_imagetext").update(window.fw_galleryImgs[imgIdx].alt);
				showNext = false;
				setThumbsPage(imgIdx);
			}else if( window.fw_galleryImgs[imgIdx].visible() ) {
				window.fw_galleryImgs[imgIdx].hide();
				showNext = true;
			}
		}
		if( showNext ) {
			window.fw_galleryImgs[0].show();
			setThumbsPage(0);
			$('gallery_currImg').update("1");
		}

		switchAds();	
	}
	
}
/** Converted to jQuery */
function gallery_prev() {
	if( window.fw_galleryImgs != null ) {
		var showIdx = -2;
		for(var imgIdx = 0; imgIdx < window.fw_galleryImgs.length; imgIdx++ ) {
			if( window.fw_galleryImgs[imgIdx].visible() ) {
				window.fw_galleryImgs[imgIdx].hide();
				showIdx = imgIdx -1;
			}
		}
		if( showIdx==-1 ) {
			window.fw_galleryImgs[window.fw_galleryImgs.length-1].show();
			setThumbsPage(window.fw_galleryImgs.length-1);
			$("gallery_imagetext").update(window.fw_galleryImgs[window.fw_galleryImgs.length-1].alt);
			$('gallery_currImg').update(window.fw_galleryImgs.length);
		} else if( showIdx != -2 ) {
			window.fw_galleryImgs[showIdx].show();
			setThumbsPage(showIdx);
			$("gallery_imagetext").update(window.fw_galleryImgs[showIdx].alt);
			$('gallery_currImg').update(showIdx+1);
		}
		switchAds();	
	}
}

function setThumbsPage(idx) {
	var galThumbs = $("gallery_thumbs");
	var newPage = Math.ceil((idx+1)/20);
	if( newPage < galThumbs.currPage ) {
		thumbsPrev();
	} else if(newPage > galThumbs.currPage) {
		thumbsNext();
	}
}

function thumbsNext() {
	var list = $$("#gallery_thumbs ul li");
	if( list != null ) {
		var galThumbs = $("gallery_thumbs");
		var numPages = Math.ceil( list.length /20 );
		if( !galThumbs.currPage ) {
			galThumbs.currPage = 1;
		}
		for( var idx = (galThumbs.currPage-1)*20, counter = 0; idx < list.length && counter < 20; idx++, counter++) {
			list[idx].hide();
		}
		galThumbs.currPage = galThumbs.currPage+1;
		if( galThumbs.currPage > numPages ) {
			galThumbs.currPage = 1;
		}
		for( var idx = (galThumbs.currPage-1)*20, counter = 0; idx < list.length && counter < 20; idx++, counter++) {
			list[idx].show();
		}
		$("gallery_thumbs_page").update(galThumbs.currPage);
	}
}


function thumbsPrev() {
	var list = $$("#gallery_thumbs ul li");
	if( list != null ) {
		var galThumbs = $("gallery_thumbs");
		var numPages = Math.ceil( list.length /20 );
		if( !galThumbs.currPage ) {
			galThumbs.currPage = 1;
		}
		for( var idx = (galThumbs.currPage-1)*20, counter = 0; idx < list.length && counter < 20; idx++, counter++) {
			list[idx].hide();
		}
		galThumbs.currPage = galThumbs.currPage-1;
		if( galThumbs.currPage == 0 ) {
			galThumbs.currPage = numPages;
		}
		for( var idx = (galThumbs.currPage-1)*20, counter = 0; idx < list.length && counter < 20; idx++, counter++) {
			list[idx].show();
		}
		$("gallery_thumbs_page").update(galThumbs.currPage);
	}
}

/** Deprecated: NOT converted to jQuery */
function eksternHjemmeside(url){ 
	window.top.location = "" + url;
}

/** Converted to jQuery */
function expandOmtaleText() {
 //	$("factsContainerSmall").toggle();
	$("omtaleContainerSmall").toggle();
	$("omtaleContainer").toggle();
	// why is this here?
	//window.location.href = window.location.href +"#articleTop";
}


	
/** Converted to jQuery */			
function changeProgDay(movieId, selectedDate) {
	//var val = $F("progDayList");
	//window.open("http://program.filmweb.no/onemovie_locations.asp?movieid="+movieId+"&dato="+val, "newProgDay");
	var form = $("ajaxForm");
	if(movieId != null && selectedDate != null && form != null)
	{
		var formHash = form.serialize();
		var paramString = formHash;
		$("progClipper").innerHTML="<img class='ajaxwait' src='http://www.filmweb.no/template/static/gfx/ajax-loader.gif' alt='Vennligst vent, laster programmet.' title='Vennligst vent, laster programmet.'/>";
		new Ajax.Request(form.action, {
			method: 'get',
			encoding: 'ISO-8859-1',
			parameters: paramString,
			/*onComplete: function(response) {
					alert(response.responseText);
				},*/
			onFailure: function(response) {
					$("ajaxTarget").innerHTML = response.responseText;
				},
			onSuccess: function(response) {
					$("ajaxTarget").innerHTML = response.responseText;
					initSlider();
				}
			});
	}
	
}

/** Converted to jQuery */	
function purchase(url) {
	window.open(url, "_blank", "width=1024,height=750,resizable=yes,scrollbars=yes");
}


/** Converted to jQuery */	
function initScrollStaticBanner(bannerNum) {
	var ss = $$(".fw_main_reklame_180x500");
	if ( ss && ss.length >= bannerNum) {
		var banner = ss[bannerNum-1];
		if( banner ) {
			banner.makePositioned();
			var initPos = banner.cumulativeOffset();
			Event.observe(window, "scroll", function(event) {
				//console.debug("Scroll Offsets %d, %d", document.viewport.getScrollOffsets()[0],document.viewport.getScrollOffsets()[1] );
				if( document.viewport.getScrollOffsets()[1] >=  initPos[1] ) {
					banner.setStyle({"position": "fixed", "top": "5px", "left": initPos[0]+"px"});
				} else if( banner.getStyle("position") == "fixed") {
					banner.setStyle({"position": "static"});
				}
			});
			if($("fbFanBox")!=null){$("fbFanBox").hide();};
		}
	}
	
}

/** Converted to jQuery */	
function initIFrameAds() {
	var ads = ['toppBanner', 'knapp', 'netboard', 'netboard1', 'skyskrapere'];
	var srch = location.search;
	if( srch != null ) {
		var idx = srch.indexOf("?", 0);
		if( idx == 0 ) {
			srch = srch.slice(1);
		}
	} else {
		srch = "";
	}
	$A(ads).each( function(itm) {
		var iframeAd = $('iframeAd'+itm);
		if( iframeAd != null ) {
			var lastChar = itm.charAt(itm.length-1);
			if( lastChar == '0' || lastChar == '1' || lastChar == '2' || lastChar == '3' ) {
				itm = itm.slice(0, itm.length-1);
			}
			if( itm == 'skyskrapere' ) {
				iframeAd.observe("load", recalcSkyskraperHeight);
			}
			iframeAd.src=publicationUrl+'template/adverticement/ajax_'+itm+'.jsp?secName='+iframeAd.name+"&"+srch;
		}
	});
}
/** Converted to jQuery */	
function recalcSkyskraperHeight() {
	var bann = $('iframeAdskyskrapere');
	var oDoc = bann.contentWindow || bann.contentDocument;
	if (oDoc.document) {
		oDoc = oDoc.document;
	}
	var bod = $(oDoc.body);
	bann.height = bod.getHeight() + 10;
}

/** Converted to jQuery */	
function switchAds() {
	var ads = ['toppBanner', 'knapp', 'netboard', 'skyskrapere'];
	$A(ads).each( function(itm) {
		var bann = $('iframeAd'+itm);
		var oDoc = bann.contentWindow || bann.contentDocument;
		if (oDoc.document) {
			oDoc = oDoc.document;
		}
		oDoc.location.reload();
	});
	//pageTracker._trackPageview();
	_gaq.push(['_trackPageview']);
}

/** Converted to jQuery
 * Override for EAS function.
 * @param {Object} width the width of the flash object
 * @param {Object} height the height of the flash object
 * @param {Object} src the flash source
 * @param {Object} extra extra params
 */
function EAS_show_flash_override(width, height, src, extra) {
	var origFunc = window["EAS_show_flash_orig"];
	var newExtra = extra;
	if( extra != null ) {
		newExtra = extra.replace('wmode=window', 'wmode=opaque');
	}
	origFunc(width, height, src, newExtra);
	var topAd = $("fw_reklame_topp_single");
	if( !topAd ) {
		topAd = $("fw_reklame_topp_single_low");
		if( !topAd ) {
			topAd = $("fw_reklame_topp");
		}
	}
	if( topAd ) {
		
	} 
}
window["EAS_show_flash_orig"] = window["EAS_show_flash"];
window["EAS_show_flash"] = EAS_show_flash_override;

/**Converted to jQuery*/
var counter = 0;
function EAS_embed_flash_override(width, height, src, params, flashvars, events, eventurl) {
   var par = "";

   if (params) {
      var args = [];
      var eq, nv0, nv1;
      args = params.split(',');
      for (i = 0; i < args.length; i++) {
         eq = args[i].indexOf('=');
         nv0 = args[i].substring(0, eq);
         nv1 = args[i].substring(eq + 1, args[i].length);
         if (nv0.toLowerCase() == 'flashvars')
            flashvars += (flashvars ? "&" : "") + nv1;
         else
            par += '<param name="' + nv0 + '" value="' + nv1 + '" />';
      }
   }

   if (events && eventurl) {
      var args = [];
      args = events.split(",");
      for (i = 0; i < args.length; i++) {
         flashvars += (flashvars ? "&" : "") + args[i] + "=" + eventurl + args[i];
      }
   }

   if (flashvars)
      par += '<param name="FlashVars" value="' + flashvars + '" />';

   document.write('<object id="X_'+counter+'" name="X_'+counter+'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + width + '" height="' + height + '"><param name="movie" value="' + src + '" />');
   counter++;
   if (params) document.write(par);

   document.write('<!--[if !IE]>-->');
   document.write('<object id="X_'+counter+'" name="X_'+counter+'" type="application/x-shockwave-flash" data="' + src + '" width="' + width + '" height="' + height + '">');
   if (params) document.write(par);
   document.write('</object>');
   document.write('<!--<![endif]-->');

   document.write('</object>');

   return;
}
window["EAS_embed_flash"] = EAS_embed_flash_override;

/** Converted to jQuery*/
function initBodyClick(url) {
	window.fwBodyClick = function(evnt) {
		var offset = $("centerFramework").cumulativeOffset();
		if(evnt.target == $(document.body) && (evnt.pointerX() < offset.left || evnt.pointerX() > offset.left +$("centerFramework").getWidth())) {
			window.open(url, '_blank');
		}
	};
	window.fwFocusClick = function(evnt) {
		$(document.body).observe("click", window.fwBodyClick);
		$(document.body).addClassName("cursorHand");
		$(document.body).stopObserving("click", window.fwFocusClick);
	};
	Event.observe(window, "blur", function(evnt) {
		$(document.body).stopObserving("click", window.fwBodyClick);
		$(document.body).removeClassName("cursorHand");
	});
	Event.observe(window, "focus", function(evnt) {
		if( window.fwInitialFocus ) {
			$(document.body).observe("click", window.fwFocusClick);
			$(document.body).addClassName("cursorHand");	
		} else {
			window.fwInitialFocus = true;
		}
	});
	$(document.body).observe("click", window.fwBodyClick);
	$(document.body).addClassName("cursorHand");
	var top = getTopAdElem();
	if( top ) {
		top.store("bgClickEnabled", url);
		if( top.retrieve("includeBgClick") ) {
			top.observe("click", function(event){window.open(url, '_blank');});
			top.addClassName("cursorHand");
		}
	}
}
/** Converted to jQuery*/
function getTopAdElem() {
	var top = $("fw_reklame_topp");
	if( !top ) {
		top = $("fw_reklame_topp_single_low");
		if( !top ) {
			top = $("fw_reklame_topp_single");
		}
		
	}
	return top;
}

/** Converted to jQuery*/
function transparentTop(url){
	var top = getTopAdElem();
	if (top != null) {
		top.addClassName("transparent");
		top.update("");
		if (url != null) {
			top.observe("click", function(evnt){
				window.open(url, '_blank');
			});
		}
	}
}

/** Converted to jQuery*/
function transparentTopBg() {
	var top = getTopAdElem();
	if( top ) {
		top.setStyle({background: 'none'});
		top.update("");
		top.store("includeBgClick", true);
		if( top.retrieve("bgClickEnabled")) {
			top.observe("click", function(event){window.open(top.retrieve("bgClickEnabled"), '_blank');});
			top.addClassName("cursorHand");
		}
	}
}


/* kinofane click */
/** Converted to jQuery*/
function showBuyCinemaTicketInfo(pubUrl, init, prodType)
{
	$$(".dvd_bd_liste").each(function(item){item.hide();});
 	show('container_program_dvd_bolk');
	//hide('dvd_ajax_kjopinfo');
	var kino = $('flappKinoprogram');

	$$("#art_filmomtale_program_block .flapp_valgt").each(function(item){
		item.removeClassName("flapp_valgt");
		item.addClassName("flapp");
	});
	
	if(kino != null) {
		kino.addClassName("flapp_valgt");
		kino.removeClassName("flapp");
	}
	
}


/* filmfane click */
function showBuyVideoInfo(pubUrl, init, prodType)
{
	var articleId = "null";
	var extId = null;
	var artIdContainer = $("dvd_info_article_id"); 
	if( artIdContainer!= null) {
		articleId = artIdContainer.innerHTML;
		extId = artIdContainer.readAttribute("extId");
		if( extId == '') {
			extId = null;
		}
	}
	if( prodType == null ) {
		prodType = "kino";
	}
	var prodArr = ["kino", "bd", "dvd", "stream", "dl"];
	var userProdType = null;
	if( init==true && window.location.hash != null && window.location.hash != "") {
		var hsh = window.location.hash.substring(1);
		if( prodArr.indexOf(hsh) != -1 ) {
			userProdType = prodType = hsh;
		}
	}
	
	// Set selected flap
	if(prodType == "kino")
		_selectType = 0;
	else if(prodType == "bd")
		_selectType = 1;
	else if(prodType == "dvd")
		_selectType = 2;
	else if(prodType == "stream")
		_selectType = 3;
	else if(prodType == "dl")
		_selectType = 4;
	
	
	var tabSelected = false;
	if( init == false || userProdType != null) {
		$$(".dvd_bd_liste").each(function(item){item.hide();});
		$$("#art_filmomtale_program_block .flapp_valgt").each(function(item){
			item.removeClassName("flapp_valgt").addClassName("flapp");
		});
		switch( prodType) {
		case 'kino':
			show('container_program_dvd_bolk');
			$("flappKinoprogram").addClassName("flapp_valgt").removeClassName("flapp");
			
			break;
		default:
			hide('container_program_dvd_bolk');
			$(prodType+"_ajax_kjopinfo").show();
			$("flapp_"+prodType+"_Kjopinfo").addClassName("flapp_valgt").removeClassName("flapp");
			break;
		
		}
		tabSelected = true;
	}
	
	
	
	if( extId == null ) {
		//progress();
		
	} else if(pubUrl != null && articleId != null && $("productTemplate") != null) {
		
		var paramString = "articleId=" + articleId;
		var dvdContent = $("dvd_ajax_kjopinfo");
		
		new Ajax.Request("/template/components/tools/jsonProxy.jsp", {
			method: 'get',
			parameters: {
				remoteUrl:'http://program.filmweb.no/MovieProducts/ProductInfo/'+extId
				
				},
			onSuccess: function(response) {
				
				$$(".dvd_bd_liste .ajaxwait").each(function(item){item.remove();});
				var jsonResult = response.responseJSON;
				if( !jsonResult && response.responseText ) {
					jsonResult = response.responseText.evalJSON(true);
				}
				var prodTemplate = $("productTemplate");
				var t = new Template(prodTemplate.innerHTML);
				var countArr = [0,0,0,0,0];
				
				
				var now = new Date();
				var selCandidates = [false, false, false, false, false];
				jsonResult.each(function(item) {
					if( item.videoProductTypeId == 0 || item.videoProductSupplierId == 0) {
						// error
						return;
					}
					
					if( item.videoProductSupplierId == 1 ) {
						item.supplierProductUrl += "?__hwaff=filmwebno";
					}
					
					if( item.videoProductTypeId == 5 ) {
						// bd+dvd product
						countArr[2]++;
						countArr[1]++;
					} else {
						countArr[item.videoProductTypeId]++;
					}
					item.formatLabel =  getProductFormatLabel(item.videoProductTypeId);
					item.formattedReleaseDate = item.releaseDate.substr(0, 10);
					item.price = formatAsNKR(item.price);
					
					// check if the releaseDate is in the past
					var relDate = new Date(item.formattedReleaseDate.substr(6),
							(new Number(item.formattedReleaseDate.substr(3,2)))-1,
							item.formattedReleaseDate.substr(0,2)
							);
					if( relDate.getTime()<=now.getTime()) {
						item.formattedReleaseDate = null;
						if( item.videoProductTypeId == 5 ) {
							// bd+dvd product
							selCandidates[2] = true;
							selCandidates[1] = true;
						} else {
							selCandidates[item.videoProductTypeId] = true;
						}
						
					}
					if( item.videoProductTypeId == 5 ) {
						$(prodArr[2]+"_ajax_kjopinfo").insert(t.evaluate(item));
						$(prodArr[1]+"_ajax_kjopinfo").insert(t.evaluate(item));
					} else {
						$(prodArr[item.videoProductTypeId]+"_ajax_kjopinfo").insert(t.evaluate(item));
					}
				});
				
				
				prodTemplate.remove();
				$$(".productPoster img").each(function(item){
					if( item.readAttribute("imageSource") != '') {
						item.writeAttribute("src", item.readAttribute("imageSource"));
					}
				});
				
				//$$(".productLinks a").each(function(item){
				$$(".productRow a").each(function(item){
					
					item.writeAttribute("href", getShopLinkTracker(item.readAttribute("shopId"))+item.readAttribute("supplierProductUrl"));
					 
					item.observe("click", function(event){
						var prodTitle = event.element().readAttribute("productTitle");
						//var pageTracker=_gat._getTracker("UA-53103-6");
						//pageTracker._trackEvent("Produktsalg", getShopName(item.readAttribute("shopId")), prodTitle);
						_gaq.push(['_trackEvent', 'Produktsalg', getShopName(item.readAttribute("shopId")), prodTitle]);
					});
				});
				
				$("bd_ProdCount").innerHTML = countArr[1];
				$("dvd_ProdCount").innerHTML = countArr[2];
				$("stream_ProdCount").innerHTML = countArr[3];
				$("dl_ProdCount").innerHTML = countArr[4];
				
				
				var customerAlertTemplate = $("customerAlertTemplate");
				var cat = new Template(customerAlertTemplate.innerHTML);
				
				//$(prodArr[1]+"_ajax_kjopinfo").innerHTML = cat.evaluate({videoProductTypeId: 1});
				
				for( var i = 1; i < countArr.length; i++) {
					if( countArr[i] == 0) {
						$(prodArr[i]+"_ajax_kjopinfo").innerHTML = cat.evaluate({videoProductTypeId: i});
					
						$('progressFeedback'+ i).hide();
						
						// feedback
						if($('signupFeedback' + i) != undefined)
							$('signupFeedback' + i).hide();
						
						// form elements
						if( $("dl_ProdCount").innerHTML != 0 ){
							$('dlFeedback' + i).hide();
						}

						if($("dvd_ProdCount").innerHTML != 0){
							$("dvdFeedback" + i).hide();
						}
						
						if($("stream_ProdCount").innerHTML != 0){
							$("olFeedback" + i).hide();
						}
						if($("bd_ProdCount").innerHTML != 0){
							$("brFeedback" + i).hide();
						}
						
					//	var button = $$("#"+prodArr[i]+"_ajax_kjopinfo .send");
				/*		if( button != null && button.length > 0) {
							button.observe('click', productAlertMe);
						}
				*/
					} 
				}
				
				//	customerAlertTemplate.remove();
				
				if( !tabSelected ) {
					var realIndexes = [0,2,1,3,4]; // needed to put dvd before bd
					for( var c = 0 ; c <selCandidates.length; c++ ) {
						if( selCandidates[realIndexes[c]] == true) {
							hide('container_program_dvd_bolk');
							
							/* On cinema even if other formats are out */
							if(c == 0){
								break;
								// Go to next if after loop
							}
							
							$("flappKinoprogram").removeClassName("flapp_valgt");
							$("flappKinoprogram").addClassName("flapp");
							$(prodArr[realIndexes[c]]+"_ajax_kjopinfo").show();
							$("flapp_"+prodArr[realIndexes[c]]+"_Kjopinfo").addClassName("flapp_valgt");
							$("flapp_"+prodArr[realIndexes[c]]+"_Kjopinfo").removeClassName("flapp");
							tabSelected = true;
							break;
						}
					}
					if( !tabSelected || true ) {
						var kinoAlerts = $$(".kinoAlert");
						if( kinoAlerts != null && kinoAlerts.length != 0) {
							for( var c = 0 ; c <countArr.length; c++ ) {
								if( countArr[realIndexes[c]] > 0) {
									hide('container_program_dvd_bolk');
									$("flappKinoprogram").removeClassName("flapp_valgt");
									$("flappKinoprogram").addClassName("flapp");
									$(prodArr[realIndexes[c]]+"_ajax_kjopinfo").show();
									$("flapp_"+prodArr[realIndexes[c]]+"_Kjopinfo").addClassName("flapp_valgt");
									$("flapp_"+prodArr[realIndexes[c]]+"_Kjopinfo").removeClassName("flapp");
									tabSelected = true;
									break;
								}
							}
						}
					}
				}
				
				progress();
				
			},
			onFailure: function(response) {
				$("dvd_ajax_kjopinfo").innerHTML = "Det oppstod en feil under henting av produkter. <!-- "+response.responseText+"-->";
			}
		});
	}
	
}

/** Converted to jQuery*/
function hideKinoAlert(){
	if($('kinoFeedback1') != undefined)
		$('kinoFeedback1').hide();
	if($('kinoFeedback2') != undefined)
		$('kinoFeedback2').hide();
	if($('kinoFeedback3') != undefined)
		$('kinoFeedback3').hide();
	if($('kinoFeedback4') != undefined)
		$('kinoFeedback4').hide();	
}

/** Converted to jQuery*/
function showKinoAlert() {
	if($('kinoFeedback1') != undefined)
		$('kinoFeedback1').show();
	if($('kinoFeedback2') != undefined)
		$('kinoFeedback2').show();
	if($('kinoFeedback3') != undefined)
		$('kinoFeedback3').show();
	if($('kinoFeedback4') != undefined)
		$('kinoFeedback4').show();
}

/**TODO: Converted to jQuery*/
function addProductNotification2(formID)  
{
	$('progressFeedback'+ _selectType).show();
	
	var pageUrl = 'http://program1.filmweb.no/FilmwebServices/ProductAlert/Add';
	var artIdContainer = $("dvd_info_article_id"); 
	if( artIdContainer!= null) {
		articleId = artIdContainer.innerHTML;
		extId = artIdContainer.readAttribute("extId");
	}
	//Serialize the form parameters to pass them along as part of the form submission  
    var params = Form.serialize(formID);
    var start = params.indexOf("&", 0);
    params = "movieExtId="+ extId + params.substring(start, params.length) + "&remoteUrl=" + pageUrl;
   
 // Disable the form - 'formID' is the id of the form that was passed in  
 //Form.disable(formID);   	
 
 // Make an ajax request with the 'get' method, passing it the serialized form  
 // and using 'ReportErrors' function to show any errors  
 // and 'ProcessResults' function to process the retrieved results  
 // To use the 'post' method, simply change the method to 'post'  
 new Ajax.Request(  
	 "/template/components/tools/jsonProxy.jsp",  
	 { 
	   method: 'POST', 
	   parameters: params, 
	   onFailure: ReportError,  
	   onComplete: function(request) {  ProcessResult(request.responseText); },  
       evalScript: false 
     }
  );
}

/** Converted to jQuery*/
function ProcessResult(responseText){

	$('signupFeedback'+ _selectType).show();
	$('progressFeedback'+ _selectType).hide();
}

/** Converted to jQuery*/
function ReportError(responseText){  
 //alert('en feil oppstod: ' + responseText);  
}  
/*
document.observe("dom:loaded", function(){
		
});
*/

/** Converted to jQuery*/
function getShopLinkTracker(shopId) {
	switch(shopId) {
	case '1': return ''; //'http://ad1.emediate.dk/eas?camp=210972;ty=ct;EASLink='; // headweb
	case '2': return ''; //'http://ad1.emediate.dk/eas?camp=210970;ty=ct;EASLink='; // platekomp
	case '3': return ''; //'http://ad1.emediate.dk/eas?camp=210971;ty=ct;EASLink='; // dvdhuset
	case '4': return ''; // film2home
	case '5': return ''; // filmarkivet
	case '6': return ''; // telenor
	} 
}

/** Converted to jQuery*/
function getProductFormatLabel(labelId) {
	switch(labelId) {
	case 0: return "Kino";
	case 1: return "Blu-Ray";
	case 2: return "DVD";
	case 3: return "Streaming";
	case 4: return "DL";
	case 5: return "DVD+BD";
	}
}

/** Converted to jQuery*/
function getShopName(shopId) {
	switch(shopId) {
	case '1': return 'Headweb';
	case '2': return 'Platekompaniet';
	case '3': return 'DVDHuset';
	case '4': return 'Film2Home';
	case '5': return 'Filmarkivet';
	case '6': return 'Telenor';
	}
}

/** Converted to jQuery*/
function formatAsNKR(price) {
	var strPrice = price.toString();
	var decimalIndex = strPrice.indexOf('.');
	if( decimalIndex != -1 ) {
		var num = strPrice.split('.');
		strPrice = num[0];
		if( num[1].length == 1) {
			num[1]+= '0';
		}
		strPrice += '<span class="priceDecimal">'+num[1]+'</span>';
	} else {
		strPrice+='<span class="priceDecimal">00</span>';
	}
	return strPrice;
}

/** TODO: Converted to jQuery*/
function productAlertMe(event) {
	
	var form = event.findElement("form");
	event.stop();
	var params = form.serialize(true);
	if( params.email == '' || params.email == 'Din e-post') {
		var inputTxt = form.getInputs("text");
		inputTxt[0].addClassName("invalidInput");
		return;
	}
	params.remoteUrl = 'http://program.filmweb.no/MovieProducts/ProductAlert/create'; 
	new Ajax.Request("/template/components/tools/jsonProxy.jsp", {
		method: 'post',
		parameters: params,
		onSuccess:function(response) {
			var jsonResult = response.responseJSON;
			if( !jsonResult && response.responseText ) {
				jsonResult = response.responseText.evalJSON(true);
			}
			if( jsonResult.validationError ) {
				if( "email" == jsonResult.validationError ) {
					var inputTxt = form.getInputs("text");
					inputTxt[0].addClassName("invalidInput");
				} else {
					form.replace("<div class='error'>Det oppstod en feil. Vennligst prøv igjen senere.<!--"+jsonResult.validationError+"--></div>");
				}
			} else {
				form.replace("<div class='thx'>Takk! Du vil bli kontaktet dersom produktet blir tilgjengelig.</div>");
			}
		},
		onFailure: function(response) {
			form.replace("<div class='error'>Det oppstod en feil. Vennligst prøv igjen senere.<!--"+response.responseText+"--></div>");
		}
	});
}

/** Converted to jQuery */
function showChangeKinoLocation() {
		var so = document.viewport.getScrollOffsets();
		var dim = document.viewport.getDimensions();
		var efw = $('changeKinoLocationWindow');
	//	efw.show();
	//	efw.setStyle({ "left": (so.left + dim.width/2-efw.getWidth()/2)+"px", "top": (so.top + dim.height/2-efw.getHeight()/2)+"px" });
	//	efw.setStyle({ "position": "absolute", "left": (so.left + dim.width/2-efw.getWidth()/2)+"px", "top": (so.top + dim.height/2-efw.getHeight()/2)+"px" });
		efw.setStyle({ "position": "absolute", "left": "50px", "top": (so.top + dim.height/2-efw.getHeight()/2)+"px" });
	//	efw.show();
		efw.setStyle( { "display": "block" });
	}

/** Converted to jQuery */
function hideChangeKinoLocation() {
	var efw = $('changeKinoLocationWindow');
	efw.hide();
}

// 302 tabs functionality
/** Converted to jQuery */
function tab302Click(tabId) {
	$$(".flippemenyTabs>div").each(function(item){
		if( item.id == 'tab302_'+tabId ) {
			item.addClassName("active");
		} else {
			item.removeClassName("active");
		}
	});
	$$("#tab_contentcontainer_302>div").each(function(item) {
			if( item.id == 'content302_'+tabId ) {
				item.show();
				if( !item.scrollInitialized  ) {
					tab302SliderInit();
				}
			} else {
				item.hide();
			}
	});
	
}
window["tab302Click"] = tab302Click;

/**
 * Converted to jQuery
 * Initialized the 302 tabslider.
 */
function tab302SliderInit() {
	$$("#tab_contentcontainer_302>div").each(function(item){
		if( item.visible() ) {													  
			var track = item.down();
			var scrollWindow = track.next();
			var con = scrollWindow.down();
			if( con != null && track != null ) {
				var conHeight = con.getHeight();
				if( conHeight <= 330 ) {
					track.hide();
					con.removeClassName("tabs_302_withSlider");
					scrollWindow.setStyle({height: conHeight+'px'});
				} else {
					var scrollRange = conHeight - 320;
					con.makePositioned();
					new Control.Slider(track.down(".handle"), track, {
							axis: "vertical",
							maximum: scrollRange,
							range: $R(0, scrollRange),
							onSlide: function(value) {
								var newVal = "-"+Math.round(value)+"px";
								con.style.top = newVal;
								},
							onChange: function(value) {
								var newVal = "-"+Math.round(value)+"px";
								con.style.top = newVal;
								} });
				}
			}
			
			item.scrollInitialized = true;
		}
	});
	
}
window["tab302SliderInit"] = tab302SliderInit;

/**
 * Converted to jQuery
 * Executes the periodical logic for the articleSwicher.
 * @param {PeriodicalExecuter} pe the PeriodicalExecuter instance
 */
function executeSwitcher(pe) {
	var articles = $$("#articleSwitcher .article");
	var toFade = null;
	var toAppear = null;
	for (var index = 0; index < articles.size(); ++index) {
		if( articles[index].visible() ) {
			toFade = articles[index];
			if( index <articles.size()-1 ) {
				toAppear = articles[index+1];
			} else {
				toAppear = articles[0];
			}
		}
	}
	
	new Effect.Parallel([ new Effect.Fade(toFade.id), new Effect.Appear(toAppear.id)],
		{duration: 1.0}
	);
	
}
window["executeSwitcher"] = executeSwitcher;

/**
 * Converted to jQuery
 * Initializes the articleSwitcher.
 */
function initArticleSwitcher() {
	var articles = $$("#articleSwitcher .article");
	if( articles != null && articles.size()>1 && $("articleSwitcher").periodicalExecuter == null) {
		$("articleSwitcher").periodicalExecuter = new PeriodicalExecuter( executeSwitcher, 6);
	}
}
window["initArticleSwitcher"] = initArticleSwitcher;

/**
 * Converted to jQuery
 * Switches the selected article
 * @param {int} newArticle the number of the article selected
 */
function articleSwitcher_manual(newArticle) {
	var pe = $("articleSwitcher").periodicalExecuter; 
	if( pe != null ) {
		$("articleSwitcher").periodicalExecuter = "stopped";
		pe.stop();
		$("articleSwitcher").periodicalExecuter = null;
	}
	var articles = $$("#articleSwitcher .article");
	var targetId = "articleSwitcher_"+newArticle;
	articles.each( function(item) {
		if( item.visible() && item.id != targetId) {
			item.hide();
		} else if(!item.visible() && item.id == targetId) {
			item.show();
		}
	}
	);
}
window["articleSwitcher_manual"] = articleSwitcher_manual;

// misc google tracking on menu items etc


document.observe("dom:loaded", function() {
  var mainMenuLinks = $$(".meny_fw_2010 .second_line_container a");
  if( mainMenuLinks != null) {
  	mainMenuLinks.each(function(link){
		link.observe("click", function(event){
			event.preventDefault();
			//var pageTracker=_gat._getTracker("UA-53103-6");
    		//pageTracker._trackEvent("Hovedmeny", this.innerHTML);
			_gaq.push(['_trackEvent', 'Hovedmeny', this.innerHTML]);
			setTimeout('document.location = "' + this.href + '"', 100);
		});
	});	
  }
  
  var ticketBarLinks = $$("#progChooseLink a");
  if( ticketBarLinks != null ) {
	  ticketBarLinks.each(function(link){
		  link.observe("click", function(event){
				event.preventDefault();
				//var pageTracker=_gat._getTracker("UA-53103-6");
	    		//pageTracker._trackEvent("Billettmeny","Byvalg", this.innerHTML);
				_gaq.push(['_trackEvent', 'Billettmeny','Byvalg', this.innerHTML]);
				setTimeout('document.location = "' + this.href + '"', 100);
			});
	  });
  }
  var changeLoc = $("changeLoc");
  if( changeLoc != null ) {
	  changeLoc.observe("click",function(event){
		  event.preventDefault();
		  //var pageTracker=_gat._getTracker("UA-53103-6");
		  //pageTracker._trackEvent("Billettmeny","Bytt sted");
		  _gaq.push(['_trackEvent', 'Billettmeny','Bytt sted']);
		  setTimeout('document.location = "' + this.href + '"', 100);
	  } );
  }
  var ticketBarDdm = $("ticketBarDdm");
  if( ticketBarDdm != null ) {
	  ticketBarDdm.observe("click",function(event){
		  //var pageTracker=_gat._getTracker("UA-53103-6");
		  //pageTracker._trackEvent("Billettmeny", "Pil ned");
		  _gaq.push(['_trackEvent', 'Billettmeny','Pil ned']);
	  } );
  }
});

/* Cookie based ads */
/** Converted to jQuery */
function prepareCookieBasedAd(adType) {
	var adContainer = $("fw_reklame_topp");
	if( adContainer == null ) {
		adContainer = $("fw_reklame_topp_single_low");
		if( adContainer == null ) {
			adContainer = $("fw_reklame_topp_single");
		}	
	}
	var retVal = null;
	if (adContainer != null) {
		var templateContext = adContainer.readAttribute("templateContext");
		if (templateContext != null) {
			var checkLocation = false;
			if (templateContext == 'art') {
				var artType = adContainer.readAttribute("articleTypeName");
				if (artType == 'filmomtale') {
					checkLocation = true;
				}
			} else if (templateContext == 'sec') {
				var secUName = adContainer.readAttribute("sectionuname");
				if( secUName == 'trailere' || adType =='program' || secUName=="filmnytt" || secUName=="konkurranser") {
					checkLocation = true;
				}
			}
			if( checkLocation ) {
				var locations = null;
				switch(adType) {
					case 'top':
						locations = $H({'Asker':13835, 'Askim':13836, 'Halden':13839, 'Horten':13842, 'Hønefoss':13845, 'Kristiansund':13851, 'Oslo':13820, 'Sarpsborg':13857, 'Tønsberg':13848, 'Verdal':13854});
						break;
					case 'program':
						locations = $H({'Asker':13824, 'Askim':13825, 'Halden':13826, 'Horten':13827, 'Hønefoss':13828, 'Kristiansund':13830, 'Oslo':13821, 'Sarpsborg':13832, 'Tønsberg':13829, 'Verdal':13831});
						break;
					case 'netboard':
						locations = $H({'Asker':13834, 'Askim':13837, 'Halden':13840, 'Horten':13843, 'Hønefoss':13846, 'Kristiansund':13852, 'Oslo':13822, 'Sarpsborg':13858, 'Tønsberg':13849, 'Verdal':13859});
						break;
					case 'bg':
						locations = $H({'Asker':13833, 'Askim':13838, 'Halden':13841, 'Horten':13844, 'Hønefoss':13847, 'Kristiansund':13853, 'Oslo':13823, 'Sarpsborg':13859, 'Tønsberg':13850, 'Verdal':13856});
						break;
					default:
						locations = null;
				} 
				if (locations != null) {
					var userCookie = getCookie("location");
					var adId = locations.get(userCookie);
					if (adId) {
						retVal = adId;	
						if ('top' == adType) {
							adContainer.setStyle({
								width: '1000px',
								padding: '0',
								height: '300px',
								background: 'transparent'
							});
							var separator = $("fw_reklame_topp_annonser");
							if( separator ) {
								separator.remove();
							}
						}
					}
				}
			}
		}
	}
	return retVal;
}

/** Converted to jQuery */
function getMovieTitle() {
	var titleMeta = $$("head meta[property='og:title']");
	if( titleMeta != null && titleMeta.length > 0) {
		var ediMeta = $$("head meta[name='edi']");
		if( ediMeta != null && ediMeta.length > 0) {
			var edi = ediMeta[0].readAttribute("content");
			if(edi != null && edi.indexOf('BVI') == 0) {
				return "kino";
			}
		}
		var ogTitle = titleMeta[0].readAttribute("content"); 
		
		var trailerIdx = ogTitle.indexOf(" trailer");
		if( trailerIdx != -1 ) {
			ogTitle = ogTitle.slice(0, trailerIdx);
		}
		return ogTitle;
	}
}

/* Deprecated. No longer in use */
/** Converted to jQuery */
function getMovieGenres() {
	var titleMeta = $$("head meta[name='movieGenre']");
	if( titleMeta != null && titleMeta.length > 0) {
		return titleMeta[0].readAttribute("content");
	}
}

/** Converted to jQuery! */
function prettyLocation(loc) {
	var isMore = false;
	var kino = getCookie("Kino");
	if( "Oslo-og-omegn" != loc ) {
		var splitKino = $A(kino.split(","));
		var firm = null;
		splitKino.each(function(item){
			var firmData = item.split("*");		
			if( firm == null ) {
				firm = firmData[0];
			} else if( firm != firmData[0] ) {
				isMore = true;
			}
		});
	}
	loc = loc.replace(/-/gi, " ");
	if( isMore ) {
		loc += ", m.fl.";
	}
	return loc;
}


document.observe("dom:loaded", function() {
	// kinotoppen
	var ktph = $("kinoToppenPlaceholder180");
	if( ktph != null ) {
		new Ajax.Request("/template/components/tools/ajax_kinotoppen.jsp", {
			method: 'post',
			parameters: {num: 10},
			onSuccess:function(response) {
				ktph.replace(response.responseText);
			},
			onFailure: function(response) {
				ktph.replace("<div class='error'>Det oppstod en feil. Vennligst prøv igjen senere.<!--"+response.responseText+"--></div>");
			}
		});
	}
	
	
	// reviews
	var reviewsFrame = $("reviewsFrame");
	if( reviewsFrame != null ) {
		var filmId = reviewsFrame.readAttribute("data-filmid");
		if( filmId != null ) {
			window.exdm = new easyXDM.Socket({
		        local: "/template/static/javascript/name.html",
		        swf: 'http://test.filmweb.no/template/static/swf/easyxdm.swf',
		        container: reviewsFrame,
				remote: "http://media.filmweb.no/filmwebbruker/Review/OtherReviews/"+filmId+"?position=left&articleId="+reviewsFrame.readAttribute("data-articleid"), // the path to the provider
				remoteHelper: "http://media.filmweb.no/filmwebbruker/Content/name.html",
				props: { 
					seamless: "seamless", 
					scrolling: "no", 
					width: "470", 
					height: "100%"},
		        onMessage:function(message, origin) {
		        	var obj = JSON.parse(message);
		        	obj.reviewsFrame = reviewsFrame;
		        	if( obj.consumerOp ) {
		        		window[obj.consumerOp](obj);
		        	}
		        }
		    });
		}
	}
	
	// IE jumplists
	if( window.prepareJumpList ) {
		prepareJumpList();
	}
});

function resizeReviewFrame(obj) {
	$("reviewWait").remove();
	obj.reviewsFrame.setStyle({height: obj.height+'px'});
	obj.reviewsFrame.down("iframe").writeAttribute("height", obj.height);
}

function reviewLogin(obj) {
	FB.login(function (response) {
		if (response.authResponse) {
			// user logged in.
			obj.response = response;
			window.exdm.postMessage(JSON.stringify(obj));
		} else {
			//TODO: make something prettier
			alert("Du må være logget inn for å kunne skrive anmeldelser");
		}
    });
}

function checkIfMobileUnit(showMobileVersion)
{
	var userAgent = navigator.userAgent;
	var isMobileUnit = false;
	var showFullversion = false;
	if(userAgent.match(/(iPod|iPhone|iPad)/ ))
	{
		isMobileUnit = true;
	} else if(userAgent.match(/(Android)/))
	{
		isMobileUnit = true;
	} else if(userAgent.match(/(NokiaN8)/))
	{
		isMobileUnit = true;
	}
	
	if(isMobileUnit && (!showMobileVersion || showMobileVersion=='f'))
	{
		var value="true";
		// setter sesjonscookie
		document.cookie="showFullversion" + "=" + value + ";path=/; domain=filmweb.no"; 
	} 
	
	var fullversionCookie = getCookie("showFullversion");
	if(fullversionCookie != null && fullversionCookie=="true")
	{
		showFullversion = true;
	}
	
	if(isMobileUnit && !showFullversion)
	{
		var url = document.URL;
		
		if(url == "http://www.filmweb.no" || url == "http://www.filmweb.no/" ||
		   url == "http://filmweb.no" || url == "http://filmweb.no/" ||
		   url == "http://test.filmweb.no" || url == "http://test.filmweb.no/")
		{
			window.location = publicationUrl + "mobil";
		}
	}
}

function detectMobile()
{
		var detectedMobile;
	var userAgent = navigator.userAgent;
	if(userAgent.match(/(iPod|iPhone|iPad)/ ))
	{
		detectedMobile = "iphone";
	} else if(userAgent.match(/(Android)/) && userAgent.match(/(AppleWebKit)/))
	{
		detectedMobile = "android";
		
	} else if(userAgent.match(/(NokiaN8)/))
	{
		detectedMobile = "nokia-n8";
	}
	return detectedMobile;
	
}
if(audiojs) {
	 audiojs.events.ready(function() {
		 var as = audiojs.createAll();
	 });
}


