function updateHeaderBasketInfo (tekst) {
	$('#basketHeaderInfo').html(tekst);
}

function loadAnimation (jqObject, start) {
	start = (typeof start == "undefined") ? true : start;
	if (start) {
		jqObject.css("cursor", "wait").stop(true).fadeTo(200, 0.5);
	} else {
		jqObject.stop(true).fadeTo(500, 1).css("cursor", "auto");
	}
}

function addAjaxToUri (uri) {
	uri = uri.split('?');
	if (uri.length == 1) {
		return uri[0]+"?ajax";
	} else {
		var params = uri[1].split("&");
		var segment = false;
		for (var i in params) {
			segment = params[i].split("=");
			if (segment[0] == "ajax") {
				return uri[0]+"?"+uri[1];
			}
		}
		return uri[0]+"?"+uri[1]+"&ajax";
	}
}

function loadPage (uri, container) {
	loadAnimation(container);

	uri = addAjaxToUri(uri);

	if (typeof ajax[uri] == 'object') {
		ajax[uri]['xhr'].abort();
		ajax[uri] = null;
	}
	ajax[uri] = new Array;
	ajax[uri]['parentId'] = container.attr('id');
	ajax[uri]['xhr'] = $.ajax({
		type: "GET",
		cache: false,
		dataType: "html",
		timeout: 15000,
		url: uri,
		success: function (html) {
			$('#'+ajax[uri]['parentId']).html(html);
		},
		error: function (msg) {
			alert("Došlo je do problema kod spajanja na server.");
		},
		complete: function () {
			loadAnimation($('#'+ajax[uri]['parentId']), false);
			scroll(0, 0);
		}
	});
}

function openItemGroup ($group) {
	if ($group.data('visible')) {
		$group
			.data('visible', false)
			.removeClass('opened')
			.hide();
	} else {
		$group
			.data('visible', true)
			.addClass('opened')
			.show();
	}
}

function carouselImgAnimation (img, direction, callback) {
	switch (direction) {
	case 'up':
		var animationSettings = {};

		if (img.height() > img.width()) {
			animationSettings = {
				height: 190,
				'max-width': 150,
				top: 5
			};
		} else {
			animationSettings = {
				width: 190,
				'max-height': 190,
				top: 5
			};
		}

		img
			.clearQueue()
			.animate(animationSettings, 150, 'linear', function () { if (typeof callback == 'function') { callback(); } });
		break;

	default:
		img
			.clearQueue()
			.animate({
				height: 150,
				'max-width': 150,
				top: 30
			}, 150, 'linear', function () { if (typeof callback == 'function') { callback(); } });
	}
}

function updateCarouselImages () {
	$bookflipImages = $('#slider img[rel=bookflip]');

	$bookflipImages.bind('carouselDim', function (e, fadeTo) {
		var $o = $(this);

		if (!$o.data('curentlyFocused')) {
			$o.animate({opacity: fadeTo}, { duration: 500, queue: false });
		} else {
			$o.animate({opacity: 1}, { duration: 300, queue: false });
		}
	}).each(function (i) {
		var $o = $(this),
			$tooltip = $o.parent().find('div.tooltip');

		$o.qtip({
			id: $o.attr('id'),
			content: {
				text: $tooltip.find('.tooltipContent:first').html(),
				title: {
					text: $tooltip.find('.tooltipTitle:first').html(),
					button: true
				}
			},
			show: {
				target: FALSE,
				event: 'showTooltip',
				effect: TRUE,
				delay: 90,
				solo: FALSE,
				ready: FALSE
			},
			hide: {
				target: FALSE,
				event: 'hideTooltip',
				effect: TRUE,
				delay: 0,
				fixed: FALSE,
				inactive: FALSE
			},
			position: {
				my: 'bottom center',
				at: 'top center',
				adjust: {
					screen: true
				}
			},
			style: {
				classes: 'ui-tooltip-alfa ui-tooltip-shadow'
			}

		});
	});
}

