$(document).ready(function(){
  
 $("#overstapservice, #overstapwekker").click(function() {
	location.href = $(this).find("a").attr("href");
	return false;
});
  
  var inputChecks = {
    postcode: /^\s*([1-9]\d{3})\s*([a-z]{2})\s*$/i,
    huisnr: /^\s*(\d+)(.*)$/i
  };
  
  $(".productcontent").createTabset();
  
  //Speedchecker submitten na een delay om te zorgen dat de andere achtergrond geladen is voordat de boel gesubmit wordt
  var submitSpeedcheck = function() {
    $(".complete").addClass("hide");
		$(".busy").removeClass("hide");
		$(".errormessage").addClass("hide");
    return true;
  }, realSubmit = false;
	$("#postcodeform").bind("submit", function() {
    if (realSubmit) { return true; }
    submitSpeedcheck();
    var form = this;
    realSubmit = true;
    window.setTimeout(function() { form.submit(); }, 100);
    return false;
	});

  var postcoderesult = $("#postcoderesult"), postcodecheck = $("#postcodecheck");
  if ($("#postcodeform .errormessage:visible").length > 0) {
    postcodecheck.addClass("reclame");
  }
  postcoderesult
    .find(".bar > .width > .upper, .bar > .width > .lower")
    .each(function() {
      var t = $(this), w = t.width();
      t.width(0).show()
        .animate({ width: w }, 1500, "swing", function() {
          $("#postcoderesult #result > p.speed").fadeIn();
        });
    });

	//Speedchecker-thickbox
  $(".thickbox").thickbox({
    mode: "ajax",
    caption: "Telfort postcodecheck",
    closeButton: "Sluiten",
    width: 494,
    height: 175,
    url: function() {
      var c = $(this).parents("#productheader,#orderinternet4mb,#orderinternet20mb");
      if (c.length > 0) {
        switch (c.get(0).id) {
          case "productheader":     return "/shop/plain/snelheidscheck.html?product=" + (document.location.pathname.indexOf("20mb") >= 0 ? 20 : 4);
          case "orderinternet4mb":  return "/shop/plain/snelheidscheck.html?product=4";
          case "orderinternet20mb": return "/shop/plain/snelheidscheck.html?product=20";
        }
      }
    }
  });
  
  //Hiermee zijn we er zeker van dat er geen junk om de root-tag staat
  $(document).bind("thickbox.loading", function(e, args) {
    args.process = function(data, args) {
      return $.trim(data);
    };
  });
  
  //Als er content in de thickbox geladen is...
  $(document).bind("thickbox.loaded", function(e, args) {
    $(args.source).find("form[name=speedcheckForm]").attr("action", args.url).submitAjax(function() {
      //...dan een formulier via ajax posten
      $(args.source).empty();
      $.thickbox.showLoader();
    }, function(data, status) {
      //...in de thickbox laden
      $(args.source).html($.trim(data));
      args.data = data;
      args.status = status;
      //...en opnieuw dit event triggeren
      $(document).trigger("thickbox.loaded", args);
      $.thickbox.hideLoader();
    }).end().find("p.redirect a:eq(0)").each(function() {
      //...en als er een resultaat wordt gegeven, dan daarheen redirecten
      $.thickbox.showLoader();
      document.location.href = $(this).attr("href") + "&" + $.param([
        { name: "telephony", value: $("#shoppingcart input[name=telephony]").value() },
        { name: "vas_fsecure", value: $("#shoppingcart input[name=vas_fsecure]").value() }
      ]);
    }).end().find("a#wijzigpostcode, .back").click(function() {
      //Postcode wijzigen en terug-knop - dus terug naar het formulier
      $(args.source).empty();
      $.thickbox.showLoader();
      $.get(args.url, null, function(data) {
        $(args.source).html($.trim(data));
        $(document).trigger("thickbox.loaded", args);
        $.thickbox.hideLoader();
      }, "html");
      return false;
    }).end().find(".close").unbind("click").click(function() {
      //Thickbox sluiten
      $.thickbox.close();
    }).end().find("#postcode").focus().blur(function() {
      //Postcode fixen als je eruit tabt
      this.value = this.value.replace(inputChecks.postcode, "$1$2").toUpperCase();
    }).end().find("#huisnr").blur(function() {
      //Huisnummer fixen (evt splitten) als je eruit tabt
      this.value = this.value.replace(inputChecks.huisnr, function($0, $1, $2) {
        if ($.trim($2) !== "") {
          $("#toevoeging").value($.trim($2.replace("-", "").toUpperCase()));
        }
        return $1;
      });
    }).end().find("#toevoeging").blur(function() {
      //Toevoeging fixen als je eruit tabt
      this.value = $.trim(this.value).toUpperCase();
    });
    //Q: Waarom was dat zo'n lange ketting van .end().find() statements?
    //A: Dat is omdat er selecties gedaan worden in de geretourneerde ajax-data. Als we het los zouden trekken en $(...) ipv .end().find(...) zouden gebruiken, zou je in het huidige DOM-document gaan zoeken naar die elementen, en niet in de geretourneerde ajax-data.
  });
  
  var popupTypes = {
		"modeminfo": { width:640, height:480 },
		"veiligheid": { width:550, height:500 },
		"consumentenbond": { width:550, height:250 },
		"maxspeed": { width:619, height:450 },
		"external": {  },
		"internetchat": {width:643, height:565}
	};

$(".popup").click(function() { 
		if (popupTypes[$(this).attr("rel")]) {
			var aWindow;
			if (popupTypes[$(this).attr("rel")].width && popupTypes[$(this).attr("rel")].height) {
				aWindow = window.open($(this).attr("href"), $(this).attr("rel"), "toolbar=0, location=0, directories=0, status=0, menubar=0, scrollbars=1, resizable=0, width=" + popupTypes[$(this).attr("rel")].width + ", height=" + popupTypes[$(this).attr("rel")].height);
			} else {
				aWindow = window.open($(this).attr("href"));
			}
			if (aWindow) { aWindow.focus(); return false; }
		}
	});
  
  //Vast bellen kosten berekenen
	var costs = null;
	var changeEvent = function() {
		var row = $(costs.get(Number(this.value))).find("td"), startup = "&euro; 0,00", minute = "&euro; 0,00";
		if (row.length > 0) {
		  startup = $(row.get(1)).html();
		  minute = $(row.get(2)).html();
		}
		$("#td_startup").html(startup);
		$("#td_minute").html(minute);
	};
	$("div.container #placeholder").hide();
	$("div.container #allcountries").append("<tr class=\"alternate selector\"><td class=\"label\"><select name=\"country\"></select></td><td id=\"td_startup\"></td><td id=\"td_minute\"></td></tr>");
	$("div.container #allcountries select").each(function() {
		var select = $(this);
		costs = $("div.container #allcountries tr.hide");
		select.append($("<option value=\"-1\"/>").text("Selecteer een land..."));
		$("div.container #allcountries").addClass("hiderows");
		costs.each(function(index) {
			select.append($("<option/>").attr("value", index).text($(this).find("td:eq(0)").text()));
		});
	}).change(changeEvent).keyup(changeEvent).keydown(changeEvent).change();
  
  //FAQ-entries
  $("div.faqs")
    .find(".container > p:last-child")
    .addClass("last")
    .end()
    
    .find(".container")
    .resetHeight(true)  //Initeel hiden
    .hide()
    .end()
  
    .faqSlider()
    .find(".toggle > :header:first-child")
    .addClass("first")
    .end()
    
    .find(".toggle > p")
    .click(function() {
      $(this).prevAll(":header").click();
    });
    
  //Overstappen FAQs
  $(".overstappen .faqs")
    .faqSlider({
      aftershow: function() { $("a.moreinfo", $(this).parent()).text("Verberg info"); },
      afterhide: function() { $("a.moreinfo", $(this).parent()).text("Meer info"); }
    });
    
  if (document.location.hash.length > 1) {
    $(":header#faq" + document.location.hash.replace(/\#openfaq(\d+)/i, "$1")).click();
  }
  
  //Speedchecker op de landingspagina
  $("#postcodeform #zip").blur(function() {
    //Postcode fixen als je eruit tabt
    this.value = this.value.replace(inputChecks.postcode, "$1$2").toUpperCase();
  });
  $("#postcodeform #houseNumber").blur(function() {
    //Huisnummer fixen (evt splitten) als je eruit tabt
    this.value = this.value.replace(inputChecks.huisnr, function($0, $1, $2) {
      if ($.trim($2) !== "") {
        $("#postcodeform #houseNumberExtension").value($.trim($2.replace("-", "").toUpperCase()));
      }
      return $1;
    });
  });
  $("#postcodeform #houseNumberExtension").blur(function() {
    //Toevoeging fixen als je eruit tabt
    this.value = $.trim(this.value).toUpperCase();
  });
  
  //Shopping carts
  $("table#shoppingcart").optionsTable()
    .find("th > input[type=checkbox]").click(function() {
      $(this).prev("input[type=hidden]").value(this.checked ? 1 : 0);
    }).each(function() {
      $(this).triggerHandler("click");
    });
  
  //Tooltips
  $("a.info-pcbeveiliging, a.info-vastbellen").tooltip({
    fade: 350,
    top: 2, 
    left: 5,
    bodyHandler: function() {
      return $($(this).attr("href")).html();
    },
    showURL: false
  });

	$(".overstappen .container .toggle").each(function() {
		$(this).css({height: $(this).height()+16}).hide();
	});	
	
	$(".container ul.arrow a").click(function() {
		var toggle = $(this).parent().parent().prev();
		if(toggle.is(":visible")) {
			toggle.slideUp();
		} else {
			toggle.slideToggle();
		}
		if($(this).hasClass("more")) {
			$(this).find("span").text("Minder");
		} else {
			$(this).find("span").text("Meer");
		}
		$(this).toggleClass("more");
		return false;
	});

	$("#overstappen .toggle").addClass("closed");
	$("#overstappen .select select").multibind(["keyup","change","click"], function() {
		$("#overstappen .toggle").addClass("closed");
		if($(this).val()!='') {
			$("#"+$(this).val()).removeClass("closed");
		}
	}).trigger("change");
  
  //Zorgen dat je op de gehele banner kunt klikken, ipv alleen op de meerinfo-knop
  $(".clickbanner").css("cursor", "pointer").click(function() {
    document.location.href = $(this).find("a.meerinfo").attr("href");
    return false;
  });
  
  //Gewone info-icoontjes
  $("span.info[title]:not(.textinfo)").infoPopup({
    transform: function(s) {
      return s.replace(/==([^\*]*)==\s+(.*)/, function($0, $1, $2) {
        var body = $2, list = body.split(";");
        if (list.length > 1 && $.inArray(false, $.map(list, function(l, i) { return $.trim(l).substr(0, 1) == "*"; })) == -1) {
          body = "<ul>" + $.map(list, function(l, i) { return "<li>" + l.replace(/^\s*\*\s*/, "") + "</li>"; }).join("") + "</ul>";
        }
        else {
          body = "<br/>" + body;
        }
        return "<strong>" + $1 + "</strong>" + body;
      });
    }
  });

  //Info op een tekstje
  $("span.info.textinfo[title]").infoPopup({
    pos: function() {
      var h = $("#productheader"), t = $("#productheader table"), hof = h.offset(), tof = t.offset();
      return { x: hof.left + 310, y: tof.top + t.height() + 8 };
    },
    transform: function(s) {
      if($("#internet-20mb, #internet-20mb-vastbellen, #internet-20mb-opties").length > 0) {
		var b = 1500;
	  } else {
		var b = 395;
	  }
	  var sum = (Math.round(Number($("td.totaal > span").text().replace(/^.\s+/, "").replace(/,/g, ".")) * 100) + b).toString().replace(/(\d{2})$/, ",$1")
	  
	  return ($("#internet-20mb, #internet-20mb-vastbellen, #internet-20mb-opties").length > 0 ? "Totale kosten na 6 maanden: &euro; " + sum + " p/mnd" : "Totale kosten na 12 maanden: &euro; " + sum + " p/mnd<br/>(inclusief pc-beveiliging totaal)")
    }
  });

});

$.fn.submitAjax = function(loadingFunc, successFunc) {
  this.filter("form").each(function() {
    $(this).bind("submit", function() {
      if (typeof(loadingFunc) == "function") {
        loadingFunc.call(this);
      }
      $.ajax({
        form: this,
        url: $(this).attr("action"),
        type: "POST",
        data: $(this).submissionData(),
        dataType: "html",
        contentType: this.enctype === "" ? "application/x-www-form-urlencoded" : this.enctype,
        success: successFunc
      });
      return false;
    });
  });
  return this;
};

$.fn.submissionData = function() {
  var result = [ ];
  this.filter("form").each(function() {
    var d = { }, el, i;
    for (i = 0; i < this.elements.length; i++) {
      el = this.elements[i];
      if (el.name !== "" && !el.disabled && el.type != "button" && el.type != "reset") {
        if ((el.type == "checkbox" || el.type == "radio") && el.checked) {
          d[el.name] = el.value === "" ? "on" : el.value;
        }
        d[el.name] = el.value;
      }
    }
    result.push(d);
  });
  return result.length == 1 ? result[0] : result;
};


$.fn.createTabset = function() {
  var tabset = this, tabs = this.children("div.step");
  this.children("ul.tabs").children("li").click(function() {
    $(this).parents("ul").children("li").removeClass("current").end().end().addClass("current");
    $(tabs.hide().get($(this).prevAll().length)).show().each(function() {
      //In MSIE8 exploderen absolutely positioned elementen uit de step-divs. Ze uit de DOM gooien en er opnieuw inzetten bij het showen van een step is voldoende om dit te fixen.
      if ($.browser.msie && $.browser.version >= 8) {
        $(this).find("#consumentenbond,button[type=submit]").each(function() {
          //Opnieuw in de DOM plaatsen
          var id = "#" + $(this).parents("div.step").get(0).id;
          $(this).remove().appendTo(id);
        });
      }
    });
    return false;
  });
  this.find("ul > li.current").click();
};

//Extension functie om de oorpsronkelijke hoogte van een item te bewaren.
$.fn.resetHeight = function(initial) {
  this.each(function() {
    if (initial) {
      this.originalHeight = this.offsetHeight + "px";
    }
    $(this).height(this.originalHeight);
  });
  return this;
};

//Extension funcie voor in- en uitklappen van FAQs
$.fn.faqSlider = function(settings) {
  settings = $.extend({
    aftershow: function() { },
    afterhide: function() { }
  }, settings);
  
  var animSettings = { 
    marginTop: "4px",
    marginBottom: "8px",
    height: "show"
  };
  var resetSettings = {
    marginTop: 0,
    marginBottom: 0
  };
  
  $(".toggle > h2, .toggle > h3", this).filter(function() {
    //Alleen h2/h3's die gevolgd worden door een div.container.
    return $(this).nextAll("div.container").length > 0;
  }).unbind(".faqslider").bind("click.faqslider", function() {
    if ($(this).hasClass("open")) {
      //Class "open" uit de header en de <div> verwijderen, eventuele lopende animatie stoppen, en verbergen.
      $(this).removeClass("open").nextAll("div.container").stop().hide().removeClass("open").resetHeight().css(resetSettings);
      if (typeof settings.afterhide == "function") {
        settings.afterhide.call(this);
      }
    }
    else {
      //Class "open" aan de header en de <div> toevoegen en weergeven.
      $(this).parents("div.faqs").find("div.container").stop().hide().removeClass("open").resetHeight().css(resetSettings).prev().removeClass("open");
      $(this).addClass("open").nextAll("div.container").addClass("open").each(function() {
        //$(this).slideDown("slow");
        $(this).animate(animSettings, "slow", "swing", function() {
          if (typeof settings.aftershow == "function") {
            settings.aftershow.call(this);
          }
        });
      });
    }
    window.location.href = "#open" + this.id;
    return false;
  });
  return this;
};

//Value setten/getten
$.fn.value = function(v) {
  var result = [];
  if (typeof v == "undefined") {
    this.each(function() { if (this.value) { result.push(this.value); } });
    if (result.length === 1) { return result[0]; }
    if (result.length === 0) { return null; }
    return result;
  }
  this.each(function() { this.value = v; });
  return this;
};

//Bestelopties-tabel interactief maken
$.fn.optionsTable = function() {
  $(this).filter("table").each(function() {
    var t = $(this), options = [], cart = [];
    var totals = $("tfoot > tr > *:last-child > span:last > span", t); //Totaal-cel is de laaste cel in de laatste rij in de tfoot
    var checkboxes = $("th > input[type=checkbox]", t); //Cache de checkboxes
        
    var createCookie = function(name, value) {
      document.cookie = name + "=" + value + ";path=/";
    };
    var readCookie = function(name) {
      var nameEQ = name + "=", result = null;
      $.each(document.cookie.split(";"), function(i, c) {
        while (c.charAt(0) == " ") { c = c.substring(1, c.length); }
        if (c.indexOf(nameEQ) === 0) { 
          result = c.substring(nameEQ.length, c.length);
          return false;
        }
      });
      return result;
    };
    var save = function() {
      checkboxes.each(function(i, el) {
        var found = $.grep(cart, function(c) { return c.name == el.id; });
        if (found.length > 0) {
          found[0].value = el.checked ? 1 : 0;
        }
        else {
          cart.push({ name: el.id, value: el.checked ? 1 : 0 });
        }
      });
      createCookie("shoppingcart", $.param(cart));
    };
    
    //Functie om het totaal te herberekenen
    var calc = function() {
      var total = 0;
      $.each(options, function(i, o) {
        //Optellen indien aangevinkt of niet aanvinkbaar
        total += o.val;
        if (o.chk.length > 0) {
          var op = o.chk.get(0);
          total -= op.checked ? 0 : o.val;
        }
      });
      total = String(Math.round(total * 100) / 100).replace(".", ","); //Afronden op 0,01 en komma forceren
      total = total.replace(/,(\d)$/, ",$10").replace(/^(\d+)$/, "$1,00"); //Nul of één decimaal omzetten naar twee
      totals.text(total);
      
      //Opties opslaan in een "sessie"
      save();
    };
    
    //Alleen doorgaan als er een totaal-cel bestaat
    if (totals.length > 0) {
      $("tbody > tr > th", t).each(function() {
        var checkbox = $("input[type=checkbox]", this);
        var value = Number($(this).next("td").find("span:last").text().replace(",", "."));
        if (!isNaN(value)) {
          //Evt checkbox + value aan de options toevoegen
          options.push({ chk: checkbox, val: value });
        }
      });
      
      //Alleen doorgaan als er checkboxes gevonden zijn
      if ($.grep(options, function(o) { return o.chk.length > 0; }).length > 0) {
        //Functie calc binden aan klikken op een checkbox
        $.each(options, function(i, o) {
          o.chk.click(calc);
        });
      }
      
      //Checks inladen uit cookie
      (function() {
        var options = {};
        $.each((readCookie("shoppingcart") || "").split("&"), function(i, c) {
          var op = c.split("=");
          if (op.length > 1) {
            options[op[0]] = op[1] == "1";
            cart.push({ name: op[0], value: options[op[0]] ? 1 : 0 });
          }
        });        
        checkboxes.each(function() {
          this.checked = options[this.id] === true;
        });
        calc();
      })();
    }
  });
  return this;
};

$.fn.multibind = function(types, data, fn) {
  if (types instanceof Array) {
    for (var i = 0; i < types.length; i++) {
      this.bind(types[i], data, fn);
    }
  }
  else {
    this.bind(types, data, fn);
  }
  return this;
};

$.infoPopup = { popup: null };
$.fn.infoPopup = function(options) {
  options = $.extend({
    pos: { x: 0, y: 0 }, //Relatieve positie t.o.v. de default (naast). Kan ook een functie zijn, die een dergelijk object teruggeeft.
    transform: function(s) { return s; }
  }, options);
  
  var popup = $.infoPopup.popup;
  if (popup === null) {
    $.infoPopup.popup = popup = $("<div class=\"info-popup\"/>").css("opacity", 0).appendTo("body");
  }
  
  this.hover(
    //popup tonen met title uit de jquery-data
    function(e) { 
      var offset, w, h;
      if (typeof options.pos == "function") {
        offset = options.pos();
        offset = { left: offset.x, top: offset.y };
        w = 0; h = 0;
      }
      else {
        offset = $(this).offset();
        offset.left += isNaN(Number(options.pos.x)) ? 0 : Number(options.pos.x);
        offset.top += isNaN(Number(options.pos.y)) ? 0 : Number(options.pos.y);
        w = $(this).width(); h = $(this).height();
      }
      
      popup[$(this).hasClass("textinfo") ? "addClass" : "removeClass"]("textinfo-popup");
      popup.html(String(options.transform($(this).data("title")))).css({ left: offset.left + w * 1.5, top: offset.top + h / 2 }).stop().show().fadeTo(350, 1.0);
    },
    function() { popup.stop().fadeTo(350, 0.0, function() { $(this).hide(); }); }
  ).each(
    //Move de titles naar jquery-data, zodat ze niet alsnog verschijnen
    function() {
      $(this).data("title", $(this).attr("title")).removeAttr("title");
    }
  );
}

try { document.execCommand("BackgroundImageCache", false, true); } catch(err) {}