
var showMessageDrawer = function(message, type) {
    // TODO: Set background color depending on type - error/info/warning.
    var color = {"info": "#d9ffd9", "error": "#ffcccc"}[type];
    var timeout = {"info": 2000, "error": 3000}[type];
    var drawer = $("#drawer");
    drawer.html("<h2>"+ message + "</h2>");
    drawer.slideDown(function() {
      drawer.css("backgroundColor", color);
      setTimeout(function() {
        drawer.css("backgroundColor", "#fff");
        setTimeout(function() { drawer.slideUp() }, timeout);
      }, 1000);
    });
    return false;
}

/**
 * Send user's comments to the server and thank them.
 */
submitFeedback = function() {
    // send data
    var dataStr = "feedbackText=" + $("#feedbackText").val();
    $.ajax({
        type: "POST",
        url: "/feedback/",
        data: dataStr,
        success: function() { }
    }); 

    // show spinner
    $("#feedbackFormControls").hide();
    $("#feedbackFormSpinner").show();

    // show thank-you
    window.setTimeout(function() {
        $("#feedbackFormDiv").hide();
        $("#feedbackThanksDiv").show();    
    }, 2000);

    return false;
}

/**
 * Ensure the form is shown and not the thank-you message after user closes
 * the dialog.
 */
resetFeedbackDialog = function() {
    $("#feedbackFormDiv").show();
    $("#feedbackFormControls").show();
    $("#feedbackFormSpinner").hide();

    $("#feedbackThanksDiv").hide();
}

/**
 * Submit search query and populate Connect Video dialog with the results.
 */
doSearch = function() {
    // TODO: Investigate templating.
    $.getJSON("/search/videos.json?q=" + $("#connectVideoQuery").val(),
              function(json, status) {
                if(status == "success") {
                    var ul = $("#searchResults");
                    ul.empty();

                    $.each(json, function(i, item) {
                        if(item.meta != $("#currentVideo").val()) {
                        var id = "r" + i;
                        var img = $("<img />").attr("src", item.thumbnail).attr("width", "40").attr("height", "30");
                        var radio = $("<input />").attr("type", "radio").attr("name", "vid").attr("id", id).attr("class", item.meta);
                        var li =  $("<li />");
                        var label = $("<label />").attr("for", id);
                        label.append(img);
                        label.append("&nbsp;" + item.title + " &ndash; " + item.uploader);
                        
                        li.append(radio);
                        li.append("&nbsp;");
                        li.append(label);
                        li.appendTo(ul);
                        }
                    });
                    
                    $("#r0").attr("checked", "true");
                    $("#wizardNext").attr("disabled", "")
                }
              });

    return false;    
}

/**
 * Ensure Connect dialog always starts from Step 1.
 */
resetConnectDialog = function() {
    $("#connectVidTwo").hide();
    $("#connectVidThree").hide();
    $("#connectVidOne").show();
    $("#wizardPrev").attr("disabled", "true");
    $("#wizardNext").attr("value", "Next");
    $("#wizardPrev").show();
    $("#wizardNext").show();
}

generate_uid = function() {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var len = 32;
	var uid = "";
	for(var i = 0; i < len; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		uid += chars.substring(rnum, rnum + 1);
	}
	return uid;
}

var showDetailsLayer = function() {
    $("#playRecordedVideoOverlayDiv1").hide();
    $("#playRecordedVideoOverlayDiv2").show();
}

var simplePublish = function() {
    $("#newVideoSpinner2").show();
    $("#newVideoPublishControls2").hide();

    $.post("/video/publish", {n: "aj9"}, function(uid, status) {
            $.post("/video/add_details", {uid: uid, title: $("#newVideoTitle").val(), descr: $("#newVideoDetails").val()}, function(resp, status) {
                window.location.href = "http://vidiowiki.com/watch/"+uid;
            }, "text");
        }, "text");
    
    
    return false;
}

var showLinkToNewVideo = function() {
    $("#playRecordedVideoOverlayDiv1").hide();
    
    // Show spinner
    $("#newVideoSpinner").show();
    $("#newVideoPublishControls").hide();

    $.post("/video/publish", {n: "aj9"}, function(uid, status) {
            $.post("/video/add_details", {uid: uid, title: $("#newVideoTitle").val(), descr: $("#newVideoDetails").val()}, function(resp, status) {
                $("#newVideoSpinner").hide();
                $("#newVideoPublishControls").show();
                $("#playRecordedVideoOverlayDiv2").hide();
                
                $("#newVideoLink").html("http://vidiowiki.com/watch/"+uid);
                $("#newVideoLink").attr("href", "http://vidiowiki.com/watch/"+uid);
                
                $("#playRecordedVideoOverlayDiv3").show();
            }, "text");
        }, "text");
}

