$(document).ready(function(){
	Insta.animate();
	Insta.topProductOffer();
	Insta.listToSelect();
	Insta.initLightbox();
	Insta.selectToFormSender();
	$("span.shield").shield();
	Insta.productComparison();
	Insta.highlightCurrentLink();
	Insta.externalLinks();
	Insta.ideaLinks();
	Insta.swinger();
	Insta.checkForms();
	Insta.massCheckForms();
	Insta.attendCart();

	Insta.checkLinks();
	Insta.languageEditInit();
	Insta.fixIe6Flicker();
});


(function($){
	//IE detektálás javítása.
	$.browser.msie = /*@cc_on !@*/false;

	//Termékek összehasonlítása
	Insta.productComparison = function(){
		//Az aktuálisan kiválasztott kezdő elem, script elemben átadva a html forrásban
		if (!Insta.comparedItem){ return; }

		var comparison = {
			"reset" : function(){
				//A megjelenített termékek nullázása, a termékek nullázása, a megjenített táblázat alaphelyzetben.
				comparison.products = {
					"length": 0
				};
				$("select#productID").html("");
				$("div#compareResult").fadeOut(function(){
					comparison.table = $(this).html([
						'<table><thead>',
							'<tr><th>&nbsp;</th></tr>',
						'</thead><tbody>',
							'<tr><th>Név</th></tr>',
							'<tr><th>Ár</th></tr>',
						'</tbody></table>'].join("")
					);

					comparison.tableHead = $("thead tr", comparison.table);
					comparison.talbeBody = $("tbody tr", comparison.table);

					$("tbody tr:odd", this).addClass("odd");
					$("tbody tr:even", this).addClass("even");
				});
			},
			"addProduct" : function(id){
				//Termékadatok hozzáadása a termékek listához.
				++comparison.products.length;

				return comparison.products[id] = {
					"id" : id,
					"index" : comparison.products.length - 1,
					"images" : [
						'/images/30/30'+$.sprint(id, 8)+'_0.jpg',
						'/images/30/30'+$.sprint(id, 8)+'_1.jpg',
						'/images/30/30'+$.sprint(id, 8)+'_2.jpg',
						'/images/30/30'+$.sprint(id, 8)+'_3.jpg',
					]
				};
			},
			//Táblázat sorainak fejléce
			"rows" : ["Név", "Ár", "Osztály", "Szélesség", "Magasság", "Hossz", "Súly"],
			"start" : Insta.comparedItem,
			"getRow": function(th){
				var
					row = false;
				$("tbody th", comparison.table).each(function(i){
					if ($(this).html() == th){
						row = i;
						return false;
					}
				});
				return row;
			}
		};
		comparison.reset();

		//Ha a termékkategória listát váltanak, akkor a terméklista változik, és az eddig látott elemek törlődnek.
		$("select#categoryID").change(function(){
			comparison.reset();
			var
				id = $(this).val(),
				cid = "productComparisonProductList" + id,
				data = $.Storage(cid);

			//Gyorsítótár használata
			if (data){
				Insta.comparisonSetProductList(data);
				return;
			}

			//Terméklista lekérése
			$.getJSON("/ajax.php", {"action": "productComparisonProductList", "categoryID": id}, function(data){
				$.Storage(cid, data, 3600*12);
				Insta.comparisonSetProductList(data);
			});
		});

		Insta.comparisonSetProductList = function(data){
			$("select#productID").html(data.options);
			$("div#compareProducts").fadeIn("slow");

			//Ha volt alapértelmezett választás
			if (comparison.start.productID){
				$("select#productID").val(comparison.start.productID).change().val(0);
				comparison.start.productID = 0;
			}
		};

		$("select#productID").change(function(){
			var
				id = $(this).val(),
				cid = "productComparisonProduct" + id,
				data = $.Storage(cid);

			if (comparison.products[id]){
				//Elemhez ugrás
				comparison.table.scroll("right", $("td", comparison.tableHead)[comparison.products[id].index]);
			}
			if (id==0 || comparison.products[id]){ return; }

			var product = comparison.addProduct(id);
			$("option:selected", this).html("&bull; "+$("option:selected", this).html());

			//Gyorsítótár használata
			if (data){
				Insta.comparisonSetProduct(data, product);
				return;
			}
			//Részletes adatok lekérése
			$.getJSON("/ajax.php", {"action": "productComparisonProduct", "productID": id}, function(data, status){
				if (!data){ return; }
				$.Storage(cid, data, 3600);
				Insta.comparisonSetProduct(data, product);
			});
		});

		Insta.comparisonSetProduct = function(data, product){
			var i = 0;

			//IE rejtélyes hiba miatti ellenőrzés
			if (!comparison.tableHead){
				delete comparison.products[id];
				return;
			}

			//Kép beolvasása
			comparison.tableHead.append('<td></td>').find('td:last').hide()
				.append($(
					'<a href="'+product.images[1]+'" alt="" title="'+data.title+'" rel="lightbox">'+
					'<img src="'+product.images[0]+'" />' +
					'</a>'
				).lightbox())
				.fadeIn("slow");

			//Oszlopok száma, táblázat kiegészítése, ha szükséges.
			var cols = $("thead td,thead th", comparison.table).length;
			for (var th in data.rows){
				var row = comparison.getRow(th);
				if (row === false){
					//Nem létező mező, sor létrehozása
					row = $("tbody", comparison.table).append("<tr></tr>").find("tr:last");
					for (var jj=cols; jj>1; --jj)
						row.append(jj==cols? "<th>"+th+"</th>" : "<td></td>");
				}
			}

			//Videó link hozzáadaása
			/*
			if (data.hasVideo){
				comparison.tableHead.find('td:last').append('<br><a href="'+data.href+'#video"><img src="/main_gui/images/vid.gif"></a>');
			}
			*/

			//Végigmegyünk a táblázat sorain, és hozzáadjuk az adatokat.
			$("tbody th", comparison.table).each(function(){
				var
					th = $(this).html(),
					row = comparison.getRow(th),
					td = data.rows[th] || "";

				if (th=="Név" && data.href){
					td = '<a href="'+data.href+'">'+td+'</a>';
				}

				$("tbody tr", comparison.table).eq(row).append("<td>"+td+"</td>").find("td:last a.ideaPopup");
			});

			$("tbody tr:odd", comparison.table).addClass("odd");
			$("tbody tr:even", comparison.table).addClass("even");
			comparison.table.scroll("right").fadeIn("slow");
		};

		//Elemek megjelenítése, js nélkül nem látható.
		//Feltétlenül így kell, mert valami késleltetés kell.
		$("div#compare").fadeIn(500, function(){
			//Kezdő érték a kategóriáknál
			if (comparison.start.categoryID){
				$("select#categoryID").val(comparison.start.categoryID);
			}
			//Kiválasztás alapján változtatás.
			$("select#categoryID").change();
		});
	};

	Insta.fixIe6Flicker = function () {
		if ($.browser.msie && $.browser.version.substr(0,1)<7) {
			try { document.execCommand("BackgroundImageCache", false, true);
			} catch(err) {}
		}
	}

	Insta.page = location.href.split(/[\?#]/)[0];

	Insta.topProductOffer = function(){
		var d = $("#TopProductOfferWrapper");
		if (!d.size()){ return; }
		$.addJS($.getBaseUrl()+"jq.countdown.js");

		//Lejárt az ajánló box
		var expiredSale = function(){
			d.slideUp(250);
			location.reload();
			//startSale();
		};
		//Ajánló box indítása
		var startSale = function(){
			$.getJSON("/ajax.php", {"action":"getTopProductOffer"}, function(data){
				if (data.html && data.endTime){
					var endTime = new Date(data.endTime*1000);

					$("div:first", d).html(data.html);
					$(".saleRemainingTime span", d).countdown(
						{until: endTime,
						compact: true,
						format: 'hms',
						onExpiry: expiredSale}
					);
					d.slideDown(250);
				}
			});
		};
		startSale();
	};
	Insta.highlightCurrentLink = function(){
		$("a").click(function(){
			if ($(this).hasClass("popup")) return;
			$("a.currentLink").removeClass("currentLink");
			$(this).addClass("currentLink clickedLink");
		});
		$("a").each(function(){
			if (this.href == Insta.page){
				$(this).addClass("currentLink");
			}
		});
	};
	//A kosárhoz tartozó javascript kódok.
	Insta.attendCart = function(){
		//A szállítási módok és fizetés összeg kijelzése a kiválasztott szállítási mód alapján.
		$("select[name='paymentMethod']").change(function(){
			Insta.displayPaymentAndShipping($(this).val());	
		});
	};
	Insta.displayPaymentAndShipping = function (param) {
		var
		val = param,
		fee = Insta.shippingFee["_"+val]? Insta.shippingFee["_"+val] : 0,
		cart = (1*Insta.cartTotal) + fee,
		text = (Insta.sumPriceTotalText).replace(/\\1/, fee.toLocaleString() + Insta.currency).replace(/\\2/, cart.toLocaleString() + Insta.currency);

		$("#sumPriceTotal").html(text)[1*val? "slideDown" : "slideUp"](750);
	};
	Insta.massCheckForms = function(){
		$("input.massChecker").click(function(){
			return Insta.massSelectCheck();
		});
	};
	Insta.massSelectCheck = function(){
		var allSelectsOK = true;
		$("select.massChecked").each(function(){
			if ($(this).val() == ""){
				allSelectsOK = false;
				$(this).css({"border" : "1px solid red"});
			}
		});
		if (!allSelectsOK){
			alert("válasszon mindenhol!");
		}
		return allSelectsOK;
	};
})(jQuery);

(function($){
	var choose = {
		hu: "válasszon!",
		en: "choose",
		de: "whälen Sie",
        fr: "cliquez!",
        ru: "Нажмите кнопку"
	}
	Insta.host = location.hostname;

	//ul>a átalakítása select listává
	Insta.listToSelect = function(){
		$("ul.listToSelect").each(function(){
			var o = null, ul = $(this);

			$("li a", ul).each(function(){
				var a = $(this);
				o += '<option value="'+a.attr("href") + '"' + (a.attr("rel")? ' selected="selected"' : '') + '>'+a.html()+'</option>';
			});

			o = '<option value="">'+((choose[Insta.lang.used]) ? choose[Insta.lang.used] : choose['en'])+'</option>'+o;
			$("<select></select>").append($(o)).insertAfter(ul.hide(0)).change(function(){
				if ($(this).val()){ document.location = $(this).val(); }
			});
		});
	};

	//Select elem változtatásakor form küldése
	Insta.selectToFormSender = function(){
		//Select form küldése művelet.
		$("select.formSender").change(function(){
			if ($(this).val()!=""){
				$(this).parents("form").submit();
			}
		}).siblings("input:submit").hide();
	};

	//Lightbox beállítások érvényesítése
	Insta.initLightbox = function(attr){
		if (!$.fn.lightbox){ return; }
		$.addCSS($.getBaseUrl()+'css/lightbox.css');
		Insta.setLightbox();
	};
	Insta.setLightbox = function(element){
		var
			index = 0,
			groups = {},
			attr = attr || "rel",
			set = {
				overlayOpacity: 0.37,
				fileLoadingImage : $.getBaseUrl()+'images/loading.gif',
				fileBottomNavCloseImage : $.getBaseUrl()+ ((Insta.lang.used == 'hu') ? 'images/closelabel.gif' : 'images/closenolabel.gif'),
				strings : Insta.getLightboxStrings()
			};

		$.each($("["+attr+"*=lightbox]", element), function(i, obj){
			var name = /(lightbox[^\s]*)/.exec($(obj).attr(attr))[0];
			if (name == "lightbox"){ name = "_"+(index++); }
			if (typeof groups[name] == 'undefined'){ groups[name] = []; }

			groups[name].push(obj);
		});
		$.each(groups, function(i, group){
			$(group).lightbox(set);
		});
	};

	Insta.getLightboxStrings = function (){
		var
			lightboxStrings = {
				hu: {
					help: ' \u2190 / P - előző kép\u00a0\u00a0\u00a0\u00a0\u2192 / N - következő kép\u00a0\u00a0\u00a0\u00a0ESC / X - ablak bezárása',
					prevLinkTitle: 'Előző kép',
					nextLinkTitle: 'Következő kép',
					prevLinkText:  '&laquo;&nbsp;előző',
					nextLinkText:  'következő&nbsp;&raquo;',
					closeTitle: 'Ablak&nbsp;bezárása',
					image: 'Képek:&nbsp;',
					of: '/'
				},
				en: {
					help: ' \u2190 / P - previous image\u00a0\u00a0\u00a0\u00a0\u2192 / N - next image\u00a0\u00a0\u00a0\u00a0ESC / X - close image gallery',
					prevLinkTitle: 'previous image',
					nextLinkTitle: 'next image',
					prevLinkText:  '&laquo; Previous',
					nextLinkText:  'Next &raquo;',
					closeTitle: 'close image gallery',
					image: 'Image ',
					of: ' of '
				},
				de: {
					help: ' \u2190 / P - vorheriges Bild\u00a0\u00a0\u00a0\u00a0\u2192 / N - nächstes Bild\u00a0\u00a0\u00a0\u00a0ESC / X - Die Bild-Galerie schliessen',
					prevLinkTitle: 'vorheriges Bild',
					nextLinkTitle: 'nächstes Bild',
					prevLinkText:  '&laquo; zurück',
					nextLinkText:  'nach vorn &raquo;',
					closeTitle: 'Die Bild-Galerie schliessen',
					image: 'Bild ',
					of: ' / '
				},
                fr: {
                    help: ' \u2190 / P - previous image\u00a0\u00a0\u00a0\u00a0\u2192 / N - next image\u00a0\u00a0\u00a0\u00a0ESC / X - close image gallery',
                    prevLinkTitle: 'previous image',
                    nextLinkTitle: 'next image',
                    prevLinkText:  '&laquo; Previous',
                    nextLinkText:  'Next &raquo;',
                    closeTitle: 'close image gallery',
                    image: 'Image ',
                    of: ' of '
                },
                ru: {
                    help: ' \u2190 / P - previous image\u00a0\u00a0\u00a0\u00a0\u2192 / N - next image\u00a0\u00a0\u00a0\u00a0ESC / X - close image gallery',
                    prevLinkTitle: 'previous image',
                    nextLinkTitle: 'next image',
                    prevLinkText:  '&laquo; Previous',
                    nextLinkText:  'Next &raquo;',
                    closeTitle: 'close image gallery',
                    image: 'Image ',
                    of: ' of '
                }
			};
			if (lightboxStrings[Insta.lang.used]){
				return lightboxStrings[Insta.lang.used];
			}
			else {
				return lightboxStrings.en;
			}
	};

	//Az üzenet beküldésénél a form elrejtése/megjelenítése, vagy bármi más, ami swinges
	Insta.swinger = function(){
		var
			p = $("div.accordion"),
			f = $(".swinging", p).eq(0).show(),
			s = $(".swinging", p).eq(1).hide();

		if (p.hasClass("accordionOff")){
			f.hide();
			s.show();
			$(".swinger", s).hide();
			return;
		}
		$(".swinger", f).click(function(){
			s.show(750, function(){ f.slideUp(500); });
		});
		$(".swinger", s).click(function(){
			s.hide(750, function(){ f.fadeIn(500); });
		});
	};

	//Animáció beállítás hibaüzenet boxhoz.
	Insta.animate = function(){
		$("div.animated").hide(0).slideDown(700);
	}

	//Linkek vagy form küldés elérhetetlen, ha nincs bejelentkezve.
	Insta.checkLinks = function(){
		if (!Insta.user.logged){
			$("input.onlyForLoggedIn").click(function(){
				alert(Insta.error.needLoginToShop || "Bejelentkezés szükséges!");
				return false;
			});
		}
	};

	Insta.languageEditInit = function(){
		var l = $("span.langEdit");
		if (!l.length) return;

		var f = $([
			'<div id="toThickbox">',
				'<form id="langEdit" method="post" action="/setup/word" accept-charset="utf-8" style="height:97%">',
				'<textarea name="word" id="word" rows="7" cols="12" style="width:100%;height:90%;"></textarea>',
				'<input type="hidden" name="wid" id="wid" value="-1">',
			'</form></div>'].join("")
		).hide().appendTo('body');

		l.click(function(){
			var t = $(this);

			$('#word', f).val( t.attr('title') );
			$('#wid', f).val( t.attr('rel') );

			f.dialog(
				{
					'buttons': {
						"Mégsem": function() { $(this).dialog("close"); },
						"Módosítás": function() { $("form#langEdit").submit(); }
					},
					'title' : 'A kifejezés módosítása',
					'autoOpen' : false,
					'width': 570
				}
			);
			f.dialog('open');
			return false;
		}).html('<img src="/js/images/edit.gif" alt="" style="border:none;cursor:pointer" />').show();
	};

	//Ha be van kapcsolva a külső link hivatkozás, akkor a külső linkek megnyitása külön ablakban.
	Insta.externalLinks = function(){
		if (!Insta.setExternal){ return; }
		$("a").each(function(){
			if ($(this).attr("host").indexOf(Insta.host) == -1){
				$(this).attr("target", "_blank");
			}
		});
	};

	//A fogalomtár linkek beállítása
	Insta.ideaLinks = function(){
		$("a.popup[href*=fogalom]").click(function(){
			var href = $(this).attr("href").split("/");
			$.getJSON('/ajax.php', {"action":"fogalom", "data":href[href.length-1]}, function(data){
				$("<div/>").html("<div class='idea'>"+(data.img || "") + data.descript+"</div>").dialog({
					title: "Fogalomtár: " + data.title,
					width: 600,
					buttons: {
						"Ok": function(){
							$(this).dialog("close");
						}
					}
				});
			});
			return false;
		});
		$("a.popup[href*=info]").click(function(){
			var href = $(this).attr("href").split("/");
			$.getJSON('/ajax.php', {"action":"info", "data":href[href.length-1]}, function(data){
				$("<div/>").html("<div class='idea'>"+(data.img || "") + data.descript+"</div>").dialog({
					title: data.title,
					width: 600,
					buttons: {
						"Ok": function(){
							$(this).dialog("close");
						}
					}
				});
			});
			return false;
		});
	}
})(jQuery);

(function($){
	//Formellenőrzés beállítása minden formon.
	Insta.checkForms = function(){
		$("input.copy-button").click(function(){
			var e = {"address-name":"billing-name", "address-city":"billing-city", "address-zip":"billing-zip", "address-street":"billing-street"};
			$.each(e, function(e, i){
				$("input#"+i).val($("input#"+e).val());
			});
		});
		$("input.once-delete").click(function(){
			if (this.onceDeleted){ return; }
			this.onceDeleted = true;
			$(this).val("");
		});
		$("form").submit(function(){
			Insta.Form.checker(this);
			return !Insta.Form.message;
		});
		$("form#payment").submit(function(){ return checkPayment(this); });
	};

	Insta.Form = {
		checker : function(f){
			Insta.Form.reset(f);
			$("input,textarea,select", f).each(function(i, e){
				$.each($(e).attr("class").split(/ +/), function(j, c){
					Insta.Form.check[c] && Insta.Form.setError(e, Insta.Form.check[c](e));
					if (Insta.Form.message){ return false; }
				});
				if (Insta.Form.message){ return false; }
			});

			Insta.Form.message && alert(Insta.Form.message);
		},
		//Visszatérési értékek: hibaüzenet - ha nem megfelelő, null - ha jó érték.
		check : {
			required : function(e){
				if ($(e).val().trim() === ""){ return Insta.error.required; }
			},
			validEmail : function(e){
				if (!/^[a-z0-9._-~]+@[a-z0-9.-]+\.[a-z]{2,4}$/i.test($(e).val())){ return Insta.error.notValid; }
			}
		},
		setError : function(e, m){
			if (!m){ return; }
			var l = $("label[for="+$(e).select().attr("id")+"]", $(e).parents("form")), h;

			if (l.length){
				l.get(0).preCSS = {"color": l.css("color")};
				l.css({"color": "red"});
				h = l.html().trim("\\s:\\*\\.").replace(/<\/?[^>]+(>|$)/g, "");
			} else {
				h = "beviteli";
			}
			if (Insta.lang.used == 'hu') {
				Insta.Form.message = m.replace(/%s/, h.article().firstUpper(), 1);
			} else {
				Insta.Form.message = m.replace(/%s/, h.firstUpper(), 1);
			}
		},
		reset : function(f){
			Insta.Form.message = null;
			Insta.Form.form = f;

			$("label", f).each(function(){
				this.preCSS && $(this).css(this.preCSS);
			});
		}
	};
})(jQuery);

//Kell a kulcs, hosszúság, szélesség
GoogleMap = {
	Init : function(){
		var key = $("div.google-map").length && Insta.GoogleMapKey;
		if (key)
			$.addJS('http'+'://maps.google.com/maps?file=api&v=2&hl=hu&oe=utf-8'+'&async=2&callback=GoogleMap.Load&key='+key);
	},
	Load : function(){
		$(window).unload(GUnload);
		$("div.google-map").each(function(){
			var c = $(this).attr("rel").split(",");
			GoogleMap.ShowMap(this, c[0], c[1]);
		});
	},
	CreateMarker : function (point, html){
		var marker = new GMarker(point);
		if (html) GEvent.addListener(marker, "click", function(){ marker.openInfoWindowHtml(html); });
		return marker;
	},
	ShowMap : function(div, lat, lng, mgn){
		if (!GBrowserIsCompatible()) return;

		var map = new GMap2(div);
		map.removeMapType(G_HYBRID_MAP);
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(lat, lng), mgn || 16);

		var point = new GLatLng(lat, lng);
		var marker = GoogleMap.CreateMarker(point);
		map.addOverlay(marker);
	}
};
$(document).ready(GoogleMap.Init);
//Az adott karakterek vagy szóközök elhagyása: str.trim(), str.trim(":")
String.prototype.trim = function(s){
	s = s || "\\s";
	return this.toString().replace(new RegExp("^["+s+"]+|["+s+"]+$", "g"), "");
};
String.prototype.article = function(){
	var
		s = this.toString(),
		a = s.match(/^Az? /i)? "" : (s.match(/^[aeiouáéíóöőúüű5]/i)? "Az " : "A ");

	return a+s;
};
String.prototype.firstUpper = function(){
	return this.toLocaleLowerCase().replace(/^./, this.charAt(0).toLocaleUpperCase());
}
