(function($) {

    $.sendToFriend = function(options) {
        return $.sendToFriend.impl.init(options);
    };

    $.fn.sendToFriend = function(options) {
        return $.sendToFriend.impl.init(this, options);
    };

    /*
    * shopping bag default options
    */
    $.sendToFriend.defaults = {
        subject: 'sent you an email from dunhill.com',
        productName: null,
        productPrice: null,
        productCode: null,
        productImagePath: null,
        productUrl: null,
        shopNowText: 'Shop Now',
        block: {
            message: null,
            overlayCSS: {
                backgroundColor: '#fdfdfd',
                opacity: '0.50'
            }
        }
    };

    $.sendToFriend.impl = {

        /*
        * shopping bag options
        */
        opts: null,

        /*
        * shopping bag helper
        */
        helper: {},

        /*
        * Initialize the form
        */
        init: function(options) {

            var self = this;

            self.opts = $.extend({}, $.sendToFriend.defaults, options);

            // define helper objects
            self.helper.container = $('div.sendtofriend-modal');
            self.helper.entry = self.helper.container.find('div.form-entry');
            self.helper.confirmation = self.helper.container.find('div.form-confirmation');
            self.helper.overlay = $('<div class="modal-overlay"></div>').insertBefore(self.helper.container);

            // position
            self.helper.container
                .css({
                    marginLeft: -Math.floor(self.helper.container.outerWidth() / 2) + 'px',
                    marginTop: -Math.floor(self.helper.container.outerHeight() / 2) + 'px'
                })
                ;

            // fix IE 6
            if ($.browser.msie && ($.browser.version < 7))
                self.fixIE();

            // bind events
            self.bindEvents();

            return self;
        },

        /*
        * Show
        */
        show: function() {

            var self = this;

            // reset the form
            self.reset();

            self.helper.container
		        .fadeIn(500)
		        ;

            self.helper.overlay
		        .css({
		            opacity: '0.00',
		            display: 'block'
		        })
		        .fadeTo(750, '0.60')
		        ;

            return;
        },

        /*
        * Hide
        */
        hide: function() {

            var self = this;

            self.helper.container
		        .fadeOut(500)
		        ;

            self.helper.overlay
		        .fadeOut(750)
		        ;

            return;
        },

        /*
        * Bind the events
        */
        bindEvents: function() {

            var self = this;

            // open
            $('a.open-sendtofriend')
		        .click(function(e) {
		            e.preventDefault();
		            self.show();
		        })
		        ;

            // submit
            self.helper.entry.find('a.submit-sendtofriend')
		        .click(function(e) {
		            e.preventDefault();
		            self.submit();
		        })
		        ;

            // cancel
            self.helper.container.find('a.close-sendtofriend')
		        .click(function(e) {
		            e.preventDefault();
		            self.hide();
		        })
		        ;

            // overlay
            self.helper.overlay
		        .click(function(e) {
		            e.preventDefault();
		            self.hide();
		        })
		        ;

            return;
        },

        /*
        * Submit
        */
        submit: function() {

            var self = this;
            var senderName = self.helper.entry.find('#senderName').val();
            var senderEmail = self.helper.entry.find('#senderEmail').val();
            var recipientName = self.helper.entry.find('#recipientName').val();
            var recipientEmail = self.helper.entry.find('#recipientEmail').val();
            var message = self.helper.entry.find('#message').val();
            var optionalParameters =
                'productName&&' + (self.opts.productName || '&nbsp;')
                + '&&' + 'productPrice&&' + (self.opts.productPrice || '&nbsp;')
                + '&&' + 'productCode&&' + (self.opts.productCode || '&nbsp;')
                + '&&' + 'productImagePath&&' + (self.opts.productImagePath || $.lookSet.impl.image) // hack to retrieve lookbook image
                + '&&' + 'productUrl&&' + self.opts.productUrl
                + '&&' + 'shopNowText&&' + self.opts.shopNowText
                + '&&' + 'message&&' + message
                ;
        
            var delimiter = '&&';
            var emailTemplatePath = '/templates/sendtofriend.html';
            var subject = senderName + ' ' + self.opts.subject;
            var copyMe = self.helper.entry.find('#chkSendMeACopy').attr('checked');

            CreateThe.Com.Web.CodeBase.WebServices.EmailService.SendEmail(senderName, senderEmail, recipientName, recipientEmail, subject, emailTemplatePath, optionalParameters, delimiter, $.sendToFriend.impl.submitSuccess, $.sendToFriend.impl.submitFailure, self);

            if (copyMe)
                CreateThe.Com.Web.CodeBase.WebServices.EmailService.SendEmail(senderName, senderEmail, recipientName, senderEmail, subject, emailTemplatePath, optionalParameters, delimiter, $.sendToFriend.impl.submitCopySuccess, $.sendToFriend.impl.submitFailure, self);

            return;
        },

        /*
        * Success
        */
        submitSuccess: function(e, self) {

            var errors = eval(e);

            self.helper.entry.find('.validation-failed')
		        .removeClass('validation-failed')
		        ;

            self.helper.entry.find('.validation-message')
		        .css('display', 'none')
		        ;

            if (errors.length == 0) {
                self.showConfirmation();
            }
            else {
                $.each(errors, function(i, error) {

                    // highlight field
                    self.helper.entry.find('#' + error['FieldName'])
		                .parent()
		                .addClass('validation-failed')
		                ;

                    // display validation message
                    self.helper.entry.find('#validation-message-' + error['FieldName'])
		                .css('display', 'block')
		                ;

                });
            }

            self.unblock();

            return;
        },

        /*
        * Copy success
        */
        submitCopySuccess: function() {

            return;
        },

        /*
        * Failure
        */
        submitFailure: function(e, self) {

            self.unblock();
            alert('An error has occurred. Please submit the form again.');

            return;
        },

        /*
        * Show the confirmation
        */
        showConfirmation: function() {

            var self = this;

            self.helper.entry
		        .css('display', 'none')
		        ;

            self.helper.confirmation
		        .css('display', 'block')
		        ;

            return;
        },

        /*
        * Reset
        */
        reset: function() {

            var self = this;

            self.helper.entry.find(':text')
		        .val('')
		        ;

            self.helper.entry.find(':checkbox')
		        .attr('checked', '')
		        ;

            self.helper.entry
		        .css('display', 'block')
		        ;

            self.helper.confirmation
		        .css('display', 'none')
		        ;

            self.helper.entry.find('.validation-failed')
		        .removeClass('validation-failed')
		        ;

            self.helper.entry.find('.validation-message')
		        .css('display', 'none')
		        ;

            return;
        },

        /*
        * Unblock
        */
        unblock: function() {

            var self = this;

            self.helper.container
		        .unblock()
		        ;

            return;
        },

        /*
        * Fix IE
        */
        fixIE: function(overlay) {

            var self = this;
            var winW = $(document.body).width();
            var winH = $(document.body).height();

            self.helper.overlay
		        .css({
		            position: 'absolute',
		            width: winW + 'px',
		            height: winH + 'px'
		        })
		        ;

            self.helper.iframe = $('<iframe src="javascript:false;">')
				.css({
				    opacity: 0,
				    position: 'absolute',
				    width: '100%',
				    height: '100%',
				    left: 0,
				    top: 0
				})
				.appendTo(self.helper.overlay);

            return;
        }

    };
})(jQuery);