 // (c) by Magnus Manske, released under GPL V3 or higher except for third party code where noted otherwise

// Testing : Pictures of the day (2009)

var cc_language ;
var cc_project ;
var ccd = new Array () ;
var commcomm_id_counter = 0 ;
var cc_thumbsize = 128 ;
var cc_thumb_div_height = 180 ;
var cc_recentchanges_refresh_sec = 30 ;
var cc_tabs = new Array ( 'cat', 'user' , 'rc' , 'fs' , 'cs' ) ;

$.postJSON = function(url, callback) {
	$.post(url, callback, "json");
};

$(document).ready(function(){
	cc_language = $.getURLParam('language','commons') ;
	cc_project = $.getURLParam('project','wikimedia') ;
	
	// Init values
	ccd['ts_url'] = "http://toolserver.org/~magnus/commcomm/get_data.php?language=" + cc_language + "&project=" + cc_project ;
	ccd['ogg_thumbnail'] = 'http://commons.wikimedia.org/skins-1.5/common/images/icons/fileicon-ogg.png' ;
	
	init_data ( 'left' ) ;
	init_data ( 'right' ) ;
	
	add_top_box () ;
	add_main_box ( 'mainbox1' , 'left' ) ;
	add_main_box ( 'mainbox2' , 'right' ) ;
	add_opt_box ( 'optbox1' , 'mainbox1' , 'left' ) ;
	add_opt_box ( 'optbox2' , 'mainbox2' , 'right' ) ;

	fix_heights ( 'left' ) ;
	fix_heights ( 'right' ) ;

	var cat = $.getURLParam('category') ;
	var cat2 = $.getURLParam('category2') ;
	var user = $.getURLParam('user') ;
	var user2 = $.getURLParam('user2') ;

	if ( cat != null ) load_category ( cat.split('_').join(' ') , 'left' ) ;
	else if ( user != null ) load_user_files ( user.split('_').join(' ') , 'left' ) ;
	else if ( null != $.getURLParam('rc') ) $('#tab_left').tabs( 'select' , 2 ) ;

	if ( cat2 != null ) load_category ( cat2.split('_').join(' ') , 'right' ) ;
	else if ( user2 != null ) {
		$('#tab_right').tabs( 'select' , 1 ) ;
		load_user_files ( user2.split('_').join(' ') , 'right' ) ;
	} else if ( null != $.getURLParam('rc2') ) $('#tab_right').tabs( 'select' , 2 ) ;
	else { $('#tab_right').tabs( 'select' , 3 ) ; $('#fs_query_right').focus() ; }
});

function fix_heights ( ori ) {
	var h = $('#mainbox1').innerHeight() ;
	h -= 110 ;
	$('#catlist_'+ori).css('max-height',h) ;
	$('#catpics_'+ori).css('max-height',h) ;
	$('#userpics_'+ori).css('max-height',h) ;
	$('#rcpics_'+ori).css('max-height',h) ;
	$('#fspics_'+ori).css('max-height',h) ;
	$('#cspics_'+ori).css('max-height',h-100) ;
}

function init_data ( ori ) {
	ccd[ori] = new Array () ;
	$(cc_tabs).each(function(){
		ccd[ori][this] = new Array () ;
		ccd[ori][this]['files'] = new Array () ;
	}) ;
	ccd[ori]['rc']['timer'] = 0 ;
}

function add_top_box () {
	var html = "<table width='100%' cellspacing=0 cellpadding=0><tr>" ;
	html += "<td style='margin-right:20px' nowrap><big><b>Commons Commander</b></big></td><td width='100%'>" ;
	html += "<input type='checkbox' id='cb_file_click' checked/><label for='cb_file_click'>Single click clears other selections</label>" ;
	html += " <input type='checkbox' id='cb_two_panes' onchange='toggle_two_panes();' checked/><label for='cb_two_panes'>Two panes</label></td>" ;
	html += "<td><div id='debug'></div></td>" ;
	html += "<td nowrap><small><a href='http://meta.wikipedia.org/wiki/Commons_Commander'>About</a> | " ;
	html += "<a href='https://fisheye.toolserver.org/browse/Magnus/commcomm'>Code</a></small></td>" ;
	html += "</tr></table>" ;
	$('#topbox').html(html);
}

function update_selection_count ( ori ) {
	var cnt = 0 ;
	var tab = ccd[ori]['curtab'] ;
	for ( var i = 0 ; i <= ccd[ori][tab]['files'].length ; i++ ) {
		var id = get_file_id ( ori , i ) ;
		if ( $('#'+id).attr('selected') == 1 ) cnt++ ;
	}
	var html = cnt + ' selected' ;
	$('#selection_count_'+ori).html ( html ) ;
}

function add_opt_box ( ob , mb , ori ) {
	var html = '' ;
	html += "<div style='float:right;color:white;background:red;display:none;padding:3px' id='loading_"+ori+"'>Loading...</div>" ;
	html += "<table id='opt_box_table_"+ori+"' style='' cellspacing='0' >" ;

	html += "<tr>" ;
	
	html += "<td>Select:</td>" ;
	html += "<td colspan='2' align='right'><span id='selection_count_"+ori+"'></span></td>" ;
	
	html += "<td style='padding-left:20px'><input type='radio' name='dispmode_"+ori+"' id='dispmode_"+ori+"_thumb' value='thumb' checked onclick='change_display_mode(\""+ori+"\")' />" ;
	html += "<label for='dispmode_"+ori+"_thumb'>Thumbnails</label></td>"
	
	html += "<td style='padding-left:20px'>Order by</td>" ;
	html += "<td><input type='radio' name='sortmode_"+ori+"' id='sortmode_"+ori+"_name' value='name' checked onclick='change_sort_mode(\""+ori+"\")' /><label for='sortmode_"+ori+"_name'>Name</label></td>" ;
	html += "<td><input type='radio' name='sortdir_"+ori+"' id='sortdir_"+ori+"_asc' value='asc' checked onclick='change_sort_dir(\""+ori+"\")' /><label for='sortdir_"+ori+"_asc'>Ascending</label></td>" ;
	
	html += "<td style='padding-left:20px' width='100%'><input type='text' id='filter_"+ori+"' />" ;
	html += "<input type='button' onclick='change_filter(\""+ori+"\")' value='Apply filter' /></td>" ;

	html += "</tr><tr>" ;
	
	html += "<td><input type='button' onclick='button_all_selection(\""+ori+"\");' value='All' /></td>" ;
	html += "<td><input type='button' onclick='button_clear_selection(\""+ori+"\");' value='None' /></td>" ;
	html += "<td><input type='button' onclick='button_toggle_selection(\""+ori+"\");' value='Toggle' /></td>" ;
	
	html += "<td style='padding-left:20px'><input type='radio' name='dispmode_"+ori+"' id='dispmode_"+ori+"_list' value='list' onclick='change_display_mode(\""+ori+"\")' /><label for='dispmode_"+ori+"_list'>List</label></td>"

	html += "<td style='padding-left:20px'><input type='radio' name='sortmode_"+ori+"' id='sortmode_"+ori+"_size' value='size' onclick='change_sort_mode(\""+ori+"\")' /><label for='sortmode_"+ori+"_size'>Size</label></td>" ;
	html += "<td><input type='radio' name='sortmode_"+ori+"' id='sortmode_"+ori+"_date' value='date' onclick='change_sort_mode(\""+ori+"\")' /><label for='sortmode_"+ori+"_date'>Date</label></td>" ;
	html += "<td><input type='radio' name='sortdir_"+ori+"' id='sortdir_"+ori+"_desc' value='desc' onclick='change_sort_dir(\""+ori+"\")' /><label for='sortdir_"+ori+"_desc'>Descending</label></td>" ;
	html += "<td style='padding-left:20px'><small>(case-sensitive; use multiple words for AND)</small></td>" ;

	html += "</tr>" ;
	
	html += "</table>" ;
	
	$('#'+ob).html(html);
	$('#filter_'+ori).keydown ( function ( event ) { if (event.keyCode == 13) change_filter(ori); } ) ;
	$('#opt_box_table_'+ori+' td').attr('nowrap','nowrap');
	ccd[ori]['loading'] = 0 ;
	ccd[ori]['loading2'] = 0 ;
}

function reload_tab ( ori ) {
	if ( ccd[ori]['curtab'] == 'rc' ) {
		ccd[ori]['rc']['timer'] = 0 ;
		$('#rcpics_'+ori).html('') ;
		ccd[ori]['rc']['files'] = new Array () ;
		load_rc_files ( ori ) ;
		update_selection_count ( ori ) ;
	} else {
		if ( ccd[ori]['curtab'] == 'cat' ) $('#catpics_'+ori).html('') ;
		if ( ccd[ori]['curtab'] == 'user' ) $('#userpics_'+ori).html('') ;
		if ( ccd[ori]['curtab'] == 'fs' ) $('#fspics_'+ori).html('') ;
		if ( ccd[ori]['curtab'] == 'cs' ) $('#cspics_'+ori).html('') ;
		if ( ccd[ori]['curtab'] == 'cs' ) $('#cscandidates_'+ori).html('') ;
		change_file_display ( ori ) ;
	}
}

