var cancelPollForFile = false;
var pid = null;
var outputFilename = null;

var downloadedClips = [];

function pollForFile(filename, objectId, objectType, callback) {
	if (cancelPollForFile) { 
		if (pid != null) {
			$.ajax({
				data: {
					action: 'cancelFileoutput',
					filename: filename,
					pid: pid
				}, 
				success: function() {
					downloadedClips =[];
				}
			});
		}
		return; 
	}
	$.ajax({
		data: {
			action: 'getFilestatus',
			filename: filename,
			pid: pid
		},
		success: function(data) {
			var obj = $.parseJSON(data);
			if (obj.ready ==1) {
				
				$("#outputBinDialog").trigger('stopWaiting');
				$("#alertDialog").dialog('close');
				if (callback !== undefined) {
					callback();
				}
				$.each(downloadedClips, function(name, value) {
					trackEvent('Download', 
						value.specialty ? 'specialty Collection' :'Standard Collection',
						value.tapeId
					); 
				});
				downloadedClips =[];
				window.location.href = BASE_PATH +  'outputVideo.php?' 
							+ 'name=' + filename 
							+ '&objectType=' + objectType
							+ '&objectId=' + objectId
							+ '&clipId=' + (currentClipId ? currentClipId : '')
							+ '&clipType=' + currentClipType
			} else {
				setTimeout(function () { pollForFile(filename, objectId, objectType, callback) }, 500);
			}
		}
	});
}

function createOutputFile(objectId, objectType, callback) {
	$.ajax({
			data: {
				action: 'createOutputfile',
				objectId: objectId,
				objectType: objectType,
				clipId: (currentClipId ? currentClipId : ''),
				clipType: currentClipType
			}, 
			success: function(data) {
				var obj = $.parseJSON(data);
				cancelPollForFile = false;
				pid = obj.pid;
				outputFilename = obj.filename;
				showAlert('Preparing your video for download.  Please wait a moment&hellip;<br/><img class="loading" src="template/loading_transparent.gif" alt="loading">',
					function() {
						cancelPollForFile = true; 
						pollForFile(outputFilename);
					},
					'Preparing Download',
					'Cancel'
				);
					
				
				pollForFile(obj.filename, objectId, objectType,callback);
			}
		});	
}

function downloadClips(message, objectId, objectType, plural) {
	if (plural == undefined) {
		plural = true;
	}
	if (message) {
		showConfirm(
			message,
			function() {
				createOutputFile( objectId, objectType);
			},
			function(){},
			"Download Clip" + (plural ? 's' :''),
			"Cancel",
			true,
			function(){},
			"Download Clips",
			{},
			550
		);
	} else {
		createOutputFile( objectId, objectType);
	}
}

function downloadSingleFile(objectId, objectType) {
	if (objectType == undefined) {
		objectType = 'Clip'
	}
	proMessage ='';
	$.ajax({
		data: {
			action: 'checkProminutesavailable',
			objectId: objectId,
			objectType: objectType,
			clipId: currentClipId ? currentClipId : '',
			clipType: currentClipType
		},
		success: function(data) {
			var obj = $.parseJSON(data);
			pauseVideo();
			if (obj.proLength) {
				if (!obj.availableMinutes) {
					showAlert(
						"Sorry!  The clip you've selected requires a &quot;Pro&quot; account for downloading.",
						function(){},
						"Nothing to download"
					);
					return;
				} else {
					var costUnit = (obj.proLength>1) ? 'minutes' : 'minute';
					if (obj.enough) {
						proMessage = "Note:  This clip is part of one of our Specialty Collections." +
							"  Downloading it will debit your &quot;Pro&quot; account balance by "+ 
							obj.proLength +" "+costUnit+".";	
					} else {
						var balanceUnit = (obj.avaliableMinutes>1) ? 'minutes' : 'minute';
						proMessage ="Note:  This clip is part of one of our Specialty Collections."+
							"  Downloading it would debit your &quot;Pro&quot; account balance by " +
							obj.proLength + 
							" "+costUnit+", but you only have a balance of "+ obj.avaliableMinutes+
							" "+balanceUnit+" left in your account." +
							"  Consider purchasing more Specialty Collection minutes, or reduce your footage selection before continuing.";
						showConfirm(
							proMessage,
							function() {
								location.href = 'buyMinutes';
							},
							function(){},
							"Purchase additional \"Specialty Collection\" minutes",
							"Cancel",
							true,
							function(){},
							"Insufficient Pro Minutes",
							{},
							550
						);
						return;
					}
				}
			}
			
			downloadClips(proMessage, objectId, objectType, false);
		}
	});
}

