/**
 * b2boss e-commerce solution
 * Scripts for klasyczne-meble.com
 * @author Krzysztof Kotowicz <web at eskot dot pl>
 * @see http://web.eskot.pl
 */
function fetchOptionImage(input) {
    var value = input.options ? input.options[input.selectedIndex].value : input.value;

	while (document.getElementById(input.name + "_image")) // bug - sometimes multiple images with the same ID get created, jQuery always return first
    	$(document.getElementById(input.name + "_image")).remove();

    if (value && value > 0) {

        $.getJSON("api/option_image", {option_id: value}, function(data) {

			while (document.getElementById(input.name + "_image")) // bug - sometimes multiple images with the same ID get created, jQuery always return first
		    	$(document.getElementById(input.name + "_image")).remove();

            if (data.url)
                $("<img>").attr({'class': 'option_image', 'id': input.name + "_image", 'src': data.url}).insertAfter(input);
        });
    }
}

/**
 * Enables gallery for a given selector (<ul> or <ol>).
 * All anchors should have a links to image that will replace the image_selector element image
 * Optionally the loaded image could be surrounded by <a> element with a link to a page
 * @author Krzysztof Kotowicz <kkotowicz at gmail dot com>
 */
jQuery.fn.gallery = function(image_selector, options) {
	var ul = this;

	var defaults = {
		auto: false,
		auto_stop_on_click: true
	};

	var options = $.extend({}, defaults, options);

	if (options.auto) {
		var getNextItem = function() {
			if ($('li.selected', ul).next('li').size())
				return $('li.selected', ul).next('li');
			else
				return $('li:first', ul);
		};

		var autoChangeInterval = setInterval(function() {
			getNextItem().find('a').trigger('click.gallery', [true]);
		}, options.auto);
	}
	return ul.find('a').bind('click.gallery', function(event, dontStop) {
		if (autoChangeInterval && options.auto_stop_on_click && !dontStop) {
			clearInterval(autoChangeInterval);
			autoChangeInterval = undefined;
		}
		var self = this;
		// clicking on <a> will replace image_selector image
		$(image_selector).fadeOut('fast', function() { // fade out first
			$(this).one('load', function() {
				var anchor;
				$(this).fadeIn('fast');

				if ((anchor = $(this).parent()) && anchor.is('a')) { // optionally replace <a> for image
					if ($(self).attr('rel'))
						anchor.attr('href',$(self).attr('rel')).unbind('click.gallery');
					else
						anchor.attr('href','#').bind('click.gallery', function() { return false});
				}

			});
			$(this).attr('src', self.href); // replace the image
		});
		$('li', ul).removeClass('selected');
		$(this).parent('li').addClass('selected');
		this.blur();
		return false;
	}).end();
};

jQuery.fn.showAjaxDialog = function(dialog_opts) {
    return this.each(function() {
        var self = this;
        // try url passed in options
        var url = dialog_opts && dialog_opts.url ? dialog_opts.url : undefined;

        // try object's href
        if (!url)
            url = self.href ? self.href : undefined;

        // if object is inside form, try its action
        if (!url) {
            // object to serialize = myself or my form
            var serial = self.action ? self : (self.form ? self.form : undefined);
            if (serial) {
                url = serial.action ? (serial.action + (serial.action.indexOf("?") == -1 ? "?" : "&" ) + $(serial).serialize()) : undefined;
            }

        }
        $('#ajax-action').remove();
        $("<div id='ajax-action'>").hide().appendTo('body');
        $('#ajax-action').load(url,
            function(text, status) {
            	if (status === 'success') {
	                $(this).hijack();
	                $(this).dialog(dialog_opts);
                }
            }
        );
    });
};

/**
 * @author Klaus Hartl
 * @author modified by Krzysztof Kotowicz <koto at webworkers dot pl>
 * @see http://groups.google.com/group/jquery-ui/browse_thread/thread/c728b8464f669674/711a7b0dd4236190?lnk=gst&q=tabs+links+ajax#711a7b0dd4236190
 * @param fun function to always call after hijacking (will be run in the same context as hijack())
 */
jQuery.fn.hijack = function(fun) {
    var target = this;

    return this
        .find('a:not(.nohijack)').click(function() {
           $(target).load(this.href, function() {
               $(this).hijack(fun);

               if (jQuery.isFunction(fun)) {
                 fun.call(this);
               }

           });

           return false;
        })
        .end()
        .find('form:not(.nohijack)')
            .hijackForm(target, fun)
        .end();
};

jQuery.fn.hijackForm = function(target, afterLoadFunction) {

    if (!jQuery.fn.ajaxForm) {
        return this;
    }

    return $(this).ajaxForm({
            target: target,
            beforeSubmit: function(fdata, jqForm, options) {
                if (jqForm.data('skip')) { // some submit handler (validation method?) told us to stop
                    jqForm.data('skip', false); // clear
                    return false;
                }
            },
            success: function() {
                var $target = $(target);
                $target.hijack(afterLoadFunction);

                if (jQuery.isFunction(afterLoadFunction)) {
                    afterLoadFunction.call($target);
                }
            }
    });
};

$(function() {
	$('.tabs').tabs({ fx: { opacity: 'toggle' } });
	$('.product_gallery_auto').gallery('.product_image img', {auto: 10000});
	$('.product_gallery:not(.product_gallery_auto)').gallery('.product_image img');
	$("#show-login").click(function() {
		$(this).showAjaxDialog({
			url: $(this).attr('rel'),
			title: $(this).html(),
			modal: true
		});
		return false;
	});
	$("body").ajaxError(function(event, request, settings){
   		alert("Error loading page: " + settings.url);
 	});
});

