(function($) {			
			$.fn.initRecordingFlow = function(options) {
				$.rflowDialog = $(this).dialog({
										autoOpen: false,
										width: 512,
										height:780,
										bgiframe: true,
										modal: true,
										close: function() {$(this).html("");} // clear dialog content on close
									});
				$.rflowDialog.s = {firstLogin: false, currentLink: null};
				return this;
			}
						
			$.fn.setOneClickEpisode = function() {
				return this.each(function(){this.s = {episode:true, season:false, recordopts:false};})
				.click(function () {
					dcsMultiTrack('DCS.dcssip','www.tivo.com','DCS.dcsuri','/tivo-tco/1clickepisode.do','WT.z_links','FTS-Recordepisode','WT.si_n','OnlineSched','WT.si_p','Recording');
					$(this).executeOneClick();
					return false;
				});
			}
			$.fn.setOneClickSeason = function() {
				return this.each(function(){this.s = {episode:false, season:true, recordopts:false};})
				.click(function () {
					dcsMultiTrack('DCS.dcssip','www.tivo.com','DCS.dcsuri','/tivo-tco/1clickseason.do','WT.z_links','FTS-Recordseasonpass','WT.si_n','OnlineSched','WT.si_p','Recording');
					$(this).executeOneClick();
					return false;
				});
			}
						
			$.fn.setRecordingOptions = function() {
				return this.each(function(){this.s = {episode:false, season:false, recordopts:true};})
				.click(function() { 
					dcsMultiTrack('DCS.dcssip','www.tivo.com','DCS.dcsuri','/tivo-tco/recoptions.do','WT.z_links','FTS-Recordwoptions','WT.si_n','OnlineSched','WT.si_p','Recording');
					$(this).executeRecordingOptions();
					return false;
				});
			}
			$.fn.setOneClickEpisode_Home = function() {
				return this.each(function(){this.s = {episode:true, season:false, recordopts:false};})
				.click(function () {
					dcsMultiTrack('DCS.dcssip','www.tivo.com','DCS.dcsuri','/tivo-tco/1clickepisode.do','WT.z_links','FTS-hp-1clickepisode;FTS-Recordepisode','WT.si_n','OnlineSched','WT.si_p','Recording');
					$(this).executeOneClick();
					return false;
				});
			}
			$.fn.setOneClickSeason_Home = function() {
				return this.each(function(){this.s = {episode:false, season:true, recordopts:false};})
				.click(function () {
					dcsMultiTrack('DCS.dcssip','www.tivo.com','DCS.dcsuri','/tivo-tco/1clickseason.do','WT.z_links','FTS-hp-1clickseason;FTS-Recordseasonpass','WT.si_n','OnlineSched','WT.si_p','Recording');
					$(this).executeOneClick();
					return false;
				});
			}				
			$.fn.setRecordingOptions_Home = function() {
				return this.each(function(){this.s = {episode:false, season:false, recordopts:true};})
				.click(function() { 
					dcsMultiTrack('DCS.dcssip','www.tivo.com','DCS.dcsuri','/tivo-tco/recoptions.do','WT.z_links','FTS-hp-recordingoptions;FTS-Recordwoptions','WT.si_n','OnlineSched','WT.si_p','Recording'); 
					$(this).executeRecordingOptions();
					return false;
				});
			}	
			
			$.fn.executeOneClick = function() {
					var link = this;
					var target = $(this).attr("href");
					$.rflowDialog.s.currentLink = link;
					
					// fade out current link
					$(this).fadeOut("slow", function () {
						// fade into interim state, if not present
						if ($("a.rflowSending").length == 0) {
							$("<a style='display:none' class='rflowSending' href='#'>Sending...</a>").insertAfter(this).fadeIn("slow");
						}
						// send request
						$.ajax({
							type: "GET",
							url: target,
							dataType: "xml",
							success: function (msg) {
								$(link).handleOneClickResponse(msg);
							},
							error: function(req, status) {
								$.rflowDialog.rflowErrorHtml().dialog("open");
								rflowWtTrackError();
							}
						});
					});	
					return this;
			};
			
			$.fn.handleOneClickResponse = function(msg) {
				return this.each(function() {
					var link = this;
					var status = getRecordingResponseStatus(msg).toLowerCase();
					
					if (status == "success") {	
						if ($.rflowDialog.s.firstLogin) {
							$.rflowDialog.unbind("dialogclose");
						}							
						$.rflowDialog.dialog("close");
						
						// create a new dialog to cache the success confirmation
						var confirmPage = $("<div class='rflowConfirmation'></div>").insertAfter($.rflowDialog)
							.dialog({
								autoOpen: false, // close by default
								width: 512,
								height: 480,
								bgiframe: true,
								modal: true 
							})
							.rflowPopupHtml(getRecordingResponseBody(msg)) // write content
							.setOneClickConfirmation(); // apply logic to the confirmation page
							
						// remove interim state, change link text to indicate success, change link to open the confirm page on click
						$("a.rflowSending").remove();
						$(link).removeClass().html("Request sent (details)").addClass("rflowThumbupLink")
							.unbind("click").click(function() {
								confirmPage.dialog("open");
								return false;
							})
							.show().before('<span class="rflowThumbup"><!-- --></span>');
											
						// if first-time login, open confirmation, refresh page on confirmation close
						if ($.rflowDialog.s.firstLogin) {
							confirmPage.rflowRefreshOnClose().dialog("open");
						}
						
						if (link.s.episode) {
							dcsMultiTrack('DCS.dcssip','www.tivo.com','DCS.dcsuri','/tivo-tco/episoderecordconfirmation.do','WT.z_links','FTS-Episode_confirmation','WT.si_n','OnlineSched','WT.si_p','Confirmation');
						}
						else if (link.s.season) {
							dcsMultiTrack('DCS.dcssip','www.tivo.com','DCS.dcsuri','/tivo-tco/seasonpassrecordconfirmation.do','WT.z_links','FTS-Seasonpass_confirmation','WT.si_n','OnlineSched','WT.si_p','Confirmation');
						}
					}
					else if (status == "failure") {
						// if first-time login, refresh page on dialog close
						if ($.rflowDialog.s.firstLogin) {
							$.rflowDialog.rflowRefreshOnClose();
						}
						// else restore link on close
						else {
							$.rflowDialog.one("dialogclose", function() {
								$("a.rflowSending").remove(); // remove interim state
								$(link).show(); 
							})
						}
						$.rflowDialog.rflowPopupHtml(getRecordingResponseBody(msg)).dialog("open");
						rflowWtTrackError();
					}
					else if (status == "login") {
						// set flag to indicate first-time login
						$.rflowDialog.s.firstLogin = true;
						// restore link text on close
						$.rflowDialog.one("dialogclose", function() {
							$("a.rflowSending").remove(); // remove interim state
							$(link).show(); 
						}).rflowPopupHtml(getRecordingResponseBody(msg)).dialog("open").setRflowLoginForm(link);
					}
					else { 
						// unrecognized status
						$.rflowDialog.rflowErrorHtml().dialog("open");
					}	
				});				
			}
			
			$.fn.setOneClickConfirmation = function() {
				if ($.rflowDialog.s.firstLogin) {
					$.rflowDialog.rflowRefreshOnClose();
				}			
				return this.each(function() {
					// popups within the confirmation page will be displayed in the main dialog instead on click
					var confirmPg = this;
					$(this).find('a.rflowPopup').click(function() { 
						// unbind any page refresh from the close event
						$(confirmPg).unbind("dialogclose").dialog("close");
						var popuplink = $(this).attr("href");
						$.ajax({
							type: "GET",
							url: popuplink,
							dataType: "html",
							success: function (msg) {
								$.rflowDialog.rflowPopupHtml(msg).dialog("open");
							},
							error: function(req, status) {
								$.rflowDialog.rflowErrorHtml().dialog("open");
							}
						});								
						return false;
					}).end()
					// open record with options
					.find('a.recordingOptions').click(function() {
						// unbind any page refresh from the close event
						$(confirmPg).unbind("dialogclose").dialog("close");
					}).setRecordingOptions(); 
				});
			}
			
			$.fn.setRflowLoginForm = function(link) {
				return this.each(function() {
					var scope = this;
					// render goldmine buttons
					$('.buttonSmall, .buttonLarge', scope).make_buttons();
					// focus on username field
					$('input[name=cams_cb_username]', scope).focus();
				});
			}
			
			$.fn.executeRecordingOptions = function() {
				var link = this;
				var target = $(this).attr("href"); // get starting target
				$.rflowDialog.s.currentLink = this;
					
				// send request
				$.ajax({
					type: "GET",
					url: target,
					dataType: "xml",
					success: function(msg) {
						$(link).handleRecordOptsResponse(msg);
					},
					error: function(req, status) {
						$.rflowDialog.rflowErrorHtml().dialog("open");
						rflowWtTrackError();
					}
				});
				return this;
			};
			
			$.fn.handleRecordOptsResponse = function(msg) {
				return this.each(function() {
					var status = getRecordingResponseStatus(msg).toLowerCase();					
					if (status == "login") {
						// set flag to indicate first-time login
						$.rflowDialog.s.firstLogin = true;
						// paste login form, render gm buttons
						$.rflowDialog.rflowPopupHtml(getRecordingResponseBody(msg)).dialog("open").setRflowLoginForm();
					}
					else if (status == "recording") {
						// if first-time login, refresh page on dialog close
						if ($.rflowDialog.s.firstLogin) {
							$.rflowDialog.rflowRefreshOnClose();
							$.rflowDialog.s.firstLogin = false;
						}							
						// paste result, convert result to ajax form, open modal dialog
						$.rflowDialog.rflowPopupHtml(getRecordingResponseBody(msg)).setAjaxRecordOptsForm().dialog("open");
					}
					else if (status == "success") {
						$.rflowDialog.rflowPopupHtml(getRecordingResponseBody(msg)).dialog("open");
						dcsMultiTrack('DCS.dcssip','www.tivo.com','DCS.dcsuri','/tivo-tco/recordwoptionsconfirmation.do','WT.z_links','FTS-Recordwoptions_confirmation','WT.si_n','OnlineSched','WT.si_p','Confirmation');
					}
					else if (status == "failure") {
						// if first-time login, refresh page on dialog close
						if ($.rflowDialog.s.firstLogin) {
							$.rflowDialog.rflowRefreshOnClose();
							$.rflowDialog.s.firstLogin = false;
						}		
						$.rflowDialog.rflowPopupHtml(getRecordingResponseBody(msg)).dialog("open");
						rflowWtTrackError();
					}
					else {
						// unrecognized status
						$.rflowDialog.rflowErrorHtml().dialog("open");
					}	
				});
			}
			
			$.fn.setAjaxRecordOptsForm = function() {
				return this.each(function() {
					var scope = this;
					// update hidden form and submit it on dvr change
					$("select[name=tsn]", scope).change(function() {
						$.rflowDialog.rflowRefreshOnClose($(this).val());
						$("form#rflowReloadChForm", scope).find("input[name=tsn]").val($(this).val()).end().submit();
					});
					// toggle different set of controls based on reocrding type
					$(":radio[name=recType]", scope).click(function() { // bind click instead of change for IE!
						// update hidden form
						$("form#rflowReloadChForm", scope).find("input[name=recType]").val($(this).val());
						// toggle control visibility and enable/disable them
						if ($(this).val() == "seasonpass") {
							$("label[for=seasonpass],label[for=explicit]").toggleClass("rflowHighlight");
							$("div.explicit").hide().find("input,select,button").attr("disabled", true);
							$("div.seasonpass").find("input,select,button").removeAttr("disabled").end().show();
						} 
						else { 
							$("label[for=seasonpass],label[for=explicit]").toggleClass("rflowHighlight");
							$("div.seasonpass").hide().find("input,select,button").attr("disabled", true);
							$("div.explicit").find("input,select,button").removeAttr("disabled").end().show();
						}
					});
					// fill in current page url as a hidden field
					var origUrl = window.location.href;	
					if (origUrl.indexOf("tivo.com") != -1) {
						$(":hidden[name=originalUrl]", scope).val(origUrl.substr(origUrl.indexOf("tivo.com")+8));
					}
					// render goldmine buttons
					$('.buttonSmall, .buttonLarge', scope).make_buttons();
					// convert any form elements to ajax forms
					$("form", scope).ajaxForm({
						target: scope,
						dataType: "xml",
						beforeSubmit: function(msg) {
							$(scope).rflowShowLoading();
						},
						success: function(msg) {
							$(scope).handleRecordOptsResponse(msg); // recursion!
						}
					});
				});
			}
			
			$.fn.rflowShowLoading = function() {
				var overlay = $("div.rflow-MiddleMedium").append('<div class="rflow-loading"><img src="/assets/images/findtv/icons/waiting_small_clear_light_background.gif"/></div>');
				$('div.rflow-loading').height(overlay.outerHeight());
			}
			
			$.fn.rflowRemoveLoading = function() {
				$('div.rflow-loading').remove();
			}
			
			$.fn.rflowErrorHtml = function() {
				return this.rflowPopupHtml('<h3>We\'re sorry</h3><p class="last">We were unable to process your request. Please try again.</p>');
			}
			
			$.fn.rflowPopupHtml = function(content) {
				return this.each(function() {
					$(this).html('<div class="rflow-ContainerMedium"><div class="rflow-MiddleMedium"><div id="rflow-ModalBody">'
					+ content
					+ '</div></div><div class="rflow-BottomMedium"><!--empty--></div></div>');
				});
			}
			
			$.fn.rflowRefreshOnClose = function(data) {
				var tsn = data;
				return this.one("dialogclose", function() {
					if (tsn && tsn != "") {						
						$("select#DVRlist").val(tsn);
					}
					var url = window.location.href;
					if (url.indexOf("http:") == 0) {
						window.location.replace("https:" + url.substr(5));
					} 
					else {
						window.location.reload();
					}
				});
			}
			
			function getRecordingResponseStatus(response) {
				return $(response).find("status").text();
			}
			
			function getRecordingResponseBody(response) {
				return $(response).find("content").text();
			}
							
})(jQuery);

