function startEditing(name){
	tinyMCE.init({
		mode: "exact",
		elements : name,
		//script_url : '/resources/js/tiny_mce/tiny_mce.js',
		
		forced_root_block : false,
		force_br_newlines : true,
		force_p_newlines : false,
		
		// General options
		theme : "advanced",
		plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,phpimage",

		// Theme options
		theme_advanced_buttons1 : "save,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect",
		theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,phpimage,cleanup,code,|,insertdate,inserttime,|,forecolor,backcolor",
		theme_advanced_buttons3 : "hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,|,fullscreen,|cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
		// theme_advanced_buttons4 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : false
		
		
		// Example content CSS (should be your site CSS)
		//content_css : "css/content.css"
		// Drop lists for link/image/media/template dialogs
		/*
		 * template_external_list_url : "lists/template_list.js",
		 * external_link_list_url : "lists/link_list.js",
		 * external_image_list_url : "lists/image_list.js",
		 * media_external_list_url : "lists/media_list.js",
		 *  // Replace values for the template plugin template_replace_values : {
		 * username : "Some User", staffid : "991234" }
		 */
	});
	$('#EditButton'+name).hide();
	$('#CancelButton'+name).show();
}

function cancelEditing(name){
	//tinyMCE.Editor(name).hide(name);
	tinyMCE.execCommand('mceRemoveControl', false, name);
	$('#EditButton'+name).show();
	$('#CancelButton'+name).hide();
}

function editForm(formUrl, params, isAjax){
	if(params == null || params == undefined){
		params='';
	}
	if(isAjax !== false){
		isAjax = true;
	}
	
	$("#editForm").empty();
	$.getJSON(formUrl + params, function(data) {
		$("#editForm").formation({action:data["action"]+params, isAjax:isAjax, callback: successEdit}); 
		for(var fieldName in data['fields']) {
			var attrs= new Array();
			
			attrs["name"] = fieldName;
			
			if(data["fields"][fieldName]["id"] != null){
				attrs["id"] = data["fields"][fieldName]["id"];
			}
			if(data["fields"][fieldName]["label"] != null){
				attrs["labelValue"] = data["fields"][fieldName]["label"];
			}
			if(data["fields"][fieldName]["value"] != null){
				attrs["value"] = data["fields"][fieldName]["value"];
			}
			if(data["fields"][fieldName]["required"] != null){
				attrs["required"] = data["fields"][fieldName]["required"];
			}
			if(data["fields"][fieldName]["validation"] != null){
				attrs["validation"] = data["fields"][fieldName]["validation"];
			}
			if(data["fields"][fieldName]["active"] != null){
				attrs["active"] = data["fields"][fieldName]["active"];
			}
			if(data["fields"][fieldName]["autocomplete"] != null){
				attrs["autocomplete"] = data["fields"][fieldName]["autocomplete"];
			}
			if(data["fields"][fieldName]["regex"] != null){
				attrs["regex"] = data["fields"][fieldName]["regex"];
				// attrs["regex"] = "^.{4,6}$";
			}
			if(data["fields"][fieldName]["legend"] != null){
				attrs["legend"] = data["fields"][fieldName]["legend"];
				// attrs["regex"] = "^.{4,6}$";
			}
			
			if(data["fields"][fieldName]["type"] == "text" || data["fields"][fieldName]["type"] == "password"){
				attrs["type"] = data["fields"][fieldName]["type"];
				$.formation.addInput(attrs); 
			}
			if(data["fields"][fieldName]["type"] == "checkboxes"){
				$.formation.addCheckboxes(
					data["fields"][fieldName]["items"], attrs
				); 
			}
			if(data["fields"][fieldName]["type"] == "select"){
				$.formation.addSelect(data["fields"][fieldName]["options"], attrs); 
			}
			
		}
		$.formation.addButton({value: "Submit"});
		
		if(data['customJS'] != undefined && data['customJS']!=null){
			eval(data['customJS']);
		}
	});

	$('#editForm').dialog('open');
}

