﻿        // *** Create a static instance
        var Proxy = new serviceProxy("/BarBuilder.asmx/");
        
        String.prototype.format = function() {
            var formatted = "";
            for (arg in arguments) {
                formatted = this.replace("{" + arg + "}", arguments[arg]);
            }
            return formatted;
        };
        
        function GetRecipe() {
            var r = $get('recipeCode');
            if (r) {
                return r.value;
            }
            return '';
        }
        function onBarResponseCompleted(sender, e) {            
            if (sender != null && sender != 'undefined') {
                HandleBarResponse(sender);
            }
        }
        
        function SetWarning(errState) {
            var clsA = 'warningCaution';
            var clsR = 'warningError';
            var msg = 'Suggestion:';
            if (errState == 2) {
                var clsT = clsR;
                clsR = clsA;
                clsA = clsT;
                msg = 'Bar Tender Says:';
            }
            $('#recipeWarnings span').html(msg);
            $('#recipeWarnings input').val(errState);
            $('#recipeWarnings').removeClass(clsR).addClass(clsA).slideDown('slow');
        }
        var warnings;
        function HandleBarResponse(barResponse) {
            $('#recipe').html(barResponse.BarHtml);
            UpdateNutrition(barResponse.NutritionValues);
            $('#allergyDiv').html(barResponse.AllergenList);
            $('#ingredientDiv').html(barResponse.IngredientList);
            $('.priceSeal span').html('$' + barResponse.DisplayPrice.toFixed(2) + ' each');
            warnings = barResponse.Warnings;
            if (warnings != null && warnings != 'undefined' && warnings.length > 0) {

                var errState = 0;
                $('#recipeWarnings ul').html('');
                for (var j = 0; j < warnings.length; j++) {
                    $('#recipeWarnings ul').append('<li>'+warnings[j].ShortMessage+'</li>');
                    if (warnings[j].IsError) {
                        errState = 2; //error
                    } else if (errState == 0) {
                        errState = 1; //warning
                    }                    
                }
                SetWarning(errState);
                
            } else {
                $('#recipeWarnings ul').html('');
                $('#recipeWarnings input').val('0');
                $('#recipeWarnings').slideUp('slow');
            }

            var barName = barResponse.BarName;
            if (hasVal(barName)) {
                $('#labelItDiv input[id$=barNameTB]').val(barName);
            }
            var barSub = barResponse.BarSubtitle;
            if (hasVal(barSub)) {
                $('#labelItDiv input[id$=barSubTB]').val(barSub);
            }
        }
        function hasVal(x) {
            return (x != null && x != undefined && x.length > 0);
        }
        var maxLen = 22;
        function checkBarName(sndr) {            
            charLimit(sndr, maxLen);
            
        }
        function onPageError(errorData) {
            alert(errorData.Message);
        }
        function LoadItem(itemSku, addIngredients) {
            Proxy.invoke("LoadItem", { itemSku: itemSku, addIngredients: addIngredients, productId: productId }, function(result) {
                HandleBarResponse(result);
                //also set the template bar message
                var msg;
                if (result.BarName.length <= 0) {
                    msg = 'You are editing a new bar';
                }else {
                    msg = 'You are editing the \'' + result.BarName + '\' bar'
                }
                $('div[id$=TopBanner]').hide().html(msg).fadeIn();
            }, onPageError);
            
        }
        function AddIngredient(ingredientId) {
            Proxy.invoke("AddIngredient", { recipe: GetRecipe(), productId: productId, ingredientId: ingredientId }, function(result) {
                HandleBarResponse(result);
            }, onPageError);
        }
        function RemoveIngredient(ingredientId) {
            Proxy.invoke("RemoveIngredient", { recipe: GetRecipe(), productId: productId, ingredientId: ingredientId }, function(result) {
                HandleBarResponse(result);
            }, onPageError);
        }
        function SetOrganic(ingredientId, makeOrganic) {
            Proxy.invoke("SetOrganic", { recipe: GetRecipe(), productId: productId, ingredientId: ingredientId, isOrganic: ("1"==makeOrganic)},
                function(result) { HandleBarResponse(result); },
                onPageError);
        }
        function SetOption(ingredientId, optionTypeId, v_selValue) {
            Proxy.invoke("SelectOption", {recipe:GetRecipe(), productId:productId, ingredientId:ingredientId, optionType:optionTypeId, optionValue:v_selValue},
                function(result) { HandleBarResponse(result); },
                onPageError);
        }
        function Increment(ingredientId, increment) {
            Proxy.invoke("IncrementOption", {recipe:GetRecipe(), productId:productId, ingredientId:ingredientId, increment:increment},
                function(result) { HandleBarResponse(result); },
                onPageError);            
        }
        function UpdateNutrition(nutritionValues) {
            $.each(nutritionValues, function(i, item) {
                var blk = $('#' + item.NutritionKey);
                var curVal = blk.html();
                if (curVal != item.DisplayValue) {
                    blk.stop().html(item.DisplayValue);
                    if (blk.attr('id') != undefined && blk.attr('id').indexOf('pctCal') < 0) {
                        blk.animate({ backgroundColor: '#E06B12', color: '#FFFFFF' }, 300).animate({ backgroundColor: 'Orange' },700).animate({ backgroundColor: '#FFFFFF', color: '#000000' }, 1000);
                    }
                }
            });
        }
        function ChooseOptionalIngredient(ingredientId, subIngredientId) {
            SetOption(ingredientId, 2, subIngredientId);
        } 
        function SlideIt(el, labelEl, ingredientId, optionId, v_min, v_max, v_step, v_currVal) {
            if (v_currVal == 'undefined' || v_currVal == null) {
                v_currVal = 0;
            }
            $('#' + el).slider({ min: v_min, max: v_max, step: v_step, orientation: 'horizontal', value: v_currVal,
                slide: function(evt, ui) {
                    $('#' + labelEl).html(ui.value);
                    $("#slider").slider();

                },
                change: function(evt, ui) {
                  //  SetOption(ingredientId, 1, ui.value);
                },
                stop : function(evt, ui) {
                    SetOption(ingredientId, 1, ui.value);
                }
            });
        }
        
        function isBarErrorFree() {
            var errState = $('#recipeWarnings input').val();
            if (errState == '0') {
                return true;
            } else if (errState == '1') {
                $('<div class="assist"><img src="/App_Themes/Earthy/images/Logo_Small_With_Tagline.gif" width="157px"  /><br /><h3>How About an Assist from the Bar Tender?</h3><p>We have a few recommendations for your bar.  You haven\'t done anything wrong, we just know through experience that some combinations are not ideal for flavor and texture.</p></div>').append(function () { var x = '<ol>'; $.each(warnings, function (i, item) { x = x + '<li>' + item.Message + '</li>'; }); return x + '</ol>'; }).dialog({ modal: true, title: 'Houston We Might Have a Problem', width: 450, buttons: { 'edit bar': function () { $(this).dialog('close'); }, 'it\'s what I want': function () { SetWarning(0); $(this).dialog('close'); trySaveBar(true); } } });
                return false;
            }else {
                $('<div class="assist"><img src="/App_Themes/Earthy/images/Logo_Small_With_Tagline.gif" width="157px"  /><br /><h3>How About an Assist from the Bar Tender?</h3><p>Before we can make your bar, we have a few issues that need fixing.  You haven\'t done anything wrong, we just know through experience that your bar is going to come out icky unless we fix this first.</p></div>').append(function () { var x = '<ol>'; $.each(warnings, function (i, item) { x = x + '<li>' + item.Message + '</li>'; }); return x + '</ol>'; }).dialog({ modal: true, title: 'Houston We Have a (tiny) Problem', width: 450, buttons: { 'edit bar': function () { $(this).dialog('close'); } } });
                return false;
            }
        }
        var nmAra = ['{1}-o-{2}', '{3} on {4} bar', '{2} {1}', '{3} {0}', '{0} {4} bar', '{4} {0}', '{1} {4}', '{3} {1}', '{1}-a-licious'];
        var vlAra = ['Yummy', 'Juicy', 'Amazing', 'Perfection', 'Oh Yeah', 'MINE'];
        function rando(ara) {
            return ara[Math.floor(ara.length * Math.random())];
        }
        var sentOnce = false;
        function autoName(sndr) {
            var nm = rando(nmAra);
            var el = $(sndr).parentsUntil('.labeler .namer');
            var sel = $(el).find('option:selected').val();
            var selTxt = $(el).find('option:selected').text();

            nm = nm.replace('{0}', rando(sel.split(',')));
            $(el).find('input').each(function(i, it) {
                var vl = $(it).val();
                if (vl != '') {
                    vl = vl.replace(/^\s*an*\s/, '')
                } else {
                    vl = rando(vlAra);
                }
                nm = nm.replace('{' + (i + 1) + '}', vl);

            });

            $('.labeler input[id*=barNameTB]').val(nm.trim().substring(0,maxLen));
            
            if (sel.length > 0 && sentOnce == false) {
                $.ajax({
                    type: 'post',
                    data: '{reason:"' + selTxt + '"}',
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    url: '/Services/DataService.asmx/ReasonToEat'                   
                });
                sentOnce = true;
            }
            return false;
        }
        function showNamer(sndr) {
            $(sndr).parentsUntil('.labeler').find('div').fadeIn();
        }
        
        var $nameItem;
        var $subItem;
        var nameSel = 'input[id$=barNameTB]';
        var subSel = 'input[id$=barSubTB]';
        function showNameBarDialog(dialogMsg, addOn, saveOn) {
            _gaq.push(['_trackPageview'], 'name your bar');
            
            var btn = {};
            if (addOn != 0) {
                btn['add to cart'] = function() {
                    $subItem.val($(this).find(subSel).DefTexter('value'));
                    var barName = $.trim($(this).find(nameSel).DefTexter('value'));
                    if (hasVal(barName)) {
                        $nameItem.val(barName);
                        $(this).dialog('close');
                        trySaveBar(true);
                    } else {
                        $(this).find('span').fadeIn();
                    }
                };
            }
            if (saveOn != 0) {
                btn['save the name'] = function() {
                    $nameItem.val($(this).find(nameSel).DefTexter('value'));
                    $subItem.val($(this).find(subSel).DefTexter('value'));
                    $(this).dialog('close');
                };
            }
            if ($('.popupEmailCollector').length > 0) {
                var collectorType = $('.popupEmailCollector').attr('id');
                if (collectorType == "emailMeDiv") {
                    btn['email me my recipe'] = function () {
                        $subItem.val($(this).find(subSel).DefTexter('value'));
                        var barName = $.trim($(this).find(nameSel).DefTexter('value'));
                        if (hasVal(barName)) {
                            $nameItem.val(barName);
                            emailCol = new emailCollector($(this));
                            emailCol.showEmailMe();
                        }
                        else {
                            $(this).find(nameSel).focus();
                            $(this).find('span').fadeIn();
                        }
                    }
                }
                else if (collectorType == "reviewThisDiv") {
                    btn['Bar Tender: have a real human reviewed my recipe'] = function () {
                        $subItem.val($(this).find(subSel).DefTexter('value'));
                        var barName = $.trim($(this).find(nameSel).DefTexter('value'));
                        if (hasVal(barName)) {
                            $nameItem.val(barName);
                            emailCol = new emailCollector($(this));
                            emailCol.showEmailMe();
                        }
                        else {
                            $(this).find(nameSel).focus();
                            $(this).find('span').fadeIn();
                        }
                    }
                }
                else if (collectorType == "sendMeCouponDiv") {
                    btn['send me a coupon'] = function () {
                        $subItem.val($(this).find(subSel).DefTexter('value'));
                        var barName = $.trim($(this).find(nameSel).DefTexter('value'));
                        if (hasVal(barName)) {
                            $nameItem.val(barName);
                            emailCol = new emailCollector($(this));
                            emailCol.showEmailMe();
                        }
                        else {
                            $(this).find(nameSel).focus();
                            $(this).find('span').fadeIn();
                        }
                    }
                }
                else if (collectorType == "sendViaFB") {
                    btn['send to my friends on Facebook'] = function () {
                        
                        $subItem.val($(this).find(subSel).DefTexter('value'));
                        var barName = $.trim($(this).find(nameSel).DefTexter('value'));
                        if (hasVal(barName)) {
                            $nameItem.val(barName);
                            emailCol = new emailCollector($(this));
                            emailCol.isVisible = true;
                            emailCol.sendRecipe();
                        }
                        else {
                            $(this).find(nameSel).focus();
                            $(this).find('span').fadeIn();
                        }
                    }
                }
            }

            this.popup = $('<div class="labeler" style="position:relative" />').append($('#labelItDiv .labeler > div').clone()).dialog({
                modal: true,
                buttons: btn,
                title: dialogMsg, width: 875, height: 648,
                open: function (event, ui) {
                    $("input:submit, input:button, button", ".labeler").button();
                    if (collectorType == "sendMeCouponDiv") {
                        $(this).nextAll().find("button:eq(1)").css("float", "left");
                    }

                }
            }).find(nameSel).keypress(function () { checkBarName($(this)); })
                .blur(function () {
                    if ($(this).DefTexter('value') != null && $(this).DefTexter('value') != 'undefined' && $(this).DefTexter('value').length > 0) {
                        $(this).parent().find("span").fadeOut();
                    }
                })
                .DefTexter({ defText: 'name it here' }).focus().end()
                .find(subSel).DefTexter({ defText: 'add a subtitle' }).parent().parent();
        }
        function initFacebookSendButton(d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s); js.id = id;
            js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=26211441829";
 
            fjs.parentNode.insertBefore(js, fjs);
            
        }
        function trySaveBar(doPost) {

            var recipe = GetRecipe();
            if (recipe == '' || $('#ingredientDiv').html() == '') {
                return true;  //empty recipe
            }
            if (!isBarErrorFree()) {
                return false;
            }
            var barName = $.trim($nameItem.val());
            
            if (barName == null || barName == 'undefined' || barName.length <= 0) {
                showNameBarDialog('Now you get to name your bar!',1,0);
                return false;
            }

            //used to be try save bar

            $('#labelItDiv input[id$=saveRecipe]').val(recipe);
            if (doPost) {
                __doPostBack($('input[id$=MakeIt]').attr('name'), '');
            } else {
                return true;
            }
        }

        var currCls = '';
        var ingredStep = 0; //1 indexed
        function setStep(stepIndex) {
            if (ingredStep == 4) {
                $('a.next').hide();
                $('a.checkout').show();
            } else {
                $('a.next').show();
                $('a.checkout').hide();
            }
        }
        var inDrag = false;
        function setDragStart() {
            inDrag = true;
            $('.qtip').fadeOut('fast');
            $('#ingredients img').qtip('disable');
        }
        function setDragDone() {
            inDrag = false;
            $('#ingredients img').qtip('enable');
        }
        function InitShowMoreIngredient(currCls) {
            selTag = currCls;
            $('#ingredients img.sec').hide();
            if ($('.' + currCls + '.sec').length == 0) {
                linkMoreIngr.hide();
            }
            else{
                linkMoreIngr.html('+ more ingredients').show();
            }
        }       
        
        var productId = 1;
        var disabled = '';
        var lnkMoreIngr;
        var selTag = '';

        var lnkMoreIngr;
        var selectedTag;

        $(document).ready(function () {
            linkMoreIngr = $('#lnk_morelessIngr');
            linkMoreIngr.click(function () {
                if (linkMoreIngr.html().indexOf('+') > -1) {
                    $(".sec." + selTag).each(function () {
                        $(this).addClass("moreless").fadeIn();
                        $(this).appendTo($("#ingredients .clearfix"));
                    });
                    linkMoreIngr.html('- less ingredients');
                }
                else {
                    $(".sec." + selTag).each(function () {
                        $(this).removeClass("moreless").hide('fast');
                    });
                    linkMoreIngr.html('+ more ingredients');
                }
            });
            productId = parseInt($('input[name$=productId]').val());

            $('#ingredients img').draggable({ distance: 2, revert: true });

            $('#recipe').droppable(
                { accept: '.draggable', hoverClass: 'cart-active',
                    drop: function (event, ui) {
                        AddIngredient(ui.draggable.attr('id').substring(1));
                    },
                    tolerance: 'touch'
                });
            $('#loaderImage').ajaxComplete(function () { $(this).hide(); });
            $('#loaderImage').ajaxStart(function () { $(this).show(); });

            $('#nameIt').click(function () {
                showNameBarDialog('Name your bar!', 0, 1);
            });

            $('a.prev').click(function () {
                //get current filter, grab prev sibling
                if (ingredStep > 0) {
                    ingredStep = ingredStep - 1;
                }
                $('#filters a').slice(ingredStep, ingredStep + 1).click();
            });
            $('a.next').click(function () {
                if (ingredStep < 4) {
                    ingredStep = ingredStep + 1;
                    $('#filters a').slice(ingredStep, ingredStep + 1).click();
                }
            });
            $('a.checkout').click(function () {
                trySaveBar();
            }).hide();

            $('#ingredients img').qtip({
                content: $(this).attr('alt'),
                show: 'mouseover',
                hide: 'mouseout',
                style: {
                    border: {
                        width: 5,
                        radius: 10
                    },
                    padding: 10,
                    textAlign: 'center',
                    tip: true, // Give it a speech bubble tip with automatic corner detection
                    name: 'green' // Style it according to the preset 'cream' style
                },
                position: {
                    corner: {
                        target: 'bottomMiddle',
                        tooltip: 'topLeft'
                    }
                }


            }).click(function () {
                if (!inDrag) {
                    AddIngredient($(this).attr('id').substring(1));
                }
                $('.qtip').fadeOut('fast');
            });

            $('#filters a, #barPowerKey a').click(
            function () {

                $('#filters a, #barPowerKey a').removeClass('active');
                $(this).addClass('active');

                ingredStep = $('#filters a').index(this);
                setStep(ingredStep);

                var newCls = $(this).attr('id').substring(2);

                $('#ingredients > div').slideUp(300,
                        function () {
                            $('#ingredients img, #ingredients .key').hide();
                            $('#ingredients .' + newCls).show().draggable({ distance: 2, revert: true, start: setDragStart, stop: setDragDone });
                            InitShowMoreIngredient(newCls);
                            $(disabled).draggable('disable').unbind('click');
                            $(this).delay(10).slideDown(300);

                        });
            });
            currCls = '.' + $('#filters a').slice(0, 1).attr('id').substring(2);
            $('#filters a').slice(0, 1).addClass('active');
            $('#ingredients img' + currCls).show('blind',
                    {},
                    300, function () {
                        $(this).draggable({ distance: 2, revert: true, start: setDragStart, stop: setDragDone });
                        $(disabled).draggable('disable').unbind('click');

                    }); //

            InitShowMoreIngredient(currCls);

            var itemSku = $('#loadItemSku').val();
            var addIngs = $('#addIngredients').val();
            if (itemSku == null || itemSku == undefined) {
                itemSku = '';
            }
            if (addIngs == null || addIngs == undefined) {
                addIngs = '';
            }
            if (itemSku.length > 0 || addIngs.length > 0) {
                LoadItem(itemSku, addIngs);
            }
            $('a[id$=OpenRecent]').click(function () {
                $(this).siblings('ul').slideToggle('fast');
            });
            $nameItem = $('#labelItDiv input[id$=barNameTB]');
            $subItem = $('#labelItDiv input[id$=barSubTB]');

            $('#menu_cart').click(function () {
                return trySaveBar(true);
            });

        });

        var emailCol;
        

        function emailCollector (content) {
            this.content = content;
            
            this.sendToEmailAddress = '';
            this.status = 0;
            this.email = '';
            this.emailTB = this.content.find("#tx_RecipeReciverEmail");
            var that = this;
            this.emailTB.blur(function () {
                that.email = that.emailTB.val();
                return that.appendValidateResult(that.validateEmail());
            });
            this.isVisible = false;
            this.beginSendRecipe = function () {
                this.content.find("#begin").fadeIn();
                this.content.find('#sending').css("display", "none");
                this.content.find('#sent').css("display", "none");
            };
            this.sendingRecipe = function () {
                this.content.find('#begin').fadeOut();
                this.content.find('#sending').fadeIn();
                this.content.find('#sent').css("display", "none");
            };
            this.finishSendRecipe = function (msg) {
                this.content.find('#begin').css("display", "none");
                this.content.find('#sending').fadeOut();
                this.content.find('#sent').fadeIn(function () { $(this).find('span').html(msg); });
            };
            this.validateEmail = function () {
                var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
                return pattern.test(this.email);
            };
            this.appendValidateResult = function (isValid) {
                if (!isValid) {
                    if (this.content.find("#tx_RecipeReciverEmail + span.textboxWarning").length == 0) {
                        this.content.find("#tx_RecipeReciverEmail").after($('<span class="textboxWarning" ></span>')
                        .html("invalid email").slideDown('slow', function () { $(this).prev().focus(); }));
                    }
                    else {
                        this.content.find("#tx_RecipeReciverEmail").focus();
                    }
                    return false;

                }
                else {
                    this.content.find("#tx_RecipeReciverEmail + span.textboxWarning").fadeOut(function () { $(this).remove(); });
                    return true;
                }
            };
            this.sendRecipe = function (type) {
                var barName = $.trim($nameItem.val());
                var barNotes = $('.CustomLabelNotesBox.defText').val();
                this.email = this.emailTB.val();

                if (type == "emailMe") {
                    if (!this.appendValidateResult(this.validateEmail())) {
                        return false;
                    }
                    var that = this;
                    $.ajax({
                        type: "Post",
                        url: "BarBuilder.asmx/SendRecipe",
                        data: JSON.stringify({ recipe: GetRecipe(), barName: barName, barNotes: barNotes, productId: productId, sendToEmail: that.email }),
                        dataType: "json",
                        contentType: "application/json",
                        beforeSend: function () {
                            that.sendingRecipe();
                        },
                        success: function (result) {
                            if (result.d.IsSentEmail == true) {

                                that.finishSendRecipe('Your email has been sent');

                            }
                            else {
                                that.finishSendRecipe('There is something wrong with our email client. It\'s our fault. We\'ll try send you the recipe later.');

                            }
                            HandleBarResponse(result.d.BuildABarResponse);
                            return doGoal(this);
                        },
                        fail: function () {
                            that.finishSendRecipe('There is something wrong with our email client. It\'s our fault. We\'ll try send you the recipe later.');
                        }
                    });
                }
                else if (type == "reviewThis") {
                    if (!this.appendValidateResult(this.validateEmail())) {
                        return false;
                    }
                    var that = this;
                    $.ajax({

                        type: "Post",
                        url: "BarBuilder.asmx/ReviewRecipe",
                        data: JSON.stringify({ recipe: GetRecipe(), barName: barName, barNotes: barNotes, productId: productId, sendFromEmail: that.email }),
                        dataType: "json",
                        contentType: "application/json",
                        beforeSend: function () {
                            that.sendingRecipe();
                        },
                        success: function (result) {
                            if (result.d.IsSentEmail == true) {

                                that.finishSendRecipe('Your email has been sent');

                            }
                            else {
                                that.finishSendRecipe('Your email has been sent');
                            }

                            HandleBarResponse(result.d.BuildABarResponse);
                            return doGoal(this);

                        },
                        fail: function () {
                            that.finishSendRecipe('There is something wrong with our email client. It\'s our fault. Please try it later.');

                        }

                    });
                }
                else if (type == "sendMeCoupon") {
                    if (!this.appendValidateResult(this.validateEmail())) {
                        return false;
                    }
                    var that = this;
                    $.ajax({

                        type: "Post",
                        url: "BarBuilder.asmx/SendCoupon",
                        data: JSON.stringify({ recipe: GetRecipe(), barName: barName, barNotes: barNotes, productId: productId, sendToEmail: that.email }),
                        dataType: "json",
                        contentType: "application/json",
                        beforeSend: function () {
                            that.sendingRecipe();
                        },
                        success: function (result) {
                            if (result.d.IsSentEmail == true) {
                                that.finishSendRecipe('The coupon has been send to ' + that.email + ' . To apply the coupon, please follow the instructions in the email. Enjoy! ');
                            }
                            else {
                                that.finishSendRecipe('There is something wrong with our email client. It\'s our fault. We\'ll try send you the coupon later.');
                            }
                            HandleBarResponse(result.d.BuildABarResponse);
                            return doGoal(this);

                        },
                        fail: function () {
                            that.finishSendRecipe('There is something wrong with our email client. It\'s our fault. We\'ll try send you the coupon later.');

                        }

                    });
                }
                else {
                    var that = this;
                    $.ajax({

                        type: "Post",
                        url: "BarBuilder.asmx/SaveItem",
                        data: JSON.stringify({ recipe: GetRecipe(), productId: productId, barName: barName, barSubTitle: "", barNotes: barNotes }),
                        dataType: "json",
                        contentType: "application/json",
                        success: function (result) {
                            HandleBarResponse(result.d.BuildABarResponse);
                            /* that.content.find(".bar").append($('<div class="fb-send" data-font="segoe ui" style="padding:0; border: 0"></div>').attr('data-href', result.d.EditUrl));
                            setTimeout(initFacebookSendButton(document, 'script', 'facebook-jssdk'), 1000);*/
                            finishSendWithFacebookSendButton(that.content.find(".bar"));
                            that.content.find('#sendViaFB').append($('<div id="userName" class="facepile"></div>').attr('data-url', result.d.EditUrl));
                            var script = document.createElement('script');
                            script.src = "/Public/Scripts/facepile.js";
                            document.body.appendChild(script);
                            return doGoal(this);


                        },
                        fail: function () {
                            that.finishSendRecipe('There is something wrong with our email client. It\'s our fault. Please try it later.');

                        }

                    });
                }


                return true;
            };
            this.showEmailMe = function () {
                if (this.isVisible == false) {
                    this.content.find(".popupEmailCollector").fadeIn();
                    this.beginSendRecipe();
                    this.isVisible = true;
                }
                else {
                    this.content.find('#begin').css("display", "none");
                    this.content.find('#sending').css("display", "none");
                    this.content.find('#sent').css("display", "none");
                    this.content.find(".popupEmailCollector").fadeOut();
                    this.isVisible = false;
                }
            }
        }

       
        


        function finishSendWithFacebookSendButton(ui) {
            $(ui).find('img.sending').hide();
            $(ui).next().find('.popupEmailCollector').show();
        }
