$.fn.qtip.styles.mystyle = { // Last part is the name of the style
    style: { width: { max: 250 } },
    'font-weight': "normal",
    color: "#0D6CBB",
    border: {
        radius: 2
    },
    /** tip: {
     corner:'bottomLeft',
     size:{
     x:10,
     y:1
     }
     }, */
    name: 'blue'
};

function pauseAjaxIndicator() {
    $(document).unbind("ajaxStart");
    $(document).unbind("ajaxStop");
}

function resumeAjaxIndicator() {
    // $(document).ajaxStart(justAMoment).ajaxError(errorHandler).ajaxStop(completed);
}

function errorHandler(event, xhr) {
    if (xhr.status == 401) {
        loginForm();
    }
}

function loginForm() {
    $("#hiddenLoginAlert").click();
}

function justAMoment() {
    pleaseWait("Just a moment...");
}

function pleaseWait(message) {
    var inFacebook = self != top;
    $.blockUI({
        message: '<h1 class="waitMessage"><img src="/images/spinner.gif" /> ' + message + '</h1>',
        overlayCSS:  {
            backgroundColor: '#FFFFFF',
            opacity:         (inFacebook ? 0.5 : 0)
        },
        css: {
            top: (inFacebook ? "250px" : "40%")
        },
        fadeIn:0,
        fadeOut:0,
        showOverlay:true
    });
}

function notification(message) {
    $.blockUI({
        message: '<h1 class="waitMessage">' + message + '</h1>',
        overlayCSS:  {
            backgroundColor: '#000000',
            opacity:         0.2
        },
        fadeIn:0,
        fadeOut:0,
        showOverlay:true
    });
}

function modalNotification(message, seconds, callback) {
    setTimeout(function() {
        $.blockUI({
            message: '<h1 class="waitMessage">' + message + '</h1>',
            overlayCSS:  {
                backgroundColor: '#000000',
                opacity:         0.2
            },
            fadeIn:0,
            fadeOut:0,
            showOverlay:true
        });
        setTimeout(function() {
            completed();
            if (callback) {
                callback();
            }
        }, seconds * 1000);
    }, 100);
}

function completed() {
    $.unblockUI();
}

function closePopup() {
    $.fn.fancybox.close();
}

/**
 * generic trim function.
 */
function trim(str) {
    return str.replace(/(^\s*)|(\s*$)/g, "");
}

/**
 * resize the img if it's offestheight greater than 150
 */
function resize(oImg) {
    if (oImg && oImg.offsetHeight > 150) {
        oImg.height = 150;
    }
}

if (!Array.indexOf) {
    Array.prototype.indexOf = function(obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return -1;
    }
}


(function($) {
    $.fn.vCenter = function(options) {
        var pos = {
            sTop : function() {
                return window.pageYOffset
                        || document.documentElement && document.documentElement.scrollTop
                        || document.body.scrollTop;
            },
            wHeight : function() {
                return window.innerHeight
                        || document.documentElement && document.documentElement.clientHeight
                        || document.body.clientHeight;
            }
        };
        return this.each(function(index) {
            if (index == 0) {
                var $this = $(this);
                var elHeight = $(this).height();
                var elTop = 0;

                if (pos.wHeight() < elHeight) {
                    elTop = pos.sTop() + 50;
                } else {
                    elTop = pos.sTop() + (pos.wHeight() / 2) - (elHeight / 2);
                }
                $this.css({
                    position: 'absolute',
                    marginTop: '0',
                    top: elTop
                });
            }
        });
    };

})(jQuery);

$.expr[":"].econtains = function(obj, index, meta, stack) {
    return (obj.textContent || obj.innerText || $(obj).text() || "").toLowerCase() == meta[3].toLowerCase();
};

$.expr[':'].icontains = function(obj, index, meta, stack) {
    return (obj.textContent || obj.innerText || jQuery(obj).text() || '').toLowerCase().indexOf(meta[3].toLowerCase()) >= 0;
};

if (!Array.prototype.filter) {
    Array.prototype.filter = function(fun /*, thisp*/) {
        var len = this.length;
        if (typeof fun != "function")
            throw new TypeError();

        var res = new Array();
        var thisp = arguments[1];
        for (var i = 0; i < len; i++) {
            if (i in this) {
                var val = this[i]; // in case fun mutates this
                if (fun.call(thisp, val, i, this))
                    res.push(val);
            }
        }

        return res;
    };
}

/** JQuery plugin for spellchecking elements */
(function($) {
    $.fn.checkSpelling = function(options) {
        var elements = $(this);
        setTimeout(function() {
            var allWords = [];
            pauseAjaxIndicator();
            elements.each(function(index) {
                var element = $(this);
                element.find("span.mistake").contents().unwrap();
                // remove non word characters then split the string.
                var checkWords = element.text().replace(/[^\w]/g, ",").split(",");

                // remove words that are too short
                checkWords = checkWords.filter(function(item) {
                    return item.length > 1;
                });
                allWords.push(checkWords.join(","));
            });

            var processResult = function(data, textStatus, xhr) {
                resumeAjaxIndicator();
                if (!data.incorrect) {
                    return;
                }
                elements.each(function(index) {
                    var element = $(this);
                    var html = element.html();
                    var originalHtml = element.html();
                    for (var i = 0; i < data["incorrect"].length; i++) {
                        html = html.replace(new RegExp("\\b" + data["incorrect"][i][0] + "\\b", "ig"), "<span class='mistake'>" + data["incorrect"][i][0] + "</span>");
                    }
                    if (originalHtml != html) {
                        element.html(html);
                    }
                });
            };

            $.post("/spellCheck/check", {words: allWords.join(",")}, processResult, "json");
        }, 500);


    };


})(jQuery);

function setupPing() {
    setInterval(function() {
        $.post("/ping.txt");
    }, 1000 * 60 * 5);
}

function removeTooltip(element) {

}

function createTooltip(element, text, replace) {
    $(element).attr("title", text);
}

function isTouchBrowser(){
    return (
        //Detect iPhone
        (navigator.platform.indexOf("iPhone") >= 0) ||
        //Detect iPod
        (navigator.platform.indexOf("iPod") >= 0) ||
        //Detect iPad
        (navigator.platform.indexOf("iPad") >= 0)
    );
}
