﻿//these functions interface directly with the jw player
var player = null;
var currently_playing = 0;
var state;
var queued_guid = null;
var queued_passthrough = null;

function playerReady(thePlayer) 
{ 
    player = window.document[thePlayer.id]; 
    addListeners();
    if (queued_guid != null)
    {
        togglePlay(queued_guid,queued_passthrough)
        queued_guid = null
        queued_passthrough = null
    } 
}

function setPlaylistInputs(guid_string,url_string,duration_string)
{
    $("#playlist").val(guid_string);
    $("#playlist_urls").val(url_string);
    $("#playlist_durations").val(duration_string);
}

function playlist()
{
    return $("#playlist").val().split(",");
}

function playlist_urls()
{
    return $("#playlist_urls").val().split(",");
}

function playlist_durations()
{
    return $("#playlist_durations").val().split(",");
}

function addListeners()
{
    player.addModelListener("TIME", "timeListener");
    player.addModelListener("STATE", "stateListener");
}

function timeListener(obj)
{
    //sets markup for dash/profile song counters
    $("#"+currently_playing+"_counter").html(fixTime(obj.position));
    //sets markup for permalink song counters
    $("#permalink_top_right").html(fixTime(obj.position));
}

function stateListener(obj)
{
state = obj.newstate
    if (state == "COMPLETED") 
    {
    var play_now = false
        for (index in playlist())
        {
            if (play_now == true) {togglePlay(playlist()[index], playlist_urls()[index]); return;}
            if (playlist()[index] == currently_playing) {play_now = true}
        }
    }
}

function fixTime(raw_time) 
{
var raw_seconds = Math.floor(raw_time)
    if (raw_seconds < 60) 
    {
    return raw_seconds;
    }
var minutes = Math.floor(raw_time / 60)
var left_over_seconds = (raw_seconds - (minutes * 60))
    if (left_over_seconds < 10)
    {
    return minutes+":0"+(raw_seconds - (minutes * 60));
    }
return minutes+":"+(raw_seconds - (minutes * 60));
}

function togglePlay(song_guid,passthrough_url)
{
    if (player != null)
    { 
        if (currently_playing != song_guid)
        {
        //toggle play new song
        $("#dashboard1_currently_playing").val(song_guid);
        songHover(song_guid)
        currently_playing = song_guid
        $("#"+currently_playing+"_counter").removeClass("player_row_counter_paused");
        $("#"+currently_playing+"_counter").addClass("player_row_counter_active");
        $("#"+currently_playing+"_counter").html("-");
        player.sendEvent("LOAD",passthrough_url);
        player.sendEvent("PLAY");
        //populate latest comment
        setCommentMarkup(song_guid,0,0);
        //destroy hover for all other songs
        for (index in playlist()) {songStopHover(playlist()[index]);}
        }
        else
        {
        //toggle song play/pause
        player.sendEvent("PLAY")
            if (state == "PLAYING")
            {
            //sets markup for dash/profile song counters
            $("#"+currently_playing+"_counter").removeClass("player_row_counter_paused");
            //sets markup for permalink song counters
            $("#permalink_top_right").removeClass("permalink_top_right_paused");
            }
            else
            {
            //sets markup for dash/profile song counters
            $("#"+currently_playing+"_counter").addClass("player_row_counter_paused");
            //sets markup for permalink song counters
            $("#permalink_top_right").addClass("permalink_top_right_paused");
            }
        
        }
    }
    else
    {
    queued_guid = song_guid
    queued_passthrough = passthrough_url
    }

}

function songHover(id)
{
$("#"+id).css('filter','alpha(opacity=100)');
$("#"+id).css('opacity','1.0');
$("#"+id+"_links").css('display','inline');
}

function songStopHover(id)
{
    if (currently_playing != id)
    {
    $("#"+id+"_links").css('display','none');
    $("#"+id).css('filter','alpha(opacity=70)');
    $("#"+id).css('opacity','0.7');
    //let's also give this function responsibility for re-setting counter div
    $("#"+id+"_counter").removeClass("player_row_counter_active");
    $("#"+id+"_counter").html(fixTime(playlist_durations()[arrayIndexFromGuid(id)]));
    }
}

function arrayIndexFromGuid(guid)
{
    for (index in playlist())
    {
    if (guid == playlist()[index]) {return index}
    }
}

