var searchDefault = "";
var masterTimer;
var masterTimer2;


function init() {
	searchDefault = $(".search_input").attr("value");
	tryActionInit();
	toggleSearch();
	// offsetSubmenu(false);
	// replaceHeaders();
	verticalAlignBlocks();
	phoneHover();
	tabbing();
	rowAlt();
	if ($.browser.msie && $.browser.version < 7) {
		setMenuHeight();	
		$(document).pngFix();
		// offsetSubmenu(true);
		$("#content .mkb.breed .row .value input[type=text]").css("width", 190);
		$("#content .mkb.breed .row .value input[type=text]").css("height", 15);
		if ($("#content .mkb").height() < 400) {
			$("#content .mkb").css("height", 400);	
		}
	}
	if ($.browser.safari) {
		$("#content .mkb").css("margin", 0);
	}
	if ($.browser.mozilla) {
		$(".data .save").each(function() {
			$(this).css("width", $(this).css("width"));
		});
    }
    $('.tipbox').each(function() {
        var divid = $(this).attr('title');
        $(this).removeAttr('title');
        $(this).mousemove(function(e) {
            tipBoxShow(e, divid);
        });
        $(this).mouseout(function(e) {
            tipBoxHide(divid);
        });
    });
	
	reflect();
	pulldown();
	// calculateBrands();
	toggleAttributes();
	lastPhoneCompare();
	extrawidth();
	telephoneEnlarger();
	$('.selected').find('input').attr('checked', true);
   	$(".bundleRow").bind("mouseenter mouseleave", function(e){
        $(this).toggleClass("over");
    });
    $(".shoptop .bundleRow").bind("click", function(e) {
        $(this).find('input').click();
    });
	

	$(".sales .phone").bind("mouseenter mouseleave", function(e){
        $(this).toggleClass("active");
    });
	$(".sales .phone").click(function() {
		document.location.href = $(this).find("a").attr("href");
	});
	setMyMobileHeight();
	disableLinks();
	phoneClicks();
	removeLastStepBg();
	showLisa();
	showOrderLaterBubble();
	fixDisabledInputs();
	setOrderHeight();
	toggleInsurance();
	wrapUrls();
	// fancyButton plugin
	$(document).fancyButton();
	// targetBlank plugin
	$(document).targetBlank();
	//default button firefox plugin
	$(document).defaultButtonFirefox();
	segmentPosition();
	resetShop();
	tooltips();
	mkb();
	fancyLists();
	$("a.disabled").click(function() { return false; });
	emailToTitle();
	telesales();
	bundelswitcher();
	galeryZoom();
	

	var subscriptiontabs = $("#newPhoneDetails .subscriptiontabs ul");
	if (subscriptiontabs.length > 0) {
	    
	    var nrtabs = $(".subscriptiontabs ul li").length;
	    var selectedTab = 0;
	    
	    if (chosenSubscription.indexOf('PREPAID') > -1) {
	        selectedTab = nrtabs - 1;
	        $('.extrabundles').hide();
	    } else if (chosenSubscription.indexOf('BB') > -1) {
	        //var idxBB = $("div.subscriptionpanel:visible").index($('#panelBundleFree'));

	        selectedTab = 2; //idxBB;
	    } else if (chosenSubscription.indexOf('-12') > -1) {
	        selectedTab = 1;
	    }

	    var tabos = subscriptiontabs.tabs({ selected: selectedTab });
        tabos.bind('select.ui-tabs', function(event, ui) {
	        var panel = ui.tab.href;
	        
	        if (panel.indexOf('Prepaid') > -1) {
	           $('.extrabundles').hide();
	        } else {
	           $('.extrabundles').show();
	        }
	    });
	   
   }
	
}
function tryActionInit() {
    $('.actionTry input').click(function() {
        $(this).focus();
        $(this).select();
    });
    
    $('.actionTry input[value=""]').each(function() {
        $(this).val('Hier uw actie code');
    });
    $('.actionTry input[value!="Hier uw actie code"]').each(function() {
        $(this).val($('.actionTry input').not(':first').val());
    });
    $('.actionTry input:first').keyup(function() {
        $('.actionTry input').not(':first').val($(this).val());
    });
    $('.actionTry input').not(':first').keyup(function() {
        $('.actionTry input:first').val($(this).val());
    });
    $('.actionTry .tryheader a[href="#"]').each(function() {
        $(this).attr('href', $('.actionTry .actioncode a[href!="#"]').attr('href'));
    });
    $('.actionTry .txtbutton').each(function() {
        $(this).removeClass('txtbutton');
    });
    if ($('.actionTry .error').length > 0) {
        $('.actionTry .errorTry').html($('.actionTry .error').html());
        $('.actionTry .errorTry').css('display', 'block');
    }
}

function toggleSearch() {
	$(".search_input").focus(function() {
		if ($(this).attr("value") == searchDefault) {
			$(this).attr("value","");	
		}
	});
	$(".search_input").blur(function() {
		if ($(this).attr("value") == undefined) {
			$(this).attr("value", searchDefault);	
		}
	});
}
function resetShop() {
	$(".resetshop").click(function() {
		shop.reset();
		calculateBrands();
		$(".textinfo").hide();
	});
}

