
(function($) {
	/*
	* input = file input selector,
	* name = image name ([imageName]_0 - initial image, [imageName]_[1..n] - preview images
	* container = iamges container selector,
	* preview = [{w: width of initial preview, h: height of initial preview},{w: width preview, h: height of preview}, .., {}]
	*/
	$.uploadImage = function(options)
	{
		this.init(options);
	};

	$.fn.uploadImage = function(options)
	{
		new $.uploadImage($.extend(options, {input: $(this)}));
		return this;
	};

	$.extend($.uploadImage.prototype,
	{
		options: {},
		timerId: null,

		init: function(options)
		{
			var self = this;

			this.options = $.extend({
				form: $($(options.input)[0].form),
				container: $(options.container).hide(),
				width: null,
				height: null,
				init: null
			}, this.options, options);

			this.options.input
				.after($('<input type="hidden"/>').attr({
					name: this.options.name,
					id: this.options.name,
					validate: this.options.input.attr('validate'),
					value: ''
				}))
				.after($('<input type="hidden"/>').attr({
					name: this.options.name + '_x',
					id: this.options.name + '_x',
					value: '0'
				}))
				.after($('<input type="hidden"/>').attr({
					name: this.options.name + '_y',
					id: this.options.name + '_y',
					value: '0'
				}))
				.after($('<input type="hidden"/>').attr({
					name: this.options.name + '_w',
					id: this.options.name + '_w',
					value: '0'
				}))
				.after($('<input type="hidden"/>').attr({
					name: this.options.name + '_h',
					id: this.options.name + '_h',
					value: '0'
				}));

			this.options.input.attr({'validate': ''});

			// set uploadify object
			$(this.options.input).uploadify({
				'fileDataName':	'image',
				'uploader':		'/js/jquery.uploadify/uploadify.swf',
				'script':		this.options.script,
				'cancelImg':	'/js/jquery.uploadify/cancel.png',
				'auto':			true,
				'multi':		false,
				'fileExt':		'*.jpg;*.jpeg;*.png;*.gif;',
				'fileDesc':		'Image files',
				'onError':		function(event, queueId, fileObj, errObj) {
					alert('Error uploading file! May be not logged in ?');
				},
				'onSelect':		function(event, queueId, fileObj, errObj) {
					self.onSelectFile();
				},
				'onComplete':	function(event, queueId, fileObj, response, data) {
					setTimeout(function() {
						self.onCompleteUpload(response);
					}, 0)
				}
			});

			if (this.options.init != null && String(this.options.init).length > 0) {
				this.onCompleteUpload(this.options.init);
			}
		},

		onSelectFile: function(response)
		{
			//clear interval
			clearInterval(self.timerId);
			self.timerId = null;
			// clear filename
			$('#' + this.options.name).val('');
			// hide old images while uploading new
			$('#' + this.options.name + '_0').imgAreaSelect({ instance: true }).setOptions({ hide: true, enable: false });
			//hide container with images
			this.options.container.hide();
			// disable submit button
			$(this.options.form).find(':submit,:reset').attr('disabled', true);
		},

		onCompleteUpload: function(response)
		{
			// enable submit button
			$(this.options.form).find(':submit,:reset').attr('disabled', null);

			var result = null, self = this;
			try {
				result = eval('(' + response + ')');
			} catch(e) { };

			if (result != null && typeof(result) == 'object')
			{
				if (result['success'] == true)
				{
					// get uploaded image filename
					var fileName = result['filename'];
					$('#' + this.options.name).val(fileName);

					// get uploaded image size
					var imageSize = this.imageSize = result['size'];

					// show images container
					this.options.container.show();

					// set uploaded image previews attributes/styles
					for (var i = 0; i < this.options.preview.length; i++)
					{
						var iSize = this.options.preview[i], isWidth = (imageSize.w / iSize.w) >= (imageSize.h / iSize.h);
						
						$('#' + this.options.name + '_' + i).attr({
							'src': fileName + '?' + (new Date()).getTime()
						}).css({
							height: isWidth ? null : iSize.h,
							width: isWidth ? iSize.w : null,
							margin: 0
						})
						.data('isWidth', isWidth);

						if (typeof(iSize.div) != 'undefined') {
							$(iSize.div).css({
								overflow: 'hidden',
								width: iSize.w,
								height: iSize.h
							});
						}
					};

					$('#' + this.options.name + '_0').load(function()
					{
						/*$(this).imgAreaSelect({
							enable: true,
							aspectRatio: self.options.preview[0].w + ':' + self.options.preview[0].h,
							handles: true,
							imageHeight: imageSize.h,
							imageWidth: imageSize.w,
							onSelectChange: showPreview,
							onSelectEnd: selectEnd
						});*/

						/*function selectEnd(img, selection)
						{
							if (!selection.width || !selection.height)
							{
								$('#' + self.options.name + '_x').val(0);
								$('#' + self.options.name + '_y').val(0);
								$('#' + self.options.name + '_w').val(0);
								$('#' + self.options.name + '_h').val(0);
							}
							else
							{
								$('#' + self.options.name + '_x').val(selection.x1);
								$('#' + self.options.name + '_y').val(selection.y1);
								$('#' + self.options.name + '_w').val(selection.width);
								$('#' + self.options.name + '_h').val(selection.height);
							}
						}*/

						function showPreview(img, selection)
						{
							//clear selection
							if (!selection.width || !selection.height)
							{
								for (var i = 1; i < self.options.preview.length; i++)
								{
									var $img = $('#' + self.options.name + '_' + i), iSize = self.options.preview[i], isWidth = $img.data('isWidth');
									$img.css({
										width: isWidth ? iSize.w : null,
										height: isWidth ? null : iSize.h,
										margin: 0
									});
								}

								return;
							}

							var imageSize = self.imageSize;

							for (var i = 1; i < self.options.preview.length; i++)
							{
								var $img = $('#' + self.options.name + '_' + i), iSize = self.options.preview[i];
								var scaleX = iSize.w / selection.width, scaleY = iSize.h / selection.height;
								var width = scaleX * imageSize['w'], height = scaleY * imageSize['h'];

								$img.css({
									width: Math.round(width),
									height: Math.round(height),
									marginLeft: -Math.round(scaleX * selection.x1),
									marginTop: -Math.round(scaleY * selection.y1)
								});
							}
						}

						// refresh only if position of the images changed and slection width > 0
						/*self.timerId = setInterval(function() {
							var $el = $('#' + self.options.name + '_0'),
								ias = $el.imgAreaSelect({ instance: true }),
								iasSel = ias.getSelection(),
								elOffset = $el.offset(),
								elOffsetOld = $el.data('oldOffset') || {};

							if (iasSel.width > 0 && (elOffset.top != elOffsetOld.top || elOffset.left != elOffsetOld.left)) {
								ias.update();
								$el.data('oldOffset', elOffset);
							};
						}, 1000);*/
					});
				}
				else
				{
					var errMsg = "";
					for (var i = 0; i < result['message'].length; i++) {
						errMsg += result['message'][i] + "\n";
					}
					alert(errMsg.length > 0 ? errMsg : 'Error uploading file! Try again.');
				}
			}
			else
			{
				alert('Error uploading file! May be not logged in ?');
			}
		}

	});

})(jQuery);


