//
// Behold, the ugly JS that a man can write alone on christmas day with a bottle of 2005 cabernet franc
//
$(function() {
    setBg();
    
    setTimeout(function() { $("#what").fadeIn(1000); }, 700);
    animate(1000, true);
    if (document.createElement("canvas").getContext) {
        (function draw() {  
            var ctx = $("#bg").get(0).getContext('2d');   
            var radgrad = ctx.createRadialGradient(800, 225, 600, 800, 225, 100);  
            radgrad.addColorStop(0, '#203150');   
            radgrad.addColorStop(.8, '#435d91');   
            radgrad.addColorStop(1, '#5d85c8');
            ctx.fillStyle = radgrad;  
            ctx.fillRect(0,0,1600,1600);

            var height = 690;
            ctx = $("#baseBg").get(0).getContext('2d');   
            ctx.beginPath();
            ctx.moveTo(0, 0);
            ctx.lineTo(673, 0);
            ctx.lineTo(673, height - 6);
            ctx.quadraticCurveTo(673, height, 667, height);
            ctx.lineTo(6, height);
            ctx.quadraticCurveTo(0, height, 0, height - 6);
            ctx.lineTo(0, 0);
            radgrad = ctx.createRadialGradient(336, 10, 200, 336, 1, 50);  
            radgrad.addColorStop(0, '#031127');   
            radgrad.addColorStop(.2, '#16366b');   
            radgrad.addColorStop(1, '#2d4e85');
            ctx.globalAlpha = 0.6;
            ctx.fillStyle = radgrad;  
            ctx.shadowOffsetX = 1;  
            ctx.shadowOffsetY = 1;  
            ctx.shadowBlur = 1;  
            ctx.shadowColor = "rgba(0, 0, 0, 0.3)";     
            ctx.fill();
            
            ctx = $("#videoBg").get(0).getContext('2d');
            ctx.beginPath();
            ctx.moveTo(0, 0);
            ctx.lineTo(490, 0);
            ctx.lineTo(490, height - 6);
            ctx.quadraticCurveTo(490, height, 484, height);
            ctx.lineTo(6, height);
            ctx.quadraticCurveTo(0, height, 0, height - 6);
            ctx.lineTo(0, 0);
            radgrad = ctx.createRadialGradient(245, 10, 220, 245, 1, 50);  
            radgrad.addColorStop(0, '#0A172E');   
            radgrad.addColorStop(.2, '#16366b');   
            radgrad.addColorStop(1, '#2d4e85');
            ctx.globalAlpha = 1;
            ctx.fillStyle = radgrad;  
            ctx.shadowOffsetX = 1;  
            ctx.shadowOffsetY = 1;  
            ctx.shadowBlur = 1;  
            ctx.shadowColor = "rgba(0, 0, 0, 0.3)";     
            ctx.fill();            
            
            ctx = $("#titleBg").get(0).getContext('2d');
            ctx.beginPath();
            ctx.moveTo(0, 6);
            ctx.quadraticCurveTo(0, 0, 6, 0);
            ctx.lineTo(667, 0);
            ctx.quadraticCurveTo(673, 0, 673, 6);
            ctx.lineTo(673, 87);
            ctx.lineTo(0, 87);
            ctx.lineTo(0, 6);
            radgrad = ctx.createRadialGradient(336, 280, 200, 336, 130, 20);  
            radgrad.addColorStop(0, '#031127');   
            radgrad.addColorStop(.8, '#16366b');   
            radgrad.addColorStop(1, '#2d4e85');
            ctx.globalAlpha = 0.6;
            ctx.fillStyle = radgrad;  
            ctx.shadowOffsetX = 1;  
            ctx.shadowOffsetY = 1;  
            ctx.shadowBlur = 1;  
            ctx.shadowColor = "rgba(0, 0, 0, 0.3)";     
            ctx.fill();
        })();
    };
    
    var setColor = function(el) {
        $(el).css({ color: "#333333" });        
    };
    var resetColor = function(el) {
        $(el).css({ color: "#666666" });        
    };
    
    $("#userName").focus(function() {
        reset(this, false, false, "@your-username");
        setColor(this);
    }).blur(function() {
        reset(this, true, resetColor);        
    });
    
    $("#userText").focus(function() {
        reset(this);
        setColor(this);
    }).blur(function() {
        reset(this, true, resetColor);   
    });
    
    var hoverAction;
    $("#iconContainer img").live("mouseover", function() { 
        $(this).css({ opacity: 1 });        
        var that = this;
        hoverAction = setTimeout(function() {
            selectIcon($(that).attr("id").replace("img-", ""));
        }, 100); 
    }).live("mouseout", function() {
        if (hoverAction) {
            clearTimeout(hoverAction);            
        }
        $(this).css({ opacity: .8 });
    });
    
    //
    // Set a default
    //
    var hover = $("#hover");
    var first = $("img.mini:first");
    hover.find(".contents").html($("#text-" + first.attr("id").replace("img-", "")).html());
    $("#selectedIcon").css({ left: $(first).offset().left + 2 + "px" });
    
    var unhover = false;
    $("#glass").hover(function() {
        unHover = setTimeout(function() {
            $("#hover").animate({ opacity: 0 }, 300, function() {
                $(this).hide();
            });            
            $("#glass").animate({ opacity: 0 }, 300, function() {
                $(this).hide();
            });
        }, 150);
    }, function() {
        if (unHover) {
            clearTimeout(unHover);            
        }
    });
    
    var keyAction = function(e, offset) {
        var item = $("#userText");
        var val = item.val()
        offset = offset || 0;
        var newLength = 2000 - (val.length + (e.keyCode != 46 && e.keyCode != 8 ? offset : 0));
        if (newLength <= 0) {
            item.val(val.substring(0, 2000));
            newLength = 0;
        }
        $("#limit span").html(newLength);
    };
    $("#userText").keypress(function(e) { keyAction(e, 1); }).keyup(function(e) { keyAction(e, 0) });
    
    setTimeout(function() {
        var hash = document.location.hash.replace("#", "")
        var selected = parseInt(hash);
        var vid = parseInt(hash.replace("v", ""));
        if (selected > 0 && $("#img-" + selected).length > 0) {
            setTimeout(function() { selectIcon(selected, true); }, 1000);
        } else if (vid > 0 && videos.length >= vid) {
            navigateVideo(videos.length - vid);
        }
    }, 1000);
    
    navigateVideo();
});

