$(document).ready(function() {

	if (!jQuery.browser.mozilla) {
		$("#img-tabs li").corner('bottom', 'corner-box-');
	}

	$('.rating-select').rating();
	$('.rating-display').displayRating();

	$('#download-button')
	.bind('click', function() {
		$.popup(contextPiqUrl($(this).parent().attr('href')) + '&popup=1');
		return false;
	})
	.hover(function() {
		this.src = '/shop/subshop/metafiles/4801/btn-download2-over.gif';
	}, function() {
		this.src = '/shop/subshop/metafiles/4801/btn-download2.gif';
	});

	$('#lightbox-button')
	.bind('click', function() {
		$.popup(contextPiqUrl($(this).parent().attr('href')) + '&popup=1');
		return false;
	}).
	hover(function() {
		this.src = '/shop/subshop/metafiles/4801/btn-lightbox2-over.gif';
	}, function() {
		this.src = '/shop/subshop/metafiles/4801/btn-lightbox2.gif';
	});

	$('#img-tabs').show()

	$('#img-tabs li')
	.bind('click', function() {
		var $fragment = $($('a', this)[0].hash);
		var show = $fragment.is(":hidden");
		var self = this;
		$(self).css('cursor', 'pointer');
		var func = function() {
			if (!show) return;
			$(self).addClass('fotos-bg').addClass('img-tab-active');

			$('#img-overlay')
			.css('left', '0')
			.bind('click', function() { $(self).trigger('click'); });

			$('#img-background').animate({height: 260}, 'fast', function() {
				$fragment.show();
			});
		};

		var $visible = $("#img-fragments div.img-fragment:visible");

		if ($visible.size() > 0) {
			$visible.each(function() {
				$(this).hide();
				$('#img-overlay')
				.css('left', '-9999px')
				.unbind('click');

				$('#img-background').animate({height: 1}, 'fast', function() {
					$(this).hide();
					$('#img-tabs li').removeClass('fotos-bg').removeClass('img-tab-active');
					func();
				});
			});
		} else {
			func();
		}

		return false;
	});
});

var contextVars = function() {
	this.$curr  = null;
	this.scroll = 230;
	this.tpl    = '';

	this.piqid       = null;
	this.index       = null;
	this.start       = null;
	this.limit       = null;
	this.count       = null;
	this.context     = null;
	this.contextdata = null;

	this.piqBoxWidth  = null;
	this.piqBoxHeight = null;

	this.prev = {};
	this.next = {};
}

var contextInit = function(piqid, start, limit, count, context, contextdata, json) {
	contextVars.$curr       = $('#context .contextbox');
	contextVars.scroll      = contextVars.$curr.width();
	contextVars.piqid       = toInt(piqid);
	contextVars.index       = 0;
	contextVars.start       = toInt(start);
	contextVars.limit       = toInt(limit);
	contextVars.count       = toInt(count);
	contextVars.context     = context;
	contextVars.contextdata = contextdata;

	this.piqBoxWidth  = toInt($('#img-box div').width());
	this.piqBoxHeight = toInt($('#img-box div').height());

	var $piq = $('#img-box div img');
	if ($piq.length) {
	    contextCenterPiq($piq[0]);
	    contextLoadPrevNext();
	}

	if (contextVars.$curr.size() == 0) {
	    return;
	}

	$('#context').css({
		'top':  toInt($('#context').css('top')) + 'px',
		'left': toInt($('#context').css('left')) + 'px'
	});

	$('#contextbuttons')
		.html('<img src="/images/btn-prev.gif" width="76" height="19" id="contextprevbutton" alt="Zur&uuml;ck" title="Zur&uuml;ck" class="disabled" /><img src="/images/btn-next.gif" width="76" height="19" id="contextnextbutton" alt="Weiter" title="Weiter" class="disabled" />');

	var $tpl = contextVars.$curr.clone();
	var item = $tpl.find('.contextitem')[0];
	$tpl.html('');
	$(item).find('img').removeClass('fotos-border').attr('src', '/shop/subshop/metafiles/4801/spacer.gif');

	for (var i = 0; i < contextVars.limit; i++) {
		$tpl.append($(item).clone());
	}

	contextVars.$tpl = $tpl;

	eval("data = " + json);
	contextFill(data);

	var size = contextVars.$curr.find('img').size();

	while (size++ < contextVars.limit) {
		contextVars.$curr.append(contextCreatePlaceholder($(item).clone()));
	}

	contextButtons();
	$('#contextbuttons').show();
};

