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

/******************************** document.ready ********************************/
/* Functions to Run When Page Loaded											*/
/********************************************************************************/
$(document).ready(function () {		
	validate();
	drag();
});

/************************************* tabIt ************************************/
/* Opens / closes tabs onmouseover / onmouseout									*/
/********************************************************************************/
var timer = new Array;
function tabIt(tab,over) {
	if(timer[tab]) {
		clearTimeout(timer[tab]);
	}
	if(over == 1) {
		//if(str_replace('sub_','',tab) != tab) $('div.sub').hide();
		//else if(tab == "nav_categories") $('#nav_brands').hide();
		//else if(tab == "nav_brands") $('#nav_categories').hide();
		showIt(tab);
	}
	else {
		//hideIt(tab);
		timer[tab] = setTimeout('hideIt(\''+tab+'\');',200);
	}
}

/********************************************************************************/
/*********************************** Product ************************************/
/********************************************************************************/

/********************************** saveText ************************************/
/* Gets text from given input, sends ajax to save text in session				*/
/********************************************************************************/
function saveText(input,name,array) {
	var v = $('#'+input).val();
	// AJAX
	$.ajax({
		type: 'GET',
		url: DOMAIN+'?ajaxRequest=saveText&name='+name+'&array='+array+'&v='+v
	});
}

/******************************** addVariation **********************************/
/* Adds new product variation to product form									*/
/********************************************************************************/
function addVariation(input,div) {
	var v = $('#'+input).val();
	// AJAX
	$.ajax({
		type: 'GET',
		url: DOMAIN+'?ajaxRequest=addVariation&v='+v,
		success: function(html){
			$('#'+div).append(html);
			
			updateQuantity();
			updatePrices();
			updateSku();
			
			messages();
			rows();
			drag();
			
			$('#'+input).val("");
			
			showIt('variations_header');
		}
	});
}

/*********************************** addSize ************************************/
/* Adds new product size to product form										*/
/********************************************************************************/
function addSize(input,div) {
	var s = $('#'+input).val();
	// AJAX
	$.ajax({
		type: 'GET',
		url: DOMAIN+'?ajaxRequest=addSize&s='+s,
		success: function(html){
			$('#'+div).append(html);
			
			updateQuantity();
			updatePrices();
			updateSku();
			
			messages();
			rows();
			drag();
			
			$('#'+input).val("");
			
			showIt('sizes_header');
		}
	});
}

/***************************** addRecommendation ********************************/
/* Adds new product recommendation to product form								*/
/********************************************************************************/
function addRecommendation(input,div) {
	var r = $('#'+input).val();
	// AJAX
	$.ajax({
		type: 'GET',
		url: DOMAIN+'?ajaxRequest=addRecommendation&r='+r,
		success: function(html){
			$('#'+div).append(html);
			messages();
			rows();
			drag();
			
			$('#'+input).val("");
			
			showIt('recommendations_header');
		}
	});
}

/******************************* updateQuantity ********************************/
/* Adds new product size to product form										*/
/********************************************************************************/
function updateQuantity() {
	var div = 'quantities';
	var row = 'quantity';
	// AJAX
	$.ajax({type: 'GET',url: DOMAIN+'?ajaxRequest=updateQuantity',success: function(html){
		if(html.length > 0) {
			$('#'+div).html(html);
			showIt(row);
		}
		else hideIt(row);
	}});
	
	$('form.require').each(function() { 
		$(this).validate({
			submitHandler: function(form) { submitIt(form); }
   		}); 
	}); 
}

/********************************** updateSku ***********************************/
/* Updates sku fields for the product form										*/
/********************************************************************************/
function updateSku() {
	var div = 'skus';
	var row = 'sku';
	// AJAX
	$.ajax({type: 'GET',url: DOMAIN+'?ajaxRequest=updateSku',success: function(html){
		if(html.length > 0) {
			$('#'+div).html(html);
			showIt(row);
		}
		else hideIt(row);
	}});
	
	$('form.require').each(function() { 
		$(this).validate({
			submitHandler: function(form) { submitIt(form); }
   		}); 
	}); 
}

