jQuery.fn.delegate = function(eventType, rules) {
  return this.bind(eventType, function(e) {
    var target = $(e.target);
    for(var selector in rules)
      if(target.is(selector)) 
        return rules[selector].apply(this, arguments);
  })
};

jQuery.fn.realOffset = function() {
	var that = this[0];
	var x = 0;
	var y = 0;
	do {
		x += that.offsetLeft;
		y += that.offsetTop;
	} while (that = that.offsetParent);
	return {left: x, top: y};
}

function wizzyForm(url) {
	$("#simplemodal-container form").ajaxForm({
		target: $("#simplemodal-data"),
		url: url,
		success: function() {
			$.modal.impl.setPosition();
			wizzyForm(url);
		}
	});	
}

function selectReplace(selector) {
	if (typeof selector == 'undefined') {
		var selector = 'select';
	}

	$(selector).each(function(){
		var oldSelect = $(this);

		var newSelect = $('<span>').addClass('select-replace').append(
			$('<span>').addClass('active')
		).append(
			$('<span>').addClass('options')
		);

		$('option', oldSelect).each(function(){
			var option = $(this);
			$('.options', newSelect).append(
				$('<a>').addClass('option').attr('rel', option.attr('value')).html(option.html())
			);
		});

		var oldSelectedOption = $('option[value=' + oldSelect.val() + ']');
		$('<span>').addClass('option').html(oldSelectedOption.html()).appendTo($('.active', newSelect));

		newSelect.insertAfter(oldSelect);
		oldSelect.hide();

		var options = $(".options .option", newSelect);
		
		$(".active", newSelect).click(function(e){
			var select = $(this).parent();
			if($(".options", select).is(":visible")){
				select.removeClass("select-open");
			}else{
				$('.select-open').removeClass('select-open');
				select.addClass("select-open");
				options.removeClass("hover");
				$('.options .option[rel=' + oldSelect.val() + ']', newSelect).addClass("hover");
			}
			e.preventDefault();
			e.stopPropagation();
		});

		options.click(function(e){
			var option = $(this);
			var selectedValue = option.attr('rel');
			if (selectedValue != oldSelect.val()) {
				oldSelect.val(option.attr('rel')).change();
			}
			$('.active .option', newSelect).text(option.text());
			newSelect.removeClass('select-open');
			e.preventDefault();
			e.stopPropagation();
		}).hover(function(){
			options.removeClass("hover");
			$(this).addClass("hover");
		});

		$("body").click(function(){
			newSelect.removeClass("select-open");
		});
	});
}

function trackPageview(url) {
	if (typeof pageTracker != "undefined") {
		pageTracker._trackPageview(url);
	} else if(typeof console != "undefined") {
		console.log('Tracking page ' + url);
	}
}

function trackEvent(category, action) {
	if (typeof pageTracker != "undefined") {
		pageTracker._trackEvent(category, action);
	} else if(typeof console != "undefined") {
		console.log('Tracking event ' + category + ' / ' + action);
	}
}

$.modal.defaults.onShow = function(dialog) {
	$.modal.impl.setPosition();
};
$.modal.defaults.autoResize = true;
$.modal.defaults.minHeight = 0;
$.modal.defaults.maxWidth = 800;

$(function() {
	$("a[href=#]").click(function(e) {
		e.preventDefault();
	});
	
	$('a.modal').click(function(e){
		e.preventDefault();
		var $this = $(this);
		$.get($this.attr("href"), "", function(data) {
            var modal = $.modal(data,{
                onShow: function(dialog) {
                    $.modal.impl.setPosition();
                }
            });
            wizzyForm($this.attr("href"));
        });
	});
	
	$("form.modal").ajaxForm({
		success: function(response, status) {
			$.modal(response);
			$.modal.impl.setPosition();
			wizzyForm(this.url);
		}
	});
	
	// Gallery
	$(".gallery .thumbs .thumb").click(function(e){
		e.preventDefault();
		var href = $(this).attr("href");
		var $thumb = $(this);
		var info = $('.info', $thumb);
		$("img", this).fadeTo(250, 0.5, function(){
			var $this = $(this);
			if($thumb.hasClass('video')) {
				$.get(href, function(data){
					var $main = $(".gallery .main img");
					$(".gallery .thumbs .thumb").removeClass("active");
					$thumb.addClass("active");
					$main.hide().parent().append('<div class="video-container">' + data + '</div>');
					var $caption = $('.caption', $thumb.closest('.gallery'));
					if($caption.length){
						$caption.text($thumb.attr('title'));
					}
					if (info.length > 0) {
						$(".gallery .main p").html(info.html());
						Cufon.refresh();
					}
					setTimeout(function(){
						$this.fadeTo(250, 1);
					}, 25);
				});
			} else {
				var i = new Image();
				i.onload = function(){
					var $main = $(".gallery .main img");
					$(".gallery .main .video-container").remove();
					$(".gallery .thumbs .thumb").removeClass("active");
					$thumb.addClass("active");
					$main.css("opacity", 0).attr("src", i.src);
					var $caption = $('.caption', $thumb.closest('.gallery'));
					if($caption.length){
						$caption.text($thumb.attr('title'));
					}
					if (info.length > 0) {
						$(".gallery .main p").empty().append(info.clone().removeClass('info'));
						if ($thumb.attr('rel') != '') {
							$(".gallery .main a").attr('href', $thumb.attr('rel'));
						}
						Cufon.refresh();
					}
					setTimeout(function(){
						$main.fadeTo(350, 1);
						$this.fadeTo(250, 1);
					}, 25);
				};
				i.src = href;
			}
		});
	});
	
	$(".rightcol .box").hover(function(e){
		$this = $(this);
		var $img = $("img", $this);
		if($img.length){
			$this.css("backgroundColor", "#000000");
			$img.stop(true).fadeTo(150,0.3);
		}
		var $ul = $("ul", $this);
		if($ul.length){
			$ul.stop(true).fadeTo(150,.99).click(function(){
				window.location = $("a", $this).attr("href");
			});
		}
	}, function(e){
		$this = $(this);
		$("img", $this).fadeTo(150,1);
		var $ul = $("ul", $this);
		if($ul.length){
			$ul.fadeTo(150,0);
		}
	});
	
	$(".related-products .box").hover(function(e){
		$('a:has(img)', $(this).closest('.box').addClass('hover')).addClass('shadow');
	}, function(e){
		$('a:has(img)', $(this).closest('.box').removeClass('hover')).removeClass('shadow');
	}).click(function(e){
		e.preventDefault();
		window.location = $('a', $(this).closest('.box')).attr('href');
	});
});
