    function calculate_total(parent,type)
    {

        var discount = parseFloat($("#f_discount").val()) / 100;
        var ot = 0;
        var savings = 0;
               $("#clubSelections b.c_price").each(function(){
                  if(type=='delete' && parent.attr('id')==$(this).parents('tr').attr('id'))
                  {}
                  else{
                      var val = $(this).html();

                      val = val.replace(/\$/,'');
                      val = val.replace(/\,/gi,'');
                      val = parseFloat(val);
                      var discountAmount = val * discount;
                      var discountPrice = val - discountAmount;
                      savings+= discountAmount;

                      ot+= parseFloat(discountPrice);
                  }
               });  //update order total
             //  console.log(ot)
               $("#cs_ot").html('$'+formatCurrency(ot)).effect("highlight",{},2000);
              if(discount > 0) $("#c_savings").html('$'+formatCurrency(savings)).effect("highlight",{},2000);
    }

    function club_selection_actions()
    {
        $("#clubSelections input").inputUpdater({
           errorMessage:'Please enter a number',
           submitPath:'clubSelectionAjaxAction.do',
           loadingImagePath:'/resources/images/2009/loading_small.gif',
           errorImagePath:'/resources/images/2009/indicator_error.gif',
           successImagePath:'/resources/images/2009/indicator_success.gif',
           actionType:'update',
           parent: 'tr',
           presubmitCallback: function(el,parent,options){
                var $this = $(el);

                return validate_selection_count(parent);


                //always return true or false so it can be submitted
           },
           submitCallback: function(el,parent,options){
               var $this = $(el);
               var priceEach = parent.children('td.td_price').children('div.sub_msg').html();
               priceEach = priceEach.replace(/\seach/gi,'');
               priceEach = priceEach.substring(1);
              // debug(priceEach)
               priceTotal = parseFloat(priceEach) * $this.val();
               parent.children('td.td_price').children('b.c_price').html('$'+formatCurrency(priceTotal));

                calculate_total(parent);
                var q = parent.children('td.td_quantity').children('input').val();
                var pName = parent.children('td').children('span.c_productName').children('a').html();

                var action = 'AM Update Quantity';
                if(q>0)
                  {
                        addNotice('You have updated the quantity of <b>'+pName+'</b> to <b>'+q+'</b>');
                  }
                else
                    {
                        addNotice('You have removed <b>'+pName+'</b> from your club selections');
                        action = 'AM Remove Product';
                    }


                 var category = 'AJAX';
                 gaPagetracker(category,action,pName);
           }
       });


       $("#clubSelections select").inputUpdater({
           valueType: 'alpha',
           submitPath:'clubSelectionAjaxAction.do',
           loadingImagePath:'/resources/images/2009/loading_small.gif',
           errorImagePath:'/resources/images/2009/indicator_error.gif',
           successImagePath:'/resources/images/2009/indicator_success.gif',
           actionType:'update',
           parent:'tr',
           submitCallback: function(el,parent,options) {
               var pName = parent.children('td').children('span.c_productName').children('a').html();
               var grind = $(el).children('option:selected').text();
               addNotice('You have updated the grind of <b>'+pName+'</b> to <b>'+grind+'</b>');

                var action = 'AM Change Grind';
                var category = 'AJAX';
                gaPagetracker(category,action,pName,grind);
           }
       });

       $("#clubSelections a.save").inputUpdater({
           valueType:'',
           submitPath:'clubSelectionAjaxAction.do',
           loadingImagePath:'/resources/images/2009/loading_small.gif',
           errorImagePath:'/resources/images/2009/indicator_error.gif',
           successImagePath:'/resources/images/2009/indicator_success.gif',
           actionType:'delete',
           parent:'tr',
           presubmitCallback: function(el,parent,options){

                return validate_selection_count(parent,'delete');

           },
           submitCallback: function(el,parent,options,data){
                calculate_total(parent,'delete');
                 var pName = parent.children('td').children('span.c_productName').children('a').html();
                addNotice('You have removed <b>'+pName+'</b> from your club selections');
                var action = 'AM Remove Product';
                var category = 'AJAX';
                gaPagetracker(category,action,pName);
           }
       });
    }

    function validate_selection_count(parent,type) //assures that user has 2 recurring items in club selections
    {
       // console.log('here')
        $("#lowclub_alert").remove();
        var count = 0;
        $("#clubSelections tbody tr").each(function(){
           var $id = parent.attr('id');

           if($(this).children('div.alert').html() == null)
               {
                   if(type=='delete' && $(this).attr('id')==$id)
                   {}
                   else
                   {
                   var q = parseInt($(this).find('input.c_quantity').val());
                   var val = $(this).children('td.td_price').find('div.sub_msg').html();
                      val = val.replace(/\$/,'');
                      val = val.replace(/\,/gi,'');
                      val = val.replace(/[\s]each/gi,'');
                      val = parseFloat(val);
                   count+= (q*val);

                   }
               }
        });

        if(count >= 0.1) return true;
        else
            {
                $("#clubSelections").before('<div class="alert" id="lowclub_alert">In order to remain an active club member, you must have at least one merchandise in your recurring club selections.</div>');
                $("#lowclub_alert").effect("highlight",{color:'#f4760f'},2000);
                return false;
            }
    }


    function seasonalEdit()
    {

        $(".ed span").unbind().eip({
           page:'',
           submitPath:'clubSelectionAjaxAction.do',
           loadingImagePath:'/resources/images/2009/loading_small.gif',
           errorImagePath:'/resources/images/2009/indicator_error.gif',
           successImagePath:'/resources/images/2009/indicator_success.gif'
      });

      $(".editcoffee").unbind().click(function(){
         $(this).parent().next().next().find('span').trigger('click');
      });

      $(".editcoffee").parent().next().unbind().click(function(){
         $(this).next().find('span').trigger('click');
      });

     makeBasicOmnitip('.editcoffee', 'alt');

    }


   function clubReady(){

        start_club_selection();
        club_selection_actions();
        load_alt_selections();

        seasonalEdit();


       $(".babyboca input").inputUpdater({
           valueType:'',
           submitPath:'clubSelectionAjaxAction.do',
           loadingImagePath:'/resources/images/2009/loading_small.gif',
           errorImagePath:'/resources/images/2009/indicator_error.gif',
           successImagePath:'/resources/images/2009/indicator_success.gif',
           actionType:'update',
           parent:'div.babyboca',
           submitCallback: function(el,parent,options) {
               var sel = $(el).parents('td').next().children('label').text();
               addNotice('You have chosen <b>'+sel+'</b> as your free Baby Boca');
               var action = 'AM Select Baby';
               var category = 'AJAX';
               gaPagetracker(category,action,sel);
           }
       });





       $("#cs_add button").inputUpdater({
           valueType:'',
           submitPath:'clubSelectionAjaxAction.do',
           loadingImagePath:'/resources/images/2009/loading_small.gif',
           errorImagePath:'/resources/images/2009/indicator_error.gif',
           successImagePath:'/resources/images/2009/indicator_success.gif',
           actionType:'insert',
           dataType:'json',
           parent:'div#cs_add',
           submitCallback: function(el,parent,options,data){
               var $this = $(el);

               $("#clubSelections tr").each(function(){
                   var id = $(this).attr('id');
                   var id_split = id.split('_');
                   if(data.clubselectionID == id_split[1]) $(this).remove();
               });

               var html = '<tr id="passData_'+data.clubselectionID+'"><td><span class="c_productName"><a href="/showProductDetail.do?productId='+data.productId+'&catalogId=1">'+data.productName+'</a></span>'
                   if(data.altProductName!=null)
                       {
                           html+='<div class="notifyeditcoffee size2 b0 mb1" alt="click coffee to edit" id="altSelection_'+data.clubselectionID+'"><div class="ct"><div class="left mr1" ><img class="editcoffee help" alt="click to edit alternate selection" src="/resources/images/2009/icon_editcoffee.gif" /></div><div class="left mr1 pt1">Alternate selection:</div><div class="left ed pt1"><span id="f_altSelection_'+data.altProductId+'" rel="required" sel="">'+data.altProductName+'</span></div></div></div>'
                       }
                   html+= '<div class="col100">';
               if(data.grind!=null && data.grind!="")
               {
                   html+='<select name="productOtherAttr" class="c_attr">';
                   html+='<option value="WB"';
                   if(data.grind=='WB') html+=' selected';
                   html+='>Whole Bean</option><option value="UG"';

                   if(data.productName.match(/Espresso/)!=null)
                   {
                     if(data.grind=='ES') html+=' selected';
                     html+='>Espresso Grind</option></select>';
                   }
                   else
                   {
                     if(data.grind=='UG') html+=' selected';
                     html+='>Universal Grind</option></select>';
                   }
               }

               html+= ' </div></td><td class="td_quantity"><input type="text" size="2" name="quantity" class="c_quantity" value="'+data.quantity+'" /></td> <td class="td_price"> <b class="c_price">$'+formatCurrency(data.price*data.quantity)+'</b><div class="sub_msg">$'+formatCurrency(data.price)+' each</div> <a href="clubSelection.do?id='+data.clubselectionID+'&action=remove" class="save" name="delete" value="delete">remove</a></td></tr>';

               addNotice('You have added <b>'+data.productName+'</b> to your club selections');

               var action = 'AM Add to Club';
               var category = 'AJAX';
               gaPagetracker(category,action,data.productName);

               $("#clubSelections").append(html);

               if(data.altProductName!=null) {seasonalEdit();load_alt_selections();}

               $('#passData_'+data.clubselectionID+' td').effect("highlight",{},2000,function(){

               });

                validate_selection_count(parent);
                    calculate_total(parent);
                    club_selection_actions();


           }
       });


       /* new datepicker */
         var jDateA = new Array();
            for(bo=0;bo< javaDates.length;bo++)
            {
                var jDate = Date.parseIso8601(javaDates[bo]) + '';
                jDateA.push(jDate);
            }

            var max = $("#lastDateDelivery").val();
            var max_split = max.split('/');
            var thisDay = max_split[2];
            if(parseInt(thisDay)==31) thisDay = 30;
            var update = new Date.today().set({day: parseInt(thisDay), month: parseInt(max_split[1])-1, year: parseInt(max_split[0])}).addDays(56);
            if(!isAdmin) {
             $("#datepicker").datepicker({blackoutDates:jDateA,minDate: '+3d', maxDate: update, altField: '#dp_alt', altFormat: 'DD, MM d, yy',onSelect:function(){
                setAlternateDate();



        }});
            }else{
                   $("#datepicker").datepicker({blackoutDates:jDateA, altField: '#dp_alt', altFormat: 'DD, MM d, yy',onSelect:function(){
                setAlternateDate();
        }});

            }



        $("select#f_frequency").inputUpdater({
           submitPath:'clubSelectionAjaxAction.do',
           loadingImagePath:'/resources/images/2009/loading_small.gif',
           errorImagePath:'/resources/images/2009/indicator_error.gif',
           successImagePath:'/resources/images/2009/indicator_success.gif',
           actionType:'update',
           parent:'form#frequency',
           submitCallback: function(el,parent,options){
                var freq = $(el).children('option:selected').text();
                var addedText = '';

                    addedText = '<b style="display:block;margin-top:10px;color:#fdd64f;font-size:84%;line-height:1.2em;">Please Note: Changing delivery frequency <strong style="font-size:124%">does not</strong> change your next shipment date. </b>';

               addNotice('You have updated your shipping frequency to <b>'+freq+'</b>'+addedText);
               var action = 'AM Shipping Frequency';
                var category = 'AJAX';
                gaPagetracker(category,action,freq);
           }
       });

    };

    function setAlternateDate()
    {
        var d = getDomain();
         $("#alternateText").remove();
         $('#datepicker').after('<div id="alternateText" class="left"><a href="#" class="load"></a></div>');
         //$("#alternateText").effect("highlight",{},2000);



         $(".row a.load").attr({name:'dateDelivery',value:$("#datepicker").val()}).unbind().inputUpdater({
           valueType:'',
           submitPath: '/clubSelectionAjaxAction.do',
           loadingImagePath:'/resources/images/2009/loading_small.gif',
           errorImagePath:'/resources/images/2009/indicator_error.gif',
           successImagePath:'/resources/images/2009/indicator_success.gif',
           actionType:'update',
           parent:'div.dpwrapper',
           submitCallback: function(el,parent,options){

           var old_date = Date.parse($("#shipping em").html());
           var new_date = Date.parse($('#dp_alt').val());
           var daysBetween = days_between(new_date,old_date);

               $("#shipping em").html($('#dp_alt').val()).effect("highlight",{},2000);
              // $("div#alternateText").fadeOut(500,function(){$(this).remove();});
              addNotice('You have changed your next shipment date to <b>'+$('#dp_alt').val()+'</b><b style="display:block;margin-top:10px;color:#fdd64f;font-size:84%;line-height:1.2em;">Please Note: Changing your next delivery date <strong style="font-size:124%">does not</strong> change your delivery frequency</b>');
               var action = 'AM Change Shipment Date';
               var category = 'AJAX';
               gaPagetracker(category,action,daysBetween, daysBetween);
           }
       });

    }

    function days_between(date1, date2) {  //number of days between 2 dates

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    var difference_ms = (date1_ms - date2_ms)

    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY)

    }

    function load_alt_selections()
    {
        var c=0;

        $("span").each(function(){
        var p = {};




        if($(this).attr('sel')!=undefined && c==0)
        {
            var select = {};
            select['8oz'] = '{';
            select['2oz'] = '{';
            var d = getDomain();
            var url = d+'clubProductsAjaxAction.do';
            $.ajax({
                       url: url,
                       data:p,
                       dataType: 'jsonp',
                       success: function (data, textStatus) {
                        for(i in data)
                        {
                            for(j in data[i])
                            {
                                 if(i!='Seasonal')
                                 {
                                     if(data[i][j].sku.match(/FRAC/)!=null) select['2oz']+= "'"+data[i][j].id+"':'"+data[i][j].name+"',";
                                     else select['8oz']+= "'"+data[i][j].id+"':'"+data[i][j].name+"',";
                                 }
                            }

                        }


                        select['8oz'] = select['8oz'].substring(0,select['8oz'].length-1);
                        select['8oz']+='}';

                        select['2oz'] = select['2oz'].substring(0,select['2oz'].length-1);
                        select['2oz']+='}';

                        $("span").each(function(){
                            var current = $(this).html();
                            var size = '8oz';
                            if(current.match(/2 oz/)!=null) size = '2oz';
                           if($(this).attr('sel')!=undefined) $(this).attr('sel',select[size]);
                        });

                       }
                    });
                      c++;
        }

        });

    }


     /** change club selection **/
	 function start_club_selection()
	 {
	 	if($("#step_1").html()!=null)
	 	{
	 		$("#step_1 select").val(1);
		 	changeUp("#step_1 select");
			$('.club_watch').change(function(){  //get the event of each selection change
				changeUp(this);
			});
	 	}
	 }

	 function changeUp(sel)
	{

			var value = $(sel).val();
			var id = $(sel).attr('name');
			var p = {};
			p[id] = value;
			//console.log('change');

			var step = $(sel).parent().attr('id');
			var stepsplit = step.split('_');
			var nextstep = parseInt(stepsplit[1]) + 1;


			$('.step').each(function(){
				var id = $(this).attr('id');
				var idsplit = id.split("_");
				if(idsplit[1] > stepsplit[1]) if($(this).is(':visible')) $(this).hide();
			});



			$(".step").each(function(){
				var sel_id = $(sel).attr('id');
				if(parseInt(sel_id) > parseInt(step)) $(this).fadeOut();
			});


				if(value!='') {

			 	var id = $("#step_1 select").attr('name');
			 	var value = $("#step_1 select").val();

                if(value==1)
                {
                    $('#coffeeType_1:hidden').fadeIn().effect('highlight','',2000);
                    p['roastlevel'] = $('#coffeeType_1 select').val();
                }
                else
                {
                    $('#coffeeType_1:visible').fadeOut();
                }

			 	p[id] = value;

					$.ajax(
					{
						type:'GET',
						url: 'clubSelectionAjax.do',
						dataType:'html',
						data:p,
						success: function(data) {

                                                        //seasonal coffee dropdown
                                                        if(p['roastlevel']=='Seasonal')
                                                        {

                                                                var seasoned = new seasonal;
                                                                seasoned.runMyAccount();

                                                        }
                                                        else
                                                            {
                                                                $("#response_seasonal").hide().empty();
                                                            }


							$("#response_"+nextstep).empty().append(data);

							if(p['productTypeId'] == 1)
							{
								var selection = '<label>Grind:</label><br /><select name="productOtherAttr"><option value="WB">Whole Bean</option><option value="UG">Universal Grind</option></select>';
								$("#response_3").empty().append(selection).show();
							}
							else if(p['productTypeId'] == 5)
							{
								var selection = '<label>Grind:</label><br /><select name="productOtherAttr"><option value="WB">Whole Bean</option><option value="ES">Espresso Grind</option></select>';
								$("#response_3").empty().append(selection).show();
							}
							else
							{
								$("#response_3").empty().hide();
							}


							$("#step_"+nextstep+":hidden").fadeIn(500,function(){
                                //load first product in the new select box
                                var productID = $("#response_2 select:first-child").val();
                                loadSelectionThumb(productID);
                                $("#response_2 select").unbind().change(function(){
                                   var id = $(this).val();
                                   loadSelectionThumb(id);
                                });
                            });
							$('.club_watch').unbind().change(function(){  //get the event of each selection change
									changeUp(this);
							});
						},
						error: function (XMLHttpRequest, textStatus, errorThrown) {
								return false;
						}
					});
				}
	}


    function loadSelectionThumb(productID)
    {
        //ajax request to get the thumb data.
        var p = {};
        p['productID'] = productID;
        $.ajax({
			type:'GET',
			url: 'productDetailAjaxAction.do',
			dataType:'html',
			data:p,
			success: function(data) {
                $("#selectionThumb").fadeOut(500,function(){
                   $(this).html(data).fadeIn(500,function(){
                       makeBasicOmnitip('.bj_more','title');
                       var pr_page_id= productID;
                       var reviewCount, reviewRating;
                       var pr_data_callback = function(info){
                            reviewCount = parseFloat(info.getFullReviewCount().toString());
                            reviewRating = info.getAverageRating();
                              };

                        prData(pr_data_callback);
                           $("span#reviewCount").html(reviewCount+' reviews');
                           $("span.rating").attr('class','rating'+reviewRating);

                   });
                });
            }
        });
    }




