var folder = randomString();
var file;
var pid;
var attempts;
var allowdownload = 1;
var allowmake = 0;
var ringtone;
var recipe;
var videoURL = '';
var proceedRecipe = 0;
var host = window.location.host;
var type = 'ringtone';
if (host.indexOf('makevideo') != -1) { type = 'videotone'; }

function silentErrorHandler() { return true; }
window.onerror = silentErrorHandler;

function randomString() {
 var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
 var string_length = 16;
 var randomstring = '';
 for (var i=0; i<string_length; i++) {
  var rnum = Math.floor(Math.random() * chars.length);
  randomstring += chars.substring(rnum,rnum+1);
 }
 return randomstring;
}

function replaceContent(place,content,func) {
 $(place).fadeTo(125,0,function() {
  $(place).html(content);
  $(place).fadeTo(125,1,func);
 });
}

function checkStatus(data) {
 if (pid == 0) return;
 var toplay;
 if (typeof(data.status) == 'string') {
  if ((data.status == 'Downloading') || (data.status == 'Finishing') || (data.status == 'Completed') || (data.status == 'Decoding')) {
   if (data.progress > 1) {
    $("#progressbar").progressbar('option','value',data.progress);
   }
  }
  if (data.status != $("#statuslabel").html()) replaceContent('#statuslabel',data.status);
  if ((data.status != 'Completed') && (data.status != 'Error') && (data.pid == pid)) {
   setTimeout('jah(' + pid + ',"' + folder + '");',500);
  }
  if ((data.status == 'Error') || (data.status == 'Completed')) { $("#stopbutton").val('reset'); }
  if (data.status == 'Completed') {
   if (data.pid != pid) return;
   file = data.filename;
   if (data.filename2) { toplay = data.filename2; } else { toplay = file; }
   showPlayer('http://' + data.host, 'downloads/' + data.folder + '/' + toplay);
  }
 }
 else {
  attempts--;
  if (attempts > 0) { setTimeout('jah();',500); }
  else {
   replaceContent('#statuslabel','Error');
   $("#stopbutton").val('reset');
  }
 }
}

function jah() {
 if (pid == 0) return;
 var url = '/status.html?pid=' + pid + '&folder=' + folder + '&rnd=' + Math.random();
 var Params = {};
 Params.type = "GET";
 Params.url = url;
 Params.dataType = "json";
 Params.success = checkStatus;
 Params.error = function() { checkStatus({}); };
 $.ajax(Params);
}

function checkMakeStatus(data) {
 if (pid == 0) return;
 var status;
 if (typeof(data.status) == 'string') {
  if (data.status != $("#makestatuslabel").html()) {
   if (data.status != 'Completed') {
    status = data.status;
    if ((data.status == 'Error') && data.details) status = 'Error: ' + data.details;
    replaceContent('#makestatuslabel',status);
   } else {
    if (data.pid != pid) return;
    ringtone = data.ringtone;
    recipe = data.recipe;
    replaceContent('#makestatuslabel',data.status,function() {
     setTimeout(function() {
      var dwnld = "Download the " + type + ": <a href=\"" + "/downloads/" + folder + "/" + ringtone + "\">" +
                  ringtone + "</a> <span style=\"font-weight: normal;\">(right click - save as)</span>" +
                  "<p style=\"margin-top: 7px; padding: 0; font-weight: normal; font-size: 0.8em;\">" +
                  "<span style=\"color: #095e09;\">Link to share this " + type + ":</span> <span style=\"color: #d52828;\">" +
                  recipe + "</span></p>";
      replaceContent('#makestatuslabel',dwnld);
     },500);
    });
   }
  }
  if ((data.status != 'Completed') && (data.status != 'Error') && (data.pid == pid)) {
   setTimeout('mjah(' + pid + ',"' + folder + '");',500);
  }
  if ((data.status == 'Error') || (data.status == 'Completed')) {
   $("#makestopbutton").val('reset');
   $("#makeprogressbar").fadeTo(250,0);
  }
 }
 else {
  attempts--;
  if (attempts > 0) { setTimeout('mjah();',500); }
  else {
   $("#makeprogressbar").fadeTo(250,0);
   replaceContent('#makestatuslabel','Error: Process/connection terminated.');
   $("#makestopbutton").val('reset');
  }
 }
}

