var NUMBER_OF_STARS = 5;


function logout() {
	document.forms.logout_form.submit();
}

function generateGuid() {
    var result, i, j;
    result = 'ID';
    for(j=0; j<32; j++) {
        if( j == 8 || j == 12|| j == 16|| j == 20) result = result;
        i = Math.floor(Math.random()*16).toString(16).toUpperCase();
        result = result + i;
    }
    return result
} 

var uploadTimer;
var loadingFrame = 1;

function animateLoading() {
    if (!$("#upload_anim").is(':visible')){
        clearInterval(uploadTimer);
        return;
    }
    $("#upload_anim > div").css('top', (loadingFrame * -40) + 'px');
    loadingFrame = (loadingFrame + 1) % 12;
}

function buildHTML() {
    var html = '';
    html += '<div id="upload_anim_overlay"></div>';
    html += '<div class="upload_anim" id="upload_anim"><div>';
    $(html).appendTo("body");
}

function showUploadProgress() {
    buildHTML();
    clearInterval(uploadTimer);
    var pos = [$(window).width(), $(window).height(), $(document).scrollLeft(), $(document).scrollTop() ];
    $("#upload_anim").css({'left': ((pos[0] - 40) / 2 + pos[2]), 'top': ((pos[1] - 40) / 2 + pos[3])}).show();
    loadingTimer = setInterval(animateLoading, 66);
}

function initStaticRating()
{
    var ratings = document.getElementsByTagName('span');
    for (var i = 0; i < ratings.length; i++)
    {
        if (ratings[i].className != 'rating')
            continue;
            
        var rating = ratings[i].firstChild.nodeValue;
        ratings[i].removeChild(ratings[i].firstChild);
        if (rating > NUMBER_OF_STARS || rating < 0)
            continue;
        for (var j = 0; j < NUMBER_OF_STARS; j++)
        {
            var star = document.createElement('img');
            if (rating >= 1)
            {
                star.setAttribute('src', '/images/rating_on.gif');
                star.className = 'on';
                rating--;
            }
            else if(rating == 0.5)
            {
                star.setAttribute('src', '/images/rating_half.gif');
                star.className = 'half';
                rating = 0;
            }
            else
            {
                star.setAttribute('src', '/images/rating_off.gif');
                star.className = 'off';
            }
            ratings[i].appendChild(star);
        } 
    }
}

function initSingleStaticRating(rating_element)
{  
        var rating = $("#" + rating_element).html();
        $("#" + rating_element).html("");
        if (rating <= NUMBER_OF_STARS && rating >= 0) {
	        for (var j = 0; j < NUMBER_OF_STARS; j++)
	        {
	            var star = document.createElement('img');
	            if (rating >= 1)
	            {
	                star.setAttribute('src', '/images/rating_on.gif');
	                star.className = 'on';
	                rating--;
	            }
	            else if(rating == 0.5)
	            {
	                star.setAttribute('src', '/images/rating_half.gif');
	                star.className = 'half';
	                rating = 0;
	            }
	            else
	            {
	                star.setAttribute('src', '/images/rating_off.gif');
	                star.className = 'off';
	            }
	            $("#" + rating_element).append(star);
	        }
        }
}

function deleteMessage(id) {
	$.post("/msg_delete/" + id + "/",
           {},
           function(data) {}
    );
	$("#msg_" + id).remove();
	if ($("#msg_count").val() > 0) {
		newVal = $("#msg_count").val() - 1;
		$("#msg_count").val(newVal);
    }
	if ($("#msg_count").val() < 1) {
		$("#msg_disp").text("no messages");
	}	
}

function deleteComment(comment_id, comment_user_id, user_id) {
    if (!(confirm("Are you sure you want to delete this comment?"))) {
        return false;
    }
	$.post("/comment_delete/" + comment_id + "/" + comment_user_id + 
	       "/" + user_id + "/",
               {},
               function(data) {}
    );
    $("#comment_full_" + comment_id).remove();
	if ($("#comment_count").val() > 0) {
		newVal = $("#comment_count").val() - 1;
		$("#comment_count").val(newVal);
		$("#comment_count_disp").text("comments (" + newVal + ")");
    }	
}

function startUpload(file_type){
    loadingFrame = 1;
    clearInterval(uploadTimer);
    showUploadProgress();
    $("#" + file_type + '_upload_form').hide();
    return true;
}

