var currentBinId = null;
var shoppingCartId = null;
var addingItem = false;
var numBins = 0;
var clipIsWritable = false;
var clipNoteLength =8;


function generateBinHash() {
	return hex_sha1(Math.random().toString());

}

function createBin(binName, redirect) {
	if (redirect == undefined) {
		redirect = false;
	}
	$.ajax({
		data: {
			'action': 'createBin',
			'title': binName
		},
		success: function(data) {
			var obj = $.parseJSON(data);
			currentBinId = obj.bin.id; 
			if (redirect) {
				location.replace('bins/' + obj.bin.hashId);
			} else {
				displayBinList(obj, false);
				displayBin(obj.bin);
			}
		}
	});
}

function showAddBinDialog(callback) {
	
	$('#newBinDialog').dialog( "option", "buttons", {
        "Create New Bin": function() {
			if (!$("#txtNewBinName").val().length) {
				$(".error", $(this)).text("You must enter a name.");
				return;
			}
			callback($("#txtNewBinName").val());
			$(this).dialog('close');
		},
		"Cancel": function() {
			
			$(this).dialog('close');
		}
    });
    $('#newBinDialog').parent().css({position:"fixed"}).end().dialog('open');
	
}

function addSelectedToBin(binId, binName, callback) {

	if (callback == undefined) {
			callback = function() {};
	}
	
	if (!binName && (!binId  || binId == -1)) {
		showAddBinDialog(function(binName) { addSelectedToBin(binId, binName, callback) });
		return;
	} 
	
	var tapes = [];
	var events = [];
	var clips = [];
	$(".selectContainer :checkbox:checked").each(function() {
		
		if ($(this).hasClass('fullReel')) {
			var id = $(this).parents(".searchResult").attr('id').substring("result".length);
			var specialtyCollection = $(".specialtyCollection", $(this).closest(".searchResult")).text() == 'true';
			tapes.push(id);
			trackEvent("Create Clip",
				specialtyCollection ? 'Specialty Collection' :'Standard Collection', 
				$(".tapeId", $(this).parents(".searchResult")).text()
			);
		} else if ($(this).hasClass('chkClip')) {
			clips.push($(this).parents('li').attr('id').substring("clipDetails".length));
		} else {
			events.push($(this).parent().attr('id').substring("log".length));
			var id = $(this).parents(".searchResult").attr('id').substring("result".length);
			var specialtyCollection = $(".specialtyCollection", $(this).closest(".searchResult")).text() == 'true';
			trackEvent("Create Clip",
				specialtyCollection ? 'Specialty Collection' :'Standard Collection',
				$(".tapeId", $(this).parents(".searchResult")).text()
			);
		}
	});

	if (events.length==  0 && tapes.length == 0 && clips.length==0) {
		showAlert("Nothing is selected.");
		return;
	}

	$.ajax({
		data: {
			action: 'binaddClips',
			tapes: tapes.join(),
			events: events.join(),
			clips: clips.join(),
			binId: (binId == null ? '' : binId),
			binName: binName,
			fromShareBin: shareBin,
			fromOrder: isOrder
		},
		success:  function(data) {
			var binInfo = $.parseJSON(data);
			displayBin(binInfo.bin);
			$(".selectNone").trigger('click');
			callback();
			
		}		
	});
}

function addLogToBin(logId, binId, index, binName) {
	
	if (!binName && (!binId  || binId == -1)) {
		showAddBinDialog(function(binName) { addLogToBin(logId, binId, index, binName) });
		return;
	} 
	
	$.ajax({
		data: {
			action: 'binaddLog',
			logId: logId,
			binId: (binId == null ? '' : binId),
			index: index,
			binName: binName
		},
		success: function(data) {
			var binInfo = $.parseJSON(data);
			if (binId == currentBinId) {
				displayBin(binInfo.bin);
			}
			trackEvent(
				"Create Clip",
				binInfo.newClip.specialtyCollection ? 'Specialty Collection' :'Standard Collection',
				binInfo.newClip.tapeId
			);
			showStatus("Clip Added");
		}, 
		complete: function(xReq,textStatus){
			addingItem = false;
			$("#clipBin").trigger("stopWaiting");
			$("#shoppingCart").trigger("stopWaiting");
		}
		
	});
}

