/* amped js*/

/* the defaults */
var layoutIds = {
	fader 			: 'adFader',
	holder 			: 'adEditWindow',
	btnClose 		: 'adMediaClose',
	header			: 'adMediaHeader',
	media				: 'adMedia',		
	loader			: 'adLoader',
	loaderData	: 'adLoaderData'
}

var layout = '<div class="'+layoutIds.fader+'"></div>';
var adFadeSpeed = 200;
var animationSpeed = 200;
var slideSpeed = 400;
var editor = null;
var loadingObj = {
	type			: 'loading',
	header		: 'Searching for ...',
	width			: 300,
	height		: 140,
	hideClose : 1
};
/* end defaults */

$(function(){
	
	// edit button click
	$('.adBlockEdit').live('click',function(){
		adDebug('edit');
		var clicked = $(this);
		//if(clicked.ha
		ad_fade({dir:'up',div:'.'+layoutIds.fader});	
		var data = {
			dbTable 		: 	clicked.siblings('.adEditBtndbTable').val(),
			guid				: 	clicked.siblings('.adEditBtnguid').val(),
			parent			: 	clicked.siblings('.adEditBtnparent').val(),
			source			:		clicked.siblings('.adEditBtnsource').val(),
			position		:		clicked.siblings('.adEditBtnposition').val(),
			dontEdit		:		clicked.siblings('.adEditDontEdit').val()
		}
		adDebug(data);
		var loadObj = {
			type			: 	'editWindow',
			width			:		700,
			height		:		500,
			data			:		data
		}
		ad_load(loadObj);
		return false;	
	});
	
	// delete button click 
	$('.adBlockDelete').live('click',function(){
		adDebug('delete');
		var confirmItem = confirm('Are you sure you want to delete this item?');
		if(confirmItem) {
			ad_delete($(this));	
		}	
		return false;
	});
	
	// add button click 
	$('.adAddSection .adSystemBtn').live('click',function(){
		ad_fade({dir:'up',div:'.'+layoutIds.fader});	
		var clicked = $(this);
		var data = clicked.attr('href').replace(/\?/,'');
		var loadObj = {
			type			: 	'addWindow',
			width			:		555,
			height		:		368,
			data			:		data,
			header		:		'Add Item'
		}
		ad_load(loadObj);
		return false;	
	});
	
	// close button
	$('.adEditWindowClose, .adSystemCancel').live('click',function(){
		var clicked = $(this);
		if(clicked.hasClass('adSystemCancel')) {
			ad_fade({dir:'down',div:'.'+layoutIds.fader,remove:1});
			ad_fade({dir:'down',div:'.adEditWindow',remove:1});
		} else {
			if(clicked.parent().attr('id') == 'adMediaLibrary') {
				ad_fade({dir:'down',div:'#adMediaLibrary',remove:1});
			}	else {
				ad_fade({dir:'down',div:'.'+layoutIds.fader,remove:1});
				ad_fade({dir:'down',div:'.adEditWindow',remove:1});
			}
		}
		return false;
	});
	
	// add image
	$('.adEditImageAdd').live('click',function(){
		var clicked = $(this);	
		var upload = clicked.parent().next().children('.adFileUpload');
		upload.show();
		adDebug(upload);
		return false;
	});
	
	// cancel image upload
	$('.adEditImageCancel').live('click',function(){
		var clicked = $(this);	
		var upload = clicked.parent();
		upload.hide();
		upload.children('.adFileUploadBrowse').val('');
		return false;
	});
	
	// remove image upload
	$('.adEditImageRemove').live('click',function(){
		var clicked = $(this);	
		clicked.parent().next().children('.adFileUploadGuid').val('');
		clicked.parent().prev().css('background-image','none');
		return false;
	});
	
	// browse image
	$('.adEditImageBrowse').live('click',function(){
		var loadObj = {
			type			: 	'mediaLibrary',
			width			:		600,
			height		:		383,
			data			:		''
		}
		ad_load(loadObj);
		return false; 	
	});
	
	// select image
	$('#adMediaLibraryItems li a').live('click',function(){
		var clicked = $(this);
		var id = clicked.attr('href');
		var bg = clicked.css('background-image');
		
		$('.adFileUploadGuid').val(id);
		$('.adEditImage').css('background-image',bg);
		$('#adMediaLibrary').fadeOut(adFadeSpeed,function(){ $(this).remove(); });		
		return false;	
	});
	
	
	// paging
	$('.adSystemPaging li').live('click',function(){
		var clicked = $(this);
		var c = clicked.attr('class');
		var pageType = c.replace('adSystemPages','');
		var num = parseInt($('.adSystemPaging .onLink').parent().attr('class').replace('adSystemPages',''));
		var total = $('.adSystemPaging li');
		adDebug('num: '+num);
		total = (total.length/2)-4;
		adDebug(total);
			
		$('.adSystemPaging .onLink').removeClass('onLink');
		switch(pageType) {
			case 'Next': 	var number = num+1; break;
			case 'Back': 	var number = num-1; break;
			case 'First':	var number = 1;			break;
			case 'Last': 	var number = total; break;
			default: 			var number = num; 	break;
		}
		if(number == 1) {
			$('.adSystemPagesFirst').addClass('adSystemHide');
			$('.adSystemPagesBack').addClass('adSystemHide');	
		} else {
			$('.adSystemPagesFirst').removeClass('adSystemHide');
			$('.adSystemPagesBack').removeClass('adSystemHide');	
		}
		if(number == total) {
			$('.adSystemPagesLast').addClass('adSystemHide');
			$('.adSystemPagesNext').addClass('adSystemHide');	
		} else {
			$('.adSystemPagesLast').removeClass('adSystemHide');
			$('.adSystemPagesNext').removeClass('adSystemHide');	
		}
		
		$('.adSystemPaging .adSystemPages'+number).children('a').addClass('onLink');	
		ad_loadNewImages(number);			
		return false; 	
	});
	
	
});