var videoId = 0;
var navigateVideo = function(mov) {
    $(".arrow").blur();
    
    mov = mov || 0;
    if (mov != 0 && videos.length > (videoId + mov) && (0 <= videoId + mov)) {
        videoId+=mov;
        var video = videos[videoId];
        $("#embed").html('<object width="320" height="180"><param name="wmode" value="transparent"><param value="true" name="allowfullscreen"/><param value="always" name="allowscriptaccess"/><param value="http://vimeo.com/moogaloop.swf?clip_id=' + video.url + '&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" name="movie"/><embed width="320" height="180" wmode="transparent" allowscriptaccess="always" allowfullscreen="true" type="application/x-shockwave-flash" src="http://vimeo.com/moogaloop.swf?clip_id=' + video.url + '&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1"/></object>');        
        $("#description span").html(video.date);
    }
    
    if (videoId < videos.length - 1) {
        $("#video-left").addClass("active");
    } else {
        $("#video-left").removeClass("active");        
    }
    if (videoId > 0) {
        $("#video-right").addClass("active");        
    } else {
        $("#video-right").removeClass("active");  
    }
};

var selectIcon = function(id, skip) {
    var hover = $("#hover");
    var selected = $("#img-" + id);
    var parent = selected.parent()
    $("#iconContainerInner a.selected").removeClass("selected");
    parent.addClass("selected");
    var width = $(document).width() - ($(document).width() - $(window).width());
    var left = $(selected).offset().left + 2;
    hover.find(".contents").html($("#text-" + id).html());
    if (hover.css("display") == "none") {
        hover.show().animate({ opacity: 1 }, 300);
        //if (!skip) {
            $("#glass").css({ width: $(document).width(), height: $(document).height() }).show().animate({ opacity: .5 }, 300);            
        //}
    }
    var relWidth = (width - $("#iconContainer").width()) / 2;
    if (left < (width - relWidth) && left >= relWidth) {
        $("#selectedIcon").css({ left: left + "px" });
    } else if (left >= (width - relWidth)){
        setIdeaScroll()(-1, $("#next"));
    } else {
        setIdeaScroll()(1, $("#last"));
    }
    iterateIdeas(parent);
};

