/*  Media Converter - Wizard
 *  (c) 2009 Pascal Beyeler
 *--------------------------------------------------------------------------*/

/**
*
* view loader
*
**/

function wizardLoadView(view) {

	//get the content and display the window
	new Ajax.Request('/wizard/' + view + '/' + Math.random(), {
		method: 'get',
		contentType: 'text/html' ,
		onSuccess: function(transport) {

			setTimeout(function() {
				new Effect.Opacity($('wizard_content'), { from: 1, to: 0, duration: 0.1, afterFinish: function() {
					var content = transport.responseText;
					$('wizard_content').innerHTML = content;

					//show or hide the next step button
					if(queue && $('wizard_settings')) {
						if(queue.jobs.length > 0) {
							$('wizard_settings').show();
						} else {
							$('wizard_settings').hide();
						}
					}

					new Effect.Opacity($('wizard_content'), { from: 0, to: 1, duration: 0.1});

					//reloads the ad in the wizard
					if($('wizard_adiframe')) {
						$('wizard_adiframe').src = $('wizard_adiframe').src;
					}

					content.evalScripts();

				}});
			}.bind(this),0);

		}
	});

}



/**
*
* the queue manager class
*
**/

var queueManager = Class.create({

	initialize: function() {

		//if no ad is displayed the user is logged in
		this.loggedin = $('wizard_adiframe') ? false : true;
		this.jobs = new Array();
		this.settings = new Object();

		if(this.loggedin) {
			this.jobsleft = 5;
			$('wizard_conversionsleft').innerHTML = this.jobsleft;
			wizardLoadView('wizardhome');
		} else {
			this.jobsleft = 0;
			this.getJobsLeft();
		}

		//to avoid the cross-frame policy
		document.domain = 'mediaconverter.org';

	},

	getJobsLeft: function() {

		var postBody = escape('loggedin=' + this.loggedin);
		new f4a.Request('http://db.mediaconverter.org/wizard/jobsleft/' + Math.random(), {
			method: 'post',
			postBody: postBody,
			contentType: 'application/x-www-form-urlencoded',
			onSuccess : function(transport) {

				setTimeout(function() {
					var response = str2xml(transport);
					var root_node = response.getElementsByTagName('root')[0];
					var count = root_node.getElementsByTagName('count')[0].firstChild.nodeValue;

					$('wizard_conversionsleft').innerHTML = count;
					this.jobsleft = count;

					if(count == '0') {
						$('wizard_adiframe').src = 'about:blank';
						wizardLoadView('limitreached');

					} else {
						wizardLoadView('wizardhome');
					}
				}.bind(this),0);

			}.bind(this)
		});

	},

	add: function(type,id,source,server,redirect) {

		//decrease the conversion limit
		this.jobsleft -= 1;
		$('wizard_conversionsleft').innerHTML = queue.jobsleft;

		var postBody = 't=' + type + '&s=' + escape(source) + '&l=' + this.jobsleft;
		new Ajax.Request('/wizard/validateinput/' + Math.random(), {
			method: 'post',
			postBody: postBody,
			onSuccess: function(transport) {

				var response = transport.responseXML;
				var root_node = response.getElementsByTagName('root')[0];
				var status = root_node.getElementsByTagName("status")[0].firstChild.nodeValue;
				var message = root_node.getElementsByTagName("message")[0].firstChild.nodeValue;

				if(status == '0') {

					var isform = false;
					if(type == 'upload') {
						isform = true;
					}

					this.jobs.push(new queueObject(type,id,source,server,isform));

					//draw the list
					this.draw('init');
					if(redirect === 1) {
						wizardLoadView('wizardhome');
					}
				} else {
					//increase the conversion limit
					this.jobsleft += 1;
					$('wizard_conversionsleft').innerHTML = queue.jobsleft;
					$('wizard_error').innerHTML = message;
				}

			}.bind(this)
		});

	},

	remove: function(index) {

		//increase the conversion limit
		this.jobsleft += 1;
		$('wizard_conversionsleft').innerHTML = this.jobsleft;

		this.jobs.splice(index,1);

		//draw the list
		this.draw('init');

		//show the other icons again if the limit was reached before
		if(this.jobsleft > 0) {
			if($('wizard_enteralink')) {
				$('wizard_enteralink').show();
				$('wizard_uploadafile').show();
				$('wizard_browseyoutube').show();
			}
		}

	},

	reset: function(loggedin) {

		this.getJobsLeft();
		this.jobs = new Array();
		this.settings = new Object();
		this.draw('init');

	},

	draw: function(state) { /*state = init/locked/download*/

		//remove all entries
		var nofiles = $('wizard_nofiles').cloneNode(true);

		//show the no files message if the queue is empty
		if(this.jobs.length === 0){
			nofiles.show();
		}else{
			nofiles.hide();
		}

		//show or hide the next step button
		if($('wizard_settings')) {
			if(this.jobs.length > 0) {
				$('wizard_settings').show();
			} else {
				$('wizard_settings').hide();
			}
		}

		$('wizard_files').innerHTML = '';
		$('wizard_files').appendChild(nofiles);

		//print all jobs
		for(var i = 0; i < this.jobs.length; i++) {

			//create the main li element
			var newli = document.createElement('li');
			newli.setAttribute('id','job_' + i);
			newli.className = i%2 == 0 ? 'grey' : '';

			//print the source name
			var selectedfilesdiv = document.createElement('div');
			selectedfilesdiv.className = 'selectedfiles';
			selectedfilesdiv.innerHTML = this.jobs[i].source;

			//show the status
			var statusdiv = document.createElement('div');
			statusdiv.className = 'status';
			statusdiv.setAttribute('id','status_' + this.jobs[i].id);

			//show the actions
			var actiondiv = document.createElement('div');
			actiondiv.className = 'action';
			actiondiv.setAttribute('id','action_' + this.jobs[i].id);

			if(state == 'init') {

				//action
				var removelink = document.createElement('a');
				removelink.setAttribute('href','javascript:queue.remove(' + i + ');');
				removelink.innerHTML = translation.get('remove');
				actiondiv.appendChild(removelink);

				//status
				statusdiv.innerHTML = '-';

			} else if(state == 'locked') {

				//action
				actiondiv.innerHTML = '-';

				//status
				statusdiv.innerHTML = '-';

			} else if(state == 'running') {

				//action
				actiondiv.innerHTML = '-';

				//progress bar
				var progressbar = document.createElement('div');
				progressbar.className = 'progressbar';

				//download progress
				var downloadprogress = document.createElement('div');
				downloadprogress.className = 'download';

				//conversion progress
				var conversionprogress = document.createElement('div');
				conversionprogress.className = 'conversion';

				//clear div
				var cleardiv = document.createElement('div');
				cleardiv.className = 'clearboth';

				progressbar.appendChild(downloadprogress);
				progressbar.appendChild(conversionprogress);
				progressbar.appendChild(cleardiv);

				statusdiv.appendChild(progressbar);

			}

			//put them all together
			newli.appendChild(selectedfilesdiv);
			newli.appendChild(statusdiv);
			newli.appendChild(actiondiv);

			//append it to the list
			$('wizard_files').appendChild(newli);

		}

	},

	invoke: function() {

		//set the onclose event to make sure the user doesn't leave the website during the conversion
		window.onbeforeunload = function() {
				return translation.get('onclose');
		}

		for(var i = 0; i < this.jobs.length; i++) {
			var job = this.jobs[i];

			switch (job.type) {

				case 'link':
					var postBody = 's=' + escape(job.source) + '&id=' + escape(job.id) + '&jobid=' + i;
					new f4a.Request('http://' + this.jobs[i].server + '.mediaconverter.org/wizard/download/' + Math.random(), {
						method: 'post',
						postBody: postBody,
						contentType: 'application/x-www-form-urlencoded',
						onSuccess : function(transport) {

							var response = str2xml(transport);
							var root_node = response.getElementsByTagName('root')[0];
							var status = root_node.getElementsByTagName("status")[0].firstChild.nodeValue;
							var message = root_node.getElementsByTagName("message")[0].firstChild.nodeValue;
							var jobid = root_node.getElementsByTagName("jobid")[0].firstChild.nodeValue;
							var id = root_node.getElementsByTagName("id")[0].firstChild.nodeValue;

							if(status == '0') {
								this.jobs[jobid].title = message;
								this.jobs[jobid].interval = window.setInterval("queue.progress('download','" + id + "','" + jobid + "')",4000);
							} else {
								this.finalize(jobid,2,message);
							}

						}.bind(this)
					});

					break;

				case 'upload':

					if(document.all) {
						var iframe = document.createElement('<iframe style="display:none;" src="about:blank" name="hidden_iframe_' + job.id + '"></iframe>');
					} else {
						var iframe = document.createElement('iframe');
						iframe.setStyle({ display: 'none' });
						iframe.setAttribute('src','about:blank');
						iframe.setAttribute('name','hidden_iframe_' + job.id);
					}

					document.body.appendChild(iframe);

					var jobidfield = document.createElement('input');
					jobidfield.setAttribute('name','jobid');
					jobidfield.setAttribute('value',i);
					jobidfield.setAttribute('type','hidden');
					this.jobs[i].formnode.appendChild(jobidfield);

					if(document.body.appendChild(queue.jobs[i].formnode)) {

						$('upload_' + job.id).submit();

						this.jobs[i].interval = window.setInterval("queue.progress('upload','" + job.id + "','" + i + "')",4000);

					}
					break;

			}

		}

	},

	formComplete: function(status,message,jobid,id) {

		//stop the progress interval
		window.clearInterval(this.jobs[jobid].interval);

		if(status == '0') {
			this.showProgress('download',id,100);
			this.jobs[jobid].title = message;

			//start the conversion
			this.convert(jobid);
		} else {
			if(status == '1') {
				message = translation.get('failed');
			} else if(status == '2') {
				message = translation.get('toolarge');
			}
			this.finalize(jobid,2,message);
		}

	},

	progress: function(type,id,jobid) {

		var status = '';

		new f4a.Request('http://' + this.jobs[jobid].server + '.mediaconverter.org/progress/' + type + '/' + id + '/' + Math.random(), {
			method: 'get',
			onSuccess : function(transport) {
				setTimeout(function() {

					var response = str2xml(transport);
					var root_node = response.getElementsByTagName('root')[0];
					var status = root_node.getElementsByTagName("status")[0].firstChild.nodeValue;
					var percentage = root_node.getElementsByTagName("percentage")[0].firstChild.nodeValue;

					if(status == '0' || status == '1' || status == '2') {
						window.clearInterval(queue.jobs[jobid].interval);

						if(status == '0') {
							percentage = 100;

							if(type == 'download') {
								//start the conversion
								this.convert(jobid);
							}else if(type == 'conversion') {
								//create the download link
								this.finalize(jobid,1,translation.get('done'));
								return;
							}

						} else if(status == '2') {
							this.finalize(jobid,2,translation.get('toolarge'));
							return;
						} else {
							this.finalize(jobid,2,translation.get('failed'));
							return;
						}
					}
					this.showProgress(type,id,percentage);
				}.bind(this),0);
			}.bind(this)
		});

	},

	showProgress: function(type,id,percentage) {

		var bar = $('status_' + id).select('div');
		var nr = type == 'download' ? 1 : 2;
		var startfrom = bar[nr].getWidth() * 2;
		new Effect.Scale(bar[nr],percentage,{
				scaleX: true,
				scaleY: false,
				scaleMode: {originalWidth: 50},
				scaleFrom: startfrom,
				duration: 0.5
			}
		);

	},


	convert: function(jobid) {

		var postBody = '';

		//put all settings together
		for(var index in this.settings) {
			var value = this.settings[index];
			postBody += index + '=' + escape(value) + '&';
		};

		//ids
		postBody += 'id=' + escape(this.jobs[jobid].id) + '&jobid=' + escape(jobid);

		new f4a.Request('http://' + this.jobs[jobid].server + '.mediaconverter.org/wizard/convert/' + Math.random(), {
			method: 'post',
			postBody: postBody,
			contentType: 'application/x-www-form-urlencoded',
			onSuccess : function(transport) {

				setTimeout(function() {

					var response = str2xml(transport);
					var root_node = response.getElementsByTagName('root')[0];
					var status = root_node.getElementsByTagName("status")[0].firstChild.nodeValue;
					var message = root_node.getElementsByTagName("message")[0].firstChild.nodeValue;
					var jobid = root_node.getElementsByTagName("jobid")[0].firstChild.nodeValue;
					var id = root_node.getElementsByTagName("id")[0].firstChild.nodeValue;

					if(status == '0') {
						this.jobs[jobid].interval = window.setInterval("queue.progress('conversion','" + id + "','" + jobid + "')",4000);
					} else {
						this.finalize(jobid,2,message);
					}

				}.bind(this),0);

			}.bind(this)
		});

	},

	start: function() {

		this.draw('running');
		this.invoke();
		wizardLoadView('started');

	},

	finalize: function(jobid,status,message) {

		//the conversion finished successfully
		if(status === 1) {
			$('status_'+this.jobs[jobid].id).innerHTML = message;
			$('action_'+this.jobs[jobid].id).innerHTML = '<a href="http://' + this.jobs[jobid].server + '.mediaconverter.org/download/file/' + this.jobs[jobid].id + '/' + this.jobs[jobid].title + '.' + this.settings['output'] + '" target="_blank">' + translation.get('download') + '</a>';
			Event.observe($('action_'+this.jobs[jobid].id),'click',function() {this.innerHTML = '-'});

			this.jobs[jobid].status = 1;

			//save the file to the user profile if the user is logged in
			if(this.loggedin) {

				//send a request to the conversion server to store the file to the premium storage
				console.debug('http://' + this.jobs[jobid].server + '.mediaconverter.org/wizard/addtostorage/' + this.jobs[jobid].id + '/' + Math.random());
				new f4a.Request('http://' + this.jobs[jobid].server + '.mediaconverter.org/wizard/addtostorage/' + this.jobs[jobid].id + '/' + Math.random(), {
					method: 'get',
					contentType: 'text/xml',
					onSuccess : function(transport) {
					}
				});


				//send a request to the main server to add the file to the account
				var postBody = 'id=' + this.jobs[jobid].id + '&server=' + this.jobs[jobid].server + '&newname=' + escape(this.jobs[jobid].title + '.' + this.settings['output']);
				new Ajax.Request('/wizard/addtoprofile/' + Math.random(), {
					method: 'post',
					postBody: postBody,
					contentType: 'application/x-www-form-urlencoded' ,
					onSuccess: function(transport) {
						setTimeout(function() {

							//reload the sidebar
							new Ajax.Request('/sidebar/index/' + Math.random(), {
								method: 'get',
								contentType: 'text/html' ,
								onSuccess: function(transport) {
									setTimeout(function() {
										$('sidebar').update(transport.responseText);
									}.bind(this),0);
								}
							});

						}.bind(this),0);

					}
				});


			}

		//the conversion failed
		} else if (status === 2) {
			$('status_' + this.jobs[jobid].id).innerHTML = message;
			this.jobs[jobid].status = 2;
		}

		//loop through the jobs to see if there are still some running
		var done = true;
		var failed = false;
		this.jobs.each(function(job) {

			if(done && job.status === 0) {
				done = false;
			}
			if(job.status === 2) {
				failed = true;
			}

		});

		//all conversions have finished
		if(done) {

			//remove the onbeforeunload event
			window.onbeforeunload = null;

			if(failed) {
				wizardLoadView('finished/failed');
			} else {
				wizardLoadView('finished');
			}

		}

	}

});