// fades in items
function ad_fade(obj) {
	if($('.'+layoutIds.fader).length < 1) $('body').append(layout);
	if(obj.dir == 'up') {
		$(obj.div).fadeIn(adFadeSpeed);
	}
	if(obj.dir == 'down') {
		if(obj.remove) {
			$(obj.div).fadeOut(adFadeSpeed,function(){ $(this).remove(); });	
		} else {
			if(obj.reload) {
				$(obj.div).fadeOut(adFadeSpeed,function(){ window.location.reload(); });	
			} else {
				$(obj.div).fadeOut(adFadeSpeed);	
			}
		}
	}
}

// load new images
function ad_loadNewImages(number) {
	adDebug('ad_loadNewImages: '+number);	
	$('.adMediaLibraryFader').fadeIn(adFadeSpeed);
	$.ajax({
		type: 'POST',
		url: '?adJax=mediaImages',
		data: 'number='+number,
		success: function(data){ 
			adDebug('sucess'); 
			adDebug(data);
			$('#adMediaLibrarySection').fadeOut(adFadeSpeed,function(){
				$(this).empty().append(data).fadeIn(adFadeSpeed,function(){
					$('.adMediaLibraryFader').fadeOut(adFadeSpeed);	
				});	
			});

		},
		complete: function(request,status){ 
			adDebug('complete');
		},
		dataType: 'html'
	});
}

