var swfu = new SWFUpload({
	//Flash Settings
	flash_url : "/UI/js/swfupload/swfupload.swf",
	// Backend settings
	//upload_url: "upload.php",
	upload_url: "http://im.twitvid.com/api/uploadAndPost",
	file_post_name: "media",

	// Flash file settings
	file_size_limit : "2000 MB",
	// or you could use something like: "*.doc;*.wpd;*.pdf",
	file_types : "*.3gp;*.3g2;*.asf;*.asx;*.avi;*.flv;*.m4v;*.mkv;*.mov;*.mp2;*.mp4;*.mpg;*.mpeg;*.ogv;*.qt;*.wmv;",			
	file_types_description : "Video Files",
	file_upload_limit : uploader_limit,
	file_queue_limit : uploader_limit,

	// Event handler settings
	swfupload_loaded_handler : swfUploadLoaded,
	
	file_dialog_start_handler: fileDialogStart,
	file_queued_handler : fileQueued,
	file_queue_error_handler : fileQueueError,
	file_dialog_complete_handler : fileDialogComplete,
	
	upload_start_handler : uploadStart,
	upload_progress_handler : uploadProgress,
	upload_error_handler : uploadError,
	upload_success_handler : uploadSuccess,
	upload_complete_handler : uploadComplete,

	// Button Settings
	button_image_url : "/UI/images/bt_choose_video_file.png",
	button_placeholder_id : "bt_choose_video_file",
	button_width: 184,
	button_height: 32,
	button_window_mode: "transparent",
	button_cursor: SWFUpload.CURSOR.HAND,

	// Debug settings
	debug: false
});
//=======================================================================
var video_types = {
	UPLOAD:"upload",
	RECORD:"record",
	NONE:"none"
};
var video_type = video_types.NONE;
var vidcap_recorded = false;
//called from vidcap flash
function setRecorded(v) {
	vidcap_recorded = v;
}
//=======================================================================
var all_cancelled = false;
var multiple = false;
var file_total = 0;
var size_total = 0;
var size_loaded = 0;
var file_index = 0;
var goto_url = "";
var uploader_guid = "";
var playlist_id = "";
var uploader_token = "";
var twitter_username = "";
var twitter_password = "";
var twitter_message = "";
var user_avatar = "";
var states = {
	uploading:'<img src="/UI/images/loading_bg.gif" align="absmiddle" width="16" height="16" />',
	success:'<span class="icon icon_1_06"></span>'
};
var status_uploading=0;
//=======================================================================
function tweetVideo() {
	if ($(".bt_tweet_video_disabled").length >0) {
		return;
	}
	if (video_type == video_types.NONE) {
		alert("Please choose video file from your computer or record from your webcam");
		return;
	}
	if (video_type == video_types.UPLOAD) {
		checkUserLogin(fileUpload);
	} else if (video_type == video_types.RECORD) {
		if (vidcap_recorded) {
			checkUserLogin(submitCapture);
		} else {
			alert("Please record from your webcam");
		}
	}
}
function checkUserLogin(callback) {
	var message = $("textarea[name='twitter_message']");
	twitter_message = message.val();
	if (twitter_message == "") {
		alert("Your message cannot be blank!");
		message.focus();
		return false;
	}
	//
	if (!logged_in) {
		var username = $("input[name='twitter_username']");
		twitter_username = username.val();
		if (twitter_username == "" || twitter_username == "twitter username") {
			alert("Your username cannot be blank!");
			username.focus();
			return false;
		}
		var password = $("input[name='twitter_password']");
		twitter_password = password.val();
		if (twitter_password == "" || twitter_password == "twitter password") {
			alert("Your password cannot be blank!");
			password.focus();
			return false;
		}
		UserLogin(twitter_username, twitter_password, function(){
			$(".bt_tweet_video").addClass("bt_tweet_video_disabled");
			$(".upload_login_loading").show();
		}, function(username, avatar, token) {
			twitter_username = username;
			user_avatar = avatar;
			uploader_token = token;
			$(".upload_login").hide();
			checkUploaderToken(callback);
		}, function(err_msg) {
			alert(err_msg);
		}, function() {
			$(".bt_tweet_video").removeClass("bt_tweet_video_disabled");
			$(".upload_login_loading").hide();
		});
	} else {
		twitter_username = $("input[name='current_username']").val();
		user_avatar = $("input[name='current_avatar']").val();
		uploader_token = $("input[name='twitter_token']").val();
		checkUploaderToken(callback);
	}
}
function checkUploaderToken(callback) {
	if (!uploader_token) {
		alert("Your twitter token is invalid, Please try to login again!");	
	} else {
		callback();
	}
}
//=======================================================================
function swfUploadLoaded() {
}
function fileDialogStart() {
	all_cancelled = false;
}
function fileItem(file) {
	//id, index, name, size, type, creationdate, modificationdate, filestatus
	var htm = '';
	htm += '<table width="100%" border="0" cellspacing="0" cellpadding="0" class="upload_list_item upload_list_item_'+file.id+'"><tr>';
    htm += '<th align="left">'+file.name+'</th>';
	htm += '<td align="right" nowrap="nowrap" class="upload_list_icon upload_list_icon_'+file.id+'">';
	if (file.filestatus == SWFUpload.FILE_STATUS.IN_PROGRESS) {
		htm += states.uploading;
	} else if (file.filestatus == SWFUpload.FILE_STATUS.COMPLETE) {
		htm += states.success;	
	} else {
		htm += "&nbsp;"
	}
	htm += '</td>';
	htm += '<td align="left" nowrap="nowrap" class="upload_list_state upload_list_state_'+file.id+'">&nbsp;</td>';
	htm += '<td align="right" nowrap="nowrap" class="upload_list_delete upload_list_delete_'+file.id+'">';
	htm += '<a href="javascript:fileCancel(\''+file.id+'\');"><span class="icon icon_1_05"></span></a>';
	htm += '</td>';
    htm += '</tr></table>';
	htm += '<div style="display:none;" class="upload_list_data_'+file.id+'"></div>';
	$(".upload_list").append(htm);
}
function fileQueued(file) {
}
function fileCancel(id) {
	//alert(id);
	swfu.cancelUpload(id, false);
	fileList();
}
function fileList() {
	$(".upload_list").html("");
	var stats = swfu.getStats();
	file_total = stats.files_queued;
	var num_all = stats.files_queued + stats.upload_cancelled + stats.in_progress + stats.successful_uploads + stats.upload_errors;
	//
	multiple = (file_total > 1)?true:false;
	size_total = 0;
	if (file_total > 0) {
		video_type = video_types.UPLOAD;
		$(".upload_list").show();
		$(".bt_record_from_webcam").addClass("bt_record_from_webcam_disabled");
		for (var i = 0; i < num_all; i ++) {
			var file = swfu.getFile(i);
			if (file.filestatus == SWFUpload.FILE_STATUS.QUEUED || file.filestatus == SWFUpload.FILE_STATUS.IN_PROGRESS) {
				size_total += file.size;
				fileItem(file);	
			}
		}
	} else {
		video_type = video_types.NONE;
		$(".bt_record_from_webcam").removeClass("bt_record_from_webcam_disabled");
		$(".upload_list").hide();
	}
}
//number of files selected, number of files queued, total number of files in the queued
function fileDialogComplete(numFilesSelected, numFilesQueued, numFilesInQueue) {
	//alert(numFilesSelected+"|"+numFilesQueued+"|"+numFilesInQueue);
	fileList();
}
function fileUpload() {
	if (size_total == 0) {
		alert("The size of all files cannot be 0!");
		return;
	}
	//
	preAllUpload();
}
//==========================================================================================================================================
function preAllUpload() {
	status_uploading = 1;
	swfu.setButtonDisabled(true);
	//
	$(".upload_title").html("Uploading ...");
	prevewTweet();
	//
	$(".swfupload_area").addClass("swfupload_area_hide");
	$(".area_preupload").slideUp();
	$(".area_uploading").slideDown();
	//for speed
	size_loaded = 0;
	//start upload
	file_index = 0;
	goto_url = "";
	if (file_total > 1 && !parent_guid) {
		var url = "http://im.twitvid.com/api/createPlaylist"; 
		$.getJSON("xssapi.php", {url:url, token:uploader_token, format:'json'}, function(data) {																						
			if (data.rsp.stat == 'fail') {
				alert(data.rsp.err.msg + '\nYour twitter token is invalid, Please try to login again!');
			} else {
				playlist_id = data.rsp.playlist_id;
				if (!playlist_id) {
					alert('Wrong playlist id');
				} else {
					preUpload();
				}
			}
		});
	} else {
		preUpload();
	}

}

