/******************************* onload functions *******************************/
/* Functions to Run When Page Loads												*/
/********************************************************************************/
$(function() {
	// Hide Session Message / Error
	$('#_error').animate({opacity: 1.0}, 5000).slideUp(500,0);
	$('#_message').animate({opacity: 1.0}, 5000).slideUp(700,0);
	// Row Backgrounds
	rows();
	// Tooltips
	tips();
	// Calendars
	calendar();
	
	$('textarea.limited1').maxlength({ 'feedback': '.wordsLeft1' });
	$('textarea.limited2').maxlength({ 'feedback': '.wordsLeft2' });
	$('textarea.limited3').maxlength({ 'feedback': '.wordsLeft3' });
	$('textarea.limited4').maxlength({ 'feedback': '.wordsLeft4' });
	$('textarea.limited5').maxlength({ 'feedback': '.wordsLeft5' });
	// SpellCheck
	spellcheck();
});

$(document).ready(function () {	
	// Validate
	validate();
	// Default Values
	defaults();
	// Superfish
	$('ul.sf-menu').superfish({ 
		delay:       200,
		animation:   {opacity:'show',height:'show'},
		autoArrows:  false
	});
});

// Double Click Radio Button
function clickIt(name) {
    var rb = document.getElementsByName(name);
    for( var i=0; i < rb.length; i++) {
         rb[i].checked = false;
    }
}

/************************************ 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;' />");
	f.submit();
}

/************************************ 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)) {
		if(document.getElementById(div).style.display=="none") $('#'+div).slideDown(500);
		else $('#'+div).slideUp(500);
	}
	/*if(document.getElementById(div).style.display=="none") document.getElementById(div).style.display = "block";
	else document.getElementById(div).style.display = "none";*/
}

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

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

/*********************************** saveInline *********************************/
/* Gets inline variable and saves it											*/
/********************************************************************************/
function saveInline(div,table,column,key,id,redirect) {
	var value = document.getElementById(div+'_inline').value;
	// AJAX
	$.ajax({
		type: 'GET',
		url: DOMAIN+'?ajaxRequest=saveInline&table='+table+'&column='+column+'&div='+div+'&key='+key+'&id='+id+'&value='+encodeURIComponent(value)+'&redirect='+redirect,
		success: function(html){
			$('#'+div).html(html);
			
			// Redirect
			if(redirect != "" && redirect != "undefined") location.assign(DOMAIN+redirect);
		}
	});
}

/********************************** cancelInline ********************************/
/* Cancels inline edit															*/
/********************************************************************************/
function cancelInline(div,table,column,key,id) {
	// AJAX
	$.ajax({
		type: 'GET',
		url: DOMAIN+'?ajaxRequest=cancelInline&table='+table+'&column='+column+'&div='+div+'&key='+key+'&id='+id,
		success: function(html){
			$('#'+div).html(html);
		}
	});
}

