/**
 * Gallery box Slim version
 * @author DaVee
 * @version 0.94
 * @license under WTFPL 2.0
 */
function GalleryBoxSlim (element, mark) {
	if (mark === undefined) mark = 'slim';
	if ($('#gallery-' + mark).length != 0) return false;
	// localization
	var clientLang = (navigator.userLanguage || navigator.language).substr(0,2).toLowerCase();
	this.text = {
		'en' : {prev: 'previous', next: 'next', close: 'close', loading: 'loading ...', error: 'Image not found.'},
		'cs' : {prev: 'p\u0159edchozí', next: 'dal\u0161í', close: 'zav\u0159ít', loading: 'na\u010dítá se ...', error: 'Obrázek nelze na\u010díst.'}
	};
	// variables
	this.ident = '#gallery-' + mark;
	this.locale = this.text[clientLang] !== undefined ? this.text[clientLang] : this.text['en'];
	this.imgShow = 0;
	this.imgCount = 0;
	this.srcs = Array();
	this.titles = Array();

	// load links from element
	this.load = function (element) {
		var box = this;
		$(element).each( function () {
			var oldCount = box.imgCount;
			var images = $(this).find("a");
			if (images.length != 0) {		
				$(images).each( function () {
					box.loadImage(this);
				});
			}
			else box.loadImage(element);
			box.appendAction(oldCount);
		});
	}
	
	// add image
	this.loadImage = function (link) {
		var box = this;
		if ($(link).attr('href') !== undefined) {
			var str = $(link).attr("href");
			box.srcs.push(str);
			box.titles.push($(link).children("img").attr("title"));
			var x = this.imgCount + 0;
			$(link).click( function () { return box.show(x); });
			box.imgCount++;
		}
	}

	// show galllery
	this.show = function (num) {
		var box = this;
		var imgNew = new Image();
		box.imgShow = num;
		if ($(box.ident).css("display") == "none") {
			if ($.browser.msie && $.browser.version < 8) $(box.ident +" .gallery-box").css("margin-top", 0);
			$(box.ident +" .gallery-box").css("top", $(window).scrollTop());
			$(box.ident).fadeIn(500);
			box.center();
		}

		$(box.ident +" .gallery-box p").text(box.locale["loading"]);
		$(box.ident +" .gallery-box-image img").fadeOut(200, function () {
			$(box.ident +" .gallery-box-image img").remove();
			$(imgNew).load(function () {
				var height = $(imgNew).attr("height");
				var width = $(imgNew).attr("width");
				$(box.ident +" .gallery-box").width(width);
				$(box.ident +" .gallery-box-image").height(height).width(width).append(this);
				box.center();
				$(box.ident +" .gallery-box-image img").fadeIn(200);
				$(box.ident +" .gallery-box p").text(box.titles[box.imgShow]);
				$(box.ident +" .gallery-box-position").text(num+1);
			}).error(function () {
				$(imgNew).stop(true,true);
				$(box.ident +" .gallery-box-image").append(new Image());
				$(box.ident +" .gallery-box p").text(box.locale["error"]);
				$(box.ident +" .gallery-box-position").text(num+1);
			}).attr('src', box.srcs[box.imgShow]);
		});

		if (this.imgShow == 0) $(box.ident +" a.gallery-box-left").hide();
		else $(box.ident +" a.gallery-box-left").show();
		if (this.imgShow == this.imgCount-1) $(box.ident +" a.gallery-box-right").hide();
		else $(box.ident +" a.gallery-box-right").show();
		return false;
	}

	// place into center of screen
	this.center = function () {
		var top = Math.round(($(window).height() - $(box.ident +" .gallery-box").height()) / 2);
		// IE 6 + 7 fix
		if ($.browser.msie && $.browser.version < 8) {
			var oldTop = parseFloat(($(box.ident +" .gallery-box").css("margin-top")).replace('px', ''));
			var baseTop = parseFloat(($(box.ident +" .gallery-box").css("top")).replace('px', ''));
			if ($.browser.version < 7) top = Math.round(top / 2);
			$(box.ident +" .gallery-box").css("top", top > 0 ? (baseTop + top - oldTop)+"px" : (baseTop + 0 - oldTop)+"px");
			$(box.ident +" .gallery-box").css("margin-top", top > 0 ? top+"px" : 0+"px");
			// IE 6 fix
			if ($.browser.version < 7) {
				$(box.ident +" .gallery-box").css('left', Math.round(($(window).width() - $(box.ident +" .gallery-box").width()) / 2) + "px");
				$(box.ident +" .gallery-box-black")
					.height($(window).height() > $(document).height() ? $(window).height() : $(document).height())
					.width($(window).width() > $(document).width() ? $(window).width() : $(document).width());
				if (($(box.ident +" .gallery-box").offset().top + $(box.ident +" .gallery-box").height()) > $(box.ident +" .gallery-box-black").height()) {
					$(box.ident +" .gallery-box-black").height($(box.ident +" .gallery-box").offset().top + $(box.ident +" .gallery-box").height());
				}
				if ($(box.ident +" .gallery-box").width() > $(box.ident +" .gallery-box-black").width()) {
					$(box.ident +" .gallery-box-black").width($(box.ident +" .gallery-box").width());
				}
			}
		}
		else {
			$(box.ident +" .gallery-box").css("margin-top", top > 0 ? top+"px" : 0);
		}
	}

	// listovani
	this.scroll = function (left) {
		if (left) {
			if (this.imgShow > 0) this.show(this.imgShow-1);
		}
		else {
			if (this.imgShow < this.imgCount-1) this.show(this.imgShow+1);
		}
		return false;
	}

	// create link on element to show gallery
	this.createLink = function (element) {
		var box = this;
		var img = $("#"+element+" img").attr('src');
		img = img.substring( img.lastIndexOf('/') + 1 );
		for(var i = 0; i < this.srcs.length; i++) {
			if (this.srcs[i].indexOf(img) > 0) {
				$("#"+element).click( function () {box.show(i);return false;} );
				$("#"+element).css('cursor','pointer');
				break;
			}
		}
	}
	
	this.appendAction = function (old) {
		var box = this;
		if (old != box.imgCount) {
			$(box.ident + " .gallery-box-count").text(box.imgCount);
			if (old <= 1 && box.imgCount > 1) {
				// action association
				$(box.ident +" a.gallery-box-left").click(function() {return box.scroll(true);});
				$(box.ident +" a.gallery-box-right").click(function() {return box.scroll(false);});
				$(document).keydown( function(event) {
					if ($(box.ident + ":visible").length != 0) {
						if (event.keyCode == "37") box.scroll(true);
						else if (event.keyCode == "39") box.scroll(false);
					}
				});
			}
		}
	}

	var box = this;
	// html gallery code insetion
	$("body").append('<div id="gallery-'+mark+'" class="gallery-box-all"><div class="gallery-box-black"></div><div class="gallery-box">'+
		'<div class="gallery-box-image"><img src="" /></div>'+
		'<div class="gallery-box-info"><a class="gallery-box-left" title="'+box.locale["prev"]+'"><span>&lt;</span></a>'+
		'<span class="gallery-box-position">1</span> / <span class="gallery-box-count">'+box.imgCount+'</span>'+
		'<a class="gallery-box-right" title="'+box.locale["next"]+'"><span>&gt;</span></a>'+
		'<a class="gallery-box-close" title="'+box.locale["close"]+'"><span>X</span></a></div>'+
		'<p></p><div class="gallery-box-clear"></div></div></div>');
	$(box.ident +" a.gallery-box-close").click(function() {$(box.ident).fadeOut(500);return false;});
	$(box.ident +" .gallery-box-black").click(function() {$(box.ident).fadeOut(500);});
	this.load(element);
	return true;
}