function stopUpload(success, file_type){
    var result = '';
    $("#upload_anim_overlay").remove();
    $("#upload_anim").remove();
    clearInterval(uploadTimer);
    if (success != 1){
       result = '<span class="emsg">there was an error during' +
                ' file upload - check that the file is not too large ' +
                'and is the correct type</span>';
       $('#upload_error').html(result);
    }
    else {
        $('#upload_error').html('');
    }
    if (file_type === '') {
    	$('#audio_upload_form').show();
    	$('#image_upload_form').show();
    	$('#audio_change_input').hide();
    	$('#image_change_input').hide();
    }
    else {
    	$('#' + file_type + '_upload_form').show();
    	$('#' + file_type + '_change_input').hide();
    }
    return true;   
}

function sceneLeave(id, fetch_replacement) {
    if (!(confirm("Abandon this scene?"))) return false;
	$.post("/scenes/leave/" + id + "/",
               {},
               function(data) {}
    );
    $("#mship_img_" + id).attr("src", "/images/group.gif");
    $("#mship_img_" + id).attr("alt", "Join.");
    $("#mship_img_" + id).attr("title", "Join.");
    $("#mship_ctl_" + id).unbind();
    $("#mship_ctl_" + id).click(function() {sceneJoin(id);});
    if (fetch_replacement) {
    	var msl = "";
        $(".msl").each(
            function(){
                msl += "|" + $(this).attr("id").substr(3);
            });
       $.post("/scenes/fetch_new/",
            {msl : msl},
            function(data){
                $("#pane_7").append(data);
            });
    }
    $("#ms_" + id).remove();
}

function getDisplayedSimilarUsersList(type, index) {
	var ssul = "";
    $("." + type).each(
        function(){
            ssul += "|" + $(this).attr("id").substr(index);
    });
    return ssul;
}

function sceneJoin(id, retain_scene) {
    if (!(confirm("Join this scene?"))) return false;
    // Count the number of "my scenes" displayed;
    // if greater than 5, remove the last of
    // "my scenes"
    var displayed_scenes = 0;
    $(".scene_list").each(function(){
        displayed_scenes += 1;
    });
    if (displayed_scenes >= 4) {
        $(".scene_list").filter(':last').remove();
    }
    $("#pane_7").append($("#similar_scene_" + id));
	var ssul = getDisplayedSimilarUsersList("ssul", 14);
	$.post("/scenes/join/" + id,
	         {sul : ssul},
	         function(data){
	        	 $("#pane_6").append(data);
	         });
	if (!retain_scene) $("#similar_scene_" + id).remove();
	if (retain_scene) {
	    $("#mship_img_" + id).attr("src", "/images/leave.gif");
        $("#mship_img_" + id).attr("alt", "Leave.");
        $("#mship_img_" + id).attr("title", "Leave.");
        $("#mship_ctl_" + id).unbind();
        $("#mship_ctl_" + id).click(function() {sceneLeave(id);});
	}
}

function preLoad() {
	 
	   var args = preLoad.arguments;
	   document.imageArray = new Array(args.length);
	 
	   for (var i=0; i < args.length; i++) {
	 
	      document.imageArray[i] = new Image;
	      document.imageArray[i].src = args[i];
	   }
}

$(document).ready(function() {

    if ($('#tweet_this')) {
        $('#tweet_this').bind('click', function() {
	        if ($('#tweet_this').is(':checked')) {
	            $('#twitter_authentication').show('slow')
	        }
	        else {
	            $('#twitter_authentication').hide('fast')
	        }
        });
    }

    $(".user_sidebar").corner("round");
    if ($(".submenu_panel").length > 0) {
        $(".submenu_panel").corner("tr");
    }
    function closeImg() {
		$("#fulldiv").empty();
        $("#fulldiv").remove();
        $("#greyout").remove();
    }
   	
   	$("a#work_image_target").fancybox({'imageScale' : true,
   	                                   'zoomOpacity' : true,
                                       'hideOnContentClick' : true,
                                       'zoomSpeedIn' : 600,
                                       'zoomSpeedOut' : 500,
                                       'overlayShow' : false,
                                       'easingIn' : 'easeOutBack',
                                       'easingOut' : 'easeInBack'
                                      });
   		
	$(".ttlb").corner("tl tr");
        if ($("#tag_management") != null) {
             $('#tag_help').jqm({modal: true, trigger: '#tag_help_trigger', toTop: true});
             $('#tag_help').jqmAddClose('#tag_help_close_dialog');
             $('#mantagmanrb').bind('click', function() {
                 document.getElementById('tag_management').visibility = 'visible';
                 $('#tag_management').show('slow');
             });
             $('#autotagmanrb').bind('click', function() { 
                 $('#tag_management').hide('slow');
                 document.getElementById('tag_management').visibility = 'hidden';
             });
        }
    $('#add_comment_trigger').bind('click', function() { 
        $('#add_comment_dialog').show('slow');
    });
    $('#add_comment_close_dialog').bind('click', function() { 
        $('#add_comment_dialog').hide('slow');
    });
    if ($('#comment_submit')) {
        $('#comment_submit').bind('click', function(){
            if ($('#id_comment').contents().find("body").html().length > 2999) {
                var msg = "Your comment is too long! ";
                msg += "Please try shortening it. If shortening it isn't ";
                msg += "an option, consider posting a text work and providing ";
                msg += "a link to it in the comment.";
                alert(msg);
                return false;
            }
        })
    }
});

