$(document).ready(function() {

  $.i18n.setDictionary(translations);

	/*playfeed roller*/
	var total = $("#playfeed ul li").size();
	var count = 0;
	
	
	var todaysDate = $(".scroll-area #days .currentday").attr("id");
	if(todaysDate) {
	  todaysDate = getFormatedDate(todaysDate ,0,"full");
	}
	

	
	var a = setInterval(function(){
		$("#playfeed ul li:nth-child("+count+")").hide();
		if (count == total) {
			count = 0;
		}
		count++;
		$("#playfeed ul li:nth-child("+count+")").fadeIn("slow");
	},6000);		
	/*/playfeed roller*/
  

  	/*tv-guide scroll to*/
	var currentTime = getCTimeNode();

	function getCTimeNode() {
		currentTime=0;
		var currentNode = $('.currentday li.first');
		if (currentNode.length==0)
			return currentTime;
		var cFound=false;
	
		while($(currentNode.next.length)&&(!cFound)){
			if(currentNode.hasClass("current-time")) {
				cFound=true;
			}
			else {
				currentTime++;
			}
			currentNode = currentNode.next();
		}
		return currentTime;
	}		
	 var playlistCount = $.cookie('playlist');
	
   if(playlistCount) {
      $("#main-menu .myplay a").html('Mitt Play ('+playlistCount+')');
      $("#main-menu .myplay").addClass('active'); 
      $("#footer .myplay").hide();
    }

  
	if(typeof background_link != 'undefined') {
		$("body").click(function(e){
		  var target = $(e.target);
		  if (target.is("body") || target.is("#content") || target.is("#footer") || target.is("#flash-wrapper")) {
		    window.open(background_link);
		  }
		});
	}


	$("#pre-day").click(function(){
		var link = $(this);
		var date = $(this).parent().next().find(".currentday").attr('id');
		var currentDay = $(".currentday");
		var prevDay = getFormatedDate(date,-1,"full");
		
		$("#next-day").removeClass("display-none");
		//if more than one week - stop
		if(todaysDate==getFormatedDate(prevDay,7,"full")) {
			$("#pre-day").addClass("display-none");
		}
		
		if (!$(':animated').length) {
			if($(currentDay).prev().length) {
				$(currentDay).removeClass("currentday");
				$(currentDay).prev().addClass("currentday");
				currentTime = getCTimeNode();
				
				if(!$(".currentday").find("ul li").length) { 
						$("#tv-guide .scroll-area").scrollTo( '.currentday' , 100, {queue:true, onAfter:function(){ 
																																																		  $("#scroll-up").addClass("display-none");
																																																			$("#scroll-down").addClass("display-none"); }})
				}
				else {
						$("#tv-guide .scroll-area").scrollTo( '.currentday .current-time' , 800, {queue:true, onAfter:function(){ 
																																																									 var offsetBottom = $(currentDay).prev().find("li:last-child").offset().top; 
																																																									 var offsetTop = $(currentDay).prev().offset().top; 
																																																									 toggleUpDownArrows(offsetBottom, offsetTop) }});
				}

				if(todaysDate==getFormatedDate(prevDay,0,"full")) {
					$(link).parent().find("span").text($.i18n._('On air today'));
				} else if (todaysDate==getFormatedDate(prevDay,+1,"full")) {
					$(link).parent().find("span").text($.i18n._('On air yesterday'));
				}
				else {
					$(link).parent().find("span").text($.i18n._('On air %s %s', [getFormatedDate(date,-1,"dayOnly"), getFormatedDate(date,-1,"short")] ));
				}

			}
			else {
				$.get(link.attr("href")+"?day="+prevDay, function(data){
					$(currentDay).parent().prepend(data);
					$(currentDay).prev().attr("id",prevDay);
					$(currentDay).removeClass("currentday");
					$(currentDay).prev().addClass("currentday");
					currentTime = getCTimeNode();
					
					
					if(!$(".currentday").find("ul li").length) {
						$("#tv-guide .scroll-area").scrollTo( '.currentday' , 100, {queue:true, onAfter:function(){  
																																																		$("#scroll-up").addClass("display-none");
																																																		$("#scroll-down").addClass("display-none");  }})
					}
					else {
						$("#tv-guide .scroll-area").scrollTo( '.currentday .current-time' , 800,  {queue:true, onAfter:function(){ 
																																																										var offsetBottom = $(currentDay).prev().find("li:last-child").offset().top; 
																																																										var offsetTop = $(currentDay).prev().offset().top;  
																																																										toggleUpDownArrows(offsetBottom, offsetTop) }});
					}
					
					if(todaysDate==getFormatedDate(prevDay,0,"full")) {
						$(link).parent().find("span").text($.i18n._('On air today'));
					} else if (todaysDate==getFormatedDate(prevDay,+1,"full")) {
						$(link).parent().find("span").text($.i18n._('On air yesterday'));
					}
					else {
						$(link).parent().find("span").text($.i18n._('On air %s %s', [getFormatedDate(date,-1,"dayOnly"), getFormatedDate(date,-1,"short")] ));
					}
					
				});
			}
		}
	
		return false;
	});
	
	//next day, day queryparameter "day" added to url in link (&day=2005-06-06)
	$("#next-day").click(function(){
		var link = $(this);
		var date = $(this).parent().next().find(".currentday").attr('id');
		
		var currentDay = $(".currentday");	
		var nextDay = getFormatedDate(date,1,"full");
		
		$("#pre-day").removeClass("display-none");
		
		//if next day is displayed - stop
		if(todaysDate==getFormatedDate(date,0,"full")) {
			$("#next-day").addClass("display-none");
		}

		if (!$(':animated').length) {		
			if($(currentDay).next().length) {
				$(currentDay).removeClass("currentday");
				$(currentDay).next().addClass("currentday");
				currentTime = getCTimeNode();

				if(!$(".currentday").find("ul li").length) {//tom
						$("#tv-guide .scroll-area").scrollTo( '.currentday' , 100, {queue:true, onAfter:function(){
							//$("#scroll-up").addClass("display-none");
							//$("#scroll-down").addClass("display-none");  
							}})
				}
				else {
						$("#tv-guide .scroll-area").scrollTo( '.currentday .current-time' , 800, {queue:true, onAfter:function(){ 
							var offsetBottom = $(currentDay).next().find("li:last-child").offset().top; 
							var offsetTop = $(currentDay).next().offset().top; 
							toggleUpDownArrows(offsetBottom, offsetTop) 
						}});
				}
					
				if(todaysDate==getFormatedDate(nextDay,0,"full")) {
						$(link).parent().find("span").text($.i18n._('On air today'));
					} else if (todaysDate==getFormatedDate(nextDay,-1,"full")) {
						$(link).parent().find("span").text($.i18n._('On air tomorrow'));
					}
					else if (todaysDate==getFormatedDate(nextDay,+1,"full")) {
						$(link).parent().find("span").text($.i18n._('On air yesterday'));
					}
					else {
						$(link).parent().find("span").text($.i18n._('On air %s %s', [getFormatedDate(date,-1,"dayOnly"), getFormatedDate(date,-1,"short")] ));
					}

			}
			else {	
				$.get(link.attr("href")+"?day="+nextDay, function(data){
					$(currentDay).parent().append(data);
					$(currentDay).next().attr("id",nextDay);
					$(currentDay).removeClass("currentday");
					$(currentDay).next().addClass("currentday");
					currentTime = getCTimeNode();
					
					if(!$(".currentday").find("ul li").length) { //tom
						$("#tv-guide .scroll-area").scrollTo( '.currentday' , 100, {queue:true, onAfter:function(){ 
																																																		  $("#scroll-up").addClass("display-none");
																																																			$("#scroll-down").addClass("display-none");  }})
					}
					else {
						$("#tv-guide .scroll-area").scrollTo( '.currentday .current-time' , 800, {queue:true, onAfter:function(){ 
																																																									 var offsetBottom = $(currentDay).next().find("li:last-child").offset().top; 
																																																									 var offsetTop = $(currentDay).next().offset().top;  
																																																									 toggleUpDownArrows(offsetBottom, offsetTop) } });
					}
					
					if(todaysDate==getFormatedDate(nextDay,0,"full")) {
						$(link).parent().find("span").text($.i18n._('On air today'));
					} else if (todaysDate==getFormatedDate(nextDay,-1,"full")) {
						$(link).parent().find("span").text($.i18n._('On air tomorrow'));
					}
					else if (todaysDate==getFormatedDate(nextDay,+1,"full")) {
						$(link).parent().find("span").text($.i18n._('On air yesterday'));
					}
					else {
						$(link).parent().find("span").text($.i18n._('On air %s %s', [getFormatedDate(date,-1,"dayOnly"), getFormatedDate(date,-1,"short")] ));
					}
					
				});
			}
	}
		
		return false;
	}); 
	
	$("#dim-layer").click(function(){
		dimPage();
	}); 														 
						
	//Show shows later that day					
	$("#scroll-down").click(function(){
		$("#scroll-up").removeClass("display-none");
		
		currentTime = currentTime+3;

		if(($(".currentday ul li").size()-6)<currentTime) {
			$("#scroll-down").addClass("display-none");
		}		
		
		$("#tv-guide .scroll-area").scrollTo( '.currentday li:eq('+(currentTime)+')', 800);
		return false;
		
	});
	
	
	//Show shows earlier that day	
	$("#scroll-up").click(function(){
					   
		$("#scroll-down").removeClass("display-none");	
		
		if(currentTime<3) {
			currentTime = 0;
		}		
		else {
			currentTime = currentTime-3;
		}
		
		if(currentTime<3) {
			$("#scroll-up").addClass("display-none");
		}
		
		$("#tv-guide .scroll-area").scrollTo( '.currentday li:eq('+(currentTime)+')', 800);

		return false;								
	});	
	/* /tv-guide scroll to */
	
	
	/* move up/down in playlist */
	$("table.playlist a.move-up").livequery("click", function(event) { 
		var currTr = $(this).parent().parent().parent();
		var prevTr = currTr.prev();
		var currCount = currTr.find("span.sort-count").text();
		var prevCount = prevTr.find("span.sort-count").text();	
		
		if (prevCount!="") {
		  console.log(prevCount);
			//save changed pos via AJAX here
			prevTr.before("<tr class=\"display-none\">"+currTr.html()+"</tr>");
			prevTr.prev().find("span.sort-count").text(prevTr.find("span.sort-count").text());
			prevTr.find("span.sort-count").text(currCount);
			if (prevTr.attr("class")=="display-none") {
				prevTr.prev().addClass("display-none");
				prevTr.find("a.mover").addClass("display-none");
				prevTr.fadeIn("slow");
				prevTr.removeClass("display-none");
			} else {
				prevTr.prev().find("a.mover").addClass("display-none");
				prevTr.prev().fadeIn("slow");
				prevTr.prev().removeClass("display-none");
			};
			currTr.remove();
		}
		return false;
	});
	
	$("table.playlist a.move-down").livequery("click", function(event) { 
		var currTr = $(this).parent().parent().parent();
		var nextTr = currTr.next();
		var currCount = currTr.find("span.sort-count").text();
		var nextCount = nextTr.find("span.sort-count").text();
		if (nextCount!="") {
		  console.log(nextCount);
			//save changed pos via AJAX here
			nextTr.after("<tr class=\"display-none\">"+currTr.html()+"</tr>");
			nextTr.next().find("span.sort-count").text(nextTr.find("span.sort-count").text());
			nextTr.find("span.sort-count").text(currCount);
			if (nextTr.attr("class")=="display-none") {
				nextTr.next().addClass("display-none");
				nextTr.find("a.mover").addClass("display-none");
				nextTr.fadeIn("slow");
				nextTr.removeClass("display-none");
			} else {
				nextTr.next().find("a.mover").addClass("display-none");
				nextTr.next().fadeIn("slow");
				nextTr.next().removeClass("display-none");
			};
			currTr.remove();
		}
		return false;
	});	
	/* /move up/down in playlist*/

	/* delete in playlist */
	$("table.playlist a.delete").livequery("click", function(event) { 
		//delete pos via AJAX
    $.get($(this).attr("href"));
		var currTr = $(this).parent().parent();
		var	count = parseInt(currTr.find("span.sort-count").text());
		var nextTr = currTr.next();
		while(nextTr.length){
			nextTr.find("span.sort-count").text(count);
			count++;
			nextTr = nextTr.next();
		}
		currTr.fadeOut("slow", function(){currTr.remove();});
		
		return false;
	});	
	/* /delete in playlist */
	
	/* delete in subscription */
	$("table.subscriptions a.delete").livequery("click", function(event) { 
		//delete pos via AJAX
		$.get($(this).attr("href"));
		$(this).parent().parent().remove();
		return false;
	});	
	/* /delete in subscription */
	

	/*toggle seasons*/
	$("table.video-tree .season-col a").click(function(){	
		var clickedSeaseon = $(this).parent().parent();
		var target = $(clickedSeaseon).attr("class").replace(/.*toggleSeason-([\w-]+).*/, "$1");
		$("table.video-tree .season-"+ target).toggle();
		
		if($(clickedSeaseon).hasClass("open")) {
			$(clickedSeaseon).removeClass("open");
		}
		else {
			$(clickedSeaseon).addClass("open");
		}
		
		return false;
	});
	
	/*clip-tree specific*/
	$("table.clip-tree .season-col a").click(function(){	
		var clickedSeaseon = $(this).parent().parent();
		var target = $(clickedSeaseon).attr("class").replace(/.*toggleSeason-([\w-]+).*/, "$1");
		$("table.clip-tree .season-"+ target).toggle();
		
		if($(clickedSeaseon).hasClass("open")) {
			$(clickedSeaseon).removeClass("open");
		}
		else {
			$(clickedSeaseon).addClass("open");
		}
		
		return false;
	});
	/*/toggle seasons*/

	
	/*voting*/
	$('div.star-rating').livequery('click', function(event) { 
		doVote($(this),event);
		return false;
    });
	/*/voting*/
			   	

	/*add to playlist*/
	$("a.playlist").livequery('click', function(event) { 
		showPlaylistMessage($(this),event);
		//addToPlaylist($(this),event);
		return false;
    });
      /*add to playlist*/
  $("a.playlist-direct").livequery('click', function(event) { 
    addToPlaylist($(this),event);
    return false;
    });
	$("a.add-to-playlist").click(function(event){
		$("div.playlistbox").css({'display' : 'none'});
		addToPlaylist($(this),event);
		return false;
    });
	/*/add to playlist*/
			   	
	
	/*show long info about clip with delay*/
	var timeoutObj;
	$('li.clip').livequery(function(){ 
        $(this).hover(function() { 
				var infoObj = $(this);
				timeoutObj = setTimeout(function() { 
					infoObj.css({'z-index' : '300'});
					infoObj.find("div.long-info").fadeIn("slow");
				}, 0);
            }, function() { 
				clearTimeout(timeoutObj);
				$(this).css({'z-index' : '100'});
                $(this).find("div.long-info").hide();
            }); 
    }); 
	/*/show long info about clip with delay*/
	

	/*hover class on clips*/
	$('li.clip').livequery(function(){ 
        $(this).hover(function() { 
				$(this).addClass("hover");
            }, function() { 
				$(this).removeClass("hover");
           }); 
    }); 
	/*/hover class on clips*/
	

	/* paging clips */
	$("a.paging.next").livequery("click", function(event) { 
		var link = $(this);
		var container = link.parent();
		
		var page = parseInt(container.find(".current-page").text());
		var totpages = parseInt(container.find(".tot-pages").text());
		
		var fullwidthMargin = 956;
		var fullwidth = 956;
		var narrow = 712;
		var narrowMargin = 712;
		var pagesNarrow = 4;
		var pagesWide = 5;
		
		var margin = 0;
		var width = 0;
		var pages = 0;
		
		if($(container).next().hasClass("narrow")) { 
			margin = narrowMargin;
			width = narrow;
			pages = pagesNarrow;
		}
		else {
			margin = fullwidth;
			width = fullwidthMargin;
			pages = pagesWide;
		}

		if (page == totpages) {
			link.addClass("disabled");
			return false;
		}
		
		$(container).find("a.paging.previous").removeClass("disabled");
		
		if (page < totpages && !link.hasClass("disabled") ) {
			page++;
			
			var block = container.parent().find(".appendTo");
			
				//tabellen
				if(block.size()==0) {
					block = container.parent().parent().find(".appendTo");
					var current=block.find("tbody.inView");
					
					//Om inte data finns p� n�sta - h�mta data
					if(current.next().size()==0) {
						
						
						
						block.animate({ 
							marginLeft: "-970px"
							}, 300, function(){
								$.get(link.attr("href")+page, function(data){
									block.animate({opacity: 0}, 0)
									block.append(data);
									block.css("margin-left",0);
									
									current.next().addClass("inView");
									current.removeClass("inView");
									current.hide();
									block.animate({opacity: 1.0}, 500)
									
									$('input.star').rating(); 

									if (page == totpages) {
										link.addClass("disabled") 
									}
							});				

						});
					}
					else { //data finns p� n�sta - bara �kning
					
				
					
						block.animate({ 
							marginLeft: "-970px"
							}, 300, function(){
								
									block.animate({opacity: 0}, 0)
									block.css("margin-left",0);
									current.next().addClass("inView");
									current.removeClass("inView");
									current.hide();
									current.next().show();
									block.animate({opacity: 1.0}, 500)
									
									$('input.star').rating();

									if (page == totpages) {
										link.addClass("disabled") 
									}
							});	
					}
				}
				//listorna 
				else {
					//Om inte data finns p� n�sta - h�mta data
					var nrOfItems = container.parent().find("div.clips-list-container ul li").size();
					if( nrOfItems < page*pages && nrOfItems % pages == 0 ) {
						block.animate({ 
						marginLeft: "-"+margin*(page-1)+"px"
						}, 300, function(){
							$.get(link.attr("href")+page, function(data) {
								if(container.parent().find("div.clips-list-container ul li").size() < page*pages) {
									block.hide();
									block.append(data);
									$(block).css("width",width*page);
									block.fadeIn("slow");
									$('input.star').rating(); 
								}
								if (page == totpages) {
									link.addClass("disabled") 
								}
							});						
						});
						
					}
					 //data finns p� n�sta - bara �kning
					else {
						block.animate({ 
						marginLeft: "-"+margin*(page-1)+"px"
						}, 300, function(){
								if(container.parent().find("div.clips-list-container ul li").size() < page*pages) {
									block.hide();
									$(block).css("width",width*page);
									block.fadeIn("slow");
									$('input.star').rating(); 
								}
								if (page == totpages) {
									link.addClass("disabled") 
								}
						});	
					}
				}
				container.find(".current-page").text(page);
			}
			return false;
		});
	
	$("a.paging.previous").livequery("click", function(event) { 
			
		var link = $(this);
		var container = link.parent();	
										  
		var fullwidthMargin = 956;
		var narrowMargin = 712;
		var margin = 0;

		if($(container).next().hasClass("narrow")) {
			margin = narrowMargin;
		}
		else {
			margin = fullwidthMargin;
		}										  
						
		var page = parseInt(container.find(".current-page").text());
		
		var totpages = parseInt(container.find(".tot-pages").text());
		
		if (page == 1) {
			link.addClass("disabled");
			return false;
		}
		$(container).find("a.paging.next").removeClass("disabled");
		
		var block = container.parent().find(".appendTo");
			
		if(block.size()==0) {
			if (page > 1) {
				page--;
			
				block = container.parent().parent().find(".appendTo");
			
				block.animate({ marginLeft:  970}, 300, function(){
					var current=block.find("tbody.inView");
					current.removeClass("inView");	
					block.css("margin-left",0);
					current.prev().addClass("inView");
					current.prev().fadeIn("slow");
					current.hide();
					
				});
				container.find(".current-page").text(page);
			}
		}
		else {				
			if (page > 1) {
				page--;
				var block = container.parent().find("div.clips-list-container ul");
				var currentMarginLeft = parseFloat($(block).css("margin-left"));
				block.animate({ marginLeft:  currentMarginLeft+margin}, 300);
				container.find(".current-page").text(page);
			}
		}
		if (page == 1) {
			link.addClass("disabled") 
		}
		return false;
	});
	/* /paging clips */

	/* sorting clips */
	$("a.sort-link").livequery("click", function(event) { 
		var link = $(this);
		var linkList = link.parent().parent();
		var container = link.parent().parent().parent().parent();	
		
		linkList.find("a.selected").removeClass("selected");
		link.addClass("selected");

		var block = container.find("ul.clips");
		block.css("margin-left",-1000);
		$.get(link.attr("href"), function(data){
			block.html(data);
			block.css("margin-left",0);
			block.fadeIn("fast");
			$('input.star').rating(); 
		});
		/* reset current-page when sorting */
		container.find("span.current-page").text("1");
		/* need to change the sortby in next/prev links */
		var sortby = getQueryStringValue(link.attr("href"),"sortby");
		var prevlink = container.find("div.paging-links a.previous");
		prevlink.attr({href: replaceQueryStringValue(prevlink.attr("href"),"sortby",sortby)});
		var nextlink = container.find("div.paging-links a.next");
		nextlink.attr({href: replaceQueryStringValue(nextlink.attr("href"),"sortby",sortby)});

		return false;
	});
	/* /sorting clips */
	
	/* change season clips */
	$("select.season").livequery("change", function(event) { 
		var url = $(this).val();
		var container = $(this).parent().parent().parent();

		var block = container.find("ul.clips");
		block.css("margin-left",-1000);
		$.get(url, function(data){
			container.html(data);
			container.fadeIn("fast");
			$('input.star').rating(); 
		});
	});
	/* /change season clips */

	
	$("a.overlay-close").click(function(){
		$("div.login").css({'display' : 'none'});
		$("div.messagebox").css({'display' : 'none'});
		$("div.playlistbox").css({'display' : 'none'});
		
		$("div.messagebox .message").html("");
		return false;
	});
	

	/* empty searchfield from "Ange s�kord" */
	$("input.search").focus(function(){
		var input = $(this);
		input.select();
		if (input.val()==$.i18n._('Enter keyword'))
			input.attr("value",""); 
	});
	/* /empty searchfield from "Ange s�kord" */
	
	
	$("a.show-long").click(function(){
	$(this).parent().parent().find(".long-desc").toggle("fast");
	
	//	$(this).parent().hide("fast", function() { $(this).parent().parent().find(".long-desc").show("fast") });	
	
		return false;
	});

	/*general hover on table rows where table has class hover*/
	$("table.hover tbody tr").livequery(function(){ 
        $(this) 
            .hover(function() { 
                $(this).addClass("tr-hover"); 
				$(this).find("a.mover").removeClass("display-none");
            }, function() { 
                $(this).removeClass("tr-hover"); 
				$(this).find("a.mover").addClass("display-none");
            }); 
    }, function() { 
        $(this) 
            .unbind('mouseover') 
            .unbind('mouseout'); 
    });
	/*/general hover on table rows*/

	/*general class clickable that finds first link and redirects to that url*/
	$('.clickable').livequery('click', function(event) { 
		window.location = $(this).find("a:first").attr("href");
    });
	/*/general class clickable*/

	/*general class clickable that with status, title & hover*/
	$('.clickable').livequery(function(){ 
        $(this).hover(function() { 
				window.status = $(this).find("a:first").attr("href");
				$(this).attr("title",$(this).find("a:first").attr("title"));
				$(this).addClass("hover");
            }, function() { 
				$(this).removeClass("hover");
            }); 
    }); 
	/*/general class clickable*/

	/*general class hover-this that adds class hover on hover*/
	$(".hover-this").livequery(function(){ 
        $(this).hover(function() { 
				$(this).addClass("hover");
            }, function() { 
				$(this).removeClass("hover");
           }); 
    }); 
	/*/general class hover-this that adds class hover on hover*/
	
	/*set clipboard with code from input text*/
	if ($("input.copy-text").length) {
		$.clipboardReady(function(){
			$("input.copy-text").click(function(){
				$("input.code").select();
				$.clipboard($("input.code").val());
				return false;
			});
		}, { swfpath: "/gui/js/jquery.clipboard.swf", debug: true } );
	}
	/*/set clipboard with code from input text*/
	
	/*autocomplete*/
	//will add ?q=[entered characters] to URL
	$("#search").autocomplete(
		/*$("form[id=search_form]").attr('action'),*/
		$("#tmp_search_url").html(),
		{
			delay:10,
			minChars:3,
			matchSubset:1,
			matchContains:1,
			cacheLength:10,
			onItemSelect:selectItem,
			onFindValue:findValue,
			formatItem:formatItem,
			width:280,
			selectFirst:true,
			autoFill:false
		}
	);
	
	$("#search2").autocomplete(
		"ajax-data/autocomplete-data.txt",
		{
			delay:10,
			minChars:3,
			matchSubset:1,
			matchContains:1,
			cacheLength:10,
			onItemSelect:selectItem,
			onFindValue:findValue,
			formatItem:formatItem,
			width:280,
			autoFill:false
		}
	);
	/*/autocomplete*/

});


