var active = false;
var convertactive = false;
var file = "";
var size = 0;
var stopPos = 100;
var upfile;
var swfu;
var player;

// LOADER ON
function loaderOn(text) {
	$.blockUI({ message: '<h3><img src="imgs/loader.gif" /> '+ text +'</h3>' });
}

// LOADER OFF
function loaderOff() {
	$.unblockUI();
}

// EXECUTE ON LOAD
$(document).ready(function() {
	// set start position for footpanel
	stopPos = $(".footpanel").position().top;
	
	// continue download
	if (inprogress == 'true') {
		$('#bartext').html('Downloading your video');
		startDownloadTimer();
		$(".footpanel").css("visibility", "visible");
		$("#ad728").show();
	}
	
	// continue convert
	if (convertinprogress == 'true') {
		$('#bartext').html('Converting your video');
		startConvertTimer();
		$(".footpanel").css("visibility", "visible");
		$("#ad728").show();
		$("#footer-like").show();
	}
	
	// start button hover
   	$("input.start-button").hover(function(event){
		$(this).addClass("start-button-hover");
	},function(){
		$(this).removeClass("start-button-hover");
	});
		
	// set onScroll to load next 20 clips
	$(window).scroll(function() {
		if ($(window).scrollTop() == $(document).height() - $(window).height()) {
			loadNextClips(category_id);
		}
	});
});

// CHANGE TAB
function changeTab(tab_id) {
	if (tab_id == 'online-videos') {
		$('#online-videos-btn').attr('class', 'current-type');
		$('#local-videos-btn').removeClass('current-type');
		$('#local-videos').hide();
		$('#tab-container').html($('#online-videos').html());
	} else {
		$('#local-videos-btn').attr('class', 'current-type');
		$('#online-videos-btn').removeClass('current-type');
		$('#online-videos').hide();
		$('#tab-container').html($('#local-videos').html());
		LoadSWF();
	}
}

// LOAD NEXT 20 CLIPS
function loadNextClips(catid) {
	var ID = $(".videolist:last").attr("id");
	if (!parseInt(ID)) {
		ID = 0;
	}
	var ajax_url = 'ajax.php?function=loadmore&last_id='+parseInt(ID)+'&catid='+parseInt(catid);
	$('div#last_loader').fadeIn();
	$.ajax({
        async: false,
        global: false,
        url: ajax_url,
        success: function (data) {
        	$('div#last_loader').fadeOut();
			if (data != "") {
				$(".loadmorehere:last").after(data);
			}
        }
    });
}

// SET DEFAULT DOWNLOAD TEXT
function defaultDownloadText(value) {
	if (value == "show") {
		if ($("#url").val() == "") {
			$("#url").val("Enter the URL then press the START button");
		}
	}
	if (value == "clear") {
		if ($("#url").val() == "Enter the URL then press the START button") {
			$("#url").val("");
		}
	}
}

// DROP FLOOR ANIMATION
function dropFloor() {
	var startPos = 0;
	$(".footpanel").css("top", startPos);
	$(".footpanel").css("visibility", "visible");
	$("#ad728").show();
	
	$(".footpanel").stop().animate({
		marginTop: stopPos+"px"
	}, {
		duration: 1000,
		easing: "easeOutBounce"
	});
	return false;
}

// DOWNLOAD ONLINE VIDEO
function downloadFromSite() {
	if (inprogress != 'true' && convertinprogress != 'true') {
		var catid = $('#category_id').val();
		if (!parseInt(catid)) {
			catid = 0;
		}
		var original_url = $('#url').val();
		$('#url').val('Please wait...');
		$.ajax({
		    url: 'ajax.php?function=downloadvideo',
		    type: 'GET',
		    cache: false,
		    dataType: 'text',
		    data: 'url=' + $.URLEncode(original_url) + '&category_id=' + catid,
		    error: function(){
		        alert('Network error. Try refreshing the page.');
		    },
		    success: function(response){
				if (response == "ok") {
					$('#bartext').html('Downloading your video');
					$('#progress').text('0%');
			        $('.progress-color').width('0%');
					dropFloor();
					startDownloadTimer();
					$('#url').val(original_url);
				} else if (response == "redirect") {
					location.href = 'http://www.xtubegrabber.com/?url='+$.URLEncode(original_url);
				} else if (response == "limit") {
					alert("You are allowed to dowload only 3 clips per day.\nYou have to register to download unlimited video clips.");
				} else {
					alert("This video can't be downloaded. Try another one.");
				}
		    }
		});
	} else {
		alert("There is another video downloading in progress.");
	}
}

function startDownloadTimer() {
	if (!active) {
		active = !active;
		$('.footpanel').everyTime(1000, 'controlled', function() {
			$.ajax({
			    url: 'ajax.php?function=checkprogress',
			    type: 'GET',
			    cache: false,
			    dataType: 'text',
			    error: function(){
			        // error here
			    },
			    success: function(response) {
			    	var progress = response+'%';
			        $('#progress').text(progress);
			        $('.progress-color').width(progress);
			        if (response == '100') {
			        	stopDownloadTimer();
			        }
			    }
			});
		});
	}
}

function stopDownloadTimer() {
	if (active) {
		active = !active;
		$('.footpanel').stopTime('controlled');
		$.ajax({
		    url: 'ajax.php?function=finished',
		    type: 'GET',
		    cache: false,
		    dataType: 'text',
		    error: function(){
		        // error here
		    },
		    success: function(response) {
		    	if (response != 'error') {
					inprogress = 'false';
					$('#progress').html('<a href="http://www.tubeminator.com/convert-'+response+'.html?reset=true">Click here to go to STEP 2</a>');
		    	}
		    }
		});
	}
}

