var $y = jQuery.noConflict();

var ytv = function() {
	return {}
}();

ytv.ie = function() {
	return {
		designfix : function() {
			$y('#header ul.quicknav li:first-child').addClass('first');
			$y('#header ul.mainnav li:first-child').addClass('first');
			$y('#header ul.mainnav li:last-child').addClass('last');
			$y('#footer li:first-child').addClass('first');
		},

		tvguidecorners : function() {
			if ($y.browser.version > 6) {
				$y('#tvguide_navigation').corner({tl: {radius:5}, tr: {radius:5}, bl: {radius:10}, br: {radius:5}, antiAlias: true}).css('height','134px');
			}	
			$y('#date, #channel, #searchguide').corner({tl: {radius:5}, tr: {radius:5}, bl: {radius:5}, br: {radius:5}, antiAlias: true}).css('height','46px');
		},
		
		movieguidecorners : function() {
			$y('#movie_navigation').corner({tl: {radius:5}, tr: {radius:5}, bl: {radius:5}, br: {radius:5}, antiAlias: true}).css('height','61px');
			$y('.search, .theme, .category').corner({tl: {radius:5}, tr: {radius:5}, bl: {radius:5}, br: {radius:5}, antiAlias: true}).css('height','46px');
		}
	}
}();

ytv.swf = function() {
	return {
		version : '1.7.7',
		scalestate : 0,
		popped : false,
		remote : function() {
			if (!swfobject.hasFlashPlayerVersion('9.0.0')) {
				$y('#remoteholder').remove();
				return;
			}	
			swfobject.embedSWF("/design/swf/YouSeeTimeline.swf?v1.1", "remote", "940", "172", "9.0.0","/design/swf/expressInstall.swf", {url:'/feeds/remote/?'+Math.random(0,100000)}, {wmode:'transparent',menu:'false'},{});
		},
		
		player : function(channel) {
			swfobject.embedSWF("/design/swf/YouSeeVideoPlayer" + ytv.swf.version + ".swf", "playerswf", "100%", "100%", "10.0.0","/design/swf/expressInstall.swf", {url:'/feeds/player/livetv/'+channel+'/?'+Math.random(0,100000),'popped':ytv.swf.popped}, {salign:'tl',scale:'noscale',wmode:'transparent',menu:'false',allowfullscreen:'true',allowscriptaccess:'always'},{});
		},
	
		movieplayer : function(movieid) {
			var of = (arguments[1]) ? arguments[1]+'/' : '';
			swfobject.embedSWF("/design/swf/YouSeeVideoPlayer" + ytv.swf.version + ".swf", "playerswf", "100%", "100%", "10.0.0","/design/swf/expressInstall.swf", {url:'/feeds/player/movie/' + movieid + '/' + of + '?'+Math.random(0,100000),'popped':ytv.swf.popped}, {salign:'tl',scale:'noscale',wmode:'transparent',menu:'false',allowfullscreen:'true',allowscriptaccess:'always'},{});
		},  		

		trailerplayer : function(movieid) {
			swfobject.embedSWF("/design/swf/YouSeeVideoPlayer" + ytv.swf.version + ".swf", "playerswf", "100%", "100%", "10.0.0","/design/swf/expressInstall.swf", {url:'/feeds/player/trailer/' + movieid + '/?'+Math.random(0,100000),'popped':ytv.swf.popped}, {salign:'tl',scale:'noscale',wmode:'transparent',menu:'false',allowfullscreen:'true',allowscriptaccess:'always'},{});
		},  		
	
		archiveplayer : function(archiveid) {
			swfobject.embedSWF("/design/swf/YouSeeVideoPlayer" + ytv.swf.version + ".swf", "playerswf", "100%", "100%", "10.0.0","/design/swf/expressInstall.swf", {url:'/feeds/player/tvarchive/' + archiveid + '/?'+Math.random(0,100000),'popped':ytv.swf.popped}, {salign:'tl',scale:'noscale',wmode:'transparent',menu:'false',allowfullscreen:'true',allowscriptaccess:'always'},{});
		},
		
		scale : function() {	
			if (ytv.swf.scalestate == 1) {
				$y('#player').css('height', '445px');
				$y('#player h4').css('visibility', 'visible');
				$y('#playerholder').css('width','644px').css('height','425px');
				ytv.swf.scalestate = 0;
				return 'normal';
			} else {
				$y('#player').css('height', '610px');
				$y('#player h4').css('visibility', 'hidden');
				$y('#playerholder').css('width','900px').css('height','567px');
				ytv.swf.scalestate = 1;
				return 'double';
			}	
			return false;
		},
		
		popout : function() {
			var popout = window.open('/afspiller-vindue/','','height=425,width=644,resizable=1');
			return 'popout';
		}
	}
}();

