$(document).ready(function() {

	var menu = window.menu = {
		initialize: function() {
			$('#side_bar .categorias .submenu').hide();

			$('#side_bar .categorias .menu_item').click(function() {
				if ($(this).parent('li').hasClass(($('#side_bar .categorias li ul:visible').parent('li').attr('class') || '').split(' ')[0])) return;
				$('#side_bar .categorias .submenu:visible').slideUp('fast');
				$('#side_bar .categorias li').removeClass('current');
				$(this).next('ul').slideDown('fast');
				$(this).parent('li').addClass('current');
				if ($(this).attr('href') == '#' || $('.submenu', $(this).parent('li')).length) return false;
			});
		},
		set_default: function(page) {
			if (!page['section']) return;
			var $submenu = $('#side_bar .categorias .' + page['section']).addClass('current').children('ul').show();
			if (page['submenu']) $('.' + page['submenu'], $submenu).addClass('current');
		}
	};

	var easy_upload = window.easy_upload = {
		uploading_file: function(embed_id, msg) {
			$(embed_id).parent('a').append('<span></span>').addClass('loading');
		},
		upload_complete: function(embed_id) {
			$(embed_id).parent('a').remove('span').removeClass('loading');
			// console.debug("upload_complete", $(embed_id));
		}
	};

	/* Add extra photo */
	$('a.add_extra_photo').mouseenter(function() {
		if (!$(this).hasClass('.flash-replaced')) {
			var d 			= new Date();
			var item_id 	= $(this).attr('href').replace(/#(\d+)/, "$1");
			var embed_id 	= "easyupload_" + d.getTime().toString() + d.getMilliseconds().toString();

			$(this).flash({
				id: 				embed_id,
				src: 				_relpath + 'static/assets/llweb/resources/up.swf?' + (new Date.now()),
				width: 				20,
				height: 			20,
				wmode: 				'transparent',
				allowScriptAccess: 	'always',
				swLiveConnect: 		true,
				flashvars: 			{
					'embed_id': 	'#' + embed_id,
					'upload_url': 	"http://" + window.location.host + _relpath + "catalogo/attachment.php?item_id=" + item_id
				}
			});
		}
	});

	/* Remove */
	$('a.remove').click(function() {
		if (!$(this).hasClass('remove_unlocked')) {
			$(this).addClass('remove_unlocked');
			return false;
		}
		var item_id = $(this).attr('href').replace(/#(\d+)/, "$1");
		var container = $(this).parents('.tiny_container, .adicional');
		if (container.is('.adicional')) {
			$.get('', {'action': 'adicionales_delete_photo', 'item_id': item_id, 'adicional_name': $(this).attr('rel')}, function() {
				container.hide('fast');
			});
		} else if (container.is('.tiny_container')) {
			$.get('', {'action': 'remove_item', 'item_id': item_id}, function() {
				container.css({'opacity': 0.4}).find('.thumb_area').hide('fast');
			});
		}
	});

	/* Pushpin */
	var pushpin = window.pushpin = {
		section: (jQuery.url.param('categoria') || '').replace(/([a-z]+\.)/, ''),
		setup: function() {
			$('a.pushpin').click(function() {
				var $pushpin = $(this);
				var pressure = ($pushpin.hasClass('attached')) ? 'remove' : 'attach';
				var item_id  = $(this).attr('href').replace(/#(\d+)/, "$1");

				$.get('', {'action': 'pushpin', 'item_id': item_id, 'pressure': pressure, 'section': pushpin.section}, function(data) {
					$pushpin.toggleClass('attached');
					if (parseFloat($('remaing', data).text()) <= 0) { // run out of pushpins
						$('a.pushpin:not(.attached)').hide();
					} else {
						$('a.pushpin:not(.attached)').show();
					}
				});
			});
			// pushpin.has_pushpins(pushpin.section);
		},
		has_pushpins: function(section) {
			$.get('', {'action': 'pushpin_available', 'section': section}, function(data) {
				if (parseFloat($('remaing', data).text()) <= 0) $('a.pushpin:not(.attached)').hide();
			});
		}
	};
	pushpin.setup();
	
	
	var fotos_adicionales = window.fotos_adicionales = {
		_proceed_image: function(gImage, great_image) {
			var opts = $.fn.fancybox.defaults;

			var width	= gImage.width;
			var height	= gImage.height;

			var horizontal_space	= (opts.padding * 2);
			var vertical_space		= (opts.padding * 2);

			var w = $.fn.fancybox.getViewport();
			
			/*
			var horizontal_space	= (opts.padding * 2) + 40;
			var vertical_space		= (opts.padding * 2) + 60;
			
			if (opts.imageScale && (width > (w[0] - horizontal_space) || height > (w[1] - vertical_space))) {
				var ratio = Math.min(Math.min(w[0] - horizontal_space, width) / width, Math.min(w[1] - vertical_space, height) / height);

				width	= Math.round(ratio * width);
				height	= Math.round(ratio * height);
			}
			*/

			var itemTop		= (height	+ 60) > w[1] ? w[3] : (w[3] + Math.round((w[1] - height	- 60) * 0.5));
			var itemLeft	= (width	+ 40) > w[0] ? w[2] : (w[2] + Math.round((w[0] - width	- 40) * 0.5));

			var itemOpts = {
				'left':		itemLeft,
				'top':		itemTop,
				'width':	(width + horizontal_space) + 'px',
				'height':	(height + vertical_space) + 'px'
			};
			
			$("#fancy_outer").animate(itemOpts, opts.zoomSpeedChange, opts.easingChange, function() {
				if ($("#fancy_outer").is(":visible") !== false) $("#fancy_div").fadeIn('fast');
				$(great_image).fadeIn();
				
				var ow	= $("#fancy_outer").outerWidth();
				var oh	= $("#fancy_outer").outerHeight();

				var pos	= {
					'top'	: (oh > w[1] ? w[3] : w[3] + Math.round((w[1] - oh) * 0.5)),
					'left'	: (ow > w[0] ? w[2] : w[2] + Math.round((w[0] - ow) * 0.5))
				};

				$('#fancy_title').css({
					'top'	: pos.top	+ oh - 20,
					'left'	: pos.left	+ ((ow * 0.5) - ($('#fancy_title').width() * 0.5))
				}).show();
			});
		},
		_load_image: function($great_image) {
			var gImage = new Image; gImage.src = $great_image.attr('src');
			
			if (gImage.complete) {
				fotos_adicionales._proceed_image(gImage, $great_image);
			} else {
				$(gImage).unbind().bind('load', function() {
					fotos_adicionales._proceed_image(gImage, $great_image);
				});	
			}
		},
		setup_container: function(container_id) {
			var $container   = $(container_id);
			var $great_image = $('img.great_image', $container);

			$('.adicional', $container).unbind('click.fa').bind('click.fa', function(e) {
				var previous_big_path   = $great_image.attr('src');
				var previous_thumb_path = $great_image.attr('rel');
				
				$great_image.hide();
				$('#fancy_title').hide();
				
				$great_image.attr('src', $('a', this).attr('href'));
				$great_image.attr('rel', $('a img', this).attr('src'));
				
				fotos_adicionales._load_image($great_image);
				
				$('a', this).attr('href', previous_big_path);
				$('a img', this).attr('src', previous_thumb_path);
				
				return false;
			});
			
			fotos_adicionales._load_image($great_image); // 1st photo
		}	
	};

	//
	// Startup
	//
	menu.initialize();
	
	$('a.bigview').fancybox({
		hideOnContentClick: false,
		callbackOnShow: function(o) {
			if (o.href.indexOf("#view_adicionales") >= 0) fotos_adicionales.setup_container('#fancy_div');
		}
	});

});