var queueObject = Class.create({

	initialize: function(type,id,source,server,isform) {

		this.type = type; //link or upload
		this.source = source; //url or file name
		this.id = id;
		this.status = 0; //0 = ready; 1 = done; 2 = failed
		this.interval = false;
		this.title = false;
		this.server = server;

		if(isform) {
			this.formnode = $('upload_' + this.id).remove();
			this.formnode.setStyle({ display: 'none' });
		}

	}

});



/**
*
* youtube browser
*
**/


function browseYoutube(term,page) {

	$('browseyoutube_content').innerHTML = '';
	var newimg = document.createElement('img');
	newimg.setAttribute('src','/assets/public/images/ajax-loader.gif');
	$('browseyoutube_content').appendChild(newimg);
	var postBody = 'q=' + escape(term) + '&p=' + page;

	if($('browseyoutube_showthumbnails').checked) {
		postBody += '&t=true';
		Cookie.set('browseyoutube_showthumbnails','true',604800);
	} else {
		postBody += '&t=false';
		Cookie.set('browseyoutube_showthumbnails','false',604800);
	}

	new Ajax.Request('/wizard/youtuberesults/' + Math.random(), {
		method: 'post',
		postBody: postBody,
		contentType: 'application/x-www-form-urlencoded' ,
		onSuccess: function(transport) {

			new Effect.Opacity($('browseyoutube_content'), { from: 1, to: 0, duration: 0.1, afterFinish: function() { $('browseyoutube_content').innerHTML = transport.responseText; new Effect.Opacity($('browseyoutube_content'), { from: 0, to: 1, duration: 0.1});}});

		}
	});

}