function change_sort_mode ( ori ) {
	reload_tab ( ori ) ;
}

function change_sort_dir ( ori ) {
	reload_tab ( ori ) ;
}

function change_filter ( ori ) {
	reload_tab ( ori ) ;
}

function change_display_mode ( ori ) {
	var tab = ccd[ori]['curtab'] ;
	for ( var i = 0 ; i <= ccd[ori][tab]['files'].length ; i++ ) {
		var id = get_file_id ( ori , i ) ;
		$('#'+id).remove() ;
	}
	for ( var i = 0 ; i <= ccd[ori][tab]['files'].length ; i++ ) {
		var id = get_file_id ( ori , i ) ;
		add_file ( ccd[ori]['thumbdiv'] , i , ori , tab )
	}
}

function toggle_two_panes () {
	var two = $('#cb_two_panes').is(':checked') ;
	var speed = 500 ;
	if ( two ) {
		$('#mainbox2').css().animate({left:'50%',right:'0px'},speed);
		$('#optbox2').css().animate({left:'50%',right:'0px'},speed);
		$('#mainbox1').css().animate({right:'50%'},speed);
		$('#optbox1').css().animate({right:'50%'},speed);
	} else {
		$('#mainbox2').css().animate({left:'100%',right:'1px'},speed);
		$('#optbox2').css().animate({left:'100%',right:'1px'},speed);
		$('#mainbox1').css().animate({right:'0px'},speed,function(){$('#catpics_left').scroll()});
		$('#optbox1').css().animate({right:'0px'},speed);
	}
}

function get_file_id ( ori , num ) {
	return 'file_' + ccd[ori]['curtab'] + "_" + ori + '_' + num ;
}

function button_all_selection ( ori ) {
	for ( var i = 0 ; i < ccd[ori][ccd[ori]['curtab']]['files'].length ; i++ ) {
		var divid = '#' + get_file_id ( ori , i ) ;
		set_file_selection ( $(divid) , 1 ) ;
	}
	update_selection_count ( ori ) ;
}

function button_clear_selection ( ori ) {
	if ( ! ccd[ori]['curtab'] ) return ;
	for ( var i = 0 ; i < ccd[ori][ccd[ori]['curtab']]['files'].length ; i++ ) {
		var divid = '#' + get_file_id ( ori , i ) ;
		set_file_selection ( $(divid) , 0 ) ;
	}
	update_selection_count ( ori ) ;
}

function button_toggle_selection ( ori ) {
	for ( var i = 0 ; i < ccd[ori][ccd[ori]['curtab']]['files'].length ; i++ ) {
		var divid = '#' + get_file_id ( ori , i ) ;
		set_file_selection ( $(divid) , 2 ) ;
	}
	update_selection_count ( ori ) ;
}


function change_file_display ( ori ) {
	$(cc_tabs).each(function(){
		ccd[ori][this]['files'] = new Array() ;
		ccd[ori][this]['last_selected'] = -1 ;
	}) ;
	
	if ( ccd[ori]['curtab'] == 'user' ) load_files_from_user ( ori ) ;
	else if ( ccd[ori]['curtab'] == 'cat' ) load_files_from_cat ( ori ) ;
}

function load_rc_files ( ori ) {
	ccd[ori]['rc']['timer'] = 1 ;
	ccd[ori]['rc']['last_timestamp'] = '' ;
	change_file_display ( ori ) ;
	update_rc ( ori ) ;
}

function get_order_params ( ori ) {
	var mode = $('input[name=sortmode_'+ori+']:checked').val() ;
	var dir = $('input[name=sortdir_'+ori+']:checked').val() ;
	var filter = $('#filter_'+ori).val() ;
	return '&order=' + mode + '&dir=' + dir + '&filter=' + escape ( filter ) ;
}

function update_rc ( ori ) {
	ccd[ori]['curtab'] = 'rc' ;
	if ( ccd[ori]['loading'] > 0 ) return ; // Busy
	if ( ccd[ori]['rc']['timer'] == 0 ) return ;
	
	var dispid = 'rcpics_' + ori ;
	ccd[ori]['thumbdiv'] = dispid ;

	var filter = $('#filter_'+ori).val().split(' ') ;
	var url = ccd['ts_url'] + "&mode=rcfiles" ;
	url += "&limit=60" ;
	url += "&timestamp=" + ccd[ori]['rc']['last_timestamp'] ;
	
	ccd[ori]['rc']['more_available'] = 0 ;
	loading ( ori , 'loading' , 1 ) ;
	$.get ( url , {} , function ( data, textStatus) {
		var d2 = data.split("\n") ;
		for ( var a = 0 ; a < d2.length ; a++ ) {
			
			// Manually apply filter
			var use = true ;
			$(filter).each ( function () {
				if ( this != '' && d2[a].split(this).length < 2 ) use = false ;
			} ) ;
			if ( !use ) continue ;
			
			if ( d2[a] == 'MORE' ) {
				ccd[ori]['rc']['more_available'] = 1 ;
				break ;
			}
			if ( d2[a] == '' ) continue ;
			var d = d2[a].split("\t") ;
			var filenumber = ccd[ori]['rc']['files'].length ;
			ccd[ori]['rc']['files'].push ( d ) ;
			add_file ( dispid , filenumber , ori , 'rc' ) ;
			if ( ccd[ori]['rc']['last_timestamp'] < d[4] ) ccd[ori]['rc']['last_timestamp'] = d[4] ;
		}
		loading ( ori , 'loading' , -1 ) ;
	} , 'text' ) ;
	
	setTimeout ( function () { update_rc ( ori ) ; } , cc_recentchanges_refresh_sec * 1000 ) ;
}

function load_files_from_cat ( ori ) {
	if ( ccd[ori]['loading'] > 0 ) return ; // Busy
	var dispid = 'catpics_' + ori ;
	ccd[ori]['thumbdiv'] = dispid ;
	var category = ucfirst ( $('#catname_'+ori).val() ) ;
	var url = ccd['ts_url'] + "&mode=files&category=" + escape ( category ) ;
	url += "&limit=60&offset=" + ccd[ori]['cat']['files'].length ;
	url += get_order_params ( ori ) ;

	ccd[ori]['cat']['more_available'] = 0 ;
	loading ( ori , 'loading' , 1 ) ;
	$.get ( url , {} , function ( data, textStatus) {
		var d2 = data.split("\n") ;
		for ( var a = 0 ; a < d2.length ; a++ ) {
			if ( d2[a] == 'MORE' ) {
				ccd[ori]['cat']['more_available'] = 1 ;
				break ;
			}
			if ( d2[a] == '' ) continue ;
			var d = d2[a].split("\t") ;
			var filenumber = ccd[ori]['cat']['files'].length ;
			ccd[ori]['cat']['files'].push ( d ) ;
			add_file ( dispid , filenumber , ori , 'cat' ) ;
		}
		loading ( ori , 'loading' , -1 ) ;
	} , 'text' ) ;
}

function loading ( ori , key , cnt ) {
	var id = '#loading_' + ori ;
	if ( cnt > 0 ) {
		ccd[ori][key]++ ;
		if ( ccd[ori]['loading'] + ccd[ori]['loading2'] == 1 ) {
			$(id).fadeIn() ;
			update_selection_count ( ori ) ;
		}
	} else {
		ccd[ori][key]-- ;
		if ( ccd[ori]['loading'] + ccd[ori]['loading2'] == 0 ) $(id).fadeOut() ;
	}
}

function newid () {
	commcomm_id_counter++ ;
	return "id_" + commcomm_id_counter ;
}

function get_thumbnail_image ( imgid , thumb_url , d , maxw ) {
	var ret ;
	var filename = d[0] ;
	if ( filename.match(/\.gif$/i) ) ret = "<img id='"+imgid+"' src='"+d[7]+"' width='"+maxw+"px' />" ;
	else if ( filename.match(/\.og[gva]$/i) ) ret = "<img id='"+imgid+"' src='"+ccd['ogg_thumbnail']+"' width='"+maxw+"px' />" ;
	else if ( parseInt ( d[1] ) <= parseInt ( maxw ) ) ret = "<img id='"+imgid+"' src='"+d[7]+"' width='"+maxw+"px' />" ;
	else ret = "<img id='"+imgid+"' src='"+thumb_url+"'/>" ;
	return ret ;
}

