(function(){

var s3 = window.S3Upload = {
	forms: {},
	files : {}
};

s3.populateForm = function(form, file, o){
	file = document.getElementById(file);
	form.setAttribute(document.all ? 'encoding' : 'enctype' , 'multipart/form-data');
	form.setAttribute('method', 'post');
	form.setAttribute('action', o.url);
//	form.setAttribute('action', "s3_callback_test2.php");

	var counter = 0;

	// add to formorm required formor AWS formorm elements
	append2Form = function(name, value){
		var input = document.createElement("INPUT");
		input.setAttribute("name", name);
		input.setAttribute("value", value || '');
		input.setAttribute("type", "hidden");
		input.setAttribute("id", "to_amazon_" + (++counter));
		file.parentNode.insertBefore(input, file);
		return input;
	}

	var mime = "text/plain";
	var ext = file.value.replace(/^(.+\.)([^\.]+)\s*$/, "$2");
	s3._mimeCodes.replace(new RegExp(ext + ":([^\,]+),", "i"), function(a, b){
		mime = b;
	})

	append2Form("AWSAccessKeyId", o.accessKey);
	append2Form("acl", o.acl);
	var k = append2Form("key", o.key).setAttribute("id", "aws_key_file");
	append2Form("policy", o.policy);
	append2Form("Content-Type", mime)
	append2Form("signature", o.signature);
	append2Form("success_action_redirect", o.successUrl || window.location.href.replace(/\/[^\/]+$/, "") + "/s3_callback.php");
	this.countFields = counter;
};

s3.doUpload = function(form, file_input, o){

	var form_id	= form.getAttribute("id");
	var o		= this.forms[form_id] = this.extend(o);
	o.form_id	= form_id;
	o.form		= form;
	var file	= document.getElementById(file_input);

	var v = file.value.replace(/^\s+|\s+$/g, '');
	v.replace(/[\\\\|\/]([^\\\\\/]+)$/, function(a,b){
		o.key = b;
	})

	if(o.onStart && o.onStart(o.key, v) === false) return false;

	o.file = v;
	s3.files[v] = {
		state: 1
	}
	o.state = 1;
	form.submit();
}

s3.removeAWSFields = function() {
	for(var i=1; i<=this.countFields; i++){
		var e = document.getElementById("to_amazon_" + i);
		if(e){
			e.parentNode.removeChild(e);
		}
	}
};

s3.attachAsync = function(form) {
	// create iframe.
	// append to body invisible div element
	var div = document.createElement("DIV");
	div.style.display = 'none';
	document.body.appendChild(div);

	var ifr = this.iframe = this.iframe(div);
	var n = window.frames[window.frames.length-1].name = "AWS_UPLD_" + form;

	// set iframe as target for the form
	form.setAttribute('target', n);
}

s3.onUpload = function(rsp){
	for(var i in this.forms){
		var o =  this.forms[i];
		if(rsp.key == o.key){
			o.onComplete && o.onComplete(rsp);
			this.files[o.file].state = 2; // done
			o.state = 2;
			return;
		}
	}
}

s3.extend = function(o2){
	var o = {};
	for(var i in o2){
		o[i] = o2[i];
	}
	return o;
}


s3.iframe = function(parent){
	var doc, i = document.createElement("iframe");
	parent.appendChild(i);

	if(i.contentDocument) doc = i.contentDocument;
	else if(i.contentWindow) doc = i.contentWindow.document;
	else if(i.document) doc = i.document;
	if(doc == null) throw "Unable to create iframe uploader";

	i.src = "javascript:;";
	doc.open();
	doc.close();
	return {iframe: i, doc: doc};
}

s3._mimeCodes =
	'mp2:audio/mpeg,'+
	'mp3:audio/mpeg,'+
	'mpga:audio/mpeg,'+
	'ram:audio/x-pn-realaudio,'+
	'rm:audio/x-pn-realaudio,'+
	'rpm:audio/x-pn-realaudio-plugin,'+
	'wav:audio/x-wav,'+
	'mpe:video/mpeg,'+
	'mpeg:video/mpeg,'+
	'mpg:video/mpeg,'+
	'mov:video/quicktime,'+
	'qt:video/quicktime,'+
	'rv:video/vnd.rn-realvideo,'+
	'asf:video/x-ms-asf,'+
	'asx:video/x-ms-asf,'+
	'avi:video/x-msvideo,'+
	'flv:video/x-flv,';

s3.post = function(url, post, onSuccess, onError){
	var req;
	if (window.XMLHttpRequest) req = new XMLHttpRequest();
	else if	(window.ActiveXObject)
	{
		req = new ActiveXObject("Msxml2.XMLHTTP");
		if (!req) req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	if(!req)
		throw "Unable to create ajax request object";

	var res = {};
	res.post = post;
	req.onreadystatechange = function() {
		if(req.readyState != 4) return;
		res.done = true;
		res.readyState = req.readyState;
		res.responseText = req.responseText;
		if (req.parseError && req.parseError.errorCode != 0) {
			res.errorMsg = req.parseError.reason;
			res.error = true;
		}
		res.success = true;
		if (req.status != 200 &&
			req.status != 206 &&
			req.status != 304) {
			res.success = false;
		}
	}

	req.open("POST", url, true);
	req.setRequestHeader('Accept', "*\/*");
	req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
	req.setRequestHeader('Connection', 'close');

	var sPost = '';
	for(var	i in post) sPost += "&" + i + "=" + encodeURI(post[i]);
	sPost = sPost.substring(1, sPost.length);

	var tm = setInterval(function(){
		if(res.done) {
			clearInterval(tm);
			res.success && onSuccess && onSuccess(res);
			res.error && onError && onError(res);
		}
	}, 10);
	req.send(sPost);
}


window.checkFileExte = function(e){
	var ef = /^(avi|mpeg|flv|mp4|flv|mpg|mpe|wmv|divx|mov|qt|mpv|wm|mp3)$/i;
	if(!ef.test( e.value.replace(/^(.+\.)([^\.]+)\s*$/, "$2"))) {
		alert("This file extension is not permitted for uploading");
		return false;
	}
	return true;
}

var savedForm = {};
var origFormAction;

var upload_options = {
	onStart: function(){
		document.getElementById("video_file").style.display = "none";
		document.getElementById("img_loading").style.display = "block";
		this.key = this.__key;
	},
	onComplete: function(){
		document.getElementById("img_loading").style.display = "none";

		for(var id in savedForm){
			document.getElementById(id).setAttribute("name", savedForm[id]);
		}
		var form = document.getElementById("triplayer");
		form.setAttribute('action', origFormAction);
		form.removeAttribute('target');

		// file already uploaded to amazon,
		// so just send to our submit.php script the original file name
		var file = document.getElementById("video_file");
		var filename = file.value;
		var parent = file.parentNode;
		parent.removeChild(file);
		var new_file = document.createElement("input");
		new_file.setAttribute("type", "hidden");
		new_file.setAttribute("name", "orig_video_file");
		new_file.value = filename;
		parent.appendChild(new_file);

		// do't send the content, that already sent to amazon
		s3.removeAWSFields(form);
		document.getElementById("aws_key_file").setAttribute("name", "aws_video_file");
		form.submit();
	}
}

window.init_my_upload = function(){
	var form = document.getElementById("triplayer");
	// create async upload form
	s3.attachAsync(form);

	form.onsubmit = function(){
		var form = this;

	// check a file extention
		if(!checkFileExte( document.getElementById("video_file"))){
			return false;
		}

	// save the form before submit.
	// remove all other fields excepts file, populate form with other fields needed by aws
	// and send form content to aws service

		// before sending we need to ask the our server for a new file name by file extention
		// to excepts the file name overlapping in aws bucket

		var ext = document.getElementById("video_file").value.replace(/^(.+\.)([^\.]+)\s*$/, "$2");
		var o = {
			ext: ext
		};

		var onResponse = function(rsp){
			var s3init;
				//cs(rsp) ; return;
			eval("s3init = " + rsp.responseText) ;
                	// save and clean the form
                	var e = form.elements;
                	for(var i=0; e[i]; i++){
                		if(!/^file$/i.test( e[i].getAttribute("type"))){
                			if(!e[i].getAttribute("id")){
                				e[i].setAttribute("id", "s3_upload_" + i );
                			}
                			savedForm[e[i].getAttribute("id")] = e[i].getAttribute("name");;
                			e[i].removeAttribute( "name" );
                		}
                	}

                        origFormAction = form.getAttribute('action');

                	s3.populateForm(form, "video_file", s3init);
                	upload_options.__key = s3init.key;
                	s3.doUpload(form, "video_file", upload_options);
		}

		s3.post("ajax_awsprops.php", o, onResponse);
		return false;
	}
}

})();