function successEdit(data, statusText, xhr, $form){
	$('#blockscreen').remove();
	if(data["status"] == 1){
		$('#editForm').dialog('close');
		parseCallbackData(data);
	}
	parseErrorInfo(data);
}

function parseErrorInfo(data){
	if(data["infos"].length){
		$.each(data["infos"], function(index, value) {
			wInfo.addInfo(value[0]);
		});
		wInfo.showInfos();
	}
			
	if(data["errors"].length){
		$.each(data["errors"], function(index, value) {
			wInfo.addError(value[0]);
		});
		wInfo.showErrors();
	}
}

function parseCallbackData(data){
	for(var field in data["updateFields"]){
		if(field != null){
			$('#'+field).html(data["updateFields"][field]);
		}
	}
	
	for(var field in data["itemsToDelete"]){
		if(field != null){
			$('#'+data["itemsToDelete"][field]).remove();
		}
	}
	
	for(var field in data["itemsToEmpty"]){
		if(field != null){
			$('#'+data["itemsToEmpty"][field]).html('');
		}
	}
	
	for(var field in data["itemsToAdd"]){
		if(typeof data["itemsToAdd"][field] == "object"){
			for(var container in data["itemsToAdd"][field]){
				if(container != null){
					$('#'+container).append(data["itemsToAdd"][field][container]);
				}
			}
		}
		else if(field != null){
			$('#'+field).append(data["itemsToAdd"][field]);
		}
	}
	
	for(var field in data["itemsToUnhide"]){
		if(field != null){
			$('#'+data["itemsToUnhide"][field]).fadeIn("slow");
		}
	}
	
	for(var field in data["itemsToHide"]){
		if(field != null){
			$('#'+data["itemsToHide"][field]).fadeOut("slow");
		}
	}
}

function toggleCheckboxes(masterCheckbox, masterNode){
	$("#"+ masterNode +" :checkbox[not(#"+masterCheckbox+")]").attr("checked", $("#"+masterCheckbox).attr('checked'));
}

function deleteItems(deleteActionUrl, form, confirmMessage){
	if(confirm(confirmMessage)){
		$.post(deleteActionUrl, 
				 $("#"+form).serialize(),
				 function(data, textStatus, XMLHttpRequest){
			if(data["status"] == 1){
				parseCallbackData(data);
				parseErrorInfo(data);
			}
		}
		, 'json');
	}
}

function clearForm(form) {
	$(':input', form).each(function() {
		var type = this.type;
		var tag = this.tagName.toLowerCase();
		
		if (type == 'text' || type == 'password' || tag == 'textarea'){
			this.value = "";
		}
		else if (type == 'checkbox' || type == 'radio'){
			this.checked = false;
		}
		else if (tag == 'select'){
			this.selectedIndex = -1;
		}
	});
}

