$(document).ready(function() {
	bind_forms();
	bind_ajax();
	set_autos();
	
});

function bind_forms(){
	$(document).find("form:not(.noajax)").each(function(){
		$(this).bind("submit", send_form);
	});
}

function bind_ajax(){
	
	$(".ajax").each(function(){
		$(this).bind('click', call_ajax);
	});
	
	$(".click").each(function(){
		$(this).bind('click', call_ajax);
	});
	
	$(".change").each(function(){
		$(this).bind('change', call_ajax);
	});
}


$.fn.uploader = function(id, uploadurl, checkurl) {
	this.each(function() {
		this.uo = {};
		this.uo.writespan = $(this).find('span').get(0);
		this.uo.ele = $(this).get(0);
		
		this.uo.upload_done = function(obj){
			$('#name').attr('value', obj.name);
			$('#uuid').attr('value', obj.uuid);
			$('#size').attr('value', obj.size);
			$('#skey').attr('value', obj.uuid+"/"+obj.name);
			$('#original').attr('value', obj.name);
			$('form#uploadafile div.progressbar div.bar div').addClass('ind');
			$('form#uploadafile div.progressbar div.bar div').removeClass('progress');			
			$('#progresstext1').html('Verifying Your File. One Moment...');
		};
		this.uo.file_selected = function(obj){
			lastfileobject = obj;
			$(this.ele).find('input').attr('disabled', '');		
			$(this.writespan).html(obj.name);
			var c = gather(document.getElementById('uploadafile'));
			obj.ajax = true;
			obj.fid = c.fid;
			obj.forceversion = c.forceversion;
			obj.foid = c.foid;
			$.ajax({type:"post", url:'/admin/check/', data:obj, success:form_processed, dataType:'json'});
			//$('form#uploadafile').stir(obj, obj, '/admin/check', {no_indicator: true});
		};
		this.uo.transfer_done = function(obj){
			$('#name').attr('value', obj.name);
			$('#uuid').attr('value', obj.uuid);
			$('#size').attr('value', obj.size);
			$('#skey').attr('value', obj.uuid+"/"+obj.name);
			$('#original').attr('value', obj.name);
			var a = $('form#uploadafile').gather_send("/admin/upload");
		};
		this.uo.on_progress = function(obj){
			if (obj.bytes_down > 0) {
				if ($('form#uploadafile div.ind').size() > 0) $('form#uploadafile div.progressbar div.bar div').addClass('progress').removeClass('ind');
				$('form#uploadafile div.progress').css('width', Number((obj.bytes_down/obj.bytes_total)*100).toFixed(0)+"%");
				$('#progresstext1').html(this.format_bytes(obj.bytes_down)+ ' of '+this.format_bytes(obj.bytes_total)+' uploaded.');			
			}
		};
		this.uo.on_cancel = function(file_ref){
			$(this.ele).find('input').attr('disabled', '');
		};
		this.uo.on_upload = function() {
			$(this.ele).find('input').attr('disabled', 'DISABLED');
			$("#disp_filename").html("Uploading "+'"'+lastfileobject.name+'"');
		};
		this.uo.io_error = function() {
			alert('io error');
		};
		this.uo.http_error = function() {
			alert('http error');
		};
		this.uo.leopard_error = function(){
			alert('leopard error');
		}
		
		this.uo.security_error = function() {
			alert('security error');
		};
		
		this.uo.format_bytes = function(bytes)
		{
			if (bytes >= Math.pow(2, 40)) return Number(bytes/Math.pow(1024, 4)).toFixed(3)+' TB';
			else if (bytes >= Math.pow(2, 30)) return Number(bytes/Math.pow(1024, 3)).toFixed(2)+' GB';
			else if (bytes >= Math.pow(2, 20)) return Number(bytes/Math.pow(1024, 2)).toFixed(1)+' MB';
			else if (bytes >= Math.pow(2, 10)) return Number(bytes/Math.pow(1024, 1)).toFixed(0)+' KB';
			else return bytes + ' bytes';
		};
		$('body').append("<div class='putaway' id='uploader1'></div>");
		//upload_file, height, width, page_id, swf_id, swf_version, server, processor, callbacks
		a = new uploader('/swf/my_upload.swf', 1, 1, $('#uploader1').get(0), "swf_test", "8", uploadurl, checkurl, this.uo);
		this.au = a;		
		$(this).find('input').click(function() {
			$(this).attr('disabled', 'disabled');
			$(this).parent().get(0).au.browse();
		});		
	});
	return true;
};

function set_autos(){
	$(".autocomplete").each(function(){
		$(this).autocomplete("/providers/autocomplete/"+this.lang+"/", {autoFill:false, cacheLength:100, minChars:1, delay:100});
	});
}

