/******************************* onload functions *******************************/
/* Functions to Run When Page Loads												*/
/********************************************************************************/
$(function() {
	// Messages
	messages();
	// Row Backgrounds
	rows();
	// Tooltips
	//tips();
	// Calendars
	calendar();
	// Tags
	tagIt();
	// Buttons
	buttons();
	// Nestable
	nest();
});

/******************************** document.ready ********************************/
/* Functions to Run When Page Loaded											*/
/********************************************************************************/
$(document).ready(function () {
	// Character Count
	counter();
	// Form Validation
	validate();
	// Text Editor (& CKEditor)
	texteditor();
	// Draggable
	drag();
	// PNG Fix
	png();
	// Default Values
	defaults();
	// Quicksearch
	quicksearch();
	// External Links
	if(links_external_window == 1) {
		$("a[@href^=http]").each(function(){
			if(this.href.indexOf(location.hostname) == -1) $(this).attr('target', '_blank');
		});
	}
	// Admin Links
	if(links_admin_window == 1) {
		$("a[@href^=http]").each(function(){
			var url = window.location.pathname;
			if(url.indexOf('/admin/') > 0 && this.href.indexOf('/admin/') == -1 && this.href.indexOf('logout') == -1) $(this).attr('target', '_blank');
		});
	}
});

/************************************ loader ************************************/
/* Shows loading icon with given text (optional) in given div					*/
/********************************************************************************/
function loader(div,text) {
	if(text == "") text = "Loading..";
	$('#'+div).html("<div style='position:relative;min-height:65px;'><div style='position:absolute;left: 50%;margin-left:-80px;margin-top:15px;'><center><img src='"+DOMAIN+"images/ajax-loader.gif' class='loader' /> "+text+"</center></div><div style='opacity:.30;filter:alpha(opacity=30);-moz-opacity:.3;'>"+document.getElementById(div).innerHTML+"</div></div>");
}

/*********************************** adClick ************************************/
/* Records ad click and returns true letting the link proceed					*/
/********************************************************************************/
function adClick(id,r) {

}

/************************************ pageIt ************************************/
/* Updates page counter and selected page number for pages_ajax					*/
/********************************************************************************/
function pageIt(id,p) {
	$('#pages_'+id+'_counter').val(p);
	$('#pages_'+id+' .p-current').removeClass('selected');
	$('#pages_'+id+'_'+p).addClass('selected');
}

/*********************************** confirmIt **********************************/
/* Shows confirm box which redirects to given url if user confirms given text	*/
/********************************************************************************/
function confirmIt(text,url) {
	if (confirm(text)){
		location.replace(url);
	}
}

/************************************ debugIt ***********************************/
/* Prints given text in the footer 'debugger' div								*/
/********************************************************************************/
function debugIt(text) {
	$('#debugger').append(text);
}

/************************************ toggleIt **********************************/
/* Shows or hides given div based upon it's current state						*/
/********************************************************************************/
function toggleIt(div) {
	if(document.getElementById(div).style.display=="none") $("#"+div).show();
	else $("#"+div).hide();
}

/************************************* showIt ***********************************/
/* Fades in given element in given amount of time								*/
/********************************************************************************/
function showIt(div,time) {
	/*if(time == null) var time = 500;
	$("#"+div).fadeIn(time);*/
	$("#"+div).show();
}

/************************************* hideIt ***********************************/
/* Fades out given element in given amount of time								*/
/********************************************************************************/
function hideIt(div,time) {
	/*if(time == null) var time = 500;
	$("#"+div).fadeOut(time);*/
	$("#"+div).hide();
}

/************************************* allIt ************************************/
/* Selects all of multiple select (radio/checkbox in future) if option = 'all'	*/
/********************************************************************************/
function allIt(id) {
	var e;
	var tag;
	$('#'+id).each(function() {
		e = $(this);
		tag = this.tagName;	
	});
	if(e) {
		var v = e.val();
		if(v == '-all-') {
			if(tag == "SELECT") {
				$("#"+id+" option").attr("selected","selected");
				$("#"+id+" option[value='-all-']").removeAttr('selected');
				$("#"+id+" option[value='']").removeAttr('selected');
			}
			if(tag == "INPUT") {
				var name = e.attr('name');
				var checked = 0;
				$("#"+id+":checked").each(function() {
					$("input[name='"+name+"']").attr("checked","checked");
					//$("#"+id).removeAttr('checked');
					checked = 1;
				});
				if(checked == 0) $("input[name='"+name+"']").removeAttr("checked");
			}
		}
	}
}

