// JS routines for shareHub.com
// jwm

var UPLOAD_STATUSCHECK = false;
var UPLOAD_IN_PROGRESS = false;
var SHAREHUB_URL = "";
var DOWNLOAD_URL = "http://go.sharehub.com/shared/";
var FILEINFO_URL = "./fileinfo.php?id=";
var MINIFIER_URL = "http://SERVICE/shrink/index.php"
var PROGRESS_MARKUP = "";
var MEGABYTE = 1024000;

$(document).ready(function() { 

	// cache these items
	SHAREHUB_URL = $("#currentHost").val();
	PROGRESS_MARKUP = $("#shareProgress").html();
		
	// sweetenFileUploads();			// because <input type=file> is just too ugly by default.

	$("#userLink").bind("focus", function(e) {
		$(this).select();
	});
	
	/* Shrinking a link --- new feature -- March 17 */
	$("#btnShrinkLink").bind("click", shrinkLink);
	
	/* Sharing a file --- its the CORE FEATURE! */
	$("#btnShareFile").bind("click", function(e) {
	
		if ( $("#userFile").val() == "" )
		{
			alert("You haven't selected a file to share yet!");
			return;
		}
		
		resetProgressBox();
		
		var coords = $("#content").offset();

		$("#windowShade").height($(document).height());
		$("#windowShade").width($(document).width());
		$("#windowShade").css("top", 0);
		$("#windowShade").css("left", 0);

		$("#windowShade").slideUp(0);
		$("#shareProgress").fadeOut(0);

		$("#windowShade").slideDown(320);
		centerIt("#shareProgress", "#content", true, false);
		$("#shareProgress").fadeIn(500);
		
		$("#shareProgressMessage").html("Starting upload...");
		UPLOAD_IN_PROGRESS = true;
		UPLOAD_STATUSCHECK = setInterval("getUploadStatus()", 900);
		
		$("#shareFileForm").submit();
		
		getUploadStatus();
				
	});

	$("#shareTabFiles").bind("click", function(e) {
		if ( $("#shareFileUI").is(':hidden') ) {
			$(this).addClass("shareTabOn");
			$("#shareTabLinks").removeClass("shareTabOn");
			$("#shareLinkUI").slideUp("normal", function() {
				$("#shareFileUI").slideDown("fast");
			});
		}
	});
	
	$("#shareTabLinks").bind("click", function(e) {
		if ( $("#linkForm").is(':hidden') ) {
			$("#linkResult").hide();
			$("#linkError").hide();
			$("#linkForm").show();

		}
			
		if ( $("#shareLinkUI").is(':hidden') ) {
			$(this).addClass("shareTabOn");
			$("#shareTabFiles").removeClass("shareTabOn");
			$("#shareFileUI").slideUp("normal", function() {
				$("#shareLinkUI").slideDown("fast");
			});
		}
	});
		
	$("#progressBoxCancel").bind("click", function(e) {
		cancelUpload();
	});
	
	
	if ( $("input.promoCheck").length > 0 )
	{
		$("input.promoCheck").bind("click", function(e) {				
			// setTimeout('$("#' + $(this).attr("id") + '").attr("checked", false);', 750);
			$(this).attr("checked", false);
			window.location.href='./new.php';
		});
		
		$("#chkFeatureDownloads").bubbletip('#promoTipDownloads', {mouseoutDelay: 400, deltaDirection: 'up', offsetTop: 5 } );
		$("#chkFeatureNotifications").bubbletip('#promoTipNotifications', {mouseoutDelay: 400, deltaDirection: 'up', offsetTop: 6} );
		$("#chkFeaturePasswords").bubbletip('#promoTipPasswords', {mouseoutDelay: 400, deltaDirection: 'up', offsetTop: 7} );
		$("#chkFeatureComments").bubbletip('#promoTipComments', {mouseoutDelay: 400, deltaDirection: 'down', offsetTop: -8} );
	}
	
});

// extract the base filename from the file input element
function getFilename(str)
{
    var m = str.match(/(.*)[\/\\]([^\/\\]+\.\w+)$/);
    
    // return {path: m[1], file: m[2]}
 	if ( m && m.length > 1 )
 		return m[2];
 	else
 		return str;
}

