$(document).ready(function(){
$.ajaxSetup({ cache: false }); 
//$("#uploadprogressbar").progressBar();
$('#GetVideoInfoBt').click(function(e){
    
	var	data = {url:$("#urlBox").val()};
	if($("#urlBox").val().indexOf("http://www.youtube.com/")==-1)
    {
     alert('Please enter a Youtube URL!');
     return;
    }
		if (data.url.length == 0 || data.url == 'PUT YOUR VIDEO URL HERE') {
					alert('PUT YOUR VIDEO URL');
		}
		else{
			$.post('start.php', data, responseHandler, 'json');	
            $('#downloadLinkA').toggle();
            $('#VideoDownloadLinkAnalyzing').toggle();
            $('#DownloadURLList').toggle();
            $('#GetVideoInfoBt').attr('disabled',true);
		}
	
	});
	
	
	
	responseHandler = function (data) {
		switch (data.state) {
			case '05':
			   IsSame=0
			   beginRemoteUploadBatch2(data.task);
			break;
        	case '02':
                SetProgress(100);
                walkDownloads2(data.msg);
			    break;
			case '03':
				$("#downloadVideoB").html('<br /><label><strong>Status: </strong></label>Preparing...');
				beginRemoteUploadBatch2(data.task);
			break;
			case '01':
			case '04':
			case '02':
			  //  $('#GetVideoInfoBt').attr('disabled',true);
			    $('#VideoDownloadLinkAnalyzing').toggle();
			    $('#DownloadURLList').toggle();
			   // $("#DownloadURLList").html(data.msg);
			   UpdataURLList(data);
			    break;
			case '06':
			    $('#VideoDownloadLinkAnalyzing').toggle();
				ShowErroMSG(data.msg);
			break;

		}

	}
	
	
});
var IsSame=0;
function ShowErroMSG(str)
{
str='<ul><li>'+str+'</li></ul>';
$("#DownloadURLList").html(str);
}
function UpdataURLList(data)
{
    var html="<ul>";
    var end="</ul>";
    var urls=data.msg;
    for(var i =0 ;i<data.total;i++)
    {
        strfunction="OnClickDownURL('"+urls[i].URL+"','"+urls[i].FileName+"','"+urls[i].ID+"','"+urls[i].FileSize+"','"+urls[i].VidoType+"')";
       html+='<li><a href="javascript:void(0)" onclick="'+strfunction+'" >'+urls[i].type+'</a></li>' ;
    }
    html+=end;
    $("#DownloadURLList").html(html);
}

var taskList = [];
var readyFiles = [];
var taskDone = 0;

function OnClickDownURL(url,filename,id,filesize,filetype)
{
    $("#downloadLinkA").toggle();
    $('#downloadVideoA').toggle();
    var	data2 = {url:url,id:id,filename:filename,filesize:filesize,filetype:filetype};
    $.post('DownLoad.php', data2, null, 'json');	
    beginRemoteUploadBatch2(id);
  //  beginRemoteUpload(id);
	//http://www.youtube.com/watch?v=lg3tIERI-D4&feature=topvideos
//    $.ajax({
//    type:"POST",
//    url:"DownLoad.php",
//    cache: false,
//    dataType:'json',
//    data:data2,
//    success:function (data)
//    {
//       switch (data.state) {
//			case '01':
//				alert(data.msg);
//				$("#downloadVideoB").html(data.html);
//			break;
//			case '02':
//			    SetProgress(100);
//			    walkDownloads2(data.msg);
//			  //  $("#mainbox").html($('.mainbox_template').html());
//			    break;
//			case '03':
//				$("#downloadVideoB").html('<br /><label><strong>Status: </strong></label>Preparing...');
//				beginRemoteUploadBatch2(data.task);
//			break;
//			case '04':
//			    $('#GetVideoInfoBt').attr('disabled',true);
//			    $('#VideoDownloadLinkAnalyzing').toggle();
//			    $('#DownloadURLList').toggle();
//			   // $("#DownloadURLList").html(data.msg);
//			   UpdataURLList(data);
//			    break;
//			case '06':
//				$("#downloadVideoB").html('<br /><label><b>Status: </b></label>' + data.msg);
//			break;

//		}
//    },
//    error:function (XMLHttpRequest, textStatus, errorThrown) 
//    {
//        alert(XMLHttpRequest.responseText);
//    }
//    });
}
    