// CONVERT VIDEO
function convertVideo(flvfile, format) {
	if (inprogress != 'true' && convertinprogress != 'true') {
		convertinprogress = 'true';
		$.ajax({
		    url: 'ajax.php?function=convertvideo',
		    type: 'GET',
		    cache: false,
		    dataType: 'text',
		    data: 'flvfile=' + flvfile + '&start=' + $('#start').val() + '&duration=' + $('#duration').val() + '&format=' + format + '&size=' + $('#size').val() + '&vq=' + $('#vq').val() + '&aq=' + $('#aq').val(),
		    error: function(){
				alert('Network error. Try refreshing the page.');
		    },
		    success: function(response){
		    	if (response == "ok") {
		    		$('#bartext').html('Converting your video');
		    		$('#progress').text('0%');
			        $('.progress-color').width('0%');
					$("#footer-like").show();
					dropFloor();
					startConvertTimer();
				}
		    }
		});
	} else {
		alert("There is another video converting in progress.");
	}
}

function startConvertTimer() {
	if (!convertactive) {
		convertactive = !convertactive;
		$('.footpanel').everyTime(1000, 'controlled', function() {
			$.ajax({
			    url: 'ajax.php?function=checkconvertprogress',
			    type: 'GET',
			    cache: false,
			    dataType: 'text',
			    error: function(){
			        
			    },
			    success: function(response){
			    	var progress = response+'%';
			        $('#progress').text(progress);
			        $('.progress-color').width(progress);
			        if (response == '100') {
			        	stopConvertTimer();
			        }
			    }
			});
		});
	}
}

function stopConvertTimer() {
	if (convertactive) {
		convertactive = !convertactive;
		$('.footpanel').stopTime('controlled');
		$.ajax({
		    url: 'ajax.php?function=convertfinished',
		    type: 'GET',
		    cache: false,
		    dataType: 'text',
		    error: function(){
		        // error here
		    },
		    success: function(response) {
		    	if (response != 'error') {
					convertinprogress = 'false';
					$('#progress').html('<a href="http://www.tubeminator.com/getvideo-'+response+'.html">Click here to download your converted file</a>');
		    	}
		    }
		});
	}
}

function secToStr(seconds) {
	var output = "00:00";
	seconds = seconds.toFixed();
	sec = seconds % 60;
	min = (seconds-sec)/60;
	if (min < 10) min = '0' + min;
	if (sec < 10) sec = '0' + sec;
	output = min + ":" + sec;
	return output;
}

function playerReady(obj) {
	player = document.getElementById(obj['id']);
};

function sendEvent(typ,prm) { 
	player.sendEvent(typ,prm);
}

function LoadSWF() {
    swfu = new SWFUpload({
		upload_url: "upload.php",
		flash_url : "swfupload.swf",

		// Flash file settings
		file_size_limit : "819200",
		file_types : "*.avi;*.mpg;*.mp4;*.3gp;*.mov;*.wmv;*.flv;*.mkv",
		file_types_description : "All Files",
		file_upload_limit : "0",
		file_queue_limit : "1",

		// Event handler settings
		swfupload_loaded_handler : swfUploadLoaded,
		file_queued_handler : fileQueued,
		file_queue_error_handler : fileQueueError,
		file_dialog_start_handler : fileDialogStart,
		file_dialog_complete_handler : fileDialogComplete,
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadSuccess,
		upload_complete_handler : uploadComplete,
	
		// UI settings
		button_image_url : "imgs/browse-btn.gif",
		button_placeholder_id : "btnBrowse",
		button_width: 91,
		button_height: 40,
		button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE,
		button_disable: false,
		button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT, 

		// OTHER SETTINGS
		custom_settings : {
			progress_target : "fsUploadProgress",
			upload_successful : false
		},
		
		// Debug settings
		debug: false
	});

}

function uploadDone() {
	loaderOn('Creating preview...');
	$.ajax({
	    url: 'ajax.php?function=createpreview',
	    type: 'GET',
	    cache: false,
	    dataType: 'text',
	    data: 'original='+upfile,
	    error: function(){
	        alert('Network error. Try refreshing the page.');
	    },
	    success: function(response){
			if (response != "error") {
				location.href = 'http://www.tubeminator.com/convert-'+response+'.html';
			}
	    }
	});
}

function killProcess() {
	$.ajax({
	    url: 'ajax.php?function=killprocess',
	    type: 'GET',
	    cache: false,
	    dataType: 'text',
	    error: function(){
	        alert('Network error. Try refreshing the page.');
	    },
	    success: function(response){
			if (response == "ok") {
				active = false;
				convertactive = false;
				inprogress = false;
				convertinprogress = false;
				location.href = 'http://www.tubeminator.com';
			}
	    }
	});
}

function refreshImage(id) {
	var numRand = Math.floor(Math.random()*101);
	$('#'+id).attr("src","imgs/kcaptcha/get_image.php?"+numRand);
}

// CHECK/UNCHECK ALL
function selectAll() {
	var fr = document.getElementsByTagName('input');
	for (var i = 0; i < fr.length; ++i)
		if (fr[i].type == 'checkbox') {
			fr[i].checked = document.getElementById('selectall').checked;
		}
}