function add_file ( id , filenumber , ori , tab ) {
	var mode = $('input[name=dispmode_'+ori+']:checked').val() ;
//	var mode = 'thumb' ;
	var d = ccd[ori][tab]['files'][filenumber] ;
	var html ;
	var imgid = 'img_' + ori + '_' + filenumber ;
	var divid = get_file_id ( ori , filenumber ) ;
	var xoff = 0 ;
	var yoff = 0 ;
	if ( mode == 'thumb' ) {
		var thumb_url = d[5] ;
		var maxw = get_max_thumb_width ( d[1] , d[2] , cc_thumbsize ) ;
		yoff = Math.floor ( ( cc_thumbsize - maxw * d[2] / d[1] ) / 2  ) ;
		thumb_url = thumb_url.split('|').join(maxw) ;
		html = "<div class='thumb_container' id='"+divid+"'>" ;
		html += "<div style='min-height:"+cc_thumbsize+"px;max-height:"+cc_thumbsize+"px'>" ;
		html += get_thumbnail_image ( imgid , thumb_url , d , maxw ) ;
		html += "</div>" ;
		html += "<span class='thumb_caption'>"+d[0]+"</span>" ;
		html += "</div>" ;
	} else if ( mode == 'list' ) {
		var thumb_url = d[5] ;
		var maxw = get_max_thumb_width ( d[1] , d[2] , cc_thumbsize ) ;
		yoff = Math.floor ( ( cc_thumbsize - maxw * d[2] / d[1] ) / 2  ) ;
		xoff = Math.floor ( ( cc_thumbsize - maxw ) / 2 ) ;
		thumb_url = thumb_url.split('|').join(maxw) ;
		var userlink = d[3] ;
		html = "<div class='list_container' id='"+divid+"'><table><tr>" ;
		html += "<td style='width:"+cc_thumbsize+"px;text-align:center'>" ;
		html += get_thumbnail_image ( imgid , thumb_url , d , maxw ) ;
		html += "</td>" ;
		html += "<td style='font-size:9pt;width:100%' valign='top'><div><b>"+d[0]+"</b><br/>"+d[1]+"&times;"+d[2]+"px, "+d[6]+" bytes; uploaded on "+d[4]+" by "+userlink+"</div></td>" ;
//		html += "<td valign='top'><div onclick='alert(\"!\")' style='width:20px;background:green'>&nbsp;</div></td>" ;
		html += "</tr></table></div>" ;
	}
	$('#'+id).append(html);
	if ( xoff > 0 ) {
		$('#'+imgid).css('margin-left',xoff);
		$('#'+imgid).css('margin-right',xoff);
	}
	if ( yoff > 0 ) {
		$('#'+imgid).css('margin-top',yoff);
		$('#'+imgid).css('margin-bottom',yoff);
	}

	$('#'+divid).attr('file',d[0]);
	$('#'+divid).attr('ori',ori);
	$('#'+divid).attr('filenumber',filenumber);
	$('#'+divid).attr('selected',0);
	
	$('#'+divid).dblclick(function(e){
		var url = 'http://' + cc_language + '.' + cc_project + '.org/wiki/File:' + $(this).attr('file') ;
		window.open ( url ) ;
	});
	
	$('#'+divid).contextMenu({

		menu: 'myMenu'

	},
		function(action, el, pos) {
			var ori = $(el).attr('ori') ;
			var tab = ccd[ori]['curtab'] ;
			var cat = $('#catname_'+ori).val() ;
			if ( tab != 'cat' ) cat = '' ;
			
			if ( $("#cb_file_click").is(':checked') && $(el).attr('selected') != 1 ) {
				for ( var i = 0 ; i <= ccd[ori][tab]['files'].length ; i++ ) {
					var divid = '#' + get_file_id ( ori , i ) ;
					set_file_selection ( $(divid) , 0 ) ;
				}
			}
			set_file_selection ( el , 1 ) ;
			
			if ( action == 'q_add' ) {
				quick_add_move ( 0 , cat , ori ) ;
			} else if ( action == 'q_move' ) {
				quick_add_move ( 1 , cat , ori ) ;
			} else if ( action == 'q_del' ) {
				if ( cat != '' ) alter_files_in_category ( cat , 2 , ori ) ;
				else alert ( 'This only works if you are in the category tab and have selected a category!' ) ;
			} else if ( action == 'q_rename' || action == 'q_checkusage' ) {
				var files = get_selected_files ( ori ) ;
				if ( files.length == 0 ) {
					alert ( 'No files selected' ) ;
					return ;
				}
				if ( files.length > 1 ) {
					var action = action == 'q_rename' ? 'rename' : 'check the usage of' ;
					alert ( 'You can only '+action+' a single file at a time' ) ;
					return ;
				}
				rename_dialog ( ori , files[0] , action == 'q_rename' ) ;
			} else if ( action == 'q_view' ) {
				var files = get_selected_files ( ori ) ;
				$(files).each ( function () {
					var url = 'http://' + cc_language + '.' + cc_project + '.org/wiki/File:' + escape ( this[0] ) ;
					window.open ( url ) ;
				} ) ;
			} else if ( action == 'q_edit' ) {
				var files = get_selected_files ( ori ) ;
				$(files).each ( function () {
					var url = 'http://' + cc_language + '.' + cc_project + '.org/w/index.php?action=edit&title=File:' + escape ( this[0] ) ;
					window.open ( url ) ;
				} ) ;
			} else if ( action == 'q_user_others' ) {
				var files = get_selected_files ( ori ) ;
				if ( files.length != 1 ) {
					alert ( "You have to select a single file!" ) ;
					return ;
				}
				var ori2 = ori == 'left' ? 'right' : 'left' ;
				var user = files[0][3] ;
				$('#tab_'+ori2).tabs( 'select' , 1 ) ;
				$('#username_'+ori2).val ( user ) ;
				load_user_files ( user , ori2 ) ;
			} else if ( action == 'q_search_related' ) {
				var files = get_selected_files ( ori ) ;
				if ( files.length != 1 ) {
					alert ( "You have to select a single file!" ) ;
					return ;
				}
				var ori2 = ori == 'left' ? 'right' : 'left' ;
				
				var qs = files[0][0].replace ( /[^\w\d]/g , ' ' ) ;
				qs = qs.split(' ') ;
				var query = '' ;
				$(qs).each ( function () {
					if ( this.length < 3 ) return ;
					if ( /\d/.test(this) ) return ;
					if ( /^jp[e]{0,1}g$/i.test(this) ) return ;
					if ( /^tif[f]{0,1}$/i.test(this) ) return ;
					if ( /^img$/i.test(this) ) return ;
					if ( /^svg$/i.test(this) ) return ;
					if ( /^png$/i.test(this) ) return ;
					if ( /^gif$/i.test(this) ) return ;
					if ( /^og[agvm]$/i.test(this) ) return ;
					if ( /^edit(ed){0,1}[\d]*$/i.test(this) ) return ;
					if ( /^and$/i.test(this) ) return ;
					query += this + ' ' ;
				} ) ;
				$('#tab_'+ori2).tabs( 'select' , 3 ) ;
				$('#fs_query_'+ori2).val ( query ) ;
				run_file_search ( ori2 , true ) ;
			} else if ( action == 'q_cats' ) {
				var files = get_selected_files ( ori ) ;
				if ( files.length != 1 ) {
					alert ( "You have to select a single file!" ) ;
					return ;
				}
				var ori2 = ori == 'left' ? 'right' : 'left' ;
				show_file_cats ( files[0] , ori2 ) ;
			}

/*			alert(

				'TESTING!!!\n\n' +

				'Action: ' + action + '\n\n' +

				'Element ID: ' + $(el).attr('id') + '\n\n' + 

				'X: ' + pos.x + '  Y: ' + pos.y + ' (relative to element)\n\n' + 

				'X: ' + pos.docX + '  Y: ' + pos.docY+ ' (relative to document)'

				);*/

	});

	
	$('#'+divid).click(function(e){
		var ori = $(this).attr('ori') ;
		if ( e.shiftKey && ccd[ori][tab]['last_selected'] > -1 ) {
			var n1 = parseInt ( $(this).attr('filenumber') ) ;
			var n2 = parseInt ( ccd[ori][tab]['last_selected'] ) ;
			if ( n1 > n2 ) { var n3 = n1 ; n1 = n2 ; n2 = n3 ; }
			for ( var i = n1 ; i <= n2 ; i++ ) {
				var divid = '#' + get_file_id ( ori , i ) ;
				set_file_selection ( $(divid) , 1 ) ;
			}
		} else {
			if ( $("#cb_file_click").is(':checked') && !e.ctrlKey && !e.metaKey ) {
				var n1 = parseInt ( $(this).attr('filenumber') ) ;
				for ( var i = 0 ; i <= ccd[ori][tab]['files'].length ; i++ ) {
					if ( i == n1 ) continue ;
					var divid = '#' + get_file_id ( ori , i ) ;
					set_file_selection ( $(divid) , 0 ) ;
				}
			}
			set_file_selection ( this , 2 ) ;
			ccd[ori][tab]['last_selected'] = $(this).attr('filenumber') ;
		}
		update_selection_count ( ori ) ;
		e.preventDefault () ;
		return false ;
	});
}