function offsetSubmenu(isIE6) {
	if ($("#menu li.active").offset()) {
		var offset = $("#menu li.active").offset().left - $("#site").offset().left;
		var offsetWidth = $("#menu li.active").width()/2;
		offset = offset + offsetWidth;
		var width = $(".offsetter").width();
		var margin = 7;
		if (isIE6) {
			margin = - 60;	// is this true?
		}
		var newOffset = offset - (width/2) +margin;
		if (newOffset < 5) {
			newOffset = 0;	
		}
		if ($("#menu li.active").hasClass("last")) {
			$(".offsetter").css("float","right");	
		} else {
			// $(".offsetter").css("display","none");
			$(".offsetter").css("margin", "0px 0px 0px " + newOffset + "px");
			$(".offsetter").fadeIn("slow");
			$(".offsetter li:last").css("borderRight", "1px solid #ffffff");
		}
	}
}
function verticalAlignBlocks() {
	var $leftBlocks = $(".left.subhome").children();
	var smspage = $("#content").find(".prepaidsms_main");
	
	if (smspage.attr("class") == undefined ) {
		$leftBlocks.each(function(index) {		
			if ($(this).attr("class") != "block") {
				if (index % 2 == 0 && index > 0) {
					var $prev = $(this).prev();
					if ($prev.offset().top != $(this).offset().top) {
						var margin = $prev.offset().top - $(this).offset().top;
						if (margin < 0) {
							$prev.css("paddingTop",	$(this).offset().top - $prev.offset().top);
						} else {
							$(this).css("paddingTop",margin);
						}
					}
				} else if (index % 2 == 1) {
					$(this).css("clear","both");
				}
			}
		});
	}
}
function replaceHeaders() {
	sIFR.replaceElement(named({sSelector:"#content .pageheader", sFlashSrc:"/rabomobiel/static/flash/myriad_pro_semiextended.swf", sColor:"#FF6600", sLinkColor:"#FF6600", sBgColor:"#FFFFFF", sHoverColor:"#FF6600", sFlashVars:"textalign=left", sWmode: "transparent"}));	
	sIFR.replaceElement(named({sSelector:".right .header", sFlashSrc:"/rabomobiel/static/flash/myriad_pro_semiextended.swf", sColor:"#FF6600", sLinkColor:"#FF6600", sBgColor:"#FFFFFF", sHoverColor:"#FF6600", sFlashVars:"textalign=left", sWmode: "transparent"}));	
	sIFR.replaceElement(named({sSelector:".left .header", sFlashSrc:"/rabomobiel/static/flash/myriad_pro_semiextended.swf", sColor:"#000099", sLinkColor:"#000099", sBgColor:"#FFFFFF", sHoverColor:"#000099", sFlashVars:"textalign=left", sWmode: "transparent"}));	
}
function phoneHover() {
	$(".shop .phone").mouseover(function() {
		$(this).addClass("hover");
		if ($.browser.msie && $.browser.version < 7) {
			if ($(this).hasClass("compared")) {
				// compared and hovered -> introduce a fixed class for ou beloved ie6
				$(this).addClass("comparedhover");
			}
		}
	});
	$(".shop .phone").mouseout(function() {
		$(this).removeClass("hover");
		$(this).removeClass("comparedhover"); // remove the ie6 class if it's there
	});
}
function reflect() {
	if (!$.browser.msie || ($.browser.msie && $.browser.version > 6)) {
    	try {
			$(".reflect").reflect({height: 0.25});
			$(".reflect_large").reflect({height: 0.5});
			$(".reflect_small").reflect({height: 0.15});
		} catch (exc) {}
	}
}
function tabbing() {
    $("#tab_specificaties").hide();
    $("#tab_nummerbehoud").hide();
    $("#tab_abonnement").hide();
    $("#tab_prepaid").hide();
    $(".tab").click(function() {

        var classes = $(this).attr("class").split(" ");
        var tab = "";
        for (var i = 0; i < classes.length; i++) {
            var className = classes[i];
            if (className != "active" && className != "tab") {
                tab = className;
            }
        }

        $(".tab").removeClass("active");
        $(this).addClass("active");

        $(this).parent().parent().find(".tabtext").hide();
        $("#tab_" + tab).show();
        return false;
    });
    var selected = $('.selected').parent().parent().parent().removeClass("content").attr("class");
    $('.selected').parent().parent().parent().addClass("content");
    if (selected != undefined && selected != "smsdiv") {
        $(".tabs a." + selected).parent().parent().addClass("active");
        toggleContent(selected);
    } else {
        $(".tabs li:first").addClass("active");
        toggleContent($(".tabs li:first").find("a").attr("class"));
    }
    $(".tabs .tab").click(function() {
    
        toggleContent($(this).find("a").attr("class"));
    });
}
function rowAlt() {
	$("#tab_overzicht").each(function() {
		var $rows = $(this).children();
		$rows.each(function(index) {
			if (index % 2 == 0) {
				$(this).addClass("alt");
			}
		});
	});
	$(".properties .propertie").each(function(index) {
		if (index % 2 == 0) {
			$(this).addClass("alt");
		}
	});
	$(".phones .phone").each(function() {
		$(this).find(".propertie").each(function(index) {
			if (index % 2 == 0) {
				$(this).addClass("alt");
			}
		});
	});
	$(".tblCdrgroup").each(function() {
		$(this).find("tr").each(function(index) {
			if (index % 2 == 1 ) {
				$(this).addClass("alt");
			}
		});
	});
	$(".bordered .alter").each(function(index) {
		if (index % 2 == 1) {
			$(this).addClass("alt");
		}
	});
}
function lastPhoneCompare() {
	$(".phones .phone:last").css("borderRight", "1px solid #dfdfdf");
	$(".phones .phone").each(function() {
		$(this).find(".ordercontainer:last").css("borderBottom", "none");
	});
	$(".properties .propertie:last").css("height", 75);
	$(".properties .propertie:last").css("borderBottom", "1px solid #dfdfdf");
}
function setMenuHeight() {
	if ($("#menu .submenu").attr("class") == undefined) {
		$("#menu").css("height","36px");
	}
}
function pulldown() {
	var initHeight = $(".pulldownContent").height();
	$(".pulldownContent").height(0);
	$(".pulldown").click(function() {
		if ($(".pulldownContent").height() == initHeight) {
			$(".pulldownContent").animate({
				height: 0
			}, 400);
			$(".pulldown").removeClass("open");
		} else {
			$(".pulldownContent").animate({
				height: initHeight
			}, 400);
			// start timer for timeout
			$.timer(200, timedHide2);
			$(".pulldown").addClass("open");
		}
	});
	$(".pulldownContent").mouseover(function() {
		// clear the timer!	
		stopHide2();
	});
	$(".pulldownContent").mouseout(function() {
		// clear the timer!		
		startHide2();
	});
	$(".brand input").click(function() {
		calculateBrands();
	});
}
function calculateBrands() {
	var brands = 0;
	var allBrands = 0;
	$(".brand input").each(function() {
		if($(this).attr("checked") == true) {
			brands++;	
		}
		allBrands++;
	});
	if (brands == 0) {
		$("#brandcounter").text("alle merken");
	} else if (brands == allBrands) {
		$("#brandcounter").text("alle merken");
	} else if (brands == 1){
		$("#brandcounter").text(brands + " merk");
	} else {
		$("#brandcounter").text(brands + " merken");
	}
}
function toggleAttributes() {
	$("#extraattributes").hide();
	$(".toggleAttributes").click(function() {
		if ($("#extraattributes").css("display") == "none") {
			$("#extraattributes").fadeIn("slow");
			$("#extraattributes").fadeTo("slow", 0.92);
			// set timeout to autoclose popup
			$.timer(100, timedHide);
		} else {
			$("#extraattributes").fadeOut("slow");
		}
		return false;
	});
	$("#extraattributes").mouseover(function() {
		// clear the timer!	
		stopHide();
	});
	$("#extraattributes").mouseout(function() {
		// clear the timer!		
		startHide();
	});
}
var hideCounter = 0;
function timedHide(timer) {
	masterTimer = timer;
	hideCounter ++;
	if (hideCounter % 20 == 0) {
	 	$("#extraattributes").fadeOut("slow");
		hideCounter = 0;
		masterTimer.reset();
		masterTimer.stop();
	}
}
function timedHide2(timer) {
	masterTimer2 = timer;
	hideCounter ++;
	if (hideCounter % 20 == 0) {
	 	$(".pulldownContent").animate({
				height: 0
			}, 400);
			$(".pulldown").removeClass("open");
		hideCounter = 0;
		masterTimer2.reset();
		masterTimer2.stop();
	}
}
function stopHide() {
	hideCounter = 0;
	masterTimer.stop();
}
function startHide() {
	masterTimer.reset();
}
function stopHide2() {
	hideCounter = 0;
	masterTimer2.stop();
}
function startHide2() {
	masterTimer2.reset();
}
function extrawidth() {
	if($(".left .textmenu").width() == null) {
		$(".items").css("width", "695px");
	}
}
function telephoneEnlarger() {
	$(".phonedetails .thumb").each(function() {
		$(this).bind("mouseenter",function() {
			var img = $(this).find("img").attr("src");
			img = img.replace("THUMB","XLARGE");
			$(".left .phone .details .image").find("img").attr("src",img);
			$("#newPhoneDetails .phone .details .image").find("img").attr("src",img);
			// firefox has problems updating the canvas so remove it
			// $(".left .phone .details .image").find("img").hide();
			$.Reflection.remove($(".left .phone .details .image").find("img"));
			$.Reflection.remove($("#newPhoneDetails .phone .details .image").find("img"));
			// it is possible to recreate the reflection but it's very time consuming!
			// $(".left .phone .details .image").find("img").reflect({height: 0.15});
		});
	});
}
function switchGeneric() {
   var subscriptionKey;
   var row;
   if ($('.bundles input[@type="radio"]:checked').length == 1) {
        row = $('.bundles input[@type="radio"]:checked').parents('.bundleRow');
        subscriptionKey = 'RM-'+row.find('.name').text().substring(12);
   } else if ($('.bundles1 input[@type="radio"]:checked').length == 1) {
        row = $('.bundles1 input[@type="radio"]:checked').parents('.bundleRow');
        subscriptionKey = 'RM-'+row.find('.name').text().substring(12)+'-12';
   } else if ($('.free input[@type="radio"]:checked').length == 1) {
        row = $('.free input[@type="radio"]:checked').parents('.bundleRow');
        var name = row.find('.name').text();
        subscriptionKey = 'BB-0';
        if (name.indexOf('1 jaar')>-1) subscriptionKey = 'BB-12';
        if (name.indexOf('2 jaar')>-1) subscriptionKey = 'BB-24';
        
   } else {
        subscriptionKey = 'BB-24';
   }
   var sms = $('.smsdiv input[@type="radio"]:checked').val() != '' ? '&sms=' + $('.smsdiv input[@type="radio"]:checked').val() : '';
   var mobileinternet = '&databundle=' + $('.datadiv input[@type="radio"]:checked').val();
   var options = '&options=';

   $('.optionsdiv input[@type="radio"]:checked').each(function(option) {
        options += $(this).val() + '-' + $(this).parents('.bundleRow').find('select').val() + ',';
   });
   var business = $('.isBusinessDiv').length == 1 ? "&business=true" : "";
   var accessories = $('.showAccessoriesDiv').length == 1 ? "&accessories=true" : "";
   var subscriptionSet = $('.bundles').length > 0 || $('.free').length > 0 ? "&subscriptionset=true" : "&subscriptionset=false";
   var newreceipt = $('#receiptHolder').length == 1 ? "&newreceipt=false" : "&newreceipt=true";
   var url = '/rabomobiel/functions/ReceiptHandler.aspx?subscription=' + subscriptionKey + sms + '&ts=' + new Date().getTime() + business + newreceipt + mobileinternet + subscriptionSet + options + accessories;

   $.get(url, function(data) {
       // maintain back url
       var href = $('#receiptHolder .back a').attr('href');
       var orderHref = $('#receiptHolder .order a').attr('href');
       $('#receiptHolder').html(data);
       $('#receiptReplaceHolder').html(data);
       $('#receiptHolder .back a').attr('href', href);
       if (orderHref) {
           var newOrderHref = $('#receiptHolder .order a').attr('href');
           var url = orderHref.substring(0, orderHref.indexOf('?'));
           var query = newOrderHref.substring(newOrderHref.indexOf('?'));
           $('#receiptHolder .order a').attr('href', url + query);
       }
   });
   $(".bundleRow").removeClass('selected');
    if (row)
		row.addClass('selected');
}
function switchAbo(el) {
    switchGeneric();
}

