$(window).load(function(){
	Helpers.resize();
	//hide iphone location
	setTimeout(function(){window.scrollTo(0, 1);}, 100);
});
$(window).resize(function(){
	Helpers.resize();
});

$.ajaxSetup({
	type: 'GET',
	dataType: 'xml',
	timeout: 10000,
	cache: false
});	
	

var SECURITY_ERROR = "Sorry there was an error connecting to the server or your session has expired, please refresh the page.";
var REQUEST_ERROR = "Sorry there was an error processing this request, please try again.";
var REQUEST_PARAMETER ="You are missing a required parameter.";

var Helpers = {
	help : function(m){
		alert(m);
	},
	resize: function(){
  	$(".scale_16_9").each(function(i){
   		$(this).height($(this).width()*9/16);
		});	
	},

	subcategory: function(s){
		$("#channelEditSubCategory").empty();
		var o = $("<option>").text("Sub-Category").appendTo($("#channelEditSubCategory"));
		if(s==""){
			o.attr("seleted","selected");
		}

		var v = $("#channelEditCategory").val();
		var t = $("#channelEditCategory option:selected").text();
		if(v==null || v==""){
			$("#channelEditSubCategory").attr("disabled","disabled");
		}else{
			$("#channelEditSubCategory").removeAttr("disabled");
			$.each(v.split(","),function(){
				var o = $("<option>").text(this+"").appendTo($("#channelEditSubCategory"));
				if(s==this+""){
					o.attr("selected","selected");
				}
			});
		}
	},
	
	upload: function(success){
		$(".videoUploadProgress").hide();
		$("#videoUploadData").val("");
		$("#videoUploadForm").show();
		if(success==false){
			alert("There was a problem with the upload or it was cancelled, please try again.");
		}
	}

};

var Support = {
	send : function(){
		$.ajax({
			url: '/api/support',
			type: 'POST',
			data: {
				email:$.trim($("#supportEmail").val()),
				copy:($("#supportCopy").attr("checked")==true?"True":"False"),
				message:$.trim($("#supportMessage").val()),
				subject:$.trim($("#supportSubject").val())
			},
			success: function(xml){
				$("#supportEmail").val("");
				$("#supportMessage").val("");
				alert("Message Sent!");
			},					
			error: function (XMLHttpRequest, textStatus, errorThrown){
				if(XMLHttpRequest.status==400){
					alert(REQUEST_PARAMETER);
				}else{
					alert(REQUEST_ERROR);
				}
			}
		});		
	}
};


var Account = {
	ready:true,
	logout: "/",
	init: function(){//this is used to init the admin interface
		$.ajax({
			url: '/api/account',
			error: function (XMLHttpRequest, textStatus, errorThrown){
				alert(SECURITY_ERROR);//XMLHttpRequest.status
				document.location=Account.logout;
			},
			success: function(xml){
				$.timer(30000,Account.get);
				Account.update(xml);
				Station.get();

				$("#accountPlayer").attr("href","/"+$(xml).find("response").attr("id"));
			}
		});	
	},
	get : function(){
		$.ajax({
			url: '/api/account',
			error: function (XMLHttpRequest, textStatus, errorThrown){
				if(XMLHttpRequest.status==401){
					document.location=Account.logout;
				}
			},
			success: function(xml){
				Account.update(xml);
				Station.check();
			}
		});	
	},
	update : function(xml){
		$("body").data("credits",parseInt($(xml).find("response").attr("credits")));
		$("body").data("network",$(xml).find("response").attr("network"));
	
		$("b[name='account_balance']").text(parseInt($(xml).find("response").attr("credits")));
		$("body").attr("id",$(xml).find("response").attr("id"));
		$("body").attr("title",$(xml).find("response").attr("title"));
		if($(xml).find("response").attr("network")=="True"){
			$("b[name='account_type']").text("network");
		}else{
			$("b[name='account_type']").text("studio");
		}		
		$("#accountCreditWarning").val($(xml).find("response").attr("warn"));			
		$("#accountOverlayPosition option:selected").removeAttr("selected");		
		$("#accountOverlayPosition option[value='"+$(xml).find("response").attr("overlay")+"']").attr("selected","selected");
		Station.check();
		Channel.check();
		Video.check();
	},
	select : function(typ){
		if(Account.ready){
			Account.ready=false;
			if($('#accountOverview').is(":visible")){
				$('#accountOverview').slideUp('fast',function(){Account.show(typ);});
			}else if($('#accountEdit').is(":visible")){
				$('#accountEdit').slideUp('fast',function(){Account.show(typ);});
			}else if($('#accountCredits').is(":visible")){
				$('#accountCredits').slideUp('fast',function(){Account.show(typ);});
			}else{
				Account.show(typ);
			}			
		}
	},
	show : function(typ){
		switch(typ){
		case "accountOverview":
			$("#accountTitle").text("Overview");
			$("#"+typ).slideDown('fast',function(){Account.ready=true;})
			break;
		case "accountCredits":
			$("#accountTitle").text("Credits");
			$("#"+typ).slideDown('fast',function(){Account.ready=true;})
			break;
		case "accountEdit":
			$("#accountTitle").text("Configure");
			$.ajax({
				url: '/api/account',
				data: {},
				error: function (XMLHttpRequest, textStatus, errorThrown){
					Account.ready=true;
					alert(REQUEST_ERROR);
				},
				success: function(xml){
					Account.update(xml);					
					$("#"+typ).slideDown('fast',function(){Account.ready=true;});					
				}
			});	
			
			break;
		default:
			Account.ready=true;	
		}
	},
	save : function(){
		$.ajax({
			url: '/api/account',
			type: 'POST',
			data: {
				overlay_position:$("#accountOverlayPosition").val(),
				warn:$("#accountCreditWarning").val()
			},
			success: function(xml){
				Account.select("accountEdit");
			},					
			error: function (XMLHttpRequest, textStatus, errorThrown){
				if(XMLHttpRequest.status==400){
					alert(REQUEST_PARAMETER);
				}else{
					alert(REQUEST_ERROR);
				}
			}
		});		
	},
	creditCost:0.027,
	calculatePayment : function(fromCredits){
		if(isNaN(parseInt($("#accountCreditsQuantity").val()))){$("#accountCreditsQuantity").val(0)}
		if(isNaN(parseFloat($("#accountCreditsAmount").val()))){$("#accountCreditsAmount").val(0)}

		if(fromCredits){
			$("#accountCreditsQuantity").val($.format('{a:d}', {a:$("#accountCreditsQuantity").val()}));
			$("#accountCreditsAmount").val($.format('{a:.2f}', {a:(parseInt($("#accountCreditsQuantity").val())*Account.creditCost)+0.00001}));
		}else{
			$("#accountCreditsAmount").val($.format('{a:0.2f}', {a:$("#accountCreditsAmount").val()}));
			$("#accountCreditsQuantity").val($.format('{a:d}', {a:(parseFloat($("#accountCreditsAmount").val())/Account.creditCost)}));
		}
	},
	doPayment : function(){
		if(isNaN(parseFloat($("#accountCreditsAmount").val()))){$("#accountCreditsAmount").val(0)}
		if(parseFloat($("#accountCreditsAmount").val())<10.00){
			alert("There is a minimum credit purchase of $10.00");
		}else{
			document.location="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=admin@sayitrightmedia.com&item_name=SayitRight.tv%20Credits&currency_code=USD&shipping=0.00&handling=0.00&notify_url=http://www.sayitright.tv/payment/paypal&return=http://www.sayitright.tv/publish&rm=0&cancel_return=http://www.sayitright.tv/publish&custom="+$("body").attr("id")+"&amount="+$("#accountCreditsAmount").val();
		}
		return false;
	}
};

