
var orderManager = {
	JSON: {},
	requestJSON: null,
	target: null,
	timer: null,
	interval: 1000,
	updating: false,
	settings: {
		controller: '/cart_json.php',
		goToCart: false
	},
	init: function() {
		$('#cartLink').droppable({
			accept: 'span.photoItem, li.album',
			activeClass: 'droppable',
			hoverClass: 'hover',
			tolerance: 'pointer',
			drop: function(event, ui) {
				orderManager.cartDnD(event, ui);
			}
		});
		$('#actions a.actionOrderAlbum').click(function(event) {
			event.preventDefault();
			this.target = $(this);
			orderManager.orderAlbum();
		});
		$('#actions a.actionSelectedPhotos').click(function(event) {
			event.preventDefault();
			this.target = $(this);
			orderManager.orderPhotos();
		});
		$('#orderSelectedPhotos').click(function(event) {
			event.preventDefault();
			this.target = $(this);
			orderManager.settings.goToCart = true;
			orderManager.orderPhotos();
		});
		$('#courierOrderPhotos').click(function(event) {
				event.preventDefault();
				this.target = $(this);
				orderManager.settings.goToCart = true;
				orderManager.orderPhotos();
			});
	},
	getJSON: function(data) {
		switch (data.action) {
			case 'orderAlbum':
			case 'orderPhotos':
				$('#cartLink').addClass('updating');
				this.updating = true;
				this.timer = setTimeout('orderManager.intervalUpdate()', this.interval);
			case 'getInfo':
				if (typeof photoManager === 'undefined') $.sfWindow.alert(i18n.iface.info, i18n.cart.addingInProgress);
				else photoManager.showMessage(i18n.cart.addingInProgress, 'message');
				break;
		}
		$.sfJson.load(this.settings.controller, function(data) { orderManager.processingJSON(data) }, data);
	},
	intervalUpdate: function() {
		this.getJSON({ action: 'getInfo' });
	},
	processingJSON: function(JSON) {
		if ($.sfJson.parse(JSON)) {
			if (!this.JSON) this.JSON = {};
			this.JSON = $.extend(true, this.JSON, JSON);
			var action = JSON.request.action;
			switch (action) {
				case 'getFormatsAndPapers':
					this.photoOrderForm();
					break;
				case 'orderAlbum':
				case 'orderPhotos':
					this.updateCart();
					$('#cartLink').removeClass('updating');
					this.updating = false;
					clearTimeout(this.timer);
					this.timer = null;
					break;
				case 'getInfo':
					this.updateCart();
					if (this.updating) this.timer = setTimeout('orderManager.intervalUpdate()', this.interval);
					break;
			}
			if (JSON.message && JSON.message.content && JSON.message.type)
				if (typeof photoManager === 'undefined') $.sfWindow.alert(i18n.iface.info, ((i18n.iface.jsonMessages[JSON.message.content]) ? i18n.iface.jsonMessages[JSON.message.content] : JSON.message.content));
				else photoManager.showMessage(JSON.message.content, JSON.message.type);
		}
	},
	cartDnD: function(event, ui) {
		this.target = $('#cartLink');
		if ($(ui.draggable).hasClass('photoItem')) this.orderPhotos();
		else this.orderAlbum(this._getId($(ui.draggable).attr('id')));
	},
	getAlbumId: function(){
		if($('#albumsList').length)
			return orderManager._getId($('#albumsList ul.list li.active').attr('id'));
		else if($('form#photosForm input[name=aid]').length)
			return $('form#photosForm input[name=aid]').val();
		return null;
	},
	orderPhotos: function(list, albumId) {
		this.requestJSON = {
			action: 'orderPhotos',
			albumId: this.getAlbumId(),
			photos: [],
			formatsQuantity: null
		};
		$('#photos span.item.selected').each(function() {
			orderManager.requestJSON.photos.push(orderManager._getId($(this).attr('id')));
		});
		$('#oldUploaderPhotos input').each(function() {
			orderManager.requestJSON.photos.push($(this).val());
		});
		if ($('#nextButton').length) {
			var getParams = $('#nextButton').attr('rel').split('?')[1].split('&');
			for (i = 0; i < getParams.length; i++)
				if (getParams[i].match(/^photos/)) {
					orderManager.requestJSON.albumId = 'none';
					orderManager.requestJSON.photos.push(getParams[i].split('='));
				}
		}
		if (list) {
			this.settings.goToCart = true;
			this.requestJSON.photos = list;
		}
		if (albumId) this.requestJSON.albumId = albumId;
		if (!this.requestJSON.photos.length)
			if (typeof photoManager === 'undefined') $.sfWindow.alert(i18n.iface.alert, i18n.photo.atLeastOnePhotoAlert);
			else photoManager.showMessage(i18n.photo.atLeastOnePhotoAlert, 'alert');
		else {
			this.photoOrderForm();
		}
	},
	orderAlbum: function(albumId) {
		if (typeof albumId === 'undefined') albumId = this._getId($('#albumsList ul.list li.active').attr('id'));
		if (albumId) {
			this.requestJSON = {
				action: 'orderAlbum',
				albumId: albumId,
				formatsQuantity: null
			};
			this.photoOrderForm();
		} else
			if (typeof photoManager === 'undefined') $.sfWindow.alert(i18n.iface.alert, i18n.photo.atLeastOneAlbumAlert);
			else photoManager.showMessage(i18n.photo.atLeastOneAlbumAlert, 'alert');
	},
	getFormatsAndPapers: function() {
		this.getJSON({ action: 'getFormatsAndPapers' });
	},
	onChangeFormat: function(select) {
		var paper = $(select).parent().find('select.paper'),
			format = $(select).parent().find('select.format'),
			edge = $(paper).find('option[value="6"]');
		if ($(format).val() == 2) $(edge).show();
		else {
			$(edge).hide();
			if ($(paper).val() == 6) $(paper).val(2);
		}
	},
	photoOrderForm: function() {
		if (this.JSON.cart && this.JSON.cart.formats) {
			if ($('#photoOrderForm').length) $('#photoOrderForm').html('');
			else $('<div id="photoOrderFormTemp"><div id="photoOrderForm"></div>').hide().appendTo('body');
			var photoOrderForm = $('#photoOrderForm');
			$('<h1>', { text: i18n.photo.order.title }).appendTo(photoOrderForm);
			$('<p>', { html: i18n.photo.order.info }).appendTo(photoOrderForm);
			var fieldset = $('<fieldset class="ui-corner-all"><legend>' + i18n.photo.order.legend + '</legend><div id="formatsQuantity"><div class="formatsQuantity"></div></fieldset>').appendTo(photoOrderForm),
				formLine = $('#formatsQuantity div.formatsQuantity:first'),
				formatSelect = $('<select>', {'class': 'format'}).appendTo(formLine),
				paperSelect = $('<select>', {'class': 'paper'}).appendTo(formLine);
			$('<input>', { type: 'text', 'class': 'quantity', size: 2 }).appendTo(formLine);
			$('<a>', { href: '#', 'class': 'icon actionAdditionalFormat', html: '<span class="ui-icon ui-icon-plusthick" />' + i18n.photo.order.additionalFormat }).appendTo(formLine);
			for (option in this.JSON.cart.formats)
				$('<option>', { value: option, text: this.JSON.cart.formats[option].name }).appendTo(formatSelect);
			for (option in this.JSON.cart.papers)
				$('<option>', { value: option, text: this.JSON.cart.papers[option] }).appendTo(paperSelect);
			$('<ul class="buttons">' +
				'<li class="right"><a href="#" class="button gray plus actionSetFormatSeparately"><span class="icon"></span>' + i18n.photo.order.setFormatSeparately + '</a></li>' +
				'<li><a href="#" class="button green plus actionAddToCart"><span class="icon"></span>' + i18n.photo.order.addToCart + '</a></li>' +
				'</ul>').appendTo(photoOrderForm);
			$('<div id="orderFormBanner">' + $('#orderManagerBanner').html() + '</div>').appendTo(photoOrderForm);
			this.fancyShow($('#photoOrderFormTemp').html());
			$('#formatsQuantity div.formatsQuantity:first select.format').val(2);
			$('#photoOrderFormTemp #photoOrderForm').html('');
		} else {
			this.getFormatsAndPapers();
			return;
		}
	},
	addFormatLine: function() {
		var newLine = $('#formatsQuantity div.formatsQuantity:first').clone().appendTo('#formatsQuantity');
		$(newLine).find('a.icon').remove();
		$('<a>', { href: '#', 'class': 'icon', html: '<span class="ui-icon ui-icon-trash" />' + i18n.iface.button.del })
			.appendTo(newLine)
			.click(function(event) {
				event.preventDefault();
				$(this).parent().remove();
			});
		$(newLine).find('select.format').val(2).change(function() { orderManager.onChangeFormat(this); });
		$(newLine).find('select.paper').focus(function() { orderManager.onChangeFormat(this); });
	},
	updateCart: function() {
		if(this.settings.goToCart)
			window.location = "/sf_zamow.sphp";
		else {
			$('#cartLink span.val').text(this.JSON.cart.total + ' ' + i18n.iface.currency);
			if (orderManager.JSON.cart.photos.count > 0 || orderManager.JSON.cart.gifts.count > 0 || orderManager.JSON.cart.products.count > 0){
				var updatedTitle = i18n.cart.containTitle;
				if(orderManager.JSON.cart.photos.count > 0)
					updatedTitle = updatedTitle + '|' + i18n.cart.containPhotos + ': *' + orderManager.JSON.cart.photos.count + '* ';
				if(orderManager.JSON.cart.gifts.count > 0)
					updatedTitle = updatedTitle + '|' + i18n.cart.containGadgets + ': *' + orderManager.JSON.cart.gifts.count + '* ';
				if(orderManager.JSON.cart.products.count > 0)
					updatedTitle = updatedTitle + '|' + i18n.cart.containProducts + ': *' + orderManager.JSON.cart.products.count + '* ';
			}
			else
				var updatedTitle = i18n.cart.emptyTitle;
			$('#cartLink').qtip('api').set({ 'content.text': simpleFormatTitle(updatedTitle) });

			$('#cartLink').effect('highlight', 'slow').addClass('full');
			if(!this.updating) $.sfWindow.alert(i18n.iface.info, i18n.photo.manager.alerts.photosAddedToCart, {
				buttons: {},
				modal: false,
				open: function(event, ui) {
					setTimeout('orderManager.closeInfo()', 2000);
					}
			});
		}
	},
	closeInfo: function() {
		$('div.sfModalAlert').dialog('close');
	},
	fancyShow: function(html) {
		var settings = $.extend(true, {}, fancyboxDefaults, {
			width: 600,
			height: 500,
			content: html,
			orig: this.target,
			enableEscapeButton: false,
			hideOnOverlayClick: false,
			onComplete: function() {
				orderManager.fancyInit();
				$.fancybox.center();
			}
		});
		$.fancybox(settings);
	},
	fancyInit: function() {
		swfInit($('#orderFormBanner'));
		$('#photoOrderForm input.quantity').val(1);
		$('#photoOrderForm a.actionAdditionalFormat').click(function(event) {
			event.preventDefault();
			orderManager.addFormatLine();
		});
		$('#formatsQuantity select.format').change(function() {orderManager.onChangeFormat(this)});
		$('#formatsQuantity select.paper').focus(function() {orderManager.onChangeFormat(this)});
		$('#photoOrderForm a.actionSetFormatSeparately').click(function(event) {
			event.preventDefault();
			orderManager.requestJSON.formatsQuantity = {};
			orderManager.requestJSON.formatsQuantity.disable = 1;
			orderManager.getJSON(orderManager.requestJSON);
			$.fancybox.close();
		});
		$('#photoOrderForm a.actionAddToCart').click(function(event) {
			event.preventDefault();
			orderManager.requestJSON.formatsQuantity = [];
			$('#formatsQuantity div.formatsQuantity').each(function() {
				var format = $(this).find('select.format').val(),
					paper = $(this).find('select.paper').val(),
					quantity = $(this).find('input.quantity').val();
				quantity = Math.abs(parseInt(quantity));
				if (!quantity) quantity = 1;
				orderManager.requestJSON.formatsQuantity.push({ format: format, paper: paper, quantity: quantity });
			});
			orderManager.getJSON(orderManager.requestJSON);
			$.fancybox.close();
		});
	},
	_getId: function(string) {
		if (!string) return null;
		return string.split('-')[1];
	}
};
$(function() {
	orderManager.init();
});