function switchBundleFree(el) {
    switchGeneric();
}
function toggleContent(content) {
    
	$(".phone .content").hide();
	$(".phone .content."+content).show();
	$(".phone .content.smsdiv").show();
	$(".phone .content.datadiv").show();
	
	if (content != undefined && content.toString().indexOf('bundles') != -1)
	{
		$('#smsPriceInCents10').hide();
		$('#smsPriceInCents15').show();
		$('.bundleRow.twofifty').show();
	}
	else
	{
		$('#smsPriceInCents10').show();
		$('#smsPriceInCents15').hide();
		$('.bundleRow.twofifty').hide();
	}
}
function setMyMobileHeight () {
	var phoneHeight = $("#mymobile .phones").height();
	var detailHeight = $("#mymobile .details .mid").height();
	var targetHeight = 0;
	if (phoneHeight > detailHeight) {
		targetHeight = phoneHeight;	
	} else {
		targetHeight = detailHeight;	
	}
	if ($.browser.msie && $.browser.version < 7) 
	{
	    $("#mymobile .details .mid .textcontent").css("height",targetHeight);
	}
	else{
	    $("#mymobile .details .mid .textcontent").css("min-height",targetHeight);
	}
	// strech the last selfcarePanel per block
	try {
		var offsetTop = $("#mymobile .details .mid .textcontent").offset().top;
		var leftLastTop = $(".leftblock .selfcarePanel:last").offset().top - offsetTop;
		var leftLastHeight = $(".leftblock .selfcarePanel:last").height();
		var leftLastBottom = leftLastTop + leftLastHeight;
		if ( leftLastBottom < targetHeight) {
			var leftLastAdded = targetHeight - leftLastBottom;
			$(".leftblock .selfcarePanel:last").css("height", leftLastHeight + leftLastAdded);
		}
		// same for right
		var rightLastTop = $(".rightblock .selfcarePanel:last").offset().top - offsetTop;
		var rightLastHeight = $(".rightblock .selfcarePanel:last").height();
		var rightLastBottom = rightLastTop + rightLastHeight;
		if ( rightLastBottom < targetHeight) {
			var rightLastAdded = targetHeight - rightLastBottom;
			$(".rightblock .selfcarePanel:last").css("height", rightLastHeight + rightLastAdded);
		}
	} catch (e) {}
}
function disableLinks() {
	$("#mymobile .nav a").each(function() {
		if ($(this).attr("href") == undefined) {
			$(this).addClass("disabled");	
		}
	});
}
function phoneClicks() {
	$(".shop .phone").each(function() {
		var href = $(this).find("a").attr("href");
		$(this).find(".image").click(function() {
			location.href = href;
		});
		$(this).find(".details").click(function() {
			location.href = href;
		});
		$(this).find(".price").click(function() {
			location.href = href;
		});
	});
}
function removeLastStepBg() {
	$(".steps .step:last").css("borderRight", "none");
}
function showLisa() {
	$("a[href=#lisa]").click(function() {
		// create a lisa bubble
		var newshop = '';
		if ($(this).parents(".shopintro")[0] != undefined) {
			newshop = 'newshop';
		}
		createLisaBubble($(this), newshop);
		return false;
	});
}
function showOrderLaterBubble() {
    $("a").click(function() {
		if ($(this).attr("href") == "#orderlater") {
			// create a lisa bubble
			createOrderLaterBubble($(this));
			return false;
		}
	});
}
function createLisaBubble(elem, newshop) {
	if ($(".lisaBubble").attr("class") == undefined) {
		var json = { header: 'Stel hier uw vraag', buttonText: 'vraag' };
		var divElem = function () {
			return [
				'div', { className: 'lisaBubble ' + newshop }, [
					'div', { className: 'right' }, [],
					'div', { className: 'content' }, [
						'div', { className: 'close'	 }, [
							'a', { className: 'toggleLisaBubble', href: '#' }, [
								'img', { width: '18', height: '18', alt: 'sluiten', src: '/rabomobiel/static/images/close_button.gif' }
							],
						], 'div', { className: 'waitimg' }, [],
						   'div', { className: 'header' }, this.header,
						'div', { className: 'question' }, [
							'input', { id: 'selfservice_question_center', className: 'campaign_code', type: 'text', name: 'vraag' },								   
						], 'div', { className: 'ask' }, [
							'a' , { href: '#' }, this.buttonText,
						], 'div', { id: 'ssc_answerid'}, [
							'div', { className: 'text' }, [],
						],
					], 'div', { className: 'bottom' }
				]
			];
		};
		$("#content").tplPrepend(json, divElem);
		//$(".lisaBubble").fadeIn("slow");
		//$(".lisaBubble").fadeTo("slow", 0.92);
		$(".lisaBubble").show();
		$(".toggleLisaBubble").click(function() {
			// $(".lisaBubble").fadeOut("slow");
			$(".lisaBubble").hide();
		});
		$('#selfservice_question_center').keydown (function(event) {
			if (event.keyCode == 13) {
				askMe();
				return false;
			}
		});
		$(".lisaBubble .ask a").click(function() {
			askMe();
			return false;
		});
		$(".lisaBubble").css("top", elem.offset().top-30);
	} else {
		//$(".lisaBubble").fadeIn("slow");
		//$(".lisaBubble").fadeTo("slow", 0.92);
		$(".lisaBubble").show();
	}
}
function createOrderLaterBubble(elem) {
	if ($(".lisaBubble").attr("class") == undefined) {
		var json = { header: 'Stuur de order naar mijn e-mail', buttonText: 'Mail' };
		var divElem = function () {
			return [
				'div', { className: 'lisaBubble newshop' }, [
					'div', { className: 'right' }, [],
					'div', { className: 'content' }, [
						'div', { className: 'close'	 }, [
							'a', { className: 'toggleLisaBubble', href: '#' }, [
								'img', { width: '18', height: '18', alt: 'sluiten', src: '/rabomobiel/static/images/close_button.gif' }
							],
						], 'div', { className: 'waitimg' }, [],
						   'div', { className: 'header' }, this.header,
						'div', { className: 'question' }, [
							'input', { id: 'emailOrderLater', className: 'campaign_code', type: 'text', name: 'vraag' },								   
						], 'div', { className: 'ask' }, [

							'a' , { href: '#' }, this.buttonText,
						], 'div', { id: 'responseOrderLater'}, [
							'div', { className: 'text' }, [],
						],
					], 'div', { className: 'bottom' }
				]
			];
		};
		$("#content").tplPrepend(json, divElem);
		
		$(".lisaBubble").show();
		$(".toggleLisaBubble").click(function() {
			$(".lisaBubble").hide();
		});
		$('#selfservice_question_center').keydown (function(event) {
			if (event.keyCode == 13) {
				saveOrderForLater();
				return false;
			}
		});
		$(".lisaBubble .ask a").click(function() {
			saveOrderForLater();
			return false;
        });
		$(".lisaBubble").css("top", elem.offset().top-30);
		$(".lisaBubble").css("left", elem.offset().left);
	} else {
		//$(".lisaBubble").fadeIn("slow");
		//$(".lisaBubble").fadeTo("slow", 0.92);
		$(".lisaBubble").show();
	}
}

