/*
IMPORTANT ADVISE
The following code is protected by copyright 
 *  (c) 2009 Davide Rolando
except for the functions that don't contain the notice:
	// Copyright © 2009 Davide Rolando //

Thus you can't use any of the copyright protected code 
without first obtaining written permission. 
Please email  webmaster@subsedit.com to obtain written consent.
*/

var f_tube = "resources_t/tubesub_f.php";
var thesubs = '';

	$('#start_time').click(function(){
		var r = retTimeS('t1');
		return true;
	})
	$('#end_time').click(function(){
		var r = retTimeS('t2');
		pause(); 
		var tt = getCurrentTime();
		if(parseFloat(tt) > 1) backOf(1);
		
		$('#sub_body').focus();
		return true;
	})
	$('#csel').click(function(){
		movesel('notes','sub_body',true);
		return true;
	})
	$('#b_clean').click(function(){
		$('#sub_body').val('');
		return true;
	})
	$('#save_subs').click(function(){
		thesubs = $('#thesubs').val();
		var saved = subsup();
		reportLog("Subtitles saved");
		return true;
	})
	$('#create_srt').click(function(){
		$('#active').val(activeVid());
		document.new_down.submit();
		return true;
	})
	$('#b_add').click(function(){
		//se thesubs è vuota mando la richiesta di upload di s_body
		//mi ritorna il sottotitolo formattato srt e l'md5 che salvo nell'input hidden subhash
		
		jslog.debug("ora in thesubs : " + thesubs );
		
		if( (thesubs.length == 0) || (MD5(thesubs) == $('#subhash').val()) ){
			var raw = addsub('diag','t1','t2','sub_body');

			var ret = req_synch('addsub',raw);
			
			thesubs = thesubs + ret[0];
			
			jslog.debug("ADDSUBS ora in thesubs : " + thesubs );	
			
			$('#subhash').val(ret[1]); 
			$('#t_count').val(ret[2]);		
			$('#t_next').val(ret[3]);
			$('#t_next2').val(ret[4]);
			
			var myhash = MD5(thesubs);
			
			//jslog.debug("subhash ora vale : " + $('#subhash').val());
			//jslog.debug("thesubs ora vale : " + myhash);
			//jslog.debug("Dati server : " + ret[2]);
			//jslog.debug("Dati locali : " + $('#thesubs').val());
			//NB : aggiungo valori a retval[] per avere comodi i comandi NEXT e NEXT-LAST
			
			if($('#subhash').val() != myhash){
				jslog.info("Necessario DOWNLOAD");
				reportLog("Working ...");
				$.ajax({
				type: "POST",
				url: f_tube,
				data: ({
					action: 'tdown',
					plus: myhash
				}),
				success: function(data){
						thesubs = data;
						$('#thesubs').val(thesubs);
						$('#thesubs').focus();
						
						}
				});		
			} //else fine.

		
		//se thesubs non è vuota confronto il suo md5 con quello di subhash
			//se è uguale a quello di sessione mando solo s_body che mi ritorna formattato e in coda al resto
			//se è diverso prima faccio l'upload di thesubs e poi mando s_body		
		} else {
			jslog.info("Necessario UPLOAD");
			var saved = subsup();
			if(saved){
				var myhash = MD5(thesubs);
				//DOWNLOAD
				if($('#subhash').val() != saved){
					jslog.info("Necessario DOWNLOAD");
					reportLog("Working ...");
					$.ajax({
					type: "POST",
					url: f_tube,
					data: ({
						action: 'tdown',
						plus: myhash
					}),
					success: function(data){
						thesubs = data;
						$('#thesubs').val(thesubs);
						$('#thesubs').focus();
						}
					});		
				} //else fine.
			}
		}
		
		//var str = addsub('diag','t1','t2','sub_body');
		//jslog.info("raw sub add " + str);
		//reverseval('thesubs')
		jslog.info("Real " + thesubs);
		//var topsy = reversesubs(thesubs);
		$('#thesubs').val(thesubs);
		$('#thesubs').focus();
		reportLog("Subtitles updated");
		return true;
	})
	$('#b_next').click(function(){
		$('#diag').val(eval(Number($('#t_count').val()) + 1));
		$('#t1').val($('#t_next').val());
		$('#t2').val($('#t_next2').val());
		$('#sub_body').focus();
		$('#sub_body').select();
		return true;
	});
	$('#b_dumb').click(function(){
		var rr = ytplayer.getVideoUrl();
		jslog.info("url : " + rr);
		return true;
	});




