/* ---- NEW RELEASE ---- */
function removeFromNewRelease(titlenum, elt){
	ajax('/movie/remove-from-new-release/titlenum/' + titlenum, null, function(json) {
		if (json.status == 'success') {
			$('#newRelease' + titlenum).hide('normal');
		}
	});
}

/* ---- BROWSE ---- */
function populateTable(json) {
	var tbody = $('#browseTable tbody');
	if (json.html == null)
		tbody.html("<tr><td colspan='5'>No results</td></tr>");
	else tbody.html(json.html);
	
	function createLink(name, offset) {
		var link = $(document.createElement('a'));
		link.attr('href', '#');
		link.html(name);
		link.click(function() {
			MovieSearch.setOffset(offset).searchLatest();
			return false;
		});
		return link;
	}
	var offset = parseInt(MovieSearch.getOffset());
	var limit = parseInt(MovieSearch.getLimit());
	
	// next
	if (offset + limit < json.total) {
		var next = createLink('next', offset + limit);
		var last = createLink('last', json.total - limit);
	}
	// previous
	if (offset - limit >= 0) {
		var prev = createLink('previous', offset - limit);
	}
	var navCell = $('#browseTable tfoot tr.navigation div.links');
	navCell.empty();
	navCell.append(last);
	navCell.append(next);
	navCell.append(prev);
	
	$('#browseTable tfoot tr.navigation div.total').html('Total Movies: ' + json.total);
}
function preSearch() {
	var tbody = $('#browseTable tbody');
	tbody.empty();
	tbody.html("<tr><td colspan='6'>Populating List...</td></tr>");
	$('#browseTable tfoot tr.navigation div.total').html('Total Movies: Calculating...');
}

function selectForSale(elt){
	var elt = $(elt);
	if (elt.attr('checked')) {
		MovieSearch.addFilter('for_sale', true).searchLatest();
	}
	else MovieSearch.removeFilter('for_sale').searchLatest();
}

function selectGenre(elt) {
	if (elt.value) {
		MovieSearch.addFilter('shelf', elt.value);
		MovieSearch.removeFilter('sub_shelf');
		ajax('/movie/get-subcategory/genre/' + elt.value, null, updateSubCategory);
	}
	else {
		$('#subgenre').fadeOut('fast');
		$('#subsubgenre').fadeOut('fast');
		MovieSearch.removeFilter('shelf');
		MovieSearch.removeFilter('sub_shelf');
	}
	MovieSearch.searchLatest();
}
function updateSubCategory(json) {
	if (json.length != 0) {
		var subCatElt = $('#subgenre');
		subCatElt.empty();
		var newOption = $(document.createElement('option'));
		newOption.attr('value', '');
		newOption.html('Filter by category');
		subCatElt.append(newOption);
		for (var i in json) {
			var display = json[i];
			var value = i;
			var newOption = $(document.createElement('option'));
			newOption.attr('value', value);
			newOption.html(display);
			subCatElt.append(newOption);
		}
		subCatElt.fadeIn('fast');
	}
	else {
		$('#subgenre').fadeOut('fast');
	}
}

function selectSubGenre(elt) {
	if (elt.value) {
		MovieSearch.addFilter('sub_shelf', elt.value);
		ajax('/movie/get-subsubcategory/sub/' + elt.value, null, updateSubSubCategory);
	}
	else {
		$('#subsubgenre').fadeOut('fast');
		MovieSearch.removeFilter('sub_shelf');
	}
	MovieSearch.searchLatest();
}
function updateSubSubCategory(json) {
	if (json.length != 0) {
		var subCatElt = $('#subsubgenre');
		subCatElt.empty();
		var newOption = $(document.createElement('option'));
		newOption.attr('value', '');
		newOption.html('Filter by subcategory');
		subCatElt.append(newOption);
		for(var i in json) {
			var display = json[i];
			var value = i;
			var newOption = $(document.createElement('option'));
			newOption.attr('value', value);
			newOption.html(display);
			subCatElt.append(newOption);
		}
		subCatElt.fadeIn('fast');
	}
	else {
		$('#subsubgenre').fadeOut('fast');
	}
}
function selectSubSubGenre(elt) {
	if (elt.value) {
		MovieSearch.addFilter('sub_shelf', elt.value);
	}
	else {
		MovieSearch.addFilter('sub_shelf', $('#subgenre').val());
	}
	MovieSearch.searchLatest();
}