var initMindmap = function(json) {
    // FIXME: use code from watch.html instead

    var ld = 100;
    if((window.location.href.indexOf("dnr") != -1) || (window.location.href.indexOf("fp7etg7") != -1)) { ld = 130; }
    
  // // FIXME: Why is this here again?
  // $("a[rel]").overlay({
  //   effect:  "default",
  //   speed:   1,
  //   expose:  {color: '#6f6f6f',
  //   loadSpeed: 1,
  //   closeSpeed: "fast"},
  //   finish:  { top: 5, left: "center" },
  //   close:   ".closeOverlay"
  // });
  
  var canvas = new Canvas('mindmapCanvas', {  
    'injectInto': 'mindmap',  
    'width': 720,  
    'height': 500  
  });
  
  window.ht = new RGraph(canvas, {  
    interpolation: 'linear',  
    levelDistance: ld,
    
    Node: {  
      color: '#2784C3',
      dim: 5,
      overridable: true
    },  
    
    Edge: {  
      color: '#aaa',
      lineWidth: 2,
      overridable: true
    },
    
    duration: 1000,
    clearCanvas: true,
    withLabels: true,
    
    onCreateLabel: function(domElement, node) {  
      domElement.innerHTML = node.name; 
      domElement.onclick = function() {

          $("#blankSlateMindmapSidebar").hide();
          $("#infoBoxMindmapSidebar").show();
          
          if(window.video_info !== undefined && video_info[node.id] !== undefined) {
            var info = video_info[node.id];
    
            $("#mindmapThumbnail").attr("src", info["thumbnail_url"]);
            $("#mindmapThumbnailA").attr("href", info["video_page_url"]);
            $("#mindmapVideoA").attr("href", info["video_page_url"]);
            $("#mindmapVideoA").html(info["video_title"]);
    
            $("#mindmapAuthorA").attr("href", info["author_page_url"]);
            $("#mindmapAuthorA").html(info["author_name"]);

            if(node.id !== VW.globals.lastNodeClicked) {
      
              // TODO: Optimize.
              if(info["connections"][VW.globals.lastNodeClicked] !== undefined) {
                var html = "";
                $.each(info["connections"][VW.globals.lastNodeClicked], function(i, keyword) {
                  html += "<span class='kwhl'>" + keyword + "</span>";
                  if(i < info["connections"][VW.globals.lastNodeClicked].length - 1) {
                    html += ", ";
                  } else {
                    // last element
                  }
                });
        
                $("#mindmapConnectionsKeywords").html(html);
                $("#mindmapConnectionsTitle").html(video_info[VW.globals.lastNodeClicked]["video_title"]);
                $("#mindmapConnections").show();
              } else {
                $("#mindmapConnections").hide();
              }
              VW.globals.lastNodeClicked = node.id;
            }
          }
          
        // Change for non-root node
        if(node.id != json.id) {
            var MAX_HISTORY_SIZE = 5;
            if ($("#history > ul > li").length == MAX_HISTORY_SIZE) {
                // TODO: slide
                $("#history > ul > li:first").remove();
                $("#history > ul").append("<li><a href='#__" + node.id + "'>" + node.name + "</a> &rarr; </li>");
            }
            else {
                $("#history > ul").append("<li><a href='#__" + node.id + "'>" + node.name + "</a> &rarr; </li>");
            }
            $.address.value("_" + node.id);
            $("#playVideo1").attr("href", "#_"+node.id);
            $("#playVideo2").attr("href", "#_"+node.id);
            //$("#history").show();
        }
        
        ht.onClick(node.id);  
      };
    },
    
    onBeforePlotLine: function(adj) {
        if(adj.nodeTo.data["connection"] == "false") {
            adj.data.$color = "#ffffff";
        }
    },
    
    //Take the left style property and  
    //substract half of the label actual width to  
    //center the label.  
    onPlaceLabel: function(domElement, node) {
          var style = domElement.style;
          style.display = '';
          style.cursor = 'pointer';
          
          if (node._depth <= 1) {
              //style.fontSize = "10px";
              //style.color = "#212121";
          } else if(node._depth == 2){
              //style.fontSize = "8px";
              //style.color = "#555";
          } else {
              style.display = 'none';
          }
          
          if(node == Graph.Util.getClosestNodeToOrigin(window.ht.graph, "pos")) {
            //style.fontSize = "12px";
            style.color = "#2784C3";
            style.zIndex = "1";
          }

          var left = parseInt(style.left);
          var w = domElement.offsetWidth;
          style.left = (left - w / 2) + 'px';
          },
          
          onAfterCompute: function() {
            $("#playVideo1").css("display", "inline");
            $("#playVideo2").css("display", "inline");
          }
  });  
      
  window.ht.loadJSON(json);  
  window.ht.refresh();
  
  if($.address.value() != "/") {
      if($.address.value().indexOf("comment") == -1) {
        var nodeId = $.address.value();
        if(nodeId[0] == "/") {
            nodeId = nodeId.substring(2, nodeId.length);
        }
        else {
            nodeId = nodeId.substring(1, nodeId.length);
        }
        playVideo(Graph.Util.getNode(window.ht.graph, nodeId), false);
        ht.onClick(nodeId);
    }
  }
  
  // set initial embed code
  var node = Graph.Util.getClosestNodeToOrigin(window.ht.graph, "pos");
  var extra = "&lt;p style=\"font-size: 80%;\"&gt;&lt;a href=\"http://vidiowiki.com/watch/" + node.id + "&gt;" + node.name + "&lt;/a&gt; on &lt;a href=\"http://vidiowiki.com\"&gt;Vidiowiki&lt;/a&gt;&lt;/p&gt;";
  var str = window.embedCode + extra;
  $("#embedCodeT").attr("innerHTML", str);
}