function mjah() {
 if (pid == 0) return;
 var url = '/status.html?pid=' + pid + '&folder=' + folder + '&rnd=' + Math.random();
 var Params = {};
 Params.type = "GET";
 Params.url = url;
 Params.dataType = "json";
 Params.success = checkMakeStatus;
 Params.error = function() { checkMakeStatus({}); };
 $.ajax(Params);
}

function showProgress() {
 $("#stopbutton").val('stop');
 $("#statuslabel").html('Connecting');
 $("#download").fadeTo(250,0,function() {
  $(this).css({ 'display' : 'none' });
  $("#progress").css({ 'display' : 'block' });
  $("#progress").fadeTo(250,1);
  $("#progressbar").progressbar('option','value',1);
 });
}

function showDownload() {
 folder = randomString();
 $("#urlinput").val('');
 $("#progress").fadeTo(250,0,function(){
  $(this).css({ 'display' : 'none' });
  $("#download").css({ 'display' : 'block' });
  $("#download").fadeTo(250,1);
  $("#urlinput").example(function() { return $(this).attr('title'); });
 });
 allowdownload = 1;
}

function showMakeProgress() {
 $("#makestopbutton").val('stop');
 $("#makeprogressbar").fadeTo(0,1);
 $("#makestatuslabel").html('Processing ' + (type == 'ringtone' ? 'audio' : 'video'));
 $("#makeform").fadeTo(250,0,function() {
  $(this).css({ 'display' : 'none' });
  $("#makeprogress").css({ 'display' : 'block' });
  $("#makeprogress").fadeTo(250,1);
 });
 $("#makestopbutton").blur();
}

function showMake() {
 $("#makeprogress").fadeTo(250,0,function(){
  $(this).css({ 'display' : 'none' });
  $("#makeform").css({ 'display' : 'block' });
  $("#makeform").fadeTo(250,1);
 });
 allowmake = 1;
 $("#makebutton").blur();
}

function disableMaker() {
 $("#maker :input, #maker :select").attr('disabled', true);
 $("#maker").fadeTo(0,0.4);
 $("#makefilename").val('');
 allowmake = 0;
}

function enableMaker() {
 $("#maker").fadeTo(250,1);
 $("#maker :input, #maker :select").removeAttr('disabled');
 $("#makefilename").val(type);
 allowmake = 1;
}

function doMake() {
 $("#makefolder").val(folder);
 $("#makefile").val(file);
 $("#makestart").val(scrollStart);
 $("#makestart2").val($f("huluPlayer").getTime());
 $("#makeend").val(scrollEnd);
 $("#makevideourl").val(videoURL);
 $('#makeform').ajaxSubmit({
  'dataType' : 'json',
  'success'  : function (data) {
                if (data.status == 'OK') {
                 pid = data.pid;
                 attempts = 20;
                 mjah();
                } else {
                 $("#makestatuslabel").html(data.details ? 'Error: ' + data.details : 'Error');
                 $("#makeprogressbar").fadeTo(0,0);
                 $("#makestopbutton").val('reset');
                }
               },
  'error'    : function () {
                $("#makestatuslabel").html('Error: Connection failed.');
                $("#makeprogressbar").fadeTo(0,0);
                $("#makestopbutton").val('reset');
               }
 });
}

