﻿function DealShare() {
    EmailWidget.show({
        from: (email == "" ? null : email),
        subject: '',
        body: '',
        link: "www.dealchicken.com",
        dealLocId: dealLocID,
        dealId: dealID
    });
}

function SubscribeShare() {
    EmailWidget.show({
        from: (email == "" ? null : email),
        subject: 'I Just Subscribed to DealChicken!',
        body: 'I Just Subscribed to DealChicken!',
        link: "www.dealchicken.com",
        dealLocId: '0',
        dealId: '0'
    });
}

function RegisterShare() {
    EmailWidget.show({
        from: (email == "" ? null : email),
        subject: 'I Just Signed-up With DealChicken!',
        body: 'I Just Signed-up With DealChicken!',
        link: "www.dealchicken.com",
        dealLocId: '0',
        dealId: '0'
    });
}

function RefCodeShare() {
    EmailWidget.show({
        from: (email == "" ? null : email),
        subject: '' + (referrerName != "" ? referrerName : email) + '' + ' is sharing the Chicken Love!',
        body: escape('Sharing the Chicken Love with my peeps. Click here for $5 off your first daily deals purchase.'), /* if there is an apostrophe use a special code and decode on backend **/
        link: refCodeURL,
        dealLocId: '0',
        dealId: 'ChickenLove'
    });
}

