﻿// requires jquery
if (!window.jQuery) {
    throw ("jQuery must be referenced before using smstools");
} else {
    (function() {

        var sms_cache = [];

        $.fn.SMS = function(options) {

            var opts = $.extend({}, $.fn.SMS.defaults, options);

            return this.each(function(i) {

                sms_cache.push(null);
                $(this).click(function() { RenderSmsForm(this, i, opts); return false; });
            });
        };

        RenderSmsForm = function(element, index, options) {

            if (sms_cache[index] != null) {

                clearValidation(sms_cache[index]);

                sms_cache[index].fadeIn(200, function() {

                    // sometimes fadeIn breaks in IE, whaddya know
                    if (jQuery.browser.msie) {
                        $(this).show();
                    }
                });

            }
            else {

                var uid = options.containerCssClass + index;

                $('<div class="' + options.containerCssClass + '">' +
                   '<label>Your name:</label><input type="text" size="20" id="name" onKeyPress="return dek(event);" autocomplete="off" /> <br />' +
                   'Enter the mobile phone # with correct area code within USA.<br />' +
                   '<label>Phone:</label> 1 - <input type="text" size="2" maxlength="3" id="areacode" onKeyPress="return dek(event);" autocomplete="off"  /> - ' +
                   '<input id="phone" type="text" size="12" onKeyPress="return dek(event);" autocomplete="off"  /><br />' +
                   '<input type="button" value="Submit" /> ' +
                   '<input type="button" value="Cancel" />' +
                   '</div>')
                .css(
                    {
                        'display': 'none',
                        'position': 'absolute'
                    }
                )
                .attr("id", uid)
                .animate({ "opacity": "show" }, "fast")
                .insertAfter(element)
                .children(":button").click(function() {

                    // clear validation results if there were any
                    clearValidation(sms_cache[index]);

                    switch ($(this).val().toLowerCase()) {
                        case 'submit':

                            var wsParameters = {
                                name: null,
                                areacode: null,
                                phone: null,
                                contentObjectID: options.contentObjectID,
                                contentTypeID: options.contentTypeID
                            };

                            invalidForm = 0;
                            var validationMsgs = [];
                            sms_cache[index].children(":text").each(function() {

                                var valid = 1;

                                if (jQuery.trim($(this).val()) == "") valid = 0;

                                switch ($(this).attr("id")) {
                                    case "name":

                                        wsParameters.name = $(this).val();

                                        if ($(this).val().length > 22) {
                                            validationMsgs.push("Name is too long, maximum 22 characters");
                                            valid = 0;
                                        }
                                        break;
                                    case "areacode":

                                        wsParameters.areacode = $(this).val();

                                        if ($(this).val().match(/^\d{3}$/) == null) {
                                            validationMsgs.push("Area code must be 3 digits long");
                                            valid = 0;
                                        }
                                        break;
                                    case "phone":

                                        wsParameters.phone = $(this).val();

                                        if ($(this).val().match(/^\d{7}$/) == null) {
                                            validationMsgs.push("Phone must be all digits, 7 digits in length");
                                            valid = 0;
                                        }
                                        break;
                                }

                                if (!valid && options.validate) {
                                    $(this).addClass('error');
                                    invalidForm = 1;
                                }

                            });

                            if (invalidForm && options.validate) {
                                for (var i = 0; i < validationMsgs.length; i++) {

                                    $('<div class="validateMessage"></div>').text(validationMsgs[i])
                                        .css({
                                            color: "#FF0000",
                                            paddingLeft: "20px"
                                        })
                                        .appendTo(sms_cache[index]);
                                }
                                return false;
                            }


                            $.ajax({

                                type: "POST",
                                url: options.webServiceURL,
                                data: "{" +
                                                "name: '" + wsParameters.name + "'," +
                                                "areacode: '" + wsParameters.areacode + "'," +
                                                "phone : '" + wsParameters.phone + "'," +
                                                "contentObjectID : '" + wsParameters.contentObjectID + "'," +
                                                "contentTypeID: '" + wsParameters.contentTypeID + "'" +
                                          "}",
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                timeout: 5000, // give a longer timeout
                                cache: false,
                                success: function(json) {
                                    if (json.d == "OK") {
                                        var div = $('<div class="OK"></div>').text("Your sms was sent!").appendTo(sms_cache[index]);

                                        setTimeout(function() {
                                            sms_cache[index].fadeOut(200, function() {
                                                $(div).remove();
                                            });
                                        }, 1500);
                                    }
                                    else {
                                        var div = $('<div class="Warning"></div>').text(json.d).appendTo(sms_cache[index]);

                                        setTimeout(function() {
                                            sms_cache[index].fadeOut(200, function() {
                                                $(div).remove();
                                            });
                                        }, 1500);
                                    }
                                },
                                error: function() {
                                    var div = $('<div class="Error"></div>')
                                                        .text("There was a problem with your request!  Please try again later.")
                                                        .appendTo(sms_cache[index]);

                                    setTimeout(function() {
                                        sms_cache[index].fadeOut(200, function() {
                                            $(div).remove();
                                        });
                                    }, 2000);
                                }
                            });

                            break;
                        case 'cancel':
                            sms_cache[index].fadeOut(200);
                            break;
                    }

                });

                // save it to cache
                sms_cache[index] = $("#" + uid);
            }

        }

        clearValidation = function(obj) {
            $(obj).children(":text").removeClass('error');
            $(obj).children(".validateMessage").remove();
        }

        dek = function(e) {
            var key;
            if (window.event)
                key = window.event.keyCode; //IE
            else
                key = e.which; //firefox      

            return (key != 13);
        }

        $.fn.SMS.defaults = {
            validate: true,
            containerCssClass: 'smsToolContainer',
            webServiceURL: '/WebServices.asmx/SendSMS',
            contentObjectID: 0,
            contentTypeID: 0
        };

    })();
}