function doVote(linkObj,e) {
	//get the form
	var p = $(linkObj).parent().parent().parent();
	
	//clicked star value
	var voted = $(linkObj).find("a").text();
	
	$.get(p.attr("action")+voted, function(data){
		var arr = data.split("|");							 
		if (arr[0] != "true") {
			showLogin(linkObj,e);
		}
		else {
			showMessage(linkObj,e, arr[2]);
		}
		$($(p).find('input')).rating('select',arr[1]) 
	});
}


function addToPlaylist(linkObj,e) {
	$.get($(linkObj).attr("href"), function(data){
		var arr = data.split("|");							 
		if (arr[0] != "true") {
			showLogin(linkObj,e);
		}
		else {
			showMessage(linkObj,e, arr[1]);
			$(linkObj).addClass("added");
		}
	});
}


function toggleUpDownArrows(e,f) {
	
	$("#scroll-up").addClass("display-none");
	$("#scroll-down").addClass("display-none");
	
	var listBottom = e;
	var listTop = f;
	
	var guideTop = $("#tv-guide").offset().top;
	var guideBottom = guideTop+365;

	if(guideTop>listTop) { $("#scroll-up").removeClass("display-none"); }
	if(guideBottom<listBottom) { $("#scroll-down").removeClass("display-none"); }
}