/************************************ submitIt **********************************/
/* Submits form and disables submit button										*/
/********************************************************************************/
function submitIt(f) {
	var s = $(f).find("input[type='submit']");
	$(s).after("<img src='"+DOMAIN+"images/ajax-loader.gif' class='loader' />");
	$('img.loader').fadeTo(100,1,function() {
		f.submit();
		$(s).attr("disabled", "disabled").fadeTo("normal", 0.4);
	});
}

/*********************************** editInline *********************************/
/* Retrieves code for inline editing of given variable							*/
/********************************************************************************/
function editInline(div,table,column,key,id,buttons,redirect) {
	// AJAX
	$.ajax({
		type: 'POST',
		url: DOMAIN,
		data: 'ajaxRequest=editInline&table='+table+'&column='+column+'&div='+div+'&key='+key+'&id='+id+'&buttons='+buttons+'&redirect='+redirect,
		success: function(html){
			$('#'+div).html(html);
			
			// Calendar
			calendar();

			// Submit on Enter
			$('#'+div+'_inline').focus().keypress(function (e) {
				if (e.which == 13) saveInline('1',div,table,column,key,id,buttons,redirect);
			});
			
			// Submit on Blur
			if(buttons == 0) {
				$('#'+div+'_inline').blur(function () {
					saveInline('1',div,table,column,key,id,buttons,redirect);
				});
			}
		}
	});
}

/*********************************** saveInline *********************************/
/* Gets inline variable and saves it											*/
/********************************************************************************/
function saveInline(save,div,table,column,key,id,buttons,redirect) {
	var value;
	var v = $('#'+div+'_inline');
	if(v.type == "radio" || v.type == "checkbox") {
		if(v.checked == true) value = v.value;
	}
	else value = encodeURIComponent($(v).val());
	
	// AJAX
	$.ajax({
		type: 'POST',
		url: DOMAIN,
		data: 'ajaxRequest=saveInline&save='+save+'&table='+table+'&column='+column+'&div='+div+'&key='+key+'&id='+id+'&value='+value+'&buttons='+buttons+'&redirect='+redirect,
		success: function(html){
			$('#'+div).html(html);
			
			// Redirect
			if(redirect != "" && redirect != "undefined" && redirect != undefined && redirect) location.assign(DOMAIN+redirect);
			
			// Refresh jQuery
			thickbox();
			//$('table.sortable').trigger("update");
		}
	});
}

/************************************** tagIt ***********************************/
/* Adds tag funcionality to input fields with class='tag'						*/
/********************************************************************************/
var tags;
function tagIt(div) {
	$('input.tag').unautocomplete();
	
	if(tags) {
		if(div == null) div = 'tags';
		$('input.tag').autocomplete(tags, {
			minChars: 0,
			matchContains: true,
			autoFill: false,
			formatItem: function(row) {
				return row.name +' <h4>'+row.note+'</h4>';
			},
			formatMatch: function(row, i, max) {
				return row.name + ' ' + row.username;
			}
		}).result(function(event, data, formatted) {
			$(this).val('');
			$.ajax({
				type: 'POST',
				url: DOMAIN,
				data: 'ajaxRequest=tagIt&id='+data.id,
				success: function(html){
					$('#'+div).append(html);
					messages();
					
					// Tag Counter
					if(document.getElementById('tag_counter')) {
						var c = $('#tag_counter').val();
						var test = html.split("class='_error");
						if(!test[1]) $('#tag_counter').val((c * 1) + 1);
						if($('label.error').is(':visible')) $(".require").valid();
					}
				}
			});
		});
	}
}

/************************************ untagIt ***********************************/
/* Removes tag from form and sends ajax request to remove from tags session		*/
/********************************************************************************/
function untagIt(div,id) {
	removeIt(div);
	
	// Re-activates checkbox (if exists)
	$('#check_'+id+'_text').slideDown(400);
	$('#check_'+id+'_input').removeAttr('checked');
	/*$('#check_'+id+'_input').removeAttr('disabled').removeAttr('checked');
	$('#check_'+id+'_text').fadeTo(500,1.0);*/
	
	$.ajax({
		type: 'POST',
		url: DOMAIN,
		data: 'ajaxRequest=untagIt&id='+id
	});
	
	// Tag Counter
	var c = $('#tag_counter').val();
	if(c) $('#tag_counter').val((c * 1) - 1);
}

