var ie=/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
var opera=/opera/i.test(navigator.userAgent);
$(document).ready(function() {
	oldshare='';
	fidcount=0;
	fCount=0;
	gCount=0;
	frand=0;
	content_height=0;
	failCount=0;
	failPerc=0;
	slide_fname=true;
	num_requests=0;
	error_count=0;
	fProgCount=0;
	change_event($(".add_file"));
	if (ie==true || opera==true) { 
		$(".add_file").css("opacity",1);
		$("#b_left").hide();
	}
	$(".fname").each(function() { $(this).text(shorten_fname($(this).text(), 18)); });
	zebra();
	update_total();
	if (typeof selected_id != 'undefined') {
		if (selected_id==-1) {
			$(".add_file").hide();
			if (logged_in==true) {
				$("#b_right").hide();
				$("#b_left").click(function() {
					$("#p_no").slideUp("medium", function() {
						$("#content_main").slideDown();
						$(".add_file").show();	
						$("#b_right").show();
						if (ie==true || opera==true) { $("#b_left").hide() }
						$("#b_left").unbind("click").text("Choose File To Upload");
					});
				}).html("&laquo; Go Back To All Files");
			} else {
				$("#b_left").html("Check Out The Site").attr("href","/");
				$("#b_right").text("Register an Account").unbind("click").attr("href","/free");
			}	
			$("#p_no_name").text(f_name);
			$("#p_no").slideDown();
		} else {
			if (selected_type=="f") {
				preview_f(selected_id);
			}
			
			if (selected_type=="g") {
				preview_g(selected_id);
			}
		}
	} else {
		selected_id=0;
		if (hash=window.location.hash.substr(1)) {
			$.get("ajax.php",{action:"url_to_id", url:hash},function(r) {
				preview_f(r);
				selected_id=r;
			});
		} else {
			if (logged_in==false) { window.location="/"; }
			$("#content_main").slideDown("slow");
			selected_id=0;
		}
	}
	
	g_drop_options={ 		
		accept: '.fmain', 
		over: function(ev, ui) {
			$(this).stop().fadeTo("fast",1);
		},
		out: function(ev, ui) {
			$(this).stop().fadeTo("fast",.4);
		},
		drop: function(ev, ui) {
			var drop_ui = $(this);
			if (ui.draggable.parent().data("pg")==drop_ui.data("id")) {
				$(".g").each(function() { $(this).fadeTo("slow",1); });
				slide_fname=true;
				return false;			
			}						
			var target = $(this).find(".gc");
			var pg=ui.draggable.parent().data("pg");
			if ($("#group" + pg).find(".f").length==0) {
				$("#group"+ pg).find(".g_default").slideDown();
			} else {
				$("#group"+ pg).find(".g_default").slideUp();
			}
			$.get("ajax.php",{ action:"change_group", gid: drop_ui.data('id'), fid:ui.draggable.find(".fname").data('id') }, function() {	
				ui.draggable.parent().appendTo(target).data('pg',drop_ui.data('id'));
				zebra();
			});
			$(".g").each(function() { $(this).fadeTo("slow",1); });
			slide_fname=true;
		}
	}
	
	f_drag_options = {
		helper: 'clone', opacity: .7, axis:'y',
		start: function() {
			slide_fname=false; 
			$(".g").each(function() { $(this).fadeTo("fast",.4); });
		},
		stop: function() {
			$(".g").each(function() { $(this).fadeTo("slow",1); });
			zebra();
		}
	}
	$(".add_file").hover(function() {
		$("#b_left").css("background-position","center left");
	}, function() {
		$("#b_left").css("background-position","top left");
	});		
	$(".temp_fdelete").live("click", function() {
		failPerc=0;
		failCount=0;
		fProgCount=0;
		if (fCount>1) {
			$("#content_main").animate({ paddingTop:"-=25px" }, 500);
		} else {
			$("#temp_files").animate({ top:"-40px" }, 500);
			$("#content_main").animate({ paddingTop:"0px" }, 500);
		}
		var myf=$(this).parent().parent().parent();
		var realid=myf.attr("realid");
		myf.fadeOut("fast",function() { $(this).remove(); });
		$("input[realid=" + realid + "]").remove();
		zebra();	
		fCount--;
		notify("File Deleted");
	});
	$(".g").each(function() {
		g=$(this);
		g.data("id",g.attr("id").substr(5)).find(".f").data("pg",g.data("id")); 
		g.droppable(g_drop_options);
	});	
	$("#content_main .f").each(function() {
		fid=$(this).attr("id").substr(4)
		$(this).data("id",fid).draggable(f_drag_options).find(".fname").data("id",fid);
	});
	
	$("#content_main .f, #preview_g_files .f").live("mouseover",function() { if (slide_fname==true) { $(this).addClass("fon").find(".fname").stop().animate({ paddingLeft:"6px" }, 60); } })
	.live("mouseout",function() { if (slide_fname==true) { $(this).removeClass("fon").find(".fname").stop().animate({ paddingLeft:"0px" }, 60); } })
	
	$(".fmain").live("click",function() {
		fid=selected_id=$(this).parent().data("id");
		preview_f(selected_id);
		window.location.hash='#' + $(this).parent().attr("url");
	}).draggable(f_drag_options);
	
	$("#p_download").live("click",function() { download(selected_id); });
	$(".fdelete").live("click",function() {	
		f=$(this);
		$.get("ajax.php",{action:"delete_file",id:$(this).parent().parent().data("id")},function(r) {		
			$(f).parent().parent().fadeOut("fast",function() { $(this).remove(); zebra(); notify("File Deleted"); update_total(); });
		});
		return false;
	});
	
	$(".gdelete").live("click",function() {	
		var g=$(this).parent().parent().parent();
		if (g.find(".f").length) {
			gname = g.find(".gname").text();
			fnum = g.find(".f").length;
			if (confirm("Warning: this group has " + fnum + " file(s) that will be deleted, are you sure you want to continue?")==true) {
				group_delete(g.data("id"), false);
				update_total();
			}
		} else {
			group_delete(g.data("id"), false);
		}	
		return false;
	});
		$(".gmenu").live("click",function() {
			g=$(this).parent().parent().parent();
			selected_id=g.data("id");
			preview_g(selected_id);
		});

		$("#warning_save").click(function() {
			group_delete($("#warning_selected").text(), true);
			$("#group" + $("#warning_selected").text()).find(".gc").appendTo($("#group0").find(".gc"));
			$("#gd_warning").animate({ top:"-250px" });
		});

		$("#warning_delete").click(function() {
			group_delete($("#warning_selected").text(), false);
			$("#gd_warning").animate({ top:"-250px" });
		});
		
		$("#warning_cancel").click(function() {
			$("#gd_warning").animate({ top:"-250px" });
		});

	$(".gview").live("click",function() {
		var g=$(this).parent().parent().parent();
		if ($(this).data("full")==0) {
			$(this).find("img").attr("src","imgs/g_t_i_min.png");			
			$(g).find(".gc").slideDown("fast");
			$(this).data("full",1);
		} else {
			$(this).find("img").attr("src","imgs/g_t_i_max.png");
			$(g).find(".gc").slideUp("fast");
			$(this).data("full",0);
		}
		return false;
	});
	
	$(".grename").live("keypress",function (e) { if (e.which==13) { save_g_rename($(this)); notify("Group Renamed"); return false; }});
	
	$("#rename_link, #rename_link_g").click(function() {
		if ($(this).attr("alt")!="clicked") {
			$(this).attr("alt","clicked").val("").css("color","#3E4148");
		}
	}).blur(function() {
		rename_link($(this));
	}).live("keypress",function (e) { 
		if (e.which==13) {
			rename_link($(this));
		}
	});

	$("#content_main .gname").live("click",function() {
		gname_clicked($(this));
		return false;
	});
	$(".gsearch").live("click",function() { $(this).val(''); }).live("keyup",function() {
		var search_val=$(this).val();
		$(this).parent().parent().parent().parent().find(".gc").find(".f").each(function() {
			$(this).show();
			if ($(this).find(".fname").text().indexOf(search_val)==-1) {
				$(this).hide();
			}
		});
		zebra();
		return false;
	});

	$("#b_right").click(function() {
		default_gname="Click to rename";
		$.get("ajax.php",{ action:"new_group",gname:default_gname }, function(data) {
			var rt= eval('(' + data + ')');	
			var g = $(document.createElement("div"));
			g.data("id",rt['id']).attr("id","group"+rt['id']).addClass("g").append($("#g_model").html()).find('.gname').text(default_gname).end()
			.find(".gmenu").attr("href","#" + rt['url']).end().droppable(g_drop_options).appendTo("#content_main").hide().slideDown("fast").find(".g_default").slideDown().end();
			gCount++;
			notify("Group Created");
		}); 
	}); 		
	$("#share_link, #share_link_g").live("click", function() {
		$(this).select();
	});
});