/************************************ 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 = vals + '&' + this.name + '=' + encodeURIComponent(this.value);
		}
		else if(this.type == "select-multiple") vals = vals + '&' + this.name + '=' + encodeURIComponent($(this).val());
		else vals = 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){
			if(loc == "prepend") $('#'+div).prepend(html);
			else if(loc == "append") $('#'+div).append(html);
			else $("#"+div).html(html);
			
			// Submit Button
			var s = $("#"+form+" input[type='submit']").fadeTo("normal", 1.0).removeAttr("disabled");
			$('img.submit_loader').each(function() { $(this).remove(); });
			
			// Refresh jQuery
			rows();
			thickbox();
			validate();
			messages();
		}
	});
}

/************************************ 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=delete&table='+table+'&div='+div+'&id='+id+'&key='+key,
				success: function(html){
					if(html.length > 0) $('#'+div).html(html);
					else $('#'+div).remove();
					
					rows();
					
					// Redirect
					if(document.getElementById('redirect')) location.assign(DOMAIN+document.getElementById('redirect').value);
				}
			});
		});
	}
}

/*********************************** uploadFile *********************************/
/* Uploads file in given input field to given path (defaults to DOMAIN/uploads/)*/
/********************************************************************************/
var uploadFile_n = 0;
function uploadFile(div,results,input,path) {
	var file = $('#'+input).val();
	var session = $('#session').val();
	if(!session) {
		document.getElementById(input).value = "";
		alert('You must include a session before you may upload.');
	}
	else if(file) {
		// Total Number of Current Uploads
		uploadFile_n = uploadFile_n + 1;
		
		// Loader
		$.ajax({
			type: 'GET',
			url: DOMAIN+'?ajaxRequest=previewFile&x='+uploadFile_n+'&div='+div+'&file='+file,
			success: function(html){
				$("#"+div).append(html);
				var d = div+'_'+uploadFile_n;
				$("#"+d).slideDown(350);
				
				// Upload Photo
				$.ajaxFileUpload({
					url:DOMAIN+'?ajaxRequest=uploadFile&path='+path+'&d='+d+'&session='+session,
					secureuri:false,
					fileElementId:input,
					dataType: 'script',
					success: function (data, status) {
						// Remove "Uploading" add Photo Info Box
						$("#"+results).show().append(data);
						$("#submit").show();
						$(".media").slideDown(350);
						$("#"+d).slideUp(350, function() {
							$(this).remove();
						});
						
						rows();
						thickbox();
						calendar();
						
						// 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: '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);
			}
		});
	}
}

/********************************* disableIt ************************************/
/* Disables given element														*/
/********************************************************************************/
/*function disableIt(id) {
	if(document.getElementById(id)) {
		document.getElementById(id).disabled = true;
		$('#'+id).css('cursor','default').fadeTo("normal", 0.4);
	}
}

/********************************** enableIt ************************************/
/* Enables given element														*/
/********************************************************************************/
/*function enableIt(id) {
	if(document.getElementById(id)) {
		document.getElementById(id).disabled = false;
		$('#'+id).css('cursor','pointer').css('cursor','hand').fadeTo("normal",1);
	}
}

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

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

/************************************** rows ************************************/
/* Adds alternate shading to odd and even rows where class="row"				*/
/********************************************************************************/
function rows() {
	$('.row:odd').addClass("odd").removeClass("even");
	$('.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 **********************************/
/* Removes old thickbox, adds new ones where class="thickbox" (call after ajax)	*/
/********************************************************************************/
function thickbox() {
	$('.thickbox').each(function(i) { $(this).unbind('click'); });
	tb_init('a.thickbox, area.thickbox, input.thickbox');
}

/************************************ validate **********************************/
/* Adds form validation to all forms with class="require"						*/
/********************************************************************************/
function validate() {
	// Form Validation
	$('form.require').each(function() { 
		$(this).validate({
			submitHandler: function(form) { submitIt(form); }
   		}); 
	}); 
	
	// Registration Validation
	$("#register").validate({
		rules: {
			email: { remote: DOMAIN+"?ajaxRequest=checkUsername" }, 
			confirm_password: { equalTo: "#password"}
		},
		messages: {
			email: { remote: "This e-mail address is already in use" },
			confirm_password: { equalTo: "Your passwords don't match" }
		},
		submitHandler: function(form) {	submitIt(form); }
	});
}

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

/*********************************** spellcheck *********************************/
/* Adds spellchecking to all inputs / textareas with class='spellcheck'			*/
/********************************************************************************/
function spellcheck() {
	$('input.spellcheck, textarea.spellcheck').spellcheck();
}

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

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

(function ($) {

$.fn.maxlength = function (settings) {

    if (typeof settings == 'string') {
        settings = { feedback : settings };
    }

    settings = $.extend({}, $.fn.maxlength.defaults, settings);

    function length(el) {
    	var parts = el.value;
    	if ( settings.words )
    		parts = el.value.length ? parts.split(/\s+/) : { length : 0 };
    	return parts.length;
    }
    
    return this.each(function () {
        var field = this,
        	$field = $(field),
        	$form = $(field.form),
        	limit = settings.useInput ? $form.find('input[name=maxlength]').val() : $field.attr('maxlength'),
        	$charsLeft = $form.find(settings.feedback);

    	function limitCheck(event) {
        	var len = length(this),
        	    exceeded = len >= limit,
        		code = event.keyCode;

        	if ( !exceeded )
        		return;

            switch (code) {
                case 8:  // allow delete
                case 9:
                case 17:
                case 36: // and cursor keys
                case 35:
                case 37: 
                case 38:
                case 39:
                case 40:
                case 46:
                case 65:
                    return;

                default:
                    return settings.words && code != 32 && code != 13 && len == limit;
            }
        }


        var updateCount = function () {
            var len = length(field),
            	diff = limit - len;

            $charsLeft.html( diff || "0" );

            // truncation code
            if (settings.hardLimit && diff < 0) {
            	field.value = settings.words ? 
            	    // split by white space, capturing it in the result, then glue them back
            		field.value.split(/(\s+)/, (limit*2)-1).join('') :
            		field.value.substr(0, limit);

                updateCount();
            }
        };

        $field.keyup(updateCount).change(updateCount);
        if (settings.hardLimit) {
            $field.keydown(limitCheck);
        }

        updateCount();
    });
};

$.fn.maxlength.defaults = {
    useInput : false,
    hardLimit : true,
    feedback : '.charsLeft',
    words : false
};

})(jQuery);