// loader
function ad_load(obj) {
	/*
		type 			// which type to pull back and display
		header 		// header text
		width 		// width of the box
		height 		// height of the box
	*/
	adDebug(obj);
	var type = obj.type;
	var header = obj.header;
	var width, height;
	obj.width ? width = obj.width : width = 400;
	obj.height ? height = obj.height : height = 400;
	var widthInner = width-12;
	var heightInner = height-42;

	if(type != 'addWindow') {
		var items = 'dbTable='+obj.data.dbTable+'&guid='+obj.data.guid+'&parent='+obj.data.parent+'&source='+obj.data.source+'&position='+obj.data.position;
		if(obj.data.dontEdit) items += '&dontEdit='+obj.data.dontEdit;
	} else {
		var items = obj.data;	
	}
			
	var offsetX = Math.floor(width / 2);
	var offsetY = Math.floor(height / 2);
	switch(type) {
		case 'editWindow':
		case 'addWindow':
			$.ajax({
				type: 'POST',
				url: '?adJax='+type,
				data: 'data='+header+'&'+items,
				success: function(data){ 
					$('body').append(data);
					$('.adEditWindow').hide().css({ width : width, height : height, marginLeft : -offsetX, marginTop : -offsetY });
					$('.adEditWindowInner').width(widthInner).height(heightInner);
					$('.adEditWindow').fadeIn(adFadeSpeed);
					$('.adRichTextInput').each(function(){ 
						var itemId = $(this).attr('id');
						var instance = CKEDITOR.instances[itemId];
						if(instance) CKEDITOR.remove(instance);
						var config = {};
						config.extraPlugins = 'stylesheetparser';
						//config.contentsCss = 'http://nuria.amplificreative.com/styles/general.css';
						config.filebrowserUploadUrl = 'inc/ckpost.php';

						CKEDITOR.replace(this,config);
					});
					$('.adInputDate').each(function(){
						$(this).datepicker({
							showOn: "button",
							buttonImage: "images/calendar.gif",
							buttonImageOnly: true
						});
					});
					type == 'addWindow' ? form = 'add' : form = 'update';
					ad_setupForm($('.adSystemContentForm'),'adForm='+form);
				},
				complete: function(request,status){ 
					adDebug('complete');
				},
				dataType: 'html'
			});
			var id = '.'+layoutIds.holder;
		break;
		case 'mediaLibrary':
			adDebug('media library');
			$.ajax({
				type: 'POST',
				url: '?adJax='+type,
				success: function(data){ 
					adDebug('sucess'); 
					adDebug(data);
					$('body').append(data);
					$('#adMediaLibrary').hide().css({ width : width, height : height, marginLeft : -offsetX, marginTop : -offsetY });
					$('.adMediaLibraryFader').css({ width : width+16, height : height+16 });
					$('#adMediaLibrary .adEditWindowInner').width(widthInner).height(heightInner);
					$('#adMediaLibrary').fadeIn(adFadeSpeed);
				},
				complete: function(request,status){ 
					adDebug('complete');
				},
				dataType: 'html'
			});
			var id = '#adMediaLibrary';
		break;
	}	
	$(id).clearQueue().animate({
		width 			: width,
		marginLeft 	: -offsetX 	
	},animationSpeed,function(){
		$(this).animate({
			height		: height,
			marginTop : -offsetY	
		}, animationSpeed,function(){ 
			adDebug(type);
		});	
	});
}

function ad_delete(clicked) {
	var dbTable = clicked.siblings('.adEditBtndbTable').val();
	var guid = clicked.siblings('.adEditBtnguid').val();
	
	$.ajax({
		type: 'POST',
		url: '?adForm=delete',
		data: 'dbTable='+dbTable+'&guid='+guid,
		success: function(data){ 
			window.location.reload();
		},
		dataType: 'html'
	});
}

function ad_setupForm(form,url) {
	var url = '?'+url;
	var options = {
		beforeSubmit	:  showRequest,  
		success				:  showResponse, 
		url						:  url  
	};
	form.unbind('submit').submit(function(){
		//for(instance in CKEDITOR.instances) CKEDITOR.instances['imageEditsbItemNotes'].updateElement();
		
		$(this).ajaxSubmit(options);
		return false;	
	});
}


// pre-submit callback 
function showRequest(formData, jqForm, options) { 
	adDebug('showRequest');
	adDebug(formData);
	adDebug(jqForm);
	adDebug($(jqForm[0]).attr('id'));
	return true; 
} 
 
// post-submit callback 
function showResponse(responseText, statusText, xhr, $form)  { 
	adDebug('showResponse');
	adDebug(responseText);
	adDebug(statusText);
	adDebug(xhr);
	adDebug($form);
	switch(responseText) {
		case 'complete':
			ad_fade({dir:'down',div:'.adEditWindow',reload:1});
		break;	
	}
} 


// debugger
adDebug = function(data){
	if(window.console) {
		//console.log(data);
	} else {
		// alert(data);
	}	
}


/* end amped js*/