var Advert = {
	toggle_ready:true,
	toggle : function(obj){
		if(Advert.toggle_ready){
			Advert.toggle_ready=false;
			Advert.get();
			$('#advertPage').slideToggle('slow',function(){
				Advert.toggle_ready=true;
				$.scrollTo('#advertPage', 500, {offset:-46});						
			});
			Helpers.resize();
			$(obj).toggleClass('open');
		}
	},
	get : function(){
	}
};

var Station = {
	toggle_ready:true,
	check : function(){
		if($("body").data("network")=="True"){
			$("#stationUpgrade").hide();
			if($("body").data("credits")<50000){
				$("#stationCredit").show();
				$("#stationAdd").hide();
			}else{
				$("#stationCredit").hide();
				$("#stationAdd").show();
			}
		}else{
			$("#stationUpgrade").show();
			$("#stationCredit").hide();
			$("#stationAdd").hide();
		}	
	},
	toggle : function(obj){
		Station.check();
	
		if(Station.toggle_ready){
			Station.toggle_ready=false;
			Station.get();
			$('#stationPage').slideToggle('slow',function(){
				Station.toggle_ready=true;
				$.scrollTo('#stationPage', 500, {offset:-46});						
			});
			Helpers.resize();
			$(obj).toggleClass('open');
		}
	},
	select : function(obj,typ){
		if($(obj).children(0).hasClass("close") || typ!=""){
			if($("#stationList span[class='open']").length>0){
				$("#stationList span[class='open']").parent().next().slideUp('fast',function(){Station.show(obj,typ);});
			}else{
				Station.show(obj,typ);
			}
		}else{
			$(obj).next().slideUp('fast');
			$(obj).children(0).addClass('close').removeClass('open');		
		}
	},
	show : function(obj,typ){
		$("#stationList span[class='open']").addClass('close').removeClass('open');			
		$("#stationEdit").appendTo($("#hidden"));
		$("#stationInfo").appendTo($("#hidden"));
		
		switch(typ){
		case "edit":
			$.ajax({
				url: '/api/station',
				data: {key:$(obj).next().data("station")},
				success: function(xml){
					Station.edit(xml);
					$(obj).next().empty().append($("#stationEdit"));
					$(obj).next().slideDown('fast');
					$(obj).children(0).addClass('open').removeClass('close');	
				},					
				error: function (XMLHttpRequest, textStatus, errorThrown){
					Station.select(obj,"info");
					alert(REQUEST_ERROR);
				}
			});
			
			break;
		default:
			$("#stationInfoLink").val("http://www.sayitright.tv/" + $(obj).next().data("station"));
			$("#stationInfoScript").val('<script src="http://www.sayitright.tv/scripts/player/'+$("body").attr("id")+'.js" type="text/javascript"></script>');
			$("#stationInfoPlay").val('<a href="http://www.sayitright.tv/'+$(obj).next().data("station")+'" onclick="return Sir.play(\''+$(obj).next().data("station")+'\');">Play</a>');
			$("#stationInfoFrame").val('<div id="sir_frame" title="'+$(obj).next().data("station")+'"></div>');
		
			$(obj).next().empty().append($("#stationInfo"));
			$(obj).next().slideDown('fast');
			$(obj).children(0).addClass('open').removeClass('close');	
		}
	},
	empty : function(){
		$("#stationEdit").appendTo($("#hidden"));
		$("#stationInfo").appendTo($("#hidden"));
		$("#stationList").empty();	
		
		var dt 		= $('<dt>').appendTo('#stationList');
		var span 	= $('<span />').attr('class','loading_icon').text("Loading").appendTo(dt);
		var dd		= $('<dd>').attr('style','display:none').appendTo('#stationList');
	},
	list : function(xml){
		$("#stationList").empty();
		$("#channelInfoStation").empty();
		$("#videoInfoStation").empty();


		//account station
		var dt 		= $('<dt>').appendTo('#stationList');
		var span 	= $('<span />').attr('class','close').text($('body').attr('title')).appendTo(dt).click(function(){Station.select($(this).parent(),"")});
		var img		= $('<img>').attr('src','/static/images/option_info.png').appendTo(dt).click(function(){Station.select($(this).parent(),"info");}).attr("title","Station Info");
		var img		= $('<img>').attr('src','/static/images/option_edit.png').appendTo(dt).click(function(){Station.select($(this).parent(),"edit")}).attr("title","Edit Station");
		var img		= $('<img>').attr('src','/static/images/option_link.png').appendTo(dt).click(function(){window.open("/"+$('body').attr("id"))}).attr("title","View Station");

		var dd		= $('<dd>').attr('class','station_item').attr('style','display:none').attr('id','station_'+$('body').attr("id")).data('station',$('body').attr("id")).appendTo('#stationList');

		//channel info
		$("<option>").text($('body').attr('title')).val($('body').attr("id")).attr("seleted","selected").appendTo($("#channelInfoStation"));
		//video info
		$("<option>").text($('body').attr('title')).val($('body').attr("id")).attr("seleted","selected").appendTo($("#videoInfoStation"));

		
		$(xml).find("response station").each(function(){
			var dt 		= $('<dt>').appendTo('#stationList');
			var span 	= $('<span />').attr('class','close').text($(this).find("title").text()).appendTo(dt).click(function(){Station.select($(this).parent(),"")});
			var img		= $('<img>').attr('src','/static/images/option_info.png').appendTo(dt).click(function(){Station.select($(this).parent(),"info");}).attr("title","Station Info");
			var img		= $('<img>').attr('src','/static/images/option_edit.png').appendTo(dt).click(function(){Station.select($(this).parent(),"edit")}).attr("title","Edit Station");
			var img		= $('<img>').attr('src','/static/images/option_link.png').appendTo(dt).click(function(){window.open("/"+$($(this).parent()).next().data("station"))}).attr("title","View Station");

			var dd		= $('<dd>').attr('class','station_item').attr('style','display:none').attr('id','station_'+$(this).attr("key")).data('station',$(this).attr("key")).appendTo('#stationList');
			
			//channel info		
			$("<option>").text($(this).find("title").text()).val($(this).attr("key")).appendTo($("#channelInfoStation"));
			//video info		
			$("<option>").text($(this).find("title").text()).val($(this).attr("key")).appendTo($("#videoInfoStation"));

		});	
	},
	get : function(){
		Station.empty();		
		$.ajax({
			url: '/api/station',
			success: function(xml){
				Station.list(xml);
			},					
			error: function (XMLHttpRequest, textStatus, errorThrown){
				alert(REQUEST_ERROR);
			}
		});	
	},
	create : function(t){
		if(confirm("This will cost 50000 credits, are you sure you wish to continue?")){
			Station.empty();
			$.ajax({
				url: '/api/station',
				type: 'POST',
				data: {
					title:$.trim(t),
					account:$("body").attr("id")
				},
				success: function(xml){
					Account.get();
					Station.list(xml);
				},					
				error: function (XMLHttpRequest, textStatus, errorThrown){
					alert(REQUEST_ERROR);
				}
			});	
		}
	},

	edit : function(xml){
		$("#stationEditTitle").val($(xml).find("title").text());
		$("#stationEditDescription").val($(xml).find("description").text());
		$("#stationEditDate").val($(xml).find("response").attr("date"));
		$("#stationEditTags").val($(xml).find("tags").text());
		
		$("#stationEditStationFilter").val($(xml).find("stations").text());
		$("#stationEditChannelFilter").val($(xml).find("channels").text());
	
		$("#stationEditPlayerBackground").val($(xml).find("style").text());
		$("#stationEditPlayerMinWidth").val($(xml).find("style").attr("width"));
		$("#stationEditPlayerMinHeight").val($(xml).find("style").attr("height"));
		$("#stationEditPlayerSpacing").val($(xml).find("style").attr("space"));
	
		$("#stationEditPlaylistWidth").val($(xml).find("playlist").attr("width"));
		$("#stationEditPlaylistHeight").val($(xml).find("playlist").attr("height"));
		
		$("#stationEditPlaylistPosition option:selected").removeAttr("selected");		
		$("#stationEditPlaylistPosition option[value='"+$(xml).find("playlist").attr("position")+"']").attr("selected","selected");
	
		$("#stationEditPlaylistLayout option:selected").removeAttr("selected");		
		$("#stationEditPlaylistLayout option[value='"+$(xml).find("playlist").attr("layout")+"']").attr("selected","selected");
		
		$("#stationEditPlayerSkin option:selected").removeAttr("selected");	
		$("#stationEditPlayerSkin option[value='"+$(xml).find("style").attr("skin")+"']").attr("selected","selected");

		$("#stationEditPlayerControls option:selected").removeAttr("selected");	
		$("#stationEditPlayerControls option[value='"+$(xml).find("style").attr("controls")+"']").attr("selected","selected");


		
		if($(xml).find("style").attr("stations")=="True"){$("#stationEditShowStations").attr("checked", "checked");}else{$("#stationEditShowStations").removeAttr("checked");}
		if($(xml).find("style").attr("search")=="True"){$("#stationEditShowSearch").attr("checked", "checked");}else{$("#stationEditShowSearch").removeAttr("checked");}
	
	
		if($(xml).find("player").attr("autoplay")=="True"){$("#stationEditAutoPlay").attr("checked", "checked");}else{$("#stationEditAutoPlay").removeAttr("checked");}
		$("#stationEditPlayerHeight").val($(xml).find("player").attr("height"));
	
	
		$("#stationEditPlayerAspect option:selected").removeAttr("selected");	
	
		//match the closest aspect ratio					
		var aspect = parseInt($(xml).find("player").attr("width"))/parseInt($(xml).find("player").attr("height"));
		
		if(aspect>2.0){
			$("#stationEditPlayerAspect option[value='2.39']").attr("selected","selected");
		}else if(aspect>1.8){
			$("#stationEditPlayerAspect option[value='1.85']").attr("selected","selected");
		}else if(aspect>1.6){
			$("#stationEditPlayerAspect option[value='1.7777777778']").attr("selected","selected");
		}else if(aspect>1.4){
			$("#stationEditPlayerAspect option[value='1.5']").attr("selected","selected");
		}else{
			$("#stationEditPlayerAspect option[value='1.3333333333']").attr("selected","selected");
		}
		
		$("#stationEditHeader").val($(xml).find("header").text());
		$("#stationEditHeaderHeight").val($(xml).find("header").attr("height"));
		$("#stationEditFooter").val($(xml).find("footer").text());
		$("#stationEditFooterHeight").val($(xml).find("footer").attr("height"));
		if($(xml).find("response").attr("ready")=="True"){$("#stationEditPublish").attr("checked", "checked");}else{$("#stationEditPublish").removeAttr("checked");}
	},
	save : function(obj){
		$.ajax({
			url: '/api/station',
			type: 'POST',
			data: {
				key:$(obj).data('station'),
				title:$.trim($("#stationEditTitle").val()),
				ready:($("#stationEditPublish").attr("checked")==true?"True":"False"),
				description:$.trim($("#stationEditDescription").val()),
				date:$.trim($("#stationEditDate").val()),
				tags:$.trim($("#stationEditTags").val()),
				
				stations:$.trim($("#stationEditStationFilter").val()),
				channels:$.trim($("#stationEditChannelFilter").val()),
				
				background:$.trim($("#stationEditPlayerBackground").val()),
				min_width:$.trim($("#stationEditPlayerMinWidth").val()),
				min_height:$.trim($("#stationEditPlayerMinHeight").val()),
				space:$.trim($("#stationEditPlayerSpacing").val()),
				
				show_station:($("#stationEditShowStations").attr("checked")==true?"True":"False"),
				show_search:($("#stationEditShowSearch").attr("checked")==true?"True":"False"),
			
				skin:$("#stationEditPlayerSkin").val(),
				controls:$("#stationEditPlayerControls").val(),
			
			
				position:$("#stationEditPlaylistPosition").val(),
				layout:$("#stationEditPlaylistLayout").val(),
				playlist_width:$("#stationEditPlaylistWidth").val(),	
				playlist_height:$("#stationEditPlaylistHeight").val(),	
				
				video_width:Math.round($("#stationEditPlayerHeight").val()*parseFloat($("#stationEditPlayerAspect").val())),
				video_height:$("#stationEditPlayerHeight").val(),
				autoplay:($("#stationEditAutoPlay").attr("checked")==true?"True":"False"),
								
				header:$.trim($("#stationEditHeader").val()),
				header_height:$.trim($("#stationEditHeaderHeight").val()),
				footer:$.trim($("#stationEditFooter").val()),
				footer_height:$.trim($("#stationEditFooterHeight").val())
			},
			success: function(xml){
				obj.prev().find("span").text($.trim($("#stationEditTitle").val()));
				Station.select(obj.prev(),"edit");
				Station.edit(xml);
			},					
			error: function (XMLHttpRequest, textStatus, errorThrown){
				if(XMLHttpRequest.status==400){
					alert(REQUEST_PARAMETER);
				}else{
					alert(REQUEST_ERROR);
				}
			}
		});		
	}	
}