function addNewClipToBin(tapeId, offsetIn, offsetOut, comment, binId, index, binName) {
	
	if (!binName && (!binId  || binId == -1)) {
		showAddBinDialog(function(binName) { addNewClipToBin(tapeId, offsetIn, offsetOut, comment, binId, index, binName) });
		return;
	} 
	
	$.ajax({
		data: 
		{
			'action': 'binaddNewclip',
			'binId': binId == null ? '' : binId,
			'libraryId': tapeId,
			'offsetIn': offsetIn,
			'offsetOut': offsetOut,
			'comment': comment,
			index: index,
			binName: binName,
			currentClipId: currentClipId ? currentClipId : '',
			currentClipType: currentClipType
		},
		success: function(data) {
			$("#clipBin").trigger("stopWaiting");
			var binInfo = $.parseJSON(data);
			displayBinList(binInfo);
			displayBin(binInfo.bin);
			if (typeof(displayBinId) !== 'undefined' && binId == displayBinId) {
				displayBinDetails(binInfo.bin);
			}
			trackEvent(
				"Create Clip", 
				binInfo.newClip.specialtyCollection ? 'Specialty Collection' :'Standard Collection',
				binInfo.newClip.tapeId
			);
			if (videoPopup) {
				showConfirm(
					"A copy of the clip has been saved to \"" + binInfo.bin.title+ "\".  Would you like to open the saved copy for editing?", 
					function() {}, 
					function() {
						hideVideoPlayer();
					}, 
					
					"Leave original up", 
					"Close window",
					true, 
					function(){},
					"Clip Saved", 
					{
						"Open saved copy": function() {
							currentClipType ="Clip";
							clipIsWritable = true;
							clipChanged =false;
							displayClip(binInfo.newClip);
							$("#confirmDialog").dialog('close');
						}
					},
					450
				); 
			}
		}
	});

}

function addClipToBin(binId, clipId, index, binName) {
	
	
	if (!binName && (!binId  || binId == -1)) {
		showAddBinDialog(function(binName) { addClipToBin(binId, clipId, index, binName) });
		return;
	} 

	$.ajax({
		data: 
		{
			'action': 'binaddClip',
			'binId': binId == null ? '' : binId,
			'clipId': clipId,
			index: index,
			binName: binName,
			fromShareBin: shareBin,
			fromOrder: isOrder
		},
		success: function(data) {
			$("#clipBin").trigger("stopWaiting");
			var binInfo = $.parseJSON(data);
			displayBin(binInfo.bin);
			showStatus("Clip Added");
		}
	});

}

function getClipRow(li, value) {

	li.empty();	
	li.append($('<a>').addClass("close").attr("title","Delete this clip"));
	var title = value.notes ? value.notes : value.tapeId;
	li.append(getThumbnailFromIndex(value.libraryId, value.thumbnailNum == null ? 0:value.thumbnailNum , 'small', 'smallThumb', false, value.hashId, value.clipType));
	li.append($("<div>")
		.addClass('positionBar')
		.width(SMALL_THUMBNAIL_WIDTH)
		.html(createPositionBar(value.tapeLength, value.offsetIn, value.offsetOut, SMALL_THUMBNAIL_WIDTH)));
	li.append($("<h5 />").text(value.tapeId))
	if (!value.notes) {
		li.append($("<span />").addClass("startTime").addClass("label").text(trimFrames(value.timecodeIn)));
	}
	var note = '';
	if (value.notes) {
		var div = $("<div/>").text(value.notes);
		note = div.text();
		if (note.length > clipNoteLength) {
			note = note.substring(0, clipNoteLength) + '&hellip;';
		}
		li.append($("<div/>")
			.addClass('comment')
			.addClass('label')
			.html(note));
	}
	if (value.specialtyCollection) {
		li.addClass('specialty');
	}
	li.attr("title", title);
	
}