function rename_file ( ori , file ) {
	rename_dialog ( ori , file , true ) ;
}

function check_usage ( ori , file ) {
	rename_dialog ( ori , file , false ) ;
}

function get_tusc_table ( id ) {
	var tusc = "<a target='_blank' href='http://toolserver.org/~magnus/tusc.php'>TUSC</a>" ;
	var tusc_user = readCookie ( 'tusc_user' ) ;
	var tusc_password = readCookie ( 'tusc_password' ) ;

	var html = '' ;
	html += "<div id='"+id+"' style='margin-top:5px'><table style='width:100%;font-size:80%' cellspacing=0 cellpadding=0><tr>" ;
	html += "<td nowrap>"+tusc+" username</td>" ;
	html += "<td><input type='text' id='tusc_user' value='"+tusc_user+"' /></td>" ;
	html += "<td nowrap>"+tusc+" password</td>" ;
	html += "<td><input type='password' id='tusc_password' value='"+tusc_password+"' /></td></tr>" ;
	html += "<tr><td colspan='4'><input type='checkbox' id='store_tusc_login' checked /><label for='store_tusc_login'>Store login as cookie</label></td></tr></table></div>" ;
	return html ;
}

function rename_dialog ( ori , file , do_rename ) {
	if ( $('#dialog_rename') ) $('#dialog_rename').remove() ;
	var html = "<div id='dialog_rename'>" ;
	if ( do_rename ) {
		html += "<div><input type='text' id='dialog_rename_newname' value='' style='width:100%' /></div>" ;
		html += get_tusc_table ( 'dialog_rename_password_table' ) ;
	}

	html += "<div id='dialog_rename_content' style='margin-top:5px;max-height:300px;overflow:auto'>Loading CheckUsage...</div>" ;
	html += "</div>" ;

	var title = do_rename ? 'Rename file' : 'CheckUsage' ;
	title += ' "' + file[0] + '"' ;
	var d = $(html) ;
	d.dialog ({ 
		modal: true , 
		width:'500px' , 
		maxHeight : '400px' ,
		title : title ,
		buttons: { 
			"OK": function() { if ( do_rename ) rename_file_ok ( ori , file ) ; else $(this).dialog("close"); } ,
			"Cancel": function() { $(this).dialog("close"); }
		}
	});
	
	if ( do_rename ) {
		$('#dialog_rename_newname').val ( file[0] ) ;
		$('#dialog_rename_newname').focus() ;
		$('#dialog_rename_newname').keydown ( function ( event ) { if (event.keyCode == 13) rename_file_ok ( ori , file ) ; } ) ;
	}
	d.dialog('option', 'position', 'center');
	
	var url = 'http://toolserver.org/~daniel/WikiSense/CheckUsage.php?i='+escape(file[0])+'&w=_100000&m=&x=&go=Check+Usage&r=on&b=0' ;
	$.get ( url , function ( data, textStatus) {
		var d2 = data.split ( "\n" ) ;
		var html = '' ;
		var cur_section_number = 0 ;
		var cur_section = '' ;
		$(d2).each ( function () {
			if ( this == '' ) return ;
			if ( this.substr ( 0 , 1 ) == '[' ) {
				cur_section = this.substr(1).split(']').shift() ;
				var nop = this.split("\t").pop() ;
				if ( cur_section_number > 0 ) html += "</div>" ;
				cur_section_number++ ;
				var csid = "dialog_rename_section_" + cur_section_number ;
				html += "<a href='#' onclick='toggle_disp(\""+csid+"\");return false;'>[+]</a> "+cur_section+" ("+nop+" pages)<br/><div id='"+csid+"' style='font-size:80%;display:none'>" ;
				return ;
			}
			var s = this.split("\t").shift() ;
			var s_text = s.split('_').join(' ') ;
			html += "<a style='margin-left:30px' target='_blank' href='http://"+cur_section+"/wiki/"+s+"'>"+s_text+"</a><br/>" ;
		} ) ;
		if ( cur_section_number > 0 ) html += "</div>" ;
		if ( html == '' ) html = 'This file is apparently not used anywhere.' ;
		$('#dialog_rename_content').html ( html ) ;
		$('#dialog_rename').dialog('option', 'position', 'center');
	} , 'text' ) ;
}

function toggle_disp ( id ) {
	$('#'+id).toggle();
}

function rename_file_ok ( ori , file ) {
	var newname = $('#dialog_rename_newname').val() ;
	
	if ( file[0] == newname ) {
		$('#dialog_rename').dialog("close");
		alert ( 'Old and new name are identical. Closing due to boring rename.' ) ;
		return ;
	}
	
	// BEGIN TEMPORARY HACK
	alert ( "My bot does not have not move rights on Commons. A window for manual renaming will open now. You will have to reload the view after renaming to update the file list." ) ;
	$('#dialog_rename').dialog("close");
	url = "http://commons.wikimedia.org/wiki/Special:MovePage/File:"+escape(file[0])+"?wpNewTitle=File:" + escape ( newname ) ;
	window.open ( url ) ;
	return ;
	// END TEMPORARY HACK

	var tusc_user = $('#tusc_user').val() ;
	var tusc_password = $('#tusc_password').val() ;
	if ( tusc_user == '' || tusc_password == '' ) {
		alert ( 'TUSC user name or password not supplied, aborting.' ) ;
		$('#dialog1').dialog("close");
		return ;
	}
	
	if ( $('#store_tusc_login').is(':checked') ) {
		createCookie ( 'tusc_user' , tusc_user , 30 ) ;
		createCookie ( 'tusc_password' , tusc_password , 30 ) ;
	}
	
	$('#dialog1_password_table').html ( "<span style='color:red'>STANDBY...</span>" ) ;

	var url = ccd['ts_url'] ;
	$.post ( url , {
		user : tusc_user ,
		pass : tusc_password ,
		title : file[0] ,
		mode : 'edit' ,
		action : 'move' ,
		newname : newname
	} , function ( data, textStatus ) {
		if ( /success/i.test ( data ) ) {
			$('#dialog1_password_table').html ( "<span style='color:green'>SUCCESS!</span>" ) ;
			setTimeout ( function () {
				$('#dialog_rename').dialog("close");
				reload_tab ( ori ) ;
			} , 500 ) ;
		} else {
			alert ( "A problem has occurred : " + data ) ;
			$('#dialog_rename').dialog("close");
		}
//		dialog1_report ( ori , file , data , textStatus , cnt2 ) ;
	} ) ;


	$('#dialog_rename').dialog("close");
}

function quick_add_move ( mode , cat , ori ) {
	if ( $('#dialog_qam') ) $('#dialog_qam').remove() ;
	var html = "<div id='dialog_qam'>" ;
	html += "<table border='1' align='center'><tbody><tr id='dialog_table'><th colspan='2' nowrap>" ;
	
	var title ;
	if ( mode == 0 ) title = "Quick-add files to a category" ;
	else if ( mode == 1 ) title = "Quick-move files to a category" ;
	title += '</i>' ;
	
	
	html += title + "</th></tr>" ;
	html += "<tr><td colspan='2'>Target category:</td></tr>" ;
	html += "<tr><td colspan='2'><input type='text' size='50' id='qam_input' /></td></tr>" ;
	if ( cat != '' ) {
		html += "<tr><td colspan='2'><input type='checkbox' id='qam_make_subcat' /><label for='qam_make_subcat'>Make subcategory of "+cat+"</label></td></tr>" ;
	}
	html += "</tbody></table>" ;
	html += "</div>" ;
	var d = $(html) ;
	d.dialog ({ 
		modal: true , 
		width:'500px' , 
		title : title ,
		buttons: { 
			"OK": function() { qam_ok(mode,ori) ; } ,
			"Cancel": function() { $(this).dialog("close"); }
		}
	});
	$('#qam_input').jsonSuggest(list_category_candidates, {ajaxResults:true,minCharacters:3});
	$('#qam_input').keydown ( function ( event ) { if (event.keyCode == 13) qam_ok(mode,ori); } ) ;
	$('#qam_input').focus() ;
}

function qam_ok ( mode , ori ) {
	var v = escape ( $('#qam_input').val() ) ;
	$('#dialog_qam').dialog("close");
	alter_files_in_category(v,mode,ori);
}

function list_category_candidates ( text, wildCard, caseSensitive, notCharacter) {
	var url = ccd['ts_url'] + "&mode=suggest&namespace=14&limit=5&text=" + escape ( text ) ;
	var v = $.ajax ( {
		url: url,
		async: false ,
		type : 'GET'
	}).responseText ;
	v = v.split("\n") ;
	
	var ret = new Array () ;
	$(v).each ( function () { ret.push ( { text : this } ) ; } ) ;
	return ret ;
}

