<link rel="stylesheet" type="text/css" href="../javascript/jquery/themes/cupertino/ui.all.css" />
{% import "macros/forms.tpl" as forms %}
<div class="row">
	<div class="col-sm-12">
		<h4 class="page-title">{% lang 'View' %} <a href="#" style="color:#005FA3" id="ViewsMenuButton" class="PopDownMenu">{{ ViewName|safe }} <img width="8" height="5" src="images/arrow_blue.gif" border="0" /></a></h4>
		<p>{{ ProductIntro|safe }}</p>
		<div id="ProductsStatus">{{ Message|safe }}</div>
		<div id="ViewsMenu" class="DropShadow DropDownMenu" style="display: none; width:200px">
			<ul>
				{{ CustomSearchOptions|safe }}
			</ul>
			<hr />
			<ul>
				<li><a href="index.php?ToDo=createProductView" style="background-image:url('images/view_add.gif'); background-repeat:no-repeat; background-position:5px 5px; padding-left:28px">{% lang 'CreateANewView' %}</a></li>
				<li style="display:{{ HideDeleteViewLink|safe }}"><a onclick="$('#ViewsMenu').hide(); confirm_delete_custom_search('{{ CustomSearchId|safe }}')" href="javascript:void(0)" style="background-image:url('images/view_del.gif'); background-repeat:no-repeat; background-position:5px 5px; padding-left:28px">{% lang 'DeleteThisView' %}</a></li>
			</ul>
		</div>
	</div>
</div>

<div class="row">
	<div class="col-sm-6">
		<input type="button" name="IndexAddButton" value="{% lang 'AddProduct' %}..." id="IndexCreateButton" class="btn btn-primary" onclick="document.location.href='index.php?ToDo=addProduct'" />
		{% lang 'Or' %}
		<select name="bulk" class="form-control" style="width: auto; display: inline;">
			<option value="">{% lang 'ChooseAnAction' %}</option>
			<option value="delete" id="IndexDeleteButton" {{ DisableDelete|safe }}>{% lang 'DeleteSelected' %}</option>
			<option value="edit" id="IndexBulkButton" style="display: {{ HideBulkExportButton|safe }}" {{ DisableBulkEdit|safe }}>{% lang 'BulkEditProducts' %}</option>
			<option value="export" id="IndexExportButton" style="display: {{ HideExport|safe }}" {{ DisableExport|safe }}>{% lang 'ExportProducts' %}</option>
			{% if ShowListOnEbay %}
			<option value="ebay" id="IndexEbayButton">{% lang 'ListOnEbay' %}
			{% endif %}
			{% if shoppingComparisonModules | length %}
			<option value="shoppingComparison" {{ DisableExport|safe }}>{% lang 'ShoppingComparisonBulkSelectTitle' %}</option>
			{% endif %}
		</select>
		<button type="button" id="optionGo" class="btn btn-primary">{% lang 'Go' %}</button>
	</div>

	<div class="col-sm-6">
		<div style="display:{{ DisplaySearch|safe }}">
			<form action="index.php?ToDo=viewProducts{{ SortURL|safe }}" method="get" class="pull-right" onsubmit="return ValidateForm(CheckSearchForm)">
				{{ forms.hiddenInputs(['ToDo':'viewProducts'] + queryParams, ['searchQuery']) }}
				<input name="searchQuery" id="searchQuery" type="text" value="{{ EscapedQuery|safe }}" class="form-control" style="display: inline; width: auto;" class="Procurar Produtos" />&nbsp;
				<button type="submit" class="btn btn-primary"><i class="fa fa-search"></i></button>
				<p><small>
				<a href="index.php?ToDo=searchProducts">{% lang 'AdvancedSearch' %}</a>
				<span style="display:{{ HideClearResults|safe }}">| <a id="SearchClearButton" href="index.php?ToDo=viewProducts">{% lang 'ClearResults' %}</a></span></small></p>
			</form>
		</div>
	</div>
</div>

<div class="row" style="display: {{ DisplayGrid|safe }}">
	<div class="col-sm-12">
		<form name="frmProducts" id="frmProducts" method="post" action="index.php?ToDo=deleteProducts">
			<div class="GridContainer">
				{{ ProductDataGrid|safe }}
			</div>
		</form>
	</div>
</div>

<div id="invDiv" class="StockList" style="display:none"></div>

<div id="shoppingComparisonModal" title="{% lang 'ShoppingComparisonProductModalTitle' %}" style="display: none;">
	<form action="index.php?ToDo=bulkSaveProductShoppingComparisonFeeds" method="post">
		<p class="description"></p>

		<div style=" margin-bottom: 10px;">
			<select name="comparisons[]" class="Field250 ISSelectReplacement" multiple="multiple" style="height: 108px;width:350px;">
				{% for module in shoppingComparisonModules %}
				<option value="{{ module.getId() }}">{{ module.getName() }}</option>
				{% endfor %}
			</select>
			<div style="clear: both;"></div>
		</div>
	</form>
</div>