var Channel = {
	toggle_ready:true,
	count:0,
	check : function(){
		if($("body").data("network")=="True"){
			$("#channelUpgrade").hide();
			if($("body").data("credits")<1){
				$("#channelCredit").show();
				$("#channelAdd").hide();
			}else{
				$("#channelCredit").hide();
				$("#channelAdd").show();
			}
		}else{
			if(Channel.count>2){
					$("#channelUpgrade").show();
					$("#channelCredit").hide();
					$("#channelAdd").hide();			
			}else{
				$("#channelUpgrade").hide();
				if($("body").data("credits")<1){
					$("#channelCredit").show();
					$("#channelAdd").hide();
				}else{
					$("#channelCredit").hide();
					$("#channelAdd").show();
				}
			}
		}		
	},
	toggle : function(obj){
		Channel.check();
		if(Channel.toggle_ready){
			Channel.toggle_ready=false;
			Channel.get();
			$('#channelsPage').slideToggle('slow',function(){
				Channel.toggle_ready=true;
				$.scrollTo('#channelsPage', 500, {offset:-46});						
			});
			Helpers.resize();
			$(obj).toggleClass('open');
		}
	},
	select : function(obj,typ){
		if($(obj).children(0).hasClass("close") || typ!=""){
			if($("#channelList span[class='open']").length>0){
				$("#channelList span[class='open']").parent().next().slideUp('fast',function(){Channel.show(obj,typ);});
			}else{
				Channel.show(obj,typ);
			}
		}else{
			$(obj).next().slideUp('fast');
			$(obj).children(0).addClass('close').removeClass('open');		
		}
	},
	show : function(obj,typ){
		$("#channelList span[class='open']").addClass('close').removeClass('open');			
		$("#channelEdit").appendTo($("#hidden"));
		$("#channelVideos").appendTo($("#hidden"));
		$("#channelInfo").appendTo($("#hidden"));
		
		switch(typ){
		case "edit":
			$.ajax({
				url: '/api/channel',
				data: {key:$(obj).next().attr("id")},
				success: function(xml){
					Channel.edit(xml);
					$(obj).next().empty().append($("#channelEdit"));
					$(obj).next().slideDown('fast');
					$(obj).children(0).addClass('open').removeClass('close');	
				},					
				error: function (XMLHttpRequest, textStatus, errorThrown){
					Channel.select(obj,"info");
					alert(REQUEST_ERROR);
				}
			});
			
			break;
		case "videos":
			$("#videoOverview").show();
			$("#videoInfo").hide();
			$("#videoEdit").hide();
			$("#videoStats").hide();
		
			$(obj).next().empty().append($("#channelVideos"));
			Video.get($(obj).next().attr("id"));
			$(obj).next().slideDown('fast');
			$(obj).children(0).addClass('open').removeClass('close');	
			break;
		default:
			$("#channelInfo").data("key",$(obj).next().attr("id"));
			Channel.info();
		
			$(obj).next().empty().append($("#channelInfo"));
			$(obj).next().slideDown('fast');
			$(obj).children(0).addClass('open').removeClass('close');	
		}
	},
	info : function(){
		$("#channelInfoLink").val("http://www.sayitright.tv/" + $("#channelInfoStation").val() + '/' + $("#channelInfo").data("key"));
		$("#channelRSSFeed").val("http://www.sayitright.tv/feed/" + $("#channelInfo").data("key")+ "/podcast.rss");
		$("#channelITunesFeed").val("itpc://www.sayitright.tv/feed/" + $("#channelInfo").data("key") + "/itunes.rss");
		$("#channelInfoScript").val('<script src="http://www.sayitright.tv/scripts/player/'+$("body").attr("id")+'.js" type="text/javascript"></script>');
		$("#channelInfoPlay").val('<a href="http://www.sayitright.tv/'+$("#channelInfoStation").val() + '/' + $("#channelInfo").data("key")+'" onclick="return Sir.play(\''+$("#channelInfoStation").val() + '/' + $("#channelInfo").data("key")+'\');">Play</a>');
		$("#channelInfoFrame").val('<div id="sir_frame" title="'+$("#channelInfoStation").val() + '/' + $("#channelInfo").data("key")+'"></div>');
	},
	empty : function(){
		$("#channelEdit").appendTo($("#hidden"));
		$("#channelVideos").appendTo($("#hidden"));
		$("#channelInfo").appendTo($("#hidden"));

		
		$("#channelList").empty();	
		
		var dt 		= $('<dt>').appendTo('#channelList');
		var span 	= $('<span />').attr('class','loading_icon').text("Loading").appendTo(dt);
		var dd		= $('<dd>').attr('style','display:none').appendTo('#channelList');
	},
	list : function(xml){
		$("#channelList").empty();
		Channel.count=$(xml).find("response channel").length;
		$(xml).find("response channel").each(function(){
			var dt 		= $('<dt>').appendTo('#channelList');
			//var span 	= $('<span />').text("test").appendTo(dt);


			var span 	= $('<span />').attr('class','close').text($(this).find("title").text()).appendTo(dt).click(function(){Channel.select($(this).parent(),"")});
			var img		= $('<img>').attr('src','/static/images/option_info.png').appendTo(dt).click(function(){Channel.select($(this).parent(),"info");}).attr("title","Channel Info");
			var img		= $('<img>').attr('src','/static/images/option_edit.png').appendTo(dt).click(function(){Channel.select($(this).parent(),"edit")}).attr("title","Edit Channel");
			var img		= $('<img>').attr('src','/static/images/option_list.png').appendTo(dt).click(function(){Channel.select($(this).parent(),"videos")}).attr("title","List Videos");
			var dd		= $('<dd>').attr('class','channel_item').attr('style','display:none').attr('id',$(this).attr("key")).appendTo('#channelList');
		});	
		if($(xml).find("response channel").length==0){
			var dt 		= $('<dt>').appendTo('#channelList');
			var span 	= $('<span />').attr('class','dot_icon').text("No Channels").appendTo(dt);
			var dd		= $('<dd>').attr('style','display:none').appendTo('#channelList');
		}
		Channel.check();
	},
	get : function(){
		Channel.empty();		
		$.ajax({
			url: '/api/channel',
			success: function(xml){
				Channel.list(xml);
				Channel.check();
			},					
			error: function (XMLHttpRequest, textStatus, errorThrown){
				alert(REQUEST_ERROR);
			}
		});	
	},
	create : function(t){
		Channel.empty();
		
		$.ajax({
			url: '/api/channel',
			type: 'POST',
			data: {
				title:$.trim(t)
			},
			success: function(xml){
				Channel.list(xml);
			},					
			error: function (XMLHttpRequest, textStatus, errorThrown){
				alert(REQUEST_ERROR);
			}
		});	
	},
	del :function(obj){
		if(confirm("Are you sure you wish to delete this channel?")){
			$.ajax({
				url: '/api/channel',
				type: 'POST',
				data: {
					key:$(obj).attr('id'),
					del:"True"
				},
				success: function(xml){
					Channel.toggle_ready=false;
					Channel.get();
					$('#channelsPage').slideToggle('normal',function(){
						$('#channelsPage').slideToggle('normal',function(){
							Channel.toggle_ready=true;				
							$.scrollTo('#channelsPage', 500, {offset:-46});						
							});
					});
					Helpers.resize();
					$(obj).toggleClass('open');
				},					
				error: function (XMLHttpRequest, textStatus, errorThrown){
					if(XMLHttpRequest.status==400){
						alert(REQUEST_PARAMETER);
					}else{
						alert(REQUEST_ERROR);
					}
				}
			});				
		}
	},
	save :function(obj){
		$.ajax({
			url: '/api/channel',
			type: 'POST',
			data: {
				key:$(obj).attr('id'),
				title:$.trim($("#channelEditTitle").val()),
				summary:$.trim($("#channelEditSummary").val()),
				description:$.trim($("#channelEditDescription").val()),
				date:$.trim($("#channelEditDate").val()),
				tags:$.trim($("#channelEditTags").val()),
				author:$.trim($("#channelEditAuthor").val()),
				website:$.trim($("#channelEditWebsite").val()),
				email:$.trim($("#channelEditEmail").val()),
				telephone:$.trim($("#channelEditTelephone").val()),
				publish:($("#channelEditPublish").attr("checked")==true?"True":"False"),
				category: ($("#channelEditCategory option:selected").text()=="Category"?"":$("#channelEditCategory option:selected").text()),
				subcategory: ($("#channelEditSubCategory option:selected").text()=="Sub-Category"?"":$("#channelEditSubCategory option:selected").text()),
				imaccount:$.trim($("#channelEditIMAccount").val()),
				language:$.trim($("#channelEditLanguage").val()),
				rating:$.trim($("#channelEditRating").val())
			},
			success: function(xml){
				obj.prev().find("span").text($.trim($("#channelEditTitle").val()));
				Channel.select(obj.prev(),"edit");
				Channel.edit(xml);
			},					
			error: function (XMLHttpRequest, textStatus, errorThrown){
				if(XMLHttpRequest.status==400){
					alert(REQUEST_PARAMETER);
				}else{
					alert(REQUEST_ERROR);
				}
			}
		});	
	},
	edit : function(xml){
		$("#channelEditTitle").val($(xml).find("title").text());
		$("#channelEditSummary").val($(xml).find("summary").text());
		$("#channelEditDescription").val($(xml).find("description").text());
		$("#channelEditDate").val($(xml).find("response").attr("date"));
		$("#channelEditWebsite").val($(xml).find("website").text());
		$("#channelEditEmail").val($(xml).find("email").text());
		$("#channelEditTelephone").val($(xml).find("telephone").text());
		$("#channelEditTags").val($(xml).find("tags").text());
		$("#channelEditAuthor").val($(xml).find("author").text());
		$("#channelEditIMAccount").val($(xml).find("im").text());

		$("#channelEditLanguage").val($(xml).find("language").text());
		$("#channelEditRating").val($(xml).find("rating").text());
		
		if($(xml).find("response").attr("ready")=="True"){$("#channelEditPublish").attr("checked", "checked");}else{$("#channelEditPublish").removeAttr("checked");}

		$("#channelEditCategory option:selected").removeAttr("selected");		
		if($(xml).find("category").text()==""){
			$("#channelEditCategory option:contains('Category')").attr("selected","selected");
			Helpers.subcategory("");		
		}else{
			$("#channelEditCategory option:contains('"+$(xml).find("category").text()+"')").attr("selected","selected");
			Helpers.subcategory($(xml).find("subcategory").text());	
		}

	}
};