function composePrivateMessage(to_user_id, from_user_id, target_username) {
    $("#pm_text").val("");
    $('#countdown').html("255");
    $("#target_username").html(target_username);
    $("#compose_private_message").jqmShow();
    $("#send_message_button").unbind();
    $("#send_message_button").click(function() {
        sendPrivateMessage(to_user_id, from_user_id);
    });
}

function sendPrivateMessage(to_user_id, from_user_id) {
    var messageText = $("#pm_text").val();
    $.post("/send_private_message/" + from_user_id + "/" + to_user_id + "/",
           { message : messageText },
           function(data) {
               $("#pm_text").val("");
               $("#send_message_button").unbind();
               $("#compose_private_message").jqmHide();
               alert("Your message has been sent.");
           }
    );
}

function disconnectUser(id, page) {
	if (confirm("Are you sure you want to stop following this user?")) {
		$.post("/accounts/profile/disconnect/" + id + "/",
		       {},
		       function(data) {}
		);
		if ($("#conn_" + id) != null) {
		    $("#conn_" + id).remove();
		}
		if (page === "profile" || page === "search") {
		    $("#cui_" + id).attr("alt", "Follow.");
            $("#cui_" + id).attr("title", "Follow.");
            $("#cui_" + id).attr("src", "/images/user.gif");
            $("#conn_control_" + id).unbind();
            $("#conn_control_" + id).click(function() {
                connectUser(id, page);
            });
		}
		if (page === "connections") {
		    $("#similar_user_" + id).remove();
		}
	}
}

function connectUser(id, page) {
	var ssul = getDisplayedSimilarUsersList("usul", 13);
	if (confirm("Follow this user?")) {
	    $.post("/accounts/profile/connect/" + id + "/",
	    		{sul : ssul},
	    		function(data){
	    			$("#pane_1").append(data);
	    			if ($(".usul").length < 1) {
                        $("#user_match_txt").html("no user matches");
                    }
	    		});
	    if ($("#similar_user_" + id) != null) {
	        if (!(page === "search")) $("#similar_user_" + id).remove();
		}
		if (page === "profile" || page === "search" || page === "scene") {
		    $("#cui_" + id).attr("alt", "Stop following.");
            $("#cui_" + id).attr("title", "Stop following.");
            $("#cui_" + id).attr("src", "/images/x.gif");
            $("#conn_control_" + id).unbind();
            $("#conn_control_" + id).click(function() {
                disconnectUser(id, page);
            });
		}
	}
}

function update_user_box() {
	$("#profile_user_info").html("<div>" + 
	    "<fb:profile-pic uid=loggedinuser facebook-logo=true>" +
	    "</fb:profile-pic></div>" + 
	    "<div>Hi, <fb:name uid=loggedinuser useyou=false></fb:name>!" +
	    " Thanks for using Facebook Connect to log in to Gavagai. " + 
	    "Gavagai is currently in private alpha - check back soon " + 
	    "for details about the initial release! " +
	    "<br /><a href=\"javascript:;\"" +
	    " onclick=\"FB.Connect.logout(function() { reload(); }); return " +
	    "false;\"><img id=\"fb_logout_image\" src=\"http://static.ak.fbcdn." +
	    "net/images/fbconnect/logout-buttons/logout_small.gif\" alt=\"" +
	    "Connect\"/></a>");
	FB.XFBML.Host.parseDomTree();
}

function reload() {
	window.location.reload();
}