function set_file_selection ( obj , new_status ) {
	if ( new_status == 2 ) {
		if ( $(obj).attr('selected') == 1 ) {
			new_status = 0 ;
		} else {
			new_status = 1 ;
		}
	}
	
	$(obj).attr ( 'selected' , new_status ) ;
	if ( new_status == 1 ) {
		$(obj).css('background-color','#666688') ;
		$(obj).css('color','#FFFFFF') ;
	} else {
		$(obj).css('background-color','') ;
		$(obj).css('color','black') ;
	}
}

function get_max_thumb_width ( w , h , m ) {
	ret = 0 ;
	w = parseInt ( w ) ;
	h = parseInt ( h ) ;
	if ( w > h ) {
		ret = m ;
	} else {
		ret = Math.floor ( w / ( h / m ) ) ;
	}
	return ret ;
}

function load_user_files ( user , ori ) {
	ccd[ori]['curtab'] = 'user' ;
	user = unescape ( user ) ;
	$('#username_'+ori).val(user) ;
	$('#userpics_'+ori).html('') ;
	change_file_display ( ori ) ;
}


function load_files_from_user ( ori ) {
	if ( ccd[ori]['loading'] > 0 ) return ; // Busy
	ccd[ori]['user']['more_available'] = 0 ;
	var dispid = 'userpics_' + ori ;
	ccd[ori]['thumbdiv'] = dispid ;
	var user = ucfirst ( $('#username_'+ori).val() ) ;
	if ( user == '' ) return ;
	
	
	var url = ccd['ts_url'] + "&mode=userfiles&user=" + escape ( user ) ;
	url += "&limit=60&offset=" + ccd[ori]['user']['files'].length ;
	url += get_order_params ( ori ) ;

	loading ( ori , 'loading' , 1 ) ;
	$.get ( url , {} , function ( data, textStatus) {
		var d2 = data.split("\n") ;
		for ( var a = 0 ; a < d2.length ; a++ ) {
			if ( d2[a] == 'MORE' ) {
				ccd[ori]['user']['more_available'] = 1 ;
				break ;
			}
			if ( d2[a] == '' ) continue ;
			var d = d2[a].split("\t") ;
			var filenumber = ccd[ori]['user']['files'].length ;
			ccd[ori]['user']['files'].push ( d ) ;
			add_file ( dispid , filenumber , ori , 'user' ) ;
		}
		loading ( ori , 'loading' , -1 ) ;
	} , 'text' ) ;
}





function load_category ( category , ori ) {
	ccd[ori]['curtab'] = 'cat' ;
	category = unescape ( category ) ;
	$('#catname_'+ori).val(category) ;
	$('#catpics_'+ori).html('') ;
	load_category_relations ( category , 'catlist_'+ori , ori ) ;
	change_file_display ( ori ) ;
}

function cc_icon ( i ) {
	return "images/" + i ;
}

function load_category_relations ( category , id , ori ) {
	$('#'+id).hide ( 'highlight' ) ;
	loading ( ori , 'loading2' , 1 ) ;
	var url = ccd['ts_url'] + "&mode=catcontext&category=" + escape ( category ) ;
	$.get ( url , {} , function ( data, textStatus) {
		var h = "<table style='font-size:8pt'>" ;
		var d = data.split("\n");
		var aids = new Array () ;
		for ( var a = 0 ; a < d.length ; a++ ) {
			if ( d[a] == '' ) continue ;
			var x = d[a].split("\t") ;
			var n = x[1] ;
			var k = '?' ;
			if ( x[0] == '0' ) k = "&uarr;&uarr;" ;
			else if ( x[0] == '1' ) k = "&uarr;" ;
			else if ( x[0] == '2' ) { k = "&rarr;" ; n = "<b>" + n + "</b>" ; }
			else if ( x[0] == '3' ) k = "&darr;" ;
			o = "load_category(\""+escape(x[1])+"\",\""+ori+"\");return false;" ;
			h += "<tr>" ;
			h += "<td>" + k + "</td>" ;
			h += "<td width='100%'><a class='catlink' href='#' onclick='" + o + "'>" + n + "</a></td><td nowrap align='center'>" ;
			if ( x[1] == category ) {
				h += "<a class='catlink' href='#' onclick='alter_files_in_category(\""+escape(x[1])+"\",2,\""+ori+"\");return false;'><img src='"+cc_icon("del.png")+"'  border=0/></a>" ;
			} else {
				h += "<a class='catlink' href='#' onclick='alter_files_in_category(\""+escape(x[1])+"\",0,\""+ori+"\");return false;'><img src='"+cc_icon("add.png")+"'  border=0/></a> " ;
				h += "<a class='catlink' href='#' onclick='alter_files_in_category(\""+escape(x[1])+"\",1,\""+ori+"\");return false;'><img src='"+cc_icon("move.png")+"'  border=0/></a>" ;
			}
			h += "</td>" ;
			h += "</tr>" ;
		}
		h += "</table>" ;
		$('#'+id).html(h);
		loading ( ori , 'loading2' , -1 ) ;
		$('#'+id).show ( 'highlight' ) ;
		$('#'+id).click ( function (e) { e.preventDefault () ; } ) ;
	} , 'text' ) ;
}

function get_selected_files ( ori ) {
	if ( ori == null ) { // Get both sides
		var l = get_selected_files ( 'left' ) ;
		var r = get_selected_files ( 'right' ) ;
		$(l).each(function(){r.push(this);}) ;
		return r ;
	}
	var tab = ccd[ori]['curtab'] ;
	var ret = new Array () ;
	if ( tab == null ) return ret ;
//	alert ( ori + " / " + tab ) ; return ret ;
	for ( var i = 0 ; i <= ccd[ori][tab]['files'].length ; i++ ) {
		var sel = $('#'+get_file_id(ori,i)).attr('selected') ;
		if ( sel == 1 ) ret.push ( ccd[ori][tab]['files'][i] ) ;
	}
	return ret ;
}

