/******************************* onload functions *******************************/
/* Functions to Run When Page Loads												*/
/********************************************************************************/
$(function() {
	// Messages
	messages();
	// Sortable Tables
	sortable();
	// Row Backgrounds
	rows();
	// Tooltips
	tips();
	// Calendars
	calendar();
});

/******************************** document.ready ********************************/
/* Functions to Run When Page Loaded											*/
/********************************************************************************/
$(document).ready(function () {		
	// Form Validation
	$('form.require').each(function() { 
		$(this).validate({
			submitHandler: function(form) { submitIt(form); }
   		}); 
	}); 
	
	// Registration Validation
	$("#register").validate({
		rules: {
			username: { remote: DOMAIN+"?ajaxRequest=checkUsername", regex: '[a-zA-Z0-9_\-]' }, 
			confirm_password: { equalTo: "#password"}
		},
		messages: {
			username: { remote: jQuery.format("This username is already taken"), regex: 'Your username may only contain letters and numbers' },
			confirm_password: { equalTo: "Your passwords don't match" }
		},
		submitHandler: function(form) {	submitIt(form); }
	});
		
		
	// Draggable
	/*** Implementaion Example ***/
	/*<form name='drag_form' onsubmit='return false;'>
		<ul class='drag'>
			<li class='draggable'><input type='hidden' class='dragged' value='$qry[photo_id]' /></li>
		</ul>
		<input type='hidden' name='type' value='photos' />
	</form>*/
	$('.drag').sortable({
		items: '.draggable',
		placeholder: 'helper',
		opacity: 0.5,
		stop : function () {
			var order = '';
			var f = document.drag_form;
			for(i = 0; i < 100; i++) {
				if(f.elements[i]) {
					if(f.elements[i].className == 'dragged') order = order + '|' + f.elements[i].value;
				}
			}
			$.ajax({type: 'GET',url: DOMAIN+'?ajaxRequest=orderIt&type='+document.drag_form.type.value+'&order='+order});
			rows();
		}
	});
});

function slideRight(id) {
	$('#'+id).animate({left: "0px"}, {queue:false, duration:250}); 
}
function slideLeft(id) {
	$('#'+id).animate({left: "-130px"}, {queue:false, duration:250}); 
}

/************************************ 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:100px;'><div style='position:absolute;left: 50%;margin-left:-40px;margin-top:30px;'><center><img src='"+DOMAIN+"images/ajax-loader.gif' style='vertical-align:middle;' /></center></div><div style='opacity:.30;filter:alpha(opacity=30);-moz-opacity:.3;'>"+document.getElementById(div).innerHTML+"</div></div>");
}

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

/************************************ showHide **********************************/
/* Shows or hides given div based upon it's current state						*/
/********************************************************************************/
function showHide(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();
}

/************************************ submitIt **********************************/
/* Submits form and disables submit button										*/
/********************************************************************************/
function submitIt(f) {
	var s = $(f).find("input[type='submit']");
	$(s).fadeTo("normal", 0.4).attr("disabled", "disabled").after("<img src='"+DOMAIN+"images/ajax-loader.gif' align='absmiddle' style='margin-left:4px;' id='submit_loader' />");
	f.submit();
}