(function($) {
	/**
	* container: form container
	* button: show/hide container button
	* refresh: true/false - refresh page after success submit
	*/
	$.fn.ajaxSubmitForm = function(options)
	{
		new $.ajaxSubmitForm($.extend(options, {container: $(this)}));
		return this;
	};
	$.ajaxSubmitForm = function(options)
	{
		this.init(options);
	};
	$.extend($.ajaxSubmitForm.prototype,
	{
		options: {},
		container: null,

		init: function(options)
		{
			var self = this;

			this.options = $.extend({
				form: $($(options.container).find('form').get(0)),
				submit: $(options.container.find(':submit')),
				cancel: $(options.container.find(':reset')),
				button: null,
				refresh: true,
				onSuccess: null
			}, this.options, options);

			if (this.options.button) {
				this.options.button.click(function() {
					self.options.container.toggle();
				});
			};

			this.options.cancel.click(function() {
				self.options.container.hide();
			});

			$.metadata.setType("attr", "validate");

			this.options.form.validate({
				submitHandler: function() {
					// show sending data message
					self.blockContainer({ icon: 'loading.gif', msg: 'Sending data..', click: true });
					//send form
					self.options.form.ajaxSubmit({
						dataType:  'json',
						beforeSerialize: function() {
							$('textarea,input[type=text]').filter('[hint]').each(function() {
								if ($(this).val() == $(this).attr('hint')) {
									$(this).val('')
								}
							});
							return true;
						},
						success: function(response) {
							if (typeof(response.message) == 'object') {
								if (!response.success) {
									var msg = "";
									for (name in response.message) {
										msg += '<ul class="errors">' + name + '<li>' + response.message[name] + '</li></ul>';
									}
									self.blockContainer({ icon: 'exclamation.png', msg: 'Some errors found<br>' + msg, click: true });
								} else {
									if (self.options.onSuccess) {
										self.options.onSuccess.call(self);
									}
									else if (self.options.refresh) {
										document.location.replace(document.location);
									}
									self.unblockContainer();
								}
							} else {
								self.blockContainer({ icon: 'exclamation.png', msg: 'Error sending data to server!', click: true });
							}
						},
						error: function(responseText, statusText) {
							self.blockContainer({ icon: 'exclamation.png', msg: 'Error sending data to server!', click: true });
						}
					});
					return false;
				}
			});
		},

		blockContainer: function(opts)
		{
			var self = this;

			this.options.container.block({
				message: '<h2><img src="/i/' + opts.icon + '" align="absmiddle"><b style="padding-left: 5px; font-size: 11px; color:black;">' + opts.msg + '</b></h2>',
				css: { border: '1px solid #FF8080', padding: 10, '-moz-border-radius': '10px', width: '50%' },
				overlayCSS: { backgroundColor: '#E0E0E0' }
			});

			if (opts.click) {
				this.options.container.find('.blockOverlay,.blockMsg')
					.attr('title', 'Click to unblock')
					.click(function() {
						self.unblockContainer();
					})
			}
		},

		unblockContainer: function()
		{
			this.options.container.unblock();
		}
	});


	var shopCart = function()
	{
		this.updateShopCart();
	};
	$.extend(shopCart.prototype,
	{
		addShopCartEl: function(el)
		{
			var aItems = this.getShopCart(), id = el.attr('id') || '';
			if ($.inArray(id, aItems) != -1) {
				/*alert("This creation already in your shop cart!");*/
				//var ch = confirm('This creation already in your shop cart! Checkout?');
				//$('div#checkout_confirm').dialog('open');
				dialogCheckoutConfirm('This creation already in your shop cart! Checkout?');
			} else {
				aItems.push(id);
				$.cookie('ShopCart', aItems.join(','), {path: '/'});
				this.updateShopCart();
				/*alert("Creation added to  your shop cart.");*/
				//var ch = confirm("Creation added to  your shop cart. Checkout?");
				//$('div#checkout_confirm').dialog('open');
				dialogCheckoutConfirm('Creation added to  your shopping cart. Checkout?');
			}
			/*alex: redirect to cart if OK*/
			//if (ch) location.href='/myloft/'+el.attr('name')+'/order/cart';
			return false;
		},

		getShopCart: function()
		{
			var val = $.cookie('ShopCart');
			return val ? val.split(",") : [];
		},

		delShopCartEl: function(el)
		{
			var aItems = this.getShopCart(), id = el.attr('id') || '', iOffset = $.inArray(id, aItems);
			aItems.splice(iOffset, 1);
			$.cookie('ShopCart', aItems.join(','), {path: '/'});
			this.updateShopCart();
		},

		updateShopCart: function()
		{
			var aItems = this.getShopCart();
			$('.shopCartNumber').html(aItems.length)
		},		
		
		setShopCart: function(ids)
		{
			$.cookie("ShopCart", ids, {path: "/"});
			this.updateShopCart();
		}
	});
	$.shopCart = new shopCart();

	$('a.addShopCartEl').click(function() {
		$.shopCart.addShopCartEl($(this));
		return false;
	});

})(jQuery);


