$(function () {
	$('div#album tr.new').attach(NewCardBehaviour);
	$('div#album tr.special').attach(SpecialCardBehaviour);
	
	$('div#album tr.special.not-included div.image').attach(ExpressCardBehaviour);
	$('div#album tr.special:not(.not-included) div.image').children('.express-link').remove();
	
	$('form').focus_first();
	
	$('div#dialog form div#offers input').attach(SelectImageBehaviour);
	$('div#dialog form div#offers img').attach(SelectImageBehaviour);
});

function addAndPositionIcon (element, className, imageURL, position) {
	var image = element.find('div.image');

	var image_obj = new Image(); 
	var new_div = '<div class="' + className + '"><img src="' + imageURL + '"/></div>';
	image.prepend(new_div);
	
	var new_image = element.find('div.' + className);
	image_obj.onload = function () {
		
		var margin = Number(image.css('margin-left').replace('px', ''));
		if (position == 'left') {
			new_image.css('left', new_image.position().left - (new_image.width() / 2));
		} else {
			new_image.css('left', new_image.position().left + image.width() - (new_image.width() / 2));
		}
		
		new_image.css('top', new_image.position().top - (new_image.width() / 2));
	}
	image_obj.src = imageURL;
}

$.fn.focus_first = function () {
  var elem = $('input:visible', this).get(0);
  var select = $('select:visible', this).get(0);

  if (select && elem) {
    if (select.offsetTop < elem.offsetTop) {
      elem = select;
    }
  }

  var textarea = $('textarea:visible', this).get(0);
  if (textarea && elem) {

    if (textarea.offsetTop < elem.offsetTop) {
      elem = textarea;
    }
  }

  if (elem) {
    elem.focus();
  }
}