/* 
 * SmartCart - jQuery cart plugin 
 * Javascript File 
 
 * addapted bij matthijs@kadijk.com for aPerfectWebShop.com ...
 
 * Home Pages:
 * http://fivelist.summerhost.info
 * http://tech-laboratory.blogspot.com
 * http://techlaboratory.wordpress.com
 *  
 * Date: 05-SEP-2009
 * Version: 0.95 beta
 * 
 */
var HEMATEL = false; // set to true in page if you need special in cart images 

jQuery.fn.localize = function(stringsVar) {
	var stringRes = stringsVar || strings;
	this.find("*").contents().each(function() {
			if (typeof this.data == 'string') {
				var s = jQuery.trim(this.data);
				if (typeof s == 'string' && s.length > 0) {
					var s2 = stringRes[s];
					if (typeof s2 == 'string') {
						this.data = s2;
					}
				}
			}
			
			if (this.nodeName == "IMG") {
				// use the nodeValue instead of this.src because this.src is resolved to full path instead of the original value in the html, so it can't be known at coding time.
				var s2 = stringRes[this.attributes['src'].nodeValue];
				if (typeof s2 == 'string') {
					this.attributes['src'].nodeValue = s2;
				}
			}

			if (this.nodeName == "A") {
				// use the nodeValue instead of this.href because this.href is resolved to full path instead of the original value in the html, so it can't be known at coding time.
				var s2 = stringRes[this.attributes['href'].nodeValue];
				if (typeof s2 == 'string') {
					this.href = s2;
				}
			}
			return this;
	});
	
};