function dynamicForm(formUrl, params){
	if(params == null || params == undefined){
		params='';
	}
	
	$("#editForm").empty();
	
	$.getJSON(formUrl + params, function(data) {
		$("#editForm").formation({action:data["action"]+params, isAjax:true, callback: successEdit}); 
		for(var fieldName in data['fields']) {
			var attrs= new Array();
			
			attrs["name"] = data['fields'][fieldName]['name'] || fieldName;
			
			if(data["fields"][fieldName]["label"] != null){
				attrs["labelValue"] = data["fields"][fieldName]["label"];
			}
			if(data["fields"][fieldName]["value"] != null){
				attrs["value"] = data["fields"][fieldName]["value"];
			}
			if(data["fields"][fieldName]["required"] != null){
				attrs["required"] = data["fields"][fieldName]["required"];
			}
			if(data["fields"][fieldName]["validation"] != null){
				attrs["validation"] = data["fields"][fieldName]["validation"];
			}
			if(data["fields"][fieldName]["active"] != null){
				attrs["active"] = data["fields"][fieldName]["active"];
			}
			if(data["fields"][fieldName]["regex"] != null){
				attrs["regex"] = data["fields"][fieldName]["regex"];
				// attrs["regex"] = "^.{4,6}$";
			}
			
			if(data["fields"][fieldName]["type"] == "text" || data["fields"][fieldName]["type"] == "password"){
				attrs["type"] = data["fields"][fieldName]["type"];
				$.formation.addInput(attrs); 
			}
			if(data["fields"][fieldName]["type"] == "select"){
				$.formation.addSelect(data["fields"][fieldName]["options"], attrs); 
			}
			
		}
		
		$("#editForm #formation ul li:first label span")
			.before(' <a id="add" href="#">[+]</a>'+
					'<a id="remove" href="#">[-]</a>'+
					 '<a id="remove-first" href="#">[-]</a>');
				
		$("#editForm #formation #remove-first").click(function(){
			$(this).parents("#editForm #formation ul").children().remove();
			$("#editForm").formation.addButton({value: "Submit", id:"submit-button"});
		});
		
		var dynForm = $("#editForm #formation ul")
			.dynamicForm("#add", "#remove", {
				// limit:5,
				formPrefix: "customFields",
				afterClone: function(clone){
					$("#remove-first", clone).remove();
				}
			});
		
		$("#editForm #formation ul")
			.before($("#editForm #formation #add").cloneWithAttribut(true));
		
		dynForm.inject(data['data']);
		
		$.formation.addButton({value: "Submit", id:"submit-button"});
	    // alert(data['email']['active']);
	});
	
	$('#editForm').dialog('open');
}

function getCheckedCheckboxes(masterCheckbox, masterNode){
	return $(masterNode +" :checkbox:checked:not("+masterCheckbox+")");
}

function getOneCheckedCheckbox(masterCheckbox, masterNode){
	var checkbox = getCheckedCheckboxes(masterCheckbox, masterNode);
	if(checkbox.length != 1){
		alert("Please select one checkbox.");
	}
	else{
		return checkbox;
	}
}

function drawDateRangeFields(){
	var selectName = $("select.date-range").attr("name");
	
	var container = $("div.date-range-container");
	$(".date-range-item", $(container))
		.each(function(){
			$(this).datepicker({
				altField: $("#hidden-"+$(this).attr("id"), $(container)),
				altFormat: "yy-mm-dd",
				//showOn: 'button',
//				buttonText: 'Please pick up a date',
				showOn: 'focus',
				changeMonth: true,
				changeYear: true,
				maxDate: '+10y',
				minDate: '-10y',
				dateFormat: 'mm/dd/yy',
//				buttonImage: SITE_PATH + 'resources/img/icons/calendar.png',
//				buttonImageOnly: true,
				defaultDate: '-0y'
			});
		});
	
	$("select.date-range")
		.change(function(){
			if($(this).attr("value") == 4){
				$(this).parent().siblings("div.date-range-container").show();
			}
			else{
				$(this).parent().siblings("div.date-range-container").hide();
			}
		});
}
$(document).ready(drawDateRangeFields);

function submitAjaxForm(ajaxForm, path){
	$.post(
		path, 
		$(ajaxForm).serialize(), 
		function(response){
			successEdit($.parseJSON(response));
		}
	);
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)){
		num = "0";
	}
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num * 100 + 0.50000000001);
	cents = num % 100;
	num = Math.floor(num/100).toString();
	if(cents<10){
		cents = "0" + cents;
	}
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++){
		num = num.substring(0, num.length - (4 * i + 3)) + ',' +
				num.substring(num.length - (4 * i + 3));
	}
	return (((sign)?'':'-') + num + '.' + cents);
}

function currencyToNumber(currency){
	num = currency.toString().replace(/[^0-9\.]/g,'');
	return num;
}