/************************************* checkIt **********************************/
/* Handles tagging when checkbox is clicked										*/
/********************************************************************************/
function checkIt(id,div) {
	if(div == null) div = 'tags';
	
	// Deactivates Checkbox
	$('#check_'+id+'_text').slideUp(400);
	/*$('#check_'+id+'_input').attr('disabled','disabled');
	$('#check_'+id+'_text').fadeTo(500,0.5);*/
	
	// Send AJAX
	$.ajax({
		type: 'POST',
		url: DOMAIN,
		data: 'ajaxRequest=tagIt&id='+id,
		success: function(html){
			$('#'+div).append(html);
			messages();
			
			// Tag Counter
			if(document.getElementById('tag_counter')) {
				var c = $('#tag_counter').val();
				var test = html.split("class='_error");
				if(!test[1]) $('#tag_counter').val((c * 1) + 1);
				if($('label.error').is(':visible')) $(".require").valid();
			}
		}
	});
}

/************************************ removeIt **********************************/
/* Removes given div															*/
/********************************************************************************/
function removeIt(div,text) {
	if(text) {
		if(confirm(text)) { 
			$('#'+div).fadeOut(500,function() { $(this).remove(); });
		}
	}
	else $('#'+div).fadeOut(500,function() { $(this).remove(); });
}

/************************************ deleteIt **********************************/
/* Sends ajax request do delete given type's id if given text is confirmed		*/
/********************************************************************************/
function deleteIt(text,div,table,key,id) {
	if (confirm(text)){
		// Hide
		$('#'+div).fadeOut(500,function() {
		
			// AJAX
			$.ajax({
				type: 'POST',
				url: DOMAIN,
				data: 'ajaxRequest=deleteIt&table='+table+'&div='+div+'&id='+id+'&key='+key,
				success: function(html){
					if(html.length > 0) $('#'+div).html(html);
					else $('#'+div).remove();
					
					// Redirect
					if(document.getElementById('redirect')) location.assign(DOMAIN+document.getElementById('redirect').value);
					
					// Rows
					rows();
				}
			});
		});
	}
}

/******************************** deactivateIt **********************************/
/* Deactivates item (deleted from frontend, still in db)						*/
/********************************************************************************/
function deactivateIt(text,div,table,column,key,id,value) {
	if (confirm(text)){
		if(!value || value == "undefined") value = 2;
		// Hide
		$('#'+div).fadeOut(500,function() {
			$(this).remove();
			// Disable in DB
			$.ajax({
				type: 'POST',
				url: DOMAIN,
				data: 'ajaxRequest=deactivateIt&table='+table+'&column='+column+'&div='+div+'&key='+key+'&id='+id+'&value='+value
			});
			rows();
		});
	}
}

/************************************ saveIt ************************************/
/* Gets values from a form, posts to AJAX, and handles response					*/
/********************************************************************************/
function saveIt(form,div,loc,method) {
	var vals;
	$('#'+form+' :input').each(function() {
		if(this.type == "radio" || this.type == "checkbox") {
			if(this.checked == true) vals += '&' + this.name + '=' + encodeURIComponent(this.value);
		}
		else if(this.type == "select-multiple") {
			var name = this.name;
			$("option:selected",this).each(function(i,selected) {
				vals += '&' + name + '=' + encodeURIComponent($(selected).val())
			});
		}
		else vals += '&' + this.name + '=' + encodeURIComponent(this.value);
	});
	
	// Method
	if(method == null) method = 'POST';
	if(method == 'GET') {
		var url = DOMAIN+'?ajaxRequest=saveIt&form='+form+'&div='+div+vals;
		var data = '';
	}
	if(method == 'POST') {
		var url = DOMAIN;
		var data = 'ajaxRequest=saveIt&form='+form+'&div='+div+vals;
	}
	
	$.ajax({
		type: method,
		url: url,
		data: data,
		success: function(html){
			// Comment
			if(str_replace("comment","",form) != form) $("textarea[name=comment_text]").val('');
			// Form Field
			if(form == "form_field_add") tb_remove();
			// Tags
			if(form == "contacts_add" || form == "contact_add"){
				var s = html.split('|||');
				$("#"+div).html(s[0]);
				if(s[1]) $("#tags").append(s[1]);
				if(document.getElementById('tag_counter')) {
					var c = $('#tag_counter').val();
					$('#tag_counter').val((c * 1) + 1);
					if($('#'+form+' label.error').is(':visible')) $(".require").valid();
				}
				if(form == "contacts_add") {
					document.getElementById('contacts_get')['email'].value = '';
					document.getElementById('contacts_get')['password'].value = '';
				}
				if(form == "contact_add") document.getElementById('contact_add')['email'].value = '';
			}
			// Auto
			else if(str_replace("auto_","",form) != form) {
				// Add Content to Document
				var r = Math.floor(Math.random() * 999999);
				$("body").append("<div id='autosave_div_"+r+"' style='display:none;'>"+html+"</div>");
				// Get Input ID
				var id = $("#autosave_div_"+r+" #autosave_id").val();
				// Remove Content
				$("#autosave_div_"+r).remove();
				// Update ID
				$("#"+form+" input[name=id]").val(id);
				// Debug
				debugIt(html);
			}
			// Default
			else {
				if(loc == "prepend") $('#'+div).prepend(html);
				else if(loc == "append") $('#'+div).append(html);
				else if(loc == "replace") $('#'+div).replaceWith(html);
				else $("#"+div).html(html);
			}
			
			// Submit Button
			if(form != "auto") {
				var s = $("#"+form+" input[type='submit']").fadeTo("normal", 1.0).removeAttr("disabled");
				$('img.loader').each(function() { $(this).remove(); });
				// Refresh jQuery
				rows();
				thickbox();
				messages();
				validate();
				drag();
				buttons();
				texteditor();
			}
		}
	});
}