function showPlaylistMessage(linkObj,e, data) {
	//need to set clip id
	var clipid = getQueryStringValue($(linkObj).attr("href"),"vid");
	//replace clipid on links in box
	$("div.playlistbox a.add").attr("href",replaceQueryStringValue($("div.playlistbox a.add").attr("href"),"vid",clipid));
	$("div.playlistbox a.add-subscribe").attr("href",replaceQueryStringValue($("div.playlistbox a.add-subscribe").attr("href"),"vid",clipid));
	var offset=-20;
	$("div.playlistbox").css({'display' : 'block','left' : e.pageX-$("body").attr("offsetLeft")+offset,'top' : e.pageY});
}


function showLogin(linkObj,e) {
	var offset=-20;
	if($(linkObj).parents("li.clickable").hasClass("last")) {
		offset=-200;
	}
	$("div.login").css({'display' : 'block','left' : e.pageX-$("body").attr("offsetLeft")+offset,'top' : e.pageY});
}


function showMessage(linkObj,e, data) {
	var offset=-20;
	$("div.messagebox .message").append("<p>"+ data +"</p>");
	$("div.messagebox").css({'display' : 'block','left' : e.pageX-$("body").attr("offsetLeft")+offset,'top' : e.pageY});
}


function doAnimate(linkObj,e) {
	var offset=-20;
	if($(linkObj).parents("li.clickable").hasClass("last")) {
		offset=-200;
	}
	$("div.login").css({'display' : 'block','left' : e.pageX-$("body").attr("offsetLeft")+offset,'top' : e.pageY});
}

