var onDemandTitle;
var onDemandURL;

function jump(sel) {
	var url = sel.options[sel.selectedIndex].value;
	if ( url != '#' ) top.location = url;
}

function mini() {
	resizeTo(375,715); 
	scrollTo(432,100); 
	return false;
}

function std() {
	scrollTo(0,0); 
	resizeTo(1024,768); 
	return false;
}

function thumb_list_layout(className) {
	try {
		var r;
		if (document.getElementById) 
			r = document.getElementById('layout_container');
		else if (document.all)
			r = document.all.layout_container;
		else
			throw new Error("Can't get layout_container");
		
		if (r) {
			
			var e = r.getElementsByTagName('div');
			
			for (var i=0; i < e.length; i++) {
				if (e[i].className.match(/video_col_one_other_text_content/)) {
					e[i].className = 'video_col_one_other_text_content ' + className;
				}
			}
		
			switch (className) {
				case 'list':
					document.getElementById('layout_list').className = "on";
					document.getElementById('layout_thumbs_list').className = "off";
					document.getElementById('layout_thumbs').className = "off";
					break;
				case 'thumb':
					document.getElementById('layout_list').className = "off";
					document.getElementById('layout_thumbs_list').className = "off";
					document.getElementById('layout_thumbs').className = "on";
					break;
				case 'thumb_list':
					document.getElementById('layout_list').className = "off";
					document.getElementById('layout_thumbs_list').className = "on";
					document.getElementById('layout_thumbs').className = "off";
					break;
				default:
					throw new Error('Illegal layout option specified');
			}
			document.cookie = 'layout=' + escape(className) + ';path=/';
		}
	} catch (e) {
		alert(e);
	}
	
	return false;
}

function NewIcon() {}
NewIcon.RE = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/g;
NewIcon.write = function (id,ds) {
	var re = new RegExp(NewIcon.RE);
	var dm = re.exec(ds);
	var d = new Date(dm[1],dm[2]-1,dm[3],dm[4],dm[5]);
	var now = new Date();
	now.setDate(now.getDate()-7);
	if (document.createElement && document.getElementById && now < d) {
		var e = document.createElement('img');
		e.setAttribute('class','new_icon');
		e.setAttribute('alt','New');
		e.setAttribute('src','http://images.tvnz.co.nz/on_demand/images/new_icon.gif');
		e.setAttribute('width',27);
		e.setAttribute('height',12);
		var s = document.getElementById(id);
		if (!s) throw new Error('Element with ID ' + id + ' not found');
		var p = s ? s.parentNode : null;
		if (p) {
			p.replaceChild(e,s);
			//var t = document.createTextNode(String.fromCharCode(160));
			//p.insertBefore(t,e);
		}
	}
}

/* persistant layout */
function layoutCookie(event) {
	var cs = document.cookie.split(';');
	for (i in cs) {
		var c = cs[i].split('=');
		if (c[0] == 'layout') {
			try {
				thumb_list_layout(c[1]);
			} finally {
				// do nothing just in case our cookie is contaminated
			}
		}
	}
}

/* Debug traceing */
function trace(msg) {
	var tr = document.getElementById('trace');
	if (tr) {
		var t = document.createTextNode(msg);
		tr.appendChild(t);
		var br = document.createElement('br');
		tr.appendChild(br);
	}
}

function debugOutput(event) {
	if (document.location.search.match(/debug=true/)) {
		if (document.createElement) {
			var p = document.createElement('pre');
			p.setAttribute('id','trace');
			var d = document.createElement('div');
			d.setAttribute('class','debug');
			d.setAttribute('style','display:block;');
			d.appendChild(p);
			document.getElementsByTagName('body').item(0).appendChild(d);
			trace('tracing...');
		}
	}
}


/* Adobe Flash 9 and IE6 ExternalInterface fix */
function unloadFlash(event) {
	window.onunload = function() {
	  var objects = document.getElementsByTagName("OBJECT");
	  for (var i=0; i < objects.length; i++) {
	    for (var x in objects[i]) {
	      if (typeof objects[i][x] == 'function') {
	        objects[i][x] = null;
	      }
	    }
	  }
	}
}

function scrollToTop() {
	scrollTo(0,0);
}

/* add events */
if (window.addEventListener){ // W3C
	window.addEventListener('load', layoutCookie, false); 
	window.addEventListener('load', debugOutput, false); 
} else if (window.attachEvent){ // MSIE
	window.attachEvent('onload', layoutCookie); 
	window.attachEvent('onload', debugOutput); 
	window.attachEvent('onbeforeunload', unloadFlash); 
	window.attachEvent('onload', scrollToTop); 
} else { // OLD
	window.onload = function (event) {
		layoutCookie(event);
		debugOutput(event);
	}
} 