function downloadMultipleFiles(objectId, objectType,selectedVideoClips,selectedNonVideoClips,selectedSpecialtyVideoClips) {
	var message= '', proMessage ='', standardClips=[];
	
	selectedVideoClips.each(function() {
		if (!$(this).hasClass('specialty')) {
			standardClips.push($(this).attr('id').substring('clipDetails'.length));
		}
	});
	
	if (selectedNonVideoClips.length != 0) {
		message = "Note:  Some of the selected clips are currently not available for download, and will therefore not be included.  Those clips are:";
		message += "<ul>";
		selectedNonVideoClips.each(function() {
			message += "<li>" + $(".tapeId", $(this)).text() + ": ";
			if($(".comment .empty", $(this)).length == 0 && $(".comment", $(this)).text()) {
				message += $(".comment", $(this)).text();
			} else {
				message += $(".tcRange", $(this)).val();
			}
			message += "</li>"
		});
		message += "</ul>";
	}
	
	if (!selectedSpecialtyVideoClips.length) {
		selectedVideoClips.each(function() {
			downloadedClips.push({
				tapeId: $(".tapeId", $(this)).text(),
				specialty: $(this).hasClass('specialty')
			});
		});
		downloadClips(message, objectId,objectType);
		return;
	}
	$.ajax({
		data: {
			action: 'checkProminutesavailable',
			objectId: objectId,
			objectType: objectType
		},
		success: function(data) {
			var obj = $.parseJSON(data);
			proMessage ='';
			if (obj.proLength) {
				if (obj.availableMinutes == 0) {
					proMessage = "Note: Some of the selected clips require a &quot;Pro&quot;" +
						" account for downloading, and will therefore not be included.  Those clips are:";
				} else {
					var costUnit = (obj.proLength>1) ? 'minutes' : 'minute';
					var verbTense = (obj.enough) ? 'will' : 'would';
					proMessage += "Note:  Some of the selected clips are part of our Specialty Collections." +
						" Downloading them "+verbTense+" debit your &quot;Pro&quot; account balance by a total of "+obj.proLength+" "+costUnit+", as follows:";
				}
				proMessage += "<ul>";
				deductedTransactions = [];
				selectedSpecialtyVideoClips.each(function() {
					var transId = $(".clipProKey",$(this)).val();
					if ($.inArray(transId, deductedTransactions) != -1) {
						return true;
					}	
					deductedTransactions.push(transId);	
					proMessage += "<li>" + $(".tapeId", $(this)).text() + ":";
					if($(".comment .empty", $(this)).length == 0 && $(".comment", $(this)).text()) {
						proMessage += '&nbsp;' + $(".comment", $(this)).text();
					} else {
						proMessage += '&nbsp;' +  $(".tcRange", $(this)).val();
					}
					proMessage += '&nbsp;(' + $(".clipProMinutes", $(this)).val() + ' min)';
					proMessage += "</li>"	
				});
				proMessage += "</ul>";
			}
			if (obj.enough) {
				selectedVideoClips.each(function() {
					downloadedClips.push({
						tapeId: $(".tapeId", $(this)).text(),
						specialty: $(this).hasClass('specialty')
					});
				});
				downloadClips(message + proMessage, objectId,objectType);
			} else {
				var extraButton = {};
				if (obj.availableMinutes != 0) {
					
					var costUnit = (obj.availableMinutes>1) ? 'minutes' : 'minute';
					proMessage += "However, you only have a balance of " +
						obj.availableMinutes + ' ' + costUnit +" left in your account." +
						"  Consider purchasing more Specialty Collection minutes," +
						" or reduce your footage selection before continuing.";
				} else  if ($("#mainArea li.hasVideo:not(.specialty):has(:checkbox:checked)").length) {
					extraButton = {
						'Continue Anyway': function() {
							selectedVideoClips.each(function() {
								if (!$(this).hasClass('specialty')) {
									downloadedClips.push({
										tapeId: $(".tapeId", $(this)).text(),
										specialty: $(this).hasClass('specialty')
									});
								}
							});
							if (standardClips.length ==1) {
								downloadClips('', standardClips[0],'Clip', false);
							} else {
								downloadClips('', standardClips.join(','),isOrder ? 'OrderClip' : (shareBin ? 'ShareClip' : 'Clip'));
							}
							$("#confirmDialog").dialog('close');
						}
					};
				}
				showConfirm(
					message + proMessage,
					function() {
						location.href = 'buyMinutes';
					},
					function(){},
					"Purchase additional \"Specialty Collection\" minutes",
					"Cancel",
					true,
					function(){},
					"Insufficient Pro Minutes",
					extraButton,
					550
				);	
			}
		}
	});
}