function preUpload() {
	//get GUID for video first
	status_uploading = 1;
	var stats = swfu.getStats();
	var num_queued = stats.files_queued;
	if (num_queued > 0) {
		var url = "/index.php?area=ajax&cmd=getGUID";
		$.post(url, {token:uploader_token}, function(data){
			if (data) {
				uploader_guid = data;
			
				if($('#retweetToWatch')) {
					if($('#retweetToWatch').attr('checked')) setRetweetToWatchOn(uploader_guid);
				}
				setUpload();
			} else {
			alert('Get guid fail! Maybe your twitter token is invalid, Please try to login again!');	
			}
		});
	}	else {
			uploadDone();
		}
}

function setUpload() {
	status_uploading = 1;
	var stats = swfu.getStats();
	var num_queued = stats.files_queued;
	if (num_queued > 0) {
		
		var url = "/index.php?area=ajax&cmd=setUploadStarting";
		$.post(url, {guid:uploader_guid});
		
		if (parent_guid) {
			swfu.setPostParams({
				"token": uploader_token,
				"message": twitter_message,
				"media_id": uploader_guid,
				"vidResponse_parent" : parent_guid,
				"source":"web",
				"format": "json"
			});
		} else {
			swfu.setPostParams({
				"token": uploader_token,
				"message": twitter_message,
				"media_id": uploader_guid,
				"playlist_id": playlist_id,
				"source":"web",
				"format": "json"
			});
		}
		try {
			swfu.startUpload();
		} catch(e) {
		}
	} else {
		uploadDone();
	}
}