ytv.tvguide = function() {
	return {
		activeids : new Array(),
		rule : '',
		
		highlight : function(ids, color, elm) {
			var inuse = '';
      		$y.each(ids, function(i, item) {
        		if (typeof(ytv.tvguide.activeids[item]) != 'undefined' && ytv.tvguide.activeids[item] != 0) {
          			$y.rule('li.category_'+item,'style:last').remove();  
          			ytv.tvguide.activeids[item] = 0;
          			$y(elm).parent().removeClass('selected'); 
        		} else {
          			rule = 'li.category_'+item+' { background-color:'+color+'!important;color:#fff}';   
          			$y.rule(rule).appendTo('style:last');
          			ytv.tvguide.activeids[item] = 1;
          			$y(elm).parent().addClass('selected');  
        		}
      		});
			$y('#categories li.selected').each(function(i, item) {
				inuse += $y(item).children('a').html() + '|';
			});
			$y.cookie('tvguide_cat', inuse, {expires: 21,path:'/',domain:'.yousee.tv'});
      		
      		return false;
    	},

		highlightcookie : function() {
			var highlighted = $y.cookie('tvguide_cat');
			if (highlighted != '') {
				$y('#categories li a').each(function(i, item) {
					if (highlighted.indexOf($y(item).html()+'|') != -1) {
						$y(item).click();
					}
				});
			}
		},

		activatedropdowns : function(activeoffset, application) {
			$y('select[name="time"]').bind('change', function() {
				ytv.tvguide.jumpto($y(this).children('option:selected').val());
			});
			
			if (application == 'tvguide') {
				$y('select[name="date"]').bind('change', function() {
					document.location.href = '/tvguide/'+$y('select[name="type"] option:selected').val()+'/'+$y(this).children('option:selected').val()+'/'+activeoffset;		
				});
			} 
			else if (application == 'channel') {
				var selected_channel = $y('select[name="channel"]').children('option:selected').val();
				$y('select[name="date"]').bind('change', function() {
					document.location.href = '/tvguide/kanal/' + selected_channel + '/'+$y(this).children('option:selected').val();		
				});
			}	
			$y('select[name="type"]').bind('change', function() {
				document.location.href = '/tvguide/'+$y(this).children('option:selected').val()+'/'+$y('select[name="date"] option:selected').val();		
			});
			
			$y('select[name="channel"]').bind('change', function() {
				var selected_channel = $y(this).children('option:selected').val();
				if (selected_channel != 'alle') {
					document.location.href = '/tvguide/kanal/' + selected_channel + '/'+$y('select[name="date"] option:selected').val();					
				} else {
					document.location.href = '/tvguide/'+$y('select[name="type"] option:selected').val()+'/'+$y('select[name="date"] option:selected').val();							
				}
			});
						
			$y('#tvguide_navigation select').uniform({selectClass:"select",focusClass:"selectfocus"});
		},
		
		jumpto : function(val) {
			var jumpto = $y('#kl-' + val).offset().top-195;
			if ($y('#tvguide_navigation').css('position') == 'relative') {
				jumpto = jumpto-215;
			}
			$y.scrollTo(jumpto+'px', {axis:'y',onAfter:function() {
				$y.cookie('guide_period', val, {path:'/',domain:'.yousee.tv'});
			}});
		},

		search : function() {
			var searchterm = $y('#searchguide input').val();
			if ($y.trim(searchterm) != '') {
				document.location.href = '/tvguide/soeg/' + searchterm + '/?q=' + searchterm + '&c=tvguide';
			}	
			return false;
		},
		
		addtomytv : function(id) {
			$y.get('/tvguide/addlistingtouser/' + id, {}, function(data) {
				if (data == '1') {
					$y('#programinfo #tvweek_action').html('Fjern fra TV-Uge');
					$y('#programinfo #tvweek_action').unbind('click');
					$y('#programinfo #tvweek_action').bind('click', function() { ytv.tvguide.removefrommytv(); });
					
				} else {
					$y('#tvguide').unblock({fadeOut:0});
					ytv.modal.login();
				}
			},
			'text');
		},

		removefrommytv : function() {
			var id = $y('#programinfo #tvweek_action').attr('id')
			$y.get('/tvguide/addlistingtouser/' + id + '/1', {}, function(data) {
				if (data == '1') {
					$y('#programinfo #tvweek_action').html('Tilf&oslash;j Tv-Uge');
					$y('#programinfo #tvweek_action').unbind('click');
					$y('#programinfo #tvweek_action').bind('click', function () { ytv.tvguide.addtomytv() });
				} else {
					alert('Programmet kunne ikke fjernes fra din Tv uge. Prøv at logge ind igen');
				}
			},
			'text');
		},
		
		positionheader : function() {
			if ($y(document).scrollTop() > 128) {
				$y('#tvguide_navigation').css({'position':'fixed'});
				$y('#tvguide .top').css({'position':'fixed','top':142,'background-image':'url(/design/img/tvguide_top_square_bg.gif)'});
			} else {
				$y('#tvguide .top').css({'position':'relative','top':0,'background-image':'url(/design/img/tvguide_top_bg.gif)'});
				$y('#tvguide_navigation').css({'position':'relative'});
			}
		}		
	}
}();