function alter_files_in_category ( target_cat , mode , ori ) {
	target_cat = unescape ( target_cat ) ;
	if ( $('#dialog1') ) $('#dialog1').remove() ;
	var ocat = $('#catname_'+ori).val() ;
	var files = get_selected_files ( ori ) ;
	if ( files.length == 0 ) {
		alert ( "No files selected!" ) ;
		return ;
	}
	var html = "<div id='dialog1'>" ;
	html += "<table border='1' align='center' id='dialog_table'>" ;
	
	if ( ocat == '' && mode == 1 ) mode = 0 ; // Can't move from an empty category...
	
	var title ;
	if ( mode == 0 ) title = "Copy "+files.length+" files to <i>"+target_cat ;
	else if ( mode == 1 ) title = "Move "+files.length+" files to <i>"+target_cat ;
	else if ( mode == 2 ) title = "Remove "+files.length+" files from <i>"+target_cat ;
	title += '</i>' ;
	
	var remove_old = mode == 1 || mode == 2 ;
	var add_new = mode == 0 || mode == 1 ;
	
	var cnt = 0 ;
	var to_check = new Array () ;
	$(files).each(function () {
		var lid = "td_" + cnt ;
		var url = 'http://' + cc_language + '.' + cc_project + '.org/wiki/File:' + escape ( this[0] ) ;
		html += "<tr><td id='"+lid+"'><input type='checkbox' id='dialog_cb_"+cnt+"' /></td>" ;
		html += "<td style='width:100%' id='dialog_file_"+lid+"'><a target='_blank' href='" + url + "'>" + this[0] + "</a></td>" ;
		if ( remove_old ) html += "<td class='dialog_unknown' id='can_remove_old_"+cnt+"'><img src='"+cc_icon("del.png")+"' /></td>" ;
		if ( add_new ) html += "<td class='dialog_unknown' id='can_add_new_"+cnt+"'><img src='"+cc_icon("add.png")+"' /></td>" ;
		html += "</tr>" ;
		var n = 0 ;
		if ( remove_old ) n++ ;
		if ( add_new ) n++ ;
		to_check[cnt] = n ;
		cnt++ ;
	} ) ;
	
	html += "</table>" ;
	html += get_tusc_table ( 'dialog1_password_table' ) ;
	html += "</div>" ;

	var d = $(html) ;
	d.dialog ({ 
		modal: true , 
		width:'500px' , 
		title : title ,
		maxHeight : '700px' ,
		buttons: { 
			"OK": function () { dialog1_OK ( ori , target_cat , ocat , mode ) ; } ,
			"Cancel": function() { $(this).dialog("close"); }
		}
	});
	$('#tusc_user').focus() ;
	
	ccd[ori]['dialog1'] = new Array () ;
	ccd[ori]['dialog1']['files'] = files ;
	ccd[ori]['dialog1']['remove_old'] = remove_old ;
	ccd[ori]['dialog1']['add_new'] = add_new ;
	ccd[ori]['dialog1']['wikicache'] = new Array () ;
	ccd[ori]['dialog1']['add_cat'] = new Array () ;
	ccd[ori]['dialog1']['mode'] = mode ;

	if ( remove_old ) {
		cnt = 0 ;
		$(files).each(function () {
			var cnt2 = cnt ;
			var lid = "td_" + cnt ;
			
			var url = "http://"+cc_language+"."+cc_project+".org/w/api.php?action=query&format=json&prop=revisions&rvprop=content&titles=File:" + escape ( this[0] ) + "&callback=?" ;
			$.getJSON ( url , function ( data ) {
				var wiki , wiki2 ;
				$.each(data.query.pages,function(key,value){
					wiki = value.revisions.pop()['*'] ;
					wiki2 = wiki.split('_').join(' ').toLowerCase();
				});
				var bad = true ;
				if ( wiki == null ) {
					wiki = '' ;
					wiki2 = '' ;
				}
				
				// FIXME should use regexp
				// Detect if ocat exists in text
				var k1 = '[[category:' + ocat + ']]' ;
				var k2 = '[[category:' + ocat + '|' ;
				k1 = k1.toLowerCase() ;
				k2 = k2.toLowerCase() ;
				if ( -1 != wiki2.indexOf(k1) || -1 != wiki2.indexOf(k2) ) {
					bad = false ;
					var p = wiki2.indexOf(k1) ;
					if ( p == -1 ) wiki2.indexOf(k2) ;
					var w = wiki.substr ( 0 , p ) ;
					var v = wiki.substr(p).split(']]') ;
					v.shift () ;
					v = v.join(']]') ;
					if ( v.substr(0,1) == "\n" ) v = v.substr ( 1 ) ;
					w += v ;
					ccd[ori]['dialog1']['wikicache'][cnt2] = trim ( w ) ;
				}
				
				$('#can_remove_old_'+cnt2).removeClass('dialog_unknown') ;
				if ( bad ) {
					$('#can_remove_old_'+cnt2).addClass('dialog_red') ;
				} else {
					$('#can_remove_old_'+cnt2).addClass('dialog_green') ;
					to_check[cnt2]-- ;
					if ( to_check[cnt2] == 0 ) {
//						$('#dialog_cb_'+cnt2).removeAttr ( 'disabled' ) ;
						$('#dialog_cb_'+cnt2).attr ( 'checked' , 1 ) ;
					}
				}
			} ) ;
			
		
			cnt++ ;
		}) ;
	}
	
	if ( add_new ) {
		cnt = 0 ;
		$(files).each(function () {
			var cnt2 = cnt ;
			var lid = "td_" + cnt ;
			
			var url = "http://"+cc_language+"."+cc_project+".org/w/api.php?action=query&format=json&prop=categories&cllimit=500&titles=File:" + escape ( this[0] ) + "&callback=?" ;
			$.getJSON ( url , function ( data ) {
				var bad = false ;
				$.each(data.query.pages,function(key,value){
					$(value.categories).each ( function () {
						var v = this.title.split(':',2).pop() ;
						if ( v == target_cat ) bad = true ;
					} ) ;
				});
				
				$('#can_add_new_'+cnt2).removeClass('dialog_unknown') ;
				if ( bad ) {
					$('#can_add_new_'+cnt2).addClass('dialog_red') ;
				} else {
					$('#can_add_new_'+cnt2).addClass('dialog_green') ;
					ccd[ori]['dialog1']['add_cat'][cnt2] = target_cat ;
					to_check[cnt2]-- ;
					if ( to_check[cnt2] == 0 ) {
//						$('#dialog_cb_'+cnt2).removeAttr ( 'disabled' ) ;
						$('#dialog_cb_'+cnt2).attr ( 'checked' , 1 ) ;
					}
				}
			} ) ;
			
		
			cnt++ ;
		}) ;
	}
	
	d.dialog('option', 'position', 'center');
	$('#tusc_user').keydown ( function ( event ) { if (event.keyCode == 13) dialog1_OK(ori,target_cat,ocat,mode) ; } ) ;
	$('#tusc_password').keydown ( function ( event ) { if (event.keyCode == 13) dialog1_OK(ori,target_cat,ocat,mode) ; } ) ;
	
	return false ;
}

function dialog1_OK ( ori , target_cat , ocat , mode ) {
	var files = ccd[ori]['dialog1']['files'] ;
	var tusc_user = $('#tusc_user').val() ;
	var tusc_password = $('#tusc_password').val() ;
	if ( tusc_user == '' || tusc_password == '' ) {
		alert ( 'TUSC user name or password not supplied, aborting.' ) ;
		$('#dialog1').dialog("close");
		return ;
	}
	
	if ( $('#store_tusc_login').is(':checked') ) {
		createCookie ( 'tusc_user' , tusc_user , 30 ) ;
		createCookie ( 'tusc_password' , tusc_password , 30 ) ;
	}
	
	$('#dialog1_password_table').html ( "<span style='color:red'>STANDBY...</span>" ) ;
	
	var cnt = 0 ;
	ccd[ori]['dialog1']['bad_results'] = new Array () ;
	ccd[ori]['dialog1']['actions_remaining'] = 0 ;
	$(files).each ( function () {
		if ( ! $('#dialog_cb_'+cnt).attr ( 'checked' ) ) return ;
		ccd[ori]['dialog1']['actions_remaining']++ ;
		cnt++ ;
	} ) ;
	
	if ( ccd[ori]['dialog1']['actions_remaining'] == 0 ) {
		$('#dialog1').dialog("close");
		return ;
	}
	
	cnt = 0 ;
	$(files).each ( function () {
		var file = this ;
		var cnt2 = cnt++ ;
		if ( ! $('#dialog_cb_'+cnt2).attr ( 'checked' ) ) return ;
		
		var url = ccd['ts_url'] ;
		var cat_text = "\n[[Category:" + ccd[ori]['dialog1']['add_cat'][cnt2] + "]]" ;

		var summary = new Array () ;
		if ( mode == 1 || mode == 2 ) summary.push ( 'removing [[Category:' + ocat + ']]' ) ;
		if ( mode == 0 || mode == 1 ) summary.push ( 'adding [[Category:' + target_cat + ']]' ) ;
		summary = summary.join ( '; ' ) ;
		
		if ( ccd[ori]['dialog1']['wikicache'][cnt2] ) { // Remove, and maybe add
			var w = ccd[ori]['dialog1']['wikicache'][cnt2] ;
			if ( ccd[ori]['dialog1']['add_cat'][cnt2] ) w += cat_text ;
			$.post ( url , {
				user : tusc_user ,
				pass : tusc_password ,
				title : this[0] ,
				mode : 'edit' ,
				action : 'replace' ,
				summary : summary ,
				text : w
			} , function ( data, textStatus ) {
				dialog1_report ( ori , file , data , textStatus , cnt2 ) ;
			} ) ;
		} else if ( ccd[ori]['dialog1']['add_cat'][cnt2] ) { // Add only
			$.post ( url , {
				user : tusc_user ,
				pass : tusc_password ,
				title : this[0] ,
				mode : 'edit' ,
				action : 'append' ,
				summary : summary ,
				text : cat_text
			} , function ( data , textStatus ) {
				dialog1_report ( ori , file , data, textStatus , cnt2 ) ;
			} ) ;
		}
	} ) ;

}

function dialog1_report ( ori , file , data , textStatus , filenum ) {
//	alert ( filenum + ' : ' + data ) ;
	var lid = 'td_' + filenum ;
	if ( /success/i.test(data) ) {
		$('#'+lid).html ( 'OK') ;
		$('#'+lid).addClass('dialog_green') ;
	} else {
		$('#'+lid).html ( data ) ;
		$('#'+lid).addClass('dialog_red') ;
		ccd[ori]['dialog1']['bad_results'].push ( file ) ;
	}

	ccd[ori]['dialog1']['actions_remaining']-- ;

	if ( ccd[ori]['dialog1']['actions_remaining'] == 0 ) {
		$('#dialog1_password_table').hide() ;
		setTimeout ( function () {
			if ( ccd[ori]['dialog1']['bad_results'].length != 0 ) {
				alert ( "There was a problem with actions on:\n" + ccd[ori]['dialog1']['bad_results'].join ( "\n" ) ) ;
			}
			$('#dialog1').dialog("close");
			if ( ccd[ori]['dialog1']['mode'] > 0 ) {
				reload_tab ( ori ) ;
			}
		} , 500 ) ;
	}

	
//	alert ( file[0] + "\n-----------\n" + data ) ;
}