playVideo = function(node, autoPlay) {
    if(autoPlay) {
        if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
            location.href = "/media/video/" + node.id + ".mp4";
        }
        else {
            window.player.setClip("/media/video/" + node.id + ".flv");
            window.player.play();
        }
    } else {
        recreatePlayer(node.id);
    }

    scroll(0, 0);
    $('#playVideo1').css('display','none');
    $('#playVideo2').css('display','none');

	// Update title.
	// FIXME: Not quite right, the two may be different.
	$("#videoTitle").html(node.name);

    $.get("/manage/supporting_materials_for_video/" + node.id, function(data) {
        if(data == "none") {
            $("#supportingMaterialsInline").html("There aren't any yet.");
            $("#blankGif").attr("height", "12");
        } else {
            $("#supportingMaterialsInline").html(data);
            // Increase height of the box on the left.
            var h = ($("#supportingMaterialsInline").children().length * 24);
            $("#blankGif").attr("height", h);
        }
    });

  // Update embed code.
  // insert embed code
  var extra = "&lt;p style=\"font-size: 80%;\"&gt;&lt;a href=\"http://vidiowiki.com/watch/" + node.id + "&gt;" + node.name + "&lt;/a&gt; on &lt;a href=\"http://vidiowiki.com\"&gt;Vidiowiki&lt;/a&gt;&lt;/p&gt;";
  var str = window.embedCode.replace(window.embedCodeCentralUid, node.id) + extra;
  $("#embedCodeT").attr("innerHTML", str);
}

playSelectedVideo = function() {
  var node = Graph.Util.getClosestNodeToOrigin(window.ht.graph, "pos");
  playVideo(node, true);
}

recreatePlayer = function(videoUid) {
  window.player = $f("player", {
          src: "/resources/flowplayer/flowplayer.commercial-3.1.1.swf",
          wmode: "opaque" },
      { key: "$25eea04ec9ff0a8dd2e",
        clip: { url: "/media/video/" + videoUid + ".flv", autoPlay: false, autoBuffering: true, scaling: "scale" },
      logo: { url: "/resources/images/vw_drops50.png", top: 5, right: 5, opacity: 0.7, displayTime: 0, fadeSpeed: 5000,
              fullscreenOnly: false },
      plugins:  { 
          controls: { all: false, play: true, scrubber: true, time: true, mute: true, volume: true, fullscreen: true,
                      bufferColor: '#333333', progressColor: '#5DA8DC', buttonColor: '#5DA8DC', buttonOverColor: '#7DC8FC', 
                      tooltipColor: '#cc0000',  height: 30, autoHide: 'never', width: '98%', bottom: 0, left: '50%', 
                      borderRadius: 15 } } });
  window.embedCode = $f().embed().getEmbedCode();
  window.embedCodeCentralUid = videoUid+"";
}

/**
 * Set up various event handlers and such.
 */