$(document).ready(function() {
		
	$("#videoWindow .downloadClip").click(function() {
		if ($(this).hasClass('disabled')) {
			return;
		}
		/*if ($(this).attr('id') != undefined && $(this).attr('id').indexOf('downloadClip') != -1) {
			var clipId = $(this).attr('id').substring('downloadClip'.length);
			downloadSingleFile(clipId, currentClipType);
		} else {*/
			downloadedClips.push({
				tapeId: $("#videoWindow .tapeId").text(),
				specialty: $("#videoWindow .specialty").is(':visible')
			});
			
			downloadSingleFile(currentTapeId + ',' + roundToSignificantDigits(offsetIn,2) + ',' + roundToSignificantDigits(offsetOut,2), 'Tape');
			
		//}
	});
	
	$(".downloadBin").click(function() {
		if ($(this).hasClass('disabled')) {
			return;
		}
		var selectedVideoClips = $("#mainArea li.hasVideo");
		var selectedNonVideoClips = $("#mainArea li:not(.hasVideo)");
		var selectedSpecialtyVideoClips = $("#mainArea li.specialty");
		var binId = $(this).attr('id').substring('downloadBin'.length);
		var objectType;
		if (isOrder) {
			objectType= 'Order';
		} else if (shareBin) {
			objectType= 'ShareBin';
		} else {
			objectType= 'Bin';
		}
		if (selectedVideoClips.length == 0) {
			showAlert(
				"Sorry!  There are no clips in this bin currently available for download.",
				function(){},
				"Nothing to download"
			);
			return;
		}
		
		downloadMultipleFiles(binId, objectType, selectedVideoClips,selectedNonVideoClips,selectedSpecialtyVideoClips);
	});
	
	$(".downloadSelectedClips").click(function() {
		if ($(this).hasClass('disabled')) {
			return;
		}
		
		var clips = [];
		var objectType = '';
		var objectId ='';
		
		var selectedVideoClips = $("#mainArea li.hasVideo:has(:checkbox:checked)");
		var selectedNonVideoClips = $("#mainArea li:not(.hasVideo):has(:checkbox:checked)");
		var selectedSpecialtyVideoClips = $("#mainArea li.specialty:has(:checkbox:checked)");
		
		selectedVideoClips.each(function() {
			clips.push($(this).attr('id').substring('clipDetails'.length));
		});
		
		if (selectedVideoClips.length == 0) {
			showAlert(
				"Sorry!  None of the clips you've selected are currently available for download.",
				function(){},
				"Nothing to download"
			);
			return;
		} 
		
		if ($("#mainArea :checkbox:not(:checked)").length == 0) {
			var objectId = displayBinId;
			if (isOrder) {
				objectType= 'Order';
			} else if (shareBin) {
				objectType= 'ShareBin';
			} else {
				objectType= 'Bin';
			}
		} else {
			var objectId = clips.join(',');
			
			if (isOrder) {
				objectType= 'OrderClip';
			} else if (shareBin) {
				objectType= 'ShareClip';
			} else {
				objectType= 'Clip';
			}
		}
		if ($("#mainArea :checkbox:checked").length == 1 && $("#mainArea :checkbox:not(:checked)").length != 0) {
			downloadedClips.push({
				tapeId: $(".tapeId", $("#mainArea :checkbox:checked").closest('li')).text(),
				specialty: $("#mainArea :checkbox:checked").closest('li').hasClass('specialty')
			});
			downloadSingleFile(clips[0], objectType);
		} else {
			downloadMultipleFiles(objectId, objectType,selectedVideoClips,selectedNonVideoClips,selectedSpecialtyVideoClips);
		}
	});
	
	$(".redownload").click(function() {
		var downloadId = $(this).attr('id').substring('redownload'.length);
		createOutputFile(downloadId , 'prodownload', function() { decrementDownloadCount(downloadId) });
	});
	
	$(window).unload( function () { cancelPollForFile = true; pollForFile(outputFilename); } );
	
});