function addYoutubeVideo(id,source,server) {

	if(queue.jobsleft > 0) {
		queue.add('link',id,source,server,0);
		$('browseyoutube_result' + id).innerHTML = '<b>' + translation.get('added') + '</b>';
	} else {
		alert(translation.get('limit_reached'));
	}

}

/**
*
* settings
*
**/

function setOutputFormat(format,advanced) {

	if(format != '') {
		//push the format to the settings array
		queue.settings['output'] = format;

		//remember the choice
		Cookie.set('wizard_filetype',format,604800);

		//redirect
		if(!advanced) {
			Cookie.unset('wizard_advanced');
			wizardLoadView('summary');
		} else {
			//remember the choice
			Cookie.set('wizard_advanced','true',604800);
			wizardLoadView('advancedsettings/' + format);
		}
	}

}

function setAdvancedOptions() {

	//audio codec
	if($('wizard_audiocodec').value != '') {
		//remember the choice
		Cookie.set('wizard_audiocodec',$('wizard_audiocodec').value,604800);
		queue.settings['acodec'] = $('wizard_audiocodec').value;
	} else {
		Cookie.unset('wizard_audiocodec');
		delete(queue.settings['acodec']);
	}

	//audio bitrate
	if($('wizard_audiobitrate').value != '') {
		//remember the choice
		Cookie.set('wizard_audiobitrate',$('wizard_audiobitrate').value,604800);
		queue.settings['ab'] = $('wizard_audiobitrate').value;
	} else {
		Cookie.unset('wizard_audiobitrate');
		delete(queue.settings['ab']);
	}

	//video codec
	if($('wizard_videocodec')) {
		if($('wizard_videocodec').value != '') {
			//remember the choice
			Cookie.set('wizard_videocodec',$('wizard_videocodec').value,604800);
			queue.settings['vcodec'] = $('wizard_videocodec').value;
		} else {
			Cookie.unset('wizard_videocodec');
			delete(queue.settings['vcodec']);
		}
	}

	//video bitrate
	if($('wizard_videobitrate')) {
		if($('wizard_videobitrate').value != '') {
			//remember the choice
			Cookie.set('wizard_videobitrate',$('wizard_videobitrate').value,604800);
			queue.settings['b'] = $('wizard_videobitrate').value;
		} else {
			Cookie.unset('wizard_videobitrate');
			delete(queue.settings['b']);
		}
	}

	//offset
	if($('wizard_offset').value != '') {
		//remember the choice
		Cookie.set('wizard_offset',$('wizard_offset').value,604800);
		queue.settings['ss'] = $('wizard_offset').value;
	} else {
		Cookie.unset('wizard_offset');
		delete(queue.settings['ss']);
	}

	//duration
	if($('wizard_duration').value != '') {
		//remember the choice
		Cookie.set('wizard_duration',$('wizard_duration').value,604800);
		queue.settings['t'] = $('wizard_duration').value;
	} else {
		Cookie.unset('wizard_duration');
		delete(queue.settings['t']);
	}

	//resolution
	if($('wizard_resolution')) {
		if($('wizard_resolution').value != '') {
			//remember the choice
			Cookie.set('wizard_resolution',$('wizard_resolution').value,604800);
			queue.settings['s'] = $('wizard_resolution').value;
		} else {
			Cookie.unset('wizard_resolution');
			delete(queue.settings['s']);
		}
	}

	//show the next step
	wizardLoadView('summary');

}

/**
*
* helper functions
*
**/

function str2xml(str) {

	// IE
	if(document.all) {
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
		xmlDoc.loadXML(str);

	// other browsers
	} else {
		parser=new DOMParser();
		xmlDoc=parser.parseFromString(str,"text/xml");
	}

	return xmlDoc;

}