function validateFeedbackForm(f) {
	var E = ['first_name','last_name','email','about','comments'];
	for (i in E) {
		var e = f.elements[E[i]];
		switch (e.type) {
			case 'text':
			case 'textarea':
				if (!e.value || (e.name == 'email' && !e.value.match(/^.+@.+$/))) {
					alert(e.title);
					e.focus();
					return false;
				}
				break;
			case 'select-one':
				if (e.selectedIndex < 1) {
					alert(e.title);
					e.focus();
					return false;
				}
				break;
		}
	}
	return true;
}

function popup(a,features) {
	var url = a.getAttribute('href');
	var target = a.getAttribute('target') || '_blank';
	
	try {
		if (document.location.host.match('tvnzondemand\.co\.nz$')) document.domain = 'tvnzondemand.co.nz';
		else if (document.location.host.match('tvnz\.co\.nz$')) document.domain = 'tvnz.co.nz';
	} catch (e) {
		//nothing... just ignore the domain stuff
	}
	
	var w = window.open(url,target,features);
	w.focus();
	return w;
}
popup.features = {
	download: 'height=230,width=470,status=yes,resizable=yes',
	speedtest: 'height=560,width=494,status=yes,resizable=yes'
};

function displayLayer( id, value )
{
    if ( document.getElementById )
    {
        document.getElementById( id ).style.display = value;
    }
    else if ( document.all )
    {
        document.all[ id ].style.display = value;
    }
}

function hide( id )
{
    displayLayer( id, 'none' );
}

function show( id )
{
    displayLayer( id, 'block' );
}

function onChangeSectionondemand() {
	var Current =
   	document.ondemand_contact.subject.selectedIndex;
	if (document.ondemand_contact.subject.options[Current].text == "Problem or Issue") {
		show( 'qsm' );
	}
	else {
		hide( 'qsm' );
	}
}



/* regionalisation */
var ondemand = {};
ondemand.regionalisation = {};
ondemand.regionalisation.isOverseas = function () {
	var re = new RegExp('(?:^|;\\s)(overseas)(?:$|;)');
	var m = re.exec(document.cookie);
	return (m.length === 2);
}
ondemand.regionalisation.setOverseas = function (b) {
	var expDate = new Date();
	// add six months if we're not deleting the cookie
	if (b) expDate.setFullYear(expDate.getFullYear() + Math.floor((expDate.getMonth() + 1 + 6)/12), (expDate.getMonth() + 1 + 6)%12);
	document.cookie = 'overseas; expires='+expDate+'; path=/';
}	

Regionalisation = {}; // TODO delete these two lines after a release post revision 4749
Regionalisation.getRegion = function () {return null}
ondemand.regionalisation.getRegion = function () {return null}

ondemand.header = function (id,vars) {
	var swfURL = 'http://images.tvnz.co.nz/on_demand/images/';
	swfURL += 'navigation.swf';
	document.getElementById(id).parentNode.innerHTML = 
		'<object id="header" name="header" height="90" width="784" type="application/x-shockwave-flash" data="'+swfURL+'">'+
			'<param name="movie" value="'+swfURL+'" />'+
			'<param name="AllowScriptAccess" value="always"/>'+
			'<param name="flashVars" value="'+vars+'" />'+
			'<p>To view this video content you need <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" target="_blank">Flash</a>!</p>'+
		'</object>';		
}

ondemand.player = function (id,previewURL,chapterURLs,contentGroup) {
	var flvURL;
	if (ondemand.regionalisation.getRegion() == 'ALL') {
		flvURL = previewURL;
	} else { // region == 'NZ'
		flvURL = chapterURLs ? chapterURLs : previewURL;
	}
	document.getElementById(id).parentNode.innerHTML = 
		'<object id="player" name="player" width="320" height="265" type="application/x-shockwave-flash" data="http://images.tvnz.co.nz/on_demand/images/Motif_FLVPlayback_v11.swf">'+
			'<param name="movie" value="http://images.tvnz.co.nz/on_demand/images/Motif_FLVPlayback_v11.swf" />'+
			'<param name="allowScriptAccess" value="always" />'+
			'<param name="allowFullScreen" value="true" />'+
			'<param name="swLiveConnect" value="true" />'+
			'<param name="flashVars" value="flvURL='+flvURL+'&amp;CG='+contentGroup+'" />'+
			'<p>To view this video content you need <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" target="_blank">Flash</a>!</p>'+
		'</object>';
}

function WMP(id,url) {
	document.write(
		'<object id="'+id+'" width="320" height="252"'+
		'	type="application/x-oleobject" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6">'+
		'	<param name="URL" value="'+url+'"/>'+
		'	<param name="AutoStart" value="true"/>'+
		'	<param name="ShowStatusBar" value="true"/>'+
		'	<param name="ShowControls" value="true"/>'+
		'	<param name="ShowDisplay" value="false"/>'+
		'	<embed name="'+id+'" width="320" height="252" type="application/x-mplayer2"'+
		'		src="'+url+'" AutoStart="1" ShowStatusBar="1" ShowControls="1" ShowDisplay="0" />'+
		'</object>');
}