function save_g_rename(t) {
	var gnameold=t.hide().parent().find(".gname");
	if (t.val()=="") {
		t.hide();	
		gnameold.show();
		return false;
	}
	gnameold.text("loading...").show();
	$.get("ajax.php",{ action: "rename_group",gid:$(t).parent().parent().data("id"),gname:t.val() },function(data) {
		gnameold.text(t.val());
	});
}

function download(fid) {
	$("#ajax_frame").attr("src", "ajax.php?action=download_file&id=" + fid);
}

function download_group(gid) {
	$("#ajax_frame").attr("src", "ajax.php?action=download_group&id=" + gid);
}

function preview_f(fid) {	
	selected_type="f";
	$(".add_file").hide();
	$("#b_left").show();
	if (logged_in==true) {
		$("#b_right").hide();
		$("#b_left").click(function() {
			$("#p_file").slideUp("medium", function() {
				$("#content_main").slideDown();
				$(".add_file").show();	
				$("#b_right").show();
				$("#p_size, #p_type, #p_user, #p_date").text("loading..");
				$("#share_link").val("loading url..");
				$("#rename_link").val("Click to change link...").attr("alt",'');
				$("#p_box").html('<img id="prev_load" src="imgs/prev_load.gif"/>');
				if (ie==true || opera==true) { $("#b_left").hide() }
				$("#b_left").unbind("click").text("Choose File To Upload");
			});
		}).html("&laquo; Go Back To All Files");
	} else {
		$("#b_left").html("Check Out The Site").attr("href","/");
		$("#b_right").text("Register an Account").unbind("click").attr("href","/free");
	}
	if ($('#content_main').is(':visible')) {
		$("#content_main").slideUp("slow", function() {
			$("#p_file").slideDown("slow");
		});
	} else {
		$("#p_file").slideDown("slow");
	} 		
	
	$.get("ajax.php",{action:"finfo", id:fid }, function(r) {
		r=eval("(" + r + ")");
		$(".p_fname").text(shorten_fname(r['name'],18));
		$("#p_user").text(r['user']);
		$("#p_date").text(r['date']);
		$("#p_size").text(r['size']);
		$("#p_type").text(r['type']);
		if (typeof uname != 'undefined') {
			if (r['user'].toLowerCase()==uname.toLowerCase()) {
				$("#rename_area").slideDown();
				$("#rename_link").val(r['url']);
			} else {
				$("#rename_area").slideUp();
			}
		} else {
			$("#rename_area").slideUp();
		}
		$("#share_link").val('http://uploadrobots.com/' + r['url']);
		preview_box(r);		
	});	
	
}

