var isChangingPage = false;

$(document).ready(function () {		
	$.ifixpng('/img/pixel.gif');
	$('img[src$=.png]').ifixpng();
	$('#logout img').mouseover(function () {
		$(this).attr('src', '/img/logout-sel.png');
	});
	$('#logout img').mouseout(function () {
		$(this).attr('src', '/img/logout.png');
	});
	
	$('#contentPreviewLink, #previewButton').click(function() {
		saveDraft(function() {
			window.open($('#contentPreviewLink').attr('href'), 'previewWin');
		});
		return false;
	});
	
	positionUploadStatus();
	$(document).scroll(function() { positionUploadStatus(); });
	$(document).resize(function() { positionUploadStatus(); });
	
	initializeCustomMetadata();
	
	// Find the controller used and initialize options.
	if ($('#indexItems').length) {
		if ($('#itemsContainer').hasClass('assets')) {
			$('#main').data('controller', 'assets');
		} else if ($('#itemsContainer').hasClass('areas')) {
			$('#main').data('controller', 'areas');
		}
	}	
	$('#main').data('options', {method: 'name', view: 'grid'});
	initializeItems();
});

function positionUploadStatus() {
	$('#uploadStatus').css('top', $(document).scrollTop() + $(window).height() - $('#uploadStatus').outerHeight(true));
}

function initializeCustomMetadata() {	
	if ($('#customMetadata').length) {
		if ($('textarea', '#customMetadata').val()) {
			$('#customMetadata').show();
		} else {
			$('#customMetadataMessage').show();
		}
		$('a', '#customMetadataMessage').click(function() {
			$('#customMetadataMessage').hide();
			$('#customMetadata').show();
		});
	}
}

function initializeItems() {
	// Set the cluetip options based on view type.
	var cluetipOptions = {
		closeText: '',
		cluetipClass: 'datavenger-grid',
		dropShadow: false,
		fx: {             
			open: 'slideDown',
			openSpeed: 'def'
		},
		hideLocal: true,
		leftOffset: -115,
		local: true,
		mouseOutClose: true,
		positionBy: 'fixed',
		showTitle: false,
		sticky: true,
		topOffset: 90
	};
	if ($('div.index div.list').length) {
		cluetipOptions.cluetipClass = 'datavenger-list';
		cluetipOptions.topOffset = 5;
		cluetipOptions.leftOffset = 10;
	}
	$('div.index div.item').cluetip(cluetipOptions);
	
	// Unbind previous click and change events.
	$('#leftStripe.index a').unbind('click');
	$('.index .paging a').unbind('click');
	$('.index .paging select').unbind('change');
	
	$('#leftStripe.index a').click(function() {
		var splitId = $(this).attr('id').split('-');
		loadItems(splitId[0], splitId[1]);
		return false;
	});
	$('.index .paging a').click(function() {
		if (!isChangingPage) {
			isChangingPage = true;
			var today = new Date();
			$('#leftStripe').addClass('loader');
			$('.grid *, .list *, .paging *').animate({opacity: 0.6});
			$('#content').load($(this).attr('href') + '/' + today.getTime(), null, 
					function() {
				$('.grid *, .list *, .paging *').css({opacity: 0.6});
				initializeItems();
				$('#leftStripe').removeClass('loader');
				$('.grid *, .list *, .paging *').animate({opacity: 1});
				isChangingPage = false;
			});
		}
		return false;
	});
	$('.index .paging select').change(function() {
		if (!isChangingPage) {
			isChangingPage = true;
			var today = new Date();
			$('#leftStripe').addClass('loader');
			$('.grid *, .list *, .paging *').animate({opacity: 0.6});
			$('#content').load($('#pageSelectorUrl').val() + '/page:' + 
					$('#pageSelector').val() + '/' + today.getTime(), null, function() 
					{
				$('.grid *, .list *, .paging *').css({opacity: 0.6});
				initializeItems();
				$('#leftStripe').removeClass('loader');
				$('.grid *, .list *, .paging *').animate({opacity: 1});
				isChangingPage = false;
			});
		}
		return false;
	});
	
	if ($.browser.mozilla) {
		$('#itemsContainer.assets').fileUploadArea({
			url: '/admin/assets/dropupload',
			onDragOver: function () {
				$('#content').addClass('dragover');
			},
			onDragLeave: function () {
				$('#content').removeClass('dragover');
			},
			onDrop: function (file) {
				$('#uploadStatus').removeClass('error');
				$('div.upload-progress', '#uploadStatus').show();
				$('div.upload-name', '#uploadStatus').text(file.fileName);
				$('div.upload-status', '#uploadStatus').text('Uploading...');
				$('div.upload-progress div', '#uploadStatus').width(0);
				$('#uploadStatus').fadeIn();
			},
			progress: function (percent, totalPercent) {
				$('div.upload-progress div', '#uploadStatus').width(Math.floor(totalPercent) + '%');
			},
			fileComplete: function (response) {
				var parsedResponse = $.parseJSON(response);
				if (parsedResponse.error) {
					$('#uploadStatus').addClass('error');
					$('div.upload-progress', '#uploadStatus').hide();
					$('div.upload-name', '#uploadStatus').text('There was an error with the file.');
					$('div.upload-status', '#uploadStatus').text(parsedResponse.error);
				}
			},
			complete: function () {
				$('div.upload-progress div', '#uploadStatus').width('100%');
				if ($('#uploadStatus').hasClass('error')) {
					setTimeout(function() { $('#uploadStatus').fadeOut(); }, 5000);
				} else {
					$('div.upload-status', '#uploadStatus').text('Complete!');
					$('#uploadStatus').fadeOut();
				}
				loadItems();
			}
		});
	} else if ($.browser.webkit) {
		$('<input />').attr('type', 'file').attr('multiple', 'multiple').attr('id', 'uploadInput')
				.appendTo('#itemsContainer.assets');
		$('#itemsContainer.assets').bind('dragenter', function() {
			$('#uploadInput').show();
			$('#content').addClass('dragover');
		});
		$('#uploadInput', '#itemsContainer').bind('dragleave', function() {
			$('#uploadInput').hide();
			$('#content').removeClass('dragover');
		});
		$('#uploadInput', '#itemsContainer').html5_upload({
			url: '/admin/assets/dropupload',
			onStart: function(event, total) {
				$('#uploadInput').hide();
				$('#content').removeClass('dragover');
				$('#uploadStatus').removeClass('error');
				$('div.upload-progress', '#uploadStatus').show();
				$('#uploadStatus').fadeIn();
			},
			onStartOne: function(event, name, number, total) {
				$('div.upload-name', '#uploadStatus').text(name);
				$('div.upload-status', '#uploadStatus').text('Uploading...');
				$('div.upload-progress div', '#uploadStatus').width(0);
			},
			onProgress: function(event, progress, name, number, total) {
				$('div.upload-progress div', '#uploadStatus').width(Math.floor((progress / total) * 100) + '%');
			},
			onFinishOne: function(event, response, name, number, total) {
				var parsedResponse = $.parseJSON(response);
				if (parsedResponse.error) {
					$('#uploadStatus').addClass('error');
					$('div.upload-progress', '#uploadStatus').hide();
					$('div.upload-name', '#uploadStatus').text('There was an error with the file.');
					$('div.upload-status', '#uploadStatus').text(parsedResponse.error);
				}
			},
			onFinish: function(event, total) {
				$('div.upload-progress div', '#uploadStatus').width('100%');
				if ($('#uploadStatus').hasClass('error')) {
					setTimeout(function() { $('#uploadStatus').fadeOut(); }, 5000);
				} else {
					$('div.upload-status', '#uploadStatus').text('Complete!');
					$('#uploadStatus').fadeOut();
				}
				loadItems();
			},
		});
	}
}