/*********************************** updateIt ***********************************/
/* Handles various update scripts												*/
/********************************************************************************/
function updateIt(table,column,key,id) {
	$.ajax({
		type: 'POST',
		url: DOMAIN,
		data: 'ajaxRequest=updateIt&table='+table+'&column='+column+'&key='+key+'&id='+id,
		success: function(html){
			var array = html.split('|||');
			for(var i in array) {
				if(!(i % 2)) {
					var j = (i * 1) + 1;
					if(array[j]) {
						$('#'+array[i]).html(array[j]);
					}
				}
			}
		}
	});
}

/*********************************** scrollIt ***********************************/
/* Scrolls content of div to given direction and reloads with given html		*/
/********************************************************************************/
var scrolling = new Array();
var scrolls = new Array();
var scrolls_start = new Array();
function scrollIt(div,direction,html,number) {
	// Variables
	if(!scrolling[div]) scrolling[div] = 0;
	if(!scrolls_start[div]) scrolls_start[div] = 0;
	if(!scrolls[div]) scrolls[div] = new Array();
	scrolls[div][scrolls_start[div]] = new Array();
	// Save Info
	if(!number || number == null) {
		number = scrolls_start[div];
		scrolls[div][number]['direction'] = direction;
		scrolls[div][number]['html'] = html;
		scrolls_start[div] += 1;
	}
	
	// Not Scrolling
	if(scrolling[div] == 0) {
		scrolling[div] = 1;
		var zero = 0;
		
		// Container Div
		var parent = $('#'+div);
		var parent_w = parent.width();
		var parent_h = parent.height();
		// Make Scrollable
		$('#'+div).addClass('scroll').css({'overflow':'hidden','height':parent_h+'px','width':parent_w+'px'});
		
		// Inner (Scrolling) Div
		if($('#'+div+' > div.scroll_inner').length == 0) {
			// Get Content Dimensions
			var child = $('#'+div+' > div');
			var child_w = child.width();
			var child_h = child.height();
			
			// Add Inner Div
			$('#'+div+' > div').wrap("<div></div>");
			$('#'+div+' > div').addClass('scroll_inner').css({'position':'absolute','width':(child.width() * 2)+'px'});
		}
		// Already Added, Child is on 2nd Level
		else {
			var child = $('#'+div+' > div > div:nth-child(1)');
			var child_w = child.width();
			var child_h = child.height();
		}
		
		// Left
		if(direction == "left") {
			// Inner Div Left/Right
			$('#'+div+' > div').css({'left':zero+'px','right':'auto'});
			// Make Old Content Absolute
			$('#'+div+' > div > div').css({'position':'absolute','left':zero+'px','right':'auto','width':child_w+'px','height':child_h+'px'});
			// Add New Content and make absolute																																						
			if(html) {
				$('#'+div+' > div').append(html);
				$('#'+div+' > div > div:nth-child(2)').css({'position':'absolute','left':(zero + child_w)+'px','right':'auto','width':child_w+'px','height':child_h+'px'});
			}
			// Slide it All
			$('#'+div+' > div').animate({'left':(zero - child_w)},1000,'swing',function() {
				$('#'+div+' > div > div:nth-child(1)').remove();
				scrolling[div] = 0;
				if(scrolls[div][number]) scrolls[div][number] = null;
				if(scrolls[div][number + 1]) scrollIt(div,scrolls[div][number + 1]['direction'],scrolls[div][number + 1]['html'],(number + 1));
				scrolling[div] = 0;
			});
		}
		// Right
		if(direction == "right") {
			// Inner Div Left/Right
			$('#'+div+' > div').css({'right':zero+'px','left':'auto'});
			// Make Old Content Absolute
			$('#'+div+' > div > div').css({'position':'absolute','right':zero+'px','left':'auto','width':child_w+'px','height':child_h+'px'});
			// Add New Content and make absolute																																						
			if(html) {
				$('#'+div+' > div').append(html);
				$('#'+div+' > div > div:nth-child(2)').css({'position':'absolute','right':(zero + child_w)+'px','left':'auto','width':child_w+'px','height':child_h+'px'});
			}
			// Slide it All
			$('#'+div+' > div').animate({'right':(zero - child_w)},1000,'swing',function() {
				$('#'+div+' > div > div:nth-child(1)').remove();
				scrolling[div] = 0;
				if(scrolls[div][number]) scrolls[div][number] = null;
				if(scrolls[div][number + 1]) scrollIt(div,scrolls[div][number + 1]['direction'],scrolls[div][number + 1]['html'],(number + 1));
				scrolling[div] = 0;
			});
		}
		
		// Refresh jQuery
		rows();
		messages();
		thickbox();
		calendar();
		validate();
		texteditor();
		quicksearch();
	}
}