function displayClips(binInfo, container) {

	$(".listBox", container).empty();
	if (binInfo.numClips > 0) {
		$.each(binInfo.clips, function(name, value) {
			var li = $("<li />")
				.attr('id', 'clip' + value.id )
				.addClass('clip');
			getClipRow(li, value);
			$(".listBox", container).append(li);
		});
		
	
		$(".mailBin", container)
			.removeClass('disabled')
			.attr('id', 'mailBin' + binInfo.id);
		
		$(".utils a", container).removeClass('disabled');
		$(".mailBin", container).removeClass('disabled');
		$(".emptyNote", container).hide();
	} else {
		$(".emptyNote").show();
		$(".mailBin", container).addClass('disabled');
		
	}
}

function displayBin(binInfo) {
	currentBinId = binInfo.id; 
	if (binInfo.numClips == 0) {
		$("#binList").hide();
	} else {
		$("#binList").show();
	}
	$("#clipBin div.utils").show();
	$.cookie('currentBinId', currentBinId, {path: COOKIE_PATH});
	displayClips(binInfo, $("#clipBin"));
	if ($("#binSelect option[value=" + binInfo.id + "]").length) {
		$("#binSelect").val(binInfo.id);
	} else {
		$("#binSelect option[value=-1]").before(
			$("<option />")
				.attr('value', binInfo.id)
				.text(binInfo.title)
		);
		$("#binSelect").val(binInfo.id);
	}
	if (binInfo.note) {	
		$("#clipBin .binNote").text(binInfo.note);
	} else {
		$("#clipBin .binNote").empty();
	}
	$("#clipBin .binNote").attr('id', 'binNote' +binInfo.id);
	makeEditable($("#clipBin .binNote"), true, 'bin', binInfo.id, 'note', "<span class=\"empty\" title=\"Click to Edit this note\">(Click to add a brief note to this bin)<\/span>");
	$("#binDetails").attr('href', absoluteURL + "bins/" + binInfo.hashId);
	$("#binOrder").click(function() {
		showContactResearcherBinDialog(binInfo.id);
	});
	$("#clipBin #thisBinBtns").show();
	$("#clipBin .mailBin").show();
	
}

function displayBinList(binList, loadCurrentBin) {
	if (loadCurrentBin == undefined) {
		loadCurrentBin =true;
	}
	
	var firstBinId = null;
	$(".binSelect").empty();
	numBins=0;
	foundCurrentBin = false;
	$.each(binList.bins, function(name, value) {
		if (value.isCart) {
			return true;
		}
		if (currentBinId && value.id == currentBinId) {
			foundCurrentBin = true;
		}
		numBins++;
		if (firstBinId == null) {
			firstBinId = value.id;
		}
		option = $("<option/>")
			.text(value.title)
			.attr('value', value.id);
		$(".binSelect").append(option);
	});
	$(".binSelect").append(
		$("<option/>")
			.addClass('action')
			.text("Create a new bin...")
			.attr('value', '')
	);
	
	if (numBins == 0) {
		$(".binSelect").prepend(
		$("<option/>")
			.html('(No Bins)')
			.attr('value', '-1')
		);
		$(".binSelect").val(-1);
		currentBinId = null;
		$.cookie('currentBinId', null, {path: COOKIE_PATH});
		$("#clipBin #thisBinBtns").hide();
		$("#clipBin .mailBin").hide();	
	} else if (loadCurrentBin) {
		if (foundCurrentBin) {
			getBin(currentBinId);
			$(".binSelect").val(currentBinId);
		} else {
			getBin(firstBinId);	
		} 
	}
}

function getBin(binId) {	
	waitingAsyncProcessCount++;
	$.ajax({
		data: {
			action:'getBin',
			binId: binId
		},
		complete: function() {
			waitingAsyncProcessCount--;
		},
		success: function(data) {
			var binInfo = $.parseJSON(data);
			displayBin(binInfo, null);
		},
		error: function() {
			if (binId == currentBinId) {
				currentBinId = null;
				$.cookie('currentBinId', null, {path: COOKIE_PATH});
			}
			/*fail silently */
		}	
	});

}

function getBinList() {
	waitingAsyncProcessCount++;
	$.ajax({
		data: {
			action: 'getBinlist'
		},
		complete: function() {
			waitingAsyncProcessCount--;
		},
		success: function(data) {
			var bins = $.parseJSON(data);
			displayBinList(bins);
		}
	});
}