/*********************************** editInline *********************************/
/* Retrieves code for inline editing of given variable							*/
/********************************************************************************/
function editInline(div,table,column,key,id,buttons,redirect) {
	// AJAX
	$.ajax({
		type: 'GET',
		url: DOMAIN+'?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) {
	// Form Element
	var v = document.getElementById(div+'_inline');
	
	// Select
	if(v.type=="select") var value = v.selectedIndex.value;
	// Radio
	else if(v.type=="radio") {
		for (var j = 0; j < v.length; j++){
			if (v[j].checked) var value = v[j].value;
		}	
	}
	// Checked
	else if(v.type=="checkbox") {
		if (v.checked == true) var value = v.value;
		else var value = 0;
	}
	// Textarea
	else if(v.type=="textarea") var value = v.value;
	// Input
	else var value = v.value;
	
	// AJAX
	$.ajax({
		type: 'GET',
		url: DOMAIN+'?ajaxRequest=saveInline&save='+save+'&table='+table+'&column='+column+'&div='+div+'&key='+key+'&id='+id+'&value='+encodeURIComponent(value)+'&buttons='+buttons+'&redirect='+redirect,
		success: function(html){
			$('#'+div).html(html);
			
			// Redirect
			if(redirect != "" && redirect != "undefined" && redirect != undefined && redirect) location.assign(DOMAIN+redirect);
			
			// Sortable
			$('.sortable').trigger("update");
		}
	});
}

/************************************ 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: 'GET',
				url: DOMAIN+'?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();
				}
			});
		});
	}
}

/************************************ saveIt ************************************/
/* Gets values from a form, posts to AJAX, and handles response					*/
/********************************************************************************/
function saveIt(form,div) {
	var f = document.getElementById(form);
	
	// Get Values
	var vals = "";
	for(i=0; i<f.elements.length; i++) {
		// Select
		if(f[i].type=="select") vals = vals + '&' + f[i].name + '=' + encodeURIComponent(f[i].selectedIndex.value);
		// Radio
		else if(f[i].type=="radio") {
			for (var j = 0; j < f[i].length; j++){
				if (f[i][j].checked) vals = vals + '&' + f[i].name + '=' + encodeURIComponent(f[i][j].value);
			}	
		}
		// Checked
		else if(f[i].type=="checkbox") {
			if (f[i].checked == true) vals = vals + '&' + f[i].name + '=' + encodeURIComponent(f[i].value);
			else vals = vals + '&' + f[i].name + '=' + 0;
		}
		// Textarea
		else if(f[i].type=="textarea") vals = vals + '&' + f[i].name + '=' + encodeURIComponent(f[i].value);
		// Input
		else vals = vals + '&' + f[i].name + '=' + encodeURIComponent(f[i].value);
	}
	
	$.ajax({
		type: 'GET',
		url: DOMAIN+'?ajaxRequest=saveIt&form='+form+'&div='+div+vals,
		success: function(html){
			$("#"+div).html(html);
			
			// Submit Button
			var s = $(f).find("input[type='submit']");
			$(s).fadeTo("normal", 1.0).removeAttr("disabled");
			$('#submit_loader').remove();
			
			// Refresh jQuery
			rows();
			thickbox();
			messages();
			$('.sortable').trigger("update");
		}
	});
}

/*********************************** updateIt ***********************************/
/* Handles various update scripts												*/
/********************************************************************************/
function updateIt(table,column,key,id) {
	$.ajax({
		type: 'GET',
		url: DOMAIN+'?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]);
					}
				}
			}
		}
	});
}

