(function ($) {
	var defaults = {
		content_id: 'barter_content',
		bg_img_id:  'superbgimage',
		menu_id:    'barter_menu',
		nav_id:     'barter',
		prev_id:    'barter_prev',
		next_id:    'barter_next',
		wrapper_id: 'barter_wrapper',
		thumbs_id:  'barter_imgs',
		form_container_id: 'make_me_an_offer',
		curr_barter_img_id: 'curr_barter_img',
		offer_barter_img_id: 'offer_barter_img',
		container_width:  600,
		container_height: 475,
		img_path:   '/assets/images/barter/',
		json_url:   '/barter/imgs'
	};

  $(document).ready(function(){
    $('#barter_form').ajaxForm({
      dataType: 'json',
      beforeSubmit: function() {
        $('#barter_status').html('Submitting...');
      },
      success: function(data) {
        if ( data['status'] == 'success' ) {
          $('#barter_status').html(data['message']);				
          $('#barter_status').show();
          $('#barter_form #description').val('');
          $('#barter_form #upload').val('');
          $('#barter_form').hide();
        } else {
          $('#barter_errors').html(data['message']);
          $('#barter_errors').show();
        }
      },
      error: function(xhr,status,error) {
        $('#barter_status').html('Sorry, we are having technical difficulties...please try again later.');
        $('#barter_status').show();
        $('#barter_form').hide();
      }
    });
  });

	var methods = {
		init: function(options) {
			// superBGimage is not jQuery 1.4-friendly, so we cannot use
			// the data() facility and instead need to be naughty and stor
			opts = $.extend({}, defaults, options);
			$.fn.aob_barter('hide');
			load_images(opts.json_url, opts.img_path, opts.thumbs_id);
			$('#'+opts.prev_id).click(function(evt) {
				prev();
				evt.preventDefault();
			});
			$('#'+opts.next_id).click(function(evt) {
				next();
				evt.preventDefault();
			});
			$('#barterclose').click(function(evt) {
				hide_form();
			});
		},
		show: function(show_callback) {
			$.fn.aob_background('stop');
         $('#barter_form').show();
			var content_id = opts.content_id;
			$('#'+content_id).slideUp(500, function () {
				$('#'+opts.menu_id).show();
				$.fn.aob_background('hide_controls');
				$('#'+content_id).slideDown(500);
			});
			$('#'+opts.bg_img_id).hide();
			$('#'+opts.nav_id).addClass('current');
			show_image();
			visible = true;
			if (show_callback) show_callback.apply(this);
		},
		hide: function(hide_callback) {
			$('#'+opts.content_id).slideUp(500, function() {
				$.fn.aob_background('start');
				$.fn.aob_background('show_controls');
				if (hide_callback) hide_callback.apply(this);
			});
			$('#'+opts.prev_id).unbind('click');
			$('#'+opts.next_id).unbind('click');
			$('#'+opts.bg_img_id).show();
			visible = false;
		},
		toggle: function(hide_callback, show_callback) {
			visible ? $.fn.aob_barter('hide', hide_callback) : $.fn.aob_barter('show', show_callback)
		}
	};

	var opts    = {};
	var visible = false;
	var current = 1; // 1-indexed
	var thumbs_count  = 0;
	var debug   = false;
	var loading = false;

	$.fn.aob_barter = function(method) {
		if ( methods[method] ) {
			return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ))
		} else if ( typeof method === 'object' || !method ) {
			return methods.init.apply( this, arguments )
		} else {
			$.error('Method '+ method + ' does not exist on jQuery.aob_barter')
		}
	};

	function next(){
		current = current >= thumbs_count ? 1 : current + 1;
		show_image();
	}
	function prev(){
		current = current <= 1 ? thumbs_count : current - 1;
		show_image();
	}

	function show_image() {
		var wrapper_id = opts.wrapper_id;
		var thumb      = $('#'+opts.thumbs_id+' li:eq('+parseInt(current-1)+')');

		if ( thumb.length ) {
			var thumb_img = thumb.find('img');

			if ( thumb_img.length ) {
				var curr_img   = $('#'+wrapper_id).find('img');
				var thumb_desc = thumb.find('div.barter_desc');

				if ( curr_img.length ) {
					var curr_desc = $('#'+wrapper_id).find('div.barter_desc');
					if (curr_desc.length) curr_desc.fadeOut(function() { $(this).remove() });
					var curr_offer = $('#'+wrapper_id).find('div.barter_offer');
					if (curr_offer.length) curr_offer.fadeOut(function() { $(this).remove() });

					curr_img.fadeOut(function() {
						$(this).remove();
						load_image(thumb_img, thumb_desc, wrapper_id);
					});
				} else {
					load_image(thumb_img, thumb_desc, wrapper_id);
				}
			}
		}
	}

	function load_image(thumb_img, thumb_desc, wrapper_id) {
		$('<img />').load(function() {
			var image = $(this);
			resize(image, opts.container_width, opts.container_height);
			image.attr('id', opts.curr_barter_img_id);
			var div   = $(document.createElement('div'));
			var offer = $('#barter_offer').clone().removeAttr('id').css('display', 'block');
			offer.click(function(evt) { if (debug) { console.log('offer click') } show_form() });
			div.append(thumb_desc.clone()).append(offer);
			$('#'+wrapper_id).empty().append(image.fadeIn()).append(div.fadeIn());
		}).attr('src',thumb_img.attr('src'));
	}

	function resize(image_in, container_width, container_height) {
		var resize_img  = new Image();
		resize_img.src  = image_in.attr('src');
		var img_width 	= resize_img.width;
		var img_height 	= resize_img.height;
		if (debug) console.log('resize_img: '+image_in.attr('src')+'('+img_width+'x'+img_height+'), width: '+container_width+', height: '+container_height);

		var container_width  = container_width;
		var container_height = container_height;;
		var wrong_width      = img_width  > container_width  || img_width  < container_width;
		var wrong_height     = img_height > container_height || img_height < container_height;

		if ( wrong_width || wrong_height ) {
			var ratio  = img_width / container_width;
			img_width  = container_width;
			img_height = img_height / ratio;

			if ( img_height > container_height || img_width > container_width ) {
				ratio      = img_height / container_height;
				img_height = container_height;
				img_width  = img_width / ratio;
			}
		}

		if (debug) console.log('resizing to ('+img_width+'x'+img_height+')');
		image_in.css({
			width:  img_width,
			height: img_height
		});
	}

	function load_images(json_url, img_path, container_id){
		if (debug) console.log('load_images (json_url: '+json_url+')');
		loading = true;
		jQuery.getJSON(json_url,function(data,textStatus,jqXHR){
			var barter_container = $('#'+container_id);
			jQuery.each(data, function(index,elem){
				if (debug) console.log("elem: {"+elem.title+', medium: '+elem.medium+', size: '+elem.size+'}');
				var desc = $(document.createElement('div'));
				desc.addClass('barter_desc');
				var title = $(document.createElement('h3'));
				title.append(elem.title);
				desc.append(title);
				var medium = $(document.createElement('div'));
				medium.append(elem.medium);
				desc.append(medium);
				var size = $(document.createElement('div'));
				size.append(elem.size);
				desc.append(size);
				var img = document.createElement('img');
				img.setAttribute('src', img_path + elem.img);
				var li = $(document.createElement('li'));
				li.append(desc);
				li.append(img);
				barter_container.append(li);
			});

			loading = false;

			thumbs_count = $('#'+container_id+' img').length;
		});
	}

	function show_form() {
		if (debug) console.log('show_form');
		$('#'+opts.form_container_id).fadeIn(function(){
         $('#barter_status').hide();
         $('#barter_errors').hide();
         $('#barter_form').show();
			var curr_barter_img      = $('#'+opts.curr_barter_img_id).clone();
			var offer_img_container  = $('#'+opts.offer_barter_img_id);
			resize(
				curr_barter_img, 
				offer_img_container.width(), 
				offer_img_container.height()
			);
			if (debug) console.log('curr_barter_img: width='+curr_barter_img.css('width')+', height='+curr_barter_img.css('height'));
			offer_img_container.append(curr_barter_img);
		});
	}

	function hide_form() {
		if (debug) console.log('hide_form');
		$('#'+opts.form_container_id).fadeOut(function() {
			$('#'+opts.offer_barter_img_id).empty();
		});
	}

})(jQuery);