function updateTimecode(fieldName, fieldValue) {
	
	if (currentClipId != null ) {
		updateClip(fieldName, fieldValue);
	} else {
		
		var tapeIn = 0;
		var tapeOut = -1;

		
		if (fieldName == 'offsetIn') {
			offsetIn = fieldValue;
			offsetOut = tapeOut;
		} else {
			offsetIn = tapeIn;
			offsetOut = fieldValue;
		}
		
		addNewClipToBin(
			currentTapeId,
			offsetIn,
			offsetOut,
			newClipTitle
		);
	}
}

function updateClip( fieldName, fieldValue) {
	
	$.ajax({
		data:{
			action: 'updateClip',
			'fieldName': fieldName,
			'fieldValue': fieldValue,
			id: currentClipId ? currentClipId : ''
		},
		success: function(data) {
			showStatus("Clip updated");
			var obj = $.parseJSON(data);
			getClipRow($('#clip' + obj.id), obj);
			if ($("#binContents #clipDetails" + obj.id).length) {
				 getClipDetails(obj, $("#binContents #clipDetails" + obj.id), obj.isWritable);
			}
		}
	});
}

function saveClipChanges(callback) {
	comment = '';
	if (!$("#clipTitle .empty").length) {
		comment = $("#clipTitle").text();
	}
	$.ajax({
		data:{
			action: 'saveClip',
			offsetIn: offsetIn,
			offsetOut: offsetOut,
			comment: comment, 
			id: currentClipId ? currentClipId : ''
		},
		success: function(data) {
			callback();
			var obj = $.parseJSON(data);
			getClipRow($('#clip' + obj.id), obj);
			if ($("#binContents #clipDetails" + obj.id).length) {
				 getClipDetails(obj, $("#binContents #clipDetails" + obj.id), obj.isWritable);
			}
		}
	});
}

function moveToBin(clipId, binId) {
	$.ajax({
		data: {
			action: 'binaddClip',
			clipId: clipId,
			binId: binId,
			fromShareBin: shareBin,
			fromOrder: isOrder
		},
		success: function(data) {
			var bin = $.parseJSON(data);
			
			displayBin(bin);
		}
	});
}

function updateField(objectName, fieldName, fieldValue, orig, idValue, element) {

	//make sure the first letter of the object name is capitalized
	first= objectName.substr(0,1); 
	rest = objectName.substr(1, objectName.length -1);
	objectName = first.toUpperCase() + rest.toLowerCase();  
	
	$.ajax({
		data:{
			action: 'update'+ objectName,
			fieldName: fieldName,
			fieldValue: fieldValue,
			id: idValue
		},
		success: function(data) {
			showStatus(objectName + " updated");
			var obj = $.parseJSON(data);
			switch (objectName) {
				case 'Clip':
					getClipRow($('#clip' + obj.id), obj);
					$("#clipDetails" + obj.id).attr('title',  obj.comment ? obj.comment : clip.tapeId);
					break;
				case 'Bin':
					
					$("#binNote" + obj.id).text(obj.note);
					if (displayBinId == obj.id) {
						$("#binDescription").text(obj.note);
					}
					$(".binSelect option[value=" +obj.id + "]").text(obj.title);
				
					break;
			}
		},
		error: function(data, testStatus, errorThrown) {
			showAlert('Error: ' + errorThrown);
			if (element) {
				element.html(orig);
			}
			
		}
	});
}

function showAdoptionPrompt() {
	 showConfirm(
	 	 'You have bins that were created prior to logging in.  Would you like to import them to your account?',
	 	 function() {
	 	 	 $.ajax({
				 data:{
				 	 action: 'adoptCookiebins'
				 },
				 success: function(data) {
				 	 var bins = $.parseJSON(data);
				 	 displayBinList(bins);
				 	
				 }
	 	 	 
	 	 	 });
	 	 },
	 	 function() {
	 	 	  $.ajax({
				 data:{
				 	 action: 'clearCookiebins'
				 },
				 success: function(data) {
				 	 //var bins = $.parseJSON(data);
				 	 //displayBinList(bins);
				 	 location.reload();
				 }
	 	 	 
	 	 	 });
	 	 },
	 	 'Yes, import them',
	 	 'No, discard them',
	 	 true,
	 	 function(){},
	 	 'Import Existing Bins');
}