function omitUser(id, retain) {
    if (!(confirm("Blocking will prevent this user from being displayed " +
                  "in your matches. If you have second thoughts later, " +
                  "you can find this user on the \"blocked\" section " +
                  "of the \"matches\" tab. Are you sure you want to " +
                  "block this user?"))) return false;
    var usul = "";
    $(".usul").each(
        function(){
            usul += "|" + $(this).attr("id").substr(13);
        });
   $.post("/accounts/profile_omit/" + id + "/",
          {sul : usul},
          function(data){
            if ($(".usul").length < 1) {
                $("#user_match_txt").html("no user matches");
            }
            $("#pane_1").append(data);
          });
   if (!retain) {
       $("#similar_user_" + id).hide();
       $("#similar_user_" + id).remove();
   }
   else {
       $("#unblock_user_" + id).attr("alt", "Unblock.");
       $("#unblock_user_" + id).attr("title", "Unblock.");
       $("#unblock_user_" + id).attr("src", "/images/undo.gif");
       $("#unblock_user_" + id).unbind();
       $("#unblock_user_" + id).click(function() {
           unblockUser(id);
       });
   }
}

function unblockUser(id) {

   if (!(confirm("Unblocking will allow this user to be displayed in your " +
                 "matches. OK to unblock?"))) return false;
   $.post("/accounts/profile_unblock/" + id + "/",
        {},
        function(data){
           $("#similar_user_" + id).remove();
           if ($(".usul").length < 1) {
               $("#user_desc").html("no blocked users to show");
           }
        });
}

function omitWork(id, pane) {

    if (!(confirm("Blocking will prevent this work from being displayed " +
                  "in your matches. If you have second thoughts later, " +
                  "you can find this work on the \"blocked\" section " +
                  "of the \"matches\" tab. Are you sure you want to " +
                  "block this work?"))) return false;
    var wsul = "";
    $(".wsul").each(
        function(){
            wsul += "|" + $(this).attr("id").substr(13);
        });
   $.post("/works/omit/" + id + "/",
        {sul : wsul},
        function(data){
            if (pane != null) {
                $("#" + pane).append(data);
                if ($(".twsul").length < 1) {
                    $("#twork_match_txt").html("no text work matches");
                }
                if ($(".awsul").length < 1) {
                    $("#awork_match_txt").html("no audio work matches");
                }
            }
        });
   if (pane != null) {
       $("#similar_work_" + id).remove();
   }
   else {
       $("#unblock_work_" + id).attr("alt", "Unblock.");
       $("#unblock_work_" + id).attr("title", "Unblock.");
       $("#unblock_work_" + id).attr("src", "/images/undo.gif");
       $("#unblock_work_" + id).unbind();
       $("#unblock_work_" + id).click(function() {
           unblockWork(id);
       });
   }
}

function unblockWork(id) {

   if (!(confirm("Unblocking will allow this work to be displayed in your " +
                 "matches. OK to unblock?"))) return false;
   $.post("/works/unblock/" + id + "/",
        {},
        function(data){
           $("#similar_work_" + id).remove();
           if ($(".awsul").length < 1) {
               $("#awork_desc").html("no blocked audio works to show");
           }
           if ($(".twsul").length < 1) {
               $("#twork_desc").html("no blocked text works to show");
           }
        });
}

function favorWork(id, pane, retain_data) {

    if (!(confirm("This will add this work to the \"favorites\" " +
                  "section of the \"works\" tab. Add this work to" +
                  "your favorites?"))) return false;

    var wsul = "";
    $(".wsul").each(
        function(){
            wsul += "|" + $(this).attr("id").substr(13);
        });
   $.post("/works/favorite/" + id + "/",
        {sul : wsul},
        function(data){
            $("#" + pane).append(data);
        });
   if (!retain_data) {
       $("#similar_work_" + id).remove();
   }
}

function favorPackage(id) {

    if (!(confirm("This will add this portfolio to the \"favorites\" " +
                  "section of the \"portfolios\" tab. Add this portfolio to" +
                  "your favorites?"))) return false;

    var pkl = "";
    $(".pkl").each(
        function(){
            pkl += "|" + $(this).attr("id").substr(16);
        });
   $.post("/works/packages/favorite/" + id + "/",
        {sul : pkl},
        function(data){
            $("#pane_5").append(data);
        });
   $("#similar_package_" + id).remove();
}

function unblockPackage(id) {

   if (!(confirm("Unblocking will allow this portfolio to be displayed in " +
                 "your matches. OK to unblock?"))) return false;
   $.post("/works/packages/unblock/" + id + "/",
        {},
        function(data){
           $("#similar_package_" + id).remove();
           if ($(".pkl").length < 1) {
               $("#pkg_desc").html("no blocked portfolios to show");
           }
        });
}