/**
 * Image changer
 * @author DaVee
 * @version 0.8
 * @license under WTFPL 2.0
 */
function ImageChanger (image) {
	this.timer = 5000;
	this.images = Array();
	this.parent = $(image).parent();
	this.element = image;
	var changer = this;
	
	this.add = function (image) {
		this.images.push(image);
	}
	
	this.change = function (i) {
		if (i >= changer.images.length) i = 0;
		var newImage = new Image();
		$(newImage).load(function () {
			$(changer.element).fadeOut( 1000, function () { $(this).remove(); });
			$(changer.element).after(newImage);
			$(newImage).hide().fadeIn(1000);
			changer.element = newImage;
			setTimeout(function(){changer.change(i+1)}, changer.timer);
		}).error(function () {
			setTimeout(function(){changer.change(i+1)}, changer.timer);
		}).attr("src", changer.images[i]);
	}

	this.run = function () {
		setTimeout(function(){changer.change(1)}, changer.timer);
	}
}

// rozbalovani menu
$(document).ready(function() {
	var submenu = $("#page-menu ul li").children(".submenu-bottom");
	if (submenu.length != 0) {
		$(submenu).hide();
		$(submenu).find("ul").hide();
		$(submenu).each( function () {
			var select = $(this);
			var subs = $(this).find("li").length;
			$(this).parent().hover(
				function() {
					var childs = $(submenu).find("ul");
					if (childs.length != 0) {
						$(childs).each( function () {
							$(select).find("ul").stop(true,true);
						});
					}
					$(select).show();
					$(select).find("ul").slideDown(80 * subs);
				},
				function() {
					$(select).find("ul").slideUp(80 * subs, function () {
						$(select).hide();
					});
				}
			);
		});
	}
});