var rootURL = "http://images.tvnz.co.nz/tvnz_site_images/";

var jsHTML = window.jsHTML || {};

jsHTML.shareMore = function(_this, _title, _url) {
	$("body").createAppend('div', {id:'shareMore', className: 'popupBox', style: 'left: ' + ($(_this).offset().left - 400) + 'px; top: ' + ($(_this).offset().top + 15) + 'px; display: none;'}, [
		'div', {className:'title'}, 'Share TVNZ videos on some of the most-popular social networking and content sites on the internet.',
		'a', {href: '#', className:'close'}, 'CLOSE',
		'div', {className:'content'}, [
			'a', {href: 'http://del.icio.us/post?url=' + _url + '&title=' + _title, title: 'Bookmark on Delicious', target: '_blank'}, [
				'img', {src: rootURL + 'images/share/shareBoxDelicious.gif', alt:'Delicious'}],
			'a', {href: 'http://digg.com/submit?url=' + _url + '&title=' + _title, title: 'Share on Digg', target: '_blank'}, [
				'img', {src: rootURL + 'images/share/shareBoxDigg.gif', alt:'Digg'}],
			'a', {href: 'http://www.facebook.com/sharer.php?u=' + _url + '&t=' + _title, title: 'Share on Facebook', target: '_blank'}, [
				'img', {src: rootURL + 'images/share/shareBoxFacebook.gif', alt:'Facebook'}],
			'a', {href: 'http://reddit.com/submit?url=' + _url + '&title=' + _title, title: 'Share on Reddit', target: '_blank'}, [
				'img', {src: rootURL + 'images/share/shareBoxReddit.gif', alt:'Reddit'}],
			'a', {href: 'http://technorati.com/faves?add=' + _url, title: 'Share on Technorati', target: '_blank'}, [
				'img', {src: rootURL + 'images/share/shareBoxTechnorati.gif', alt:'Technorati'}],
			'a', {href: 'http://www.newsvine.com/_wine/save?popoff=0&u=' + _url + '&h=' + _title, title: 'Share on Newsvine', target: '_blank'}, [
				'img', {src: rootURL + 'images/share/shareBoxNewsvine.gif', alt:'Newsvine'}],
			'a', {href: 'http://www.stumbleupon.com/submit?url=' + _url + '&title=' + _title, title: 'Share on Stumbleupon', target: '_blank'}, [
				'img', {src: rootURL + 'images/share/shareBoxStumbleupon.gif', alt:'Stumbleupon'}],
			'a', {href: 'http://www.myspace.com/Modules/PostTo/Pages/?u=' + _url + '&t=' + _title, title: 'Share on MySpace', target: '_blank'}, [
				'img', {src: rootURL + 'images/share/shareBoxMyspace.gif', alt:'MySpace'}],
			'a', {href: 'http://www.mixx.com/submit?page_url=' + _url + '&title=' + _title, title: 'Share on Mixx', target: '_blank'}, [
				'img', {src: rootURL + 'images/share/shareBoxMixx.gif', alt:'Mixx'}],
			'a', {href: '#', title: 'Share on Twitter', target: '_blank', id: 'twitterBtn'}, [
				'img', {src: rootURL + 'images/share/shareBoxTwitter.gif', alt:'Twitter'}],
		],
		'img', {src: rootURL + 'images/ondemandmakeHPArrow.gif', height:'9', width:'17', className:'arrow', alt:''}
	]);
	$(document).ready(function(){
		$("#twitterBtn").click(function(event){
			twitter_click();
			event.preventDefault();
		});
	});
}

var initShareMore = function() {
	// Share Box
	$(".shareMore").each(function() {
		var $this = $(this);
		$(this).click(function() {
			if (($("#shareMore").is(":hidden") == false) && ($("#shareMore").is(":visible") == false)) {
				// calls the HTML from jsHTML
				jsHTML.shareMore(this, onDemandTitle, onDemandURL);
				$("#shareMore .close").click(function() {
					$("#shareMore").animate({height: "hide"}, 250);
					return false;
				}).css({cursor: "pointer"});
				$("#shareMore").animate({height: "show"}, 250);
			} else if ($("#shareMore").is(":visible")) {
				$("#shareMore").animate({height: "hide"}, 125, function() {
					$(this).css({left: ($this.offset().left - 380) + 'px', top: ($this.offset().top + 15) + 'px'}).animate({height: "show"}, 125);
				});
			} else {
				$("#shareMore").css({left: ($(this).offset().left - 380) + 'px', top: ($(this).offset().top + 15) + 'px'});
				$("#shareMore").animate({height: "show"}, 250);
			}
			return false;
		}).css({cursor: "pointer"});
	});
}