if ( typeof(Sage) != "object" ) { Sage = {}; }
Sage.WebChat = {};

(function($){
    $.extend(Sage.WebChat, {
        // default values - some to be overwritten
        windowFeatures : '',
        url: '',
        question: '',
        emailField: '',
        nameField: '',
        productFamily: '',
        productTitle: '',
        // onDocReady to be called on document ready
        onDocReady : function(){
            // show the web chat when clicking on the Web Chat link in the right hand side
            $("span.webchat").click(function(){
                var $t = $(this);
                $t.parent().find("span.webChatHolder").slideToggle();
                $t.closest(".bullet").toggleClass("open");
            });
            
            // prevent enter key from submitting form, instead open the popup
            $(".webChat .field input").keydown ( function(e) {
                if (e.keyCode == '13') {
                    e.preventDefault();
                    e.stopImmediatePropagation();
                    setTimeout('Sage.WebChat.openPopup()',100);
                    return false;
                }
            });
            
            // display the web chat link (ensures it's hidden when js disabled)
            $("li.webChatBullet").show();

            var H2Text = function() { return $("#contentLeft h2").text(); };
            
            // attempt to get the product title / family from page content
            if ( Sage.WebChat.pageType == "product" ) {
                if ( !Sage.WebChat.productFamily ) {
                    var crumbs = $("#breadcrumb").text().split(" / ");
                    if ( crumbs.length > 2 ) {
                        Sage.WebChat.productFamily = crumbs[crumbs.length-2];
                    }
                }
                if ( !Sage.WebChat.productTitle ) {
                    Sage.WebChat.productTitle = H2Text();
                }
            } else if ( $.inArray(Sage.WebChat.pageType, ["family","template"]) > -1 ) {
                if ( !Sage.WebChat.productFamily ) {
                    Sage.WebChat.productFamily = H2Text();
                }
            } else if ( Sage.WebChat.pageType == "checkout" ) {
                Sage.WebChat.productFamily = "checkout";
                Sage.WebChat.productTitle = H2Text();
            }
        },
        validate : function() {
            var errors = [],
                clearError = function($field) {
                    $field.closest("div.field").removeClass("error");
                },
                addIfError = function($field, msg, valid) {
                    if (valid) {
                        clearError($field);
                    } else {
                        errors.push(msg);
                        $field.focus().closest("div.field").addClass("error");
                    }
                },
                $name = $("#"+this.nameField),
                $email = $("#"+this.emailField),
                address = $email.val();

            // check a name has been entered
            addIfError($name, "Please enter your name.", $name.val().replace(/\s+/g,""));

            // if an email address has been entered, check that it is basically valid
            if ( address != "" ) {
                var pos = address.lastIndexOf("@"); 
                var valid = (pos > 0 && (address.lastIndexOf(".") > pos) && (address.length - pos > 4)) && (address.indexOf("..")<0);
                
                addIfError($email, "Please enter a valid e-mail address.", valid);
            } else {
                clearError($email);
            }

            if ( errors.length > 0 ) {
                alert("Please correct the following fields before continuing:\n\n" + errors.join("\n"));
                return false;
            }            
            return true;
        },
        getUrl : function() {
            var encValue = function(id) {
                return encodeURIComponent($.trim(getControlByID(id).value));
            };
            
            var question = this.question.
                replace('{2}', encValue(this.emailField)).
                replace('{3}', encodeURIComponent($.trim(this.productFamily))).
                replace('{4}', encodeURIComponent($.trim(this.productTitle))).
                toLowerCase();

            return this.url.replace('{0}', encValue(this.nameField)).
                replace('{2}', encValue(this.nameField)).
                replace('{4}', question);
        },
        openPopup : function() {
            if ( this.validate() ) {
                this.windowpane = window.open(this.getUrl(), 'webChat', this.windowFeatures);
            }
        }
    });

    $(Sage.WebChat.onDocReady);
})(jQuery);