/**
    @description Creates a new EmailWidget with the given options.
    @param {EmailWidgetOptions} options
    @description {
            isDebug: true,      // Needs changed for production
            to: null,           // {string} person to send email to
            from: null,         // {string} person to send email from
            subject: null,      // {string} subject of email
            body: null,         // {string} message body of email
            link: null,         // {string} link to attach
            onOpen: null,       // {event} fired when modal is opened
            onClose: null,      // {event} fired when modal is closed
            onBeforeSend: null, // {event} fired before sending email
            onAfterSend: null,  // {event} fired after sending email
            dialogElement: null,// {container} div element to put the widget content into
            isFancybox: true    // {bool} true if the modal will be using fancybox, false defaults to jQuery dialog.
    }
*/
var EmailWidget = new function () {
    var self = this;
    this.options = null;


    this.defaults = {
        isDebug: false,  // Needs changed for production
        to: null,
        from: null,
        subject: null,
        body: null,
        link: null,
        onOpen: null,
        onClose: null,
        onBeforeSend: null,
        onAfterSend: null,
        dialogElement: null,
        isFancybox: true,
        dealLocId: null,
        dealId: null
    };

    /**
    Creates a new EmailWidgetOptions object
    @class EmailWidgetOptions
    @descripton {
    isDebug: true,      // Needs changed for production
    to: null,           // {string} person to send email to
    from: null,         // {string} person to send email from
    subject: null,      // {string} subject of email
    body: null,         // {string} message body of email
    link: null,         // {string} link to attach
    onOpen: null,       // {event} fired when modal is opened
    onClose: null,      // {event} fired when modal is closed
    onBeforeSend: null, // {event} fired before sending email
    onAfterSend: null,  // {event} fired after sending email
    dialogElement: null,// {container} div element to put the widget content into
    isFancybox: true    // {bool} true if the modal will be using fancybox, false defaults to jQuery dialog.
    }
    */
    this.setOptions = function (options) {
        if (options) {
            var _props = {};
            $.extend(_props, self.defaults, options);
            return (_props);
        }
        else {
            return (self.defaults);
        }
    };

    /**
    @function draws the content and shows the dialog
    @param {EmailWidgetOptions}
    @description {
    isDebug: true,      // Needs changed for production
    to: null,           // {string} person to send email to
    from: null,         // {string} person to send email from
    subject: null,      // {string} subject of email
    body: null,         // {string} message body of email
    link: null,         // {string} link to attach
    onOpen: null,       // {event} fired when modal is opened
    onClose: null,      // {event} fired when modal is closed
    onBeforeSend: null, // {event} fired before sending email
    onAfterSend: null,  // {event} fired after sending email
    dialogElement: null,// {container} div element to put the widget content into
    isFancybox: true    // {bool} true if the modal will be using fancybox, false defaults to jQuery dialog.
    }
    */
    this.show = function (options) {

        // draw the message box
        if ($("#modal-email").children().length == 0) {
            self.options = self.setOptions(options);
            self.draw();
        }

        if (self.options.isFancybox) {
            if ($("#modal-email").children().length == 0) {
                $("#modal-email").append(self.options.dialogElement).modal();
                $('#m_modal-email.modal .content div textarea').val('');
                //$('#m_modal-email.modal .content div input').val(''); //-- disabled to provide user submitted from address
                $('#m_modal-email.modal .content div span.error').attr("style", "display:none");
            } else {
                $("#m_modal-email").modal();
                $('#m_modal-email.modal .content div textarea').val('');
                //$('#m_modal-email.modal .content div input').val('');
                $('#m_modal-email.modal .content div span.error').attr("style", "display:none");
            }
        }
        else {
            self.options.dialogElement.dialog({
                autoOpen: true,
                closeOnEscape: true,
                modal: true,
                position: 'center',
                resizeable: false,
                title: "DoubleTakeDeals Email Share",
                close: self.close
            });
        }

    };

    /**
    @function draws the dialog content
    */
    this.draw = function () {
        var con = self.options.dialogElement;

        if (!con) {
            con = $('<div id="modal-EmailWidgetContainer"></div>');
            self.options.dialogElement = con;
        }

        con.append("<h5>Sharing is good!</h5><p>It's easy too! Simply complete the form below.</p>");

        var div = $('<div></div>');

        var newRow = function (elementA, elementB, requiredError, requiredClass, invalidError, invalidClass) {
            return (div.clone().append(
                $('<label></label>').append(elementA)).append($('<span class="error" style="display:none;"></span>').addClass(requiredClass).append(requiredError)).append($('<span class="error" style="display:none;"></span>').addClass(invalidClass).append(invalidError)).append(elementB)
                );
        };

        var msgData = {
            to: $('<textarea rows="4" cols="43" id="modal-EmailWidgetContainer_to" />'),
            from: $('<input type="text" id="modal-EmailWidgetContainer_from" style="width:90%;" />'),
            subject: $('<div id="modal-EmailWidgetContainer_subject" class="ewStaticText">I think you might like DealChicken</div>'),
            body: null,
            link: $('<div id="modal-EmailWidgetContainer_link" class="ewStaticText" style="text-decoration:none; color: #2284CD;">http://www.dealchicken.com</div>')
        };

        var msgOptions = {
            to: $('<textarea rows="4" cols="36" id="modal-EmailWidgetContainer_to" />'),
            from: $('<input type="text" id="modal-EmailWidgetContainer_from" style="width:90%;" value="' + self.options.from + '"/>'),
            subject: $('<div id="modal-EmailWidgetContainer_subject">' + self.options.subject + '</div>'),
            body: $('<div id="modal-EmailWidgetContainer_body">' + self.options.body + '</div>'),
            link: $('<div id="modal-EmailWidgetContainer_link" style="text-decoration:none; color:#f58023;">' + self.options.link + '</div>')
        };

        for (var prop in msgData) {
            if (self.options.isDebug) {
                console.log("self.options[" + prop + "] = " + self.options[prop]);
            }
            self.options[prop] = (self.options[prop] != null) ? msgOptions[prop] : msgData[prop];

            if (self.options.isDebug) {
                console.log("self.options[" + prop + "] = " + self.options[prop]);
            }
        }

        if (self.options.isDebug) {
            console.log("drawing: ");
            console.dir(self.options);
        }

        self.options.link.hover(function () { $(this).css("text-decoration", "underline"); }, function () { $(this).css("text-decoration", "none"); });

        var cancelButton = $('<a class="large button" style="cursor:pointer;">Cancel</a>');
        var sendButton = $('<a class="large green button" style="cursor:pointer;">Send</a>');

        cancelButton.click(function () {
            self.close();
        });
        $('a#fancybox-close').click(function () {
            self.close();
        });
        sendButton.click(function () {
            self.send();
        });

        con.append(
                newRow("To (separate multiple addresses with a comma)", self.options.to, "Recipient email is required", "to-required", "Please enter valid email", "to-invalid"),
                newRow("From", self.options.from, "Sender email is required", "from-required", "Please enter valid email", "from-invalid")
        );

        var dvButtonContainer = $('<div></div>');
        dvButtonContainer.append(sendButton);
        dvButtonContainer.append(cancelButton);
        con.append(dvButtonContainer);
    };

    /**
    @function draws the Thank You content into the dialog
    */
    this.drawThankYou = function () {
        ///TODO: Finish this EmailWidget.drawThankYou
        self.close();
    };

    /**
    @function draws the Error message into the dialog
    */
    this.drawError = function () {
        ///TODO: Finish this EmailWidget.drawError
        self.close();
    };

    this.valid = function (email, type) {
        if (email == "" || email == null || typeof email == 'undefined') {
            if (type == "to") {
                $('.modal .content div span.to-required').removeAttr('style');
                $('.modal .content div span.to-invalid').attr('style', 'display:none');
                return false;
            }
            if (type == "from") {
                $('.modal .content div span.from-required').removeAttr('style');
                $('.modal .content div span.from-invalid').attr('style', 'display:none');
                return false;
            }
        } else if (!EMAIL_REGEX.test(email)) {
            if (type == "to") {
                $('.modal .content div span.to-required').attr('style', 'display:none');
                $('.modal .content div span.to-invalid').removeAttr('style');
                return false;
            }
            if (type == "from") {
                $('.modal .content div span.from-required').attr('style', 'display:none');
                $('.modal .content div span.from-invalid').removeAttr('style');
                return false;
            }
        } else {
            if (type == "to") {
                $('.modal .content div span.to-required').attr('style', 'display:none');
                $('.modal .content div span.to-invalid').attr('style', 'display:none');
                return true;
            }
            if (type == "from") {
                $('.modal .content div span.from-required').attr('style', 'display:none');
                $('.modal .content div span.from-invalid').attr('style', 'display:none');
                return true;
            }
        }
    };

    /**
    @function sends the message with the supplied content
    */
    this.send = function () {
        if (self.options.onBeforeSend) {
            self.options.onBeforeSend();
        }

        // transport data
        var isStaticText = self.options.from.hasClass("ewStaticText");
        var _from = "";
        var friendList = "";
        var goodMail = true;
        var friendMail = self.options.to.val();

        //remove linebreaks, spaces
        friendMail = friendMail.replace(/(\r\n|\n|\r)/gm, '');
        friendMail = friendMail.replace(/\s+/g, '');

        if (isStaticText) {
            _from = self.options.from.html();
        } else {
            _from = self.options.from.val();
        }
        goodFromMail = self.valid(_from, "from");


        while (friendMail.length > 0 && (friendMail.length - 1 == friendMail.lastIndexOf("\n") || friendMail.length - 1 == friendMail.lastIndexOf(",") ||
            friendMail.length - 1 == friendMail.lastIndexOf(";") || friendMail.length - 1 == friendMail.lastIndexOf(" "))) {
            friendMail = friendMail.substr(0, friendMail.length - 1);
        }

        friendList = friendMail.split(",");
        for (f in friendList) {
            goodMail = self.valid(friendList[f], "to");
            if (goodMail == false) {
                return false;
            }
        }

        if (goodMail && goodFromMail) {
            var msgData = {};
            if (isStaticText) {
                msgData = {
                    to: self.options.to.val(),
                    from: _from,
                    subject: self.options.subject.html(),
                    body: self.options.body.html(),
                    link: encodeURIComponent('<a href="http://' + self.options.link.html() + '">' + self.options.link.html() + '</a>'),
                    dealLocId: self.options.dealLocId,
                    dealId: self.options.dealId
                };
            } else {
                msgData = {
                    to: self.options.to.val(),
                    from: _from,
                    subject: self.options.subject.html(),
                    body: self.options.body.html(),
                    link: encodeURIComponent('<a href="http://' + self.options.link.html() + '">' + self.options.link.html() + '</a>'),
                    dealLocId: self.options.dealLocId,
                    dealId: self.options.dealId
                };
            }

            if (self.options.isDebug) {
                console.log("msgData:");
                console.dir(msgData);
            }

            var idx = 0;
            var curIdx = 0;

            msgData.to = friendMail;

            $.ajax({
                url: "/WebServices/EmailShare.asmx/SendMessage",
                type: "POST",
                dataType: "json",
                data: msgData,
                beforeSend: function () {
                    if (self.options.onBeforeSend) {
                        self.options.onBeforeSend();
                    }

                },
                success: function (json) {
                    if (json.code == 0) {
                        $.fancybox.close();
                        //self.close();
                        self.clear();
                    }
                    else {
                        self.drawError();
                    }
                },
                complete: function (json) {
                    if (self.options.onAfterSend) {
                        self.options.onAfterSend();
                    }
                },
                error: function (json) {
                    if (self.options.isDebug) {
                        console.log(json);
                    }
                }

            });
        }
    };

    /**
    @function closes the EmailWidget and cleans up
    */
    this.close = function () {
        $.fancybox.close();
        $('#m_modal-email div span.error').attr('style', 'display:none');
        $('#m_modal-email.modal .content div textarea').val('');
        //$('#m_modal-email.modal .content div input').val('');
    };

    /**
    @function cleans up
    */
    this.clear = function () {
        // clear binds
        $.each(self.options.dialogElement.children(), function (i, item) {
            try { item.unbind(); } catch (e) {
                if (self.options.isDebug) {
                    console.log(e);
                }
            }
        });
        // empty container
        self.options.dialogElement.empty();

        self.options.dialogElement.parent().empty().remove();
    };

    /**
    @function safely hides the fancybox/dialog
    */
    this.hide = function () {

        if (self.options.isFancybox) {
            //try to hide it if its a fancybox
            try {
                $.fancybox.close();
            } catch (ex) {
                if (self.options.isDebug) {
                    console.log(ex);
                }
            }

        } else {
            // try to hide it if its a dialog
            try {
                self.options.dialogElement.dialog("close");
            } catch (ex) {
                if (self.options.isDebug) {
                    console.log(ex);
                }
            }
        }
    };
};