/************************************ 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;
}

/*********************************** requireIt **********************************/
/* Checks given form to make sure all required fields (class="required") were 	*/
/* filled in, else shows error message											*/
/********************************************************************************/
/*function requireIt(f) {
	var error = "";
	for(i = 0;i < f.elements.length; i++) {
		var temp = null;
		if(f[i].className == "required") {
			// Select
			if(str_replace('select','',f[i].type) != f[i].type)	{
				// Too lazy to figure out Multiple Select
				if(f[i].multiple);
				else if(f[i].options[f[i].selectedIndex].value == null || f[i].options[f[i].selectedIndex].value.length == 0 || f[i].options[f[i].selectedIndex].value == "") error = error + "You forgot to select a " + f[i].name + "\n";
			}
			// Radio
			else if(f[i].type=="radio") {
				for (var j = 0; j < f[i].length; j++){
					if (f[i][j].checked) temp = f[i][j].value;
				}	
				if(temp == null) error = error + "You forgot to select a " + f[i].name + "\n";
			}
			// Checked
			else if(f[i].type=="checkbox") {
				if (f[i].checked) var temp = 1;
				else error = error + "You forgot to check " + f[i].name + "\n";
			}
			// Textarea
			else if((f[i].type=="textarea" || f[i].type=="text") && f[i].value == "") error = error + "You forgot to enter a " + f[i].name + " value\n";
		}
	}

	var error = str_replace('_',' ',error);
	if(error.length > 5) {
		// Re-enable Submit Button
		enableIt('submit');
		
		// Show Alert
		alert(error);
		
		return false;
	}
	// Submit
	else {
		// Disable Submit Button
		disableIt('submit');
		
		// Button Text
		var submit_text = $('#submit').val();
		if(submit_text == "Save") var new_text = "Saving..";
		if(submit_text == "Submit") var new_text = "Submitting..";
		if(submit_text == "Filter") var new_text = "Filtering..";
		if(new_text) $('#submit').val(new_text);
		
		// AJAX Loader
		$('#submit').after("<img src='"+DOMAIN+"images/ajax-loader.gif' align='absmiddle' style='margin-left:4px;' />");
		
		return true;
	}
}

/********************************* 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: 'GET',
			url: DOMAIN+'?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: 'GET',
			url: DOMAIN+'?ajaxRequest=enableIt&table='+table+'&column='+column+'&div='+div+'&key='+key+'&id='+id+'&button='+button,
			success: function(html){
				$('#'+button).html(html);
			}
		});
	}
}

/************************************ Defaults **********************************/
/* Clears or Restores default value for input field								*/
/********************************************************************************/
function clearDefault(e) {
	if (e.defaultValue==e.value){
		e.value = "";
	}
}

function restoreDefault(e) {
	if (!e.value){
		e.value = e.defaultValue;
	}
}

/*********************************** 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].'+classclassID).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() {
	$('.tip').tooltip({
		track: true,
		delay: 0,
		showURL: false
	});
}

/*********************************** sortable ***********************************/
/* Runs scripts to sort tables with class="sortable"							*/
/********************************************************************************/
function sortable() {
	$('.sortable')
		.collapsible("td.collapsible", {
			collapse: true
		})
		.tablesorter({
			textExtraction: 'complex',
			widgets: ['zebra']
		});
}

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

/************************************ calendar **********************************/
/* Shows calendar date picker on all input fields with class="calendar"			*/
/********************************************************************************/
function calendar() {
	$('.calendar').datepicker({ 
		showOn: 'both', 
		buttonImage: DOMAIN+'images/calendar.png', 
		buttonImageOnly: true 
	});
}

/************************************ thickbox **********************************/
/* Adds thickbox functionality to all elements with class="thickbox"			*/ 
/* (only call if added after page load)											*/
/********************************************************************************/
function thickbox() {
	tb_init('a.thickbox, area.thickbox, input.thickbox');
}

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

/********************************************************************************/
/******************************** 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) : "");
}

/********************************************************************************/
/********************************** .PNG Fix ************************************/
/********************************************************************************/
if(!window.XMLHttpRequest) {
	var clear = "images/clear.gif" //path to clear.gif
	
	pngfix=function(){var els=document.getElementsByTagName('*');var ip=/\.png/i;var i=els.length;while(i-- >0){var el=els[i];var es=el.style;if(el.src&&el.src.match(ip)&&!es.filter){es.height=el.height;es.width=el.width;es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+el.src+"',sizingMethod='crop')";el.src=clear;}else{var elb=el.currentStyle.backgroundImage;if(elb.match(ip)){var path=elb.split('"');var rep=(el.currentStyle.backgroundRepeat=='no-repeat')?'crop':'scale';es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+path[1]+"',sizingMethod='"+rep+"')";es.height=el.clientHeight+'px';es.backgroundImage='none';var elkids=el.getElementsByTagName('*');if (elkids){var j=elkids.length;if(el.currentStyle.position!="absolute")es.position='static';while (j-- >0)if(!elkids[j].style.position)elkids[j].style.position="relative";}}}}}
	window.attachEvent('onload',pngfix);
}