/************************************ loadIt ************************************/
/* Handles various load scripts													*/
/********************************************************************************/
function loadIt(div,type,id,loc,vars,animation,direction) {
	if(!vars) vars = null;
	$.ajax({
		type: 'POST',
		url: DOMAIN,
		data: 'ajaxRequest=loadIt&div='+div+'&type='+type+'&id='+id+'&animation='+animation+'&'+vars,
		success: function(html){
			if(loc == "prepend") $('#'+div).prepend(html);
			else if(loc == "append") $('#'+div).append(html);
			else {
				if(animation == "scroll") scrollIt(div,direction,html);
				else $('#'+div).html(html);
			}
			
			// No Animaiton
			if(animation != "scroll") {
				// Refresh jQuery
				rows();
				messages();
				thickbox();
				calendar();
				validate();
				texteditor();
				quicksearch();
				//$('.sortable').trigger("update");
			}
		}
	});
}

/*********************************** updateIt ***********************************/
/* Handles various update scripts												*/
/********************************************************************************/
function updateIt(table,column,key,id) {
	$.ajax({
		type: 'POST',
		url: DOMAIN,
		data: 'ajaxRequest=updateIt&table='+table+'&column='+column+'&key='+key+'&id='+id,
		success: function(html){
			var array = html.split('|||');
			for(var i in array) {
				if(!(i % 2)) {
					var j = (i * 1) + 1;
					if(array[j]) {
						$('#'+array[i]).html(array[j]);
					}
				}
			}
		}
	});
}

/*********************************** uploadPhoto ********************************/
/* Uploads file in given input field to given path (defaults to DOMAIN/uploads/)*/
/********************************************************************************/
var uploadPhoto_n = 0;
function uploadPhoto(div,results,input,path) {
	var file = $('#'+input).val();
	var album = $('#album_id').val();
	if(file) {
		// Total Number of Current Uploads
		uploadPhoto_n = uploadPhoto_n + 1;
		
		// Loader
		$.ajax({
			type: 'POST',
			url: DOMAIN,
			data: 'ajaxRequest=previewPhoto&x='+uploadPhoto_n+'&div='+div+'&file='+file,
			success: function(html){
				$("#"+div).append(html);
				var d = div+'_'+uploadPhoto_n;
				$("#"+d).slideDown(350);
				
				// Upload Photo
				$.ajaxFileUpload({
					url:DOMAIN+'?ajaxRequest=uploadPhoto&path='+path+'&d='+d+'&album='+album,
					secureuri:false,
					fileElementId:input,
					dataType: 'script',
					success: function (data, status) {
						if(path == "uploads/photos/o/") {
							var array = data.split('|||');
							// Remove "Uploading" add Photo Info Box
							$("#heading").show();
							$(results).show().prepend(array[0]);
							$("#submit").show();
							$("#"+d+'_up').slideDown(350);
							$("#"+d).slideUp(350, function() {
								$(this).remove();
								calendar();
							});
							tagIt(array[1]);
							notes(array[1]);
						}
						else if(div == "uploads_processing") {
							$("#"+d).slideUp(350);
							$(results).append(data);
							buttons();
						}
						
						rows();
						thickbox();
						
						// Hide Failure Messages
						$("#red").animate({opacity: 1.0}, 1500).slideUp(500, function() {
							$(this).remove();
						});
						
					},
					error: function (data, status, e) {
						alert(e);
					}
				});
				
				// Clear File Input
				$('#'+input).animate({opacity: 1.0}, 50,function(){
					document.getElementById(input).value = "";
				});
				
			}
		});
	}
	return false;
}

