﻿(function ($) {
    $.common = {
        adClick: function(url, title, callback){
            $.ajax({
                async: false,
                type: "POST",
                cache: false,
                url: "/Home/AdClick",
                data: { url: url, title: title },
                success: function () {
                    if ($.isFunction(callback)) {
                        callback();
                    }
                }
            });
        },
        removeLineBreaks: function (t) {
            t = t.replace(/(\r\n|\n|\r)/gm, "");
            return t;
        },
        validateCCNumber: function (n, s) {
            //1) if user enters a card start digit of 9, 8, 7, 2, 1, 0
            //3) If user enters the start digit of 4 and it's NOT 16 digits total
            //6) If user enters a card start digit of 5 and it's NOT 16 digits total
            //7) If user enters a card start digit of 6 and it's NOT 16 digits total
            //9) If user enters a card start digit of 3 and it's NOT 15 digits total
            if (n.length == 0 || s.length == 0)
                return false;
            if (n.charAt(0) == "9" || n.charAt(0) == "8" || n.charAt(0) == "7" || n.charAt(0) == "2" || n.charAt(0) == "1" || n.charAt(0) == "0")
                return false;
            if (n.charAt(0) == "4" && (n.length != 16 || s.length != 3))
                return false;
            if (n.charAt(0) == "5" && (n.length != 16 || s.length != 3))
                return false;
            if (n.charAt(0) == "6" && (n.length != 16 || s.length != 3))
                return false;
            if (n.charAt(0) == "3" && (n.length != 15 || s.length != 4))
                return false;
            return true;
        },
        logon: function (username, password, rememberMe, callback) {
            $.ajax({
                type: "POST",
                cache: false,
                url: "/Account/AjaxLogOn",
                data: { userName: username, password: password, rememberMe: rememberMe },
                success: function () {
                    if ($.isFunction(callback)) {
                        callback(true);
                    }
                },
                error: function () {
                    if ($.isFunction(callback)) {
                        callback(false);
                    }
                }
            });
        },
        displayBetaMessage: function () {
            return;
            var display = $.common.getCookie("betapopup");
            if (display.length == 0) {
                var html = '<div id="beta-message" style="width: 500px; height: 100px; margin: 3px 3px 2px 3px; background-color: #E78F08; padding: 20px;  color: white;">';
                html += '<div style="background-color: #E78F08;"><CENTER><h2 style="color: white;">Welcome to inthepearl.com BETA</h2></CENTER>';
                html += '<br /><br /><div style="font-size: 9pt; font-weight: bold;">inthepearl.com is brand new and we need your help by reviewing your ';
                html += 'favorite businesses! Tell your Pearl story to everyone now! Just click the write a review link.</div></div></div>';

                $.common.setCookie("betapopup", "true");

                $.common.modalDialog(html, true);
            }
        },
        getRandomBusinessImages: function (businessType, number, callback) {
            $.ajax({
                type: "POST",
                cache: false,
                url: "/Business/GetRandomBusinessIds",
                data: { businessType: businessType, number: number },
                success: function (obj) {
                    if ($.isFunction(callback)) {
                        callback(obj);
                    }
                },
                error: function () {
                    callback(null);
                }
            });
        },
        submitRsvp: function (firstName, lastName, business, email, position, session) {
            $.ajax({
                type: "POST",
                cache: false,
                url: "/Home/SendInviteEmail",
                data: { firstName: firstName, lastName: lastName, business: business, email: email, position: position, session: session }
            });
        },
        validateHappyHours: function (startTime, endTime) {
            if (startTime.length > 1)
                startTime = startTime.replace(":", ".");
            if (endTime.length > 1)
                endTime = endTime.replace(":", ".");

            return parseFloat(startTime) < parseFloat(endTime);
        },
        pausecomp: function (millis) {
            var date = new Date();
            var curDate = null;
            do { curDate = new Date(); }
            while(curDate-date < millis);
        },
        modalDialog: function (html, showCloseButton) {
            $.fancybox({
                "Modal": true,
                "autoDimensions": true,
                "autoScale": true,
                "scrolling": "no",
                "padding": 10,
                "showCloseButton": showCloseButton || false,
                "content": html
            });

            $("#beta-message").parent().parent().css("background-color", "#E78F08");
        },
        closeModalDialogTimeout: function (timeout) {
            window.setTimeout("$.fancybox.close()", timeout == null ? 1000 : timeout);
        },
        closeModalDialog: function () {
            $.fancybox.close();
        },
        errorDialog: function (message) {
            var html = "<div>" + message + "</div><div style='margin: 20px;'>";
            html += '<a class="ui-button-text-only ui-state-default ui-corner-all" href="javascript:$.fancybox.close();"><span class="ui-button-text">Close</span></a></div></div>';

            $.common.modalDialog(html);
        },
        flagContentDialog: function (id, type, callback) {
            var html = "<div class='flag-content-dialog-wrapper'><div><h2>Confirm Flag</h2></div><div><h3>Please tell us why you're flagging this content:</h3></div>";
            html += "<div style='margin: 10px;'><textarea id='flagcomments' style='width: 390px; height: 100px;'></textarea></div>";
            html += '<div style="margin: 10px;"><a class="ui-button-text-only ui-state-default ui-corner-all" href="#"><span class="ui-button-text" id="submitFlag">Flag</span></a>&nbsp;';
            html += '<a class="ui-button-text-only ui-state-default ui-corner-all" href="javascript:$.fancybox.close();"><span class="ui-button-text">Cancel</span></a></div>';
            html += '<div style="display: none; color: red; margin-bottom: 10px;" id="commentRequired">&nbsp;</div></div>';

            $.fancybox({
                "Modal": true,
                "autoDimensions": true,
                "autoScale": true,
                "scrolling": "no",
                "padding": 10,
                "content": html,
                "showCloseButton": false,
                "onClosed": callback,
                "onComplete": function () {
                    $("#submitFlag").unbind().click(function () {
                        var comment = $("#flagcomments").val();

                        if (comment.length == 0) {
                            $("#commentRequired").html("*Please tell us why you're flagging this content.").show();
                            return;
                        }

                        $.ajax({
                            type: "POST",
                            cache: false,
                            url: "/Review/FlagContent",
                            data: { id: id, type: type, comment: comment },
                            success: function () {
                                $.fancybox.close();
                            },
                            error: function () {
                                $("#commentRequired").html("Error flagging content").show();
                            }
                        });
                    });
                }
            });
        },
        getHappyHourMinute: function (value) {
            var min = "0";
            if (value.indexOf(":") > -1) {
                min = value.substring(value.indexOf(":") + 1, value.length - value.indexOf(":") + 1);
            }
            return min;
        },
        setInfoMessage: function (msg) {
            $("#info-message strong").html(msg);
        },
        setErrorMessage: function (msg) {
            $("#error-message strong").html(msg);
        },
        setCookie: function (c_name, c_value) {
            var exdate = new Date();
            var exdays = "30";
            exdate.setDate(exdate.getDate() + exdays);
            var c_value = escape(c_value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
            document.cookie = c_name + "=" + c_value;
        },
        isIE: function () {
            var br = navigator.appName;
            if (br == "Microsoft Internet Explorer") {
                return true;
            }
            return false;
        },
        getCookie: function (name) {
            var allcookies = document.cookie.split(";");
            for (var i = 0; i < allcookies.length; i++) {
                x = allcookies[i].substr(0, allcookies[i].indexOf("="));
                y = allcookies[i].substr(allcookies[i].indexOf("=") + 1);
                x = x.replace(/^\s+|\s+$/g, "");
                if (x == name) {
                    return unescape(y);
                }
            }
            return "";
        },
        postify: function (value) {
            var result = {};
            var buildResult = function (object, prefix) {
                for (var key in object) {
                    var postKey = isFinite(key)
                        ? (prefix != "" ? prefix : "") + "[" + key + "]"
                        : (prefix != "" ? prefix + "." : "") + key;
                    switch (typeof (object[key])) {
                        case "number": case "string": case "boolean":
                            result[postKey] = object[key];
                            break;
                        case "object":
                            if (object[key].toUTCString)
                                result[postKey] = object[key].toUTCString().replace("UTC", "GMT");
                            else {
                                buildResult(object[key], postKey != "" ? postKey : key);
                            }
                    }
                }
            };

            buildResult(value, "");

            return result;
        },
        getCCExpirationYears: function (callback) {
            var d = new Date();
            var results = [];

            results.push(d.getFullYear());
            for (var i = 0; i < 7; i++) {
                results.push(d.getFullYear() + i);
            }
            callback(results);
        },
        getCCExpirationMonths: function (callback) {
            var results = [];
            for (var i = 1; i <= 12; i++) {
                results.push(i);
            }
            callback(results);
        },
        getStates: function (callback) {
            var states = ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL", "IN",
            "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM",
            "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV",
            "WI", "WY"];

            callback(states);
        },
        dateDeserialize: function (dateStr) {
            try {
                return eval('new' + dateStr.replace(/\//g, ' '));
            } catch (err) {
                return null;
            }
        },
        dateFriendly: function (dateStr) {
            var dt = this.dateDeserialize(dateStr);
            if (dt != null)
                return (dt.getMonth() + 1) + '/' +
                    dt.getDate() + '/' +
                    dt.getFullYear();
            else return "";
        },
        dateTimeFriendly: function (dateStr) {
            var dt = this.dateDeserialize(dateStr);
            if (dt != null)
                return (dt.getMonth() + 1) + '/' +
                    dt.getDate() + '/' +
                    dt.getFullYear() + ' ' +
                    (dt.getHours() == 0 ? "12" :
                        (dt.getHours() > 12 ? dt.getHours() - 12 : dt.getHours())
                    ) + ":"
                    + (dt.getMinutes() < 10 ? "0" + dt.getMinutes() : dt.getMinutes()) + " " +
                    (dt.getHours() > 12 ? "pm" : "am");

            else return "";

        },
        getTimeDifference: function (earlierDate, laterDate, callback) {
            var nTotalDiff = laterDate.getTime() - earlierDate.getTime();
            var oDiff = new Object();

            oDiff.days = Math.floor(nTotalDiff / 1000 / 60 / 60 / 24);
            nTotalDiff -= oDiff.days * 1000 * 60 * 60 * 24;

            oDiff.hours = Math.floor(nTotalDiff / 1000 / 60 / 60);
            nTotalDiff -= oDiff.hours * 1000 * 60 * 60;
            if (oDiff.hours.toString().length < 2) {
                oDiff.hours = "0" + oDiff.hours;
            }

            oDiff.minutes = Math.floor(nTotalDiff / 1000 / 60);
            nTotalDiff -= oDiff.minutes * 1000 * 60;
            if (oDiff.minutes.toString().length < 2) {
                oDiff.minutes = "0" + oDiff.minutes;
            }

            oDiff.seconds = Math.floor(nTotalDiff / 1000);
            if (oDiff.seconds.toString().length < 2) {
                oDiff.seconds = "0" + oDiff.seconds;
            }

            callback(oDiff);
        },
        validateEmail: function (email) {
            var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
            return reg.test(email);
        },
        checkIfEmailExists: function (email, callback) {
            $.ajax({
                async: false,
                type: "POST",
                cache: false,
                url: "/Account/CheckIfEmailExists",
                data: { email: email },
                success: function (exists) {
                    if ($.isFunction(callback)) {
                        callback(exists);
                    }
                },
                error: function (exists) {
                    if ($.isFunction(callback)) {
                        callback(exists);
                    }
                }
            });
        },
        queryString: function (v) {
            var q = window.location.search.substring(1);
            var vars = q.split("&");
            for (var i = 0; i < vars.length; i++) {
                var p = vars[i].split("=");
                if (p[0] == v) {
                    return p[1];
                }
            }
            return "";
        },
        getValueOrDefault: function (v) {
            if (v == null)
                return "";
            return v;
        },
        escapeComments: function (str) {
            return str.replace(/"/, '\"');
            //return str.replace(/'/, "'");
        }
    }
})(jQuery);
