var deeb = {

	setGravityRecommIds: function(a)
	{
		this.gravityRecommIds = a;
	},

	getGravityRecommId: function(pid)
	{
		if (this.gravityRecommIds[pid])
		{
			return this.gravityRecommIds[pid]
		}
		return null;
	},

    getStore: function(form)
    {
        $.post("/?q=ajax", 'function=getStore&' + $(form).serialize(), function(data)
        {
            $('#stores').html(data);
        }, "json");
    },
    
    getStoreCity: function(form)
    {
        $.post("/?q=ajax", 'function=getStoreCity&' + $(form).serialize(), function(data)
        {
            $('#cities').html(data);
        }, "json");
    },

    copyBillFields: function(el)
    {
        var fields = ['name', 'country', 'zip', 'city', 'domain', 'nr', 'floor', 'door'];
        for (var i=0; i<fields.length; i++)
        {
            $('#bill_'+fields[i]).val((el.checked)?$('#post_'+fields[i]).val():'');
        }
    },
    
    toggleBill: function()
    {
        $('#billing').toggle();
    },
    
    searchSidebar: function(link, def)
    {
        var p = $('#search-prices').val().split('-');
        var t = $('#search-text').val();
        if (t == def) t = '';
        window.location = link + '&price_from='+p[0]+'&price_to='+p[1]+'&text='+t;
    },
    
    bigyonap: function(v)
    {
        if (v == 'other') {
            $('#bigyonapalatt-other').css('display', 'block');
            $('#bigyonapalatt-other-value').val('');
        } else {
            $('#bigyonapalatt-other').css('display', 'none');
            $('#bigyonapalatt-other-value').val(v);
        }
    },
    
    addToWish: function(id)
    {
		var rid = deeb.getGravityRecommId(id);

		GravityRD.addEvent({ eventType: "ADD_TO_WISHLIST", itemId: id, recommendationId: rid });
		GravityRD.commit();

        $('#wish-loader').css('display', 'block');
        $('#wish-container').css('display', 'none');

        $.post('/?q=ajax', {'function': 'wish', 'id': id}, deeb.wishResponse, "json");

        if ($(window).scrollTop() > $('#wish').offset().top + 100)
        {
            $('html').animate({scrollTop:$('#wish').offset().top}, 'slow');
        }
    },

    wishResponse: function(data, status)
    {
        $('#wish-loader').css('display', 'none');
        $('#wish-container').css('display', 'block').html(data);
    },
    
    removeFromWish: function(id)
    {
		var rid = deeb.getGravityRecommId(id);

		GravityRD.addEvent({ eventType: "REMOVE_FROM_WISHLIST", itemId: id, recommendationId: rid });
		GravityRD.commit();

        $('#wish-loader').css('display', 'block');
        $('#wish-container').css('display', 'none');

        $.post('/?q=ajax', {'function': 'wishremove', 'id': id}, deeb.wishResponse, "json");

        if ($(window).scrollTop() > $('#wish').offset().top + 100)
        {
            $('html').animate({scrollTop:$('#wish').offset().top}, 'slow');
        }
    },
    
    removeFromCart: function(id, attr)
    {
		var rid = deeb.getGravityRecommId(id);

		GravityRD.addEvent({ eventType: "REMOVE_FROM_CART", itemId: id, recommendationId: rid });
		GravityRD.commit();

		$('#cart-loader').css('display', 'block');
        $('#cart-container').css('display', 'none');

        $.post('/?q=ajax', 'function=cartremove&id='+id+'&attr='+attr+'&'+$('#product-form').serialize(), deeb.cartResponse, "json");

        if ($(window).scrollTop() > $('#cart').offset().top + 100)
        {
            $('html').animate({scrollTop:$('#cart').offset().top}, 'slow');
        }
    },
    
    addToCartSimple: function(id, qty)
    {
		var rid = deeb.getGravityRecommId(id);

		GravityRD.addEvent({ eventType: "ADD_TO_CART", itemId: id, recommendationId: rid, nameValues: [{ name: "Quantity", value: qty}] });
		GravityRD.commit();

		$('#cart-loader').css('display', 'block');
        $('#cart-container').css('display', 'none');

        $.post('/?q=ajax', 'function=cart&id='+id+'&count='+qty, deeb.cartResponse, "json");

        if ($(window).scrollTop() > $('#cart').offset().top + 100)
        {
            $('html').animate({scrollTop:$('#cart').offset().top}, 'slow');
        }
    },
    
    addToCart: function(id)
    {
		var rid = deeb.getGravityRecommId(id);
		var qty = $('#count').val();

		GravityRD.addEvent({ eventType: "ADD_TO_CART", itemId: id, recommendationId: rid, nameValues: [{ name: "Quantity", value: qty}] });
		GravityRD.commit();

        $('#cart-loader').css('display', 'block');
        $('#cart-container').css('display', 'none');

        $.post('/?q=ajax', 'function=cart&id='+id+'&'+$('#product-form').serialize(), deeb.cartResponse, "json");

        if ($(window).scrollTop() > $('#cart').offset().top + 100)
        {
            $('html').animate({scrollTop:$('#cart').offset().top}, 'slow');
        }
    },

    cartResponse: function(data, status)
    {
        $('#cart-loader').css('display', 'none');
        $('#cart-container').css('display', 'block').html(data);
    },

    setWrapper: function()
    {
        this.wrapper = $('#content .pager-content');
    },
    
    loadPage: function(url)
    {
        $('html').animate({scrollTop:$('body').offset().top}, 'slow', 'linear', function(){
                deeb.wrapper.fadeTo('fast', 0, function() {
                    $.get(url, '', deeb.loadedPage);
                });
        });
    },
    
    loadedPage: function(data, status)
    {
        deeb.wrapper.html(data);
        deeb.parsePagerLinks();
        deeb.wrapper.fadeTo('fast', 1);
    },
    
    parsePagerLinks: function()
    {
        $('.product_grid').each(function(){
            var $this = $(this);
            $this.lead = $this.find('.product_lead');
            $this.hot = $this.find('.annotation_box');

            $this.hot.hover(function(){
			   if ( $this.lead.is(":animated") === false ) {
				   $this.lead.slideDown();
			   }
            },function(){
                $this.lead.fadeOut();
            })
        });
/*
        $('.pager a').each(function(idx,el){
            $(el).bind('click', function(e){
                e.stopPropagation();
                e.preventDefault();
                deeb.loadPage(this.href);
            })
        });
*/
    }

};

