var controls = {
	opacity 		:		0.5,
	opacityFull	:		1,
	fade				:		300
},
formType,
itemTemplates = {},
regs = {
		email 	: /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i,
		pass 		: /^[A-Za-z0-9!@#$%^&*()_]{6,20}$/, // Password supports special characters and here min length 6 max 20 charters.
		blank 	: /^.+[\s]{0,4}/ ,
		name		: /^[a-zA-Z0-9]{6,12}[\s]{0,4}/,
		phone		:	/^[0-9\-\+\(\). ]{7,24}/g
},
pbar,
userType,
newsType,
fileName,
newFileName,
newFileId,
uploadTime,
fileUploadOptions = {
	url: 'index.php?adJax=uploadFile',
	type: 'submit',
	iframe: 1,
	iframeSrc: 'index.php?adJax=',
	dataType: 'json',
	success: function(responseText, statusText, xhr, $form){
		AdDebug(responseText);
		if(responseText.error) {
			$('.adEditWindowFileStatus').empty().append('There was an error, please try again...');
			alert('There was an error uploading your file, please try again.');
		} else {
			// get the image
			newFileId = responseText.id;
			
			$.ajax({
				url: 'index.php?adJax=getUploadedImage',
				type: 'POST',
				data:  responseText,
				success: function(d){
					newFileName = d.name;
					uploadFileComplete();
				},
				dataType: 'json',
			});
		}
	}
},
updateUserOptions = {
	url: '?adJax=updateUserItem',
	type: 'submit',
	success: function(responseText, statusText, xhr, $form){
		alert('User Updated');
	}
},
addUserOptions = {
	url: '?adJax=addUser',
	type: 'submit',
	success: function(responseText, statusText, xhr, $form){
		$('.adSystemSystemUsers .adCurrent').removeClass('adCurrent');
		$('.adSystem'+userType).addClass('adCurrent');
		$('.adSystemWindowUsers').empty().append(responseText);
		$('.adSystemWindowUsersCover').fadeOut(controls.fade);
	}
},
addNewsletterOptions = {
	url: '?adJax=addNewsletter',
	type: 'submit',
	success: function(responseText, statusText, xhr, $form){
		$('.adSystemSystemNewsletters .adCurrent').removeClass('adCurrent');
		$('.adSystemNewsletters').addClass('adCurrent');
		$('.adSystemSystemNewsletters .adSystemWindowAreaBody').empty().append(responseText);
		$('.adSystemWindowUsersCover').fadeOut(controls.fade);
	}
},
updateOptions = {
	url: '?adJax=updateItem',
	type: 'submit',
	success: function(responseText, statusText, xhr, $form){
		AdDebug(responseText);
		window.location.reload();
	}
},
formBuilderUpdateOptions = {
	url: '?adJax=updateItem',
	type: 'submit',
	success: function(responseText, statusText, xhr, $form){
		AdDebug(responseText);
		
	}
}
;

$(function(){
	$('.adMedia').adGallery();
	$('.adDateInput').datepicker({
		showOn: "button",
		buttonImage: "inc/images/calendar.png",
		buttonImageOnly: true,
		dateFormat: 'dd/mm/yy'
	});	
	
	$('#adSystemMenuLeft a').live('click',function(e){
		e.preventDefault();
		var clicked = $(this),
				type = clicked.attr('class');
				
		switch(type) {
			case 'adSystemMenuSettings':
				var data = { windowId: new Date().getTime(), type: 'Forms' }
				$.ajax({
					url: '?adJax=siteSettings',
					data: data,
					type: 'GET',
					success: function(response){
						AdDebug(response);
						$('body').append(response)
						$('#window'+data.windowId+' .adSystemWindowBody').height(531);
						$('#window'+data.windowId+' .adSystemWindowArea').height(528);
						$('#window'+data.windowId+' .adSystemWindowAreaBody').height(528);
						$('#window'+data.windowId).hide().width(800).height(600).css({ marginLeft: '-355px', marginTop: '-302px'}).fadeIn(controls.fade).draggable({ handle: '.adSystemWindowHeader' });
						setupSystemLinks($('#window'+data.windowId));
					},
					dataType: 'html'
				});
			break;
			case 'adSystemMenuSitePages':
				var data = { windowId: new Date().getTime(), type: 'image' }
				$.ajax({
					url: '?adJax=sitePages',
					data: data,
					type: 'GET',
					success: function(response){
						AdDebug(response);
						$('body').append(response);
						$('#window'+data.windowId).hide().fadeIn(controls.fade).draggable({ handle: '.adSystemWindowHeader' });
						$('#window'+data.windowId+' .adTree').adTree({type: 'siteBuilder'});
						formType = 'tree';
					},
					dataType: 'html'
				});
			break;
			case 'adSystemMenuUsers':
				var data = { windowId: new Date().getTime(), type: 'Users' }
				userType = 'Users';
				$.ajax({
					url: '?adJax=siteUsers',
					data: data,
					type: 'GET',
					success: function(response){
						AdDebug(response);
						$('body').append(response);
					//	$('#window'+data.windowId).hide().fadeIn(controls.fade).draggable({ handle: '.adSystemWindowHeader' });
						$('#window'+data.windowId+' .adSystemWindowBody').height(531);
						$('#window'+data.windowId+' .adSystemWindowArea').height(528);
						$('#window'+data.windowId+' .adSystemWindowAreaBody').height(528);
						$('#window'+data.windowId).hide().width(900).height(600).css({ marginLeft: '-450px', marginTop: '-302px'}).fadeIn(controls.fade).draggable({ handle: '.adSystemWindowHeader' });
						formType = 'users';
						setupUserLinks($('#window'+data.windowId));
					},
					dataType: 'html'
				});
			break;
			case 'adSystemMenuNewsletters':
				var data = { windowId: new Date().getTime(), type: 'Newsletters' }
				userType = 'Newsletters';
				$.ajax({
					url: '?adJax=newsletters',
					data: data,
					type: 'GET',
					success: function(response){
						AdDebug(response);
						$('body').append(response);
					//	$('#window'+data.windowId).hide().fadeIn(controls.fade).draggable({ handle: '.adSystemWindowHeader' });
						$('#window'+data.windowId+' .adSystemWindowBody').height(531);
						$('#window'+data.windowId+' .adSystemWindowArea').height(528);
						$('#window'+data.windowId+' .adSystemWindowAreaBody').height(528);
						$('#window'+data.windowId).hide().width(900).height(600).css({ marginLeft: '-450px', marginTop: '-302px'}).fadeIn(controls.fade).draggable({ handle: '.adSystemWindowHeader' });
						formType = 'newsletters';
						setupNewsletterLinks($('#window'+data.windowId));
					},
					dataType: 'html'
				});
			break;
		}	
	
	});
	
	$('.adFormTree #ad_form_Template').live('change',function(){
		var selectd = $(this);
		AdDebug(selectd);
		AdDebug(selectd.val());	
		if(selectd.val() == 103) {
			$('.adFormTree .adHide').show();
		} else {
			$('.adFormTree .adHide').hide();
		}
	});
	
	/* handles the forms */
	$('.adForm').live('submit',function(e){
		AdDebug('form is submittin');
		e.preventDefault();
		var options;

		switch(formType) {
			case 'upload':
				pbar = $('.adEditWindowFileProgressBar');
				pbar.parent().css('opacity',100);
				$('.adEditWindowFileStatus').empty().append('Your file "'+fileName+'" is uploading...');
				uploadTime = setTimeout(function () {
					updateProgress($('.adFileUploadId').val());
				}, 1000);
				options = fileUploadOptions;
			break;
			case 'update':
				options = updateOptions;
			break;
			case 'updateUser':
				options = updateUserOptions;
			break;
			case 'addUser':
				$('.adSystemWindowUsersCover').fadeIn(controls.fade);
				options = addUserOptions;
			break;
			case 'addNewsletter':
				$('.adSystemWindowUsersCover').fadeIn(controls.fade);
				options = addNewsletterOptions;
			break;
			case 'updateFormBuilder':
				options = formBuilderUpdateOptions;
			break;
		}
		$(this).ajaxSubmit(options);
	});
	
	/* handles the web forms */
	$('.adWebForm').live('submit',function(e){
		e.preventDefault();
		var form = $(this),
				required = form.find('.adFormRowRequired'),
				errors = [];
		
		/* time to check the fields */
		for(i=0;i<required.length;i++) {
			/* checking the field*/
			var div = $(required[i]),
					inputs = div.find('input'),
					textareas = div.find('textarea'),
					selects = div.find('select'),
					check, fields, checkMulti = false;
					
			if(inputs.length) check = inputs;
			if(textareas.length) check = textareas; 
			if(selects.length) check = selects;
			var fields = check.length;

			if(fields == 1) {
				if($(check).is('input') || $(check).is('textarea')) {
					if($(check).hasClass('adEmailInput')){
						if(!regs.email.test(check.val())) {
							errors.push(div.find('label').text().trim().replace('*:',''));
							div.addClass('adFormRowError');
						} else {
							div.removeClass('adFormRowError');
						}
					} else if($(check).hasClass('adPhoneInput')){
						if(!regs.phone.test(check.val())) {
							errors.push(div.find('label').text().trim().replace('*:',''));
							div.addClass('adFormRowError');
						} else {
							div.removeClass('adFormRowError');
						}
					} else {
						if(!regs.blank.test(check.val())) {
							errors.push(div.find('label').text().trim().replace('*:',''));
							div.addClass('adFormRowError');
						} else {
							div.removeClass('adFormRowError');
						}
					}
				} else if($(check).is('select')) {
					var val = $(check).val().replace(/[-]+/,'').replace(/[-_]+/gi,'');
					if(val == 'PleaseSelect' || val == 'Please Select' || val.trim() == '') {
						errors.push(div.find('label').text().trim().replace('*:',''));
						div.addClass('adFormRowError');
					} else {
						div.removeClass('adFormRowError');
					}
				}
			} else {
				/* check radio / checkboxes */
				for(j=0;j<fields;j++) {
					if($(check[j]).is(':checked')) checkMulti = true;
				}
				if(checkMulti == false) {
					errors.push(div.children('label:first-child').text().trim().replace('*:',''));
					div.addClass('adFormRowError');					
				} else {
					div.removeClass('adFormRowError');					
				}
			}
		}
		var errorString = "You missed a few fields, you must enter content into the following: \n";
		for(x=0;x<errors.length;x++) errorString += errors[x]+"\n";
		if(errors.length > 0) {
			alert(errorString);
		} else {
			/* if no errors, send the form */
			form.find('img.adHide').show();
			form.find('input.adWebForm').attr('disabled','disabled').addClass('adDisabled');

			$(this).ajaxSubmit({
				url: 'index.php?adEmail=send',
				type: 'submit',
				dataType: 'json',
				success: function(responseText, statusText, xhr, $form){
					AdDebug(responseText);
					if(responseText) {
						var errorString = "You missed a few fields, you must enter content into the following: \n";
						$('.adFormRowError').each(function(){ $(this).removeClass('adFormRowError'); });
						for(var j in responseText) {
							errorString += responseText[j]+"\n";
							if(j == 'adFormRowCapture') {
								$('.adFormRowCapture').addClass('adFormRowError');
							} else {
								$('#adFormRow'+j).addClass('adFormRowError');
							}
						}
						alert(errorString);	
					} else {
						form.find('img.adHide').hide();
						form.find('input.adWebForm').attr('disabled','').removeClass('adDisabled');
						form.prev('.adWebFormThankYou').show();
						form.hide();
					}
					//window.location.reload();
				}
			});
		}
			
	});
	
	
	/* handles the add button clicks */
	$('a.adSystemBtn').live('click',function(e){
	 var clicked = $(this),
                                parent = clicked.parent().parent();
                        if(clicked.hasClass('adNewsEdit')) return true
		e.preventDefault();	

			if(clicked.hasClass('adNewsEdit')) window.open(clicked.attr('http'));	
		/* body add button*/
		if(clicked.closest('.adSystemBtnHolder') && clicked.hasClass('adSystemBtnAdd')) {
			var control = clicked.attr('control'),
					count = parent.children().length;
					control = formatControls(control);
					
			$.ajax({
				type: 'POST',
				url: 	'?adJax=add',
				data: control,
				success: function(response) {
					AdDebug(response);
					var data = response.replace('~count~',count-1);
					parent.append(data);
					renderEdit();
					if(count == control.limit) clicked.parent().fadeOut(controls.fade,function(){ $(this).remove(); });
					
				},
				dataType: 'html'	
			});
			
			//parent.append(itemTemplates[control.template]);
			AdDebug(parent.children().length);
			if(count-1 >= control.limit) clicked.parent('.adSystemBtnHolder').fadeOut(controls.fade,function(){ $(this).remove(); }); 
			AdDebug(control);
		}
		
		if(clicked.hasClass('adEditWindowImageBrowse')) {
			var data = { windowId: new Date().getTime(), type: 'image' }
			$.ajax({
				type: 'GET',
				url: '?adJax=mediaLibraryHolder',
				data: data,
				success: function(response){
					$('body').append(response);
					$('#window'+data.windowId).hide().fadeIn(controls.fade).draggable({ handle: '.adSystemWindowHeader' });
					var mlControls = { type: 'select', files: 'images'}
					$('#window'+data.windowId+' .adMediaLibrary').adMediaLibrary(mlControls);

				},
				dataType: 'html'
			});	
		}
		
		if(clicked.hasClass('adEditWindowClear')) {
			clicked.siblings('.adInput').val('');	
			clicked.parent().prev().css('backgroundImage','');
		}
		
		/* window inline form save */
		if(clicked.hasClass('adFormBtnSubmit')) {
			AdDebug('here');
			clicked.closest('adForm').submit();	
		}
		/* end window inline form save */
		
		/* add form btn */
		if(clicked.hasClass('adAddForm')) {
			AdDebug('add form ');
			var name = prompt('Form Name: ','');
			if(name) {
				$.ajax({
					url: '?adJax=addForm',
					type: 'GET',
					data: 'name='+name,
					success: function(d) {
						AdDebug(d);
						$('.adSystemWindowFormListHolder').append(d);
					},
					dataType: 'html'
				});
			}
		}
		/* end add form btn */
		
		/* add form field btn */
		if(clicked.hasClass('adAddFormField')) {
			AdDebug('add form field');
			var name = prompt('Field Name: ',''),
					itemId = clicked.closest('.adFormList').attr('id');
			if(name) {
				$.ajax({
					url: '?adJax=addFormField',
					type: 'GET',
					data: 'name='+name+'&parent='+itemId.replace('adFormList',''),
					success: function(d) {
						AdDebug(d);
						$('#'+itemId+' .adFormListDataSectionFields .adFormListDataSectionFieldsList').append(d);
						if($('#'+itemId+' .adFormListSubs').size() > 0) $('.adFormNoFields').remove();
						$('.adFormListDataSectionFieldsList').sortable({ stop: function(e,ui) {
							formReorder(e,ui);
						}});
					},
					dataType: 'html'
				});
			}
		}
		/* end add form field btn */
		
		/* window save button */
		if(clicked.hasClass('adSystemWindowSubmit')) {
			formType = 'update';
			form = clicked.parent().prev().children('form');
			form.submit();
			
		}
		/* end window save button */
		
		
		/* window cancel button */
		if(clicked.hasClass('adSystemWindowCancel')) {
			clicked.closest('.adSystemWindow').fadeOut(controls.fade,function(){ 
				if(clicked.hasClass('adSiteBuilderClose')) {
					window.location.reload();	
				} else {
					$(this).remove(); 
				}
			});
		}
	});

	
});

/* sets up the links for the system area */
function setupSystemLinks(editWindow){
	formType = 'updateFormBuilder';
	var windowArea = $('.adSystemSystemSettings'),
			menu = editWindow.find('.adSystemWindowAreaMenu');	

	/* the links */
	menu.find('a').live('click',function(e){
		e.preventDefault();
		var clicked = $(this),
				type = clicked.attr('class').replace(' adCurrent','').replace('adSystemSettings',''),
				data = { type: type };
				
		menu.find('.adCurrent').removeClass('adCurrent');
		clicked.addClass('adCurrent');
				
		$.ajax({
			url: '?adJax=systemSettingsSection',
			type: 'GET',
			data: data,
			success: function(d) {
				AdDebug(d);
				editWindow.find('.adSystemWindowAreaBody').empty().append(d).hide().fadeIn(controls.fade);
				$('.adFormListDataSectionFieldsList').sortable({ stop: function(e,ui) {
					formReorder(e,ui);
				}});
			},
			dataType: 'html'				
		});
		
		AdDebug('clicked');	
	});
	
	/* the acordian */
	$('.adFormList h4').live('click',function(){
		var clicked = $(this),
				parentC = clicked.parent().attr('class');
				p = parentC.split(' ');
				parent = p[p.length-1];
		$('.'+parent+' > .adFormListDataOpen').next().slideUp(controls.fade,function(){
			$(this).prev().removeClass('adFormListDataOpen');
		});
		if(!clicked.hasClass('adFormListDataOpen')) {
			clicked.addClass('adFormListDataOpen');
			clicked.next().slideDown(controls.fade);	
		}
		clicked.next().children('.adFormListDataSectionEdit').find('input[name="Name"]').bind('keyup',function(){
			var input = $(this),
					value = input.val();
			if(value.length > 50) value = value.substr(0,50)+'...';
			clicked.text(value);
		});
	});
	
	$('.adFormFieldDelete').live('click',function(){
		var clicked = $(this),
				parent = clicked.parent(),
				id = parent.attr('id').replace('adFormListFields','');
		
		if(confirm('Are you sure you wish to delete this item?')) {
			$.ajax({
				url: '?adJax=deleteFormField',
				data: 'id='+id,
				success: function(response) {
					AdDebug(response);
					parent.fadeOut(controls.fade,function(){ $(this).remove(); });
				},
				dataType: 'json'	
			});
		}	
	});
	//$('.adFormListDataSectionFields').sortable();
	
}

/* sets up the links for the users area */
function setupUserLinks(editWindow){
	var windowArea = $('.adSystemSystemSettings'),
			menu = editWindow.find('.adSystemWindowAreaMenu'),
			pages = editWindow.find('.adSystemWindowUsersBottom a');

	/* the links */
	menu.find('a').live('click',function(e){
		e.preventDefault();
		var clicked = $(this),
				type = clicked.attr('class').replace(' adCurrent','').replace('adSystem',''),
				data = { type: type };
				
		userType = type;
		
		menu.find('.adCurrent').removeClass('adCurrent');
		clicked.addClass('adCurrent');
		
		$.ajax({
			url: '?adJax=systemSettingsSection',
			type: 'GET',
			data: data,
			success: function(d) {
				AdDebug(d);
				editWindow.find('.adSystemWindowAreaBody').empty().append(d).hide().fadeIn(controls.fade);
				if(type == 'AddMember') {
					formType = 'addUser';
					var theType = $('#ad_form_Type');
					if(theType.length) {
						if(theType.val() == 'Contact') {
							userType = 'Contacts';
							$('#ad_form_Username').parent().hide();
							$('#ad_form_Password').parent().hide();
						}
					}
					theType.live('change',function(){
						if(theType.val() == 'Contact') {
							userType = 'Contacts';
							$('#ad_form_Username').parent().hide();
							$('#ad_form_Password').parent().hide();
						} else {
							userType = 'Users';
							$('#ad_form_Username').parent().show();
							$('#ad_form_Password').parent().show();
						}
					})
				}
			},
			dataType: 'html'				
		});
		
		AdDebug('clicked');	
	});
	
	editWindow.find('.adSystemWindowUsersFiltering a').live('click',function(e){
		//debug(pages);
		e.preventDefault();
		var clicked = $(this),
				pos = pages.index(clicked),
				nextPage,
				current = $('.adSystemWindowUsersFiltering .adCurrent');

		var data = { filter: clicked.text(), table: '_users', type:userType }
		current.removeClass('adCurrent');
		clicked.addClass('adCurrent');
		
		$('.adSystemWindowUsersCover').fadeIn(controls.fade,function(){
			$.ajax({
				url: 'index.php?adJax=getUsers',
				type: 'POST',
				data: data,
				success: function(response){
					//debug(response);
					$('.adSystemWindowUsers').empty().append(response);
					$('.adSystemWindowUsersCover').fadeOut(controls.fade);
				},
				dataType: 'html'	
			});
		});
	});
	
	editWindow.find('.adUserBack').live('click',function(e) {
		e.preventDefault();
		var clicked = $(this);

		var data = { table: '_users', type:userType }
		
		$('.adSystemWindowUsersCover').fadeIn(controls.fade,function(){
			$.ajax({
				url: 'index.php?adJax=getUsers',
				type: 'POST',
				data: data,
				success: function(response){
					//debug(response);
					$('.adSystemWindowUsers').empty().append(response);
					$('.adSystemWindowUsersCover').fadeOut(controls.fade);
				},
				dataType: 'html'	
			});
		});
	});
	
	$('.adSystemUserItem a').live('click',function(e) {
		e.preventDefault();
		var clicked = $(this),
				id = clicked.parent().parent().attr('id').replace('adSystemUserItem','');
		var data = { id:id, table: '_users', type:userType }
		
		$('.adSystemWindowUsersCover').fadeIn(controls.fade,function(){
			$.ajax({
				url: 'index.php?adJax=getUsersData',
				type: 'POST',
				data: data,
				success: function(response){
					//debug(response);
					$('.adSystemWindowUsers').empty().append(response);
					$('.adSystemWindowUsersCover').fadeOut(controls.fade);
					formType = 'updateUser';
				},
				dataType: 'html'	
			});
		});
		
			
	});
	
	editWindow.find('.adUserDelete').live('click',function(e){
		e.preventDefault();
		if(confirm('Are you sure you want to delete this contact?')) {
	
			var clicked = $(this),
					id = clicked.parent().attr('id').replace('deleteUser','');
			var data = { id:id, table: '_users', type:userType }
			
			$('.adSystemWindowUsersCover').fadeIn(controls.fade,function(){
				$.ajax({
					url: 'index.php?adJax=getUsersDelete',
					type: 'POST',
					data: data,
					success: function(response){
						//debug(response);
						$('.adSystemWindowUsers').empty().append(response);
						$('.adSystemWindowUsersCover').fadeOut(controls.fade);
						formType = 'updateUser';
					},
					dataType: 'html'	
				});
			});
		} 
	});
	
}
/* sets up the links for the newsletter area */
function setupNewsletterLinks(editWindow){
	var windowArea = $('.adSystemSystemSettings'),
			menu = editWindow.find('.adSystemWindowAreaMenu');

	/* the links */
	menu.find('a').live('click',function(e){
		e.preventDefault();
		var clicked = $(this),
				type = clicked.attr('class').replace(' adCurrent','').replace('adSystem',''),
				data = { type: type };
				
		newsType = type;
		
		menu.find('.adCurrent').removeClass('adCurrent');
		clicked.addClass('adCurrent');
		
		$.ajax({
			url: '?adJax=systemSettingsSection',
			type: 'GET',
			data: data,
			success: function(d) {
				AdDebug(d);
				editWindow.find('.adSystemWindowAreaBody').empty().append(d).hide().fadeIn(controls.fade);
				if(type == 'AddNewsletters') {
					formType = 'addNewsletter';
					
				}
			},
			dataType: 'html'				
		});
		
		AdDebug('clicked');	
	});
	
	editWindow.find('.adNewsBack').live('click',function(e) {
		e.preventDefault();
		var clicked = $(this);

		var data = { table: '_users', type:userType }
		
		$('.adSystemWindowUsersCover').fadeIn(controls.fade,function(){
			$.ajax({
				url: 'index.php?adJax=getNewsletters',
				type: 'POST',
				data: data,
				success: function(response){
					//debug(response);
					$('.adSystemSystemNewsletters .adSystemWindowAreaBody').empty().append(response);
					$('.adSystemWindowUsersCover').fadeOut(controls.fade);
				},
				dataType: 'html'	
			});
		});
	});
	
	$('.adSystemNewsItem a').live('click',function(e) {
		e.preventDefault();
		var clicked = $(this),
				id = clicked.parent().parent().attr('id').replace('adSystemNewsItem','');
		var data = { id:id, table: '_users', type:userType }
		
		$('.adSystemWindowUsersCover').fadeIn(controls.fade,function(){
			$.ajax({
				url: 'index.php?adJax=getNewsletterData',
				type: 'POST',
				data: data,
				success: function(response){
					//debug(response);
					$('.adSystemSystemNewsletters .adSystemWindowAreaPadding').empty().append(response);
					$('.adSystemWindowUsersCover').fadeOut(controls.fade);
					formType = 'updateNewsletter';
				},
				dataType: 'html'	
			});
		});
		
			
	});
	
	editWindow.find('.adNewsDelete').live('click',function(e){
		e.preventDefault();
		if(confirm('Are you sure you want to delete this newsletter?')) {
	
			var clicked = $(this),
					id = clicked.parent().attr('id').replace('deleteNews','');
			var data = { id:id, table: '_newsletters', type:userType }
			
			$('.adSystemWindowUsersCover').fadeIn(controls.fade,function(){
				$.ajax({
					url: 'index.php?adJax=getNewsDelete',
					type: 'POST',
					data: data,
					success: function(response){
						//debug(response);
						$('.adSystemSystemNewsletters .adSystemWindowAreaBody').empty().append(response);
						$('.adSystemWindowUsersCover').fadeOut(controls.fade);
						formType = 'updateNewsletter';
					},
					dataType: 'html'	
				});
			});
		} 
	});
	
}

function formReorder(e,ui) {
	var itemToUpdate = $(ui.item),
			items = itemToUpdate.parent().children(),
			controls = {}

	controls['_position'] = items.index(itemToUpdate);
	controls['_parent'] = itemToUpdate.parent().attr('id').replace('adFormFields','');
	controls['pControls'] = { type: '_forms_fields' }
	controls['id'] = itemToUpdate.attr('id').replace('adFormListFields','');
	$.ajax({
		url: '?adJax=updatePosition',
		data: controls,
		success: function(response) {
			AdDebug(response);
		},
		dataType: 'json'	
	});	
}


function AdDebug(data) {
	//if(debug) {
		if(window.console) {
			 //console.log(data);
		} else {
//			 alert(data);
		}	
//	}
}