function ajaxLoad (link, element) {
	var retState = true;
	var urlRequest = $(link).attr('href') + '&ajax=true';
	$.ajax({
		type: "GET",
		dataType: "xml",
		async: false,
		url: urlRequest,
		success: function (xhtml) {
			var title = $(xhtml).find('title').text();
			if (title != "") document.title = title;
			$(element).html($(xhtml).find('xhtml').text());
			retState = false;
		}
	});
	return retState;
}

function partnersChanger (parent) {
	this.start = function (i) {
		if (i >= this.images.length) i = 0;
		var linkOld = changer.images[this.active];
		var link = changer.images[i];
		var newImage = new Image();
		$(newImage).load(function () {
			$(linkOld).fadeOut(400);
			$(link).fadeIn(600, function () {
				setTimeout( function () {changer.active = i;changer.start(i+1);}, 3000);
			});
		}).error(function () {
			setTimeout( function () {changer.active = i;changer.start(i+1);}, 3000);
		}).attr("src", $(link).children("img").attr("src"));
	}

	var changer = this;
	this.active = 0;
	this.images = $(parent).find("a");
	setTimeout( function () {changer.start(1);}, 3000);
}


var ticker = {
	speed: 30,
	side: "left",
	ticketer: "",
	alwayScroll: false,
	emptySpace: 2,
	width: 0,
	widthBox: 0,

	create: function (ticketer) {
		ticker.ticketer = ticketer;
		ticker.width = $(ticker.ticketer).width();
		ticker.widthBox =  $(ticker.ticketer).parent().width();

		if (ticker.alwayScroll || ticker.width > ticker.widthBox) {
			if (ticker.emptySpace > 1) {
				ticker.cloneText();
				ticker.width += ticker.widthBox / ticker.emptySpace;
				if (ticker.widthBox > ticker.width) {
					for (var i = 0; i < ticker.widthBox / ticker.width; i++) ticker.cloneText();
				}
			}

			$(ticker.ticketer).hover(
				function () {$(this).stop(true)},
				function () {
					var residualSpace = ticker.width - ($(this).parent().offset().left - $(this).offset().left);
					ticker.scrollIt(ticker.width,residualSpace * (ticker.speed - 5 ));
				}
			);
			setTimeout(function () {ticker.scrollIt(ticker.width, ticker.width*ticker.speed)}, 2000);
		}
	},
	scrollIt: function (width,duration) {
		$(ticker.ticketer).animate({left: -width}, duration, "linear", function () {
			$(ticker.ticketer).css("left", ticker.emptySpace > 1 ? 4 : ticker.widthBox - 5);
			ticker.scrollIt(ticker.width, ticker.width*ticker.speed);
		});
	},
	cloneText: function () {
		$(ticker.ticketer).append('<span style="margin: 0 0 0 ' + (ticker.widthBox / ticker.emptySpace)
			+ 'px;"> </span>' + $(ticker.ticketer).html());
	}
}


function showIeShadow (parent, element, copy) {
	if ($.browser.msie && $.browser.version < 9) {
		var text = $(parent).find(element).html();
		$(parent).append('<div class="' + copy + '">' + text + '</div>');
	}
}