var Video ={
	count:0,
	check : function(){
		if($("body").data("network")=="True"){
			$("#videoUpgrade").hide();
			if($("body").data("credits")<50){
				$("#videoCredit").show();
				$("#videoAdd").hide();
			}else{
				$("#videoCredit").hide();
				$("#videoAdd").show();
			}
		}else{
			if(Channel.count>99){
					$("#videoUpgrade").show();
					$("#videoCredit").hide();
					$("#videoAdd").hide();			
			}else{
				$("#videoUpgrade").hide();
				if($("body").data("credits")<50){
					$("#videoCredit").show();
					$("#videoAdd").hide();
				}else{
					$("#videoCredit").hide();
					$("#videoAdd").show();
				}
			}
		}		
	},

	create : function(c,t){
		Video.empty();
		$.ajax({
			url: '/api/video',
			type: 'POST',
			data: {
				channel:$.trim(c),
				title:$.trim(t)
			},
			success: function(xml){
				Video.list(xml);
			},					
			error: function (XMLHttpRequest, textStatus, errorThrown){
				alert(REQUEST_ERROR);
			}
		});	
	},
	empty : function(){
		$("#videoList").empty();
		var li 		= $('<li>').appendTo('#videoList');
		var span 	= $('<span />').attr('class','loading_icon').text("Loading").appendTo(li);
	},
	get : function(c){
		//set channel for info
		$("#videoInfo").data("channel",c);
		Video.empty();
		$.ajax({
			url: '/api/video',
			data: {channel:c},
			success: function(xml){
				Video.list(xml);
			},					
			error: function (XMLHttpRequest, textStatus, errorThrown){
				alert(REQUEST_ERROR);
			}
		});	
	},
	list : function(xml){
		$("#videoList").empty();
		Video.count = $(xml).find("response video").length;
		$(xml).find("response video").each(function(){
			var li 		= $('<li>').appendTo('#videoList').attr("id",$(this).attr("key"));
			//ff needs images before span?? ok in channel list!
			var img		= $('<img>').attr('src','/static/images/option_info.png').appendTo(li).click(function(){Video.info($(this).parent())});
			var img		= $('<img>').attr('src','/static/images/option_edit.png').appendTo(li).click(function(){Video.edit($(this).parent())});
			var img		= $('<img>').attr('src','/static/images/option_stats.png').appendTo(li).click(function(){Video.stats($(this).parent())});

			if($(this).attr("ready")=="True"){
				var span 	= $('<span />').attr('class','green_icon').text($(this).find("title").text()).appendTo(li).click(function(){Video.info($(this).parent())});			
			}else{
				var span 	= $('<span />').attr('class','red_icon').text($(this).find("title").text()).appendTo(li).click(function(){Video.info($(this).parent())});
			}
		});	
		if($(xml).find("response video").length==0){
			var li 		= $('<li>').appendTo('#videoList');
			var span 	= $('<span />').attr('class','dot_icon').text("No Videos").appendTo(li);
		}
		Video.check();
	},
	edit : function(obj){
		$.ajax({
			url: '/api/video',
			data: {key:$(obj).attr("id")},
			success: function(xml){
			
				$("#videoEditKey").val($(xml).find("response").attr("key"));
				$("#videoEditTitle").val($(xml).find("title").text());
				$("#videoEditSummary").val($(xml).find("summary").text());
				$("#videoEditDescription").val($(xml).find("description").text());
				$("#videoEditDate").val($(xml).find("response").attr("publish"));
				$("#videoEditWebsite").val($(xml).find("website").text());
				$("#videoEditEmail").val($(xml).find("email").text());
				$("#videoEditTelephone").val($(xml).find("telephone").text());
				$("#videoEditTags").val($(xml).find("tags").text());
				$("#videoEditAuthor").val($(xml).find("author").text());
				$("#videoEditIMAccount").val($(xml).find("im").text());
				$("#videoEditRating").val($(xml).find("rating").text());
			
				if($(xml).find("response").attr("ready")=="True"){$("#videoEditPublish").attr("checked", "checked");}else{$("#videoEditPublish").removeAttr("checked");}
				
				//ADD UPLOADER TO STACK - THEY WILL REMOVE THEMSELVES WHEN COMPLETE - NEED RANDOM IFRAME ID TO KILL CACHING
				//var i = $("<iframe>").attr('id','iframe_'+Math.random()).attr('scrolling','no').attr('src','/upload/form?v='+$(xml).find("response").attr("key")+'&u='+$("body").attr("id")+'&r='+Math.random()).prependTo("#videoEditUploads");
				
				$("#videoOverview").slideUp('fast',function(){$("#videoEdit").slideDown();});
			},					
			error: function (XMLHttpRequest, textStatus, errorThrown){
				alert(REQUEST_ERROR);
			}
		});
	},
	del :function(obj){
		if(confirm("Are you sure you wish to delete this video?")){
		$.ajax({
			url: '/api/video',
			type: 'POST',
				data: {
					key:$.trim($("#videoEditKey").val()),
					del:"True"
				},
				success: function(xml){
					Channel.show($("#"+$(xml).find("response").attr("channel")).prev(),"videos"); //we send back channel id, but id is dd, we need to send dt (prev node)
				},					
				error: function (XMLHttpRequest, textStatus, errorThrown){
					if(XMLHttpRequest.status==400){
						alert(REQUEST_PARAMETER);
					}else{
						alert(REQUEST_ERROR);
					}
				}
			});			
		}	
	},
	save :function(){
		$.ajax({
			url: '/api/video',
			type: 'POST',
			data: {
				key:$.trim($("#videoEditKey").val()),
				title:$.trim($("#videoEditTitle").val()),
				summary:$.trim($("#videoEditSummary").val()),
				description:$.trim($("#videoEditDescription").val()),
				date:$.trim($("#videoEditDate").val()),
				tags:$.trim($("#videoEditTags").val()),
				author:$.trim($("#videoEditAuthor").val()),
				website:$.trim($("#videoEditWebsite").val()),
				email:$.trim($("#videoEditEmail").val()),
				telephone:$.trim($("#videoEditTelephone").val()),
				publish:($("#videoEditPublish").attr("checked")==true?"True":"False"),
				imaccount:$.trim($("#videoEditIMAccount").val()),
				rating:$.trim($("#videoEditRating").val())
			},
			success: function(xml){
							
				//alert($("body").attr("id")+"/"+$(xml).find("channel").text()+"/"+$.trim($("#videoEditKey").val()));
				if($("#videoPreviewUploadData").val()!="" && $("body").attr("id")!=""){
					$("#videoPreviewUploadKey").val($.trim($("#videoEditKey").val()));
					$("#videoPreviewUploadUser").val($("body").attr("id"));
					$("#videoPreviewOption").val("false");					
					$("#videoPreviewUploadForm").submit();
				}else{
					$("#videoPreviewOption").val("true");									
				}

				if($("#videoUploadData").val()!="" && $("body").attr("id")!=""){
					$("#videoUploadKey").val($.trim($("#videoEditKey").val()));
					$("#videoUploadTitle").val($("body").attr("id")+"_"+$.trim($("#videoEditKey").val()));
					$("#videoUploadUser").val($("body").attr("id"));
										
					$("#videoUploadForm").submit();
					$("#videoUploadForm").hide();
					$(".videoUploadProgress").show();
				}
				$("#videoEdit").slideUp('fast',function(){$("#videoEdit").slideDown();$("#videoPreviewUploadData").val("");})
				
			},					
			error: function (XMLHttpRequest, textStatus, errorThrown){
				if(XMLHttpRequest.status==400){
					alert(REQUEST_PARAMETER);
				}else{
					alert(REQUEST_ERROR);
				}
			}
		});	
	},

	update : function(){
		
		$("#videoInfoLink").val("http://www.sayitright.tv/" + $("#videoInfoStation").val() + '/' + $("#videoInfo").data("channel") + '/' + $("#videoInfo").data("video"));
		$("#videoInfoScript").val('<script src="http://www.sayitright.tv/scripts/player/'+$("body").attr("id")+'.js" type="text/javascript"></script>');
		$("#videoInfoPlay").val('<a href="http://www.sayitright.tv/'+$("#videoInfoStation").val() + '/' + $("#videoInfo").data("channel") + '/' + $("#videoInfo").data("video") +'" onclick="return Sir.play(\''+$("#videoInfoStation").val() + '/' + $("#videoInfo").data("channel") + '/' + $("#videoInfo").data("video")+'\');">Play</a>');
		$("#videoInfoFrame").val('<div id="sir_frame" title="'+$("#videoInfoStation").val() + '/' + $("#videoInfo").data("channel") + '/' + $("#videoInfo").data("video")+'"></div>');
		$("#videoInfoEmbed").val('<object width="400" height="370" type="application/x-shockwave-flash" data="http://www.sayitright.tv/video/'+$("#videoInfoStation").val() + '/' + $("#videoInfo").data("channel") + '/' + $("#videoInfo").data("video")+'.swf"><param name="movie" value="http://www.sayitright.tv/video/'+$("#videoInfoStation").val() + '/' + $("#videoInfo").data("channel") + '/' + $("#videoInfo").data("video")+'.swf"><param name="quality" value="best"><param name="allowFullScreen" value="true"><param name="wmode" value="transparent"></object>');
	},
	info : function(obj){
		$("#videoInfo").data("video",$(obj).attr("id"));
		Video.update();
		$("#videoOverview").slideUp('fast',function(){$("#videoInfo").slideDown();});
	},
	stats : function(obj){
		$.ajax({
			url: '/api/hits',
			data: {item:$(obj).attr("id")},
			success: function(xml){
				$("#videoStatsTable").empty();

				percent=0;
				max=0;
				$(xml).find("response item").each(function(){
					if(parseInt($(this).attr("count"))>max){
						max = parseInt($(this).attr("count"));
					}
				});
				percent = 1/(max/100);
				if(max>0){
					$(xml).find("response item").each(function(){
						$('<tr><td class="label">'+$(this).attr("date")+'</td><td class="space"><img class="space" src="/static/images/spacer.gif" /></td><td class="hit"><span style="width:' + Math.round(parseInt($(this).attr('count'))*percent) + '%;"></span></td><td class="space"><img class="space" src="/static/images/spacer.gif" /></td><td>'+$(this).attr("count")+'</td></tr>').appendTo($("#videoStatsTable"));
					});
				}else{
					$('<tr><td class="label">No Stats Yet</td><td class="hit"></td></tr>').appendTo($("#videoStatsTable"));
				}			
			},					
			error: function (XMLHttpRequest, textStatus, errorThrown){
				alert(REQUEST_ERROR);
				$('<tr><td class="label">Stats Error</td><td class="hit"></td></tr>').appendTo($("#videoStatsTable"));
			}
		});
		$("#videoOverview").slideUp('fast',function(){$("#videoStats").slideDown();});
	}
};

var Guide = {
	get : function(s){
		$.ajax({
			url: '/api/guide',
			data: {search:s},
			success: function(xml){
				$("#guideList").empty();
				$(xml).find("response item").each(function(){
					$("#guideList").append('<li onclick="Guide.play(\''+$(this).attr("url")+'\',\''+$(this).text()+'\')"><span class="dot_icon">'+$(this).text()+'</span></li>'); 
				});
			},					
			error: function (XMLHttpRequest, textStatus, errorThrown){
				alert(REQUEST_ERROR);
			}
		});	
	},
	play : function(u,t){
		alert("Guide will play when you click this: " + u + t);
	}
};