function add_main_box ( root , ori ) {
//	var id = root + ".tab." + ori ;
	var id = "tab_" + ori ;
	
	var links = new Array () ;
	var divs = new Array () ;
	
	// Categories
	header_div = "<div id='cat_header_"+ori+"'><table border='0' style='width:100%'><tr><td style='width:100%'><input type='text' name='catname_"+ori+"' id='catname_"+ori+"' style='width:100%'/></td>" ;
	header_div += "<td><input ori='"+ori+"' id='cat_button_"+ori+"'type='button' value='Show category'/></td></tr></table></div>" ;
	
	content_div = "<table id='tab_cat_"+ori+"' style='width:100%;position:absolute;top:100px;left:0px;right:0px;bottom:0px;overflow:hidden' border='0'>" ;
	content_div += "<tr><td valign='top' style='width:210px'><div id='catlist_"+ori+"' style='background:#BBBBBB;overflow:auto'></div></td>" ;
	content_div += "<td valign='top'><div id='catpics_"+ori+"' style='background:#DDDDDD;overflow:auto'></div></td></tr></table>" ;
	
	links.push ( "<li><a href='#category_"+ori+"'>Categories</a></li>" ) ;
	divs.push ( "<div id='category_"+ori+"' style=''>"+header_div+content_div+"</div>" ) ;
	
	// User uploads
	header_div = "<div id='user_header_"+ori+"'><table border='0' style='width:100%'><tr><td style='width:100%'><input type='text' name='username_"+ori+"' id='username_"+ori+"' style='width:100%'/></td>" ;
	header_div += "<td><input ori='"+ori+"' id='user_button_"+ori+"'type='button' value='Show user files'/></td></tr></table></div>" ;

	content_div = "<table id='tab_user_"+ori+"' style='width:100%;position:absolute;top:100px;left:0px;right:0px;bottom:0px;overflow:hidden' border='0'>" ;
	content_div += "<tr><td width='100%' valign='top'><div id='userpics_"+ori+"' style='background:#DDDDDD;overflow:auto'></div></td></tr></table>" ;
	
	links.push ( "<li><a href='#user_"+ori+"'>User uploads</a></li>" ) ;
	divs.push ( "<div id='user_"+ori+"'>"+header_div+content_div+"</div>" ) ;
	
	
	// Recent Changes
	content_div = "<table id='tab_rc_"+ori+"' style='width:100%;position:absolute;top:100px;left:0px;right:0px;bottom:0px;overflow:hidden' border='0'>" ;
	content_div += "<tr><td width='100%' valign='top'><div id='rcpics_"+ori+"' style='background:#DDDDDD;overflow:auto'></div></td></tr></table>" ;

	links.push ( "<li><a href='#rc_"+ori+"'>Recent uploads</a></li>" ) ;
	divs.push ( "<div id='rc_"+ori+"'>"+content_div+"</div>" ) ;
	
	// File search
	header_div = "<div id='fs_header_"+ori+"'><table border='0' style='width:100%'><tr><td style='width:100%'><input type='text' name='fs_query_"+ori+"' id='fs_query_"+ori+"' style='width:100%'/></td>" ;
	header_div += "<td><input ori='"+ori+"' id='fs_button_"+ori+"'type='button' value='Search files'/></td></tr></table></div>" ;

	content_div = "<table id='tab_fs_"+ori+"' style='width:100%;position:absolute;top:100px;left:0px;right:0px;bottom:0px;overflow:hidden' border='0'>" ;
	content_div += "<tr><td width='100%' valign='top'><div id='fspics_"+ori+"' style='background:#DDDDDD;overflow:auto'></div></td></tr></table>" ;

	links.push ( "<li><a href='#fs_"+ori+"'>File search</a></li>" ) ;
	divs.push ( "<div id='fs_"+ori+"'>"+header_div+content_div+"</div>" ) ;

	// Category search
	header_div = "<div id='cs_header_"+ori+"'><table border='0' style='width:100%'><tr><td style='width:100%'><input type='text' name='cs_query_"+ori+"' id='cs_query_"+ori+"' style='width:100%'/></td>" ;
	header_div += "<td><input ori='"+ori+"' id='cs_button_"+ori+"'type='button' value='Search categories'/></td></tr></table></div>" ;

	content_div = "<table id='tab_cs_"+ori+"' style='width:100%;position:absolute;top:100px;left:0px;right:0px;bottom:0px;overflow:hidden' border='0'>" ;
	content_div += "<tr><td width='100%' valign='top'><div id='cscandidates_"+ori+"' style='background:#DDDDDD;overflow:auto;height:100px;border:1px solid black'></div></td></tr></table>" ;
	content_div += "<tr><td width='100%' valign='top'><div id='cspics_"+ori+"' style='background:#DDDDDD;overflow:auto;margin-top: 120px;'></div></td></tr></table>" ;

	links.push ( "<li><a href='#cs_"+ori+"'>Category search</a></li>" ) ;
	divs.push ( "<div id='cs_"+ori+"'>"+header_div+content_div+"</div>" ) ;


	
	var html = "<div style='position:absolute;top:0px;bottom:0px;right:0px;left:0px;' id='"+id+"'><ul>"+links.join('')+"</ul>"+divs.join('')+"</div>" ;
	var t = $(html);
	t.appendTo('#'+root) ;
	t.tabs();
	t.tabs( 'select' , 0 ) ;
	t.bind('tabsselect', function(event, ui) {
		ccd[ori]['rc']['timer'] = 0 ;
//		ccd[ori]['curtab'] = cc_tabs[ui.index] ;
//		update_selection_count ( ori ) ;
		if ( ui.index == 2 ) {
			load_rc_files ( ori ) ;
			update_selection_count ( ori ) ;
		}
   	});
	
	// Category
	$('#catname_'+ori).keydown ( function ( event ) { if (event.keyCode == 13) $('#cat_button_'+ori).click(); } ) ;
	$('#cat_button_'+ori).attr('ori',ori);
	$('#cat_button_'+ori).click(function(e){
		var ori = this.id.split('_').pop() ;
		var cat = $('#catname_'+ori).val() ;
		load_category ( cat , ori ) ;
	});
	$('#catpics_'+ori).disableSelection();
	$('#catpics_'+ori).scroll(function(){
		if ( ccd[ori]['cat']['more_available'] == 1 && isScrollBottom ( this , cc_thumb_div_height * 3 ) ) {
			load_files_from_cat ( ori ) ;
		}
	}); 

	// User
	$('#username_'+ori).keydown ( function ( event ) { if (event.keyCode == 13) $('#user_button_'+ori).click(); } ) ;
	$('#user_button_'+ori).attr('ori',ori);
	$('#user_button_'+ori).click(function(e){
		var ori = this.id.split('_').pop() ;
		var user = $('#username_'+ori).val() ;
		load_user_files ( user , ori ) ;
	});
	$('#userpics_'+ori).disableSelection();
	$('#userpics_'+ori).scroll(function(){
		if ( ccd[ori]['user']['more_available'] == 1 && isScrollBottom ( this , cc_thumb_div_height * 3 ) ) {
			load_files_from_user ( ori ) ;
		}
	}); 


	// Recent Changes
	$('#rcpics_'+ori).disableSelection();
	
	
	// File search
	$('#fspics_'+ori).disableSelection();
	$('#fspics_'+ori).scroll(function(){
		if ( ccd[ori]['fs']['more_available'] == 1 && isScrollBottom ( this , cc_thumb_div_height * 3 ) ) {
			load_files_from_search ( ori ) ;
		}
	}); 
	$('#fs_query_'+ori).keydown ( function ( event ) { if (event.keyCode == 13) $('#fs_button_'+ori).click(); } ) ;
	$('#fs_button_'+ori).attr('ori',ori);
	$('#fs_button_'+ori).click(function(e){
		var ori = this.id.split('_').pop() ;
		run_file_search ( ori , true ) ;
	});
	
	// Category search
	$('#cspics_'+ori).disableSelection();
	$('#cspics_'+ori).scroll(function(){
		if ( ccd[ori]['cs']['more_available'] == 1 && isScrollBottom ( this , cc_thumb_div_height * 3 ) ) {
			load_files_from_search ( ori ) ;
		}
	}); 
	$('#cs_query_'+ori).keydown ( function ( event ) { if (event.keyCode == 13) $('#cs_button_'+ori).click(); } ) ;
	$('#cs_button_'+ori).attr('ori',ori);
	$('#cs_button_'+ori).click(function(e){
		var ori = this.id.split('_').pop() ;
		run_category_search ( ori , true ) ;
	});

	// Misc
	$('#catlist_'+ori).click ( function ( e ) {
		e.preventDefault () ;
	} ) ;

	$(cc_tabs).each ( function () {
		$('#'+this+'pics_'+ori).click ( function () {
			button_clear_selection ( ori ) ;
		} ) ;
		$('#tab_'+ori).click ( function () {
			button_clear_selection ( ori ) ;
		} ) ;
	} ) ;
}

function run_category_search ( ori , clear ) {
	if ( clear ) {
		$('#cspics_'+ori).html('');
		$('#cscandidates_'+ori).html('');
		ccd[ori]['cs']['files'] = new Array () ;
	}
	load_categories_from_search ( ori ) ;
}