function updateInvoiceTotals(){
	var subTotal = Number(0);
	$(".invoice-qty-field")
		.each(function(){
			var id = $(this).attr("id").replace("invoice-qty-", "");
			var total = Number(
				parseFloat(
					currencyToNumber($("#invoice-price-"+id).attr("value"))
				) *	parseFloat($(this).attr("value"))
			);
			$("#invoice-total-"+id).html(formatCurrency(total?total.toFixed(2):0));
			subTotal += Number(total?total.toFixed(2):0);
		});
	$(".invoice-qty-price")
		.each(function(){
			var id = $(this).attr("id").replace("invoice-price-", "");
			var total = Number(
				parseFloat($("#invoice-qty-"+id).attr("value")) *
			   	parseFloat(currencyToNumber($(this).attr("value")))
			);
			$("#invoice-total-"+id).html(formatCurrency(total?total.toFixed(2):0));
			subTotal += Number(total?total.toFixed(2):0);
		});
	$("#invoice-subtotal").html(formatCurrency(subTotal));
	var penalty = Number(parseFloat($("#invoice-penalty").attr("value")));
	var interest = Number(parseFloat($("#invoice-interest").attr("value")));
	var paid = Number(parseFloat($("#invoice-paid").html()));
	subTotal += Number(penalty?penalty.toFixed(2):0);
	subTotal += Number(interest?interest.toFixed(2):0);
	subTotal -= Number(paid?paid.toFixed(2):0);
	$("#invoice-grand-total").html(formatCurrency(subTotal));
}

function editInvoice(){
	
	$(".invoice-qty-field, .invoice-price-field, #invoice-penalty, #invoice-interest")
		.removeClass("plain-text")
		.addClass("invoice-field")
		.keyup(updateInvoiceTotals);
	$("#invoice-status").removeClass("view").addClass("edit");
	$("#invoice-statement-date").removeClass("view").addClass("edit");
	$("#invoice-due-date").removeClass("view").addClass("edit");
}

function hideEditInvoiceFields(){
	$(".invoice-qty-field, .invoice-price-field, #invoice-penalty, #invoice-interest")
		.removeClass("invoice-field")
		.addClass("plain-text")
	$("#invoice-status").removeClass("edit").addClass("view");
	
	$("#invoice-statement-date span").html($("#invoice-statement-date input").val());
	$("#invoice-due-date span").html($("#invoice-due-date input").val());
	
	$("#invoice-statement-date").removeClass("edit").addClass("view");
	$("#invoice-due-date").removeClass("edit").addClass("view");
}

function editInvoicePrices(event){
	event.preventDefault();
	$(".invoice-price-field")
		.removeClass("plain-text")
		.addClass("invoice-field");
	$("#save-invoice-prices").show();
	$("#edit-invoice-prices").hide();
}

function hideInvoicePriceFields(){
	$(".invoice-price-field")
		.removeClass("invoice-field")
		.addClass("plain-text")
	$("#save-invoice-prices").hide();
	$("#edit-invoice-prices").show();
}

function clearOnFocus(obj, value){
	if(obj.value == value){
		obj.value = "";
	}
}

$(document).ready(function(){
	$("input.button").hover(
		function () {
			$(this).addClass("hover");
		},
		function () {
			$(this).removeClass("hover");
		}
	);
});


var W3CDOM = (document.createElement && document.getElementsByTagName);

function initFileUploads() {
	if (!W3CDOM) return;
	var fakeFileUpload = document.createElement('div');
	fakeFileUpload.className = 'fakefile';
	fakeFileUpload.appendChild(document.createElement('input'));
	//var image = document.createElement('img');
	//image.src='pix/button_select.gif';
	//fakeFileUpload.appendChild(image);
	var x = document.getElementsByTagName('input');
	for (var i=0;i<x.length;i++) {
		if (x[i].type != 'file') continue;
		if (x[i].parentNode.className != 'fileinputs') continue;
		x[i].className = 'file hidden';
		var clone = fakeFileUpload.cloneNode(true);
		x[i].parentNode.appendChild(clone);
		x[i].relatedElement = clone.getElementsByTagName('input')[0];
		x[i].onchange = x[i].onmouseout = function () {
			this.relatedElement.value = this.value;
		}
	}
}