ytv.livetv = function() {
	return {}
}();

ytv.livetv.nowandnext = function(name, prefix, prefixnext, currentchannel) {
	var listings = new Array();
	var dataloaded = false;
	this.listings = new Array();
	this.channels = new Array();
	this.currentchannel = currentchannel;
	this.name = name;
	this.prefix = prefix;
	this.prefixnext = prefixnext;
	this.currentpositions = new Array();
	
	this.init = function() {
		var myself = this;
		function callStartChannels() {
			myself.startchannels();
		}
		
		$y.getJSON('/feeds/tvguide/dailyjson/' + this.currentchannel + '/', function(data) {
			$y.each(data, function(i, item) {
				foo = 'channel_' + i;
				listings[foo] = new Array(item);
			});
			this.listings = listings;
			dataloaded = true;
			callStartChannels();
		});
	}

	this.addchannel = function(channel) {
		this.channels[(this.channels.length)] = channel;
	}

	this.startchannels = function() {
		for (i = 0; i < this.channels.length; i++) {
			this.setnexton(this.channels[i]);
			this.next(this.channels[i]);
		}
	}

	this.next = function(channel) {
		items = listings['channel_' + channel];
		if (items == undefined) {return;}
		if (this.currentpositions['channel_' + channel] == undefined) {
			this.currentpositions['channel_' + channel] = 0;
		}
		
		next = items[0][this.currentpositions['channel_' + channel]];
		if (next == undefined) {return;}
	
		this.currentpositions['channel_' + channel]++;
		
		nexttitle = '';
		if (items[0][this.currentpositions['channel_' + channel]] != undefined) {
			nexttitle = 'Kl. ' + items[0][this.currentpositions['channel_' + channel]].starttime + ' ' + items[0][this.currentpositions['channel_' + channel]].title;		
			if (next.timetostart >= 300 && next.desc != '') {
				setTimeout(this.name + ".setcomingup('" + next.title.replace(/\'/, "\\'") + "')", (next.timetostart-300)*1000);
			}
		}

		setTimeout(this.name + ".set('" + next.title.replace(/\'/, "\\'") + "', '" + nexttitle.replace(/\'/, "\\'") + "', '" + next.desc.replace(/\'/, "\\'") + "', '" + next.timeslot.replace(/\'/, "\\'") + "', " + channel + ");", next.timetostart*1000);
	}

	this.setnexton = function(channel) {
		items = listings['channel_' + channel];
		if (items != undefined && items[0][0] != undefined) {
			nexttitle = 'Kl. ' + items[0][0].starttime + ' ' + items[0][0].title;		
			$y('#' + this.prefixnext + channel).html(nexttitle);
		} 
	}
	
	this.setcomingup = function(title) {
		$y('#player h4').next('p').html($y('#player h4').next('p').html() + '<br /><br />Lige om lidt: ' + title);	
	}
	
	this.set = function(title, nexttitle, description, timeslot, channel) {
		$y('#' + this.prefix + channel).html(title);
		$y('#' + this.prefixnext + channel).html(nexttitle);
	
		if (description != '' && timeslot != '') {
			$y('#player h4').html(title);	
			$y('#player h4').next('p').html(description);	
			$y('#player p.timeslot').html(timeslot);	
		}
		
		this.next(channel);
	}	
}

ytv.movie = function() {
	return {
		activatedropdowns : function() {
			$y('select[name="category"]').bind('change', function() {
				if ($y('select[name="category"] option:selected').val() != 0) {
					document.location.href = '/film/liste/genre/'+$y('select[name="category"] option:selected').val();	
				}		
			});
			$y('select[name="theme"]').bind('change', function() {
				if ($y('select[name="theme"] option:selected').val() != 0) {
					document.location.href = '/film/liste/tema/'+$y('select[name="theme"] option:selected').val();		
				}	
			});			
			
			$y('#movie_navigation select').uniform({selectClass:"select",focusClass:"selectfocus"});
		},
		
		activatesearch : function() {
			var defaultval = 'Indtast film, instruktør eller skuespiller';
			$y('#movie_navigation input[name="search"]').
			bind('focus', 
				function() { 
					if ($y(this).val() == 'Indtast film, instruktør eller skuespiller') { 
						$y(this).val('') 
					}
				}).
			bind('blur', 
				function() { 
					if ($y(this).val() == '') { 
						$y(this).val('Indtast film, instruktør eller skuespiller'); 
					}
				});
			$y('#movie_navigation input[name="search"]').autocomplete('/autocomplete/movies', {
				minChars:3,
				delay:400,
				scrollHeight:300,
				formatResult: 	function(data, value) {									
									var regexp = /.*\<span\>(.*)\<\/span\>/;
									var match = value.match(regexp);
									if (match) {
										return match[1];
									} else {
										return value;
									}
								}

			}).result(function(event, item) {
				document.location.href = '/film/soeg/' + event.target.value;
			});
		},
		
		search : function() {
			if ($y('#movie_navigation input[name="search"]').val() == 'Indtast film, instruktør eller skuespiller' || $y('#movie_navigation input[name="search"]').val() == '') {
				alert('Der er ikke indtastet søgeord');
				return false;
			}
			else { 	
				document.location.href = '/film/soeg/' + $y('#movie_navigation input[name="search"]').val() + '/?q=' + $y('#movie_navigation input[name="search"]').val() + '&c=film';
				return false; 
			}
		},
		
		purchase : function() {
			var regexp = /[0-9]{10,12}/
			var giftcertificate = $y('input[name="giftcertificate"]').val();
			
			if (giftcertificate.length > 0 || $y('#gift:checked').length == 1) {
				if (!regexp.test(giftcertificate)) {
					alert('Den indtastede gavekode skal bestå af 10 til 12 tal uden mellemrum');
					return false;
				} else {
					$y('form[name="paymentform"]').attr('action', '/film/koeb/gavekort/');
				}
			}
			$y('form[name="paymentform"]').submit();
			return true;
		},
		
		showrelease : function(elm, releasedate) {
			$y(elm).prepend('<span class="release">' + releasedate + '</span>');
		},
		
		hiderelease : function(elm) {
			$y(elm).find('span').remove();
		}
	}
}();

ytv.archive = function() {
	return {
		activatedropdowns : function() {
			$y('select[name="date"]').bind('change', function() {
				document.location.href = '/arkiv/'+$y('select[name="date"] option:selected').val() + '/' + $y('select[name="channel"] option:selected').val() + '/' + $y('select[name="genre"] option:selected').val();		
			});
			$y('select[name="channel"]').bind('change', function() {
				document.location.href = '/arkiv/' + $y('select[name="date"] option:selected').val() + '/'+$y('select[name="channel"] option:selected').val() + '/' + $y('select[name="genre"] option:selected').val();		
			});		
			$y('select[name="genre"]').bind('change', function() {
				document.location.href = '/arkiv/' + $y('select[name="date"] option:selected').val() + '/'+$y('select[name="channel"] option:selected').val() + '/' + $y('select[name="genre"] option:selected').val();		
			});					
			
			$y('#archive_navigation select').uniform({selectClass:"select",focusClass:"selectfocus"});
		},
		search : function() {
			var searchterm = $y('#archive_navigation input[name="search"]').val();
			if (searchterm.length > 2) {
				document.location.href = '/arkiv/soeg/' + searchterm + '/?q=' + searchterm + '&c=tvarkiv';
			}	
			return false;		
		}
	
	
	}
}();

ytv.sso = function() {
	return {
		isloggedin : function() {
			if ($y.cookie('yspro')) {
				return true;			
			} 
			else if ($y.cookie('remember')) {
				try { _gaq.push(['_trackEvent', 'User','login','auto logged in']); } catch (err) {}
				ytv.sso.login(false,false,true);
			}
			else {
				return false;
			}
		},
		
		writemenu : function() {
			$y('ul.quicknav li.ssomenu').remove();
			if (ytv.sso.isloggedin()) {
				$y('ul.quicknav').prepend('<li class="ssomenu"><a href="#" onclick="ytv.sso.logout(1);">Log ud</a></li>');
			} else {
				$y('ul.quicknav').prepend('<li class="ssomenu"><a href="#" onclick="ytv.modal.login();">Log ind</a></li><li class="ssomenu"><a href="/opret-login/">Opret bruger</a></li>');		
			}		
		},
		
		logout : function(reload) {
			$y.get('/sso/logout/', {}, function() { 
				ytv.sso.writemenu();
				if (reload == 1) {
					window.location.reload();
				}
			});
		},
		
		login : function(username,password) {
			var remember = $y('input[name="rememberme"]:checked').length;
			var int_arguments = arguments;

			$y.post('/sso/login/', {username:username,password:password,remember:remember}, function(data) {
				
				if (data == '1') {
					if (int_arguments.length == 2) {
						$y.getJSON('http://ysprowebtv.yousee.dk/setcookie.js.php?callback=?&yspro=' + $y.cookie('yspro'), function(data) {});
					}
					if (remember == 1) { try { _gaq.push(['_trackEvent', 'User','login','checked remember me']);} catch (err) {} }
					if (int_arguments.length == 3) {
						window.location.reload();
					}		
				} else {
					if (data == -1) {
						try { pageTracker._trackEvent('User','login','max ip reached'); } catch(err) {}	
						alert('Du har været logget ind fra fem forskellige computere indenfor det seneste døgn. Du kan først logge på fra denne computer om et døgn.');
					} else {
						try { _gaq.push(['_trackEvent', 'User','login','wrong username or password']); } catch(err) {}	
						alert('Brugernavn eller kodeord er forkert!');
					}	
				}

				
			}, 'text');
		},
		
		callback : function(data) {
			if ($y.cookie('lt')) {
				var targeturl = $y.cookie('lt');
				$y.cookie('lt', null, {path:'/',domain:'.yousee.tv'});
				window.location.href = targeturl;
			} else {
				$y.unblockUI();
				ytv.sso.writemenu();
				window.location.reload();
			}	
		},
		
		create : function() {
			var regexp = /^([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(\.){1}[a-zA-Z]{2,4})+$/;
		
			var password = $y('.createuser input[name="password"]').val();
			var rep_password = $y('.createuser input[name="rep_password"]').val();
			var email = $y('.createuser input[name="username"]').val();
			var firstname = $y('.createuser input[name="firstname"]').val();
			var lastname = $y('.createuser input[name="lastname"]').val();
			var cellphone = $y('.createuser input[name="cellphone"]').val();
			var username = email;
			var newsletter = $y('.createuser input[name="newsletter"]:checked').length;

			username = $y.trim(username);
			password = $y.trim(password);
			rep_password = $y.trim(rep_password);
			email = $y.trim(email);
			firstname = $y.trim(firstname);
			lastname = $y.trim(lastname);
			cellphone = $y.trim(cellphone);
			
			var error = '';
			
			if (password.length < 1 || password != rep_password) {
				error += "Kodeord\n"
			}
			if (!regexp.test(email)) {
				error += "Email adresse\n";
			}
			if (firstname.length < 2) {
				error += "Fornavn\n"
			}
			if (lastname.length < 2) {
				error += "Efternavn\n"
			}
			//if (cellphone.length < 8) {
			//	error += "Mobiltelefonnr.\n"
			//}

			if ($y('input[name="accept"]:checked').length < 1) {
				error += "Accept af vilkår\n";
			}
			
			if (error != '') {
				alert('Flg. felter blev ikke udfyldt korrekt:\n' + error);
				return false;
			} else {
				$y.post('/sso/createlogin/', {username:username,password:password,rep_password:rep_password,email:email,firstname:firstname,lastname:lastname,cellphone:cellphone,newsletter:newsletter}, function(data) {
					if (data == '1') {
						ytv.modal.createuser_receipt();
						return false;
					} else {
						if (data == '-1') {
							alert('Der er allerede oprettet en bruger med den valgte email adresse');
						} else {
							alert('Der skete en fejl under oprettelse af bruger. Prøv venligst igen.');
						}	
						return false;
					}
				}, 'text');
				return false;
			}
		},

		validate_update : function() {
			var regexp = /^([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(\.){1}[a-zA-Z]{2,4})+$/;
		
			var password = $y('input[name="password1"]').val();
			var rep_password = $y('input[name="password2"]').val();
			var email = $y('input[name="email"]').val();
			var firstname = $y('input[name="firstname"]').val();
			var lastname = $y('input[name="lastname"]').val();
			var cellphone = $y('input[name="mobile"]').val();
			
			password = $y.trim(password);
			rep_password = $y.trim(rep_password);
			email = $y.trim(email);
			firstname = $y.trim(firstname);
			lastname = $y.trim(lastname);
			cellphone = $y.trim(cellphone);
			
			var error = '';
			
			if (password != rep_password) {
				error += "Kodeord\n"
			}
			if (!regexp.test(email)) {
				error += "Email adresse\n";
			}
			if (firstname.length < 2) {
				error += "Fornavn\n"
			}
			if (lastname.length < 2) {
				error += "Efternavn\n"
			}
			
			if (cellphone.length > 0 && cellphone.length < 8) {
				error += "Mobiltelefonnr.\n"
			}

			if (error != '') {
				alert('Flg. felter blev ikke udfyldt korrekt:\n' + error);
				return false;
			} else {
				return true;
			}
		},

		
		refresh : function() {
			var now = new Date().getTime() / 1000;  
			var s = parseInt(now); 
			$y('body').append('<img src="/sso/refresh/?' +now+ '" alt="" />');
		},
		
		updatedata : function(data) {
			$y.get('/sso/refreshuserdata/' + escape(data));
		}
	
	}	
}();	

ytv.modal = function() {
	blockuicss = {width:'477px',textAlign:'left',top:'257px',border:'0',cursor:'auto'};	
		
	return {
		login : function(target) {
			if (typeof(target) != undefined) {
				$y.cookie('lt', target, {path:'/',domain:'.yousee.tv'});
			}
			$y.get(	'/modal/login/', 
					{}, 
					function(data) {
						$y.blockUI({message:data,css:blockuicss});		
					}, 
					'html'
				);	
		},
		
		forgotpassword : function() {
			$y.get(	'/modal/forgotpassword/', 
					{}, 
					function(data) {
						if ($y('div.blockPage').length > 0) {
							$y('div.blockPage').html(data);		
						} else {
							$y.blockUI({message:data,css:blockuicss});
						}
					}, 
					'html'
				);	
		},
		
		createuser : function() {
			$y.get(	'/modal/createuser/', 
					{}, 
					function(data) {
						if ($y('div.blockPage').length > 0) {
							$y('div.blockPage').html(data);
						} else {
							$y.blockUI({message:data,css:blockuicss});		
						}			
					}, 
					'html'
				);		
		},

		createuser_receipt : function() {
			$y.get(	'/modal/createuser_receipt/', 
					{}, 
					function(data) {
						$y.blockUI({message:data,css:blockuicss});
						pageTracker._trackPageview('/bruger-oprettet/');	
					}, 
					'html'
				);		
		},
		
		showprograminfo : function(id, offsettop) {
			$y.get(	'/modal/tvguide_programinfo/' + id, 
				{}, 
				function(data) {
					$y.extend(blockuicss, {top:'40%'});
					$y.blockUI({message:data,centerY:false,fadeIn:0,css:blockuicss,overlayCSS:{opacity:0.3}});
				}, 
				'html'
			);
			return false;		
		},
		
		beta : function() {
			$y.get(	'/modal/beta/', 
					{}, 
					function(data) {
						$y.blockUI({message:data,css:blockuicss});
					}, 
					'html'
				);	
		}
	}
}();

ytv.coverbrowser = function(element, id) {
	this.holderelement = element;
	this.element = $y(element).children('div.covers');
	if ($y(this.holderelement).hasClass('tvarchive') || $y(this.holderelement).hasClass('channelslist')) { 
		this.scrollwidth = 923;
	} else {
		this.scrollwidth = 910;
	}	
	this.currentpage = 1;
	this.maxpage = Math.ceil( ($y(this.element).children('div.coverscroller').children('div').length) / 5);
	this.id = id;
	
	this.scrollleft = function() {
		if (this.currentpage == 1) {
			this.scroll(this.maxpage, 125);			
		}
		else {
			this.scroll(this.currentpage-1, 500);
		}
		return false;
	}

	this.scrollright = function() {
		if (this.currentpage == this.maxpage) {
			this.scroll(1, 125);
		} else {
			this.scroll(this.currentpage+1, 500);
		}
		return false;
	}
		
	this.scroll = function(pageno, duration) {
		$y(this.element).scrollTo(((pageno-1)*this.scrollwidth)+'px', {axis:'x','duration':duration});	
		this.currentpage = pageno;
		$y(this.holderelement).children('div.top').children('div.pager').children('a').removeClass('selected');
		$y(this.holderelement).children('div.top').children('div.pager').children('a:eq('+(this.currentpage-1)+')').addClass('selected');	
		return false;
	}
	
	this.updatemarkers = function() {
		var i = 1;
		for (i = 1; i <= this.maxpage; i++) {
			var html = '&nbsp;<a href="#" onclick="return coverbrowser[' + this.id + '].scroll(' + i + ', 500);"';
			if (i == 1) {
				html += ' class="selected"';
			}
			html += '>&bull;</a>';
			
			$y(this.holderelement).children('div.top').children('div.pager').append(html);
		}
	}
	
	this.updatemarkers();	
}

var coverbrowser = new Array();

ytv.purchase = function() {
	return {
		setrecurring : function(state) {
			if (state == 1) {
				$y('#purchaselivetv').append('<input type="hidden" name="maketicket" value="1" />');
			} else {
				$y('input[name="maketicket"]').remove();
			}						
			return true;
		},
		
		acceptterms : function() {
			if ($y('input[name="accept"]:checked').length < 1) {
				alert('Du har ikke accepteret YouSee vilkår');
				return false;
			} else {
				$y('#terms').hide();
				$y('#paytypes').show();
				return true;
			}
		}
	}
}();

ytv.settings = function() {
	return {
		savechannelorder : function() {
			var channels = new Array();
			$y('#settings div.channels div.channel').each(function(i, item) {
				channels[i] = $y(item).attr('id').replace(/channel_/,'');
			});
			
			$y.post('/sso/savechannelorder', {channelorder:channels.toString()}, function(data) {
				
			});
			return true;
		}
	}
}();

ytv.global = function() {
	return {
		search : function() {
			var searchterm = $y('#header input[name="search"]').val();
			if (searchterm.length > 2) {
				document.location.href = '/soeg/' + searchterm + '/?q=' + searchterm + '&c=global';
			}	
			return false;		
		},
		
		initTeasers : function() {
			$y('#teasers').cycle({
				fx:'scrollHorz',
				timeout:7000,
				speed:1000,
				next:'#teaserholder .scrollright a',
				prev:'#teaserholder .scrollleft a',
				pause:1,
				pauseOnPagerHover:1,
				height:374,
				slideExpr:'div.teaser',
				sync:1
			});
			
			return true;
		}	
	}
}();

$y(document).ready(function() {
	if ($y.browser.name == 'msie') {
		ytv.ie.designfix();
	}
	
	$y('div.coverbrowser').each(function(i, item) {
		coverbrowser[i] = new ytv.coverbrowser($y(item), i);
		$y(item).find('div.scrollleft a').bind('click',function() { return coverbrowser[i].scrollleft(); });	
		$y(item).find('div.scrollright a').bind('click',function() { eval("coverbrowser[" + i + "].scrollright();"); return false; });	
	});

	setInterval("ytv.sso.refresh()", 300000 );

});

$y(window).load( function() {
	$y.get('/support-besked/', function(data) { 
		if ($y(data).children('p').html() != '') {
			$y('body').append(data); 
			$y('#statusmsg').css('width', $y(window).width() + 'px');
		}	
	}, 'html');
});