function show_file_cats ( file , ori ) {
	ccd[ori]['curtab'] = 'cs' ;
	$('#tab_'+ori).tabs( 'select' , 4 ) ;
	$('#cs_query_'+ori).val ( '' ) ;
	$('#cscandidates_'+ori).html ( '' ) ;
	$('#cspics_'+ori).html ( '' ) ;
	
	var url = "http://"+cc_language+"."+cc_project+".org/w/api.php?action=query&prop=categories&cllimit=500&format=json&titles=File:" + escape ( file[0] ) ;
	url += "&callback=?" ;
	loading ( ori , 'loading' , 1 ) ;
	$.getJSON ( url , function ( data ) {
//		alert ( JSON.stringify ( data ) ) ;
		data = data.query ;
		data = data.pages ;
		var d = new Array () ;
		$.each ( data , function ( key , value ) {
			d = value.categories ;
		} ) ;
		if ( d.length == 0 ) {
			loading ( ori , 'loading' , -1 ) ;
			return ;
		}
		var invoke = cs_show_candidates ( ori , d ) ;
		loading ( ori , 'loading' , -1 ) ;
//		if ( invoke != '' ) cs_show_cat_details ( escape ( invoke ) , ori ) ;
	} ) ;
}


function load_categories_from_search ( ori ) {
	if ( ccd[ori]['loading'] > 0 ) return ; // Busy
	ccd[ori]['curtab'] = 'cs' ;
	var query = $('#cs_query_'+ori).val() ;
	
	var url = "http://"+cc_language+"."+cc_project+".org/w/api.php?action=query&list=search&srnamespace=14&srlimit=30&format=json&srsearch=" + escape ( query ) ;
	url += "&callback=?" ;

	loading ( ori , 'loading' , 1 ) ;
	$.getJSON ( url , function ( data ) {
		data = data.query ;
		data = data.search ;
		if ( data.length == 0 ) {
			loading ( ori , 'loading' , -1 ) ;
			return ;
		}
		var invoke = cs_show_candidates ( ori , data ) ;
		loading ( ori , 'loading' , -1 ) ;
		if ( invoke != '' ) cs_show_cat_details ( escape ( invoke ) , ori ) ;
	} ) ;
}

function cs_show_candidates ( ori , data ) {
	var invoke = '' ;
	var html = "<table width='100%' cellspacing=0 cellpadding=0><tr>" ;
	var cnt = 0 ;
	$(data).each ( function () {
		if ( cnt % 3 == 0 ) html += "</tr><tr>" ;
		cnt++ ;
		var title = this.title.split(':') ;
		title.shift() ;
		title = title.join ( ':' ) ;
		if ( invoke == '' ) invoke = title ;
		var oc_browse = "cs_show_cat_details(\""+escape(title)+"\",\""+ori+"\");return false;"
		var oc_cat = "$(\"#tab_"+ori+"\").tabs(\"select\",0) ;load_category(\""+escape(title)+"\",\""+ori+"\");return false;" ;
		html += "<td><a href='#' class='catlink' onclick='"+oc_browse+"'>" + title + "</a>" ;
		html += " <a href='#' onclick='"+oc_cat+"'><img src='"+cc_icon('cats.png')+"' border='0' /></a></td>" ;
	} ) ;
	html += "</tr></table>" ;
	$("#cscandidates_"+ori).html(html);
	return invoke ;
}

function cs_show_cat_details ( category , ori ) {
	category = unescape ( category ) ;
	var id = 'cspics_' + ori ;
	loading ( ori , 'loading2' , 1 ) ;
	var url = ccd['ts_url'] + "&mode=catcontext&category=" + escape ( category ) ;
	$.get ( url , {} , function ( data, textStatus) {
		var html = "<table style='width:100%'>" ;
		var d = data.split("\n");
		var aids = new Array () ;
		for ( var a = 0 ; a < d.length ; a++ ) {
			if ( d[a] == '' ) continue ;
			var x = d[a].split("\t") ;
			var n = x[1] ;

			var oc_browse = "cs_show_cat_details(\""+escape(n)+"\",\""+ori+"\");return false;"
			var oc_cat = "$(\"#tab_"+ori+"\").tabs(\"select\",0) ;load_category(\""+escape(n)+"\",\""+ori+"\");return false;" ;
			
			var link = "<a class='catlink' href='#' onclick='"+oc_browse+"'>"+n+"</a>" ;
			link += " <a href='#' onclick='"+oc_cat+"'><img src='"+cc_icon('cats.png')+"' border='0' /></a>" ;
			var k = '' ;
			if ( x[0] == '0' || x[0] == '1' ) k = "<td colspan='2'>"+link+"</td><td colspan='2'></td>" ;
			else if ( x[0] == '2' ) k = "<td></td><td colspan='2'><b>"+link+"</td><td></td>" ;
			else if ( x[0] == '3' ) k = "<td colspan='2'></td><td colspan='2'>"+link+"</td>" ;
			html += "<tr>" + k + "</tr>" ;
		}
		html += "</table>" ;
		$('#'+id).html(html);
		loading ( ori , 'loading2' , -1 ) ;
	} , 'text' ) ;
}

function run_file_search ( ori , clear ) {
	if ( clear ) {
		$('#fspics_'+ori).html('');
		ccd[ori]['fs']['files'] = new Array () ;
		ccd[ori]['fs']['offset'] = 0 ;
	}
	load_files_from_search ( ori ) ;
}

function load_files_from_search ( ori ) {
	if ( ccd[ori]['loading'] > 0 ) return ; // Busy
	ccd[ori]['curtab'] = 'fs' ;
	ccd[ori]['fs']['more_available'] = 0 ;
	var dispid = 'fspics_' + ori ;
	ccd[ori]['thumbdiv'] = dispid ;
	var query = $('#fs_query_'+ori).val() ;
	
	ccd[ori]['fs']['limit'] = 50 ;
	var url = ccd['ts_url'] + "&mode=filesearch&query=" + escape ( query ) + "&offset=" + ccd[ori]['fs']['offset'] + "&limit=" + ccd[ori]['fs']['limit'] ;

	loading ( ori , 'loading' , 1 ) ;
	$.get ( url , {} , function ( data, textStatus) {
		var d2 = data.split("\n") ;
		var cnt = 0 ;
		for ( var a = 0 ; a < d2.length ; a++ ) {
			if ( d2[a] == '' ) continue ;
			cnt++ ;
			var d = d2[a].split("\t") ;
			var filenumber = ccd[ori]['fs']['files'].length ;
			ccd[ori]['fs']['files'].push ( d ) ;
			add_file ( dispid , filenumber , ori , 'fs' ) ;
		}
		ccd[ori]['fs']['more_available'] = cnt >= ccd[ori]['fs']['limit'] ;
		ccd[ori]['fs']['offset'] += cnt ;
		loading ( ori , 'loading' , -1 ) ;
	} , 'text' ) ;
}






function isScrollBottom ( obj , before ) {
	return $(obj).scrollTop() >= $(obj).attr("scrollHeight") - $(obj).outerHeight() - before ;
}


function ucfirst ( str ) {
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1);
}

// THIRD PARTY CODE

// BEGIN getURLParam function
/* Copyright (c) 2006 Mathias Bank (http://www.mathias-bank.de)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * Thanks to Hinnerk Ruemenapf - http://hinnerk.ruemenapf.de/ for bug reporting and fixing.
 */
jQuery.extend({
/**
* Returns get parameters.
*
* If the desired param does not exist, null will be returned
*
* @example value = $.getURLParam("paramName");
*/ 
 getURLParam: function(strParamName,defaultValue){
	  var strReturn = "";
	  var strHref = window.location.href;
	  var bFound=false;
	  
	  var cmpstring = strParamName + "=";
	  var cmplen = cmpstring.length;

	  if ( strHref.indexOf("?") > -1 ){
	    var strQueryString = strHref.substr(strHref.indexOf("?")+1);
	    var aQueryString = strQueryString.split("&");
	    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
	      if (aQueryString[iParam].substr(0,cmplen)==cmpstring){
	        var aParam = aQueryString[iParam].split("=");
	        strReturn = aParam[1];
	        bFound=true;
	        break;
	      }
	      
	    }
	  }
	  if (bFound==false) return defaultValue;
	  return strReturn;
	}
});
// END getURLParam function


// BEGIN COOKIE SCRITPS
// FROM http://www.quirksmode.org/js/cookies.html

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return '';
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

// END COOKIE SCRITPS



// BEGIN TRIM

/**
*
*  Javascript trim, ltrim, rtrim
*  http://www.webtoolkit.info/
*
**/
 
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

// END TRIM



// Icons from http://commons.wikimedia.org/wiki/Category:Bluesphere_SVG_icons