$(document).ready(function () {
	var $main = $('#main'),
		$itemsGroupSelect = $('#itemsGroupSelect'),
		$kategorija_right = $('#kategorija_right'),
		$content_right = $('#content_right'),
		$basketHeaderInfo = $('#basketHeaderInfo'),
		basketHeaderInfo = $('#basketHeaderInfo');

	$main.delegate('.pagination.ajax a', 'click', function () {
		var $clicked = $(this);

		loadPage($clicked.attr('href'), $clicked.parents('div.ajaxPagination:first'));

		return false;
	});

	/*
	$itemsGroupSelect.find('ul')
		.hide()
		.data('visible', false);

	$itemsGroupSelect.delegate('a.ajax', 'click', function () {
		var $clicked,
			$parent,
			$opens;

		$clicked = $(this);
		$parent = $clicked.parent();
		$opens = $parent.children('ul:first');

		if ($opens.length != 0) {
			openItemGroup($opens);
		}

		$itemsGroupSelect.find('a')
			.removeClass('active');
		$clicked.addClass('active');

		if ($opens.length != 0) {
			if ($opens.data('visible')) {
				$clicked.addClass('opened');
			} else {
				$clicked.removeClass('opened active');
			}
		} else {
			loadPage($clicked.attr('href'), $kategorija_right);
		}

		return false;
	});
	//*/

	$content_right.delegate('a.lnk_dodaj', 'click', function () {
		var $clicked = $(this),
			uri;
		$clicked.html('dodajem...');

		uri = addAjaxToUri($clicked.attr('href'));

		if (typeof ajax[uri] == 'object') {
			ajax[uri]['xhr'].abort();
			ajax[uri] = null;
		}
		ajax[uri] = new Array;
		ajax[uri]['xhr'] = $.ajax({
			type: "GET",
			cache: false,
			dataType: "json",
			timeout: 15000,
			url: uri,
			success: function (response) {
				switch (response['status']) {
				case 'success':
					$clicked.html('<span class="green">dodano ✓</span>');
					$basketHeaderInfo.html(response['basket']['headerMsg']);
					break;

				case 'item_not_found':
					alert('Artikal više nije dostupan te nije dodan u košaricu.')
					break;
				}
			},
			error: function (msg) {
				alert("Došlo je do problema kod spajanja na server.");
			}
		});

		return false;
	});

	$main.delegate('.itemAddButton', 'click', function () {
		var $clicked = $(this),
			$add = $clicked.find('.content > .add'),
			$content = $clicked.find('.content');

		if ($add.size()) {
			$add.remove();
			$content.html('<button class="quantityButton negative">&nbsp;</button><input type="text" class="articleQuantity" name="articleQuantity" value="1" /><button class="quantityButton positive">&nbsp;</button><button class="commit">&nbsp;</button>');
		}

		return false;
	});

	$main.delegate('.quantityButton', 'click', function () {
		var $button = $(this),
			$quantity = $button.parent().find('.articleQuantity:first'),
			val = parseInt($quantity.val());

		if (isNaN(val)) {
			alert('Količina mora biti broj');
			return false;
		}

		if ($button.hasClass('negative')) {
			if (val > 1) {
				$quantity.val(val - 1);
			}
		} else {
			$quantity.val(val + 1);
		}

		return false;
	});

	$main.delegate('.commit', 'click', function () {
		var $commit = $(this),
			$content = $commit.parent(),
			quantity = parseInt($commit.parent().find('.articleQuantity:first').val()),
			uri = false;

		if (isNaN(quantity)) {
			alert('Količina mora biti broj');
			return false;
		}

		$content.html('dodajem...');
		uri = addAjaxToUri($content.parents('.itemAddButton').find('.href').html()+'/'+quantity);

		//*
		if (typeof ajax[uri] == 'object') {
			ajax[uri]['xhr'].abort();
			ajax[uri] = null;
		}
		ajax[uri] = new Array;
		ajax[uri]['xhr'] = $.ajax({
			type: "GET",
			cache: false,
			dataType: "json",
			timeout: 15000,
			url: uri,
			success: function (response) {
				switch (response['status']) {
				case 'success':
					$content.html('<span class="green add">dodano ✓</span>');
					$basketHeaderInfo.html(response['basket']['headerMsg']);
					break;

				case 'item_not_found':
					alert('Artikal više nije dostupan te nije dodan u košaricu.')
					break;
				}
			},
			error: function (msg) {
				alert("Došlo je do problema kod spajanja na server.");
			}
		});
		//*/

		return false;
	});

	$main.delegate("a[rel='addToBasket']", 'click', function () {
		var $clicked = $(this),
			uri;
		$clicked.find('span').remove();
		$clicked.html('<span><img src="/media/img/icons/loading.gif" alt="Dodajem..." /></span>'+$clicked.html());

		uri = addAjaxToUri($clicked.attr('href'));

		if (typeof ajax[uri] == 'object') {
			ajax[uri]['xhr'].abort();
			ajax[uri] = null;
		}
		ajax[uri] = new Array;
		ajax[uri]['xhr'] = $.ajax({
			type: "GET",
			cache: false,
			dataType: "json",
			timeout: 15000,
			url: uri,
			success: function (response) {
				$clicked.find('span').remove();
				switch (response['status']) {
				case 'success':
					$clicked.html('<span class="checkmark">✓</span>'+$clicked.html());
					$basketHeaderInfo.html(response['basket']['headerMsg']);
					break;

				case 'item_not_found':
					alert('Artikal više nije dostupan te nije dodan u košaricu.')
					break;
				}
			},
			error: function (msg) {
				alert("Došlo je do problema kod spajanja na server.");
			}
		});
		//*/

		return false;
	});

});