function initConverter() {
 $("#bluebox, #urlinputwrapper, .buttonwrapper, .makebuttonwrapper").corner("5px");
 disableMaker();
 $("#urlinput").example(function() { return $(this).attr('title'); });
 $("#downloadbutton").bind("click",function() {
  if (allowdownload == 0) { return false; }
  if ($("#urlinput").val().indexOf('http') != 0) { return false; }
  allowdownload = 0;
  pid = 0;
  videoURL = $("#urlinput").val();
  showProgress();
  $("#folderinput").val(folder);
  $('#downloadform').ajaxSubmit({
   'dataType' : 'json',
   'success'  : function (data) {
                 if (data.status == 'OK') {
                  pid = data.pid;
                  folder = data.folder;
                  attempts = 20;
                  jah();
                 } else {
                  $("#statuslabel").html('Error');
                  $("#stopbutton").val('reset');
                 }
                },
   'error'    : function () {
                 $("#statuslabel").html('Error');
                 $("#stopbutton").val('reset');
                }
  });
  return false;
 });
 $("#makebutton").bind("click",function() {
  if (allowmake == 0) { return false; }
  allowmake = 0;
  pid = 0;
  setTimeout('$f("huluPlayer").getPlugin("myContent").hide()', 1500);
  pauseTo();
  showMakeProgress();
  setTimeout("doMake()",500);
  return false;
 });
 $("#stopbutton").bind("click",function (){
  var url = '/stopprocess.html?pid=' + pid + '&folder=' + folder + '&rnd=' + Math.random();
  auto = {}; videoURL = '';
  if (($("#stopbutton").val() == 'stop') || ($("#makestopbutton").val() == 'stop')) { $.get(url); }
  if (($("#makestopbutton").val() == 'stop') || ($("#makestopbutton").val() == 'reset')) showMake();
  if (($("#stopbutton").val() == 'reset') && (proceedRecipe == 1)) $(location).attr('href','http://' + host);
  showDownload();
  clearPlayer();
  $("#makefilename").val('');
  disableMaker();
  return false;
 });
 $("#progressbar").progressbar({ 'value' : 0 });
 $("#makestopbutton").bind("click",function (){
  var url = '/stopprocess.html?pid=' + pid + '&folder=' + folder + '&rnd=' + Math.random();
  if ($("#makestopbutton").val() == 'stop') { $.get(url); }
  showMake();
  return false;
 });
 if (auto.url) {
  if (auto.url.indexOf('http') == 0) {
   var rmessage = '<div style="font-size: 15px; font-family: Arial;"><h2>Welcome to online ' + type + ' maker!</h2><h3>You have come to this site by clicking a link to a ' + type + ' recipe!</h3> ' +
                  '<b>It means that someone chosen a youtube video, set start/end times to cut a ' + type + ' and shared the recipe with others.</b> ' +
                  '<p style="text-align: center;"><a style="font-size: 1.2em; font-weight: bold; color: #0000FF;" id="recipeproceed" href="#">OK, proceed with the recipe!</a>' +
                  ' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a style="font-size: 1.2em; font-weight: bold; color: #0000FF;" id="mainproceed" href="#">No, take me to the main page!</a></p>' +
                  'If you proceed with the recipe the ' + type + ' maker will download the video file and load it into the player/editor. ' +
                  'You can watch the process of downloading by a progress bar in "Step 1" section. It takes time.<br><br>' +
                  'Then after you play/edit and click "MAKE" the software will cut the proper piece from the clip, detach the audio track, ' +
                  'amplify its volume, apply short fade in/out effect' + (type == 'ringtone' ? '' : ', combine with video track') + ' and offer you to download the result.<br><br> ' +
                  'Please notice that downloading may not be successfull if the video is no longer available or there is any other youtube download problem.</b></div>';
   $("#recipemessage").html(rmessage);
   $("#recipetip").fancybox({
   		'width': 560,
   		'height': 390,
   		'autoDimensions': false,
   		'onClosed': function() { if (proceedRecipe == 0) setTimeout("$(location).attr('href','http://' + host)", 1000) },
   		'hideOnOverlayClick': false
   });
   setTimeout('$("#recipetip").trigger("click")',500);
   $("#recipeproceed").bind("click",function (){
	proceedRecipe = 1;
    $("#urlinput").val(auto.url);
    setTimeout('$("#downloadbutton").click()',1000);
    $.fancybox.close();
    return false;
   });
   $("#mainproceed").bind("click",function (){
	setTimeout("$(location).attr('href','http://' + host)", 1000);
    $.fancybox.close();
    return false;
   });
  }
 }
}

////////////////////////////////////////////