/* show info/descr of clips */
function showInfo(infoObj) {
	infoObj.parent().css({'z-index' : '300'});
	infoObj.find("div.long-info").fadeIn("slow");
}

/*returnerar datum/dag i olika format*/
function getFormatedDate(theDate,nextOrPrev,format) { 
	var d = theDate;
	var shortDayName = new Array($.i18n._('Sun'), $.i18n._('Mon'), $.i18n._('Tue'), $.i18n._('Wed'), $.i18n._('Thu'), $.i18n._('Fri'), $.i18n._('Sat'));
	var dateArr = d.split("-");	
	var formatedDate;
	//to remove string "date" from the date
	if (dateArr[0].indexOf("date")==0) {
		dateArr[0] = dateArr[0].substring(4, dateArr[0].length);
	}
	var newDate = new Date(dateArr[0], (dateArr[1])-1, dateArr[2]);
	newDate.setDate(newDate.getDate() + nextOrPrev);

	var year = newDate.getFullYear();
	var month = newDate.getMonth()+1;
	var day = newDate.getDate();
	
	if(day<10) day = "0" + day
  	if(month<10) month= "0" + month 

	if(format == "full") {
		formatedDate = year + "-" + month + "-" + day ;
	}
	else if (format == "short") {
		formatedDate = day + "/" + month;
	}
	else if (format == "dayOnly") {
		newDate = new Date(year, month-1, day);
		formatedDate = shortDayName[newDate.getDay()];
	}
	return formatedDate;
}