(function($) {

	$.fn.smartCart = function(options) {

		var defaults = {
    			// Most Required Options - Element Selectors 
    			itemSelector: '.scItemButton', // collection of buttons which add items to cart 
          cartListSelector: '#sc_cartlist', // element in which selected items are listed
    			subTotalSelector: '#lblTotal', // element in which subtotal shows
    			subTotalQSelector: '#lblTotalQuantity', // count ...  
          messageBox: '#NOsc_message', // element in which messages are displayed	
          // Prefix Item Attribute Selector - Required
          itemNameSelectorPrefix: '#prod_name', // combination of this data and product/item id is used to get an element in product list with the item name (can be a div/span)
          itemQuantitySelectorPrefix: '#prod_qty', // for quantity ( should be a textbox/<select>)
          itemPriceSelectorPrefix: '#prod_price',  // for price (can be a div/span)
          // Text Labels
    			removeLabel: 'regel verwijderen',		// text for the "remove" link
    			addedLabel: 'bestelling aangepast',	// text to show message when an item is added
    			removedLabel: 'bestelling aangepast',	// text to show message when an item is removed
    			emptyCartLabel: '<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>Uw winkelmandje is leeg</b> Kies het aantal te bestellen kaarten om ze in het winkelmandje te plaatsen',	// text or empty cart (can be even html)
          // Css Classes
    			selectClass: 'scProductSelect',	// css class for the <select> element
    			listClass: 'scULList',					// css class for the list ($ol)
    			listItemClass: 'scCartListItem', // css class for the <li> list items
    			listItemLabelClass: 'scListItemLabel',	// css class for the label text that in list items
    			removeClass: 'h-basketDelete',			// css class given to the "remove" link
    			highlightClass: 'scHighlight',				// css class given to the highlight <span>   
          // Other Options     	
          allow_delete: true,
    			highlight: true					// toggle highlight effect to the added item
			};

		var options = $.extend(defaults,options);

		return this.each(function(index) {  
      var scCartCont = $(this);  // a container that is wrapped around the cart
			var scItemList = $("select",scCartCont);	// the hidden select element holds the selected product list
      var scItemAnchors = $(options.itemSelector); // "add to cart" buttons
      var scCartList = $(options.cartListSelector,scCartCont); //Cart list elemetn
      var scSubtotalDisp = $(options.subTotalSelector,scCartCont); //Subtotal display element
      var scMessageBox = $(options.messageBox); //Message display element
      var lastAddedItemId = 0;
			var $ol; 	// the list that we are manipulating

			function init() {
          $ol = $("<ol></ol>").addClass(options.listClass).attr('id', options.listClass);
				  resetCartData();
				  // Add Change Event
				  scItemList.change(selectChangeEvent).addClass(options.selectClass);
          // "Add to cart" button event
				  scItemAnchors.change(addCartItemEvent); 
			}
			
			function addCartItemEvent(e) {
          var prodId   = lastAddedItemId = $(this).attr('rel');
  				var prodName = $(options.itemNameSelectorPrefix+prodId).html();          
  				var prodQty  = $(options.itemQuantitySelectorPrefix+prodId).val();
  				if(prodQty == ''){
  				  prodQty = 1;
  				}
  				if(prodQty == 0){
  				  dropListItem(prodId);
  				  $(this).parents('.scProductListItem').find('span.addedToBasket').html("niet in mandje").hide(100);

  				} else {
            var $option = $("<option></option>").text(prodName).val(prodId+"|"+prodQty).attr("selected", true); 
  				  $(scItemList).append($option).change();
  				  $(this).parents('.scProductListItem').find('span.addedToBasket').html(prodQty+"x in mandje").show(100);
  				  
            // $(options.itemQuantitySelectorPrefix+prodId).val('1');         
    		  }
    		return false;
      }
			
      function resetCartData() {
				scItemList.children("option").each(function(n) {
					var $t = $(this);
					
	        if(!$t.is(":selected")){ // make every entries in the <select> as selected
            $t.attr('selected', true);
          }
          var tmpVal = $t.val().split('|');          
          if(!$t.attr('rel')){ // set the rel if not
            $t.attr('rel',  tmpVal[0]);     
          }
					$t.attr('id', 'sc' + 'option' + n);
					var id = $t.attr('id');	
					
					if($t.html()==''){ // set the item name if not
					    var itemName =  $(options.itemNameSelectorPrefix+tmpVal[0]).html();
              $t.html(itemName);
          }

          // logic for grouping multiple item entries
          var listRel = $t.attr('rel');
          var listItems = scItemList.children("option[rel=" + $t.attr('rel') + "]"); 
          if(listItems.length>1){
            var mulPId = 0;
            var mulQty = 0;
            var tmpOption = $t;
            listItems.each(function(n) {
                var tmpRel = $(this,scItemList).attr('value');
                var tmpRelVal = tmpRel.split('|');
                mulPId = tmpRelVal[0];
                // mulQty = mulQty + (tmpRelVal[1]-0);
                // the last entered quantity overrides the previous ones !
                mulQty = (tmpRelVal[1]-0);
            });
            scItemList.children("option[rel=" + $t.attr('rel') + "]").remove();
            $t.val(mulPId+"|"+mulQty)
            scItemList.append($t); 
          }
				}); 
				try {
				  resetListItem();	
				} finally {
				  calcualteSubTotal();
				}
			}
			function resetListItem() {
				// refresh the html list 
				admin_item  = null;
				$ol.html('');
				if(scItemList.children("option").length > 1){
            scItemList.children("option").each(function(n) {
                 var tmpOpt = $(this);
        					
                  var itemVal = $(this,scItemList).val();
                  var tmp = itemVal.split('|');
                  var itemId = tmp[0];
                  var itemQty = tmp[1];
                  var itemPrice =  $(options.itemPriceSelectorPrefix+itemId).html();
                  var itemTotal = itemPrice*itemQty;
                  var itemText = '';
                  itemTotal = itemTotal.toFixed(2);
                  if( HEMATEL == true ){
                    itemText = "<img width='25px'  src='/static/HEMA/images/prod/small_"+itemId.slice(2,4)+".png'>"+tmpOpt.html().slice(0,22) + "<span><span>" + itemPrice +"</span>" + itemQty + "x</span>";
                  } else {
                    itemText = "<img width='25px'  src='/static/HEMA/images/prod/small_"+itemId+".png'>"+tmpOpt.html().slice(0,22) + "<span><span>" + itemPrice +"</span>" + itemQty + "x</span>";
                  }
                  var itemText2 = "<table width='100%'><tr><td>"+tmpOpt.html()+"</td><td width='70px'>"+itemQty+
                                 "</td><td width='130px'>"+itemTotal+"</td></tr></table>";
          				var $itemLabel = $("<a></a>")
          					.addClass(options.listItemLabelClass)
          					.html(itemText); 

          				var $removeLink = $("<a></a>")
          					.attr("href", "#")
          					.addClass(options.removeClass)
          					.prepend(options.removeLabel)
          					.click(function() { 
          						var prodId  = $(this).parent('li').attr('rel');
          						dropListItem(prodId);
          						// reset the selector to zero !
          						$(options.itemQuantitySelectorPrefix+prodId).val('0');
          						$(options.itemQuantitySelectorPrefix+prodId).parents('.scProductListItem').find('span.addedToBasket').html("niet in mandje").hide(100);

          						return false; 
          					});
          				if(itemId == 'ADMIN' || !options.allow_delete){
          				  $removeLink = $('<a href="#" class="h-basketDelete" style="display: None;">deze kan niet verwijd worden</a>');
          				}
          				var $item = $("<li></li>")
          					.attr('rel', itemId)
          					.addClass(options.listItemClass)
          					.append($itemLabel)
          					.append($removeLink)
          					.hide();

                  if(itemId != 'ADMIN'){
          				  //$ol.prepend($item); // MK: make sure the ADMIN cost stays the latest in the cart ...
          				  $ol.append($item);
          				  $(options.cartListSelector,scCartCont).append($ol);
          				  $item.show();
          				} else {
          				    if( itemPrice != undefined && itemPrice > 0){
          				      admin_item = $item;
        				      }
          				}
            });
            $(options.cartListSelector).scrollTo($('li[rel='+lastAddedItemId+']',scCartCont));
            if(options.highlight){
              $('li[rel='+lastAddedItemId+'] a',scCartCont).effect('highlight', {}, 2000);               
            }
            lastAddedItemId = 0;
            
            $('input[type="submit"]').removeAttr('disabled');
            if(admin_item != undefined){
              $ol.append(admin_item);
              $(options.cartListSelector,scCartCont).append($ol);
              admin_item.show();
            }
        
        }else{
          // Cart is empty
          $ol.html(options.emptyCartLabel);
          $('input[type="submit"]').attr('disabled','disabled');
          
        }
        
			}
			
			function selectChangeEvent(e) {
				$ol.empty();
				resetCartData();
				setHighlight(options.addedLabel);
			}

			function dropListItem(relId, highlightItem) { 
				$item = $ol.children("li[rel=" + relId + "]"); 
        $item.remove();
				scItemList.children("option[rel=" + relId + "]").remove();
        scItemList.change();
				setHighlight(options.removedLabel);
			}
			
      function calcualteSubTotal() {
        var subTotal = 0;
        var prod_count = 0;
				scItemList.children("option").each(function(n) {
					var $t = $(this);
            var tmpVal = $t.val().split('|');
            var itemId = tmpVal[0];
            var itemQty = tmpVal[1];
            prod_count += 1.0 * itemQty;
            var itemPrice =  $(options.itemPriceSelectorPrefix+itemId).html();
            subTotal += itemPrice*itemQty;     
				}); 
				subTotal = subTotal.toFixed(2);
				$(options.subTotalSelector).html(subTotal);
				prod_count -= 1;
				if( prod_count == 1){
				  count_txt = prod_count + " artikel";
				} else {
				  count_txt = prod_count + " artikelen";
				}
				$(options.subTotalQSelector).html(count_txt);
			}

      function setHighlight(label) {
				var $highlight = $(options.messageBox)
					.hide()
					.addClass(options.highlightClass)
					.html(label); 
					 
				$highlight.fadeIn("fast", function() {
					setTimeout(function() { $highlight.fadeOut("slow"); }, 2000); 
				}); 
			}
			
			// Initialize
			init();
		});
	};

})(jQuery); 

