// this is a PCC shopping list plug-in for jQuery
(function($) {
  // save the shopping list to user's Drupal profile if logged in
	$.fn.updateList = function(action, item_id, desc, dept, notes, qty, valid, updateCallBack) {
		if (!checkCookiesEnabled(false)) return;
		$.post("/shoppinglist/actions.php", { action: action, item_id: item_id, desc: desc, dept: dept, notes: notes, qty: qty, valid: valid }, function(){ if (updateCallBack && typeof updateCallBack == 'function') updateCallBack.call(this); });
  };
  // get shopping list
	$.fn.getList = function() {
		if (!checkCookiesEnabled(false)) return;
		name = 'default';
		$.post("/shoppinglist/actions.php", { action: 'getList' }, function(data){
			var list = eval('(' + data + ')');
			$.each(list[name], function(i, val) {
				$('#' + i + ' td.add').html('<img src="/images/products/list/btn_check.gif" alt="add" width="15" height="16" border="0" />');
			});
		});
  };
  // get shopping list for ingredients
	$.fn.getListRecipe = function() {
		if (!checkCookiesEnabled(false)) return;
		name = 'default';
		$.post("/shoppinglist/actions.php", { action: 'getList' }, function(data){
			var list = eval('(' + data + ')');
			$.each(list[name], function(i, val) {
				$('#' + i + ' a img').replaceWith('<img src="/images/products/list/btn_check.gif" alt="add" width="15" height="16" border="0" />');
				$('#' + i + ' a').removeClass('add').show();
			});
		});
  };
  // display message
	$.fn.listMsg = function() {
		if (!checkCookiesEnabled(false)) return;
		$('#list-msg').text('Changes saved');
		$('#list-msg').fadeOut(1000, function () {
			$('#list-msg').show();
			$('#list-msg').html('&nbsp;');
		});
  };
  // update item from shopping list
	$.fn.updateItem = function() {
		if (!checkCookiesEnabled(true)) return;
		var item_id = $(this).parent().parent().attr('id');
		if ($(this).parent().parent().attr('class') == 'notes') item_id = $(this).parent().parent().prev().attr('id');
		var id = '#' + item_id;
		var desc = $(id + ' td:first span').text();
		desc = escape(desc);
		var dept = $(id + ' td:eq(1) :selected').val();
		if (!dept) dept = $(id + ' td:eq(1)').text();
		var qty = $(id + ' td:eq(2) :input').val();
		var notes = $('#notes-' + item_id).val();
		notes = escape(notes);
		$(this).updateList('updateItem', item_id, desc, dept, notes, qty);
		$(this).listMsg();
  };
  // add item from product search database to shopping list
	$.fn.addItem = function() {
		if (!checkCookiesEnabled(true)) return;
		var item_id = $(this).parent().attr('id');
		var id = '#' + item_id;
		var brand = $(id + ' td:first').text();
		var desc = $(id + ' td:eq(1)').text();
		if (brand) desc = brand + ' ' + desc;
		desc = escape(desc);
		var dept = $(id + ' td:eq(2)').attr("title");
		$(this).updateList('addItem', item_id, desc, dept, '', '', '', function(){ $(this).updateCount(); });
		$(this).html('<img src="/images/products/list/btn_check.gif" alt="add" width="15" height="16" border="0" />');
		addEvent('Product database', desc);
  };
  // add item from bulk search results to shopping list
	$.fn.addBulkResults = function() {
		if (!checkCookiesEnabled(true)) return;
		var item_id = $(this).parent().attr('id');
		var id = '#' + item_id;
		var brand = $(id + ' td:eq(1)').text();
		var desc = $(id + ' td:eq(2)').text();
		if (brand) desc = brand + ' ' + desc;
		desc = escape(desc);
		var dept = $(id + ' td:eq(3)').attr("title");
		$(this).updateList('addItem', item_id, desc, dept, '', '', '', function(){ $(this).updateCount(); });
		$(this).html('<img src="/images/products/list/btn_check.gif" alt="add" width="15" height="16" border="0" />');
		addEvent('Bulk database results', desc);
  };
  // add item from bulk item page to shopping list
	$.fn.addBulkProduct = function(item_id) {
		if (!checkCookiesEnabled(true)) return;
		var id = '#' + item_id;
		var desc = $('#bulkBrand').text() + ' ' + $('#bulkDesc').text();
		desc = escape(desc);
		var dept = $('#bulkBin').attr("title");
		$(this).updateList('addItem', item_id, desc, dept);
		alert('Added ' + unescape(desc) + ' to shopping list');
		$(this).updateCount();
		addEvent('Bulk database product', desc);
  };
  // add item from online ad
	$.fn.addSpecial = function(item_id) {
		if (!checkCookiesEnabled(true)) return;
		$.post("/shoppinglist/actions.php", { action: 'addSpecial', special: item_id } );
		alert('Item added to your shopping list');
		$(this).updateCount();
		addEvent('Specials', item_id);
  };
  // add item from link (no item ID)
	$.fn.addItemPCC = function() {
		if (!checkCookiesEnabled(true)) return;
		var href = $(this).attr('href');
		var q = href.replace(/^.*\?/, '');
		var r = {};
		jQuery.each(q.split('&'), function(){
			var key = this.split('=')[0];
			var val = this.split('=')[1];
			r[key] = val;
		});
		if (!r['dept']) r['dept'] = ''; if (!r['notes']) r['notes'] = ''; if (!r['valid']) r['valid'] = '';
		if(r['item_id']) {
			$(this).updateList('addItem', r['item_id'], r['add'], r['dept'], r['notes'], '', r['valid']);
		} else {
			$(this).updateList('addItemPCC', '', r['add'], r['dept'], r['notes'], '', r['valid']);
		}
		alert('Item added to your shopping list');
		$(this).updateCount();
		addEvent('Custom', r['add']);
  };
  // add ingredients from recipe
	$.fn.addIngredients = function(mobile) {
    mobile = typeof(mobile) != 'undefined' ? mobile : 'y';
		if (!checkCookiesEnabled(true)) return;
		var items = '';
    $('.ingredients li').each(function (i) {
      var txt = $(this).text();
      var id = $(this).attr('id').substring(1);
      items += '<input type="checkbox" checked="checked" id="' + id + '" /> <label for="' + id + '">' + txt + '</label><br />';
    });
		var append_id = mobile == 'y' ? '#ingredients-to-list' : '#ingredients';
    $(append_id).after('<form id="recipe-add">' + items + '<input type="submit" value="Add" /> <a href="#" id="cancel-add">Cancel</a></form>');
    $('#cancel-add').click(function(){
      $('#ingredients-to-list a').show();
      $('.js-msg').remove();
      $('#recipe-add').remove();
      return false;
    });
    $('#ingredients-to-list a').hide().before('<span class="js-msg"> Select ingredients to add</span>');
    $('#recipe-add').submit(function(){
      var nid = $('.node').attr('id').substring(5);
			var desc = '';
      $('#recipe-add input:checked').each(function (i) {
        var id = $(this).attr('id');
        var href = $('#r' + id + ' a:last').attr('href');
        var q = href.replace(/^.*\?/, '');
        var r = {};
        jQuery.each(q.split('&'), function(){
          var key = this.split('=')[0];
          var val = this.split('=')[1];
          r[key] = val;
        });
       desc = desc + r['ingred'] + '|';
			 addEvent('Recipe', r['ingred']);
      });
			desc = desc.slice(0, -1);
			$.post("/shoppinglist/actions.php", { action: 'addRecipe', desc: desc, nid: nid } );
      $('.js-msg').html('<span>Shopping list updated&nbsp; </span>').css('color', 'red').fadeOut(2000, function(){ $(this).remove(); $('#ingredients-to-list a').show(); });
;
      $('#recipe-add').remove();
      return false;
    });
    return false;
  };
  // increment quantity of item in shopping list
	$.fn.increment = function() {
		if (!checkCookiesEnabled(true)) return;
		var item_id = $(this).parent().parent().attr('id');
		var id = '#' + item_id;
		var qty = $(id + ' td:eq(2) :input').attr('value');
		if (qty.search(/^[0-9]/) >= 0 && qty.search(/[0-9]\/[0-9]/) < 0) {
			var txt = '';
			var qty_current = parseFloat(qty);
			myregexp = new RegExp(qty_current);
			if (qty.search(/[^0-9]/) >= 0) txt = qty.replace(myregexp, '');
			var qty_new = qty_current + 1;
			$(this).updateList('increment', item_id);
			$(id + ' td:eq(2) :input').attr('value', qty_new + txt);
			$(this).listMsg();
		}
  };
  // decrement quantity of item in shopping list
	$.fn.decrement = function() {
		if (!checkCookiesEnabled(true)) return;
		var item_id = $(this).parent().parent().attr('id');
		var id = '#' + item_id;
		var desc = $(id + ' td:eq(0)').text();
		var qty = $(id + ' td:eq(2) :input').attr('value');
		if (qty.search(/^[0-9]/) >= 0 && qty.search(/[0-9]\/[0-9]/) < 0) {
			var txt = '';
			var qty_current = parseFloat(qty);
			myregexp = new RegExp(qty_current);
			if (qty.search(/[^0-9]/) >= 0) txt = qty.replace(myregexp, '');
			var qty_new = qty_current - 1;
			if (qty_new <= 0) {
				if (confirm('Remove ' + desc + ' from your list?')) {
					$(id).remove();
					$(this).updateList('decrement', item_id);
					$(this).listMsg();
				}
			} else if (qty_new > 0) {
				$(id + ' td:eq(2) :input').attr('value', qty_new + txt);
				$(this).updateList('decrement', item_id);
				$(this).listMsg();
			}
		}
  };
  // remove a single item from shopping list
	$.fn.removeOne = function() {
		if (!checkCookiesEnabled(true)) return;
		var item_id = $(this).parent().parent().attr('id');
		var id = '#' + item_id;
		var desc = $(id + ' td:eq(0)').text();
		if (confirm('Remove ' + desc + ' from your list?')) {
			$(id).remove();
			$(this).updateList('removeOne', item_id);
		}
		$(this).listMsg();
  };
  // remove all items from shopping list
	$.fn.removeAll = function() {
		if (!checkCookiesEnabled(true)) return;
		if (confirm('Are you sure you want to remove all items?')) {
			$(this).updateList('removeAll');
			$('#shopping-list tbody tr').remove();
		}
  };
  // update count of items in shopping list
	$.fn.updateCount = function() {
		if (!checkCookiesEnabled(false)) return;
		var txt = 'Your shopping list is empty';
		$.post(
			'/shoppinglist/actions.php',
			{ action: 'countItems' },
			function(data){
				count = data;
				if (count == 1) {
					txt = '<span>1</span> item in your list';
				} else {
					txt = '<span>' + count + '</span> items in your list';
				}
				$('#shopping-list p.count').html(txt);
			},
			'text'
		);
  };
	
  // check if cookies are enabled
	function checkCookiesEnabled(msg) {
		if (navigator.cookieEnabled == 0) {
			if (msg) alert('Please enable browser cookies');
			return false;
		} else {
			return true;
		}
  };
	
	function addEvent(source, item) {
		if (typeof pageTracker != "undefined") {
			item = decodeURIComponent(unescape(item));
			pageTracker._trackEvent('Shopping List', source, item, 1);
		}
	}
})(jQuery);