function fileQueueError(file, errorCode, message)  {
	// Handle this error separately because we don't want to create a FileProgress element for it.
	switch (errorCode) {
	case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
		alert("You have attempted to queue too many files.");
		return;
	case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
		alert("The file you selected is too big.");
		return;
	case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
		alert("The file you selected is empty.  Please select another file.");
		return;
	case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
		alert("The file you choose is not an allowed file type.");
		return;
	default:
		alert("An error occurred in the upload. Try again later.");
		return;
	}
}
function uploadStart(file) {
	$(".upload_list_icon_"+file.id).html(states.uploading);
}
function uploadProgress(file, bytesLoaded, bytesTotal) {
	if (bytesTotal) {
		var size_uploaded = size_loaded + bytesLoaded;
		var per = size_uploaded / size_total;
		showPercent(per);
		var speed = SWFUpload.speed.formatBytes(file.currentSpeed * 0.125) + "/s &nbsp;&nbsp; ETA: " + SWFUpload.speed.formatTime(file.timeRemaining)
		$(".upload_list_state_"+file.id).html(speed);
	}
}

function showPercent(per) {
	if (per > 1) {
		per = 1;	
	} else if (per < 0) {
		per = 0;	
	}
	var per_width = Math.round(per * $(".uploading_bar").width());
	$(".uploading_per").width(per_width).html(Math.floor(per * 100) + "%");
}
function uploadError(file, errorCode, message) {
	if (errorCode == SWFUpload.UPLOAD_ERROR.FILE_CANCELLED) {
		return;
	}
	var msg = "";
	switch (errorCode) {
	case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
		msg = "Upload Error: " + message;
		var url = "/index.php?area=ajax&cmd=errorVideo"
		$.post(url, {guid:uploader_guid, extra:errorCode + " " + msg + ": " + message}, function(data){
			//alert(data);
		});
		break;
	case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
		msg = "Upload Failed.";
		var url = "/index.php?area=ajax&cmd=errorVideo"
		$.post(url, {guid:uploader_guid, extra:errorCode + " " + msg + ": " + message}, function(data){
			//alert(data);
		});
		break;
	case SWFUpload.UPLOAD_ERROR.IO_ERROR:
			msg = "Server (IO) Error";
			var url = "/index.php?area=ajax&cmd=errorVideo"
			$.post(url, {guid:uploader_guid, extra:errorCode + " " + msg + ": " + message}, function(data){
				//alert(data);
			});
			break;
	case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
		msg = "Security Error";
		var url = "/index.php?area=ajax&cmd=errorVideo"
		$.post(url, {guid:uploader_guid, extra:errorCode + " " + msg + ": " + message}, function(data){
			//alert(data);
		});
		break;
	case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
		msg = "Upload limit exceeded.";
		var url = "/index.php?area=ajax&cmd=errorVideo"
		$.post(url, {guid:uploader_guid, extra:errorCode + " " + msg + ": " + message}, function(data){
			//alert(data);
		});
		break;
	case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
		msg = "Failed Validation. Upload skipped.";
		var url = "/index.php?area=ajax&cmd=errorVideo"
		$.post(url, {guid:uploader_guid, extra:errorCode + " " + msg + ": " + message}, function(data){
			//alert(data);
		});
		break;
	case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
		msg = "Stopped";
		var url = "/index.php?area=ajax&cmd=errorVideo"
		$.post(url, {guid:uploader_guid, extra:errorCode + " " + msg + ": " + message}, function(data){
			//alert(data);
		});
		break;
	default:
		msg = "Unhandled Error - " + errorCode;
		break;
	}
	$(".upload_list_state_"+file.id).html('<font color="#ff0000">'+msg+'</font>');	
	$(".upload_list_icon_"+file.id).html("&nbsp;");
}
function uploadSuccess(file, serverData) {
	var msg = "";
	if (serverData === " ") {
		msg = "No server data return";
	} else {
		$(".upload_list_data_"+file.id).html(serverData);
		var response = (new Function("return " + serverData))();
		if (response && response.rsp) {
			if (response.rsp.stat == 'ok') {
				if (file_index == 0 || !goto_url) {
					goto_url = "http://twitvid.com/" + response.rsp.media_id;
					prevewTweet();
				}
			} else {
				msg = response.rsp.err.msg;
			}
		} else {
			msg = "Server data parse error";
			var url = "/index.php?area=ajax&cmd=errorVideo";
			$.post(url, {guid:uploader_guid, extra:errorCode + " " + msg+ " "+serverData}, function(data){
				//alert(data);
			});
			
		}
	}
	
	
	
	if (msg) {
		$(".upload_list_state_"+file.id).html('<font color="#ff0000">'+msg+'</font>');
		$(".upload_list_icon_"+file.id).html("&nbsp;");
	} else {
		$(".upload_list_state_"+file.id).html("&nbsp;");
		$(".upload_list_icon_"+file.id).html(states.success);
	}
}