/************************************ uploadIt **********************************/
/* Uploads file in given input field to given path (defaults to DOMAIN/uploads/)*/
/********************************************************************************/
function uploadIt(div,input,path) {
	loader(div,'Uploading..');
	
	$.ajaxFileUpload(
		{
			url:DOMAIN+'?ajaxRequest=upload&path='+path,
			secureuri:false,
			fileElementId:input,
			dataType: 'html',
			success: function (data, status) {
				// Add Message / Hidden Input
				$("#"+div).append(data);
				// Clear File Input
				document.getElementById(input).value = "";
				// Hide Failure Messages
				$("#red").animate({opacity: 1.0}, 1500).slideUp(500, function() {
					$(this).remove();
				});
			},
			error: function (data, status, e) {
				alert(e);
			}
		}
	)
	return false;
}

/********************************* disableIt ************************************/
/* Disables given element														*/
/********************************************************************************/
function disableIt(div,table,column,key,id,button) {
	// Fade Out Div
	if(document.getElementById(div)) {
		document.getElementById(div).disabled = true;
		$('#'+div).css('cursor','default').fadeTo("normal", 0.4);
	}
	
	// Disable in DB
	if(table) {
		$.ajax({
			type: 'POST',
			url: DOMAIN,
			data: 'ajaxRequest=disableIt&table='+table+'&column='+column+'&div='+div+'&key='+key+'&id='+id+'&button='+button,
			success: function(html){
				$('#'+button).html(html);
			}
		});
	}
}

/********************************** enableIt ************************************/
/* Enables given element														*/
/********************************************************************************/
function enableIt(div,table,column,key,id,button) {
	// Fade In Div
	if(document.getElementById(div)) {
		document.getElementById(div).disabled = false;
		$('#'+div).css('cursor','pointer').css('cursor','hand').fadeTo("normal",1);
	}
	
	// Enable in DB
	if(table) {
		$.ajax({
			type: 'POST',
			url: DOMAIN,
			data: 'ajaxRequest=enableIt&table='+table+'&column='+column+'&div='+div+'&key='+key+'&id='+id+'&button='+button,
			success: function(html){
				$('#'+button).html(html);
			}
		});
	}
}

/********************************** showAudio ***********************************/
/* Loads flash for audio into given div											*/
/********************************************************************************/
function showAudio(div,file) {
	if(document.getElementById(div).innerHTML == "") {
		$.ajax({
			type: 'GET',
			url: DOMAIN+'?ajaxRequest=showAudio&div='+div+'&file='+file,
			success: function(html){
				$('#'+div).html(html);
			}
		});
	}
	else document.getElementById(div).innerHTML = "";
}

/********************************** hideAudio ***********************************/
/* Removes flash for audio from given div										*/
/********************************************************************************/
function hideAudio(div,file) {
	$('#'+div).html("");
}


/************************************ defaults **********************************/
/* Clears or Restores default value for input field where class='default'		*/
/********************************************************************************/
function defaults() {
	$('input.default').focus(function() {	
		if(this.defaultValue == this.value) $(this).val('').removeClass('default');
	}).blur(function() {
		if(!this.value) $(this).val(this.defaultValue).addClass('default');
	});
}

/*********************************** checkAll ***********************************/
/* Checks or unchecks all checkboxes (with optional class name) 				*/
/********************************************************************************/
function checkAll(c,classID) {
	if(classID) {
		if(c.checked) $('input[type=checkbox].'+classID).attr('checked', 'checked');
		else $('input[type=checkbox].'+classID).removeAttr('checked');
	}
	else {
		if(c.checked) $('input[type=checkbox]').attr('checked', 'checked');
		else $('input[type=checkbox]').removeAttr('checked');
	}
}