var contextLoadPrevNext = function() {
	contextVars.prev = {};
	$('#prev')
	.unbind('click')
	.css('display', 'none')
	.css('cursor', 'default');

	contextVars.next = {};
	$('#next')
	.unbind('click')
	.css('display', 'none')
	.css('cursor', 'default');

	var cb = function(data)
	{
		if (data.prev != undefined) {
			contextVars.prev = data.prev;
			var i = new Image(); i.src = data.prev.image.detail.url;

			$('#prev')
			.bind('click', function() {
				contextSetPrevPiq();
				return false;
			})
			.css('display', 'block')
			.css('cursor', 'pointer');
		}

		if (data.next != undefined) {
			contextVars.next = data.next;
			var i = new Image(); i.src = data.next.image.detail.url;

			$('#next')
			.bind('click', function() {
				contextSetNextPiq();
				return false;
			})
			.css('display', 'block')
			.css('cursor', 'pointer');
		}
	};

	$.getIfModified(
		'/?module=frontend&action=contextprevnext&piqid=' + contextVars.piqid + '&context=' + contextVars.context + '&contextdata=' + contextVars.contextdata,
		null,
		cb,
		'json'
	);
};

var contextSetPrevPiq = function()
{
	contextSetPiq(contextVars.prev, --contextVars.index);
};

var contextSetNextPiq = function()
{
	contextSetPiq(contextVars.next, ++contextVars.index);
};

var contextSetPiq = function(data, index)
{
	var $piq = $('#img-box img');

	if (!$piq.length) {
	    return;
	}

	contextVars.piqid = data.piqid;
	contextVars.index = index;

	$('.piqurl').each(function() {
	    if (this.href != undefined) {
	        this.href = contextPiqUrl(this.href);
	    }
	    if (this.action != undefined) {
	        this.action = contextPiqUrl(this.action);
	    }
	});

	contextLoadPrevNext();

	if (jQuery.trim(data.title) == '') {
	    data.title = '...';
	}

	var e = $piq.clone()[0];
	e.alt    = data.title;
	e.title  = data.title;
	e.src    = data.image.detail.url;
	e.width  = toInt(data.image.detail.width);
	e.height = toInt(data.image.detail.height);

	contextCenterPiq(e);

	$('#img-title').fadeOut('fast', function() {
		$(this)
		.attr('title', data.title)
		.html(truncate(data.title, 50));
		$(this).fadeIn('fast');
	});

	$('#img-box div').fadeOut('fast', function() {
		$(this).find('img').remove();
		$(this).append(e);

		$(this).fadeIn('fast');
	});

	if (contextVars.index < 0) {
		$('#contextprevbutton').trigger('click');
		contextVars.index = contextVars.limit - 1;
	}

	if (contextVars.index == contextVars.limit) {
		$('#contextnextbutton').trigger('click');
		contextVars.index = 0;
	}

	var i = 0;

	$('.contextitem img', contextVars.$curr).each(function() {
		$(this)[i++ == contextVars.index ? 'addClass' : 'removeClass']('fotos-border');
	});
};

var contextCenterPiq = function(e)
{
	$(e).parent().css('textAlign', 'left');

	if (toInt(e.width) < this.piqBoxWidth) {
		$(e).css('marginLeft', toInt(this.piqBoxWidth - e.width) / 2 + 'px');
	} else {
		$(e).css('marginLeft', 0);
	}

	if (toInt(e.height) < this.piqBoxHeight) {
		$(e).css('marginTop', toInt(this.piqBoxHeight - e.height) / 2 + 'px');
	} else {
		$(e).css('marginTop', 0);
	}
};

var contextButtons = function() {
	$('#contextprevbutton').unbind('click');
	if (contextVars.start > 0) {
		$('#contextprevbutton').hover(function() {
			this.src = '/images/btn-prev-over.gif';
		}, function() {
			this.src = '/images/btn-prev.gif';
		}).bind("click", function() {
			$(this).unbind('click');

			contextVars.start = contextVars.start - contextVars.limit;

			$('#context').css('width', toInt($('#context').width()) + contextVars.scroll + 20 + 'px');
			$('#context').css('left', toInt($('#context').css('left')) - contextVars.scroll + 'px');
			var $new = contextCreateBox();
			contextVars.$curr.before($new);

			var pos = toInt($('#context').css('left')) + contextVars.scroll;

			$('#context')
			.animate(
				{'left': pos},
				'fast',
				function() {
					contextSetup($new);
				}
			);
		})
		.removeClass('disabled')
		.css('cursor', 'pointer');
	} else {
		$('#contextprevbutton')
		.unbind('mouseover')
		.unbind('mouseout')
		.addClass('disabled')
		.css('cursor', 'default');
	}

	$('#contextnextbutton').unbind('click');
	if ((contextVars.start + contextVars.limit) < contextVars.count) {

		$('#contextnextbutton').hover(function() {
			this.src = '/images/btn-next-over.gif';
		}, function() {
			this.src = '/images/btn-next.gif';
		}).bind("click", function() {
			$(this).unbind('click');

			contextVars.start = contextVars.start + contextVars.limit;

			$('#context').css('width',  toInt($('#context').width()) + contextVars.scroll + 20 + 'px');
			var $new = contextCreateBox();
			contextVars.$curr.after($new);

			var pos = toInt($('#context').css('left')) - contextVars.scroll;

			$('#context')
			.animate(
				{'left': pos},
				'fast',
				function() {
					contextSetup($new);
				}
			);
		})
		.removeClass('disabled')
		.css('cursor', 'pointer');
	} else {
		$('#contextnextbutton')
		.unbind('mouseover')
		.unbind('mouseout')
		.addClass('disabled')
		.css('cursor', 'default');
	}
};

