
$(document).ready(function() {

	var sg = new SortableGrid({
		selector: 'DIV.products .item',
		width: 228,  // item width
		height: 141, // item height
		unit: 'px',
		speed: 1000  // in msecs
	});


	// Create orders
		
	sg.create_order('popularity', function(a, b) {
		return parseInt($('.popularity', a).text()) > parseInt($('.popularity', b).text()) ? 1 : -1;
	});

	sg.create_order('category', function(a, b) {
		return $('.head', a).text() > $('.head', b).text() ? 1 : -1;
	});

	sg.create_order('price', function(a, b) {
		return parseFloat($('.price', a).text()) > parseFloat($('.price', b).text()) ? 1 : -1;
	});

	sg.create_order('random', function(a, b) {
		return Math.round(Math.random() * 2 - 1);
	});

	// Ready to initialize with default order
	var def = $('#controls .selected A');
	sg.init(def.length > 0 ? def.attr('id') : 'price');
	
	
	// Bind control events
	$('#controls .sortname A').click(function(e) {
		e.preventDefault();
		$(this).parents('.sortoption:first').find('.order')
			[sg.reverse ? 'removeClass' : 'addClass']('reverse');
		sg.animate($(this).attr('id'));
    $.cookie('unicef_pehmea_sort', sg.order, { path: '/', expires: 3 });
		$.cookie('unicef_pehmea_reverse', sg.reverse, { path: '/', expires: 3 });
	});

/*
	
$(function() {
   if ($.cookie('unicef_pehmea_sort') != null
     sg.order = ($.cookie('unicef_pehmea_sort');
   if ($.cookie('unicef_pehmea_reverse') != null
  	 sg.reverse = ($.cookie('unicef_pehmea_reverse'));
});

*/
	


$(function() {
				// set up product links to set new cookies on click
                var options = { path: '/', expires: 3 };

                // set cookie with grid parameters, expiration 3 days
                $('.item .content a').click(function() {
                    $.cookie('unicef_pehmea_sort', sg.order, options);
                    $.cookie('unicef_pehmea_reverse', sg.reverse, options);
                    return true;
                });
            });

});



var SortableGrid = function(params) {

	this.width = params.width;
	this.height = params.height;
	this.unit = params.unit;
	this.speed = params.speed;

	this.orders = {};
	this.container = $(params.selector).parent();
	this.items = $(params.selector).get();
	this.cols = Math.floor(this.container.width() / this.width);
	this.count = this.items.length;
	this.reverse = false;
}

SortableGrid.prototype.init = function(order) {
	this.container.height(this.height * Math.ceil(this.count / this.cols) + this.unit);
	this.animate(order, false, true);
}

SortableGrid.prototype.coords = function(item, order, reverse) {
	var index = reverse ? this.count - 1 - this.orders[order][item] : this.orders[order][item];
	var col = index % this.cols;
	var row = Math.floor(index / this.cols);
	return { x: (col * this.width) + this.unit, y: (row * this.height) + this.unit }
}

SortableGrid.prototype.animate = function(order, reverse, no_fx) {
	if (reverse == null)
		reverse = ! this.reverse;
	for (var item in this.orders[order]) {
		var coords = this.coords(item, order, reverse);
		if (no_fx)
			$('#' + item).css('top', coords.y).css('left', coords.x);
		else
			$('#' + item).animate({ top: coords.y, left: coords.x },
				{ duration: parseInt(this.speed) });
	}
	this.order = order;
	this.reverse = reverse;
}

SortableGrid.prototype.create_order = function(name, sort_func) {
	this.items.sort(sort_func);
	var indexed = {};
	for (var i = 0; i < this.items.length; i++)
		indexed[$(this.items[i]).attr('id')] = i;
	this.orders[name] = indexed;
}