/************************************* tips *************************************/
/* Runs scripts for tooltips on elements with class="tip"						*/
/********************************************************************************/
function tips() {
	$('a.tip, img.tip, div.tip, #age_menu a').tooltip({
		track: true,
		delay: 0,
		showURL: false
	});
}

/************************************** rows ************************************/
/* Adds alternate shading to odd and even rows where class="row"				*/
/********************************************************************************/
function rows() {
	$('tr.row:odd, div.row:odd, table.row:odd').addClass("odd").removeClass("even");
	$('tr.row:even, div.row:even, table.row:even').addClass("even").removeClass("odd");
}

/************************************ calendar **********************************/
/* Shows calendar date picker on all input fields with class="calendar"			*/
/********************************************************************************/
function calendar() {
	$('img.ui-datepicker-trigger').remove();
	$('input.hasDatepicker').removeAttr('id').removeClass('hasDatepicker');
	
	$('input.calendar').each(function() {
		//$(this).attr('readonly','readonly');
		$(this).datepicker({ 
			showOn: 'both', 
			buttonImage: DOMAIN+'images/calendar.png',	
			changeMonth: true,
			changeYear: true,
			buttonImageOnly: true
		});
	});
}

/************************************ validate **********************************/
/* Adds form validation to all forms with class="require"						*/
/********************************************************************************/
function validate() {
	$('input[type=text].required:not(.norequired), input[type=password].required:not(.norequired), select.required:not(.norequired), textarea.required:not(.norequired)').after('<img src="'+DOMAIN+'images/required.gif" alt="Required" class="absmiddle" style="padding-left:1px;" />').addClass('norequired');
	
	// Form Validation
	$('form.require').each(function() { 
		$(this).validate({
			submitHandler: function(form) { submitIt(form); }
   		}); 
	}); 
	
	// Registration Validation
	$("#register").validate({
		rules: {
			user_name: { remote: DOMAIN+"?ajaxRequest=checkUsername", regex: register_regex_rule },
			user_email: { remote: DOMAIN+"?ajaxRequest=checkEmail" }, 
			user_confirm_password: { equalTo: "#user_password"}/*, 
			user_confirm_email: { equalTo: "#user_email"}*/
		},
		messages: {
			// If user_name validation isn't working, there's probably an error in the AJAX file
			user_name: { remote: "This username is already taken", regex: register_regex_message },
			user_email: { remote: register_email_unique_message },
			user_confirm_password: { equalTo: "Your passwords don't match" }/*,
			user_confirm_email: { equalTo: "Your e-mail addresses don't match" }*/
		},
		submitHandler: function(form) { submitIt(form); }
	});
}

/************************************ counter ***********************************/
/* Adds character counter span to text/textarea fields							*/
/********************************************************************************/
function counter() {
	$('input.counter:not(.counted), textarea.counter:not(.counted)').each(function() {				
		var maxlength = $(this).attr('maxlength');	
		if(maxlength > 0) {
			// get current number of characters  
			var length = $(this).val().length;  
			// get current number of words  
			//var length = $(this).val().split(/\b[\s,\.-:;]*/).length; 
			// Add span after input with character count
			$(this).after("<span class='counter'><span title='You have typed "+length+" characters of the "+maxlength+" characters allowed'>"+length+"/"+maxlength+"</span></span>");
			// bind on key up event  
			$(this).keyup(function(){  
				// get new length of characters  
				var new_length = $(this).val().length;
				// get new length of words  
				//var new_length = $(this).val().split(/\b[\s,\.-:;]*/).length;  
				// Update character count
				$(this).next("span.counter").html("<span title='You have typed "+new_length+" characters of the "+maxlength+" characters allowed'>"+new_length+"/"+maxlength+"</span>");
			}); 
			// Don't want to re-add counter span
			$(this).addClass('counted');
		}
	});
}

/************************************** drag ************************************/
/* Add draggability functionality to various elements							*/
/********************************************************************************/
function drag() {
	// Draggable
	/*** Implementaion Example ***/
	/*<ul class='drag'>
		<li class='draggable'><input type='hidden' class='dragged' value='$qry[photo_id]' /></li>
		<input type='hidden' name='type' value='photos' />
	</ul>
	*/
	$('div.drag, ul.drag, table.drag').sortable({
		items: 'div.draggable, li.draggable, tr.draggable',
		placeholder: 'helper',
		handle: ".handle",
		opacity: 0.5,
		stop : function () {
			var order = '';
			var type;
			var category;
			var module;
			$(this).find('input').each(function() {
				if(this.className == "dragged") order += '|' + this.value;
				if(this.name == "type") type = this.value;
				if(this.name == "category") category = this.value;
				if(this.name == "module") module = this.value;
			});
			if(order) $.ajax({type: 'POST',url: DOMAIN, data: 'ajaxRequest=orderIt&type='+type+'&module='+module+'&category='+category+'&order='+order, success: function(html) {debugIt(html);}});
			rows();
		}
	});
	
	$('div.dragThese, ul.dragThese, table.dragThese').sortable({
		items: 'div.dragThis, li.dragThis, tr.dragThis',
		placeholder: 'helper',
		opacity: 0.5,
		stop : function () { rows(); }
	});
}