function reversesubs(subs){
	if(subs.length < 1 || subs.indexOf("\n\n") == -1 ){
		return subs;
	}
	var temp = subs.split("\n\n");
	jslog.info("revers temp " + temp.length);
	var revers = '';
	for(var i = temp.length-1; i > -1; i--){
		revers += temp[i] + "\n\n";
	}
	jslog.info("revers " + revers);
	return revers;
}

function lastuservid(usr){
	if(usr.length < 1) return false;
	reportLog("Searching videos...");
		$.ajax({
			type: "POST",
			url: f_tube,
			data: ({
				action: 'user',
				req: usr
			}),
			success: function(data){
				//tt = eval(data);
				jslog.info(data);
				$('#uservideos').html(data);
				reportLog("Video search complete");
			}
		});
	
}

var retreq = '';
function req_synch(todo, param){
jslog.debug("req_synch richiesta : " + todo + " e " + param);
	$.ajax({
	  type: "POST",
	  url: f_tube,
	  data: ({
	  	action: todo,
	  	req: param
	  }),
	  async: false,
	  success: function(data) {	  
				retreq = data;
				return true;							
			}
	});
jslog.debug("req_synch ritorno : " + retreq);
	return eval(retreq);
}

function retTime(el){
	var cs = getCurrentTime();
	jslog.info("Richiesta tempo start " + cs);
	
	$.ajax({
	type: "POST",
	url: f_tube,
	data: ({
		action: 'sertime',
		req: cs
	}),
	success: function(data){$('#'+el).val(data)}
	});
	//$('#'+el).val(toTimeCode(cs));
	return true;
}
function retTimeS(el){
	var cs = getCurrentTime();
	jslog.info("Richiesta tempo start " + cs);
	$('#'+el).val(toTimeCode(cs));
	return true;
}

function movesel(fromId, toId, sel){
	// Copyright © 2009 Davide Rolando //
	var txtarea = document.getElementById(fromId);
	var curdiag = document.getElementById(toId).value;
	if(sel == true){
		var stxt = (txtarea.value).substring(txtarea.selectionStart,txtarea.selectionEnd);
		stxt.length<1 ? alert("No text selected") : curdiag += stxt;
	}
	else{curdiag += (txtarea.value);}
	document.getElementById(toId).value =curdiag.substring(0,100);
	//wCount();
	document.getElementById(toId).focus();
}

function changeytvid(vidsh){
	jslog.info("vidsh : " + vidsh);

	var dlink = vidsh.indexOf("watch?v=");
	
	jslog.info("dlink : " + dlink);
	if(dlink != -1){
		var id = vidsh.substr(eval(dlink+8),11);
		jslog.info("video id : " + id);
		var trr = loadNewVideo(id,0) ; 
		return true;
	} else {
		var trr = loadNewVideo(vidsh,0) ; 
		jslog.info("loadnNewVideo : " + trr);
		return true;		
	}
	return false;
	
}


function subsup(){
	var valsh = uploadsubs('thesubs', 10000, 'youtube');
	var ret = eval(valsh); 
	$('#subhash').val(ret[1]);
	$('#t_count').val(ret[2]);
	$('#t_next').val(ret[3]);
	$('#t_next2').val(ret[4]);

	jslog.debug("subsup : " + valsh);
	return ret[1];
}

function addsub(snum,sstart,send,sbody){
	// Copyright © 2009 Davide Rolando //
	var tn = $('#'+snum).val();
	var ts = $('#'+sstart).val();
	var te = $('#'+send).val();
	var tb = $('#'+sbody).val();
	
	if(tb.length < 1){
		return false;
	}

	var rawsub = tn + "|" + ts + "|" + te + "|" + tb;
	return rawsub;
}