// requests the upload status from the server, parses the results and displays
function getUploadStatus()
{
	var statusUrl = $("#shareFileForm").attr("action");
	var fileName = getFilename($("#userFile").val());
	
	if ( !UPLOAD_IN_PROGRESS )
		return;
	
	$.ajax({
	  dataType: 'jsonp',
	  data: 'app=shareHub',
	  jsonp: 'jsonp_callback',
	  url: statusUrl,
	  success: function (data) {
	  	// console.log('upload: ' + data.upload_id + ' is ' + data.percent_complete + '% completed.');
	  	if ( data.content_length > MEGABYTE )
	  		totalSize = parseInt(data.content_length / MEGABYTE) + "MB";
	  	else
	  		totalSize = parseInt(data.content_length / 1024) + "kb";
	  		
	  	totalSent = parseInt(data.bytes_read / 1024) + "kb";
	  	
  		$("#shareProgressMessage").html("Uploading " + fileName + " (" + totalSize + ")");
		$("#shareProgressBar").css("width",data.percent_complete + '%');
  		$("#shareProgressPercent").html(totalSent + ' (' + data.percent_complete + '%) transferred');
  		document.title = "shareHub [Upload in progress: " + data.percent_complete + "%] ";
	  	
	  	if ( parseInt(data.percent_complete) == 100 || data.finished == true )
	  	{
	  		document.title = "shareHub [Upload complete!] :)";
	  		$("#shareProgressMessage").html("<strong>Upload complete!</strong>");
	  		$("#progressBoxOk").bind("click", function() { finishUpload(data.upload_id) });
	  		// $("#shareProgressPercent").append('<br/><br/><a href="#" onclick="finishUpload(\''+ data.upload_id +'\')"> OK </a>');
	  		$("#progressBoxOk").show();
	  		$("#progressBoxCancel").hide();
	  		cancelStatusCheck();
	  	}
	  	else if ( data.error )
	  	{
	  		document.title = "shareHub [Upload error.] :(";
	  		$("#shareProgressMessage").html("<strong>Error:</strong> " + data.error);
	  		$("#shareProgressPercent").html("0kb transferred");
	  		$("#shareProgressPercent").append('<br/><br/><a href="#" onclick="finishUpload()"> OK </a>');
	  		cancelStatusCheck();
	  		$("#progressBoxOk").show();
	  		$("#progressBoxCancel").hide();
	  	}
	  }
	});
}

function resetProgressBox()
{
	$("#shareProgressMessage").html("...");
	$("#shareProgressPercent").html("0%");
	$("#shareProgressBar").css("width","0px");
	$("#progressBoxOk").hide();
	$("#progressBoxCancel").show();
}

// user-initited cancel of upload in progress
function cancelUpload()
{
	$("#shareProgressMessage").html("Cancelling...");
	cancelStatusCheck();
	UPLOAD_IN_PROGRESS = false;

	window.frames.uploadFrame.location.href = "blank.html";
	finishUpload();	

}

// stops the interval polling the server for upload status
function cancelStatusCheck()
{
	if ( UPLOAD_STATUSCHECK )
		clearInterval(UPLOAD_STATUSCHECK);
}

// all done, close up and pass things on to the publisher
function finishUpload(fileId)
{
	cancelStatusCheck();
	
	UPLOAD_IN_PROGRESS = false;
	
	setTimeout('document.title = "shareHub"', 2600);
	
	if ( fileId && fileId.length > 0 )
	{
		location.href = FILEINFO_URL + fileId;
	}
	else
	{
		$("#windowShade").slideUp(400);
		$("#shareProgress").fadeOut(600);
		resetProgressBox();
	}
}

function shrinkLink(e)
{
	var service = MINIFIER_URL.replace(/SERVICE/, $("#smallDomain").val());
	var bigOne = encodeURIComponent($("#userLink").val());
	var smallOne = encodeURIComponent($("#userLinkAlias").val());
	
	$("#linkResult").hide();
	$("#linkError").hide();
		
	$.ajax({
	  dataType: 'jsonp',
	  data: 'url=' + bigOne + '&alias=' + smallOne,
	  jsonp: 'jsonp_callback',
	  url: service,
	  success: function (jsObj) {
	  		if ( jsObj.completed )
	  		{
	  			
	  			$("#freshLink").val(jsObj.mini);
	  			$("#freshHref").attr("href", jsObj.mini);
	  			$("#linkResult").fadeIn();
	  			$("#linkForm").slideUp();
	  			$("#userLink").val("http://");
	  			$("#userLinkAlias").val("");
	  		}
		  	else
		  	{
		  		$("#linkError").text(jsObj.message);
		  		$("#linkError").fadeIn();
		  	}
	  }
	});	
}


// utility function to center an element vertically and/or horizontally in a container
function centerIt(targetId,containerId,doHoriz,doVert)
{
		var coords = $(containerId).offset();
		var pWidth = $(containerId).width();
		var pHeight = $(containerId).height();
		var xpos = Math.floor(coords.left + ((pWidth - $(targetId).width()) / 2));
		var ypos = Math.floor(coords.top + ((pHeight - $(targetId).height()) / 2 ));
		
		if ( doHoriz )
			$(targetId).css("left", xpos + "px");
			
		if ( doVert )
			$(targetId).css("top", ypos + "px");
}

// Styling file upload input... technique courtesy of quirksmode
function sweetenFileUploads()
{
	var fakeFileUpload = document.createElement('div');
	if ( !fakeFileUpload )
		return;
	fakeFileUpload.className = 'fakefile';

	var image = document.createElement('img');
	image.src='img/btnselectfile.png';
	fakeFileUpload.appendChild(image);
		
	fakeFileUpload.appendChild(document.createElement('input'));

	var x = document.getElementsByTagName('input');
	for (var i=0;i<x.length;i++) {
		if (x[i].type != 'file') continue;
		if (x[i].parentNode.className != 'fileinputs') continue;
		x[i].className = 'file hidden';
		var clone = fakeFileUpload.cloneNode(true);
		x[i].parentNode.appendChild(clone);
		x[i].relatedElement = clone.getElementsByTagName('input')[0];
		x[i].onchange = x[i].onmouseout = function () {
			this.relatedElement.value = this.value;
		}
	}
}