function uploadProgress(){
	hideDiv("upload_controls")
	document.getElementById("upload_progress").style.display = "block";
	document.getElementById("upload_percentage").style.display = "block";
	intervalID = window.setInterval(function(){
	//extract the fresh token associated with this instance of the file_upload handler
	var upload_token = document.getElementById("DJUploadController1").childNodes.item(0).value;
	//perform the web request using this value
	var request = new Sys.Net.WebRequest();
	request.set_url('UploadProgress.ashx?DJUploadStatus=' + upload_token + '&ts=' + new Date().getTime());
	request.set_httpVerb('GET');
	request.add_completed(function(executor){
	//  the progress is returned as xml
	var e = executor.get_xml().documentElement; 
	var empty = e.getAttribute('empty');
	if(!empty){
		//  extract the attributes I am interested in
		var percent = e.getAttribute('progress');
		var file = e.getAttribute('file').toString();
		if (file.substring(file.length - 4).toUpperCase() != ".MP3") {window.location = "http://songtwit.com/song_upload.aspx?bad_file=true"}
		var kbs = Math.round(parseInt(e.getAttribute('bytes')) / 1024);
		var size = Math.round(parseInt(e.getAttribute('size')) / 1024);
		if(percent == 100){
			window.clearInterval(intervalID);
		}
		document.getElementById("upload_percentage").innerHTML = percent+'%';
		if(percent == 100) {document.getElementById("upload_percentage").innerHTML = '99%';} 
		
		 }
		}); 
	request.invoke();
	}, 1000);
}
function hideDiv(div_id){
	document.getElementById(div_id).style.display = "none";
}
function showDiv(div_id){
	document.getElementById(div_id).style.display = "block";
}

function showWelcome()
{
    $("#ViewWelcome").css('display','block');
    $("#ViewMain").css('visibility','hidden');
}

function showCheckBack()
{
    $("#ViewWelcome").css('display','none');
    $("#ViewMain").css('visibility','hidden');
}

function addSongRow(new_markup,guid,guid_passthrough_url,duration) {
    //called when user adds new song so that a postback is not necessary to show the new row in their profile
    //also gets rid of "welcome" dialog if necessary
    var p = parent;
    p.$("#ViewMain").css('visibility','visible');
    p.$("#ViewWelcome").css('display','none');
    p.$("#player_container_contentwrapper").html(new_markup+p.$("#player_container_contentwrapper").html());
    p.$("#playlist").val(guid+","+p.$("#playlist").val());
    p.$("#playlist_urls").val(guid+","+p.$("#playlist_urls").val());
    p.$("#playlist_durations").val(duration+","+p.$("#playlist_durations").val());
    if (currently_playing == 0)
    {
    parent.callTogglePlay(guid,guid_passthrough_url);
    }
}

function downloadSong(permalink_id) {
    $("#download").attr("src","http://songtwit.com/song_download.aspx?permalink_id="+permalink_id); 
}

function tweetTextChanged(textbox_id,countdown_id,max_length) {
    var maxlength = max_length
    var current_value = $("#"+textbox_id).attr("value");
    if (current_value.length > maxlength) {$("#"+textbox_id).attr("value", current_value.substring(0, maxlength))}
    $("#"+countdown_id).html($("#"+textbox_id).attr("value").length+"/"+maxlength);
}

function sayThanks() {
    document.getElementById("thanks").style.display = "block";
    setTimeout("self.parent.tb_remove()",1000);
}

function pmSetCommentMarkupSuccess(res, destCtrl)
{   
    $("#latest_comment").html(res);
    $("#comment_progress_client").css('display','none');
}
 
function pmSetCommentMarkupFailure(res, destCtrl)
{
}

function setCommentMarkup(song_guid,min_id,max_id)
{
    
    $("#comment_progress_client").css('display','block');
    PageMethods.pageMethodGetCommentMarkup(song_guid,min_id,max_id,pmSetCommentMarkupSuccess,pmSetCommentMarkupFailure);
}

function pmSetPermalinkCommentMarkupSuccess(res, destCtrl)
{   
     $("#comment_markup").html(res);
     $("#permalink_middle").css("height",$("#permalink_comments_inner").css("height"))
}
 
function pmSetPermalinkCommentMarkupFailure(res, destCtrl)
{
}

function SetPermalinkCommentMarkup(song_guid,min_id)
{
    
    PageMethods.pageMethodSetPermalinkCommentMarkup(song_guid,min_id,pmSetPermalinkCommentMarkupSuccess,pmSetPermalinkCommentMarkupFailure);
}

function pmPostNewCommentSuccess(res, destCtrl)
{   
    if (res == 'redirect')
    {
    window.location = "http://songtwit.com/twitter_callback";
    }
    else
    {
     $("#song1_txtComment").attr("value","");
     $("#permalink_post_comment_progress").css('display','none');
     $("#permalink_post_comment").css('display','block');
     $("#comment_markup").html(res);
     $("#permalink_middle").css("height",$("#permalink_comments_inner").css("height"))
     }
}
 
function pmPostNewCommentFailure(res, destCtrl)
{
}

function PostNewComment(song_guid)
{
    $("#permalink_post_comment_progress").css('display','block');
    $("#permalink_post_comment").css('display','none');
    PageMethods.pageMethodPostNewComment(song_guid,$("#song1_txtComment").attr("value"),pmPostNewCommentSuccess,pmPostNewCommentFailure);
}



