function showLoad(show){
	show = show ? "block" : "none";
	$('#loading_mask').style("display",show);
}

//Initialize the GUI
egg.ready(function (){
	//Navi rollovers
	$$('.top_centering li').toggle('mouseout|mouseover',{'paddingTop':'0px','opacity':1},{'animate':[200,['easeOut',4]]});
});

/* HISTORY MANAGEMENT */
egg.bind('ajax.historychange', function(oldurl, newurl){
	//set window wait cursor
	showLoad(true);
	//urls follow this format: #!/page/phpFile/argName1/argVal1/argName2/argVal2...
	//which is parsed to: pages/page/run/phpFile.php?argName1=argVal1&argName2=argVal2...
	var ajaxurl = "pages/";
	//trim the slashes, then split into ['page','phpFile','argName1/argVal1...']
	newurl = newurl.replace(/^\/+|\/+$/g,"").match(/(.*?)(?:\/(.*?)(?:\/(.*)|$)|$)/);
	newurl.shift();
	//add 'page' and 'phpFile' to the ajaxurl
	ajaxurl += egg.isset(newurl[0]) && newurl[0] != '' ? newurl[0] : 'home';
	ajaxurl += egg.isset(newurl[1]) && newurl[1] != '' ? '/run/'+newurl[1]+'.php' : '/index.php';
	//add arguments to the ajax url
	var urlargs = {};
	if (egg.isset(newurl[2])){
		//split the args by the slash
		newurl[2] = newurl[2].split('/');
		//there needs to be an even number of args (argName=argVal)
		if (newurl[2].length/2 - parseInt(newurl[2].length/2) != 0) newurl[2].pop();
		//store the num of args for ajax_update_context referencing
		var numArgs = newurl[2].length/2;
		//add the args to the ajaxurl
		for (var arg=0; arg<newurl[2].length; arg=arg+2)
			urlargs[newurl[2][arg]] = newurl[2][arg+1];
	}
	//If this is the first page load, we need to tell the php script to load the entire thing
	var fullPage = oldurl == '';
	//If we newurl[2] was set, we can load a custom context for this ajax request (as long as this isn't the first page load)
	if (!fullPage && egg.isset(ajaxUpdateContext[newurl[0]]) && egg.isset(numArgs)){
		var context = $(ajaxUpdateContext[newurl[0]][numArgs]);
		//If we couldn't find the update element, just load the full page
		if (context.getContext() == false) fullPage = true;
	} else fullPage = true;
	//Load the full page
	if (fullPage){
		urlargs['loadFullPage'] = true;
		context = $('#contents');
	}
	//Load the url
	context.ajax(ajaxurl, {html:true, params:urlargs, oncomplete:function(text){
		showLoad(false);
		//run onload triggers
		var onfinish = navi_callback[newurl[0]];
		if (egg.isFn(onfinish)) onfinish.apply(this, [urlargs, newurl[1]]);
	}});
});
//This tells where to update on the page, given an ajax history url
var ajaxUpdateContext = {
	'goats':['#contents','#contents','#bottom_stuff']
}
//These are callbacks for after loading a page
var tracker = 0;
var navi_callback = {
	'goats': function(args, phpFile){
		if (!egg.isset(phpFile) || phpFile == 'goat_format'){
			//only initialize the slideshow if its a full page load or not an indi display
			if (egg.isset(args['loadFullPage']) || !egg.isset(args['id'])){
				//Is the slideshow already contracted?
				var topStuff = $('#top_stuff'),
					hidden = egg.contains(topStuff.active().className, '%contracted%'),
					styles = [[-148, 0],['Show','Hide']];

				//Setup the goat navi slideshow
				var origin = $('.imgs_subtitle_text').active().innerHTML;
				//right-left slide buttons
				$('.top_ss').bind('mouseleave',function(e){
					$('.imgs_subtitle_text').text(origin);
				}).slideshowFX('lr',['.top_ss_navileft','.top_ss_naviright'],{animate:[300,['easeOut',2]]});
				//image rollovers
				$$('.top_ss_shift>a').fire(function(){
					$(this).refine('*>.goat_thumb').toggle('mouseleave|mouseenter',{'opacity':[1,{animate:200}],'boxShadow':'0px 0px 10px black'},{triggerObj:this});
				}).bind({'mouseenter':function(e){
					$('.imgs_subtitle_text').text(this.title);
				}});

				//This will show the current goat in the subtitle bar
				var setGoatName = function(e){
					var name = $('#goat_info_name');
					if (name.getContext() != false) $('.imgs_subtitle_text').text(name.active().value);
				}
				topStuff.bind('mouseleave',setGoatName);
				egg.addEvent('setGoatName',setGoatName);

				//Hiding/showing of the navi slideshow
				var hideBtn = $('#expand_contract');
				topStuff.toggle('click',{'marginTop':styles[0][hidden?1:0]},{animate:100, triggerObj:hideBtn.active(), id:'toggleHiddenSS'});
				hideBtn.toggle('click','@innerHTML',styles[1][hidden?1:0],{id:'toggleHiddenSS'}).click(function(e){this.blur()});

				//hide the slideshow when an image is clicked
				if (egg.isset(args['type'])){
					$$('.top_ss_shift img').click(function(){
						hideBtn.toggle().change('toggleHiddenSS',0);
						topStuff.toggle().change('toggleHiddenSS',0);
					});
				}
			}
			//Goat Info specific javascript
			if (egg.isset(args['id'])){
				//Initialize the tabs plugin
				$('.goat_info_content').tabs('active_goat_info', 'description');
				//Set the new goat name
				egg.trigger('setGoatName');
				//Center the image in the viewing pane
				$$('.goat_ss_imgs img').fire(function(){
					var center = function(){this.style.marginLeft = (220-this.offsetWidth/2)+"px";}
					$(this)[this.offsetWidth != 0 ? 'fire' : 'load'](center);
				});
				//Initialize the slideshow and such
				$('.goat_ss').slideshowFX('ss','activeImg',{animate:200});
			}
		}
		else if (phpFile == 'edit_format' || phpFile == 'add_format'){
			$('.edit_goat_contentbar').tabs('activeEdit','editSummary');
			//set up iframe response system
			$('#goat_editing_form').bind('submit',function(e){
				$('#goat_form_feedback').text('Loading...');
			});
			$('#hiddenIFRAME').load(function(e){
				var response = this.contentWindow.document.body.innerHTML;
				//Load the new page
				var goat_id = response.match(/Success:(.*?)\|(.*)/);
				if (egg.isset(goat_id)){
					goat_id.shift();
					egg.history("goats/goat_format/type/"+goat_id[0]+"/id/"+goat_id[1]+"");
				}
				//There was some type of error in the form
				else if (response != '')
					$('#goat_form_feedback').text(response).active().style.display = 'inline';
			});
		}
	},
	'other': function(args, phpFile){
		//Add a new category
		if (phpFile == 'add_format'){
			$('#file_chooser').bind('change',function(e){
				$('#crop_widget').cropWidget(e.target.files[0],[300,300]);
			});
			$('#add_category').click(function(e){
				var cont = this.parentNode.parentNode,
					response = $('#success_info');
				if (!cont.cat_name.value.length) response.text('Name is blank!');
				else{
					var img = $('#crop_widget').cropWidget().getImage();
					if (!img) response.text('Crop an image first!');
					else{
						//Upload the cropped image
						egg.ajax('pages/other/run/add_action.php',{type:'post',params:{
							'subcat':cont.cat_par.value,
							'subenab':egg.isset(cont.cat_subs) ? cont.cat_subs.checked : false,
							'data':img,
							'name':cont.cat_name.value
						},oncomplete:function(error){
							if (error.substring(0,2) == 'S:'){
								//Successfully added a category
								var cat = parseInt(error.substring(2));
								if (cat != -1) egg.history("/other/sub_category/id/"+cat);
								else egg.history("/other/");
							}
							else response.text(error);
						}});
					}
				}
			});
		}
		else if (phpFile == 'addimage_format'){
			$('#file_chooser').bind('change',function(e){
				$('#crop_widget').cropper(e.target.files[0],[730,300]);
			});
			$('#add_category').click(function(e){
				var cont = this.parentNode.parentNode,
					response = $('#success_info');
				if (!cont.cat_name.value.length) response.text('Title is blank!');
				else if (!cont.descript.value.length) response.text('Description is blank!');
				else{
					var img = $('#crop_widget').cropper();
					if (!img) response.text('Crop an image first!');
					else{
						//Upload the cropped image
						egg.ajax('pages/other/run/addimage_action.php',{type:'post',params:{
							'subcat':cont.cat_par.value,
							'descript':cont.descript.value,
							'data':img,
							'title':cont.cat_name.value
						},oncomplete:function(error){
							if (error.substring(0,2) == 'S:'){
								//Successfully added a category
								var cat = error.substring(2).split("|");
								egg.history("/other/display/id/"+cat[0]+"/img/"+cat[1]);
							}
							else response.text(error);
						}});
					}
				}
			});
		}
		else{
			//Setup the navi slideshow
			var origin = $('.imgs_subtitle_text').active().innerHTML;
			//right-left slide buttons
			$('.top_ss').bind('mouseleave',function(e){
				$('.imgs_subtitle_text').text(origin);
			}).slideshowFX('lr',['.top_ss_navileft','.top_ss_naviright'],{animate:[300,['easeOut',2]]});
			//image rollovers
			$$('.top_ss_shift>a').fire(function(){
				$(this).refine('*>.other_thumb').toggle('mouseleave|mouseenter',{'opacity':[1,{animate:200}],'boxShadow':'0px 0px 10px black'},{triggerObj:this});
			}).bind({'mouseenter':function(e){
				$('.imgs_subtitle_text').text(this.title);
			}});

			//This will show the current goat in the subtitle bar
			var setGoatName = function(e){
				var name = $('#goat_info_name');
				if (name.getContext() != false) $('.imgs_subtitle_text').text(name.active().value);
			}
			//topStuff.bind('mouseleave',setGoatName);
			egg.addEvent('setGoatName',setGoatName);
		}
	},
	'report':function(){
		$$('#bug_report *').inputClearFX('#947b63');
	}
}