function preview_g(gid) {
	selected_type="g";
	$(".add_file").hide();
	$("#b_left").show();
	if (logged_in==true) {
		$("#b_right").hide();
		$("#b_left").click(function() {
			$("#p_group").slideUp("medium", function() {
				$("#content_main").slideDown();
				$(".add_file").show();	
				$("#b_right").show();
			});
			$("#b_left").unbind("click").text("Choose File To Upload");
		}).html("&laquo; Go Back To All Files");
	} else {
		$("#b_left").html("Check Out The Site").attr("href","/");
		$("#b_right").text("Register an Account").unbind("click").attr("href","/free");
	}
	if ($('#content_main').is(':visible') ) {
        $("#content_main").slideUp("slow", function() {	
			$("#p_group").slideDown("slow");
		});
	} else {
		$("#p_group").slideDown("slow");
	} 		
	
	$.get("ajax.php",{action:"ginfo", id:gid }, function(r) {
		r=eval("(" + r + ")");
		l=r['files'].length;
		add_html="";
		$("#gname_g").text(r['name']);
		is_alt=false
		for (i=0;i<l;i++) {
			f=r['files'][i];
			if (is_alt==false) { is_alt=true; add_html+='<div class="f falt" alt="' + f['id'] + '">'; } else { is_alt=false;  add_html+='<div class="f" alt="' + f['id'] + '">';} 
			add_html+='<div class="fleft"><span class="fname">' + shorten_fname(f['name'],17) + '</span></div>';
			add_html+='<div class="fm"><span class="fsize">' + f['size'] + '</span></div>';
			add_html+='<div class="clear"></div></div>';
		}
		$("#p_group .gc:first").hide().html(add_html).slideDown().find(".f").click(function() {
			download($(this).attr("alt"));
		});
		$("#p_download_g").unbind().click(function() {
			download_group(selected_id);
		});
		if (typeof uname != 'undefined') { 
			if (r['uname'].toLowerCase()==uname.toLowerCase()) {
				$("#rename_area_g").slideDown();
				$("#rename_link_g").val(r['url']);
			} else {
				$("#rename_area_g").slideUp();
			}
		} else {
			$("#rename_area_g").slideUp();
		} 
		$("#share_link_g").val('http://uploadrobots.com/' + r['url'])	
	});	
	
}