function loadItems(newKey, newValue) {
	var today = new Date();
	var options = $('#main').data('options');
	
	$('#cluetip').fadeOut('fast');

	// If a new key/value pair is passed, set it in options.
	if (newKey && newKey.length > 0) {
		options[newKey] = newValue;
		$('#main').data('options', options);
	}
	
	// Build the address for the AJAX call.
	var address = '/admin/' + $('#main').data('controller') + 
			'/index/';
	$.each(options, function(key, value) {
		address = address + key + ':' + value + '/';
	});
	address = address + today.getTime();
	
	// Fade out, fade in, and load!
	$('#leftStripe').addClass('loader');
	$('.grid *, .list *, .paging *').animate({opacity: 0.6});
	$('#content').load(address, null, function() {
		initializeItems();
		
		// Reset the stripe links.
		$('#leftStripe').find('a').removeClass('selected');
		$('#leftStripe').find('img').each(function() {
			$(this).attr('src', '/img/' + $(this).parent().attr('id') + '.png');
		});
		
		// Mark the correct links and images as selected.
		$.each(options, function(key, value) {
			var elemId = key + '-' + value;
			$('#' + elemId).addClass('selected')
					.find('img').attr('src', '/img/' + elemId + '-sel.png');
		});
		
		// Fade back in.
		$('#leftStripe').removeClass('loader');
		$('.grid *, .list *, .paging *').animate({opacity: 1});
	});
	
}

function saveDraft(func) {
	$.ajax({
		type: "POST",
		url: "/admin/revisions/update",
		dataType: "json",
		data: {
			area_id: $('#RevisionAreaId').val(),
			content: xinha_editors.RevisionContent.outwardHtml(xinha_editors.RevisionContent.getHTML()),
			title: $('#RevisionTitle').val(),
			keywords: $('#RevisionKeywords').val(),
			description: $('#RevisionDescription').val(),
			draft: 1
		},
		success: function(data) {
			if (data.message && data.message.length) {
				$('#lastDraft').html(data.message);
				$('#contentPreviewLink').attr('href',
						$('#contentPreviewLink').attr('href').replace(/view\/[0-9]+/,
								'view/' + data.id));
			}
			if (jQuery.isFunction(func)) {
				func.call();
			}
		}
	});
}