var tweetmeme_service = 'bit.ly';
var voteActive = false;

var killTwitter = function() {
	var date = new Date();
	date.setTime(date.getTime()-(24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
	document.cookie = "service=twitter"+expires+"; path=/";
	
	document.location.reload();
};

Raphael.fn.drawGrid = function (x, y, w, h, wv, hv, color) {
    color = color || "#000";
    var path = ["M", x, y, "L", x + w, y, x + w, y + h, x, y + h, x, y],
        rowHeight = h / hv,
        columnWidth = w / wv;
    for (var i = 1; i < hv; i++) {
        path = path.concat(["M", x, y + i * rowHeight, "L", x + w, y + i * rowHeight]);
    }
    for (var i = 1; i < wv; i++) {
        path = path.concat(["M", x + i * columnWidth, y, "L", x + i * columnWidth, y + h]);
    }
    return this.path(path.join(",")).attr({stroke: color});
};

$.ajaxSetup({
  data: { key: sessionKey }
});

var setExpiration = function(el, seconds, simple) {
    var element = $("#" + el).find(".expiresIn");
    if (seconds > 0) {
        var clock = new Clock(element, seconds, simple);        
    } else {
        element.html("Poll Has Expired").show();
    }
};

var doFacebookLogin = function(base) {
    if (!$.browser.msie) {
        $("#login").html("<img src=\"" + base + "images/loader.gif\" />");        
    }
    setTimeout(function() {
        document.location.href = document.location.href;
    }, 150);
};

var Clock = function(el, seconds, simple) {
    var that = this;
    this.simple = simple;
    var format = function() {
        if (!simple) {
            el.html("<strong>Expires in</strong> " + that.format(seconds--));            
        } else if (simple.length !== true) {
            el.html(that.format(seconds--));                    
        } else {
            el.html(that.format(seconds--));
        }
    };
    setInterval(format, 1000);
    el.show();
    format();
};

Clock.prototype.format = function(seconds) {
    until = this.parse(seconds);
    
    var text = [];
    if (this.simple !== true) {
        if (until.days < 10) { text.push("0"); }
        text.push(until.days);
        text.push(":");
        if (until.hours < 10) { text.push("0"); }
        text.push(until.hours);
        text.push(":");
    }
    if (until.minutes < 10) { text.push("0"); }
    text.push(until.minutes);
    text.push(":");
    if (until.seconds < 10) { text.push("0"); }    
    text.push(until.seconds);

    
    return text.join("");
};

Clock.prototype.parse = function(seconds) {
    var time = {};
    time.days = Math.floor(seconds / 86400);
    seconds+=-(time.days * 86400);
    
    time.hours = Math.floor(seconds / 3600);
    seconds+=-(time.hours * 3600);
    
    time.minutes = Math.floor(seconds / 60);
    seconds+=-(time.minutes * 60);
    
    time.seconds = seconds;
    
    return time;
};

var highlight = function() {
    var movement = {};
    $("#sign-in, #login .fbconnect_login_button").each(function() {
        var top = $(this).css("top").replace("px", "");
        top = parseInt(top ? top : 0);
        movement[$(this).attr("id")] = [top - 20, top + 10, top - 5, top];
    });
    $("#sign-in, #login .fbconnect_login_button").each(function() {
        var top = movement[$(this).attr("id")];
        var that = $(this);
        that.animate({ top: [top[0], "swing"] }, { duration: 200, queue: true });
        that.animate({ top: [top[1], "swing"] }, { duration: 150, queue: true });
        that.animate({ top: [top[2], "swing"] }, { duration: 100, queue: true });
        that.animate({ top: [top[3], "swing"] }, { duration: 50, queue: true, complete: function() {
            voteActive = false;
        }});
    });
};

var ajaxSuccessTimer;
var triggerPointNotice = function(points, title) {
    clearTimeout(ajaxSuccessTimer);
    var that = $("#ajaxSuccess").css({ opacity: 0 });
    var text = "+" + points + " point" + (points != 1 ? "s" : "");
    if (pageData.isProduct || title) {
        text += " on \"" + (title || pageData.title) + "\"";
    }
    text += "!"
    that.html(text);
    that.css({ opacity: 0 }).show();
    that.animate({ opacity: .95 }, 600);
    ajaxSuccessTimer = setTimeout(function() {
        that.animate({ opacity: 0 }, 600, function() {
            that.hide();
        });
    }, 4000);
}
$(function() {    
    $("body,html").css({background: "#151414"});
    
    $("#ajaxSuccess").mouseover(function() {
        clearTimeout(ajaxSuccessTimer);
    }).click(function() {
        $(this).fadeOut(600);
    }).ajaxSuccess(function(evt, xhr, settings) {
        if (xhr && settings.url != BASE + ITEM_URL + "add") {
            var data = $.parseJSON(xhr.responseText);
            if (data) {
                if (data.success && data.points && data.title) {
                    triggerPointNotice(data.points, data.title);
                } else if (data.success && data.points) {
                    triggerPointNotice(data.points);
                }
            }
        }
    });

    $("#twitter-users a img, #add-a-product .icons img, #categories img, #story-videos img, #people a img, #product-list .contributors a img, #topInfluencers img, #hitlistIndex a, #listVoters img, .product .details h3 img").live("mouseover", function() {
        var that = this.tagName != "IMG" ? $(this).find("img") : $(this);
        var offset = that.offset();
        var margin = parseInt(that.css("margin-right").replace("px", ""));
        if (!margin || margin == 0) {
            if (that.css("width") == "48px") {
                margin = [24,24];
            } else {
                margin = [12,12];                
            }
        } else if (that.closest("#categories").length > 0) {
            margin = [10,-5];
        }
        var alt = that.attr("alt");
        $("<div/>", {
             id: "twitterHover",
             css: {
                 left: offset.left + 16 + margin[0], 
                 top: offset.top - 10 - margin[1]
             }
        }).html(alt).appendTo(document.body);
    }).live("mouseout", function() {
        $("#twitterHover").remove();
    });
    
    $("body").live("mousedown", function(ev) {
        var target = $(ev.srcElement ? ev.srcElement : (ev.target ? ev.target : ev.originalTarget));
        $.each($(".hoverable"), function() {
            if (!target.hasClass("hoverable") && target.closest(".hoverable").length == 0) {
                var callback = $(this).data("callback");
                if (callback) { 
                    callback.call($(this), ev); 
                }
            }
        });
    });
    
    $(".vote").live("click", function() {
        $(this).blur();
        var that = $(this);
        if (!voteActive) {
            voteActive = true
            if (isLoggedIn) {
                var vote = $.grep($(this).attr("class").split(/\s+/), function(n) {
                    return n.indexOf("vote-") === 0;
                })[0].replace("vote-", "");
                var productId = $(this).closest(".product-container").attr("id").replace("product-", "");
                var voteVal = $("#voteHover input:checked").val();
                $("#voteHover").remove();
                $.post(BASE + "votes/add", { vote: vote, productId: productId, tweet: voteVal == "y" }, function(data) {
                    if (data.success) {
                        var li = $(that).closest(".product-container");
                        li.find(".vote, .new").hide();
                        var voteCount = li.find(".vote-count");
                        var previous = parseInt(voteCount.html());
                        voteCount.html(previous + (vote == "up" ? 1 : -1));
                        if (previous == 0 && vote == "up") {
                            li.find(".vote-text").html("POINT");
                        }
                        voteActive = false;
                    }
                }, "json");
            } else {
                var position = { left: that.css("left"), top: that.css("top") };
                that.animate({ left: [532, "swing"], top: [170 - that.offset().top + parseInt(position.top.replace("px", "")) - ($("#categories .invisible").length > 0 ? 50 : 0), "swing"], opacity: 0 }, 1000, function() {
                    setTimeout(function() {
                        that.css({ left: position.left, top: position.top }).animate({ opacity: 1 }, 500);
                    }, 1750);
                });
                if ($(window).scrollTop()) {
                    var i = 0;
                    $("body,html").animate({ scrollTop: 0 }, 1000, function() {
                        if (i == 0) {   
                            highlight();                            
                        }
                        i++;
                    });
                } else {
                    setTimeout(highlight, 1000);
                }            
            }
        }
    }).live("mouseover", function() {
        if (isLoggedIn) {
            if ($("#voteHover").length == 0) {
                var offset = $(this).offset();
                 $("<div/>", {
                     id: "voteHover",
                     css: {
                         left: offset.left + 20, 
                         top: offset.top - 18,
                         position: "absolute",
                         zIndex: 99
                     }
                }).hover(function() {}, function(e) {
                    var target = $(e.relatedTarget || e.toElement);
                    if(!target.hasClass("vote")) {
                        $(this).remove();
                    }                      
                }).html("<div><label><input name=\"tweet\" type=\"radio\" value=\"y\" " + (!tweetSetting ? "checked=\"checked\"" : "") + "/>" + shareMessage + "</label></div><div><label><input name=\"tweet\" type=\"radio\" value=\"n\" " + (tweetSetting ? "checked=\"checked\"" : "") + " />Don't " + shareMessage + "</label></div>").appendTo(document.body).find("input").focus(function() {
                    if($("#voteHover input:checked").val() == "y") {
                        tweetSetting = true;
                    } else {
                        tweetSetting = false;
                    }
                });
            }
        }
    }).live("mouseout", function(e) {
        if (isLoggedIn) {        
            var target = $(e.relatedTarget || e.toElement);
            if(target.attr("id") != "voteHover") {
                $("#voteHover").remove();
            }
        }
    });
    
    
    var reset = function(el, blur, callback, startValue) {
        el = $(el);
        var resetValue = el.data("resetValue");
        var currentValue = el.attr("value");

        if (blur) {
            if (currentValue == "") {
                if (callback) {
                    callback(el);
                }
                $(el).val(resetValue);
            }            
        } else {
            if (!resetValue) {
                el.data("resetValue", currentValue);
            }
            if ((resetValue || currentValue) == currentValue && (currentValue.indexOf("...") >= 0 || currentValue == startValue)) {
                $(el).val("");
            }
        }
    };    

    $("input[class!=basic], textarea[class!=basic], select[class!=basic]").live("focus", function(el) {
        if (this.tagName != "SELECT") {
            reset(this, false, false, $(this).val());            
        }
        $(this).css({ color: "#333333" });
    }).live("blur", function() {
        reset(this, true, function(el) { $(el).css({ color: "#999999" }); });              
    });
    
    $("#scroller li a").hover(function() {
        var offset = $(this).offset(); 
        $("<div/>", {
            id: "activeHover",
            css: {
                left: offset.left - 79, 
                top: offset.top + 52,
                position: "absolute",
                zIndex: 99
            }
        }).html($(this).next(".description").show()).appendTo(document.body);
    }, function() {
        $("#activeHover").remove().children().hide().insertAfter($(this));   
    });

    (function() {
        var arrowAnimating = false;
        var slide = function(direction) {
            var scroller = $("#scroller ul");
            var position = parseInt(scroller.css("left").replace("px", ""));
            var movement = -(direction * 511);
            var count = $("#scroller li").length;

            if (position + movement >= 0 || count <= 7) {
                $("#arrowLeft a").addClass("disabled");
            } else {
                $("#arrowLeft a").removeClass("disabled");                
            }
            
            if (count <= 6 + (-((position + movement) / 490) * 7) || count <= 7) {
                $("#arrowRight a").addClass("disabled");
            } else {
                $("#arrowRight a").removeClass("disabled");                
            }

            if (position + movement <= 0 && count > -1 + (-((position + movement) / 490) * 7)) {
                if (!arrowAnimating) {
                    arrowAnimating = true;
                    scroller.animate({ left: ["+=" + movement, "swing"] }, 500, function() {
                        arrowAnimating = false;
                    });
                }           
            }
        };

        var selected = $("#scroller a.selected");
        if ($("#scroller li").length > 7) {
            $("#arrowRight a").removeClass("disabled");
        }
        if (selected.length > 0) {
            var position = Math.floor((parseInt(selected.attr("id").replace("productList-", "")) - 1) / 7);
            if (position > 0) {
                slide(position);
            }
        }
        
        $("#arrowLeft a").click(function() { slide.call(this, -1); $(this).blur(); });
        $("#arrowRight a").click(function() { slide.call(this, 1); $(this).blur(); });
    })();
});

var Completer = function(el, url, color, opacity) {
    this.el = $(el);
    this.url = url;
    this.color = color;
    this.display = $("#completer").length > 0 ? $("#completer") : false;
    this.opacity = opacity || .9;

    this.attach();
};

Completer.prototype.attach = function() {
    var that = this;
    this.el.keyup(function(ev) { 
        var val = $(this).val();
        if(!that.dispatch(ev, val)) {
            that.monitor(val);            
        } 
    }).keydown(function(ev) {
        var val = $(this).val();
        var method = that.dispatch(ev, val);
        if (method) {
            var hold = method();
            if (hold) {
                ev.preventDefault();                
            }
        }
    });

    $("#completer li").die("mousedown").die("mouseover").die("mouseout").live("mousedown", function(ev) {
        ev.stopPropagation();
        that.display.find("li").removeClass("selected");
        $(this).addClass("selected");
        that.setSelect(that.el.val());
        setTimeout(function() { that.el.focus(); }, 255);
        
        return false;
    }).live("mouseover", function() {
        $(this).css({ fontWeight: "bold" });
    }).live("mouseout", function() {
        $(this).css({ fontWeight: "normal" });        
    });


    var hideCompleterFunc = function() {
        $("#completer").hide();
    };
    this.el.blur(function() { setTimeout(hideCompleterFunc, 50); }).mousedown(hideCompleterFunc);
};

Completer.prototype.getCurrent = function() {
    return this.display.find(".selected");
};

Completer.prototype.dispatch = function(ev, val) {
    var that = this;
    var codes = {    
        13: function() {
            if (that.display.is(":visible")) {
                that.setSelect(val);
                ev.preventDefault();
            }
            
            return true;
        },
        188: function() {
            that.display.hide();
            
            return false;
        },
        27: function() {
            that.display.hide();
            
            return false;
        },
        38: function() {
            var current = that.getCurrent();
            var previous = current.prev();
            if (previous.length > 0) {
                current.removeClass("selected");
                previous.addClass("selected");
            }
            
            return true;
        },
        40: function() {
            var current = that.getCurrent();
            var next = current.next();
            if (next.length > 0) {
                current.removeClass("selected");
                next.addClass("selected");
            } 
            
            return true;           
        }
    };
    
    var request = false
    if (codes[ev.keyCode]) {
        request = codes[ev.keyCode];
    }

    return request;
};

Completer.prototype.setSelect = function(val) {
    var current = this.getCurrent();
    this.el.val(val.replace(/(,?\s*)[^,]*$/, "$1" + current.html()));
    
    var that = this;
    setTimeout(function() { that.display.hide(); }, 50);
};

Completer.prototype.monitor = function(val) {
    var terms = val.split(",");
    var length = terms.length;
    var term = $.trim(terms[length > 0 ? length - 1 : 0]);
    if (term.length >= 1) {
        this.getPossibleTerms(term);        
    }
};

Completer.prototype.getPossibleTerms = function(term) {
    var that = this;
    $.post(BASE + this.url, { term: term }, function(html) {
        that.render(html);
    });
};

Completer.prototype.render = function(html) {    
    color = this.color || "#CCC";
    if (html.length > 0) {
        if (!this.display) {
            var paddingOffset = { width: parseInt(this.el.css("padding-left").replace("px", "")) * 2, height: parseInt(this.el.css("padding-top").replace("px", "")) * 2 };            
            this.dimensions = { width: this.el.width() + paddingOffset.width, height: this.el.height() + paddingOffset.height };
            this.position = this.el.offset();
            this.display = $("<ul>", {
                id: "completer",
                css: {
                    top: this.dimensions.height + this.position.top,
                    left: this.position.left,
                    width: this.dimensions.width,
                    borderLeft: "1px solid " + this.color,
                    borderRight: "1px solid " + this.color,
                    borderBottom: "1px solid " + this.color,
                    opacity: this.opacity                    
                }
            }).appendTo("body");
        } else {
            this.display.show();
        }
        
        this.display.html(html);
    } else {
        if (this.display) {
            this.display.hide();
        }
    }
};