function formatPrice(num, decpoint, sep)
{
  // check for missing parameters and use defaults if so
  if (arguments.length == 2) {
    sep = ",";
  }
  if (arguments.length == 1) {
    sep = ".";
    decpoint = "m";
  }
  // need a string for operations
  num = num.toString();
  // separate the whole number and the fraction if possible
  a = num.split(decpoint);
  x = a[0]; // decimal
  y = a[1]; // fraction
  z = "";


  if (typeof(x) != "undefined") {
    // reverse the digits. regexp works from left to right.
    for (i=x.length-1;i>=0;i--)
      z += x.charAt(i);
    // add seperators. but undo the trailing one, if there
    z = z.replace(/(\d{3})/g, "$1" + sep);
    if (z.slice(-sep.length) == sep)
      z = z.slice(0, -sep.length);
    x = "";
    // reverse again to get back the number
    for (i=z.length-1;i>=0;i--)
      x += z.charAt(i);
    // add the fraction back in, if it was there
    if (typeof(y) != "undefined" && y.length > 0)
      x += decpoint + y;
  }
  return x; 
}

function mediaImages(el, n)
{
    var current = 0;
    var numbers = [];

	var speed = 4000;
    var next = 1;
    var transitionSpeed = 1000;

    function cycleImages()
	{
        $(numbers[current]).removeClass("active");
        $(numbers[next]).addClass("active");

		$(el[current]).fadeOut(transitionSpeed);
        $(el[next]).fadeIn(transitionSpeed, function() {
            current = current + 1;
            if ( current > el.length - 1 ) current = 0;
            next = next + 1;
            if ( next > el.length - 1 ) next = 0;
        });
    }
        
    var interval = setInterval(cycleImages, speed);

    for (var i=0; i<el.length; i++)
    {
        var a = $('<a rel="'+i+'">'+(i+1)+'</a>');
        a.rel = i;

        if (i == 0) $(a).addClass('active');
        if (i !== 0) $(el[i]).hide();

        a.mouseover(function(){

			clearInterval(interval);

            $this = $(this);

            for (var j=0; j<numbers.length; j++)
            {
                $(numbers[j]).removeClass('active');
            }

            $this.addClass("active");
            var index = parseInt($this.attr("rel"));

            if ( index != current ) {
                $(el[current]).stop().animate({ opacity: 0 }, function() {
                    $(this).hide();
                });
                $(el[index]).stop().css({ display: "block", opacity: 0 }).animate({ opacity: 1 });
            }
            current = index;
        });

        numbers.push(a);
        n.append(a);
    }

}

$(document).ready(function() {
    deeb.setWrapper();
    deeb.parsePagerLinks();
	mediaImages($('#media-images li'), $('#numbers'))
    $("a.zoom").fancybox();
});

