(function($){
	var IE6 =/MSIE 6\.[^\;]+\;/.test(navigator.userAgent);
	var maxw =0;
	
	function isset (v){
		//_Z.err.mark('isset','started');
		return(typeof v !='undefined');
	}
	
	function defStr(s,inserts){
		var temp = s;
		for(var i  in inserts){
			var regx = new RegExp("{"+i+"}","gi");
			temp = temp.replace(regx,inserts[i]);
		}
		return temp;
	}
	
	var ShoppingInfo = {
		flowerbeds:[],
		cartiges:[],
		shipping: {
			loc: "kogu maailm",
			time:shopConfig.shippings[0].name,
			price:shopConfig.shippings[0].price
		}
	}
	
	var Shopping = {
		init: function (){
				var d = "";
				$.ajax({ url: 'templates/shopitem.html', cache: false, async: false, success: function(data) {d= data; }});
				this.shopitem = d;
				
				var dd = "";
				$.ajax({ url: 'templates/bigshopitem.html', cache: false, async: false, success: function(data) {dd= data; }});
				this.bigShopitem = dd;
				
				var ddd = "";
				$.ajax({ url: 'templates/bigshopcartige.html', cache: false, async: false, success: function(data) {ddd= data; }});
				this.bigShopCartige = ddd;
				
				this.renderBuyableStuff();
				
				for(var i in shopConfig.shippings){
					$("#shipPeriod").append('<option value="'+shopConfig.shippings[i].name+'">'+shopConfig.shippings[i].name+'</option>');
					$("#ShipPeriodTxt").val($("#shipPeriod").val());
				}
		},
		
		shopitem:  '',
		bigShopitem:  '',
		bigShopCartige: '',
			
		addFlowerbed: function(item,e){
			ShoppingInfo.flowerbeds.push({item:item});
			
			var box = $(e).parent().parent().parent();
			var l = box.offset().left;
			var t = box.offset().top;
			var lend = $("#ShopFbeds").offset().left + 100;
			var tend = $("#ShopFbeds").offset().top;
			
			var newanim = box.clone().css({"position":"absolute","left":l+"px","top":t+"px"}).insertAfter(box);
			var me = this;
			$(newanim).animate({"top": tend+"px", "left":lend+"px"}, "slow",function(){
				me.render();
				$(this).remove();
			});
		},
		
		removeFlowerbed: function(item){
			for( var i in ShoppingInfo.flowerbeds){
				if(ShoppingInfo.flowerbeds[i].item == item){
					ShoppingInfo.flowerbeds.splice(i, 1);
					break;
				}
			}
			this.render();
		},
		
		addCartige: function(item, type, e){
			
			ShoppingInfo.cartiges.push({
				item:item,
				type: type
			});
			
			var box = $(e).parent().parent().parent();
			var l = box.offset().left;
			var t = box.offset().top;
			var lend = $("#ShopCartiges").offset().left + 100;
			var tend = $("#ShopCartiges").offset().top;
			var newanim = box.clone().css({"position":"absolute","left":l+"px","top":t+"px"}).insertAfter(box);
			var me = this;
			$(newanim).animate({"top": tend+"px", "left":lend+"px"}, "slow",function(){
				me.render();
				$(this).remove();
			});
		},
		
		removeCartige: function(item,type){
			for( var i in ShoppingInfo.cartiges){
				if(ShoppingInfo.cartiges[i].item == item  && ShoppingInfo.cartiges[i].type == type){
					ShoppingInfo.cartiges.splice(i, 1);
					break;
				}
			}
			this.render();
		},
		
		clearAll: function(){
			ShoppingInfo.flowerbeds=[];
			ShoppingInfo.cartiges=[];
			ShoppingInfo.shipping= {
					loc: "the World",
					time:shopConfig.shippings[0].name,
					price:shopConfig.shippings[0].price
				};
			this.render();
		},
		changeShipping: function(loc,time,price,e){
			ShoppingInfo.shipping.loc = loc;
			ShoppingInfo.shipping.time = time;
			ShoppingInfo.shipping.price = parseInt(price);
			
			if(isset(e)){
				var box = $(e);
				var l = box.offset().left;
				var t = box.offset().top;
				var lend = $("#ShopShipping").offset().left+50;
				var tend = $("#ShopShipping").offset().top;
				var newanim = box.clone().css({"position":"absolute","left":l+"px","top":t+"px"}).insertAfter(box);
				var me = this;
				$(newanim).animate({"top": tend+"px", "left":lend+"px"}, "slow",function(){
					me.render();
					$(this).remove();
				});
			} else {
				this.render();
			}
			
		},
		
		infoPopup: function (i,type){
			if(type == "cartige"){
				popUp.infoPopup(shopConfig.cartiges[i].infoBgImage,  shopConfig.cartiges[i].popup);
			} else if (type == "flowerbed"){
				popUp.infoPopup(shopConfig.flowerbeds[i].infoBgImage,  shopConfig.flowerbeds[i].popup);
			}
			
		},
		
		render: function(){
			$(".shopGroup").css("height","auto"); 
			$("#ShopFbeds").html("");
			 $("#ShopCartiges").html("");
			 $("#ShopShipping").html("");
			 
			var productPrice = 0;
			 
			for( var i in ShoppingInfo.flowerbeds){
				productPrice += shopConfig.flowerbeds[ShoppingInfo.flowerbeds[i].item].price;
				var f = defStr(this.shopitem,{
					'image': shopConfig.flowerbeds[ShoppingInfo.flowerbeds[i].item].smallimage,
					'item':ShoppingInfo.flowerbeds[i].item,
					'price':shopConfig.flowerbeds[ShoppingInfo.flowerbeds[i].item].price+shopConfig.currency,
					'plus': (i==ShoppingInfo.flowerbeds[ShoppingInfo.flowerbeds.lenght-1])?'+':'',
					'click': "CaG.Shopping.removeFlowerbed('"+ShoppingInfo.flowerbeds[i].item+"');"
				});
				 $("#ShopFbeds").append(f);
			}
			 $("#ShopFbeds").append("&nbsp;");
			 
			for( var i in ShoppingInfo.cartiges){
				productPrice += shopConfig.cartiges[ShoppingInfo.cartiges[i].item].price
				var c = defStr(this.shopitem,{
					'image': shopConfig.cartiges[ShoppingInfo.cartiges[i].item].smallimage,
					'item':ShoppingInfo.cartiges[i].item,
					'price':shopConfig.cartiges[ShoppingInfo.cartiges[i].item].price+shopConfig.currency,
					'plus': '+',
					'click': "CaG.Shopping.removeCartige('"+ShoppingInfo.cartiges[i].item+"','"+ShoppingInfo.cartiges[i].type+"');"
				});
				$("#ShopCartiges").append(c);
			}
			$("#ShopCartiges").append("&nbsp;");
			
			if (ShoppingInfo.shipping.loc != ""){
				var tmph = $(defStr(this.shopitem,{
					'plus': "+",
					'price': ShoppingInfo.shipping.price+shopConfig.currency,
					'click': "CaG.Shopping.changeShipping('','',0);"
				}));
				tmph.find('.inner').html('<br/>'+ShoppingInfo.shipping.time+'<br/><span class="gray">transport<br/>riiki</span><br/>'+ShoppingInfo.shipping.loc);
				$("#ShopShipping").append(tmph); 
				
			}
			$("#ShopShipping").append("&nbsp;");
			
			var shippingPrice = (ShoppingInfo.shipping.loc!="")?ShoppingInfo.shipping.price:0;
			var sumPrice = shippingPrice+productPrice;
			
			$("#ProductSum").html(productPrice+" "+shopConfig.currency);
			$("#ShippingSum").html((ShoppingInfo.shipping.loc!="")?shippingPrice +" "+shopConfig.currency:"");
			$("#VatSum").html(Math.round(sumPrice*0.2*100)/100+" "+shopConfig.currency);
			$("#Sum").html(sumPrice+" "+shopConfig.currency);
			var shh = 1;
			$(".shopGroup").each(function(){
				if($(this).height() > shh){ shh = $(this).height(); }
			});
			
			$(".shopGroup").height(shh);
			
		},
		
		renderBuyableStuff: function(){
			$('#SFBeds').html('');
			var cartigeLinks = "";
			for(var i in shopConfig.flowerbeds){
			
				if(shopConfig.flowerbeds[i].price < 0 ){
					var f = $(defStr(this.bigShopitem,{
						'item': i
					}));
					f.addClass("inactive").find(".shopButton, .userImage").remove();
				} else {
					var f = $(defStr(this.bigShopitem,{
						'image': shopConfig.flowerbeds[i].image,
						'item':i,
						'price':shopConfig.flowerbeds[i].price+shopConfig.currency
					}));
					cartigeLinks += '<span class="smalltxt10">'+i+'</span> <a href="javascript:void(0);"  class="shopButton" onclick="CaG.Shopping.addCartige(\'{item}\',\''+i+'\',this);">{price}</a>';
				}
				$('#SFBeds').append(f);
			}
			$('#SFCartiges').html('');
			for(var i in shopConfig.cartiges){
				var c = defStr(this.bigShopCartige,{
					'image': shopConfig.cartiges[i].image,
					'item':i,
					'pricelinks': defStr(cartigeLinks, { 
						item:i, 
						price: shopConfig.cartiges[i].price+shopConfig.currency
					})
				});
				$('#SFCartiges').append(c);
			}
			this.render();
		}
	}
	
	function changeShippingValue(e){
		for(var i in shopConfig.shippings){
			if(shopConfig.shippings[i].name == $("#shipPeriod").val()){
				$('#ShipVal').val(shopConfig.shippings[i].price);
				$('#shipValBtn').html(shopConfig.shippings[i].price +shopConfig.currency);
			}
		}
	}
	
	function changeShippingPeriod(e){
		for(var i in shopConfig.shippings){
			if(shopConfig.shippings[i].name == $("#shipPeriod").val()){
				$('#ShipVal').val(shopConfig.shippings[i].price);
				$('#shipValBtn').html(shopConfig.shippings[i].price +shopConfig.currency);
			}
		}
	}
	
	function getSelTxt(el){
		return $(el).find('option[value="'+$(el).val()+'"]').html();
	}
	
	function setMergedSelect(el){
		function setInp(e) { $(e).parent().find("input").val(getSelTxt($(e))); }
		if(isset(el)){
			$(el).find('.mergedSelect select').each(function(){
				setInp(this);
				$(this).change(function(){setInp(this);});
			});
		} else {
			$('.mergedSelect select').each(function(){
				setInp(this);
				$(this).change(function(){setInp(this);});
			});
		}
	}
	
	function setMenuHovers(){
		$("#MainMenu li, #LangMenu li").hover(
			  function () {
				$(this).addClass("active");
			  },
			  function () {
				$(this).removeClass("active");
			  }
			);
	}
	
	function changeTab(link,id){
		$(link).parent().parent().find(".active").removeClass("active");
		$(link).addClass("active");
		$(".tabBox.active").fadeOut("fast",function(){
			$(this).removeClass("active");
			$("#"+id).addClass("active").fadeIn("fast");
		});
	}
	
	function changeComment(link,id){
		$(link).parent().find(".active").removeClass("active");
		$(link).addClass("active");
		$(".commentBox.active").removeClass("active").fadeOut("fast",function(){
			 $(this).hide();
			$("#"+id).addClass("active").fadeIn("fast");
		});
	}
	
	function setToViewportCenter(e){
		var eh = e.height();
		var ew = e.width();
		if(ew==0)
		    ew=600;
		var Ww = $(window).width();
		var Wh = $(window).height();
		var St = $(window).scrollTop();
		var Sl = $(window).scrollLeft();
		var topLoc = St + ((Wh/2)-(eh/2));
		var leftLoc = Sl + ((Ww/2)-(ew/2));
		toploc = (topLoc >= St)?topLoc:St;
		leftloc = (leftLoc >= Sl)?leftLoc:Sl;
		e.css({top: topLoc+'px', left: leftLoc+'px'});
	}
	
	var popUp = {
		wrapHtml: '',
		
		
		
		showOverlay: function(){
				if(IE6){ $("select").hide(); }
				$("#Overlay").remove();
				$(document.body).prepend("<div id='Overlay'></div>");   
				if(maxw > 0 && $("#Wrapper").width() < maxw+60){ $("#Overlay").css("width", maxw+60); } else { $("#Overlay").css("width", "100%");  }
				$("#Overlay").css("height",$(document).height()).click(function(){
					popUp.removePopup();
				});
		},
		
		removePopup: function (){
			$("#Overlay, #popUp").remove();
			if(IE6){ $("select").show(); }
		},
		
		show: function(pg){
			this.showOverlay();
			var d = "";
			$.ajax({ url: pg, cache: false, async: false, success: function(data) {d= data; }});
			var pop = $(d);
			$(document.body).prepend(pop);
			setToViewportCenter(pop);
			setMergedSelect(pop);
			this.showOverlay();
		},
		
		showHtml: function(d){
			this.showOverlay();
			var pop = $(defStr(this.wrapHtml,{'content':d}));
			$(document.body).prepend(pop);
			setToViewportCenter(pop);
		},
		
		Activate: function(){
			this.removePopup();
			this.show("activationSuccess.html");
		},
		
		infoPopup: function(bg,file){
			this.showOverlay();
			var d = "";
			$.ajax({ url: 'templates/popups/'+file, cache: false, async: false, success: function(data) {d= data; }});
			var pop = $(defStr(this.wrapHtml,{'content':d}));
			
			var img = $('<img src="'+bg+'" alt="" title="" />').css({
				"position": "absolute",
				"z-index":"140",
				"margin-top":"18px"
			});
			pop.prepend(img);
			
			$(document.body).prepend(pop);
			setToViewportCenter(pop);
		}
	}
	
	var payPal = {
		send: function (){
			if(ShoppingInfo.shipping.loc==""){
				alert("Enter a shipping location!");
			} else if (ShoppingInfo.flowerbeds.length>0 || ShoppingInfo.cartiges.length >0){
				popUp.showHtml('<div class="textCenter"><br/><img src="images/loading.gif" alt="" title="" /><br/>Please Wait a Second!</div>');
			
				$('#paypalForm').remove();
				var postArray = {
						"business": payPalOptions.user,
						"currency_code": payPalOptions.currency,
						"cmd": "_cart",
						"upload": 1,
						"return": ShoppingInfo.returnAddr
				};
				var j = 1;
				
				for(var i in ShoppingInfo.flowerbeds){
					postArray["item_name_"+j] = "Flowerbed: "+ ShoppingInfo.flowerbeds[i].item;
					postArray["amount_"+j] = shopConfig.flowerbeds[ShoppingInfo.flowerbeds[i].item].price;
					postArray["quantity_"+j] = 1;
					j++;
				}
				
				for(var i in ShoppingInfo.cartiges){
					postArray["item_name_"+j] = "Cartige: "+ShoppingInfo.cartiges[i].item;
					postArray["amount_"+j] = shopConfig.cartiges[ShoppingInfo.cartiges[i].item].price;
					postArray["on0_"+j] = "color";
					postArray["os0_"+j] = ShoppingInfo.cartiges[i].type;
					j++;
				}
				
				postArray["item_name_"+j] = ShoppingInfo.shipping.time +" shipping to "+ShoppingInfo.shipping.loc;
				postArray["amount_"+j] = ShoppingInfo.shipping.price;
				
				var fHtml = '<form action="'+payPalOptions.href+'" id="paypalForm" method="POST">';
				for(var i in postArray){
					fHtml += '<input type="hidden" name="'+i+'" value="'+postArray[i]+'"/>';
				}
				fHtml += '</form>';
				$(document.body).prepend(fHtml);
				$('#paypalForm').get(0).submit();
			} else {
				alert("Choose some item to buy!");
			}
		}
		
		
	}
	
	var popupGallery = {
		thumb_w: 100,
		thumb_h: 100,
		
		getTrueSize: function (img){
			//var e = $('<img src="'+$(img).attr("src")+'" alt="" title="" />');
			var e = $(img).clone();
			e.css({
				"visibility":"hidden",
				"width":"auto",
				"height":"auto"
			});
			$(document.body).prepend(e);
			var s = {
				width: e.width(),
				height: e.height()
			}
			e.remove();
			return s;
		},
		
		set: function (e){
			var me = this;
			$(e).each(function(){
				$(this).find("a").each(function(){
					
					
					$(this).click(function(ev){
						var bigpic = $(this).attr("href");
						ev.preventDefault();
						$(this).parent().find("img[cloneImage]").stop().remove();
						popUp.showHtml('<div style="text-align:center;"><img class="cimage" src="'+bigpic+'" alt="" title="" /></div>');
						$("#popUp .cimage").load(function(){
							setToViewportCenter($("#popUp"));
						});
					});
					
					$(this).css({
						"width": me.thumb_w+"px",
						"height": me.thumb_h+"px",
						"overflow": "hidden",
						"display": "block",
						"float":"left"
					})
					var img = $(this).find("img:not([cloneImage])").eq(0);
					var s = me.getTrueSize(img);
					if(s.width > s.height){
						img.css("height",me.thumb_h+"px");
						img.css("width",s.width*(me.thumb_h/s.height)+"px");
						img.css("margin-left",-1*Math.round(((s.width*(me.thumb_h/s.height))-me.thumb_w)/2)+"px");
					} else {
						img.css("width",me.thumb_w+"px");
						img.css("height",s.height*(me.thumb_w/s.width)+"px");
						img.css("margin-top",-1*Math.round(((s.height*(me.thumb_w/s.width))-me.thumb_h)/2)+"px");
					}
					
					$(this).mouseenter(function(){
						$(this).parent().find("img[cloneImage]").stop().remove();
						var i = $(this).find("img:not([cloneImage])").eq(0);
						var is = me.getTrueSize(i);
						var oldw = i.width();
						var oldh = i.height();
						var ni = i.clone().prependTo(this);
						
						ni.css({ 
							"position":"absolute", 
							"left": $(this).offset().left+"px",
							"top": $(this).offset().top+"px",
							"border": "5px solid #FFFFFF"
						}).attr({
							"cloneImage":"cloneImage"
						}).mouseleave(function(){
							$(this).stop().animate({
								"width": oldw+"px",
								"height": oldh+"px",
								"left": "+="+((is.width-oldw)/2)+"px",
								"top": "+="+((is.height-oldh)/2)+"px"
							},"normal", function(){
								$(this).remove();
							});
						}).animate({
							"width": is.width+"px",
							"height": is.height+"px",
							"left": "-="+((is.width-oldw)/2)+"px",
							"top": "-="+((is.height-oldh)/2)+"px"
						},"slow");
						
					});
					
					
				});
			});
		}
	}
	
	
	/* define globally accessible functions here */
	window.CaG = {
		changeTab:changeTab,
		changeComment:changeComment,
		ShoppingInfo: ShoppingInfo,
		Shopping:Shopping,
		popUp: popUp,
		payPal:payPal,
		changeShippingValue: changeShippingValue,
		changeShippingPeriod: changeShippingPeriod
	}
	
	
	$(document).ready(function(){
		setMergedSelect();
		setMenuHovers();
		//Shopping.init();
		//popUp.init();
		if(IE6){$(document).pngFix(); }
		$(".bigbox .innerWrap").each(function(){
			if($(this).width() > maxw){ maxw = $(this).width();}
		});
		if($("#Wrapper").width() < maxw+60){         
					$(".bigbox, #Header").css({"width": maxw+60+"px"});
				} else {  
					$(".bigbox, #Header").css({"width": "auto"});
				}
		
		$(window).resize(function(){
				$(".bigbox .innerWrap").each(function(){
					if($(this).width() > maxw){ maxw = $(this).width();}
				});
				if($("#Wrapper").width() < maxw+60){         
					$(".bigbox, #Header").css({"width": maxw+60+"px"});
				} else {  
					$(".bigbox, #Header").css({"width": "auto"});
				}
		}); 
	});
	
	$(window).load(function(){
			popupGallery.set($(".popupGallery"));
	});
	
})(jQuery);