function saveOrderForLater() {
    var url = '/rabomobiel/functions/orderLater.ashx';
    var regEmail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!regEmail.test($("#emailOrderLater").attr("value"))) {
	    $("#responseOrderLater div.text").text("E-mailadres is niet goed ingevuld");
	    $(".lisaBubble .right").css("height", "70px");
		$(".lisaBubble .right").css("height", $(".lisaBubble").height() - 9);
	    return;
	}
    var params = 'email='+$("#emailOrderLater").attr("value")+'&ts='+new Date().getTime();
    $.ajax({
		type: "GET",
		url: url,
		data: params,
		success: fillOrderLater,
		error: fillOrderLater
	});
	
}
function fillOrderLater(request) {
    $("#responseOrderLater div.text").html(request);
    $(".lisaBubble .right").css("height", "70px");
	$(".lisaBubble .right").css("height", $(".lisaBubble").height() - 9);
}

function startCdrView(groupname) {
  	$('#tab_'+groupname).addClass("active");
  	$('#tabpanel_'+groupname).addClass("active");
 }
function selectCdrView(tab) {
	$(".cdrTabPanel").removeClass("active");
	var id = $(tab).attr("id");
	var panel = id.replace("tab","#tabpanel");
	$(panel).addClass("active");
	// $(".tab").removeClass("selected");	
}
function postForm()
{
	var data = 'opw=' + $('#changepw_old').attr('value');
	data += '&pw1=' + $('#changepw_new1').attr('value');
	data += '&pw2=' + $('#changepw_new2').attr('value');
	
	$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
	$("#TB_load").show();
	$("#TB_window").hide();
	$.post('/rabomobiel/functions/ChangePassword.ashx', data, processResult);
}