/**
*	show flag dialog
*/
(function($) {
	$.flagDialog = function(options)
	{
		this.init(options);
	};
	$.fn.flagDialog = function(options)
	{
		new $.flagDialog($.extend(options, {input: $(this)}));
		return this;
	};
	$.extend($.flagDialog.prototype,
	{
		init: function(options)
		{
			if (!options.url) {
				return false;
			}

			var self = this;
			var $dialog = $('#flagDialog');

			$dialog.find('.cancelFlagDialog').click(function() {
				$.iTooltip.hide();
				return false;
			});

			$dialog.find('form').attr('action', options.url);

			$(options.input).tooltip({
				event: 'click',
				sticky: true,
				className: 'complaintt',
				text: $dialog.clone(true)
			})
			.bind('show.tooltip', function(e, el) {
				$.iTooltip.helper.find('textarea').each(function() {
					$(this).val($(this).attr('hint') ? $(this).attr('hint') : "");
				});

				$.iTooltip.helper.find('label.error').hide();

				if (el.ttCFG.text.jquery) {
					$($.iTooltip.helper).find('#flagDialog').ajaxSubmitForm({
						refresh: false,
						onSuccess: function() {
							$.iTooltip.hide();
						}
					});
				}
			});
		}
	});
})(jQuery);


(function($) {
	// my validate routine for hint form fields
	$.fn.validateMy = function(opts) {
		opts = $.extend(opts, {
			submitHandler: function(form) {
				$('textarea,input[type=text]').filter('[hint]').each(function() {
					if ($(this).val() == $(this).attr('hint')) {
						$(this).val('');
					}
				});

				form.submit();
			}
		});
		return $(this).validate(opts);
	};
})(jQuery);

(function($) {
	// show in text areas default hint text
	$.setHint = function()
	{
		$('textarea,input[type=text]').filter('[hint]').each(function()
		{
			if ($(this).val() == "") {
				$(this).val($(this).attr('hint'));
			}

			$(this).focus(function() {
				if ($(this).val() == $(this).attr('hint')) {
					$(this).val('')
				}
			})

			$(this).blur(function() {
				if ($(this).val() == "") {
					$(this).val($(this).attr('hint'))
				}
			})
		});
	};
	$.setHint();
})(jQuery);