/* takes an url with querystring and replaces a parameter with new value */
function replaceQueryStringValue(url,param,value) {
    var re = new RegExp("([?|&])" + param + "=.*?(&|$)","i");
    if (url.match(re))
        return url.replace(re,'$1' + param + "=" + value + '$2');
    else
        return url + '&' + param + "=" + value;
}	

/* gets a value from querystring from url and parameter name */
function getQueryStringValue(url,param) {
  param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+param+"=([^&#]*)");
  var qs = regex.exec(url);
  if(qs == null)
    return "";
  else
    return qs[1];
} 

/* dims page, to be called from flashplayer */
function dimPage(){
	var dimLayer = $("#dim-layer");
	if (dimLayer.attr("class")=="display-none") {
		$("#flash-container").css({'z-index' : '101'});
		dimLayer.removeClass("display-none");
	} else {
		$("#flash-container").css({'z-index' : '0'});
		dimLayer.addClass("display-none");
	}
}

/*autocomplete help functions*/
function findValue(li) {
	if( li == null ) return alert("No match!");
	if( !!li.extra ) var sValue = li.extra[0];
	//goto URL
	window.location = sValue;
}
function selectItem(li) {
	findValue(li);
}
function formatItem(row) {
	return row[0];
}
function lookupAjax(){
	var oSuggest = $("#CityAjax")[0].autocompleter;
	oSuggest.findValue();
	return false;
}
/*/autocomplete help functions*/

