﻿AI = (typeof(AI) == "object") ? AI : {};
AI.SURL = {
    prefix: "",
    ext: "rails",
    api: "http://lab.ai/app/surl/",
    selector: ".surl",
    host: "http://lab.ai/",
    gtags: [/^utm(.*)$/gi],
    display: {
        impression: false,
        view: false,
        like: false,
        share: true,
        tweet: true
    },
    qtip: function(e, message) {

        // Destroy currrent tooltip if present
        if (e.data("qtip")) e.qtip("destroy");

        e.qtip({
            content: message, // Set the tooltip content to the current corner
            position: {
                corner: {
                    tooltip: 'bottomMiddle', // Use the corner...
                    target: 'topRight' // ...and opposite corner
                }
            },
            show: {
                when: false, // Don't specify a show event
                ready: true, // Show the tooltip when ready
                effect: {
                    type: 'fade',
                    length: 700
                }
            },
            hide: { when: { event: 'keyup'} },
            style: {
                border: {
                    width: 5,
                    radius: 5
                },
                padding: 7,
                //textAlign: 'center',
                tip: true, // Give it a speech bubble tip with automatic corner detection
                name: 'light' // Style it according to the preset 'cream' style
            },
            api: {
                onShow: function() {
                    setTimeout(function() {
                        if (e.data("qtip")) e.qtip("destroy");
                    }, 3000);
                }
            }
        });
    },
    bind: function(config) {
        var _this = this;
        var _conf = config || {};
        _conf.prefix = _conf.prefix || this.prefix;
        _conf.api = _conf.api || this.api;
        _conf.group = _conf.group || "default";
        _conf.selector = _conf.selector || this.selector;
        _conf.display = _conf.display || this.display;
        _conf.gtags = _conf.gtags || this.gtags;
        _conf.host = _conf.host || this.host;
        _conf.ext = _conf.ext || this.ext;
        var listUrls = [];
        var detailUrls = [];
        var cleanUrl = function(url) {
            var rules = _conf.gtags;
            if (url.indexOf("?") == -1) return url;
            var s = url.split("?");
            var np = [];
            $.each(s[1].split("&"), function(i, o) {
                var b = false;
                for (var j = 0; j < rules.length; j++) {
                    if (rules[j].test(o) === true || rules[j].test(o) === true) {
                        b = true;
                        break;
                    }
                }
                if (!b) np.push(o);
            });
            s[1] = np.join("&");
            return ($.trim(s[1]) == "") ? s[0] : s.join("?");
        };
        var updateValue = function(ul, o) {
            var b = o.canLike && o.canDisLike;
            if (typeof (o.like) == "number") {
                $(".btn_like").attr("alt", "like");
                if (!b) $(".btn_like", ul).addClass("disabled");
                $(".span_like", ul).html(o.like + "").next().html((o.like > 1) ? "Likes" : "Like");
            }
            if (typeof (o.dislike) == "number") {
                $(".btn_dislike").attr("alt", "dislike");
                if (!b) $(".btn_dislike", ul).addClass("disabled");
                $(".span_dislike", ul).html(o.dislike + "").next().html((o.dislike > 1) ? "Dislikes" : "Dislike");
            }
        };
        var postData = function(method, urls, type) {
            $.each(urls, function(index, url) {
                $.ajax({
                    url: _conf.api + [method, _this.ext].join("."),
                    //data:{strUrls:urls.join(","),increaseType:type},
                    data: { strUrls: [url].join(","), increaseType: type },
                    type: "get",
                    dataType: "jsonp",
                    success: function(json) {
                        var res = (typeof (json) == "string") ? eval("(" + json + ")") : json;
                        if (res.success) {
                            var render = (typeof (_conf.renderer) == "function") ? _conf.renderer : function(ul, o, api) {

                                if (typeof (o.facebookSUrl) == "string") {
                                    var fbUrl = "http://www.facebook.com/sharer.php?u=" + encodeURIComponent(_conf.host + o.facebookSUrl);
                                    $(".surl-facebook").click(function() {
                                        if ($(this).is(".disabled")) return false;
                                        window.open(fbUrl, "fbWin", "toolbar=0,status=0,width=626,height=436");
                                        return true;
                                    });
                                }
                                if (!o.canShare)
                                    $(".surl-facebook", ul).addClass("disabled");

                                if (typeof (o.twitterSUrl) == "string") {
                                    var twUrl = "http://twitter.com/home/?status=" + encodeURIComponent(_conf.host + o.twitterSUrl);
                                    $(".surl-twitter").click(function() {
                                        if ($(this).is(".disabled")) return false;
                                        window.open(twUrl, "twWin", "toolbar=0,status=0,width=626,height=436,scrollbars=1");
                                        return true;
                                    });
                                }
                                if (!o.canTweet)
                                    $(".surl-twitter", ul).addClass("disabled");

                                $(".btn_like,.btn_dislike", ul).click(function() {
                                    var a = $(this);
                                    //if(!member_login.isLogin){
                                    /*
                                    if(false){
                                    _this.qtip(a,a.is(".btn_like")
                                    ?
                                    "ท่านไม่สามารถกด Like ได้ กรุณาเข้าระบบ"
                                    :
                                    "ท่านไม่สามารถกด DisLike ได้ กรุณาเข้าระบบ");
                                    return false;
                                    }
                                    */
                                    var alt = a.attr("alt");
                                    if (a.is(".disabled")) {
                                        _this.qtip(a, "คุณกด Like หรือ DisLike แล้ว");
                                        return false;
                                    }
                                    var clickPost = function() {
                                        a.addClass("disabled");
                                        var virtual = "";
                                        $.ajax({
                                            url: api,
                                            data: { strUrls: o.url, type: a.attr("alt") },
                                            type: "get",
                                            dataType: "jsonp",
                                            success: function(json) {
                                                var res = (typeof (json) == "string") ? eval("(" + json + ")") : json;
                                                if (res.success) {
                                                    _this.qtip(a, a.is(".btn_like")
											?
											"คุณกด Like เรียบร้อยแล้ว"
											:
											"คุณกด DisLike เรียบร้อยแล้ว");
                                                    if (a.is(".btn_like")) {
                                                        virtual = '/virtual-event/' + a.attr("data") + '/click-like';
                                                        _gaq.push(['_trackPageview', virtual]);
                                                        //document.title = virtual;
                                                    } else {
                                                        virtual = '/virtual-event/' + a.attr("data") + '/click-dislike';
                                                        _gaq.push(['_trackPageview', virtual]);
                                                    }
                                                    $.each(res.rows, function(i, o) {
                                                        var marker = $(".surl-marker");
                                                        marker.each(function() {
                                                            var ul = $(this);
                                                            if ($.trim(ul.attr("rel")).toLowerCase() == $.trim(o.url).toLowerCase()) {
                                                                updateValue(ul, o);
                                                            }
                                                        });
                                                    });
                                                }
                                            }
                                        });
                                    };
                                    clickPost();
                                    return false;
                                });
                                return ul;
                            };
                            $.each(res.rows, function(i, o) {
                                var marker = $(".surl-marker");
                                marker.each(function() {
                                    var a = $(this);
                                    if ($.trim(a.attr("rel")).toLowerCase() == $.trim(o.url).toLowerCase()) {
                                        if (!a.is(".surl-rendered")) {
                                            render(a, o, _conf.api + ["IncreaseValue", _this.ext].join("."));
                                            a.addClass("surl-rendered");
                                        }
                                        updateValue(a, o, _conf.api + ["IncreaseValue", _this.ext].join("."));
                                    }
                                });
                            });
                        }
                    }
                });
            });
        };
        $(_conf.selector).each(function() {
            var a = $(this);
            var href = a.addClass("surl-group-" + _conf.group + " surl-marker").attr("rel");
            if (typeof (href) != "string" || $.trim(href) == "") {
                href = cleanUrl(window.location.href);
                a.attr("rel", href);
                detailUrls.push(href);
            } else {
                if (_conf.prefix && _conf.prefix != "" && href.toLowerCase().indexOf(_conf.prefix) == -1) {
                    href = cleanUrl(_conf.prefix + href);
                } else {
                    href = cleanUrl(a.attr("rel"));
                }
                a.attr("rel", href);
                listUrls.push(href);
            }
        });
        if (detailUrls.length > 0)
            postData("LoadURLPropertyList", detailUrls, "view");
        if (listUrls.length > 0)
            postData("LoadURLPropertyList", listUrls, "impression");
    }
};