function getMovieProfile(titlenum) {
	ajax('/movie/index/titlenum/' + titlenum, null, displayMovieProfile);
}

function displayMovieProfile(json){
	if (json.html) {
		$('#movie_profile').html(json.html);
	}
}

/* ---- MOVIE ---- */
function addToNewRelease(id){
	ajax('/movie/add-to-new-release/titlenum/' + id, null, function(json){
		if (json.status == 'success') {
			$('#addnewrelease').hide();
			$('#alreadynewrelease').fadeIn('normal');
		}
	});
}

function rentMovie(id){
	ajax('/bin/rent-movie/id/' + id, null, rentMovieResponse);
}
function rentMovieResponse(json){
	if (json.error) {
		alert(json.error);
		return;
	}
	else if (json.packages) {
		$('#packages_content').html(json.packages);
		$('#packages').fadeIn('normal');
	}
	$('#rent_movie_button').replaceWith("<div class='rent'><img src='/images/inbin.gif' title='this item for rent is already in your bin'/></div>");
	$('#bin_image').attr('src', '/images/bin_full.jpg');
}
function buyMovie(id){
	ajax('/bin/buy-movie/id/' + id, null, function(json){
		if (json.error) {
			alert(json.error);
			return;
		}
		$('#bin_image').attr('src', '/images/bin_full.jpg');
		$('#buy_movie_button').replaceWith("<div class='rent'><img src='/images/inbin.gif' title='this item for sale is already in your bin'/></div>");
	});
}

/* ---- PACKAGE ---- */ 
function addPackage(id){
	ajax('/bin/add-package/id/' + id, null, function(json){
		if (json.error) {
			alert(json.error);
			return;
		}
		$('#bin_image').attr('src', '/images/bin_full.jpg');
		
		var bin = $('#bin');
		if(bin) {
			ajax('/bin/view', null, function(response) {
				$('#content').html(response.html);
			});
		}
	});
}

function buyPackage() {
	ajax('/package', null, function(json) {
		$('#packages_content').html(json.html);
		$('#packages').fadeIn('normal');
	});
}

/* ---- BIN ---- */
function toggleCredit(elt, id, packageInfo){
	var elt = $(elt);
	var late_fee = $('#late_fee_' + id);
	var rental_period = $('#rental_period_' + id);
	
	if (elt.attr('toggled') == 'false') {
			elt.attr('toggled', 'true')
			elt.html('$' + packageInfo.price + '.00');
			late_fee.html('$' + packageInfo.late_fee + '.00');
			rental_period.html(packageInfo.rental_period);
			$('#shipping_pickup_rent_' + id).hide();
			$('#shipping_link_rent_' + id).show();
			$('#rental_' + id + " input[value=mail]").attr('checked', 'checked');
			updateTotalCredits(-1)
	}
	else {
		elt.attr('toggled', 'false')
		elt.html(elt.attr('default'));
		late_fee.html(late_fee.attr('default'));
		rental_period.html(rental_period.attr('default'));
		$('#shipping_pickup_rent_' + id).show();
		$('#shipping_link_rent_' + id).hide();
		$('#rental_' + id + ' input').removeAttr('checked');
		updateTotalCredits(1);
	}
}
function updateTotalCredits(amount){
	var elt = $('#total_credits');
	var total = parseInt(elt.html());
	if (total + amount >= 0)
		elt.html((total + amount) + '');
	if (total + amount > 0) {
		//enable links
		$('#rentals table tr td.price a[toggled=false]').each(function() {
			$(this).show();
			$('#rental_price_' + $(this).attr('titlenum')).hide();
		});
	}
	else {
		// disable links
		$('#rentals table tr td.price a[toggled=false]').each(function() {
			$(this).hide();
			$('#rental_price_' + $(this).attr('titlenum')).show();
		});
	}
}
function changeShipping(elt, id, buyRent){
	var elt = $(elt);
	var value = elt.val();
	if (value == 'pick_up') {
		$('#shipping_link_' + buyRent + '_' + id).html('Pick up');
	}
	else if (value == 'mail') {
		$('#shipping_link_' + buyRent + '_' + id).html('Mail');
	}
	else if (value == 'standard') {
		$('#shipping_link_' + buyRent + '_' + id).html('Standard');
	}
	else if (value == 'priority') {
		$('#shipping_link_' + buyRent + '_' + id).html('Priority');
	}
	if (buyRent == 'buy') {
		updateShippingCost(id, parseFloat(elt.attr('price')));
	}
	$('#shipping_option_' + buyRent + '_' + id).fadeOut('fast');
}
function updateShippingCost(id, shippingCost){
	var elt = $('#sale_price_' + id);
	var original = parseFloat(elt.attr('default'));
	elt.html('$' + (original + shippingCost).toFixed(2));
}