/* widget-generator */
$(".widget.generator :input").change(function() {	
	widgetGeneratorUpdate();
});

function widgetGeneratorUpdate()
{	
	var widgetInput = {}
	
	// read some values that exists in hidden fields
	var isLoggedIn = $('#widget_user').length;
	widgetInput['affiliate'] = $('#widget_affiliate').val();
	widgetInput['country'] = $('#widget_country').val();
	widgetInput['logos'] = $('#widget_logos').val();
	
	// formats select box can have ids to formats
	// or string rss links to personal playlists
	var playlistSelected;
	if(isNaN($('#formats').val())) { playlistSelected = true; }
	else playlistSelected = false;
	
	// set format title on the page
	$('#formatTitle').html($('#formats :selected').text());
	
	// amount of clips to show
	var amount = $('.widget .Tumnaglar:checked').val();
	
	// rss links to pass to widget depends on
	// if user is logged in
	var user_rss = '';
	
	/*
	if(isLoggedIn && playlistSelected == true) {
		
	}
	else if(isLoggedIn) {
		
	}
	*/
	
	if(isLoggedIn) {
		
		// 
		user_rss = $('#widget_user').val();

		// if the user has chosen a user-specific rss
		// e.g. "viewed" or "not viewed", the three
		// general rss, e.g. "recently added", should be without fid.
		// also disable the "sort by" menu
		if(isNaN($('#formats').val()))
		{
			// formats select was not numeric
			// it was thus a playlist rss link
			
			$('#sort').attr('disabled', true);
			
			// create rss links
			
			var playlist = $('#formats').val();	
			
			var rss = '';
			var counter = 1;
			
			// add the sorton rss links
			$('#sort').find("option").each(function() {
				rss += "&rss_"+ counter +"="+$(this).text()+"]["+$(this).val();
				counter++;
		    });

			// add the profile specific rss links
			// by looping all formats options and adding
			// only the ones that are not numeric.
			// not numeric means that it is a rss link.
			$('#formats').find("option").each(function() {
				// add if rss link and not the selected one
				if(isNaN($(this).val()) && playlist!=$(this).val()) {
					rss += "&rss_"+ counter +"="+ user_rss + $(this).text()+"]["+$(this).val();
					counter++;
				}
			});
			
			// add the selected rss as last
			rss += "&rss_"+ counter +"="+ user_rss + $('#formats :selected').text()+"]["+playlist;
		}
		else
		{
			// formats was numeric, a format id 
			// was chosen.
			
			$('#sort').attr('disabled', false);
			
			// rss links
			var formatId =  $('#formats').val();	
			
			var rss = '';
			var counter = 1;
			
			// add the sorton rss links
			$('#sort').find("option").each(function() {
				// only get not selected options
				if($('#sort').val()!=$(this).val()) {
					rss += "&rss_"+ counter +"="+$(this).text()+"]["+$(this).val();
					rss += '%3Ffid%3D'+ formatId;
					counter++;
				}
		    });
			
			// add the profile specific rss links
			$('#formats').find("option").each(function() {
				// add if rss link
				if(isNaN($(this).val())) {
					rss += "&rss_"+ counter +"="+ user_rss + $(this).text()+"]["+$(this).val();
					counter++;
				}
			});
			
			// add the selected rss as last
			rss += "&rss_"+ counter +"="+$('#sort :selected').text()+"]["+$('#sort').val();
			rss += '%3Ffid%3D'+ formatId;	
		}
	
	}
	else
	{
		// not a logged in user 
		
		$('#sort').attr('disabled', false);
		
		// rss links
		var formatId =  $('#formats').val();	
		
		var rss = '';
		var counter = 1;
		
		// add the sorton rss links
		$('#sort').find("option").each(function() {
			// only get not selected options
			if($('#sort').val()!=$(this).val()) {
				rss += "&rss_"+ counter +"="+$(this).text()+"]["+$(this).val();
				rss += '%3Ffid%3D'+ formatId;
				counter++;
			}
	    });
		
		// add the selected rss as last
		rss += "&rss_"+ counter +"="+$('#sort :selected').text()+"]["+$('#sort').val();
		rss += '%3Ffid%3D'+ formatId;	
	}

	// vertical widget
	if($('.widget .Orientering:checked').val() == 1) { 
		
		widgetInput['width'] = 190;
		widgetInput['height'] = 100 + 160 * amount;
		
		if(isLoggedIn) { widgetInput['height'] += 40; }
	}
	// horizontal widget
	else {

		widgetInput['width'] = 190 * amount;
		widgetInput['height'] = 208;
		
		// note: if amount is 1, the pager etc
		// is placed below the clips in widget;
		// height must thus the be increased
		if(amount==1) { widgetInput['height']+=50; }
		
		if(amount==1 && isLoggedIn) { widgetInput['height']+=40; }
	}
	
	if($('.widget .Farg:checked').val() == 1) { 
		widgetInput['theme'] = 'white';
	}
	else { 
		widgetInput['theme'] = 'grey';
	}
	
	// channel logos
	rss += '&logos=' + widgetInput['logos'];
	
	//var embedCode = '<object width="'+ widgetInput['width'] +'" height="'+ widgetInput['height'] +'"><param name="movie" value="http://flvplayer.static.vss.viasat.tv/play/swf/widget_web.swf?affiliate=2se&country=se&theme='+widgetInput['theme']+'&rss_1=Recommended shows][http://flvplayer.static.vss.viasat.tv/play/rekommenderat.rss&rss_2=Top shows][http://flvplayer.static.vss.viasat.tv/play/topplistan.rss"></param></param><param name="allowscriptaccess" value="always"></param><embed src="http://flvplayer.static.vss.viasat.tv/play/swf/widget_web.swf?affiliate=2se&country=se&theme='+widgetInput['theme']+'&rss_1=Recommended shows][http://flvplayer.static.vss.viasat.tv/play/rekommenderat.rss&rss_2=Top shows][http://flvplayer.static.vss.viasat.tv/play/topplistan.rss" type="application/x-shockwave-flash" allowscriptaccess="always"  width="'+widgetInput['width']+'" height="'+widgetInput['height']+'"></embed></object>';
	
	var embedCode = '<object width="'+ widgetInput['width'] +'" height="'+ widgetInput['height'] +'"><param name="movie" value="http://flvplayer.viastream.viasat.tv/flvplayer/play/swf/widget_web.swf?affiliate='+ widgetInput['affiliate'] +'&country='+ widgetInput['country'] +'&theme='+widgetInput['theme'] + rss +'"></param></param><param name="allowscriptaccess" value="always"></param><embed src="http://flvplayer.viastream.viasat.tv/flvplayer/play/swf/widget_web.swf?affiliate='+ widgetInput['affiliate'] +'&country='+ widgetInput['country'] +'&theme='+widgetInput['theme']+ rss +'" type="application/x-shockwave-flash" allowscriptaccess="always"  width="'+widgetInput['width']+'" height="'+widgetInput['height']+'"></embed></object>';
	
	$(".widget #code").val(embedCode);
	
	$("#widget_administration_preview").html(embedCode);
}

// if we are on the widget generator page, update generator
if($(".widget.generator :input").length) { widgetGeneratorUpdate(); }

// desktop widget administration
$(".widget.desktop #types").change(function() {	   
	var type =  $('.widget.desktop #types').val();
	
	$('.widget.desktop #types').find("option").each(function() {
		if(type!=$(this).val()) {
			$('.widget.desktop.'+$(this).val()).hide();
			$('.widget.step1.desktop img.'+$(this).val()).hide();
		}
		else {
			$(".widget.desktop."+type).show();
			$('.widget.step1.desktop img.'+$(this).val()).show();
		}
	});
});

/*/widget-generator */

/* Simple select all function */
function GeneralSelectAll(id)
{
    document.getElementById(id).focus();
    document.getElementById(id).select();
}