var lib = {};
$ = jQuery;

lib.lv = function() {
  return {
      init: function() {
          if($.browser.msie) {
              var h = Math.max(0,$(".maincontent").height() - 500);
              $("#navbg").css({height: h});
              if(parseInt($.browser.version) == 6) {
                  DD_roundies.addRule('.leftround', '20px 0px 20px 0px');
                  DD_roundies.addRule('.toprightround', '0px 20px 0px 0px');
                  DD_roundies.addRule('.rightround', '0px 20px 0px 20px');
                  DD_roundies.addRule('.bottomleftround', '0px 0px 0px 20px');
              } else if(parseInt($.browser.version) >= 7) {
                  DD_roundies.addRule('.leftround', '20px 0px 20px 0px');
                  DD_roundies.addRule('.toprightround', '0px 20px 0px 0px');
                  DD_roundies.addRule('.rightround', '0px 20px 0px 20px');
                  DD_roundies.addRule('.bottomleftround', '0px 0px 0px 20px');
              }
          }
      },
      togglehover: function() {
          alert($(this));
          $(this).toggleClass("navmenuhover");
      },
      setLangCookie: function() {
          var langs = {nl: "nl_BE", en: "en_US"};
          if(/^\/(\w\w)\//.test(window.location.pathname)) {
              var cur = window.location.pathname.match(/^\/(\w\w)\//)[1];
              if(cur) { $.cookie("webhivelang", langs[cur], { expires: 7, path: '/' }); }
          }
      },
  	  ajaxHandler : {},

	  getCurrentStyle : function() { return $("link.cur").attr("title") },

	  setCurrentStyle : function(name) {
		    if(! $("link.alt[title="+name+"]")) { return 0 };
			$("link.alt").each(function() {
				  if($(this).attr("title") == name) {
					  $(this)[0].disabled = false;
					  $(this).addClass("cur");
				  } else {
					  $(this).removeClass("cur");
					  $(this)[0].disabled = true;
				  }
			});
			lib.lv.storePreferedStyle();
	  },

	  attachCssSelectors : function() {
		  $(".cssselector").click(function() {
			  var to = $(this).attr("rel");
			  lib.lv.setCurrentStyle(to);
	      });
	  },

	  storePreferedStyle : function() {
		var curstyle = lib.lv.getCurrentStyle();
		var cookie_name = $("meta[name=version]").attr("content");
		$.cookie(cookie_name,curstyle);
	  },

	  applyPreferedStyle : function() {
		var cookie_name = $("meta[name=version]").attr("content");
		//console.log(cookie_name);
		if($.cookie(cookie_name)) {
			lib.lv.setCurrentStyle($.cookie(cookie_name));
		} else {
			lib.lv.setCurrentStyle($("link.alt:first").attr("title"));
		}
	  },

      applyJIR : function() {
			//JSONify
			var url = "/text.png";
            var src2 = url + "?" +
                  + "fontsize=" + escape( $(this).css("font-size"))
                  + "&text=" + escape( $(this).text() )
                  + "&fontfamily=" + escape( $(this).css("font-family"))
                  + "&color=" + escape( $(this).css("color"))
                  + "&background_color=" + escape( $(this).css("background-color"))
                  + "&marginleft=" + escape( $(this).css("padding-left"))
                  + "&marginright=" + escape( $(this).css("padding-right"))
                  + "&margintop=" + escape( $(this).css("padding-top"))
                  + "&marginbottom=" + escape( $(this).css("padding-bottom"));
	
			var c = Base64_URLSafe.encode("fontsize=" + $(this).css("font-size")
                 						 + "&text=" + $(this).text() 
                 						 + "&fontfamily=" + $(this).css("font-family")
                 						 + "&color=" + $(this).css("color")
                 						 + "&background_color=" + $(this).css("background-color")
                 						 + "&marginleft=" + $(this).css("padding-left")
                 						 + "&marginright=" + $(this).css("padding-right")
                 						 + "&margintop=" + $(this).css("padding-top")
                 						 + "&marginbottom=" + $(this).css("padding-bottom") );

			var src = url + "?c=" + c;

			$(this).wrap('<div style="position: relative"></div>')
					.after($('<img src="'+src+'" />')
							  .css({"position":"absolute",
							  		"left": 0,
									"top": (-1 * ($(this).height() / 2))
									}));

			if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 7 && parseInt(jQuery.browser.version) > 4) {
				$(this).parent().find("img").each(function(i,obj) {
					$(obj).css({
						"width": $(obj).width() + 'px',
						"height": $(obj).height() + 'px',
						"filter":"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+$(obj).attr("src")+"', sizingMethod='scale')"
					}).attr("src","/images/null.gif");
				}); 
			}
            $(this).html("&nbsp;");
      },



      loadBasket : function(el) {
              $.ajax({
                  async: false,
                  type: "GET",
                  url: "/parts/basket.phtml",
				  cache: false,
                  dataType: "html",
                  success: function(data) {
                      $("#minibasket").html(data);
                      if($.cookie("retracted") == 1) {
                          $("#minibasket #downarrow").show();
                          $("#minibasket #uparrow").hide();
                      } else {
                          $("#minibasket #downarrow").hide();
                          $("#minibasket #uparrow").show();
                      }
                  }
              });
              lib.lv.attachBasketShowHandler($("#minibasket"));
              lib.lv.attachBasketDeleteHandler($("#minibasket li table.ttduo"));

              if($.cookie("basketdelat")) {
                  st = parseInt($.cookie("basketdelat") || 0);
                  $.cookie("basketdelat",null,{path: "/"}); //delete cookie
              } else if($("#newest").attr("rel")) {
                  st = parseInt($("#newest").attr("rel") || 0);
              } else {
                  st = 0;
              }
			  $("#minibasket").show();
			  $("#minibasket").find("ul").jcarousel({
                      initCallback: lib.lv.carouselReg,
                      start: st,
                      scroll: 1
                  });

              $("#minibasket").animate({opacity:1},500,function() {
                  //delayed
                  flashid = $("#newest").text();
                  $("#t_"+flashid).animate({backgroundColor: "#eeee00"}, 200,function() {
					  $("#t_"+flashid).animate({backgroundColor: "#ffffff"}, 1000);
					});
              });
      },
        removeFromBasket : function(datahash) {
            $.ajax({
                async: false,
                type: "GET",
                url: "/delete.phtml",
                dataType: "text",
                data: datahash,
                success: function(data) {
                }
            });
            if(lib.lv.basketAt) {
                $.cookie("basketdelat",lib.lv.basketAt(), { path: "/" });
            }
            $.cookie("basketcount", (parseInt($.cookie("basketcount")) - 1 || 0),{ path: "/" });
            lib.lv.showBasketIfNonEmpty();
        },

       carouselReg: function(carousel) {
            lib.lv.basketScrollTo = function(i) { carousel.scroll(i,true); }
            lib.lv.basketAt = function(i) { return carousel.first; }
        },

        basketEmpty : function() {
            var count = (parseInt($.cookie("basketcount")) || 0)
            if(count > 0) { return false }
            else { return true };
        },
        showBasketIfNonEmpty : function() {
            //mainloop
            lib.lv.positionBasket($("#minibasket"));
            if(lib.lv.basketEmpty()) {
                $("#minibasket").hide();
            } else {
                lib.lv.loadBasket($("#minibasket"));
                $("#minibasket").show();
            }
        },
        slideUpBasket : function() {
            $("#minibasket").animate({"bottom": 0}, function() {
                $(this).data("retracted",false);
                $("#minibasket #downarrow").show();
                $("#minibasket #uparrow").hide();
                $.cookie("retracted",1,{ path: '/' });
            });
        },
        slideDownBasket : function() {
            $("#minibasket").animate({"bottom": $("#minibasket").data("moveHeight") }, function() {
                    $(this).data("retracted",true);
                    $("#minibasket #uparrow").show();
                    $("#minibasket #downarrow").hide();
                    $.cookie("retracted",0,{ path: '/' });
            });
        },

	
	attachBasketShowHandler : function(el) {
		$(el).find("div.clicktop").click(function() {
			if($(el).data("retracted")) {
				lib.lv.slideUpBasket();
            } else {
                lib.lv.slideDownBasket();
            }
		})
	},

        attachBasketDeleteHandler: function(el) {
                $(el).hover(function() { $(this).addClass("beforedel").find(".delete").attr("src","/images/x.gif");  },
                            function() { $(this).removeClass("beforedel").find(".delete").attr("src","/images/null.gif"); });

                $(el).find(".delete").click(function() {
                    //alert("deleting "+$(this).attr("rel"));
					var rel = $(this).attr("rel");
					var cn = $("#t_"+rel).find(".cn").attr("rel");
					var maat = $("#t_"+rel).find(".maat").attr("rel");
					var color = $("#t_"+rel).find(".colorsku").find("img").attr("alt");
					var colorsku = $("#t_"+rel).find(".colorsku").attr("rel");
                    $("#t_"+rel).animate({"opacity": 0},1000,function() {
						lib.lv.removeFromBasket({
							orderid: cn, 
							maat: maat,
							kleur: color,
							kleursku: colorsku
						});
					});
                });
        },

        positionBasket : function(el) {
                var moveHeight = -1*parseInt($(el).css("height"));
                //var moveLeft =  ( $("body").outerWidth() - $(el).outerWidth() ) / 2;

                if($.cookie("retracted") == "1") {
                    $(el)
                        .data("retracted",false)
                        .data("moveHeight",moveHeight)
                        .css({bottom: 0});
                } else {
                    $(el)
                        .data("retracted",true)
                        .data("moveHeight",moveHeight)
                        .css({bottom: moveHeight});
                }
        },
		feedback: function() {
			$('<div class="jqmWindow" id="feedbackpop"></div>').appendTo(document.body);
			$("#feedbackpop").jqm();
			$("#feedback").click(function() {
				$.ajax({
					type: "GET",
					url: "/parts/feedback.phtml",
					cache: false,
					dataType: "html",
					success: function(data) {
						$("#feedbackpop").html(data).jqmShow();
					},
					error: function() {
					}
				});
				return false;
			});
		},
		translateComments: function() {
			$(".comment").find(".flags img").click(function() {
				var curcomment = $(this).parent().parent();
				$(curcomment).find(".trans").translate($(this).attr("data"), { });
			});
		},

		indekijker : function() {
			var width = 690;
			var diff = 50;
			var normal = width/3 + "px";
			var wide = (width/3 + (2*diff)) + "px";
			var small = (width/3 - diff);
			var speed = 1000;
			$(".frontimages li").hover(
				function() {
					var rel = $(this).find("img").attr("rel");
					$(".idklogos").hide();
					$(".idkel").hide();
					$(".idktxt").show();
					$("#idk"+rel).css({opacity: 0}).show().animate({"opacity": 1}, { queue: false, duration: 500 });
					$(this).prev("li").prev("li").stop().animate({"width": small},{ queue: false, duration: speed });
					$(this).prev("li").prev("li").find("img").stop().animate({left: (-1*diff/2)},{ queue: false, duration: speed });
					$(this).prev("li").stop().animate({"width": small},{ queue: false, duration: speed });
					$(this).prev("li").find("img").stop().animate({left: (-1*diff/2)},{ queue: false, duration: speed });
					$(this).stop().animate({ "width": wide },{ queue: false, duration: speed });
					$(this).find("img").stop().animate({left: 0 },{ queue: false, duration: speed });
					$(this).next("li").stop().animate({"width": small},{ queue: false, duration: speed });
					$(this).next("li").find("img").stop().animate({left: (-1*diff/2)},{ queue: false, duration: speed });
					$(this).next("li").next("li").stop().animate({"width": small},{ queue: false, duration: speed });
					$(this).next("li").next("li").find("img").stop().animate({left: (-1*diff/2) },{ queue: false, duration: speed });
				},
				function() {
					$(".idkel").hide();
					$(".idklogos").show();
					$(".idktxt").hide();
					$(this).prev("li").prev("li").stop().animate({"width": normal},{ queue: false, duration: speed });
					$(this).prev("li").prev("li").find("img").stop().animate({left: (-1 * diff/2)},{ queue: false, duration: speed });
					$(this).prev("li").stop().animate({"width": normal},{ queue: false, duration: speed });
					$(this).prev("li").find("img").stop().animate({left: (-1*diff/2)},{ queue: false, duration: speed });
					$(this).stop().animate({ "width": normal },{ queue: false, duration: speed });
					$(this).find("img").stop().animate({left: (-1 * diff / 2) },{ queue: false, duration: speed });
					$(this).next("li").stop().animate({"width": normal},{ queue: false, duration: speed });
					$(this).next("li").find("img").stop().animate({left: (-1*diff/2)},{ queue: false, duration: speed });
					$(this).next("li").next("li").stop().animate({"width": normal},{ queue: false, duration: speed });
					$(this).next("li").next("li").find("img").stop().animate({left: (-1*diff/2)},{ queue: false, duration: speed });
				}
			);
		},



	  calcMaat : function() {
		var borst = $("#borst")[0];
		var romp = $("#romp")[0];
	
		if(borst.value - romp.value < 0) {
			alert($("#switch1").text()+"\n"+$("#switch2").text());
			var tmp = borst.value;
			borst.value = romp.value;
			romp.value = tmp;
		}
	
		var boxheight = $("#maatbox").height();
		var old = $("#maatbox").html();
		$("#maatbox").html("<div style=\"height:"+boxheight+"px; background-color: #ececec\" id=\"submaatbox\">" +
						  "<img style=\"margin-top:"+((boxheight * 0.5 ))+"px;\" src=\"/images/indicator.gif\"/>" +
						  "</div>");

		$.ajax({
			type: "GET",
			url: "/parts/maten_result.phtml",
			cache: false,
			data: { borst: borst.value, romp: romp.value },
			dataType: "html",
			success: function(r) {
				$("#maatbox").html(r);
				$("#maatboxstore").hide().html(old);
			},
			error: function(e) {
				$("#maatbox").html($("#messages #error").text())
			}

		});
	
	  }
  }
		
}();

// for every page
$(function() {
	//var settings = { tl: { radius: 8 }, tr: { radius: 8 }, antiAlias: true, autoPad: true };
	//$("#minibasketcont").each(function() { new curvyObject(settings,this).applyCorners(); });
    lib.lv.init();
    lib.lv.setLangCookie();
	lib.lv.applyPreferedStyle();
	//$(".jir").each(lib.lv.applyJIR);
	lib.lv.attachCssSelectors();
	lib.lv.showBasketIfNonEmpty();
	$("body").supersleight();
});

// vim: ts=4 smartindent cindent