function uploadComplete(file) {
	size_loaded += file.size;
	$(".upload_list_delete_"+file.id).html("&nbsp;");
	file_index ++;
	preUpload();
}

// Called by the queue complete handler to submit the form
function uploadDone() {
	status_uploading = 0;
	if (!all_cancelled) {
		showPercent(1);
		$(".upload_title").html("Upload Complete!");
		$(".uploading_per").addClass("uploading_per_complete");
		if (goto_url) {
			$(".tweet_head").html("The following tweet has been posted:");
			$(".uploading_per").fadeOut("fast",function(){
				$(this).html("Your video"+(multiple?"s":"")+" "+(multiple?"are":"is")+" now in the Twittersphere!").fadeIn("fast");		
			});
			$(".uploading_button").fadeOut("fast",function(){
				$(this).html('<a href="'+goto_url+'" class="bt_go_to_video"></a>').fadeIn("fast");
			});
			if (parent_guid){
				try {
					getVideoResponses(1);
				} catch(e) {}
			}
		}
	}
}
function cancelAllUpload() {
	status_uploading = 0;
	all_cancelled = true;
	video_type = video_types.NONE;
	file_total = 0;
	//
	swfu.stopUpload();
	//
	var stats = swfu.getStats();
	var num_all = stats.files_queued + stats.upload_cancelled + stats.in_progress + stats.successful_uploads + stats.upload_errors;
	//
	for (var i = 0; i < num_all; i ++) {
		var file = swfu.getFile(i);
		swfu.cancelUpload(file.id, false);
	}
	//
	swfu.setButtonDisabled(false);
	showPercent(0);
	
	$(".upload_title").html("Upload and tweet a video");
	//
	$(".upload_list").hide().html("");
	$(".swfupload_area").removeClass("swfupload_area_hide");
	$(".area_preupload").slideDown();
	$(".area_uploading").slideUp();
	//
	$(".bt_record_from_webcam").removeClass("bt_record_from_webcam_disabled").show();
	//
	swfUploadLoaded();
}
//====================================================================================================================================
var record_guid;
var vidcap_created = false;
function showVideoCapture(new_guid) {
	if ($(".bt_record_from_webcam_disabled").length >0 || !new_guid) {
		return;
	}
	record_guid = new_guid;
	if (!vidcap_created) {
		var flashvarsObj = {url:"rtmp://e8wa0nahb6ec.rtmphost.com/videoCap/" + record_guid};
		var parObj = {allowfullscreen:"true", allowscriptaccess:"always", wmode:"opaque"};		
		swfobject.embedSWF("/UI/flash/vidcap.swf", "vidcap", "350", "272", "10", "/UI/flash/expressInstall.swf", flashvarsObj, parObj);
		vidcap_created = true;
	}
	//
	var display = $(".webcam_area").data("display");
	if (display) {
		closeCapture();
	} else {
		openCapture();
	}
}