function tableMonth (element, action) {
	var height = $(element).children("tbody").height() / $(element).children("tbody").children("tr").length;
	$(element).children("tbody").children("tr").children("td").css("height",height+'px');
	$(element).children("tbody").children("tr").each( function () {
		$(this).find(action).height($(this).children("td").height());
	});

	$(element).find("a").each( function () {
		var link = $(this);
		$(this).parent().css("cursor","pointer");
		$(this).parent().click( function () {
			window.location = $(link).attr("href");
		});
	});
}

function tableWeek (element, action, block) {
    $(element).find(action).each ( function () {    
	  var height = 0;
	  var parent = $(this).parent().attr("class");
	  parent = '.' + parent.replace(' ', '.');
	  $(element).find(parent).each( function () {
		height += $(this).height();
	  });
	  if (height != 0) $(parent).find(block).height(height + "px");
    });
}

function showTitleBox (parent,element) {
    $("body").append('<div id="text-box-show"><p></p></div>');
    $(parent).find(element).each ( function () {
	  if ($(this).attr('title') != "") {
		$(this).attr('alt',$(this).attr('title'));
		$(this).attr('title','');
		$(this).mouseenter( function(e) {
		    $("#text-box-show p").html($(this).attr('alt'));
		    $("#text-box-show").show();
	    });
	    $(this).mousemove( function(e) {
		    $("#text-box-show").css({'left': e.pageX+8,'top': e.pageY + 2});
	    });
	    $(this).mouseout( function(e) {
		    $("#text-box-show").unbind();
		    $("#text-box-show").hide();
	    });
	  }
    });
}

function runBasket (basket) {
	$("#shop-recount").hide();
	$(basket).find("input:text").each ( function () {
		$(this).change( function () {$("#shop-recount").click();});
	});
}

function login (form) {
	$(form).find("input").keyup( function(event) {
		if(event.keyCode == 13) $(form).find("button").click();
	});
}

// vyber statu
var PayType = {
	activeState: 0,
	table: "",
	currency: "",
	state: new Array(),

	init: function (table, state, currency) {
		var pay = this;
		this.activeState = state;
		this.currency = currency;
		this.table = table;
		$("select[name='b_state']").change( function () { pay.change($(this).val()); });
		$("input[name='b_paytype']").change( function () { pay.recount(); } );
		$("input[name='b_deliverytype']").change( function () { pay.setDelivery(); } );
		PayType.setDelivery();
	},

	addState: function (id,cost,delivery) {
		this.state[id] = new Array(cost, delivery);
	},
	
	change: function (select) {
		this.activeState = select;
		if (this.state[select][1] !== false) $("#pay_deliver").parent().show();
		else {
			 $("#pay_deliver").parent().hide();
			 $("#pay_deliver").attr('checked', false);
		}
		this.recount();
	},
	
	recount: function () {
		var payType =  $("input[name='b_paytype']:checked").val();
		var deliverType =  $("input[name='b_deliverytype']:checked").val();

		var oldPost = $(this.table + " td.post.price").text().replace(this.currency,'');
		var newPost = deliverType == "post" ? this.state[this.activeState][0] : 0;
		if (payType == "deliver") newPost += this.state[this.activeState][1];
		var newPrice = $(this.table + " td.total.price").text().replace(this.currency,'') - oldPost;

		$(this.table + " td.post.price").text(newPost + " " + this.currency);
		$(this.table + " td.total.price").text((newPrice + newPost) + " " + this.currency);
	},
	
	setDelivery: function () {
		var val = $("input[name='b_deliverytype']:checked").val();
		$("#pay_deliver").removeAttr('disabled');
		$("#pay_cash").removeAttr('disabled');
		if (val == 'post') {
			$("#pay_cash").attr("disabled","disabled");
			if ($("#pay_cash:checked").length != 0) $("#pay_cash").removeAttr("checked");
		}
		else if (val == 'shop') {
			$("#pay_deliver").attr("disabled","disabled");
			if ($("#pay_deliver:checked").length != 0) $("#pay_deliver").removeAttr("checked");
		}
		this.recount();
	}
}