/* ###################################### */
		function wCount(){
			// Copyright © 2009 Davide Rolando //
			var txt = document.getElementById('one_d').value;
			var cnt = document.getElementById('wcount');
			var wlen = txt.length-1;
			var wret = txt.indexOf("\n");
			var maxr = 0;
			var warr = (txt.split("\n")).length;
			
			wret >= (wlen-wret) ? maxr = wret : maxr = wlen-wret;
			
				if(maxr > 40 || warr > 2){
					cnt.style.color='red';
				} else {
					cnt.style.color='white';
				}
					cnt.innerHTML = maxr;
			return maxr;
		}

		function newSub(elemId, last){
			// Copyright © 2009 Davide Rolando //
			var temp = document.getElementById('source').value;
			var dnum = srtparse2('source') + 1; 
			document.getElementById('s_num').value = dnum;
				if(dnum > 1 && temp.length < 1){
					dnum--;
				}
				if(last != undefined && last == true){
					var timestart = askfor('dtmk', 'dtmk', false, false,false, 'dtmk')
				} else {
					var prevend = document.getElementById('t_end').value;
						if(prevend == '' || temp.length < 1){
							prevend = '00:00:00,100';
						}
					document.getElementById('t_begin').value = prevend;
					var timestart = askfor(prevend, 'a4e7rblqz70s143', 't_end');
				}
			document.getElementById(elemId).focus();
		}
		
		
		var src_subs = '';
		
		
		var down_check = false;
		
		

		
		
		function down_new(){document.new_down.submit();}
		
		

		
		
		function srtparse2(elemId){
			// Copyright © 2009 Davide Rolando //
			var src = trim(document.getElementById(elemId).value);
			src = scrub(src, 'srt');
			document.getElementById(elemId).value = src;
			var sArr = dialSplit(src, 'srt');
			return sArr.length;
		}
		
		
		var stest = '';
		var t_from = '';
		var t_to = '';
		var t_bool = false;
		var c_next = 0;
		var t_num = 0;
		
		var t_display = false;
		var c_att_b = 0;
		var c_att_e = 0;
		
		var t_gap = 0;
		var t_old = 0;
		
		
		
		function test_sel(c_time){
			// Copyright © 2009 Davide Rolando //
		if(c_time < 0.1){c_next = 0;}
			t_gap = Math.abs(c_time - t_old);
			t_old = c_time;

			if(t_gap > 0.6){
				c_next = sub_next(c_time, stest);
							document.getElementById('test_a').value = '';
							document.getElementById('test_b').value = '';
							document.getElementById('test_e').value = '';
							document.getElementById('test_n').value = '';
				return;
			}
			
			if(t_display == false){
			
				if(c_time > stest[c_next][1]){
					document.getElementById('test_a').value = stest[c_next][5];
					/*
					document.getElementById('test_b').value = stest[c_next][3];
					document.getElementById('test_e').value = stest[c_next][4];
					document.getElementById('test_n').value = stest[c_next][0];
					*/
					t_display = true;
					//document.getElementById('temp').value = t_display + " " + c_next;
					//document.getElementById('preview').value += c_time; 
					return;
				} else { 
					return;
				}
				
			} else {
				//for(i=1; i < stest.length; i++){
				if(c_time > stest[c_next][2]){
						document.getElementById('test_a').value = '';
					/*	
						document.getElementById('test_b').value = '';
						document.getElementById('test_e').value = '';
						document.getElementById('test_n').value = '';
					*/
						
						c_next++;

						t_display = false;
						//document.getElementById('temp').value = t_display + " " + c_next;
						return;
				} else { 				
					return;
				}
			}

				
		}	
		
		function sub_next(tc , sarr){
			// Copyright © 2009 Davide Rolando //
				for(var i = 1;i < sarr.length;i++){;
					if(tc > sarr[i-1][1] && tc < sarr[i][1]){
						var s_next = i;
						return s_next;
					}
				}
				return 0; 
		}
		
		function s_edit(sw){
			// Copyright © 2009 Davide Rolando //
			document.getElementById('s_num').value = stest[sw][0];
			document.getElementById('t_begin').value = stest[sw][3];
			document.getElementById('t_end').value = stest[sw][4];
			document.getElementById('one_d').value = stest[sw][5];
		}
		
		
		
		
		
	
		

		

		

		function test_vis(){
			// Copyright © 2009 Davide Rolando //
		askfor('test_arr', 'd4d1x9oxnfg0mgm', false, false,false, 'test_arr');
			document.getElementById('ctrl_t').style.display = 'block';
			document.getElementById('ctrl_t1').style.display = 'block';	
			document.getElementById('ctrl_0').style.display = 'none';
			document.getElementById('ctrl_1').style.display = 'none';
			document.getElementById('ctrl_2').style.display = 'none';
			
		}
		function timecode2(tvalue){
			// Copyright © 2009 Davide Rolando //
			if(tvalue > 0.6){
				tvalue = eval(tvalue - 0.3);
				} else { tvalue = 0,100 }
			var start = "00:00:" + roundTo(tvalue, 3);
			var stop = "00:00:"+eval(tvalue + 2.5);
			return start + " --" + "> " +stop; 
		}
	
	
	
	
	function askfor(what, comId, where, addup, hnd, plus){
			// Copyright © 2009 Davide Rolando //
	var http = objCreate();
		if (what != ""){
			var url = "resources_t/tubesub_f.php";
			var params = "need="+comId+"&content="+what;
			
			http.open("POST", url, true);
			http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			http.setRequestHeader("Content-length", params.length);
			http.setRequestHeader("Connection", "close");
			http.onreadystatechange = function() {
				
				if(http.readyState == 4) {
					var retAsk = http.responseText;
					document.getElementById('alertlog').innerHTML = "Ready";
						if(hnd != undefined && hnd != false){
							retAsk = handleResponse(retAsk, hnd);
						}
						if(hnd != undefined && addup == true){
							document.getElementById(where).value += retAsk;
						} else {
							if(where != false){
								document.getElementById(where).value = retAsk;
							} 
						}
					if(plus){
						handleResponse(retAsk, plus);
					}
				} else {
					document.getElementById('alertlog').innerHTML = 'Please wait...';
				}
			}
			http.send(params);
		} else { 
			alert("empty source");
		}
	}
	
	
	
	function handleResponse(stuff,rid){
			// Copyright © 2009 Davide Rolando //
		if(rid == true){
			var decom = stuff.split("|||");
			src_subs = decom[1];
			alert(src_subs);
			document.getElementById('preview').value = src_subs;
			return decom[0];
		}
		
		if(rid == "md5_1"){
			var decom = stuff.split("|||");
			switch (decom[0]) {
				case '1010':
					document.getElementById('source').value += decom[1];
					break;

				case '1020':
					document.getElementById('source').value = decom[1];
					break;
				case '2010':
					document.getElementById('source').value += decom[1];
					down_check = true;
					uploadplus('source','tube','msg_src');
					break;
				case '2020':
					alert('Connection Error');
					break;
				default:
					document.getElementById('source').value += decom[1];
					down_check = true;
					uploadplus('source','tube','msg_src');
					break;
			} 
		}
		if(rid == "up1stpass"){
			var decom = stuff.split("|||");
			alert(decom[0]);
			var add_subs = decom[1];
			return decom[1];
		}
		if(rid == "dchk"){
			if(stuff != 'dnn'){
				var tmp = stuff;
				document.getElementById('source').value = tmp;
			}
		}
		if(rid == "dtmk"){
			var tm = eval(stuff);
			document.getElementById('t_begin').value = tm[0];
			document.getElementById('t_end').value = tm[1];
		}
		if(rid == "test_arr"){
			if(stuff == 'ko'){stest = '';return false;}
			stest = eval(stuff);
			//document.getElementById('one_d').value = tm[0][5];
			//document.getElementById('preview').value = tm[0][4];
		}
		if(rid == "ref"){
			alert("ref md5 PHP " + stuff);
			alert("ref md5 JS  " + MD5(document.getElementById('source').value));
			if(stuff == MD5(document.getElementById('source').value)){
				alert("Upload Not necessary");
			} else {
				alert("Need Upload");
			}
		return false;
		}
	}
	
	//corners
	$('#header').corner();
	$('#container').corner();
	$('#footer').corner();
	$('#reportLog').corner();