/******************************** updatePrices **********************************/
/* Updates price fields for the product form									*/
/********************************************************************************/
function updatePrices() {
	var div = 'prices';
	var row = 'price';
	// AJAX
	$.ajax({type: 'GET',url: DOMAIN+'?ajaxRequest=updatePrices',success: function(html){
		if(html.length > 0) {
			$('#'+div).html(html);
			showIt(row);
		}
		else hideIt(row);
	}});
	
	$('form.require').each(function() { 
		$(this).validate({
			submitHandler: function(form) { submitIt(form); }
   		}); 
	}); 
}

/************************************ 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){
			if(table == "photos" && column == "photo_name") {
				var i = str_replace('_name','_file',div);
				$('#'+i).attr('title',html);
				$('#'+div).html('');
			}
			else $('#'+div).html(html);
			
			// Redirect
			if(redirect != "" && redirect != "undefined" && redirect != undefined && redirect) location.assign(DOMAIN+redirect);
			
			// Refresh jQuery
			$('.sortable').trigger("update");
			tb_init(this);
		}
	});
}

/************************************ 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();
					
					// Product
					if(table == "products_sizes" || table == "products_variations") {
						updateQuantity();
						updateSku();
						updatePrices();
					}
				}
			});
		});
	}
}

/************************************ 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();
			tb_init(this);
			messages();
			$('.sortable').trigger("update");
		}
	});
}

/************************************ removeIt **********************************/
/* Removes div																	*/
/********************************************************************************/
function removeIt(id) {
	$('#'+id).remove();
}

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

/********************************** uploadGallery *******************************/
/* Uploads file in given input field to given path (defaults to DOMAIN/uploads/)*/
/********************************************************************************/
var uploadGallery_n = 0;
function uploadGallery(div,input,path,gallery) {
	var file = $('#'+input).val();
	if(file) {
		// Total Number of Current Uploads
		uploadGallery_n = uploadGallery_n + 1;
		
		// Loader
		$.ajax({
			type: 'GET',
			url: DOMAIN+'?ajaxRequest=previewGallery&x='+uploadGallery_n+'&div='+div+'&file='+file,
			success: function(html){
				$("#"+div).prepend(html);
				var d = div+'_'+uploadGallery_n;
				
				// Upload Photo
				$.ajaxFileUpload({
					url:DOMAIN+'?ajaxRequest=uploadGallery&path='+path+'&d='+d+'&gallery='+gallery,
					secureuri:false,
					fileElementId:input,
					dataType: 'script',
					success: function (data, status) {
						$("#"+d).html(data);
						tb_init(this);
						drag();
						
						// Hide Failure Messages
						$("#red").animate({opacity: 1.0}, 1500).slideUp(500, function() {
							$(this).remove();
						});
						
					}
				});
				
				// Clear File Input
				$('#'+input).animate({opacity: 1.0}, 50,function(){
					document.getElementById(input).value = "";
				});
				
			}
		});
	}
	return false;
}