function cancelCapture() {
	closeCapture();
}
function openCapture() {
	video_type = video_types.RECORD;
	$(".webcam_area").slideDown("slow").data("display","true")
	if (swfu) {
		swfu.setButtonDisabled(true);	
	}
}
function closeCapture() {
	video_type = video_types.NONE;
	$(".webcam_area").slideUp("slow").data("display","")
	if (swfu) {
		swfu.setButtonDisabled(false);	
	}
}

var intervalID;
var percent = 0.1;
function submitCapture() {
	status_uploading = 1;
	//alert("submitCapture");
	goto_url = "http://twitvid.com/" + record_guid;
	prevewTweet();
	//
	$(".upload_title").html("Tweet sending ...");
	$(".swfupload_area").addClass("swfupload_area_hide");
	$(".area_preupload").slideUp();
	$(".area_uploading").slideDown();
	$(".uploading_button").hide().html('<a href="'+goto_url+'" class="bt_go_to_video"></a>');
	//
	showPercent(percent);
	intervalID = window.setInterval(percentHandler, 50);
	//
	if (parent_guid){
		var url = "/index.php?area=ajax&cmd=webcamResponse"
		$.post(url, {tweet_msg:twitter_message, new_guid:record_guid, parent_guid:parent_guid}, function(data){
			captureDone();
		});
	} else {
		var url = "index.php?area=ajax&cmd=webcamStore"
		$.post(url, {tweet_msg:twitter_message, guid:record_guid}, function(data){
			captureDone();
		});
	}
}
function captureDone() {
	clearInterval(intervalID);
	showPercent(1);

	$(".uploading_per").fadeOut("fast",function(){
		$(this).addClass("uploading_per_complete").html("Tweet sent!").fadeIn("fast");	
	});
	
	$(".uploading_button").fadeIn("fast");

	$(".upload_title").html("Tweet sent!");									 
	$(".tweet_head").html("The following tweet has been posted:");
	if (parent_guid){
		try {
			getVideoResponses(1);
		} catch(e) {}
	}
}
function percentHandler() {
	percent += 0.005;
	if (percent < 0.98) {	
		showPercent(percent);
	} else {
		clearInterval(intervalID);
	}
}
function prevewTweet() {
	status_uploading = 0;
	if (parent_guid) {
		return;
	}
	$(".tweet_head").html("The following tweet will be posted after your upload has finished:");
	$(".tweet_icon").html('<img src="'+user_avatar+'" width="45" height="45" onerror="thumbnailError(this, \'user\');" />');
	var tweet_text = '<a href="/videos/'+twitter_username+'" target="_blank"><b>'+twitter_username+'</b></a> '+twitter_message;
	if (goto_url) {
		tweet_text += ' <a href="'+goto_url+'" target="_blank">'+goto_url+'</a>';
	}
	$(".tweet_text").html(tweet_text); 
}
function doNothing() {
	return 1;
}
window.onbeforeunload = function (evt) {


	//alert(status_uploading);
	if(status_uploading==1) {
  		var message = 'Please click Cancel to keep uploading this video.';
  		if (typeof evt == 'undefined') {
    		evt = window.event;
  		}
  		if (evt) {
    		evt.returnValue = message;
  		}
		msg = "Try Browser Close";
		var url = "/index.php?area=ajax&cmd=errorVideo";
		$.post(url, {guid:uploader_guid, extra:msg}, function(data){
			//alert(data);
		});
  		return message;
	}


}
window.onunload = function(){
  //alert('Video is uploading.');
	if(status_uploading==1) {
	msg = "Browser Close";
	var url = "/index.php?area=ajax&cmd=errorVideo";
	$.post(url, {guid:uploader_guid, extra:msg}, function(data){
		//alert(data);
	});
	setTimeout ( "doNothing()", 5000 );
	}
}