var contextSetup = function($new) {
	var el = contextVars.$curr[0];
	contextVars.$curr = $new;

	$(el).pause(1000).each(function() {
		this.parentNode.removeChild(this);

		$('#context').css({
			'width': contextVars.scroll + 'px',
			'left': 0,
			'top': 0
		});
	});

	$('#contextinfo .start').html(contextVars.start+1);
	$('#contextinfo .end').html(contextVars.start+contextVars.limit > contextVars.count ? contextVars.count : contextVars.start+contextVars.limit);

	$.getIfModified(
		'/?module=frontend&action=context&start=' + contextVars.start + '&context=' + contextVars.context + '&contextdata=' + contextVars.contextdata,
		null,
		contextFill,
		'json'
	);

	contextButtons();
};

var contextFill = function(data) {
	var i = 0;
	contextVars.index = 0;

	$(contextVars.$curr)
	.find('.contextitem')
	.each(function() {
		if (data[i] == undefined) {
		    contextCreatePlaceholder(this);
		    return;
		}

		var current = data[i];
		var index = i;

		$(this)
		.find('a')
		.css('cursor', 'pointer')
		.unbind('click')
		.bind('click', function() {
			var $piq = $('#img-box img');

	        // No piq, enable direct link
	        if (!$piq.length) {
	            return true;
	        }

			if (current != null && current.piqid != contextVars.piqid) {
				$('#img-tabs li.img-tab-active').trigger('click');
				contextSetPiq(current, index);
				$('img', this).addClass('fotos-border');
			}
			return false;
		})
		.each(function() {
			this.href = contextPiqUrl(this.href);

			$(this)
			.find('img')
			.each(function() {
				this.alt    = current.title;
				this.title  = current.title;
				this.src    = current.image.mini.url;
				this.width  = current.image.mini.width;
				this.height = current.image.mini.height;

				if (current.piqid == contextVars.piqid) {
					contextVars.index = i;
					$(this).addClass('fotos-border');
				}
			});
		});

		contextZoom(this);
		i++;
	});
}

var contextCreateBox = function()
{
	var box = contextVars.$tpl.clone()[0];

	var start = contextVars.start;

	$(box).find('.contextitem').each(function() {
		if (start++ < contextVars.count) {
			$(this)
			.find('a')
			.css('cursor', 'default')
			.bind('click', function(e) { e.preventDefault(); e.stopPropagation(); return false;})
			.find('img')
			.attr('src', '/images/loading-img.gif')
			.removeClass('fotos-border');
		} else {
			contextCreatePlaceholder(this);
		}
	});

	return $(box);
};

var contextCreatePlaceholder = function(el)
{
	$(el)
	.find('a')
	.attr('href', 'javascript:;')
	.css('cursor', 'default')
	.unbind('mouseover')
	.unbind('mouseout')
	.unbind('click')
	.find('img')
	.addClass('contextimgplaceholder')
	.attr('alt', '')
	.attr('title', '')
	.attr('src', '/images/spacer.gif')
	.removeClass('fotos-border');

	return el;
};

var contextZoom = function(el)
{
	$(el)
	.find('a')
	.hover(function(e) {
		$(this).css({
			'position': 'relative',
			'display': 'block'
		});

		var $img = $('img', this).clone();

		$img.css({
			'visibility': 'hidden',
			'position': 'absolute',
			'top': 0,
			'left': 0,
			'width': '64px',
			'height': '64px'
		});

		$(this).prepend($img);

		$img.css('visibility', 'visible');

		$img.animate({
			'top': -3,
			'left': -3,
			'width': 70,
			'height': 70
		}, 75, 'original');

		//e.preventDefault();
		//e.stopPropagation();

	}, function(e) {
		this.removeChild(this.firstChild);
	});
};

var contextPiqUrl = function(href)
{
    href = href.replace(/piqid(=|%3D)([0-9]+)/g, 'piqid=' + contextVars.piqid);
	href = href.replace(/([0-9]+)\.html/g, contextVars.piqid + '.html');

	if (href.indexOf(contextVars.piqid + '.html') == -1 && href.indexOf('piqid=' + contextVars.piqid) == -1 && href.indexOf('piqid%3D' + contextVars.piqid) == -1) {
	    //href += encodeURIComponent('?piqid=' + contextVars.piqid);
	}

	return href;
};