function processResult(data, status)
{
	var stat = eval("(" + data + ")");
	if (stat == null)
	{
		$("#changepw_result").html('Wijzigen is mislukt.');
	}
	else
	{
		$("#TB_load").remove();
		$("#TB_window").show();
		$("#changepw_result").html(stat.status);
		if(stat.valid)
		{
			$('#changepw_old').val('');
			$('#changepw_new1').val('');
			$('#changepw_new2').val('');
		}
	}
	
}
function isValidBirthdate(dayInput, monthInput, yearInput) {

    var dateok = true;

	if(dayInput.value == '' || monthInput.value == ''  || yearInput.value == '' || isNaN(dayInput.value) || isNaN(monthInput.value) || isNaN(yearInput.value)  )
	{
		dateok=false;
	}
	else
	{
		if (monthInput.value < 1 || monthInput.value > 12 )
		{
			dateok=false;
		}
		else
		{
			switch (monthInput.value)
			{
				case '1':
				case '3':
				case '5':
				case '7':
				case '8':
				case '10':
				case '12':
					max = 31;
					break;
				case '2' :
					if (((yearInput.value % 4 == 0) && (yearInput.value % 100 != 0)) || (yearInput.value % 400 == 0))
					{
						max = 29;
					}
					else
					{
						max = 28;
					}
					break;
				default:
					max = 30;
					break;			
			}
			if (dayInput.value < 1 || dayInput.value > max)
			{
				dateok =false;
			}
		}
	}
	return dateok;
}
function fixDisabledInputs() {
	$("input[disabled]").each(function() {
		$(this).css("backgroundImage","url(/rabomobiel/static/images/input_disabled_bg.gif)");
	});
}
function setOrderHeight() {
    $(".orderoverview .details div").each(function() {
        var height = $(this).find(".overview").height();


        if (height != null) {
            //console.log('div'+$(this).attr("id")+'height: ' + height);
            $(this).find(".eenmalig").css("height", height);
            $(this).find(".maand").css("height", height);
        }
    });
}
function toggleInsurance() {
	if($(".insuranceCheckbox input").attr("checked")) {
		$(".insurance").show();
	}
	$(".insuranceCheckbox input").click(function() {
		if($(this).attr("checked")) {
			$(".insurance").slideDown("fast");
		} else {
			$(".insurance").slideUp("fast");
		}
	});
}
function wrapUrls() {
	$(".resultUrl .text").each(function() {
		var url = $(this).html();
		var lastDash = url.lastIndexOf("/");
		if (lastDash > 80) {
			url = url.substring(0,lastDash+1) + "<br/>" + url.substring(lastDash+1,url.length);
			$(this).html(url);
		}
	});
}
function checkInsurance(val, args) {
    if ($('.insuranceCheckbox input').attr("checked") && !$('.agreeInsurance input').attr("checked")) {
        args.IsValid = false;
    }
}
function segmentPosition() {
	if ($(".segmentBlock").attr("class") != undefined) {
		$(".segmentBlock").parent().css("width", 710);
		$(".segmentBlock").each(function(index) {
			if (index % 2 == 1) {
				$(this).css("marginLeft", 19);	
			}
		});
	}
}
function tooltips() {
    if ($(".tooltip").attr("class") != undefined) {
	$(".tooltip").tooltip({ 
    	bodyHandler: function() { 
        	return $($(this).attr("href")).html();
	    }, 
    	showURL: false,
		delay: 0 
	});	
	}
}
function hbxIt(name, category, url) {
//    if (category == "default" || category == null || category == undefined) {
//        category = s.pageName;
//    }
//	_hbPageView(name, category);
	if (url != null) document.location.href = url;
}
function mkb() {
	$(".mkbtab a").bind("mouseenter mouseleave", function() {
		$(this).parent().parent().toggleClass("hover");
	});
	$(".mkb .bundles, .mkb .bundles1").each(function() {
		$(this).find("tr").each(function(index) {
			if (index % 2 == 1) {
				$(this).addClass("alt");	
			}
		});
	});
	$(".mkbaccount .overview").each(function() {
		$(this).find(".row").each(function(index) {
			if (index % 2 == 1) {
				$(this).addClass("alt");	
			}
		});
	});
}
function fancyLists() {
	// list items with a A tag inside won't get a list-style-type while items without one will get it
	$("#content .right .panel ul li").each(function() {
		if (!$(this).find("a")[0]) {
			$(this).addClass("normalListItem");
		}
	});
}
function initProductDetails() {
    /*
    toggleDivsOnContract($('#_tableContract input:checked').val());
    var inputButtons = $('.samenstellerOpties input');
    inputButtons.bind("click", function() {
        $(this).parents('table:first').find('td').removeClass('active');
        $(this).parent().addClass('active');
        switchContract();
    });
    $('#prepaidChoicesDiv input').bind("click", function() {
        switchContract();
    });*/
}
function switchContract() {
    var contract = $('input[name="thesub"]:checked').val();
   
    var subscriptionKey;
    var rateplan = '';

    if (contract.indexOf('PREPAID') > -1) {
        //console.log('prepaid contract found');
        subscriptionKey = 'PREPAID';
        rateplan = '&rateplan=' + contract;
        $('#_tableSMS input').attr('disabled', true);
        $('#_tableSMS input').attr('checked', '');
        $('#_tableInternet input').attr('disabled', true);
        $('#_tableInternet input').attr('checked', '');
    } else {
        //console.log('no prepaid contract found');
        $('#_tableSMS input').attr('disabled', false);
        $('#_tableInternet input').attr('disabled', false);
        subscriptionKey = contract;
    }
    
    var smsChoice = $('#_tableSMS input:checked').val();
    var internetChoice = $('#_tableInternet input:checked').val();
    
    var sms = '';
    if (smsChoice && smsChoice != '0') {
        sms = '&sms=' + smsChoice;
    }
    var internet = '';
    if (internetChoice && internetChoice != '0') {
    internet = '&internet=' + internetChoice;
    }
    var business = $('.isBusinessDiv').length == 1 ? "&business=true" : "";
    var url = '/rabomobiel/functions/ReceiptNewHandler.aspx?subscription=' + subscriptionKey + rateplan + sms + internet + business + '&ts=' + new Date().getTime();
    $.get(url, null, doLoadContractDivs, 'HTML');
}