function zebra() {
	$(".f").removeClass("falt");
	$(".f:even").addClass("falt");
	$(".ftemp").removeClass("ftemp_z");
	$(".ftemp:even").addClass("ftemp_z");
	$(".g").each(function() {
		if ($(this).find(".f").length==0) {
			$(this).find(".g_default").slideDown();
		} else {
			$(this).find(".g_default").slideUp();
		}
	});
}

function shorten_fname(str, len) {
	if (str.length>len) {
		var splits=str.split(".");
		return splits[0].substr(0,len) + "..";
	}
	return str;
}

function gname_clicked(g) { 
	if (g.parent().parent().attr("id")=="group0") { return false; }
	g.hide().parent().find(".grename").show().val(g.text()).focus().select().blur(function() {
		save_g_rename($(this));
		$(this).unbind("blur");
	});
}

function next_queue() {
	frand=rand();		
	document.upload_form.action = "../cgi-bin/upload.cgi?sid=" + frand + "&r=" + tmp_r;		
	i=0;
	$("#upload_form").submit();
	return frand;
}

function group_delete(gid, save_files) {
	$.get("ajax.php",{ action:"delete_group", id:gid, save:save_files },function() {
		$("#group" + gid).slideUp("fast", function() { $(this).remove(); notify("Group Removed"); });
	});	
}

function update_total() {
	$.get("ajax.php",{ action:"get_total_size" },function(data) {
		r=eval('(' + data + ')');
		perc=r['percent'];
		size=r['size'];
		$("#total_size").text(size + " of storage used. (" + perc + "%)"); 
	});
}

function change_event(add_file) {
	$(add_file).change(function() {
		fidcount++;
		$(this).unbind().hide();
		var u=$(document.createElement("input"));
		u.attr("type","file").attr("name","file").addClass("add_file").appendTo("#upload_form").attr("realid",fidcount+1);
		change_event(u);
		if (ie==true|| opera==true) { u.css("opacity",1); }
		var temp_f = $(document.createElement("div"));
		temp_f.addClass('ftemp').append($("#temp_f_model").html()).attr("realid",fidcount)
		.find('.temp_fname').text(add_file.val()).end()
		.find('.progress_inner').data('percent',0).end().fadeTo("fast", .5).appendTo($("#temp_inner"));
		zebra();
		if (++fCount==1) {
			$("#temp_files").animate({ top:"0px" }, 500);
			$("#content_main").animate({ paddingTop:"35px" }, 500);
			upload_progress();
		} else {
			$("#content_main").animate({ paddingTop:"+=25px" }, 500);
		}
	});
}

