if ( typeof(Sage) != "object" ) { Sage = {}; }
Sage.WebChat = {};

(function($){
    $.extend(Sage.WebChat, {
        // default values - some to be overwritten
        windowFeatures : '',
        url: '',
        question: '',
        emailField: '',
        nameField: '',
        productFamily: '',
        productTitle: '',
        hiddenFields: false,
        // 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
            if ($("span.webChatHolder input:button").length > 0) {
                $("span.webchat").click(function(){
                    var $t = $(this);
                    $t.parent().find("span.webChatHolder").slideToggle();
                });
            } else {
                $("span.webchat").click(function(){Sage.WebChat.openPopup(false)});
            }
            
            // 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;
                }
            });
        },
        validate : function() {
            if (this.hiddenFields) {
                return true;
            }
        
            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($("#"+id).val()));
            };
            
            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(check) {
            if ( check === false || this.validate() ) {
                this.windowpane = window.open(this.getUrl(), 'webChat', this.windowFeatures);
            }
        }
    });

    $(Sage.WebChat.onDocReady);
})(jQuery);