function inElement(pos, element) {

	if (!element.length) {
		return false;
	}
	var elPos = element.offset();
	return pos.y >= elPos.top &&
		pos.y <= elPos.top + element.height() &&
		pos.x >= elPos.left &&
		pos.x <= elPos.left + element.width()
	
}

function sortClips(binId, clipId, newPos) {
	$.ajax({
		data:{
			'action': 'sortClips',
			'binId': binId,
			'clipId': clipId,
			'newPos': newPos
		},
		success: function(data) {
			var binInfo = $.parseJSON(data);
			if (binId == currentBinId) {
				displayBin(binInfo);
			}
			
			if (typeof(displayBinDetails) !== 'undefined' && currentBinId == displayBinId) {
				displayBinDetails(binInfo);
			}
			addingItem = false;
		}
	});
}

function receiveNewItem(item, index) {

	var binId = currentBinId;
	addingItem = true;
	
	if (item.hasClass('reelDetails')) {
		var tapeId = item.attr('id').substring('details'.length);
		addNewClipToBin(tapeId, 0,-1, '', binId, index);
		
	} else if (item.hasClass('logEntry')) {
		var logId = item.attr('id').substring("log".length);
		addLogToBin(logId, binId, index);
		
		
	} else if (item.hasClass('clipDetails')) {
		var clipId = item.attr('id').substring('clipDetails'.length);
		if (currentBinId == displayBinId) {
			if (item.prevAll("#clip" + clipId).length) {
				var newPos = index -1;
			} else {
				var newPos = index;
			}
			sortClips(currentBinId,  clipId, newPos); 
		} else {
			addClipToBin(binId, clipId, index);
		}

	} else if (item.hasClass('clip')) {
		var clipId = item.attr('id').substring('clip'.length);
		moveToBin(clipId, currentBinId)
	}
}