function upload_progress() {
	dont_recall=false;
	is_big=false;
	if ($("#temp_files .progress_inner").length<1) { return false; }
	temp=$("#temp_files .progress_inner:first");			
	if (temp.data("sid")==undefined) {
		temp.data("sid",next_queue());
	}	
	temp.parent().parent().parent().fadeTo("medium",1);
	sid=temp.data("sid");
	$.get("ajax.php",{"action":"get_progress", "sid":sid, "noinclude":true },function(data) {
		if (fProgCount++>8) {
			is_big=true;
		}
		perc=eval('(' + data + ')');
		if (failCount>25 || perc[0]<failPerc) {
			file_error('Your connection was interrupted, uploading process cannot continue.');
			failCount=0;
			failPerc=0;
			return;
		}
		if (perc[0]==failPerc) {
			failCount++;
		} else {
			failCount=0;
			failPerc=perc[0];
		}
		i=0;
		if (perc['error']==1) {
			if (tmp_r==0) {	
				file_error('Maximum upload size is 10mb. <a href="proregister.html" class="upgrade1">Upgrade To Pro Today</a>');
			} else {
				file_error('Too Large. Maximum upload size is 250mb.');
			}
			return;
		}
		if (ie==false) { $("title").html(perc[0] + "% complete | " + $(".ftemp:first").find(".temp_fname").text()); }
		temp.data('percent',parseInt(perc[0])).animate({ width:temp.data('percent')+'%' },1000);
		if (parseInt(temp.data('percent'))>=100) {	
			failPerc=0;
			failCount=0;
			fProgCount=0;
			if (ie==false) { $("title").html($(".ftemp:first").find(".temp_fname").text() + " Completed"); }
			dont_recall=true;
			var myftemp=temp.parent().parent().parent();
			var realid=myftemp.attr("realid");
			$("input[realid=" + realid + "]").remove();
			var fname=myftemp.find(".temp_fname").text();
			myftemp.slideUp("fast").remove();
			fCount--;
			$.get("ajax.php",{"action":"finish_upload", "sid":sid, "big":is_big },function(r) {
				d=eval('(' + r + ')');
				var f = $(document.createElement("div"));
				f.addClass('f').html($("#f_model").html()).attr("url",d['url']).data("id",d['id']).data("pg",0)
				.find('.fsize').text(d['size']).end().find('.ftype').text(d['type']).end()
				.find('.fname').text(shorten_fname(d['name'],18)).end().appendTo($("#group0 .gc"))
				.css("background-color","#999").hide().fadeIn("fast").animate( { backgroundColor: '#DBDFE1' }, 500)
				.find(".fname").data("id",d['id']).end().find(".fmain").draggable(f_drag_options);
				zebra();
				update_total();
				$("#content_main").animate({ paddingTop:"-=25px" }, 500);
				if (fCount>0) {
					upload_progress();
				}
				if (fCount==0) {
					$("#temp_files").animate({ top:"-40px" }, 500);
					$("#content_main").animate({ paddingTop:"0px" }, 500);
				}
			});
			return true;	
		}
		i++;
		setTimeout(upload_progress,1000);
	});
}

function file_error(msg) {
	myf=$(".ftemp:first");
	$("title").html(msg);
	var realid=myf.attr("realid");
	$("input[realid=" + realid + "]").remove();
	myf.animate( { backgroundColor: '#DD5445' }, 500).css("color","#e9e9e9").unbind();
	myf.html('<span class="too_large">' + msg + '</span>');
	setTimeout(function() {
		myf.slideUp("slow",function() {
			$(this).remove();
			zebra();
			if (fCount>1) {
				$("#content_main").animate({ paddingTop:"-=25px" }, 500);
			} else {
				$("#temp_files").animate({ top:"-40px" }, 500);
				$("#content_main").animate({ paddingTop:"0px" }, 500);
			}
			fCount--;
			upload_progress();
		});
	}, 3000);
}

function rename_link(txt) {
	if (oldshare!='') {
		if (txt.val()==oldshare) {
			return false;
		}
	}
	if (txt.val()=='') {
		txt.val("Click to change link..").attr("alt",'');
		return false;
	}
	myval=txt.val();
	oldshare=myval;
	$.get("ajax.php",{ action:"rename_url", "fid":selected_id, "selected_type":selected_type, new_url: myval},function(r) {
		r=eval("(" + r + ")");
		if (r['error']==true) {
			alert(r['message']);
			$("#share_rename").val("");
		} else {	
			if (selected_type=="f") {
				$("#share_link").val("http://uploadrobots.com/" + myval); 
			} else {
				$("#share_link_g").val("http://uploadrobots.com/" + myval); 
			}
			
		}
	});
}