function beginRemoteUploadBatch2(id) {
	$('#downloadVideoB').html('Preparing');
	beginRemoteUpload(id);
}
function SetProgress(num)
{
  $('#videoToServer').html(Math.ceil(num)+'%<div id="toServerProgress"><div id="toServerProgressBar" style="width:'+Math.ceil((num*400)/100)+'px"></div></div>');
}
function beginRemoteUpload (taskid) {
	
	var i = setInterval(function(){
	$.getJSON("call.php?action=downloadstatus&id="+taskid, function (data) {
		/*
		* codes
		* 01 video not found in database
		* 02 error in file
		* 03 error in filename or totalsize
		* 04 downloaded
		* 05 in progress
		* 06 wrong neightborhoud
		*/
		switch (data.state) {
			case '01':
			case '02':
			case '03':
//				try { clearInterval(i); } catch (e) { }
//				$("#downloadVideoB").html('<br /><span style="color:red;font-weight:bold;">'+data.msg+'</span>');
//				Registry.write_err(data.msg);
//				nextUpload();
				//restoreMainbox();
			break;
			case '04':
				clearInterval(i);
				$.getJSON("call.php?action=status&id="+taskid, function (data) {
					switch (data.state) {
						case '03':
							bridgeProgress(taskid);
						break;
						default:
							clearInterval(i);
							$("#downloadVideoB").html('<br /><span style="color:red;font-weight:bold;">Internal Error: Please try again later  (Code: AjaxDD1)</span>');
							return;
						break;
					}
				});
				SetProgress(100);
			break;
			case '05':
			    if(ShowURL==0)
			    {
				var size = 0;
				var total_size = 1;
				size = Math.ceil(data.current/1024);
				total_size = Math.ceil(data.total/1024);
				if(size>total_size)
				{
				size=total_size;
				}
				var percentage = size/total_size;
				if(percentage==1)
				{
				percentage=0.99;
				}		
				SetProgress(percentage*100);	
				}
			break;
			case '06':
				clearInterval(i);
				return;
			break;
		}
		
	});
  }, 2000);
  return true;
}
function bridgeProgress (taskid){
	$.getJSON("call.php?action=startconvert&id="+taskid, function (data) {
		//01 not found in database
		//02 can not update
		//03 ready
		//04 started
	 	switch (data.state) {
			case '01':
			case '02':
				$("#downloadVideoB").html('<br /><span style="color:red;font-weight:bold;">'+data.msg+'</span>');
				return;
			break;
			case '03':
				finished(taskid);
			break;
			case '04':
				beginConvertProgress(taskid);
			break;
			default:
				return;
			break;
		}
	});
}

function finished (taskid) {
	$.getJSON("call.php?action=finished&id="+taskid, function (data) {
		//01 not found in database
		//02 ready
		//03 error
		switch (data.state) {
			case '01':
			case '03':
				$("#downloadVideoB").html('<br /><span style="color:red;font-weight:bold;">'+responsecheck[1]+'</span>');
				return;
			break;
			case '02':
				readyFiles.push(data.file);
				nextUpload();
				if (taskDone&&(ShowURL==0)) {
					$("#downloadVideoB").html(data.msg);
					walkDownloads2(data.file) ;
				}
				//$("#mainbox").html($('.mainbox_template').html());
			break;
		}
	});
}

function walkDownloads2 (url) {
    $("#videoToServer").toggle();
    var msg = "Task done!";
		$("#downloadVideoB").html(msg);
	var text = "Your video has been successfully prepared<br />";
		text += '<a class="download"  href="'+url+'">Hit Here to Download</a>';
		$("#videoToCustomer").toggle();
	$("#videoToCustomer").html(text);
	ShowURL=1;
}

function nextUpload() {
		taskDone = 1;
		var msg = "Task done!";
		$("#downloadVideoB").html(msg);
}
function ShowVedioInfo(img,title,info)
{
	var html='<div class="screenshots"><img src="'+img+'" /></div><div class="videoTitle">'+title+'</div><div class="description">'+info+'</div><div class="clear"></div>';
	$('#videoInfo').hmtl(html);
	
}
var ShowURL=0;