var delay;
var delay2;
var FullTime;
var RealTime;
var scrollStart;
var scrollEnd;
var playerLoaded = 0;
var infohtml1 = '<p class="info">Please WAIT<br>until the video is fully loaded.</p>';
var infohtml2 = '<p class="info">Now you need to drag the green markers to<br>the beginning and the end of your ' + type + '.</p>';
var infohtml3 = '<p class="info">The markers are set according to the recipe.<br>Please play/edit and click "MAKE".</p>';
var firstPlay = 1;

function showPlayer(base,file) {
	delay = null;
	delay2 = null;
	FullTime = 0;
	RealTime = 0;
	scrollStart = 0;
	scrollEnd = 0;
	
	if (playerLoaded == 0)
	{
		$f("huluPlayer", "/flash/flowplayer-3.1.5.swf", {
			clip: {
				autoPlay: false,
				autoBuffering: true,
				baseUrl: base,
				url: file
			},
			plugins: {
				controls: null,
				myContent: { 
					url: '/flash/flowplayer.content-3.1.0.swf', 
					bottom: 30, 
					width: 460,
					borderRadius: 5,
					style: { 
						'.info': { 
							fontFamily: 'Arial, Helvetica, Verdana',
							fontSize: 14, 
							fontWeight: 'bold',
							textAlign: 'center',
							letterSpacing: 1
						}
					},
					html: infohtml1,
			        onClick: function() { 
			            this.hide(); 
			        } 
				} 
			}
		})
		.controls(
			"hulu", {
			  template: '<a class="play">play</a>' +
						'<a class="stop">stop</a>' +
						'<div class="time"></div>' +
						'<a class="mute">mute</a>' +
						'<div class="demo">' +
						'<div id="slider-range"> </div>' +
						'<div class="track">' +
						'<div class="buffer"></div>' +
						'<div class="progress"></div>' +
						'<div class="playhead"><div class="playheadCursor"></div></div>' +
						'</div>' +
						'<div type="text" class="counterAmount" />' +
						'<span id="amount">00:00 - 00:00</span>' +
						'</div><div style="clear: both;"> </div>' +
						'</div>'
					}
		);
		playerLoaded = 1;
	}
	else {
		$f("huluPlayer").setClip({
			baseUrl: base,
			url: file
		});
	}
	$(".buffer").mousedown(pingSeekCursor);
	$(".buffer").mouseup(pingSeekCursor);
	$(".stop").click(pauseTo);
	$f("huluPlayer").startBuffering();
	$f("huluPlayer").setVolume('100');
	if ( $.browser.msie )
	{
		$(".play").mouseenter( function() { $(this).addClass('play_hover'); } );
		$(".play").mouseleave( function() { $(this).removeClass('play_hover'); } );
		$(".stop").mouseenter( function() { $(this).addClass('stop_hover'); } );
		$(".stop").mouseleave( function() { $(this).removeClass('stop_hover'); } );
	}
	setDefTimeLine();
	delay = setInterval("pingBuffer()", 1000);
	$(".playerClipContainer").css({ 'top' : '0', 'left' : '0' });
	$f("huluPlayer").getPlugin("myContent").setHtml(infohtml1);
	$f("huluPlayer").getPlugin("myContent").show();
}

function setDefTimeLine() {
	var range = $('<div id="def-range"></div>');
    var slider = $("#slider-range");
    $(slider).addClass("ui2-slider"
				+ " ui2-slider-horizontal"
				+ " ui2-widget"
				+ " ui2-widget-content"
				+ " ui2-corner-all");
	$(range)
		.appendTo(slider)
		.addClass("ui2-slider-range ui2-widget-header")
		.css({width:'100%'});
}

function pingBuffer() {
	if ( !$f("huluPlayer").isLoaded() ) return;
	var trackWide = $("#slider-range").width();
	var bufferWide = $(".buffer").width();
	if ( bufferWide < trackWide ) return;
	clearInterval(delay);
	delay = setInterval("setupTimeScroll()", 500);
}

function pad(val) {
	val = parseInt(val, 10);
	return val >= 10 ? val : "0" + val;
}