/* ---- ADMIN CHECKOUT  ---- */
function clearMovieId(id){
	$('#movie_id_' + id).val('');
}
function clearCancel(id) {
	$('#cancel_' + id).removeAttr('checked');
}

function checkInvoice(id){
	var count = -5; // number of blank text boxes = 5 (for adding an invoice item)
	var ok = 0;
	$('#items_' + id + ' :text').each(function() {
		var text = $(this);
		var checkbox = $('#cancel_' + text.attr('invoice_item_id'));
		if (text.val() || checkbox.attr('checked')) {
			ok++;
		}
		count++;
	});
	var radio = 0;
	total_radio = 0;
	$('#items_' + id + ' :radio').each(function() {
		if ($(this).attr('checked'))
			radio++;
		total_radio++;
	});
//	alert('ok='+ok+', count='+count+', radio='+radio+', total_radio='+total_radio);
	if (total_radio / 2 == radio && ok == count) {
		$('#span_requirements_' + id).hide();
		$('#process_' + id).fadeIn('fast');
	}
	else {
		$('#process_' + id).hide();
		$('#span_requirements_' + id).fadeIn('fast');
	}
}

function deleteInvoice(id) {
	if(confirm('This invoice and all containing invoice items will be deleted. Do you want do continue?')) {
		ajax('/invoice/delete/id/'+id, null, function(response) {
			// TODO: Nested duplicated elements need to be removed
			$('#invoice_'+id).fadeOut();
		});
	}
}

function addInvoiceItem(id) {
	var form = $('#add-invoice-item-'+id+' > td > input').serialize();
	ajax('/invoice/add-item/id/'+id, form, function(response) {
		// TODO: Nested duplicated elements need to be removed
		$('#invoice_'+id).html(response.html);
	});
}
function updateInvoiceItem(id) {
	var form = $('#update-invoice-item-'+id+' > td > input').serialize();
	ajax('/invoice/update-item/id/'+id, form, function(response) {
		// TODO: Nested duplicated elements need to be removed
		$('#invoice_'+response.invoiceId).html(response.html);
	});
}
function deleteInvoiceItem(id) {
	if(confirm('This invoice item will be deleted. Do you want do continue?')) {
		ajax('/invoice/delete-item/id/'+id, null, function(response) {
			// TODO: Nested duplicated elements need to be removed
			$('#invoice_'+response.invoiceId).html(response.html);
		});
	}
}

function processInvoice(id) {
	var form = $('#items_' + id + ' :input').serialize();
	ajax('/invoice/process/id/' + id, form, paymentResponse);
}
function paymentResponse(json){
	if (json.error) {
		alert(json.error);
	}
	else if (json.status == 'cancelled') {
		NEWORDERS--;
		$('#invoice_' + json.invoice_id).fadeOut('fast');
	}
	else if (json.status == 'success' || json.status == 'payment error') {
		NEWORDERS--;
		$('#invoice_' + json.invoice_id).replaceWith(json.html);
	}
}

/* ---- Rentals ---- */
function submitRentalStatus(elt) {
	var table = $(elt).parent().parent().parent().parent();
	var form = table.find(":input").serialize();
	ajax('/rental/update', form, function(json) {
		if (json.error) {
			alert(json.error);
		}
		else if (json.html) {
			table.replaceWith(json.html);
			var submit = table.find('tfoot span');
			submit.fadeIn('fast');
			setTimeout(function() {
				submit.fadeOut('slow');
			}, 1000);
		}
	});
}

function searchRentals(elt) {
	var elt = $(elt);
	$('#rentals tr[movie_id]').each (function() {
		var tr = $(this);

		if (tr.attr('movie_id').indexOf(elt.val()) == -1) {
			tr.css('display', 'none');
		}
		else {
			tr.css('display', '');
		}
	});
}

function faq(id) {
	var element = document.getElementById(id);
	if (element.style.display == "none")
		element.style.display = "block";
	else element.style.display = "none";
}

function onActionChanged(element, id) {
	if(element.value == 'late') {
		$('#late-fee-'+id).show('medium');
	}
	else {
		$('#late-fee-'+id).hide('medium');
	}
}