var tweet_currently_open = 0;
function runEffect(rowID,songID,songTYPE,songGUID,songTITLE){
	//run the following code only if the requested item is not already open
	if (tweet_currently_open != rowID)
	{
	//close any other open tweet, if there is one
	if (tweet_currently_open != 0)
	{
	closeFeedTweet(tweet_currently_open);
	}
	tweet_currently_open = rowID
	//make the pointer default
	$("#tweet_"+rowID).css("cursor", "default");
	//make control read 'click to close'
	document.getElementById("feed_tweet_control_"+rowID).innerHTML = "<a href=\"javascript:closeFeedTweet('"+rowID+"')\">click to close</a>";
	//load the iframe embed
	document.getElementById('feed_tweet_iframe_'+rowID).innerHTML = '<iframe id="iframe_'+rowID+'" scrolling="no" frameborder="0" src="http://songtwit.com/embedded_song.aspx?bgcolor=F5F5F5&id='+songID+'&type='+songTYPE+'&guid='+songGUID+'&title='+songTITLE+'" width="425px" style="height: 1; margin-top: 15px;"/>';
	};
}
function closeFeedTweet(rowID) {
	document.getElementById("feed_tweet_iframe_"+rowID).innerHTML = '&nbsp;';
	//make control read 'click to play'
	document.getElementById("feed_tweet_control_"+rowID).innerHTML = "click to play";
	tweet_currently_open = 0;
	tweetUnHighlight("tweet_"+rowID);
	//make cursor = pointer again
	$("#tweet_"+rowID).css("cursor", "pointer");
}
function tweetHighlight(div_id) {
	$("#"+div_id).css("background-color", "#F5F5F5");
}
function tweetUnHighlight(div_id) {
  if (div_id != 'tweet_'+tweet_currently_open)
  {
  $("#"+div_id).css("background-color", "#FFF");
  }
}
function dimBackground() {
	$("#dim-background").css("visibility","visible");
}
function unDimBackground() {
	$("#dim-background").css("visibility","hidden");
}
function showSearchResults() {
	dimBackground();
	$("#search-popup").css("visibility","visible");
}
function hideSearchResults() {
	unDimBackground();
	$("#search-popup").css("visibility","hidden");
}
function previewSong(preview_id,preview_title) {
	var preview_type = mid(preview_id,0,3);
	$("#UserHome1_PreviewID").val(preview_id);
	$("#UserHome1_PreviewTitle").val(preview_title);
	$("#preview-popup").css("visibility","visible");
	//if the preview_id corresponds to a YouTube video, embed the YouTube player
	if (preview_type=='ytb')
  	{
	document.getElementById("preview_iframe_container").innerHTML = '<iframe id="preview_iframe" scrolling="no" frameborder="0" src="http://songtwit.com/embedded_song.aspx?bgcolor=222&id='+preview_id+'&type=4&guid=NOGUID&title='+preview_title+'" width="425px" style="height: 1; margin-top: 15px;"/>'
  	}
	//if the preview_id corresponds to an iMeem video, embed it
	if (preview_type=='ime')
  	{
	document.getElementById("preview_iframe_container").innerHTML = '<iframe id="preview_iframe" scrolling="no" frameborder="0" src="http://songtwit.com/embedded_song.aspx?bgcolor=222&id='+preview_id+'&type=5&guid=NOGUID&title='+preview_title+'" width="425px" style="height: 1; margin-top: 15px;"/>'
  	}
	$("#preview-popup").css("zIndex","15");
}
function hideSongPreview() {
	document.getElementById("preview_iframe_container").innerHTML = ""
	document.getElementById('preview-popup').style.visibility = 'hidden';
}
function blank() {
}
/***************
helper functions
***************/
function mid(str, start, len)
{
// Make sure start and len are within proper bounds
    if (start < 0 || len < 0) return "";
    var iEnd, iLen = String(str).length;
    if (start + len > iLen)
          iEnd = iLen;
    else
          iEnd = start + len;
    return String(str).substring(start,iEnd);
}
function convertSeconds(seconds){
	var secondCount = Math.ceil((seconds-(Math.floor(seconds/60)*60)))
	if (secondCount < 10) {secondCount = "0"+secondCount}
	return Math.floor(seconds/60)+":"+secondCount;
}

/***************
Uploader Scripts
***************/
function goLite(btnName)
{
   document.getElementById(btnName).style.backgroundColor = "#DDDDDD";
}

function goDim(btnName)
{
   document.getElementById(btnName).style.backgroundColor = "#EFEFEF";
}
function showSearchDiv() {
	var id = 'search_controls';
	showDiv(id);
	hideDiv('uploader_controls');
	hideDiv('enter_controls');
}
function showEnterDiv() {
	var id = 'enter_controls';
	showDiv(id);
	hideDiv('uploader_controls');
	hideDiv('search_controls');
}
function showUploadDiv() {
	var id = 'uploader_controls';
	showDiv(id);
	hideDiv('enter_controls');
	hideDiv('search_controls');
}

function nothing(){
}
function is_owner() {
	showDiv('txtIsOwner');
	hideDiv('txtNotOwner');
}
function not_owner() {
	hideDiv('txtIsOwner');
	showDiv('txtNotOwner');
}