/*********************************** uploadPhoto ********************************/
/* Uploads file in given input field to given path (defaults to DOMAIN/uploads/)*/
/********************************************************************************/
var uploadPhoto_n = 0;
function uploadPhoto(div,input,v,path) {
	var file = $('#'+input).val();
	if(file) {
		// Total Number of Current Uploads
		uploadPhoto_n = uploadPhoto_n + 1;
		
		// Loader
		$.ajax({
			type: 'GET',
			url: DOMAIN+'?ajaxRequest=previewPhoto&x='+uploadPhoto_n+'&div='+div+'&file='+file+'&v='+v,
			success: function(html){
				$("#"+div).append(html);
				var d = div+'_'+uploadPhoto_n;
				
				// Upload Photo
				$.ajaxFileUpload({
					url:DOMAIN+'?ajaxRequest=uploadPhoto&path='+path+'&d='+d+'&v='+v,
					secureuri:false,
					fileElementId:input,
					dataType: 'script',
					success: function (data, status) {
						// Swap "Uploading" for result
						$("#"+d).html(data);
						// Remove "Uploading" add Photo Info Box
						/*$("#instructions").hide();
						$("#"+results).show().append(data);
						$("#submit").show();
						$("#"+d+'_up').slideDown(500);
						$("#"+d).slideUp(500, function() {
							$(this).remove();
						});*/
						
						rows();
						tb_init(this);
						drag();
						
						// 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;
}

/*********************************** 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.2);
	}
	
	// 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].'+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() {
	$('.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() {
	$('.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 **********************************/
/* Adds thickbox functionality to all elements with class="thickbox"			*/ 
/* (only call if added after page load)											*/
/********************************************************************************/
function thickbox() {
	// Remove Existing Thickbox
	//$('.thickbox').each(function(i) $(this).unbind('click'); });
	// Re-Initalize Thickbox
	//tb_init('a.thickbox, area.thickbox, input.thickbox');
}

/************************************ validate **********************************/
/* Adds validation functionality 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: {
			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); }
	});
}

/************************************** drag ************************************/
/* Adds Dragabble functionality to dragThese dragThis 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>*/
			
	$('.drag').sortable({
		items: '.draggable',
		placeholder: 'helper',
		handle: ".handle",
		opacity: 0.5,
		stop : function () {
			var order = '';
			var type;
			var cat;
			var brand;
			$(this).find('input').each(function() {
				if(this.className == "dragged") order = order + '|' + this.value;
				if(this.name == "type") type = this.value;
				if(this.name == "cat") cat = this.value;
				if(this.name == "brand") brand = this.value;
			});
			if(order) $.ajax({type: 'GET',url: DOMAIN+'?ajaxRequest=orderIt&type='+type+'&cat='+cat+'&brand='+brand+'&order='+order});
			rows();
		}
	});
	
	$('.drag1').sortable({
		items: '.draggable1',
		placeholder: 'helper',
		handle: ".handle1",
		opacity: 0.5,
		stop : function () {
			var order = '';
			var type;
			var cat;
			var brand;
			$(this).find('input').each(function() {
				if(this.className == "dragged1") order = order + '|' + this.value;
				if(this.name == "type1") type = this.value;
				if(this.name == "cat1") cat = this.value;
				if(this.name == "brand1") brand = this.value;
			});
			if(order) $.ajax({type: 'GET',url: DOMAIN+'?ajaxRequest=orderIt&type='+type+'&cat='+cat+'&brand='+brand+'&order='+order});
			rows();
		}
	});
	
	$('.dragThese').sortable({
		items: '.dragThis',
		placeholder: 'helper',
		opacity: 0.5,
		stop : function () { rows(); }
	});
}

/************************************* color ************************************/
/* Adds colorpicker functionality to all inputs with class='color'				*/
/********************************************************************************/
function color() {
	var c = $('input.color').val();
	$('input.color').after('<img src="'+DOMAIN+'images/blank.gif" width="16" height="16" style="vertical-align:middle;margin-left:2px;border:1px solid #333333;background:#'+c+';" class="color" />')
	$('input.color').ColorPicker({
		onSubmit: function(hsb, hex, rgb) {
			$('input.color').val(hex);
			$('img.color').css('background','#'+hex);
			$('.colorpicker').css('display', 'none');
		},
		onBeforeShow: function () {
			$(this).ColorPickerSetColor(this.value);
			$('img.color').css('background','#'+this.value);
		}
	});
}

/************************************ messages **********************************/
/* Removes '_message' and '_error' divs											*/
/********************************************************************************/
function messages() {
	$('#_error').animate({opacity: 1.0}, 5000).slideUp(500,0);
	$('._error').animate({opacity: 1.0}, 5000).slideUp(500,0);
	$('#_message').animate({opacity: 1.0}, 5000).slideUp(700,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);
}