function randomString(length) {
	var chars = "abcdefABCDEF0123456789";
	var randomstring = '';
	for (var i=0; i < length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

window.addEvent('domready', function()
{
	// js menu
	var menuObj = new MenuMatic( { hideDelay: 250 } );
	
	var checkall = $('checkall');
	if(checkall != null)
	{
		checkall.addEvent('click', function() {
			if(checkall.getProperty("checked") == true) 
			{
				$$('.checkbox').each(function(box) {
					box.checked = true;
				});
			} 
			else
			{
				$$('.checkbox').each(function(box) {
					box.checked = false;
				});
			}
		});
	}
	
	var confirm_prompt = $$('.confirm_prompt');
	if(confirm_prompt != null)
	{
		confirm_prompt.each(function(item) {
			item.addEvent('click', function(e) {
				if(!confirm(item.get('rel')))
				{
					e = new Event(e);
					e.preventDefault();
				}
			});
		});
	}
	
	var tab_list = $('tab_submenu');
	if(tab_list != null)
	{
		var tab_fx_list = Array();
		var item_id;
		var item_fx;
		var active_id = null;
		var last_update = new Date().getTime() / 100;

		if($('default') != null)
		{
			active_id = $('default').getChildren('a');
			active_id.addClass('active');
		}
		
		tab_list.getChildren('li').each(function(item) {
			var slider = item.getChildren('a');
			item_id = slider.get('id');
			tab_fx_list[item_id] = new Fx.Slide($(item_id+'_wrapper'));
			if(active_id != null && item_id.toString() == active_id.get('id').toString())
			{
				tab_fx_list[item_id].slideIn();
			}
			else
			{
				tab_fx_list[item_id].slideOut();
			}
					
			slider.addEvent('click', function(e) {
				e = new Event(e);
				e.preventDefault();
				if(((new Date().getTime() / 100) - last_update) < 10)
				{
					return;
				}
				if(slider.get('id').toString() == active_id.get('id').toString())
					return;
				tab_fx_list[active_id.get('id')].slideOut();
				active_id.removeClass('active');
				active_id = slider;
				active_id.addClass('active');
				tab_fx_list[active_id.get('id')].slideIn();
				last_update = (new Date().getTime() / 100);
			});
		});
		tab_fx_list[active_id.get('id')].slideIn();
	}
	
	var media_image_code = $$('.media_image_code');
	if(media_image_code != null)
	{
		media_image_code.each(function(item) {
			item.addEvent('click', function(e) {
				item.select();
			});
		});
	}
	if($('calendar_start_date') != null)
	{
		new DatePicker('.calendar_start_popup', {
			'allowEmpty': true,
			'inputOutputFormat': 'Y/m/d',
			'format': 'Y/m/d',
			'startDay': 0
		});	
	}
	
	if($('calendar_end_date') != null)
	{
		new DatePicker('.calendar_end_popup', {
			'allowEmpty': true,
			'inputOutputFormat': 'Y/m/d',
			'format': 'Y/m/d',
			'startDay': 0
		});	
	}
	
	if($('search_advanced') != null)
	{
		var advanced_options = new Fx.Slide('search_advanced_wrapper').slideOut();
		$('search_advanced_wrapper').setStyle('display', 'inline');
		$('search_advanced_toggle').addEvent('click', function(e) {
			e = new Event(e);
			e.preventDefault();
			advanced_options.toggle();
		});
	}
	
	if($('rank_permissions') != null)
	{
		$$('#rank_permissions li').each(function(current) {
			var checkall = current.getElement('.check_all');
			checkall.addEvent('click', function(e) {
				if(checkall.getProperty("checked") == true) 
				{
					current.getChildren().each(function(child) {
						if(child.hasClass('checkable'))
							child.getElement('input').checked = true;
					});
				} 
				else
				{
					current.getChildren().each(function(child) {
						if(child.hasClass('checkable'))
							child.getElement('input').checked = false;
					});
				}
			});
		});
	}
	
	if($('clan_template_list') != null)
	{
		var template_window = $('template_window');
		var template_list = $('template_window_ranks');
		var rank_list = $('rank_list');
		var rank_sort = $('rank_sort');
		var template_data = null;
		var rank_sort_array = new Array();
		var template_window_body = $('template_window_body');
		// center the template rank window
		var browserSize = $(document.body).getSize();	
		var window_size = template_window.getDimensions(true);
		template_window.setStyles({
			'left':  (browserSize.x / 2) - (window_size.x / 2),
			'top': ((browserSize.y / 2) - (window_size.y / 2) - 100)
		});
		
		var sortable = new Sortables('rank_list', {
			clone: false,
			revert: true,
			onComplete: function(el) {
				reZebra();
			}
		});	

		$$('#rank_list li').each(function(current_rank) {
			var rankDelete = current_rank.getElement('.rank_delete');
			
			var rankName = current_rank.getElement('.rank_name');
			var rankNameValue = rankName.get('text');
			rankName.set('text', '');
			var text_box = new Element('span', { 'text': rankNameValue }).inject(rankName);
			var edit_box = new Element('input', { 'type': 'text', 'name': 'rank_name[]', 'class': 'rank_name_edit', 'value': rankNameValue }).inject(rankName);
			
			text_box.addEvent('click', function(e) {
				var start_text = text_box.get('text');
				sortable.removeItems(current_rank);
				edit_box.set('value', text_box.get('text'));
				edit_box.setStyle('display', 'inline');
				text_box.setStyle('display', 'none');
				edit_box.focus();
				edit_box.addEvent('blur', function(event) {
					edit_box.setStyle('display', 'none');
					if(edit_box.get('value').length == 0)
						edit_box.set('value', start_text);
					else
						start_text = edit_box.get('value')
					text_box.set('text', start_text);
					sortable.addItems(current_rank);
					text_box.setStyle('display', 'inline');
					edit_box.removeEvent('blur');
				});
			});
			
			rankDelete.addEvent('click', function(e) {
				rankDelete.removeEvent('click');
				current_rank.dispose();
				reZebra();	
			});
		});
		
		$('addRank').addEvent('submit', function(e) {
			e.preventDefault();	
			var rank_value = $('newRank').value;
			if(rank_value == "")
				return;
			addRank(rank_value);

			$('newRank').set('value', '');
			reZebra();
		});
		
		$('rank_submit').addEvent('submit', function(e) {
			rank_sort_array.empty();
			$$('#rank_list .rank_id').each(function(id) {
				rank_sort_array.include(id.get('value'));
			});
			rank_sort.set('value', rank_sort_array.join(','));	
		});
	
		$('template_window_close').addEvent('click', function(e) {
			template_window.hide();
		});
		
		$('template_window_add').addEvent('click', function(e) {
			template_data.each(function(rank) {
				addRank(rank.value);
			});
			
			if(template_list != null)
				template_list.dispose();

			reZebra();
			template_window.hide();
		});
		
		$('template_window_replace').addEvent('click', function(e) {
			$$('#rank_list li').each(function(rank) {
				rank.dispose();
			});
			
			template_data.each(function(rank) {
				addRank(rank.value);
			});
			if(template_list != null)
				template_list.dispose();

			reZebra();	
			template_window.hide();
		});
		
		// add event listener to each template link
		$$('.clan_template').each(function(item) {
			item.addEvent('click', function(e) {
				e.preventDefault();
							
				template_window.setStyle('display', 'none');

				new Request.JSONP({
					callBackKey: 'callback',
					url: 'http://data.d3clans.com/getRankTemplate.php',
					data: {
						'template': item.get('id')
					},
					onRequest: function() { 
						template_window.addClass('json_loading');
					},
					onComplete: function(response) {
						
						// delete existing ul of ranks
						var template_list = $('template_window_ranks');
						if(template_list != null)
							template_list.dispose();
						
						// create new ul
						template_list = new Element('ul', { 'id': 'template_window_ranks' }).inject(template_window_body, 'top');
					
						// parse json and add li of ranks to ul
						template_data = response.ranks.rank;
						template_data.each(function(rank) {
							var li_rank = new Element('li').inject(template_list);
							var div_value = new Element('div', { 'text': rank.value }).inject(li_rank);
						});
						
						template_window.setStyle('display', 'block');
					}
				}).send();
			});
		});
		
		function addRank(rank)
		{
			var new_id = randomString(10);
			var li_rank = new Element('li', { 'class': 'rank_sort subheader_row_2' } ).inject(rank_list);
			var div_select = new Element('div', { 'class': 'rank_select' }).inject(li_rank);
			var radio_button = new Element('input', { 'type': 'radio', 'name': 'default', 'value': new_id }).inject(div_select);
			var div_value = new Element('div', { 'class': 'rank_name' }).inject(li_rank);
			var text_box = new Element('span', { 'text': rank }).inject(div_value);
			var edit_box = new Element('input', { 'type': 'text', 'name': 'rank_name[]', 'class': 'rank_name_edit', 'value': rank }).inject(div_value);
			var div_action = new Element('div',{ 'class': 'rank_action' }).inject(li_rank);
			var hidden_id = new Element('input', { 'type': 'hidden', 'class': 'rank_id', 'name': 'rank_id[]', 'value': new_id }).inject(div_action);
			var link_delete = new Element('a', { 'class': 'rank_delete', 'text': 'Delete' }).inject(div_action);
			sortable.addItems(li_rank);
			
			text_box.addEvent('click', function(e) {
				var start_text = text_box.get('text');
				sortable.removeItems(li_rank);
				edit_box.set('value', text_box.get('text'));
				edit_box.setStyle('display', 'inline');
				text_box.setStyle('display', 'none');
				edit_box.focus();
				edit_box.addEvent('blur', function(event) {
					edit_box.setStyle('display', 'none');
					if(edit_box.get('value').length == 0)
						edit_box.set('value', start_text);
					else
						start_text = edit_box.get('value')
					text_box.set('text', start_text);
					sortable.addItems(li_rank);
					text_box.setStyle('display', 'inline');
					edit_box.removeEvent('blur');
				});
			});
			
			link_delete.addEvent('click', function(e) {
				link_delete.removeEvent('click');
				li_rank.dispose();
				reZebra();	
			});
		}
		
		function reZebra()
		{
			var cur_element = null;
			var zebra_flag = true;
			$$('.rank_sort').each(function(row) {	
				if(row.hasClass('subheader_row_2'))
					row.removeClass('subheader_row_2');
				if(row.hasClass('subheader_row_1'))
					row.removeClass('subheader_row_1');
					
				if(zebra_flag)
					row.addClass('subheader_row_2');
				else
					row.addClass('subheader_row_1');
				zebra_flag = !zebra_flag;
			});
		}
	}
	
	if($('media_manage_images') != null)
	{
		var gallery_box = $('create_gallery_box');
		var create_button = $('create_gallery_button');
		var browserSize = $(document.body).getSize();	
		var window_size = gallery_box.getDimensions(true);
		gallery_box.setStyles({
			'left':  (browserSize.x / 2) - (window_size.x / 2),
			'top': (browserSize.y / 2) - (window_size.y / 2)
		});
		
		create_button.addEvent('click', function(e) {
			gallery_box.setStyle('display', 'block');
		});
	}
	
	var links_add_menu = $('links_add_menu');
	if(links_add_menu != null)
	{
		var links_add_menu 	= $('links_add_menu');
		var links_edit_menu = $('links_edit_menu');
		var link_add_form 	= $('link_add_form');
		var add_button 		= $('add_button');
		var link_add_url 	= $('add_url');
		var link_add_label 	= $('add_label');
		var links_table 	= $('links_table');
		var link_type		= $('link_type');
		var edit_button		= $('edit_button');
		var edit_url 		= $('edit_url');
		var edit_label 		= $('edit_label');
		var	edit_id			= $('edit_id');
		var cancel_button	= $('cancel_button');
		var delete_button	= $('delete_button');
		var success_div		= $('success');
		var failure_div		= $('failure');
		var no_links_found 	= $('no_links_found');
		var current_edit	= null;

		$$('.stop_edit_link').addEvent('click', function(event){ new Event(event).preventDefault().stopPropagation(); });
		
		$$('.edit_link').each(function(item) {
			item.addEvent('click', function(event) {
				initEdit(item);
			});
		});

		cancel_button.addEvent('click', function() {
			cancelEdit()
		});	
		
		add_button.addEvent('click', function(event)
		{
			new Event(event).preventDefault().stopPropagation();
			
			new Request.JSONP({
				callBackKey: 'callback',
				url: 'http://data.d3clans.com/addLink.php',
				data: {
					'type':		link_type.get('value'),
					'url':		link_add_url.get('value'),
					'label':	link_add_label.get('value')
				},
				onComplete: function(response) 
				{
					if(response.response.success == 'true')
					{
						if(no_links_found != null)
							no_links_found.dispose();
							
						var tr = new Element('tr', { 'class': 'link_row' } ).inject(links_table.getElement('tbody'));
						var td_checkbox = new Element('td').inject(tr);
						var input_checkbox = new Element('input', { 'type': 'checkbox', 'class': 'checkbox', 'name': 'link_id[]', 'value': response.response.link_id }).inject(td_checkbox);
						var td_url = new Element('td').inject(tr);
						var span_url = new Element('span', { 'title': link_add_url.get('value'), 'text': link_add_url.get('value'), 'class': 'select_link_url' }).inject(td_url);
						var td_label = new Element('td').inject(tr);
						var span_label = new Element('span', { 'title': link_add_label.get('value'), 'text': link_add_label.get('value'), 'class': 'select_link_label' }).inject(td_label);
						var td_action = new Element('td').inject(tr);
						var a_action = new Element('a', { 'id': response.response.link_id, 'class': 'edit_link', 'text': $('edit_button_label').get('value') }).inject(td_action);
						
						a_action.addEvent('click', function(item){
							initEdit(a_action);
						});
						
						success_div.set('text', response.response.message);
						success_div.setStyles({ 'display': 'block', 'opacity': 0});
						new Fx.Tween(success_div, {
							'duration': '2000',
							'property': 'opacity',
							'link': 'chain'
						}).start(100).wait(100).start(0).chain(function(){ 
							success_div.setStyle('display', 'none'); 
							success_div.set('text', '');
						});
						reZebra();
						
					}
					else
					{
						failure_div.set('text', response.response.error);
						failure_div.setStyles({ 'display': 'block', 'opacity': 0});
						new Fx.Tween(failure_div, {
							'duration': '2000',
							'property': 'opacity',
							'link': 'chain'
						}).start(100).wait(100).start(0).chain(function(){ 
							failure_div.setStyle('display', 'none'); 
							failure_div.set('text', '');
						});
					}
					link_add_url.set('value', ''),
					link_add_label.set('value', '')
					link_add_form.setStyle('display', 'block');					
				}
			}).send();
		});
		
		edit_button.addEvent('click', function(event)
		{
			new Event(event).preventDefault().stopPropagation();
			$$('.edit_link').each(function(item) {
				item.removeEvent('click');
			});
						
			new Request.JSONP({
				callBackKey: 'callback',
				url: 'http://data.d3clans.com/editLink.php',
				data: {
					'id':		edit_id.get('value'),
					'url':		edit_url.get('value'),
					'label':	edit_label.get('value')
				},
				onComplete: function(response) 
				{
					if(response.response.success == 'true')
					{
						var parent	= current_edit.getParent('tr');
						parent.getElement('.select_link_url').set('text', edit_url.get('value'));
						parent.getElement('.select_link_label').set('text', edit_label.get('value'));					  						

						success_div.set('text', response.response.message);
						success_div.setStyles({ 'display': 'block', 'opacity': 0});
						new Fx.Tween(success_div, {
							'duration': '2000',
							'property': 'opacity',
							'link': 'chain'
						}).start(100).wait(100).start(0).chain(function(){ 
							success_div.setStyle('display', 'none'); 
							success_div.set('text', '');
						});
						cancelEdit();
					}
					else
					{
						failure_div.set('text', response.response.error);
						failure_div.setStyles({ 'display': 'block', 'opacity': 0});
						new Fx.Tween(failure_div, {
							'duration': '2000',
							'property': 'opacity',
							'link': 'chain'
						}).start(100).wait(100).start(0).chain(function(){ 
							failure_div.setStyle('display', 'none'); 
							failure_div.set('text', '');
						});
					}
				}
			}).send();
			
			$$('.edit_link').each(function(item) {
				item.addEvent('click', function() {
					initEdit(item);
				});
			});
		});
		
		delete_button.addEvent('click', function(event)
		{
			new Event(event).preventDefault().stopPropagation();
			
			if(confirm('Are you sure you want to delete the selected link(s)?'))
			{
				var ids = new Array();
				$$('.checkbox').each(function(box) {
					if(box.checked)
						ids.push(box.get('value'));
				});
				new Request.JSONP({
					callBackKey: 'callback',
					url: 'http://data.d3clans.com/deleteLinks.php',
					data: {
						'id': ids
					},
					onComplete: function(response) 
					{
						if(response.response.success == 'true')
						{
							$$('.checkbox').each(function(box) {
								if(ids.contains(box.get('value')))
									box.getParent('tr').dispose();
							});
							success_div.set('text', response.response.message);
							success_div.setStyles({ 'display': 'block', 'opacity': 0});
							new Fx.Tween(success_div, {
								'duration': '2000',
								'property': 'opacity',
								'link': 'chain'
							}).start(100).wait(100).start(0).chain(function(){ 
								success_div.setStyle('display', 'none'); 
								success_div.set('text', '');
							});
							reZebra();
						}
						else
						{
							failure_div.set('text', response.response.error);
							failure_div.setStyles({ 'display': 'block', 'opacity': 0});
							new Fx.Tween(failure_div, {
								'duration': '2000',
								'property': 'opacity',
								'link': 'chain'
							}).start(100).wait(100).start(0).chain(function(){ 
								failure_div.setStyle('display', 'none'); 
								failure_div.set('text', '');
							});
						}
					}
				}).send();
			}
		});
		function initEdit(item)
		{
			current_edit = item;
			var parent	= item.getParent('tr');
			edit_url.set('value', parent.getElement('.select_link_url').get('text'));
			edit_label.set('value', parent.getElement('.select_link_label').get('text'));
			edit_id.set('value', item.get('id'));
			links_add_menu.setStyle('display', 'none');
			links_edit_menu.setStyle('display', 'block');
		}
		
		function cancelEdit()
		{
			edit_url.set('value', '');
			edit_label.set('value', '');
			edit_id.set('value', '');
			links_add_menu.setStyle('display', 'block');
			links_edit_menu.setStyle('display', 'none');
		}
		
		function reZebra()
		{
			var cur_element = null;
			var zebra_flag = true;
			$$('.link_row').each(function(row) {			
				if(row.hasClass('subheader_row_2'))
					row.removeClass('subheader_row_2');
				if(row.hasClass('subheader_row_1'))
					row.removeClass('subheader_row_1');
					
				if(zebra_flag)
					row.addClass('subheader_row_2');
				else
					row.addClass('subheader_row_1');
				zebra_flag = !zebra_flag;
			});
		}
	}



	var manage_images_menu = $('manage_images_menu');
	if(manage_images_menu != null)
	{
		var js_form			= $('js_form');
		var upload_menu		= $('image_upload_menu');
		var inner_add_images= $('inner_add_images');
		var images_list		= $('manage_images_list');
		var image_link		= $('image_link').get('value');
		var images_shown	= $('images_shown');
	 	var load_images		= $('load_images');
	 	var type			= $('type');
	 	var type_id			= $('type_id');
	 	var results			= $('results');
		var json_loaded 	= 0;
		var checkall 		= $$('.checkall');		
		var checkall_toggle = true;
		var delete_button	= $$('.delete_button');
		var success_div		= $('success');
		var failure_div		= $('failure');
		var no_images_found	= $('no_images_found');
		
		if(checkall != null)
		{
			checkall.each(function(button) {
				button.addEvent('click', function() {
					if(checkall_toggle) 
					{
						$$('.checkbox').each(function(box) {
							box.checked = true;
						});
						checkall_toggle = false;
					} 
					else
					{
						$$('.checkbox').each(function(box) {
							box.checked = false;
						});
						checkall_toggle = true;
					}
				});
			});
		}
			
	 	if(js_form != null)
		{
			var up = new FancyUpload2($('upload_status'), $('upload_progress'), { // options object
				// we console.log infos, remove that in production!!
				verbose: true,
		 
				// url is read from the form, so you just have to change one place
				url: $('upload_procssor').action,
		 
				// path to the SWF file
				path: 'http://d3clans.com/flash/Swiff.Uploader.swf',
		 
				// remove that line to select all files, or edit it, add more items
				typeFilter: {
					'Images (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.gif; *.png'
				},
		 
				// this is our browse button, *target* is overlayed with the Flash movie
				target: 'upload_browse',
								
				// append cookie data to request
		 		appendCookieData: true,
				
				// graceful degradation, onLoad is only called if all went well with Flash
				onLoad: function() {
					$('upload_status').removeClass('hide'); // we show the actual UI
					$('no_js_form').destroy(); // ... and hide the plain form
		 
					// We relay the interactions with the overlayed flash to the link
					this.target.addEvents({
						click: function() {
							return false;
						},
						mouseenter: function() {
							this.addClass('hover');
						},
						mouseleave: function() {
							this.removeClass('hover');
							this.blur();
						},
						mousedown: function() {
							this.focus();
						}
					});
		 
					// Interactions for the 2 other buttons
		 
					$('upload_clear').addEvent('click', function() {
						up.remove(); // remove all files
						return false;
					});
		 
					$('upload_start').addEvent('click', function() {
						up.start(); // start upload
						return false;
					});
				},
		 
				onSelectFail: function(files) {
					files.each(function(file) {
						new Element('li', {
							'class': 'validation-error',
							html: file.validationErrorMessage || file.validationError,
							title: MooTools.lang.get('FancyUpload', 'removeTitle'),
							events: {
								click: function() {
									this.destroy();
								}
							}
						}).inject(this.list, 'top');
					}, this);
				},
		 
				/**
				 * This one was directly in FancyUpload2 before, the event makes it
				 * easier for you, to add your own response handling (you probably want
				 * to send something else than JSON or different items).
				 */
				onFileSuccess: function(file, response) {
					var json = null;
					imageUploadResult = function(data){
						json = data;
					};
					eval(response);					
				
					if(json.response.success == 'true') {
						file.element.addClass('file-success');
						file.info.set('html', '<strong>Image was uploaded:</strong> (' + json.response.width + ' x ' + json.response.height + 'px, <em>' + json.response.filetype + '</em>)');
						if(images_shown.get('value') == 0)
							no_images_found.setStyle('display', 'none');
						addImage(json.response);
						images_shown.set('value', images_shown.get('value').toInt()+1);
					} else {
						file.element.addClass('file-failed');
						file.info.set('html', '<strong>Error:</strong> ' + (json.response.error ? json.response.error : response));
					}
				},
		 
				/**
				 * onFail is called when the Flash movie got bashed by some browser plugin
				 * like Adblock or Flashblock.
				 */
				onFail: function(error) {
					switch (error) {
						case 'hidden': // works after enabling the movie and clicking refresh
							alert('To enable the embedded uploader, unblock it in your browser and refresh (see Adblock).');
							break;
						case 'blocked': // This no *full* fail, it works after the user clicks the button
							alert('To enable the embedded uploader, enable the blocked Flash movie (see Flashblock).');
							break;
						case 'empty': // Oh oh, wrong path
							alert('A required file was not found, please be patient and we fix this.');
							break;
						case 'flash': // no flash 9+ :(
							alert('To enable the embedded uploader, install the latest Adobe Flash plugin.')
					}
				}
		 
			});
			
			var menu_toggler = new Element('div', { 'id': 'image_menu_toggler', 'text': 'Hide' });
			inner_add_images.grab(menu_toggler);
			var menuSlider = new Fx.Slide('image_upload_menu').slideIn();
			var toggle_state = false;
			menu_toggler.addEvent('click', function(e) {
				if(toggle_state)
				{
					menuSlider.slideIn();
					menu_toggler.set('text', 'Hide');
					toggle_state = false;
				}
				else
				{
					menuSlider.slideOut();
					menu_toggler.set('text', 'Show');
					toggle_state = true;
				}
			});
		}		
		
		load_images.addEvent('click', function(event)
		{
			new Request.JSONP({
				callBackKey: 'callback',
				url: 'http://data.d3clans.com/getImages.php',
				data: {
					'type':	type.get('value'),
					'type_id': type_id.get('value'),
					'start': images_shown.get('value'),
					'results': results.get('value')
				},
				onComplete: function(response) 
				{
					
					if(response.response.success == 'true')
					{
						json_loaded = 0;
						if($type(response.response.image) == 'array')
						{
							response.response.image.each(function(item) {
								addImage(item);
								json_loaded++;
							});
						}
						else
						{
							addImage(response.response.image);
							json_loaded++;
						}
						images_shown.set('value', images_shown.get('value').toInt()+json_loaded);
						
						if(json_loaded != results.get('value'))
						{
							load_images.removeEvent('click');
							load_images.addClass('deactivated');
						}
					}	
					else
					{
						load_images.removeEvent('click');
						load_images.addClass('deactivated');
					}
				}
			}).send();
		});
		
		delete_button.each(function(button) {
			button.addEvent('click', function(event)
			{
				new Event(event).preventDefault().stopPropagation();
				
				if(confirm('Are you sure you want to delete the selected image(s)?'))
				{
					var ids = new Array();
					$$('.checkbox').each(function(box) {
						if(box.checked)
							ids.push(box.get('value'));
					});
					
					new Request.JSONP({
						callBackKey: 'callback',
						url: 'http://data.d3clans.com/deleteImages.php',
						data: {
							'id': ids
						},
						onComplete: function(response) 
						{
							if(response.response.success == 'true')
							{
								$$('.checkbox').each(function(box) {
									if(ids.contains(box.get('value')))
										box.getParent('div.media_image_item').dispose();
								});
								success_div.set('text', response.response.message);
								success_div.setStyles({ 'display': 'block', 'opacity': 0});
								new Fx.Tween(success_div, {
									'duration': '2000',
									'property': 'opacity',
									'link': 'chain'
								}).start(100).wait(100).start(0).chain(function(){ 
									success_div.setStyle('display', 'none'); 
									success_div.set('text', '');
								});
								images_shown.set('value', images_shown.get('value').toInt()-ids.length);
								if(images_shown.get('value').toInt() == 0)
								{
									no_images_found.setStyle('display', 'block');
								}
							}
							else
							{
								failure_div.set('text', response.response.error);
								failure_div.setStyles({ 'display': 'block', 'opacity': 0});
								new Fx.Tween(failure_div, {
									'duration': '2000',
									'property': 'opacity',
									'link': 'chain'
								}).start(100).wait(100).start(0).chain(function(){ 
									failure_div.setStyle('display', 'none'); 
									failure_div.set('text', '');
								});
							}
						}
					}).send();
				}
			});
		});
		
		function addImage(element)
		{
			var div = new Element('div', { 'class': 'media_image_item' } ).inject(images_list, 'top');
			var label = new Element('label', { 'for': 'image_'+element.external_id } ).inject(div);
			var a_link = new Element('a', { 'href': image_link+element.external_id } ).inject(label);
			if(element.width > 150 || element.height > 150)
				var img = new Element('img', { 'src': 'http://images.d3clans.com/thumbnail/'+element.external_id, 'class': 'media_image_item_img' } ).inject(a_link);
			else
				var img = new Element('img', { 'src': 'http://images.d3clans.com/'+element.external_id, 'class': 'media_image_item_img' } ).inject(a_link);
			var checkbox = new Element('input', { 'type': 'checkbox', 'class': 'media_image_checkbox checkbox', 'name': 'images[]', 'value': element.external_id, 'id': 'image_'+element.external_id } ).inject(div);	
		}
	}



	var video_add_menu = $('video_add_menu');
	if(video_add_menu != null)
	{
		var video_edit_menu	= $('video_edit_menu');
		var video_add_form 	= $('video_add_form');
		var add_button 		= $('add_button');
		var video_add_url 	= $('add_url');
		var video_add_title = $('add_title');
		var video_add_desc 	= $('add_desc');
		var videos_table 	= $('videos_table');
		var video_type		= $('video_type');
		var edit_button		= $('edit_button');
		var edit_title 		= $('edit_title');
		var edit_desc 		= $('edit_desc');
		var	edit_id			= $('edit_id');
		var cancel_button	= $('cancel_button');
		var delete_button	= $('delete_button');
		var success_div		= $('success');
		var failure_div		= $('failure');
		var no_videos_found = $('no_videos_found');
		var current_edit	= null;

		$$('.stop_edit_video').addEvent('click', function(event){ new Event(event).preventDefault().stopPropagation(); });
		
		$$('.edit_link').each(function(item) {
			item.addEvent('click', function(event) {
				initEdit(item);
			});
		});

		cancel_button.addEvent('click', function() {
			cancelEdit()
		});	
		
		add_button.addEvent('click', function(event)
		{
			new Event(event).preventDefault().stopPropagation();
			
			new Request.JSONP({
				callBackKey: 'callback',
				url: 'http://data.d3clans.com/addVideo.php',
				data: {
					'type':		video_type.get('value'),
					'url':		video_add_url.get('value'),
					'encoded_url':		escape(video_add_url.get('value')),
					'title':	video_add_title.get('value'),
					'desc':		video_add_desc.get('value')
				},
				onComplete: function(response) 
				{
					if(response.response.success == 'true')
					{
						if(no_videos_found != null)
							no_videos_found.setStyle('display', 'none');
							
						var tr = new Element('tr', { 'class': 'video_row' } ).inject(videos_table.getElement('tbody'));
						var td_checkbox = new Element('td').inject(tr);
						var input_checkbox = new Element('input', { 'type': 'checkbox', 'class': 'checkbox', 'name': 'video_id[]', 'value': response.response.video_id }).inject(td_checkbox);
						var hidden_desc = new Element('input', { 'value': video_add_desc.get('value'), 'class': 'select_video_desc', 'type': 'hidden' }).inject(td_checkbox);
						var td_title = new Element('td').inject(tr);
						var span_title = new Element('span', { 'title': video_add_title.get('value'), 'text': video_add_title.get('value'), 'class': 'select_video_title' }).inject(td_title);
						var td_action = new Element('td').inject(tr);
						var a_action = new Element('a', { 'id': response.response.video_id, 'class': 'edit_link', 'text': $('edit_button_label').get('value') }).inject(td_action);
						var spacer = new Element('span', { 'style': 'width: 10px; display: inline-block;' }).inject(td_action);
						var a_view = new Element('a', { 'text': $('view_button_label').get('value'), 'href': $('view_link').get('value')+response.response.video_id }).inject(td_action);
						
						a_action.addEvent('click', function(item){
							initEdit(a_action);
						});
						
						success_div.set('text', response.response.message);
						success_div.setStyles({ 'display': 'block', 'opacity': 0});
						new Fx.Tween(success_div, {
							'duration': '2000',
							'property': 'opacity',
							'link': 'chain'
						}).start(100).wait(100).start(0).chain(function(){ 
							success_div.setStyle('display', 'none'); 
							success_div.set('text', '');
						});
						video_add_url.set('value', '');
						video_add_title.set('value', '');
						video_add_desc.set('value', '');
						reZebra();
					}
					else
					{
						failure_div.set('text', response.response.error);
						failure_div.setStyles({ 'display': 'block', 'opacity': 0});
						new Fx.Tween(failure_div, {
							'duration': '2000',
							'property': 'opacity',
							'link': 'chain'
						}).start(100).wait(100).start(0).chain(function(){ 
							failure_div.setStyle('display', 'none'); 
							failure_div.set('text', '');
						});
					}
				}
			}).send();
		});

		edit_button.addEvent('click', function(event)
		{
			new Event(event).preventDefault().stopPropagation();
			$$('.edit_link').each(function(item) {
				item.removeEvent('click');
			});

			new Request.JSONP({
				callBackKey: 'callback',
				url: 'http://data.d3clans.com/editVideo.php',
				data: {
					'id':		edit_id.get('value'),
					'title':	edit_title.get('value'),
					'desc':		edit_desc.get('value')
				},
				onComplete: function(response) 
				{
					if(response.response.success == 'true')
					{
						var parent	= current_edit.getParent('tr');
						parent.getElement('.select_video_title').set('text', edit_title.get('value'));	
						parent.getElement('.select_video_desc').set('value', edit_desc.get('value'));

						success_div.set('text', response.response.message);
						success_div.setStyles({ 'display': 'block', 'opacity': 0});
						new Fx.Tween(success_div, {
							'duration': '2000',
							'property': 'opacity',
							'link': 'chain'
						}).start(100).wait(100).start(0).chain(function(){ 
							success_div.setStyle('display', 'none'); 
							success_div.set('text', '');
						});
						cancelEdit();
					}
					else
					{
						failure_div.set('text', response.response.error);
						failure_div.setStyles({ 'display': 'block', 'opacity': 0});
						new Fx.Tween(failure_div, {
							'duration': '2000',
							'property': 'opacity',
							'link': 'chain'
						}).start(100).wait(100).start(0).chain(function(){ 
							failure_div.setStyle('display', 'none'); 
							failure_div.set('text', '');
						});
					}
				}
			}).send();
			
			$$('.edit_link').each(function(item) {
				item.addEvent('click', function() {
					initEdit(item);
				});
			});
		});
		
		
		delete_button.addEvent('click', function(event)
		{
			new Event(event).preventDefault().stopPropagation();
			
			if(confirm('Are you sure you want to delete the selected video(s)?'))
			{
				var ids = new Array();
				$$('.checkbox').each(function(box) {
					if(box.checked)
						ids.push(box.get('value'));
				});
				new Request.JSONP({
					callBackKey: 'callback',
					url: 'http://data.d3clans.com/deleteVideos.php',
					data: {
						'id': ids
					},
					onComplete: function(response) 
					{
						if(response.response.success == 'true')
						{
							$$('.checkbox').each(function(box) {
								if(ids.contains(box.get('value')))
									box.getParent('tr').dispose();
							});
							success_div.set('text', response.response.message);
							success_div.setStyles({ 'display': 'block', 'opacity': 0});
							new Fx.Tween(success_div, {
								'duration': '2000',
								'property': 'opacity',
								'link': 'chain'
							}).start(100).wait(100).start(0).chain(function(){ 
								success_div.setStyle('display', 'none'); 
								success_div.set('text', '');
							});
							reZebra();
						}
						else
						{
							failure_div.set('text', response.response.error);
							failure_div.setStyles({ 'display': 'block', 'opacity': 0});
							new Fx.Tween(failure_div, {
								'duration': '2000',
								'property': 'opacity',
								'link': 'chain'
							}).start(100).wait(100).start(0).chain(function(){ 
								failure_div.setStyle('display', 'none'); 
								failure_div.set('text', '');
							});
						}
					}
				}).send();
			}
		});
		
		function initEdit(item)
		{
			current_edit = item;
			var parent	= item.getParent('tr');
			edit_title.set('value', parent.getElement('.select_video_title').get('text'));
			edit_desc.set('value', parent.getElement('.select_video_desc').get('value'));
			edit_id.set('value', item.get('id'));
			video_add_menu.setStyle('display', 'none');
			video_edit_menu.setStyle('display', 'block');
		}
		
		function cancelEdit()
		{
			edit_title.set('value', '');
			edit_desc.set('value', '');
			edit_id.set('value', '');
			video_add_menu.setStyle('display', 'block');
			video_edit_menu.setStyle('display', 'none');
		}
		
		function reZebra()
		{
			var cur_element = null;
			var zebra_flag = true;
			$$('.video_row').each(function(row) {			
				if(row.hasClass('subheader_row_2'))
					row.removeClass('subheader_row_2');
				if(row.hasClass('subheader_row_1'))
					row.removeClass('subheader_row_1');
					
				if(zebra_flag)
					row.addClass('subheader_row_2');
				else
					row.addClass('subheader_row_1');
				zebra_flag = !zebra_flag;
			});
		}
	}
	
	
	var load_affinity = $('more_affinity');
	if(load_affinity != null)
	{
		var affinity_current 	= $('affinity_current');
		var affinity_additional = $('affinity_additional');
		var affinity_list		= $('affinity_list');
		var profile_userid		= $('profile_userid');
		
		load_affinity.addEvent('click', function(event)
		{
			new Request.JSONP({
				callBackKey: 'callback',
				url: 'http://data.d3clans.com/getAffinity.php',
				data: {
					'user':	profile_userid.get('value'),
					'start': affinity_current.get('value'),
					'results': affinity_additional.get('value')
				},
				onComplete: function(response) 
				{
					if(response.response.success == 'true')
					{
						json_loaded = 0;
						if($type(response.response.affinity) == 'array')
						{
							response.response.affinity.each(function(item) {
								addAffinity(item);
								json_loaded++;
							});
						}
						else
						{
							addAffinity(response.response.affinity);
							json_loaded++;
						}
						affinity_current.set('value', affinity_current.get('value').toInt()+json_loaded);
						
						if(json_loaded != affinity_additional.get('value'))
						{
							load_affinity.removeEvent('click');
							load_affinity.addClass('deactivated');	
						}
					}	
					else
					{
						load_affinity.removeEvent('click');
						load_affinity.addClass('deactivated');
					}
				}
			}).send();
		});
		
		function addAffinity(item)
		{						
			var outer_div = new Element('div', { 'class': 'affinity_boundary' } ).inject(affinity_list, 'top');
			var status_div = new Element('div', { 'class': 'affinity_background affinity_box_'+item.status } ).inject(outer_div);
			var username_div = new Element('div', { 'class': 'affinity_username' } ).inject(status_div);
			var username_a = new Element('a', { 'href': 'http://d3clans.com/players/view/'+item.subject_id, 'text': item.subject } ).inject(username_div);
			var avatar_img = new Element('img', { 'src': item.avatar_location, 'height': item.avatar_height, 'width': item.avatar_width, 'alt': 'Avatar' } ).inject(status_div);
		}
	}

	var add_comment 		= $('add_comment');
	var comment_additional 	= $('comment_additional');
	var comment_current 	= $('comment_current');
	var comment_form		= $('comment_form');
	var comment_id			= $('comment_id');
	var comment_list		= $('comment_list');
	var comment_message 	= $('comment_message');
	var comment_submit		= $('comment_submit');
	var comment_type		= $('comment_type');
	var comment_last_load 	= $('comment_last_load');
	var more_comments 		= $('more_comments');
	
	if(more_comments != null)
	{
		more_comments.addEvent('click', function(event)
		{
			new Request.JSONP({
				callBackKey: 'callback',
				url: 'http://data.d3clans.com/getComments.php',
				data: {
					'type':	comment_type.get('value'),
					'type_id': comment_id.get('value'),
					'start': comment_current.get('value'),
					'results': comment_additional.get('value')
				},
				onComplete: function(response) 
				{
					if(response.response.success == 'true')
					{
						json_loaded = 0;
						if($type(response.response.comment) == 'array')
						{
							response.response.comment.each(function(item) {
								addComment(item, false);
								json_loaded++;
							});
						}
						else
						{
							addComment(response.response.comment, false);
							json_loaded++;
						}
						comment_current.set('value', comment_current.get('value').toInt()+json_loaded);
						
						if(json_loaded != comment_additional.get('value'))
						{
							more_comments.removeEvent('click');
							more_comments.addClass('deactivated');	
						}
					}	
					else
					{
						more_comments.removeEvent('click');
						more_comments.addClass('deactivated');
					}
				}
			}).send();
		});
	}
	if(add_comment != null)
	{
		failure_div = $('failure');
		comment_submit.addEvent('click', function(event)
		{
			event.stop();
			new Request.JSONP({
				callBackKey: 'callback',
				url: 'http://data.d3clans.com/addComment.php',
				data: {
					'id':		comment_id.get('value'),
					'comment': 	comment_message.get('value'),
					'type': 	comment_type.get('value')
				},
				onComplete: function(response) 
				{
					if(response.response.success == 'true')
					{
						var json_loaded = 0;
						comment_message.set('value', '');
						if(comment_current.get('value').toInt() == 0)
						{
							comment_list.set('text', '');
						}
						//alert('http://data.d3clans.com/getComments.php?type=' + comment_type.get('value') + '&type_id=' + comment_id.get('value') + '&since=' + comment_last_load.get('value'));
						
						new Request.JSONP({
							callBackKey: 'callback',
							url: 'http://data.d3clans.com/getComments.php',
							data: {
								'type':	comment_type.get('value'),
								'type_id': comment_id.get('value'),
								'since': comment_last_load.get('value')
							},
							onComplete: function(response) 
							{
								if(response.response.success == 'true')
								{
									comment_last_load.set('value', (new Date().getTime() / 1000));
									json_loaded = 0;
									if($type(response.response.comment) == 'array')
									{
										response.response.comment.each(function(item) {
											addComment(item, true);
											json_loaded++;
										});
									}
									else
									{
										addComment(response.response.comment, true);
										json_loaded++;
									}
									comment_current.set('value', comment_current.get('value').toInt()+json_loaded);
									
									if(json_loaded != comment_additional.get('value'))
									{
										more_comments.removeEvent('click');
										more_comments.addClass('deactivated');	
									}
								}	
								else
								{
									more_comments.removeEvent('click');
									more_comments.addClass('deactivated');
								}
							}
						}).send();	
					}
					else
					{
						failure_div.set('text', response.response.error);
						failure_div.setStyles({ 'display': 'block', 'opacity': 0});
						new Fx.Tween(failure_div, {
							'duration': '2000',
							'property': 'opacity',
							'link': 'chain'
						}).start(100).wait(100).start(0).chain(function(){ 
							failure_div.setStyle('display', 'none'); 
							failure_div.set('text', '');
						});	
					}
				},
				onError: function(response)
				{
					comment_form.submit();	
				}
			}).send();
		});
	}
	
	function addComment(item, top)
	{			
		var avatar_width = item.avatar_width;
		var avatar_height = item.avatar_height;
		
		if(avatar_width > 100 || avatar_height > 100)
		{
			var ratio = 100 / ((avatar_width > avatar_height) ? avatar_width : avatar_height);
			avatar_width = avatar_width * ratio;
			avatar_height = avatar_height * ratio;
		}
		var clear_div = new Element('div', { 'style': 'clear: both;' });	
		if(top)
			var boundary_div = new Element('div', { 'class': 'comment_boundary' }).inject(comment_list, 'top');
		else
			var boundary_div = new Element('div', { 'class': 'comment_boundary' }).inject(comment_list);

		var header_div = new Element('div', { 'class': 'comment_header' }).inject(boundary_div);
		var body_div = new Element('div', { 'class': 'comment_body' }).inject(boundary_div);
		var username_div = new Element('div', { 'class': 'comment_username' }).inject(header_div);
		var username_a = new Element('a', { 'href': 'http://d3clans.com/players/view/'+item.userid, 'style': 'color: #'+item.color+';', 'text': item.username }).inject(username_div);
		var comment_date = new Element('div', { 'class': 'comment_date', 'text': item.date }).inject(header_div);
		clear_div.inject(header_div);
		var comment_avatar = new Element('div', { 'class': 'comment_avatar' }).inject(body_div);
		var avatar_img = new Element('img', { 'src': item.avatar_location, 'height': avatar_height, 'width': avatar_width, 'alt': 'User Avatar' } ).inject(comment_avatar);
		var comment_message = new Element('div', { 'class': 'comment_message', 'text': item.message }).inject(body_div);
		clear_div.inject(boundary_div);		
	}
	
	
	// clan name generator
	var cng_button = $('cng_generate');
	if(cng_button != null)
	{
		var cng_pattern = $('pattern');
		var cng_result = $('cng_result');
		var cng_failure = $('failure');
		var cnf_fail_count = 0;
		cng_button.addEvent('click', function(event)
		{
			event.stop();
			new Request.JSONP({
				callBackKey: 'callback',
				url: 'http://data.d3clans.com/generateClanName.php',
				data: {
					'pattern':		cng_pattern.get('value')
				},
				onComplete: function(response) 
				{
					if(response.response.success == 'true')
					{
						cng_result.setStyle('display', 'block');
						cng_result.set('text', response.response.name);
					}
					else
					{
						cnf_fail_count++;
						if(cnf_fail_count > 10)
							cng_button.removeEvent('click');
					}
				}
			}).send();
		});
	}
	
	
});