$(document).ready(function() {
	
	currentBinId = $.cookie('currentBinId');
	if (!showingAdoptionPrompt) {
		getBinList();
	}

	$("#sidebarSignUp").click(function() {
			$("#signUpButton").trigger('click');
	});

	$(".addToBin").live('click', function() {

		addNewClipToBin(
			currentTapeId,
			offsetIn,
			offsetOut,
			newClipTitle,
			$(this).siblings('select').val()
		);
	});
		
	$("#clipBin li .delete,#binContents li .delete").live('click', function(event) {
		if ($(this).hasClass('disabled')) {
			return;
		}
		var btn = $(this);
		if ($(this).hasClass('disabled')) { return; }
		showConfirm("Are you sure you want to delete the clip '" + $("h5",$(this).parents('li')).text() + "'?",
			function() {
				event.stopPropagation();
				var id =  btn.parents('li').attr('id');
				if (match = id.match(/clip(\d+)/)) {
					$("#clipBin").trigger("startWaiting");
					var clipId = match[1];
					
				
					$.ajax({
						data:{
							action: 'deleteClip',
							clipId: clipId
						},
						success: function(data) {
					
							var binInfo = $.parseJSON(data);
							showStatus("Clip Deleted");
							 btn.parents('li').remove();
							displayBin(binInfo);
							
						},
						complete: function() {
							$("#clipBin").trigger("stopWaiting");
						}
					});
				}
			}
		);
		return false;
	});
	
	$("#newBinDialog").dialog({
		autoOpen:false,
		modal:true,
		width: 350,
		resizable: false,
		open: function(event, ui) { 
			$(".ui-draggable",$(".bin .listBox")).remove();
			if ($("#txtNewBinName").val() == '') {
				$("#txtNewBinName").val('Bin ' + (numBins +1));
			}
			$("#txtNewBinName").select();
			$("#txtNewBinName").focus();
		}, 
		close: function() {
			$("#txtNewBinName").val('');
		}
	});

	$(".binSelect").live('change', function() {
		if ($(this).val() == -1) {
			return;
		} else if ($(this).val() == '') {
			showAddBinDialog(function(binName) {createBin(binName)});
		} else {
			getBin($(this).val());
		}
	});
	
	$("#binList").sortable({
		appendTo: 'body',
		helper: function(event, ui) {
			var helper = ui.clone();
			helper.addClass('dragHelper');
			helper.addClass('binSortHelper');
			helper.addClass('fromSideBar');
			$('.close', helper).remove();
			return helper;
		},
		
		tolerence: 'pointer',
		connectWith: "#binContents",
		receive: function(event, ui) {
			
			var newItemIndex =  $(".ui-draggable", $(event.target)).prevAll().length;
			$(".ui-draggable",$("#binList")).hide();
			receiveNewItem(ui.item, newItemIndex); 
		},
		update: function(event, ui) {
			if (addingItem) {return};
			sortClips(currentBinId,  ui.item.attr('id').substring('clip'.length), ui.item.prevAll().length); 
		}
	});
	
	$(".addSelected").click(function(event) {
		if ($(this).hasClass('disabled')) {
			return;
		}
		var addToBinId = $(".binSelect", $(this).parent()).val();
		addToBinId = addToBinId == -1 || addToBinId == '' ? null : addToBinId;
		addSelectedToBin(addToBinId);
	});
	
	$("#sideBar .mailBin").click(function() {
		if ($(this).hasClass('disabled')) {
			return;
		}
		var binId = $(this).attr('id').substring('mailBin'.length);
		showMailBinDialog(binId);		
	});

	$("#clipBin li").live('click', function(event) {
		if ($(event.target).hasClass('close')) {
			return;
		}
			
		var clipId=$(this).attr('id').substring("clip".length);
		currentClipId = clipId;
		showClip(clipId,true,false,false);
	
	});
	
	$(".videoPlayer.clip .nextTape").live('click', function() {
		if ($(this).hasClass('disabled')) { return; }
		if ($("#binList li.displayed").length) {
			$('#binList li.displayed').next().trigger('click');
		} else {
			$('div.img',$('#binContents li.displayed').next()).trigger('click');
		}
	});
	
	$(".videoPlayer.clip .prevTape").live('click', function() {
		if ($(this).hasClass('disabled')) { return; }
		if ($("#binList li.displayed").length) {
			$('#binList li.displayed').prev().trigger('click');
		} else {
			$('div.img',$('#binContents li.displayed').prev()).trigger('click');
		}
	});
	
	$(".addNewBin").click(function() {
		var redirect = $(this).hasClass('redirect');
		showAddBinDialog(function(binName) {createBin(binName, redirect)});
	});
	
	$(".contactResearcherBinPage, .contactResearcherBin").click(function() {
		if ($(this).hasClass('disabled')) {
			return;
		}
		showContactResearcherBinDialog(currentBinId);
	});
	
	$(".dragHelper").live('mousemove', function(event) {
		var pos = {x: event.pageX, y:event.pageY};
		if (inElement(pos, $("#clipBin"))) {
			if ($(this).hasClass('fromSideBar')) {
				$(this).css('cursor', 'move');
			}else {
				$(this).css('cursor', 'copy');
			}
		} else if( inElement(pos, $("#clipBin"))) {
			if ($(this).hasClass('fromBinContents')) {
				$(this).css('cursor', 'move');
			} else {
				$(this).css('cursor', 'copy');
			}
		} else {
			$(this).css("cursor", 'no-drop');
		}
	});
	
	$("#clipBin li .close").live('click', function() {
		if ($(this).hasClass('disabled')) {
			return;
		}
		var clipId = $(this).parents('li').attr('id').substring('clip'.length);
		var title = $(this).parents('li').attr('title');
			
		showConfirm('Are you sure you want to delete the clip "' + title + '"?',
		function() {
			$.ajax({
				data: {
					action: 'deleteClip',
					clipId: clipId
				},
				success: function(data) {
					var binInfo = $.parseJSON(data);
					displayBin(binInfo);
					if (currentBinId == displayBinId) {
						displayBinDetails(binInfo);
					} 
				}
			});
		});
	});
	
	$(".dragHelper").live('mouseup', function (event){
		var pos = {x: event.pageX, y:event.pageY};
		if (inElement(pos, $("#clipBin")) && !inElement(pos, $("#binList"))) {
			var id = $(this).attr('id').substring('drag'.length);
			receiveNewItem($('#' + id), '');
			$(this).remove();
		}
	});
		
	$(".buyMinutes").click(function() {
			location.href = 'buyMinutes';
	});
});