// Start!
jQuery(function($) {
	$('<div class="rflowDialog"></div>').appendTo("body").initRecordingFlow();	
	$("a.oneClickRecord").setOneClickEpisode();
	$("a.oneClickSeason").setOneClickSeason();
	$("a.recordingOptions").setRecordingOptions();
	// home page only
	$("a.oneClickRecord_hp").setOneClickEpisode_Home();
	$("a.oneClickSeason_hp").setOneClickSeason_Home();
	$("a.recordingOptions_hp").setRecordingOptions_Home();	
	$("img.bbOneClickLoading").remove();
	$("div.oneClickPanel").show();	
	// end home page only
});

// Functions to handle one-click login
function rflowStartLogin(form) {
	if (window.rflowLoginFrame && window.rflowLoginFrame.rflowSubmitLogin) {
		jQuery.rflowDialog.rflowShowLoading();
		window.rflowLoginFrame.rflowSubmitLogin(form);
		dcsMultiTrack('DCS.dcssip','www.tivo.com','DCS.dcsuri','/tivo-tco/index.do','WT.z_links','FTS-hp-recflow-signin');
	}
}
function rflowContinue() {
	var curlink = jQuery.rflowDialog.s.currentLink;
	curlink.each(function() {
		if (this.s.recordopts) {
			jQuery(this).executeRecordingOptions();
		}
		else {
			jQuery(this).executeOneClick();
		}
	});
}
function rflowLoginError(msg) {
	jQuery.rflowDialog.rflowRemoveLoading();
	window.rflowLoginFrame.location.href = "/tivo-tco/1clickhlogin.do";
	jQuery("div.rflowDialog form[name=loginForm]")
		.each(function(){this.reset();})
		.find("span.error").text(msg); 
	jQuery.rflowDialog.rflowRefreshOnClose();
	rflowWtTrackError();
}

function rflowWtTrackError() {
	dcsMultiTrack('DCS.dcssip','www.tivo.com','DCS.dcsuri','/tivo-tco/errorscreens.do','WT.z_links','FTS-errorscreen');
}	