function toggleDivsOnContract(contract) {
    
    var callMinuteTable = $('#_tableBelminuten');
    var smsTable = $('#_tableSMS');
    var internetTable = $('#_tableInternet');
    if (!contract) {
        $('#prepaidChoicesDiv').show();
    } else if (contract == '0') {
        callMinuteTable.find('input[value="0"]').attr('disabled', false);
        callMinuteTable.find('input[value="0"]').attr('checked', 'checked');
        
        callMinuteTable.find('input').not('[value="0"]').attr('checked', '');
        callMinuteTable.find('input').not('[value="0"]').attr('disabled', true);
        
        internetTable.find('tr#prepaidInternet').hide();
        internetTable.find('tr.postpaidInternet').show();
        
        callMinuteTable.find('td').removeClass('active');
        smsTable.find('input').attr('disabled', false);
        internetTable.find('input').attr('disabled', false);
        var bundleFree = callMinuteTable.find('input[value="0"]');
        bundleFree.attr('checked', 'checked');
        bundleFree.parent().addClass('active');
        $('#prepaidChoicesDiv').hide();
    } else if (contract == 'PREPAID') {
        callMinuteTable.find('input').attr('checked', '');
        callMinuteTable.find('td').removeClass('active');
        callMinuteTable.find('input').attr('disabled', true);
        
        smsTable.find('input').attr('checked', '');
        smsTable.find('td').removeClass('active');
        smsTable.find('input').attr('disabled', true);

        internetTable.find('tr.postpaidInternet').hide();
        internetTable.find('tr#prepaidInternet').show();

        internetTable.find('input').attr('checked', '');
        internetTable.find('td').removeClass('active');
        internetTable.find('tr.postpaidInternet input').attr('disabled', true);

        internetTable.find('tr#prepaidInternet input').attr('checked', 'checked');
        internetTable.find('tr#prepaidInternet td').addClass('active');
        
        $('#prepaidChoicesDiv').show();
    } else {
        
        
        if (contract == '12') {
            $('#_tableBelminuten .label1y').show();
            $('#_tableBelminuten .label2y').hide();
        } else if (contract == '24') {
            $('#_tableBelminuten .label2y').show();
            $('#_tableBelminuten .label1y').hide();
        }
        
        callMinuteTable.find('input').attr('disabled', false);
        if (!callMinuteTable.find('input:checked').val()) {
            var bundleFree = callMinuteTable.find('input[value="0"]');
            bundleFree.attr('checked', 'checked');
            bundleFree.parent().addClass('active');
        }

        var isSim = $('.pageheader').text().toLowerCase().indexOf('sim') > -1;
        if (isSim) {
            callMinuteTable.find('input[value="0"]').attr('disabled', true);
            callMinuteTable.find('input[value="0"]').attr('checked', '');
            callMinuteTable.find('td').removeClass('active');

            //callMinuteTable.find('input').not('[value="0"]').attr('checked', 'checked');
            callMinuteTable.find('input').not('[value="0"]').attr('disabled', false);
            if (!callMinuteTable.find('input:checked').val()) {
                callMinuteTable.find('input:eq(1)').attr('checked', 'checked');
            }
            callMinuteTable.find('input:checked').parent().addClass('active');
        }
        
        internetTable.find('tr.postpaidInternet').show();
        internetTable.find('tr#prepaidInternet').hide();
        
        smsTable.find('input').attr('disabled', false);
        if (!smsTable.find('input:checked').val()) {
            var bundleFree = smsTable.find('input[value="0"]');
            bundleFree.attr('checked', 'checked');
            bundleFree.parent().addClass('active');
        }
        internetTable.find('input').attr('disabled', false);
        $('#prepaidChoicesDiv').hide();
    }
}
function doLoadContractDivs(data, status) {
    $('#offlineContainer').html(data);
    var receiptNormal = $('#offlineContainer').find('#receiptNormal');
    var receiptSim = $('#offlineContainer').find('#receiptSim');
    var subscriptionInfo = $('#offlineContainer').find('#receiptSubscriptionInfo');
    var minutesInfo = $('#offlineContainer').find('#receiptMinutesInfo');
        
    $('#receiptHolderNew').html(receiptNormal.html());
    $('#receiptHolderSim').html(receiptSim.html());
    $('#_divSubscriptionHolder').html(subscriptionInfo.html());
    if ($('.minutescontainer').length > 0) {
        $('.minutescontainer').html(minutesInfo.html());
    }
    
    $('#offlineContainer').html('');

    $(".tabs .tab").removeClass("active");
    $(".tabs .abonnement").addClass("active");
    $(".tabdetails .tabtext").hide();
    $("#tab_abonnement").show();
    var idFirstDiv = $('#_divSubscriptionHolder div:eq(0)').attr('id');
    if (idFirstDiv) {
        if (idFirstDiv.indexOf('Prepaid') > -1) {
            $(".tabs .abonnement a").html('Prepaid');
        } else {
            $(".tabs .abonnement a").html('Abonnement');
        }
    }
    toggleContent('abonnement');
}
function doShowOverzichtTab()
{
    $(".tabs .tab").removeClass("active");
    $(".tabs .overzicht").addClass("active");
    $(".tabtext").hide();
    $("#tab_overzicht").show();
    return true;
}
function emailToTitle() {
	if ($("#emailToTitle").text().length > 20) {
		$("#emailToTitle").attr("title", $("#emailToTitle").text());
		$("#emailToTitle").css("cursor", "help");
		$("#emailToTitle").text($("#emailToTitle").text().substr(0,20) + " ...");
	}
}
function telesales() {
	$(".telesalesBlock .product").bind("mouseenter mouseleave", function() {
		$(this).toggleClass("hover");
	});
	$(".telesalesBlock .product").click(function() {
		document.location.href = $(this).find("a").attr("href");
	});
	$(".userBlock").click(function() {
		document.location.href = $(this).find("a").attr("href");
	});
	// don't add em to step 3!
	$(".stepcontainer.3 .userBlock").unbind('click');
	$(".stepcontainer.3 .telesalesBlock .product").unbind('click');
	$(".stepcontainer.3 .telesalesBlock .product").unbind('mouseenter');
	$(".stepcontainer.3 .telesalesBlock .product").unbind('mouseleave');
	$(".stepcontainer.3 .userBlock").addClass("nomouse");
	$(".stepcontainer.3 .telesalesBlock .product").addClass("nomouse");
}
function bundelswitcher() {
    var switchItemWidth = 170;
    var animate = false;

    $(".bs_switch").each(function() {
        var listItems = $(this).find(".bs_items").children();
        listItems.each(function(i) {
            $(this).addClass("err" + i);
        });
        var currentOffset = Number($(this).find(".bs_items").css("marginLeft").substr(0, ($(this).find(".bs_items").css("marginLeft").length - 2)));
        var itemsWidth = $(this).find(".bs_viewport .bs_items>li").length * switchItemWidth;

        $(this).find(".bs_viewport .bs_items").css("width", itemsWidth);
        if (currentOffset == 0) {
            $(this).find(".bs_nav_left").css("opacity", 0.5);
            $(this).find(".bs_nav_left").css("cursor", "default");
        }
        $(this).find(".bs_nav_left").click(function() {
            if (!animate && $(this).css("opacity") == 1) {
                animate = true;
                var currentOffset = Number($(this).parents(".bs_switch").find(".bs_items").css("marginLeft").substr(0, ($(this).parents(".bs_switch").find(".bs_items").css("marginLeft").length - 2)));
                bsLeft(currentOffset + switchItemWidth, $(this).parents(".bs_switch"));
                bsRight(currentOffset + switchItemWidth, itemsWidth, switchItemWidth, $(this).parents(".bs_switch"));
                $(this).parents(".bs_switch").find(".bs_viewport .bs_items").animate({
                    marginLeft: currentOffset + switchItemWidth
                }, 500, function() { animate = false; });
            }
        });
        $(this).find(".bs_nav_right").click(function() {
            if (!animate && $(this).css("opacity") == 1) {
                animate = true;
                var currentOffset = Number($(this).parents(".bs_switch").find(".bs_items").css("marginLeft").substr(0, ($(this).parents(".bs_switch").find(".bs_items").css("marginLeft").length - 2)));
                bsLeft(currentOffset - switchItemWidth, $(this).parents(".bs_switch"));
                bsRight(currentOffset - switchItemWidth, itemsWidth, switchItemWidth, $(this).parents(".bs_switch"));
                $(this).parents(".bs_switch").find(".bs_viewport .bs_items").animate({
                    marginLeft: currentOffset - switchItemWidth
                }, 500, function() { animate = false; });
            }
        });
        // initial offset
        var lowerSize = $(this).find(".bs_lower").length;
        var allSize = $(this).find('.bs_select').length;
        if (allSize == lowerSize && lowerSize != 0) lowerSize -= 1;
        
        var initialOffset = 0 - lowerSize * switchItemWidth;

        $(this).find(".bs_viewport .bs_items").css("marginLeft", initialOffset);
        bsLeft(initialOffset, $(this));
        //FIX: hoi lucien, waarom: initialOffset - switchItemWidth?? als er 3 items zijn dan blijft er hierdoor 1 verborgen :/
        //bsRight(initialOffset - switchItemWidth, itemsWidth, switchItemWidth, $(this));
        bsRight(initialOffset, itemsWidth, switchItemWidth, $(this));
        $(".bs_items input:checked").parents("li").addClass("bs_active");
    });
    $(".bs_items>li").click(function() {
        $(this).find("input").click();
        if ($.browser.msie && $.browser.version < 7) {
            if ($(this).hasClass("bs_lower")) {
                $(this).parents(".bs_items").children().removeClass("bs_activelower");
                $(this).parents(".bs_items").children().removeClass("bs_active");
                $(this).addClass("bs_activelower");
            } else {
                $(this).parents(".bs_items").children().removeClass("bs_activelower");
                $(this).parents(".bs_items").children().removeClass("bs_active");
                $(this).addClass("bs_active");
            }
        } else {
            $(this).parents(".bs_items").children().removeClass("bs_active");
            $(this).parents(".bs_items").children().removeClass("bs_activelower");
            $(this).addClass("bs_active");
        }


        checkPenalty($(this).find("input"));
        $(this).parents(".row").find(".bs_current").removeClass("bs_border");
    });
    $(".bs_items>li").bind("mouseenter mouseleave", function() {
        if ($.browser.msie && $.browser.version < 7) {
            if ($(this).hasClass("bs_lower") && !$(this).hasClass("bs_lowerhover")) {
                $(this).addClass("bs_lowerhover");
            } else if ($(this).hasClass("bs_lower") && $(this).hasClass("bs_lowerhover")) {
                $(this).removeClass("bs_lowerhover");
            } else {
                $(this).toggleClass("bs_hover");
            }
        } else {
            $(this).toggleClass("bs_hover");
        }
    });
    $(".abbo .bs_items>li").bind("mouseenter mouseleave", function(e) {


        // show penalty on mouse over
        if ($(this).hasClass("bs_lower") && e.type == "mouseenter") {
            //$(this).parents(".row").find(".bs_error").css("visibility", "visible");
            setPenalty($(this));
        }
        // hide penalty on mouseleave except when bs_lower is also active
        else if ($(this).hasClass("bs_lower") && e.type == "mouseleave" && $(this).hasClass("bs_active")) {
            //$(this).parents(".row").find(".bs_error").css("visibility", "hidden");
            setPenalty($(this));

        } else if (e.type == "mouseleave") {
            removePenalty($(this));
            setPenalty($(this).parents('ul').find('li:has(input:checked)'));
            
        }

    });
    $(".bs_items input").click(function() {
        $(this).parents(".bs_items").children().removeClass("bs_active");
        $(this).parents("li").addClass("bs_active");
        
        checkPenalty($(this));
        $(this).parents(".row").find(".bs_current").removeClass("bs_border");
    });
    $(".bs_current").click(function() {
        // back to old
        removePenalty($(this));
        $(this).next().find(".bs_active input").removeAttr("checked");
        $(this).next().find(".bs_active").removeClass("bs_active");
        $(this).find("input").attr("checked", "checked");
        $(this).addClass("bs_border");
    });
    $(".bs_close").click(function() {
        $(".bs_intro").slideUp(1000);
        return false;
    });
    $(".bs_cancel").click(function() {
        return confirm($(".bs_confirmText").text());
    });
}
function bsLeft(offset, obj) {
    if (offset != 0) {
        obj.find(".bs_nav_left").css("opacity", 1);
        obj.find(".bs_nav_left").css("cursor", "pointer");
    } else {
    obj.find(".bs_nav_left").css("opacity", 0.5);
    obj.find(".bs_nav_left").css("cursor", "default");
    }
}
function bsRight(offset, width, itemWidth, obj) {
    if (Number(Math.abs(offset) + Number(itemWidth * 2)) >= width) {
        obj.find(".bs_nav_right").css("opacity", 0.5);
        obj.find(".bs_nav_right").css("cursor", "default");
    } else {
        obj.find(".bs_nav_right").css("opacity", 1);
        obj.find(".bs_nav_right").css("cursor", "pointer");
    }
}
function checkPenalty(obj) {
    // find the selected input
    if (!obj) return;
    
    if (obj && obj.parents("li").hasClass("bs_lower")) {
        //if (!hasPenalty) {
        if (obj.attr('checked') == true) {
            setPenalty(obj.parents("li"));
        } else {
            removePenalty(obj.parents("li"));
            setPenalty($(".abbo .bs_switch input:checked").parents("li"));
        }
        //}
    } else if ($(".abbo .bs_switch input:checked").length != 0) {
        setPenalty($(".abbo .bs_switch input:checked").parents("li"));
    } else {
        removePenalty(obj);
    }
}
var hasPenalty = false;
function setPenalty(obj) {
    
    obj.parents(".row").find(".bs_error .err").each(function() {
        
        $(this).removeClass("err");
        $(this).css("display", "none");
    });
    obj.parents(".row").find(".bs_error span").each(function() {
        if (obj.hasClass($(this).attr("class"))) {
            
            $(this).css("display", "inline");
            hasPenalty = true;
        } 
        $(this).addClass("err");
    });
    
}
function removePenalty(obj) {
    obj.parents(".row").find(".bs_error .err").hide();
    
    hasPenalty = false;
}
function galeryZoom() {
	$(".zoom").click(function() {
		if (window.console) console.log(location);
		tb_show("", location.protocol +"//"+location.hostname+$(".images .thumb a.thickbox").attr("href"), $(".images .thumb a.thickbox").attr("rel"));
	});
}
function tipBoxShow(e, id) { $(id).css({ "display": "block", "top": e.pageY + 13, "left": e.pageX }); }
function tipBoxHide(id) { $(id).css({ "display": "none" }); }   
$(document).ready(function() {
    init();
});