function toTime(sec) {
	var h = Math.floor(sec / 3600);
	var min = Math.floor(sec / 60);
	sec = sec - (min * 60);
	if (h >= 1) {
		min -= h * 60;
		return pad(h) + ":" + pad(min) + ":" + pad(sec);
	}
	return pad(min) + ":" + pad(sec);
}

function pingSeekCursor(e) {
	//ev = e ? e : window.event;
	//alert(ev.pageX+" - "+ev.target);
}

function clearPlayer() {
	if (playerLoaded == 0) return;
	$f("huluPlayer").stop();
	clearInterval(delay);
	clearInterval(delay2);
	delay=null;
	delay2=null;
	$(".playhead").css({left: 0});
	$("#amount").html('00:00 - 00:00');
	$("#slider-range").slider('destroy');
	$(".playerClipContainer").css({ 'top' : '-2000px', 'left' : '-2000px' });
}

function setupTimeScroll() {
	var todo;
	clearInterval(delay);
	FulTime = $f("huluPlayer").getClip().fullDuration;
	$("#slider-range").slider({
		range: true,
		min: 0,
		max: parseInt(FulTime),
		values: [0, parseInt(FulTime)],
		slide: function(event, ui) {
			scrollStart = parseInt(ui.values[0]);
			scrollEnd = parseInt(ui.values[1]);
			document.onmouseup = seekToStartPoint;
			$("#amount").html(toTime(ui.values[0]) + ' - ' + toTime(ui.values[1]));
			if ((allowmake == 0) || (firstPlay == 1)) {
				if (allowmake == 0) enableMaker();
				setTimeout('$f("huluPlayer").getPlugin("myContent").hide()', 1500);
				firstPlay = 0;
			}
			if ($("#makestopbutton").val() == 'reset') showMake();
		}
	});
	scrollEnd = $("#slider-range").slider("values", 1);
 	$("#amount").html(toTime(scrollStart) + ' - ' + toTime(scrollEnd));
	delay2 = setInterval("pingCurrTime()", 500);
	if (auto.begin && auto.end > 0) {
		scrollStart = auto.begin;
		scrollEnd = auto.end;
		$("#slider-range").slider("values", 0, scrollStart);
		$("#slider-range").slider("values", 1, scrollEnd);
		seekTo();
		enableMaker();
		if ($f("huluPlayer").getPlugin("myContent").getHtml() != infohtml3) setTimeout("changeInfo(infohtml3);", 1500);
		$("#amount").html(toTime(scrollStart) + ' - ' + toTime(scrollEnd));
	}
	else {
		if ($f("huluPlayer").getPlugin("myContent").getHtml() != infohtml2) setTimeout("changeInfo(infohtml2);", 1500);
	}
	$($("#slider-range a")[0]).show(250);
	$($("#slider-range a")[1]).show(250);
}

function changeInfo(str) {
	$f("huluPlayer").getPlugin("myContent").hide();
	$f("huluPlayer").getPlugin("myContent").setHtml(str);
	setTimeout('$f("huluPlayer").getPlugin("myContent").show()', 250);
}

function pingCurrTime() {
	realTime = $f("huluPlayer").getStatus().time;
	if (parseInt(realTime) >= parseInt(scrollEnd)) pauseTo();
	if (parseInt(realTime) < parseInt(scrollStart)) seekTo(); 
	if ((parseInt(realTime) > parseInt(scrollStart)) && (firstPlay == 1)) {
		if ($f("huluPlayer").getPlugin("myContent").getHtml() == infohtml3) setTimeout('$f("huluPlayer").getPlugin("myContent").hide()', 1500);
		firstPlay = 0;
	}
	$(".playhead").mousedown(
    	function() {
        	document.onmousemove = function() { return false; };
        	return false;
    	}
	);
	document.onmousemove = function() {return false;};
	$(".playhead").mouseup(function() {return false;});
	$(".playhead").click(function() {return false;});
}

function pauseTo() {
	$f("huluPlayer").pause();
	seekTo();
}

function seekTo() {
	var seekTo = $($("#slider-range a")[0]).css("left");
	$(".playhead").css({left: seekTo});
	$f("huluPlayer").seek(scrollStart);
}

function seekToStartPoint() {
	document.onmouseup = null;
	seekTo();
}