$(window).resize(function(){
    setBg();
});

var iterateIdeas = function(selected) {
    selected = selected || $("#iconContainerInner a.selected");
    var left = $("#arrow-left").blur().unbind("click");
    var right = $("#arrow-right").blur().unbind("click");
    var prev = selected.prevAll("a");
    if (prev.length > 0) {
        left.addClass("active");
        left.click(function() {
            selectIcon($(prev[0]).find("img").attr("id").replace("img-", ""));
        });
    } else {
        left.removeClass("active");
    }
    var next = selected.nextAll("a");
    if (next.length > 0) {
        right.addClass("active");
        right.click(function() {
            selectIcon($(next[0]).find("img").attr("id").replace("img-", ""));
        });
    } else {
        right.removeClass("active");
    }
};

var animating = false; //Ugly I know, FML
var animate = function(delay, firstLoad) {
    $("#logo,#mode").blur();
    
    var direction = arguments.callee.direction = -arguments.callee.direction || 1;
    var wingAnimation = [!$.browser.msie ? "273px" : "265px",1];
    var leftAnimation = !$.browser.msie ? "5px" : "7px";
    var contentAnimation = 0;
    var baseAnimation = "555px";
    var userAnimation = 1;
    var ideaAnimation = 0;
    var timeOut = [delay || 0,0,500,500,600];
    var mode = "Anti-Stealth";
    var title = ["-5px","95px", 300];
    var connector = [0,150];
    var embed = 1;
    
    if (direction == -1) {
        wingAnimation = [0,0];
        leftAnimation = "280px";
        contentAnimation = "-200px";
        baseAnimation = 0;
        userAnimation = 0;
        ideaAnimation = "-33px";
        timeOut = [0,700,0,500,0];
        mode = "Stealth";
        title = ["95px",0, 0];
        connector = [0,0];
        embed = 0;
    }
    
    $("#mode span").html(mode);
    if (!animating) {
        animating = true;
        setTimeout(function() { animating = false; }, 800);
        setTimeout(function() {
                setTimeout(function() {
        	        $("#right-wing").animate({ width: wingAnimation[0], opacity: wingAnimation[1] }, 500);
        		    $("#left-wing").animate({ width: wingAnimation[0], left: leftAnimation, opacity: wingAnimation[1] }, 500);                
                }, timeOut[1]);
                setTimeout(function() {
                    $("#baseContent").animate({ top: contentAnimation }, 800);
                    $("#base").animate({ height: baseAnimation }, 700);
                    setTimeout(function() {
                        $("#directMe").animate({ opacity: connector[0] }, 400);
                    }, connector[1]);
                }, timeOut[2]);
                setTimeout(function() {
                    $("#title").animate({ top: title[0], height: title[1] }, 800);
                }, title[2]);
            $("#logo").blur();
    	    setTimeout(function() { $(".user").animate({ opacity: userAnimation }, 500); }, timeOut[3]);
    	    setTimeout(function() { 
    	        var container = $("#ideaContainer");
    	        container.show().animate({ top: ideaAnimation }, 500); 
                setTimeout(function() { 
                    if (direction == -1) { 
                        container.hide() 
                    }
                }, 500);
                if (firstLoad) {

                }
    	    }, timeOut[4]);
    	}, timeOut[0]);
    }
};