<script type="text/javascript" src="../javascript/jquery/plugins/jquery.form.js"></script>
<script type="text/javascript">
	var tok = "{{ AuthToken|safe }}";
	var inventory_product_id = 0;
	var action = "";
	var total_stock_units = 0;
	var Interspire_Ebay_ListProductsMachine = null;
	
	function ExportProducts() {
		document.getElementById("frmProducts").action = "{{ ExportAction|safe }}";
		document.getElementById("frmProducts").submit();
	}
	
	var searchId = {{ CustomSearchId }};
	var searchQuery = "{{ EscapedQuery|safe }}";

	function CheckSearchForm() {
		var query = document.getElementById('searchQuery');

		if (query.value == '') {
			alert("{% lang 'ChooseFilterOrEnterSearchTerm' %}");
			return false;
		}

		return true;
	}

	function ListProductsOnEbay() {
		var productOptions = {};
		productOptions.productIds = $("#frmProducts").serialize();
		productOptions.searchId = searchId;
		productOptions.searchQuery = searchQuery;

		Interspire_Ebay_ListProductsMachine.start({productOptions: productOptions});
	}

	function ConfirmDeleteSelected() {
		var fp = document.getElementById('frmProducts').elements;
		var c  = 0;

		for (i = 0; i < fp.length; i++) {
			if(fp[i].type == 'checkbox' && fp[i].checked)
				c++;
		}

		if (c > 0){
			if (confirm("{% lang 'ConfirmDeleteProducts' %}")) {
				document.getElementById('frmProducts').submit();
			}
		} else {
			alert("{% lang 'ChooseProduct' %}");
		}
	}

	function ToggleDeleteBoxes(Status) {
		var fp = document.getElementById('frmProducts').elements;

		for (i = 0; i < fp.length; i++) {
			fp[i].checked = Status;
		}
	}

	function ShowStock(id, InventoryType, VariationId) {
		var tr  = document.getElementById('tr' + id);
		var trQ = document.getElementById('trQ' + id);
		var tdQ = document.getElementById('tdQ' + id);
		var img = document.getElementById('expand' + id);

		if (img.src.indexOf('plus.gif') > -1) {
			img.src = 'images/minus.gif';

			for (i = 0; i < tr.childNodes.length; i++) {
				if (tr.childNodes[i].style != null) {
					tr.childNodes[i].style.backgroundColor = "#dbf3d1";
				}
			}

			$(trQ).find('.QuickView').load(
				'remote.php?w=inventoryLevels&p='
				+ id
				+ '&i='
				+ InventoryType
				+ '&v='
				+ VariationId
				+ '&t='
				+ tok
				, {
					'cache' : false
				}
				, function() {
					trQ.style.display = '';
				}
			);
		} else {
			img.src = "images/plus.gif";

			for (i = 0; i < tr.childNodes.length; i++) {
				if (tr.childNodes[i].style != null) {
					tr.childNodes[i].style.backgroundColor = '';
				}
			}

			trQ.style.display = 'none';
		}
	}

	function UpdateStockLevel(ProductId, InventoryType) {
		var loading = document.getElementById('loading' + ProductId);
		inventory_product_id = ProductId;

		if (InventoryType == 0) {
			var stock_level = document.getElementById('stock_level_' + ProductId);
			var stock_level_notify = document.getElementById('stock_level_notify_' + ProductId);

			if (isNaN(stock_level.value) || stock_level.value == '') {
				alert("{% lang 'EnterValidStockLevel' %}");
				stock_level.focus();
				stock_level.select();
			} else if(isNaN(stock_level_notify.value) || stock_level_notify.value == '') {
				alert("{% lang 'EnterValidStockLevel' %}");
				stock_level_notify.focus();
				stock_level_notify.select();
			} else {
				loading.src = 'images/ajax-loader.gif';
				total_stock_units = stock_level.value;
				action = 'update_inventory_levels';

				DoCallback('w=updatePerProductInventoryLevels&p=' + ProductId + '&c=' + stock_level.value + '&l=' + stock_level_notify.value + '&t=' + tok);
			}
		} else if(InventoryType == 1) {
			var fp = document.getElementById('frmProducts').elements;
			var c = 0;
			var is_error = false;
			var update_data = '';
			total_stock_units = 0;

			for (i = 0; i < fp.length; i++) {
				if (fp[i].id.indexOf('stock_level_' + ProductId) > -1 || fp[i].id.indexOf('stock_level_notify_' + ProductId) > -1) {
					if (isNaN(fp[i].value) || fp[i].value == '') {
						alert("{% lang 'EnterValidStockLevel' %}");
						fp[i].focus();
						fp[i].select();
						is_error = true;

						break;
					} else {
						update_data = update_data + fp[i].id + '=' + fp[i].value + '&';
						if (fp[i].id.indexOf('stock_level_notify') == -1) {
							total_stock_units = total_stock_units + parseInt(fp[i].value);
						}
					}
				}
			}

			if (!is_error) {
				loading.src = 'images/ajax-loader.gif';
				action = 'update_inventory_levels';
				DoCallback('w=updatePerOptionInventoryLevels&i=' + escape(update_data) + '&t=' + tok);
			}
		}
	}

	function show_inventory_levels(result) {
		var inventory_info = document.getElementById('StockLevelInfo' + inventory_product_id);
		inventory_info.innerHTML = result;
	}

	function update_inventory_levels(result) {
		var loading = document.getElementById('loading' + inventory_product_id);
		var instock_cell = document.getElementById('InStock' + inventory_product_id);
		loading.src = 'images/ajax-blank.gif';

		if (result == '1') {
			display_success('ProductsStatus', "{% lang 'InventoryLevelsUpdated' %}".replace('%d', inventory_product_id));
		} else {
			display_error('ProductsStatus', "{% lang 'InventoryLevelsUpdateFailed' %}");
		}
	}

	function ProcessData(html) {
		ret = html;

		if(action == 'get_inventory_levels') {
			show_inventory_levels(ret);
		} else if(action == 'update_inventory_levels') {
			update_inventory_levels(ret);
		}
	}

	function confirm_delete_custom_search(search_id) {
		if (confirm("{% lang 'ConfirmDeleteCustomSearch' %}")) {
			document.location.href = 'index.php?ToDo=deleteCustomProductSearch&searchId=' + search_id;
		}
	}

	function quickToggle(element, what) {
		$.ajax({
			url: element.href + '&ajax=1',
			success: function(response) {
				if(response) {
					if(element.childNodes.length == 1 && element.childNodes[0].tagName == "IMG") {
						var image = element.childNodes[0];
						if(image.src.indexOf('tick') != -1) {
							element.href = element.href.replace(what+'=0', what+'=1');
							image.src = image.src.replace('tick', 'cross');
						} else {
							element.href = element.href.replace(what+'=1', what+'=0');
							image.src = image.src.replace('cross', 'tick');
						}
					}
				}
			}
		});
	}

	function BulkEditSelected() {
		var count = $('#frmProducts input:checked').length;
		if (count > 0) {
			document.getElementById('frmProducts').action = 'index.php?ToDo=bulkEditProducts';
			document.getElementById('frmProducts').submit();
		} else {
			alert("{% lang 'ChooseProductToBulkEdit' %}");
		}
	}

	function getSelectedProducts() {
		return getAllProducts().filter(':checked');
	}

	function getAllProducts() {
		return $('#frmProducts .GridRow > td:first-child > :checkbox');
	}

	function getSelectedOrAllProducts() {
		var products = getSelectedProducts();

		if (!products.length) {
			products = getAllProducts();
		}

		return products;
	}

	function toggleShoppingComparisonFeeds() {
		var comparison = $('#shoppingComparisonModal');
		var buttons    = '<button class="FormButton" type="button" onclick="jQuery.iModal.close();" style="float: left;">{% lang 'ShoppingComparisonProductModalCancel' %}</button>';
			buttons   += '<button class="FormButton" type="submit" onclick="return toggleShoppingComparisonSubmit();" style="font-weight:bold;">{% lang 'ShoppingComparisonProductModalSave' %}</button>';

		comparison.find('.description').html("{% lang 'ShoppingComparisonProductModalDescription' %}".replace(':numberOfProducts', getSelectedOrAllProducts().length));

		$.iModal({
			title   : comparison.attr('title'),
			data    : comparison.html(),
			buttons : buttons,
			width	: 385
		});
	}

	function toggleShoppingComparisonSubmit() {
		var products = getSelectedProducts();
		var uncheck  = false;

		if (!products.length) {
			uncheck = true;
			products = getAllProducts();
			products.attr('checked', 'checked');
		}

		var fields = $('.ModalContent form select').add(products);
		var serial = fields.serialize();

		if (uncheck) {
			products.removeAttr('checked');
		}

		$.post('index.php?ToDo=bulkSaveProductShoppingComparisonFeeds', serial, function(result) {
			if (result == 1) {
				$.iModal.close();

				display_success('ProductsStatus', "{% lang 'ShoppingComparisonProductMessageSuccess' %}".replace(':numberOfProducts', products.length));
			} else {
				display_error('ProductsStatus', "{% lang 'ShoppingComparisonProductMessageError' %}".replace(':numberOfProducts', products.length));
			}
		});

		return false;
	}

	$(document).ready(function() {
		if ("{{ HideThumbnailField|safe }}" == '1') {
			$('td.ImageField').css('display', 'none');
		}

		$('#optionGo').click(function() {
			var sel = $('select[name="bulk"]');
			var raw = sel.get(0);
			var val = sel.val();

			switch (val) {
				case 'delete':
					ConfirmDeleteSelected.apply(raw);
					break;
				case 'edit':
					BulkEditSelected.apply(raw);
					break;
				case 'export':
					ExportProducts.apply(raw);
					break;
				case 'ebay':
					ListProductsOnEbay.apply(raw);
					break;
				case 'shoppingComparison':
					toggleShoppingComparisonFeeds.apply(raw);
					break;
			}
			sel.val('');
		});
	});
</script>
<script type="text/javascript" src="../javascript/jquery/plugins/disabled/jquery.disabled.js"></script>
<script type="text/javascript" src="../javascript/fsm.js"></script>
<script type="text/javascript" src="script/ebay.listproducts.js"></script>