function omitPackage(id, retain) {
    if (!(confirm("Blocking will prevent this portfolio from being displayed " +
                  "in your matches. If you have second thoughts later, " +
                  "you can find this portfolio on the \"blocked\" section " +
                  "of the \"matches\" tab. Are you sure you want to " +
                  "block this portfolio?"))) return false;
    var pkl = "";
    $(".pkl").each(
        function(){
            pkl += "|" + $(this).attr("id").substr(16);
        });
   $.post("/works/packages/omit/" + id + "/",
        {sul : pkl},
        function(data){
            $("#pane_5").append(data);
            if ($(".pkl").length < 1) {
                 $("#port_match_txt").html("no portfolio matches");
             }
        });
   if (!retain) {
       $("#similar_package_" + id).remove();
   }
   else {
       $("#unblock_package_" + id).attr("alt", "Unblock.");
       $("#unblock_package_" + id).attr("title", "Unblock.");
       $("#unblock_package_" + id).attr("src", "/images/undo.gif");
       $("#unblock_package_" + id).unbind();
       $("#unblock_package_" + id).click(function() {
           unblockPackage(id);
       });
   }
}

function unblockScene(id) {

   if (!(confirm("Unblocking will allow this scene to be displayed in " +
                 "your matches. OK to unblock?"))) return false;
   $.post("/scenes/unblock/" + id + "/",
        {},
        function(data){
           $("#similar_scene_" + id).remove();
           if ($(".ssul").length < 1) {
               $("#scene_desc").html("no blocked scenes to show");
           }
        });
}

function omitScene(id, retain) {
    if (!(confirm("Blocking will prevent this scene from being displayed " +
                  "in your matches. If you have second thoughts later, " +
                  "you can find this scene on the \"blocked\" section " +
                  "of the \"matches\" tab. Are you sure you want to " +
                  "block this scene?"))) return false;
    var ssul = getDisplayedSimilarUsersList("ssul", 14);
    
    $.post("/scenes/omit/" + id + "/",
         {sul : ssul},
         function(data){
             $("#pane_6").append(data);
             if ($(".ssul").length < 1) {
                 $("#scene_match_txt").html("no scene matches");
             }
         });
    if (!retain) {
        $("#similar_scene_" + id).remove();
    }
    else {
       $("#unblock_scene_" + id).attr("alt", "Unblock.");
       $("#unblock_scene_" + id).attr("title", "Unblock.");
       $("#unblock_scene_" + id).attr("src", "/images/undo.gif");
       $("#unblock_scene_" + id).unbind();
       $("#unblock_scene_" + id).click(function() {
           unblockScene(id);
       });
   }
    
}

function deleteWork(id, page) {
    var msg = "This will permanently delete this work from any portfolios, ";
    msg += "scenes album and your profile. Are you sure you want to ";
    msg += "continue?";
    confirmation = confirm(msg);
	if (confirmation == true) {
	    $.post("/works/delete/" + id + "/",
	        {},
	        function(data) {}
	    );
	    $("#work_div_" + id).remove();
	    if (page === "profile") {
	        $("#work_obj_" + id).remove();
	    }
	    if (page === "works_all") {
            $("#similar_work_" + id).remove();
        }
        if (page === "works_edit") {
            window.location = "/works/";
        }
	}
}

function deletePackage(id, page) {
	var msg = "This will permanently delete this portfolio from your ";
	msg += "profile. It will also remove all the works from this portfolio ";
	msg += "(though it won't delete the individual works). ";
	msg += "Are you sure you want to continue?";
	confirmation = confirm(msg);
	if (confirmation == true) {
	    $.post("/works/packages/delete/" + id,
	        {},
	        function(data) {}
	    );
	    if (page === "packages_all") {
	        $("#similar_package_" + id).remove();
	    }
	    if (page === "packages") {
	        window.location = "/works/packages"
	    }
	}
}

function limitText(limitField, countField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } else {
        countField.html(limitNum - limitField.value.length);
    }
}

function showUpdateStatusPopup(id, action) {
    $("#status").val("");
    $("#action").html(action);
    $('#change_status_popup').jqmShow();
}

function updateStatus(id) {
    if ($("#status").val() === "" || $("#status").val() == null) {
        alert("Enter a status or click on \"cancel\".");
        return false;
    }
    var action = $("#action").html();
    if ($("#action").html() === "listening to") {
        $("#listening").html($("#status").val());
    }
    if ($("#action").html() === "reading") {
        $("#reading").html($("#status").val());
    }
    if ($("#action").html() === "thinking") {
        $("#thinking").html($("#status").val());
    }
    $.post("/accounts/profile/change_status/" + id + "/",
               { action : $("#action").html(),
                 target : $("#status").val() },
               function(data) {
                   if (data.status != 0) {
                       alert("Couldn't update your status right now; please try again later.");
                   }  
               },
               "json"
        );
    $('#change_status_popup').jqmHide();
    return false;
}