$(document).ready(    
function() {
    
    var opts = {
        api: true,
        effect: "default",
        speed: 1,
        finish:  { top: 10, left: "center" },
        expose: {
            color: "#6f6f6f",
            loadSpeed: 1,
            closeSpeed: "fast"},
        close: ".closeOverlay"
    };
    
    // Set-up default overlays with APIs.
    var elts = $("a[rel]");
    window.overlayApis = {};
    elts.each(function(i, elt) {
        var api_id = elt.rel;
        var api = $("a[rel|=" + elt.rel + "]").overlay(opts);
        window.overlayApis[api_id] = api;
    });
    
    window.api1 = $("#playRecordedVideoOverlay").overlay({ // c'n'p
        api: true,
        effect: "default",
        speed: 1,
        finish:  { top: 10, left: "center" },
        expose: {
            color: "#6f6f6f",
            loadSpeed: 1,
            closeSpeed: "fast"},
        close: ".closeOverlay",
        onLoad: function() {
            $("#playRecordedVideoOverlayDiv1").show();
            $("#playRecordedVideoOverlayDiv2").hide();
            $("#playRecordedVideoOverlayDiv3").hide();
            // hide spinner
            $("#newVideoSpinner").hide();
            $("#newVideoPublishControls").show();
            // take focus away from Flash
            $("#id_simple_q").focus();
            $("#recorderContainer").hide(); // work around random recording bug
            $("#recorderContainerPlaceholder").show();
            setTimeout(function() {
                $("#oneMomentSpinner").hide();
                window.player.load(); 
            }, 3000);
            
        },
        onClose: function() { $f(0).unload(); $("#recorderContainerPlaceholder").hide();$("#recorderContainer").show(); }
});
        
    // onclick handler for #
    $("#publishButton1").click(showDetailsLayer);
    $("#publishButton2").click(showLinkToNewVideo);
    $("#publishButton3").click(simplePublish);
        
// ----- Feedback dialog
$("button[rel]").overlay({expose:  '#6f6f6f',
    finish:  { top: 10, left: "center" },
    close:   ".closeOverlay",
    onLoad:  function() { $("#feedbackText").focus(); },
    onClose: resetFeedbackDialog
});

    // submit
    // TODO: On form post event rather than button click. Other forms too.
    $("#submitFeedback").click(submitFeedback);
    
    // ----- Connect dialog
    if($("#connectVideoLink").length != 0) {
        $("#connectVideoLink").overlay({
            effect:  "default",
            speed:   1,
            expose:  {
                color: '#6f6f6f',
                loadSpeed: 1,
                closeSpeed: "fast"
            },
            finish:  { top: 5, left: "center" },
            close:   ".closeOverlay",
            onLoad:  function() { 
                $("#connectVideoQuery").focus();
            },
            onClose: resetConnectDialog
        });
    } else {
    }
     
    if(!location.href.toLowerCase().match(/feature/)) {
     
        // setup ul.tabs to work as tabs for each div directly under div.panes 
        $("ul.tabs").tabs("div.panes > div");
    
        $("#wizardPrev").attr("disabled", "true");
        $("#wizardNext").attr("disabled", "true");
        // advance through dialog on Next
        $("#wizardNext").click(function() {
            if($("#connectVidTwo").css("display") == "none") { // on step 1            
                $("#searchResults>li>input").each(function(i) {
                    if($(this).attr("checked") == true) {
                        $.vwConnectTarget = $(this).attr("class");
                    }
                });
            
                $("#connectVidOne").hide();
                $("#connectVidTwo").show();
                $("#wizardNext").attr("value","Connect");
                $("#wizardPrev").attr("disabled", "");
                $("#connectVidKeywords").focus();
            }
            else { // step 2 -- connect
                if($.trim($("#connectVidKeywords").val()) != "") {
                    $("#connectVidTwo").hide();
                    $("#connectVidThree").show();
                    $("#wizardPrev").hide();
                    $("#wizardNext").hide();

                    // async API call
                    data = {
                                v1:  $("#currentVideo").val(),   // "from"
                                v2:  $.vwConnectTarget,          // "to"
                                kws: $("#connectVidKeywords").val()
                            },
                    
                    $.post("/video/connect_videos", data);

                    // update the mindmap
                    $.getJSON("/video/connections/" + $("#currentVideo").val(), function(json_data, status) {
                        window.ht.loadJSON(json_data);
                        window.ht.refresh();
                        });
                    }
                else {
                        alert("Please enter keywords.");
                }
            }
            });
        $("#wizardPrev").click(function() {
                                            //
                                            $("#connectVidOne").show();
                                            $("#connectVidTwo").hide();
                                            $("#wizardPrev").attr("disabled", "true");
                                            $("#wizardNext").attr("value", "Next");
                                            $("#connectVideoQuery").focus();
                                            });


        // Set Ajax handlers for forms.
        $("#submitSearch").click(doSearch);
    
    }
    
    if(location.href.toLowerCase().match(/feature/)) {
        loadMindmapWithJson();
    }
    
    /* {{ dropdowns for IE */
    $("ul.dropdown li").hover(function(){
       $(this).addClass("hover");
       $('> .dir',this).addClass("open");
       $('ul:first',this).css('visibility', 'visible');
     },function(){
       $(this).removeClass("hover");
       $('.open',this).removeClass("open");
       $('ul:first',this).css('visibility', 'hidden');
     });
     /* }} */
});