/* HOME PAGE ADMIN TOOLS */
function save_home_edits(){
	var c = egg.lookup('#home_edits')[0].new_content.value;
	$('#edit_errors').ajax('pages/home/run/edit_action.php',{html:true,type:'post',params:{'new_content':c},oncomplete:function(response){
		//Load the home page, if there were no errors
		if (response == '') egg.history("/");
	}});
}

/* GOATS ADMIN TOOLS */
function create_file_upload(){
	var new_file_uploads = parseInt(document.getElementById('upload_boxes').value);
	var new_upload = document.createElement('div');
	var new_id = "newfileupload"+new_file_uploads;
	new_upload.setAttribute('id',new_id);
	$('#file_uploads').active().appendChild(new_upload);
	//Submit form
	new_upload.innerHTML = "<input type='file' size='50' name='fileUpload"+new_file_uploads+"'> <a href='javascript:remove_file("+new_file_uploads+");' class='small_link'>Remove</a>";
	$('#upload_boxes').active().value = new_file_uploads+1;
}
function remove_file(id){
	$('#file_uploads').active().removeChild(egg.lookup("#newfileupload"+id)[0]);
}
function delete_goat(id){
	var check = confirm("Do you really want to delete this goat? It will remove all images as well.");
	if (check) $('#bottom_stuff').ajax('pages/goats/run/delete_action.php',{html:false,params:{'id':id},oncomplete:function(response){
		var isSuccess = response.match(/Success:(.*)/);
		if (egg.isset(isSuccess)){
			this.innerHTML = "<div class='page_padding'>Goat deleted!</div>";
			//the id needs some 0 padding
			var padded_id = '00000'+isSuccess[1];
			padded_id = padded_id.substring(padded_id.length-5,padded_id.length);
			//delete the goat <a> tag
			var oldNode = egg.lookup('#imgLink-'+padded_id)[0];
			oldNode.parentNode.removeChild(oldNode);
			//expand the navigation
			var hidden = egg.contains(egg.lookup('#top_stuff')[0].className, '%contracted%') ? 1 : 0;
			$$('#expand_contract,#top_stuff').toggle().change('toggleHiddenSS',0,hidden);
			$('.imgs_subtitle_text').text("Pick a goat above");
		}
		//alert the error message
		else alert(response);
	}});
}
function goat_add_type(){
	$('#goat_type_custom').active().style.display = 'inline';
	$('#goat_type').active().style.display = 'none';
}

/* BUG REPORT FORM */
function submit_report(){
	var complete = $$('#bug_report *').inputClearFX().isset();
	if (!complete) $('#goat_form_feedback').text("Please complete the form first.").active().style.display = 'inline';
	else{
		var form = egg.lookup('#bug_report')[0];
		//Submit the form
		$('.page_padding').ajax('pages/report/send_report.php',{type:'post',params:{
			'browser':window.navigator.userAgent,
			'email':form.email.value,
			'message':form.description.value
		},oncomplete:function(response){
			if (response != '') $('#goat_form_feedback').text(response).active().style.display = 'inline';
			else this.innerHTML = "<strong>Thanks for your help!</strong>";
		}});
	}
}