var setBg = function(offset) {
    offset = offset || 0;
    var width = $(window).width();
    var height = $(document).height();
    $("#bgContainer").css({ width: width - offset + "px", height: height + "px" });
    $("#bg").css({ left: width/2 - 800 + "px" });
	$("#ideaContainer").css({ width: width - offset + "px" });
	var iconWidth = width - 200;
	var offset = iconWidth % 28;	
	$("#iconContainer").css({ width: iconWidth - offset + "px" });
	$("#hover .contents").css({ width: iconWidth - offset + "px" });
    $("#iconContainerInner").animate({ left: 0 }, 500, setIdeaScroll);
};

var posting = false;
var post = function() {
    if (!posting) {
        posting = true;
        $("#submit").blur();
        $("#loader").show();
        var name = $("#userName").val();
        var text = $("#userText").val();

        var newWindow;
        var actions = [function() {
            $("#loader").hide();
            $("#error").show().html("Please fill out both fields.");
            posting = false;
        }, function() {
            $("#loader").hide();
            $("#error").show().html("Please provide a valid Twitter username.");        
            posting = false;
        }, function() {
            $("#loader").hide();
            $("#iconContainer").load("/welcome/ideas");
            $("#ideaCount span").html(parseInt($("#ideaCount span").html()) + 1);
            setIdeaScroll();
            $("#twitterContainer").children().hide();
            $("#twitterContainer").append("<div id=\"thanks\"><span>Thanks!</span>&nbsp;&nbsp;Be sure to keep up to date with us on <a href=\"http://www.twitter.com/untitledstartup\">Twitter</a>.<br /><br />Exciting stuff is on the way and we'll need plenty more of your input.<br /><br /><a href=\"javascript:newIdea();\">Share another idea</a>.</div>");
            posting = false;
        }, function() {
            var interval = setInterval(function() {
                if (newWindow.closed) {
                  actions[2]();
                  clearInterval(interval);
            	}
            }, 1000);
        }];

        var public = $("#privacy input:checked").val();

        $.post("add", { name: name, text: text, public: public }, function(data) {
            actions[data.response]();
        }, "json");

        if (text.length > 0 && text != "What you think we're working on...") {
            newWindow = window.open("/welcome/twitter", "twitterWindow", "location=0,status=0,width=800,height=385");
            if (public != "y") {
                alert("We only use Twitter for verification and will NOT do anything with your account.");
                newWindow.focus();
            }
        }
    } 
};

var setIdeaScroll = function() {
    var width = parseInt($("#iconContainer").css("width").replace("px", ""));
    var length = $("#iconContainer img.mini").length;
    var iconWidth = (length - 1) * 28;
    var left = parseInt($("#iconContainerInner").css("left").replace("px", ""));
    $(".scroller").remove();
    var clickEvent = function(direction) {
        var selected = $("#selectedIcon");
        selected.fadeOut(100);
        $("#iconContainerInner").animate({ left: left + (direction * width) + "px" }, 500, function() {
            setIdeaScroll();
            var position = direction == -1 ? Math.round(-(left + (direction * width)) / 28) :  Math.round((-(left) / 28) - 1);
            selectIcon($($("#iconContainer img.mini")[position]).attr("id").replace("img-", ""));
            selected.fadeIn(100);
        });
    };
    var more = $(document.createElement("a")).attr({ 'class': "scroller", href: "javascript: void(0);", id: "more" }).click(function() { $(this).blur(); }).html("&raquo;");
    var less = $(document.createElement("a")).attr({ 'class': "scroller", href: "javascript: void(0);", id: "less" }).click(function() { $(this).blur(); }).html("&laquo;");
    if (-(left) + width <= iconWidth) {
        more.click(function() {
            clickEvent(-1, this);
        }).css({ color: "#FFFFFF" });
    }    
    if (-width - left >= 0) {
        less.click(function() {
            clickEvent(1, this);
        }).css({ color: "#FFFFFF" });
    }
    $("#ideaContainer").append(more).append(less);
    
    return clickEvent;
};

var newIdea = function() {
    $("#thanks").remove();
    $("#userText").val("").focus();
    $("#limit span").html(2000);
    
    $.each($("#twitterContainer").children(), function() {
        if ($(this).attr("id") != "loader" && $(this).attr("id") != "error") {
            $(this).show();
        }
    });
};

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("");
        }
    }
};