/************************************ thickbox **********************************/
/* Removes old thickbox, adds new ones where class="thickbox" (call after ajax)	*/
/********************************************************************************/
function thickbox() {
	$('a.thickbox, area.thickbox, input.thickbox').each(function(i) { $(this).unbind('click'); });
	tb_init('a.thickbox, area.thickbox, input.thickbox');
}

/********************************** quicksearch *********************************/
/* Adds quicksearch functionality to input id='quicksearch_q for ul with id='quicksearch'*/
/********************************************************************************/
function quicksearch() {
	$('#quicksearch_q').liveUpdate('#quicksearch');
}

/*********************************** texteditor *********************************/
/* Adds texteditor (TinyMCE) to textarea's with class='texteditor'				*/
/********************************************************************************/
function texteditor() {
	// LWRTE (Light weight rich texteditor)
	$('textarea.texteditor:not(.textedited)').addClass('textedited').rte({
		css: [DOMAIN+'css/css.css',DOMAIN+'css/basic.css'],
		style: 'lwrte_body',
		controls_rte: public_toolbar,
		controls_html: html_toolbar
	});
}

/************************************** nest ************************************/
/* Makes li class="nestable" elements nestable within a ul class="nest" list 	*/
/********************************************************************************/
function nest() {
	$('ul#nest').NestedSortable( {
		accept: 'nested',
		noNestingClass: "unnested",
		opacity: .8,
		helperclass: 'helper',
		autoScroll: true,
		handle: '.handle',
		onChange : function(serialized) {
			var module = $('ul.nest input[name=module]').val();
			var parent = $('ul.nest input[name=parent]').val();
			$.ajax({
				type: 'POST',
				url: DOMAIN,
				data: 'ajaxRequest=nestIt&module='+module+'&parent='+parent+'&'+serialized[0].hash,
				success: function(html) {
					debugIt(html);	
				}
			});
		}
	});
}

/************************************* buttons **********************************/
/* Shows / hides elements with class=buttons on mouseover / mouseout			*/
/********************************************************************************/
function buttons() {
	//$('div.buttons').parent('div').mouseover(function() { $('div.buttons',this).show(); }).mouseout(function() { $('div.buttons',this).hide(); });
	$('div.button, li.button').mouseover(function() { $('div.buttons',this).show(); }).mouseout(function() { $('div.buttons',this).hide(); });
}

/*************************************** png ************************************/
/* Fixes .png images for IE <= 6												*/
/********************************************************************************/
function png() {
	$('body').pngFix();
}

/************************************ messages **********************************/
/* Removes '_message' and '_error' divs											*/
/********************************************************************************/
function messages() {
	$('div.slideDown').slideDown(1000,0).removeClass('slideDown');
	$('div.slideUp').slideUp(1000,0).removeClass('slideUp');
	$('div.fadeOut').fadeOut(1000,0).removeClass('fadeOut');
	$('div.fadeIn').fadeIn(1000,0).removeClass('fadeIn');
	
	$('div._error').animate({opacity: 1.0}, 5000).slideUp(500,function() { $(this).remove(); });
	$('div._message').animate({opacity: 1.0}, 5000).slideUp(700,function() { $(this).remove(); });
}

/********************************************************************************/
/******************************** PHP Functions *********************************/
/********************************************************************************/

/********************************* str_replace **********************************/
function str_replace(search, replace, subject) {
    var f = search, r = replace, s = subject;
    var ra = is_array(r), sa = is_array(s), f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;

    while (j = 0, i--) {
        while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
    };
     
    return sa ? s : s[0];
}

/*********************************** is_array ***********************************/
function is_array( mixed_var ) {
    return ( mixed_var instanceof Array );
}

/********************************* number_format ********************************/
function number_format(number,decimals,dec_point,thousands_sep) {
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}