function call_ajax(event){
	$('#activity').addClass('activity');
	var target = event ? event.target : this;
	if (target === undefined) target = event.srcElement;
	var action = target.href || target.lang || target.parentNode.href || target.parentNode.action || target.parentNode.lang;
	var method = $(target).attr("method") || 'POST';
	if (action == target.src) action = target.parentNode.href;
	var a = {};
	if (this.value) a[this.name] = this.value;
	a.ajax = true;
	$.ajax({type:method, url:action, data:a, success:form_processed, dataType:'json'});
	return false;
}

function send_form(event){
	var str = '';
	var target = event ? event.target : this;
	if (target === undefined) target = event.srcElement;
	$(target).gather_send(target.action);
	return false;
}

gather = function(el){
	var a = {};
	for(var i = 0; i < el.length; i++){
		var go = true;
		var item = el.elements[i];
		if (((item.parentNode.tagName == 'OPTGROUP') || (item.parentNode.type == 'select-one') || (item.parentNode.type == 'select-multiple')) && (!item.selected)) go = false;
		if (((item.type == 'radio') || (item.type == 'checkbox')) && (!item.checked)) go = false;
		if(go && item.name){
			a[item.name] = item.value;
		}
	}
	return a;
}

$.fn.gather_send = function(action){
	$('#activity').addClass('activity');
	this.each(function(){
		var a = {};
		for(var i = 0; i < this.length; i++){
			var go = true;
			var item = this.elements[i];
			if (((item.parentNode.tagName == 'OPTGROUP') || (item.parentNode.type == 'select-one') || (item.parentNode.type == 'select-multiple')) && (!item.selected)) go = false;
			if (((item.type == 'radio') || (item.type == 'checkbox')) && (!item.checked)) go = false;
			if(go && item.name){
				a[item.name] = item.value;
			}
		}
		$('.forminclude').each(function(){
			a[this.name] = this.value;
		});
		a.ajax = true;
		var method = $(this).attr("method") || 'POST';
		if (action == this.src) action = this.parentNode.href;
		$.ajax({type:method, url:action, data:a, success:form_processed, dataType:'json'});
	});
}

function form_processed(result){
	if(result.length){
		for(var i = 0; i < result.length; i++){
			process2(result[i]);
		}
	}else{
		process2(result);
	}
	$('#activity').removeClass('activity');
}

function process2(result){
	var e = result;
	if (e.div && e.action != 'call' && e.action != 'alert') var el = $('#'+e.div.toString()).get(0);
	switch(e.action) {
		case 'call':
			if(typeof e.string == 'object') {
				var callstr = false;
				for(var ai = 0; ai < e.string.length; ai++) {
					callstr = callstr ? callstr+', e.string['+ai+']' : 'e.string['+ai+']';
				}
			} else {
				var callstr = 'e.string';
			}
			eval(e.div+'('+callstr+');');
			break;
		case 'reload':
			window.location.reload();
			break;
		case 'location':
			document.location = e.string;
			break;
		case 'replace':
			if (el.tagName.toLowerCase() == 'div' && e.string) el.style.display = 'block';
			if (el.tagName.toLowerCase() == 'div' && !e.string) el.style.display = 'none';				
			$(el).html(e.string);
			break;
		case 'replace_outer':
			el.outerHTML = e.string;
			break;
		case 'append':
			$(el).after(e.string);
			break;
		case 'prepend':
			$(el).before(e.string);
			break;			
		case 'remove':		
			if ($(el).size() > 0) $(el).remove();
			break;
		case 'hide':
			$(el).hide();					
			break;
		case 'run':
			eval(e.string);
			break;
		case 'set_name':
			$(el).set('name', e.string);
			break;
		case 'concat':
			$(el).prepend(e.string);
			break;
		case 'concat_after':
			$(el).append(e.string);
			break;
		case 'alert':
			alert(e.string);
			break;
		case 'confirm':
			var agreed = confirm(e.string);
			if (agreed) { 
				var transaction = $('body').stir(e.div, e.div, e.div.callbackurl);
			}
			break;
		default:
			break;
	}
	if(e.callback_class && e.callback_method && e.callback_args){
		e.callback_args.uclass = e.callback_class;
		e.callback_args.umethod = e.callback_method;
		$.post('/'+e.callback_class+'/'+e.callback_method, 'POST',  $.json(e.callback_args), request);
	}
}

function set_radio_values(name, classer){
	$('.hidden_radio'+classer).each(function(){
		if(this.name == name){
			this.value = 1;
			alert('turned on: '+name+' :: '+this.name);
		}else{
			this.value = 2;
			//alert('turned off: '+name+' :: '+this.name);
		}
	});
}

function toggle_check_value(id){
	var chk = $('#'+id+'_hidden').val();
	if(chk == 2){
		$('#'+id+'_hidden').attr('value', '1');
	}else if(chk == 1){
		$('#'+id+'_hidden').attr('value', '2');
	}
}