/*	jQuery extensions
============================================================= */
$.toFirstUpper = function(str) {
    if (str != null) {
        strnew = str.substr(0, 1).toUpperCase();
        if (str.length > 1) { strnew += str.substr(1); }
        return strnew;
    } else {
        return str;
    }
}

$.postJSON = function(url, data, callback) {
	$.post(url, data, callback, "json");
};

$.postXML = function(url, data, callback) {
	$.post(url, data, callback, "xml");
};

$.postSOAP = function(url, data, callback) {
    var callbackJSON = function(d) {
        var n = d.lastChild;
        var o;
        eval("o=" + (n.text || n.textContent));
        callback(o);
    }
    $.post(url, data, callbackJSON, "xml");
};

// use for non-link
$.sitestatClick = function(sitestatCode) {
	var image = new Image();
	image.src = ns_sitestatUrl + sitestatCode;
	return true;
};
$.sitestatCode = function(sitestatCodeFormat, param1, param2, param3) {
	for (var index = 1; index < arguments.length; index++) {
		sitestatCodeFormat = (sitestatCodeFormat.replace(new RegExp("\\{" + (index - 1) + "\\}", "g"), arguments[index]));
	}
	return sitestatCodeFormat;
};
//	image.onerror = function() { alert("ERROR"); }
//	image.onabort = function() { alert("ABORTED"); }
//	image.onload = function() { alert("LOAD"); }

/* 	document on load cue
============================================================= */

$(document).ready(function() { 		// always load these function when the DOM is ready
    p80jq_zebra_table(); 			// alternating row colors for class tables.p80jq_zebra_table
    p80jq_src_hover(); 				// quick way of setting a swap image functionality on images with class img.p80jq_src_hover
    //p80jq_epandinglist(); 		// FAQ like exapding list on dl-tag with class dl.p80jq_expandinglist
    p80jq_element_restore_value(); 	// Swap a classname on inputfields input|textarea.p80jq_element_restore_value	
    p80jq_toggle_login(); 			// Show / hide the login dropdown div
    p80jq_toggle_help_icon(); 		// Tooltip show/hide on form pages
    p80jq_input_focus(); 			// CSS :focus class (background-color) for Win/IE 6 and 7
    p80jq_input_hover(); 			// Hover effect on input elements for Win/IE6

    benAjaxErrorHandler();
    hideIkBen();

    //IFrame Login/Logout functions
    SetIFrameLogin();
    SetIFrameLogout();

    VirtueleMedewerkerHandler();

    TextImage();
});

/* 	jQuery alternating row colors (zebra_stripe_tables) 
	adds a 'odd' or 'even' classnames on all tables which have a classname of 'p80_zebra_table'
============================================================= */

function p80jq_zebra_table() {
	$("table.p80jq_zebra_table tbody tr").each(function(index) {	// to all tr-tags
		$(this).addClass(index % 2 == 0 ? "odd" : "even");			// add an 'odd' or 'even' classname
	});
}


/* 	jQuery rollovers on elements with a src-attribute
    on rollover 'demo.gif' becomes 'demo_hover.gif'
============================================================= */
function p80jq_src_hover() {
    $(".p80jq_src_hover").hover(function() { 									// classname to trigger
        var filename = $(this).attr("src").replace(/\.(\w+)$/, "_hover.$1"); // mouse-over: add the filename suffix
        $(this).attr("src", filename);
    }, function() {
        var filename = $(this).attr("src").replace(/_hover\.(\w+)$/, ".$1"); // mouse-out: restore, remove filename suffix
        $(this).attr("src", filename);
    });
}

/*	Restore defaultValue on form elements onblur
============================================================= */

function p80jq_element_restore_value() {
	$("input:text.p80jq_element_restore_value, textarea.p80jq_element_restore_value").each(function() {
		$(this).attr('p80_org_formvalue', $(this).val());
		$(this).addClass('p80_form_label');
	})
	.focus(function () {
		if($(this).val() != '' && $(this).val() == $(this).attr('p80_org_formvalue')) {
			$(this).val('');
			$(this).removeClass('p80_form_label');
		}					
	 })
	.blur(function() {
		if($(this).val() == '') {
			$(this).val($(this).attr('p80_org_formvalue'));
			$(this).addClass('p80_form_label');
		}
	});
}

/*	Thumbnail list on template index list
============================================================= */

function p80jq_toggle_thumbs(){
	$("img.index_thumb").each(function() {					// img-tags with 'index_thumb' classnames
		$(this).toggleClass("index_thumb_show"); 			// toggle the classname
	});
}

/*	Thumbnail list on template index list
============================================================= */

function p80jq_toggle_help_icon(){
	
	$(".iconHelp span").css("visibility", "hidden");
	
	$(".iconHelp img").hover(
		function () {
			$(this).next("span").css("visibility", "visible");
		}, 
		function () {
			$(this).next("span").css("visibility", "hidden");
		}
    );
}

/*	Show / hide the login dropdown div
============================================================= */

var login_open = false;

function p80jq_toggle_login(){

    $("li.ikben_login").find("a").attr("id", "btnLogin");	
	
	// By default, the login menu is shown for webbrowsers with javascript disabled, so they can still login
	// This class will reposition the login menu and hides it using CSS, then it becomes a drop-down-fly-out menu
    $("#login").addClass('loginPositioned');

    // on click, toggle the login menu

    $("#btnLogin").click(p80jq_login_click_handler);
}

function p80jq_login_click_handler() {

    //toggle the login menu
    if (login_open == true) {
        p80jq_close_login();
    } else {
        p80jq_open_login();
    }
    return false;
}



function p80jq_open_login() {
	$("#login").slideDown("slow"); // Show the login menu
	$("#mainNav li.ikben_login").addClass('active'); // add the 'active' class on the menu item
	//$("body").bind('click', p80jq_close_login);
	login_open = true;
	return false;
}

function p80jq_close_login(e) {
	$("#login").slideUp('fast'); // Hide the login menu
	$("#mainNav li.ikben_login").removeClass('active'); // remove the 'active' class on the menu item
	//$("body").unbind('click', p80jq_close_login);
	login_open = false;
	return false;
}

/*	Toggle display of help-icon
============================================================= */

function p80jq_toggle_help_icon(){
	
	$(".iconHelp span").css().css("visibility", "hidden");
	
	$(".iconHelp img").hover(
		function () {
			$(this).next("span").css("visibility", "visible");
		}, 
		function () {
			$(this).next("span").css("visibility", "hidden");
		}
    );
}


/* Add a CSS class Win/IE 7 and lower, these browser versions don't understand CSS :focus
============================================================= */

function p80jq_input_focus() {
	// check specifically for Win/IE 7 and lower
	if ($.browser.msie && $.browser.version.substr(0,1)<8) {
		$("input[type='text'], input[type='password'], textarea").focus(function(){
			$("input[type='text'], input[type='password'], textarea").removeClass('inputFocus'); // first remove the class form all form fields
			$(this).addClass('inputFocus'); // add a css class (see ie_all.css) for the background color
		});
	}
}

/* Input :hover effect for Win/IE6
============================================================= */

function p80jq_input_hover() {
	// apply only for Win/IE6
	if ($.browser.msie && $.browser.version.substr(0,1) == 6) {
		$(".scaleButton input").hover(
			function () {
				$(this).addClass("inputButtonHover"); // mouse-over
			}, 
			function () {
				$(this).removeClass("inputButtonHover"); // mouse-out
			}
		);
	}
}

function MoreInfo(mainbundle_id, additionalbundle_id,ns_product_group,ns_product_id) {
	var url = '/ajax/BundleDetails.aspx';

	$.sitestatClick($.sitestatCode(ns_sitestatCodes.OrderStep.MoreInfo
	,	(additionalbundle_id == null ? 1 : 2)
	,	ns_product_id
	)); 

    if (mainbundle_id) {
        $.post(url, { mid: mainbundle_id, aid: additionalbundle_id }, function(data) {
            $("body").append(data);
            $(".btnClose").click(function() {
                $("#popup").remove();
                $(".dimmedOverlayType1").remove();
            });
        }, "html");
    }
}

var ShoppingCartCalls = new Array();
function SendShoppingCart(card_id, email) {
    var url = '/ajax/ShoppingCart.aspx';

    if (!ShoppingCartCalls[card_id] 
            && email != ''
            && email != $(".userCartEmail").attr('p80_org_formvalue')
       ) {
        ShoppingCartCalls[card_id] = true;
        $(".userCartEmailSendButton").addClass("disabled");
        $(".userCartEmail").val(labels["Processing"]);

        $.post(url, { cart_id: card_id, email: email }, function(data) {
            $("body").append(data);
            $(".btnClose").click(function() {
                $("#popup").remove();
                $(".dimmedOverlayType1").remove();

                //remove entered email address
                $(".userCartEmail").val($(".userCartEmail").attr('p80_org_formvalue'));
                $(".userCartEmailSendButton").removeClass("disabled");
                ShoppingCartCalls[card_id] = false;

                return false;
            });
        }, "html");
    } else {
        //
    }
    return false;
}

function AskBen(question,label) {
	var url = '/ajax/AskBen.aspx';
	if (question != null && question.replace(/\s+/g, "").length != 0 && question!=label) {
	    $.post(url, { question: question }, function(data) {
	        $("body").append(data);

            //fix select fields showing through popup's in IE6
	        if ($.browser.msie && $.browser.version.substr(0, 1) == 6) {
	            $("#popup").bgiframe();
	        }
	        
	        AskBenQuestion(question, $("#benAnwerParagraph").html());
	        $(".btnClose").click(function() {
	            $("#popup").remove();
	            $(".dimmedOverlayType1").remove();
	            return false;
	        });
	    });
	}
	return false;
}

function AskBenQuestion(question, label, sessionID) {
	var url = '/json/GetAnswerFromVirtualAgent';
	if (!question) { 
		return false;
	}
	$("#benAnwerParagraph").html(label);
	$.postSOAP(url, { question: question, sessionID: sessionID }, function(data) {
	    var session = data.SessionID;
	    $("#benQuestionParagraph").text(question);
	    $("#benAnwerParagraph").html(data.Text);
	    document.getElementById("askBenQuestionButton").onclick = function() {
	        var qst = $('#benQuestionInPopup').val();
	        $('#benQuestionInPopup').val('');
	        return AskBenQuestion(qst, label, session);
	    };
	    $("#benQuestionInPopup").keypress(function(e) {
	        var key = e.which ? e.which : e.keyCode;
	        if (key == 13) {
	            var qst = $('#benQuestionInPopup').val();
	            $('#benQuestionInPopup').val('');
	            return AskBenQuestion(qst, label, session);
	        }
	    });
	});
	return false;
}

function CallMe(ticket) {
	var url = '/popups/CallMe';
	$.post(url, { ticket: ticket }, function(data) {
		$("body").append(data);
		$("body").append($("#form1").html());
		$("#form1").remove();
		$("body title").remove();
		$("body div:has('#__VIEWSTATE')").remove();

		//fix select fields showing through popup's in IE6
		if ($.browser.msie && $.browser.version.substr(0, 1) == 6) {
		    $("#popup").bgiframe();
		}
		
		$(".btnClose").click(function() {
			$("#popup").remove();
			$("#dimmedOverlay").remove();
			return false;
		});
		$(".btnSend").click(function() {
			if ($('.popupForm').hasClass('formValidationError')) {
				$('.popupForm').removeClass("formValidationError");
			}
			$(".validationMessage span").each(function(index) {
				if (!$(this).hasClass("hide")) {
					$(this).addClass("hide");
				}
			})
			CallMeSend(ticket, $('#phoneNumber').val());
			return false;
		});
	});
	return false;
}

function CallMeSend(ticket,phone) {
	var url = '/popups/CallMe';
	$.postJSON(url, { ticket:ticket,phone: phone }, function(data) {
		$('#phoneNumber').val(phone);
		if (data.error != null) {
			if (!$('.popupForm').hasClass("formValidationError")) {
				$('.popupForm').addClass("formValidationError");
			}
			$('#phoneNumberMessage-' + data.error).removeClass('hide');
		}
		if (data.value != null) {
			$("#popup .body p").each(function(index) {
				$(this).toggleClass("hide");
			})
		}
	});
	return false;
}

/* Generic AJAX error handler, just shows an alert whenever an AJAX calls fails */
function benAjaxErrorHandler() {
    $("body").ajaxError(function(event, request, settings) {
        alert("Error requesting page " + settings.url + "");
    });
}

function getURLParam(strParamName) {
    var strReturn = "";
    var strHref = window.location.href;
    if (strHref.indexOf("?") > -1) {
        var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
        var aQueryString = strQueryString.split("&");
        for (var iParam = 0; iParam < aQueryString.length; iParam++) {
            if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1) {
                var aParam = aQueryString[iParam].split("=");
                strReturn = aParam[1];
                break;
            }
        }
    }
    return unescape(strReturn);
}

function hideIkBen(overwrite) {
    var loggedin = readCookie("ben_login");
    if (!loggedin || overwrite) {
        //Hide the "Ik Ben nav link"
    	$(".ikben_loginname").addClass("hide");
    	$(".ikben_loginname").unbind('click'); 
    } else {
        showIkBen(loggedin);
    }
}

function showIkBen(name) {
    var elmIkBen = top.document.getElementById("ben_naam");

    if (elmIkBen && name && name.length > 0) {
        name = name.substr(0, 1).toUpperCase() + name.substr(1);
        createCookie("ben_login", name);
        elmIkBen.innerHTML = name;
    }
    
    //Show the "Ik Ben nav link"
    $(".ikben_loginname").removeClass("hide");
    if (typeof(ns_ik_ben) != "undefined") {
        $(".ikben_loginname").click(ns_ik_ben);
    }
    SetLogout();
}

function LoggedOut() {

    eraseCookie("ben_login");
    hideIkBen(true);                //hide ikben menu item

    $("#btnLogin").html(labels["Login"]); //set link to logout text
    $("#btnLogin").attr('href', '/ikben');
    $("#btnLogin").click(p80jq_login_click_handler);
    if (typeof(ns_ik_ben_inloggen)  != "undefined") {
        $("#btnLogin").click(ns_ik_ben_inloggen);
    }
   }

function SetLogout() {
    $("#btnLogin").html(labels["Logout"]); //set link to logout text
    $("#btnLogin").attr('href', '/ikben/uitloggen');
    $('#btnLogin').unbind('click');        //remove click handler for the dropdown
    if (typeof (ns_ik_ben_uitloggen) != "undefined") {
        $("#btnLogin").click(ns_ik_ben_uitloggen);
    }


    //remove loggedin cookie when used logs out
    //Done by the Logout.aspx file
    /*
    $('#btnLogin').click(function() {
        LoggedOut();
    });
    */
}


function createCookie(name, value, minutes) {
    if (minutes) {
        var date = new Date();
        date.setTime(date.getTime() + (minutes * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

function Search(elm) {
    if (elm) {
        var input = $('#' + elm).val() || "";
        if (input.length > 0) {
            window.location.href = "/zoeken/" + UrlEncode(input);
        }
    }
    return false;
}

function UrlEncode(input) {
    var encodedInputString = escape(input);
    encodedInputString = encodedInputString.replace("+", "%2B");
    encodedInputString = encodedInputString.replace("/", "%2F");
    return encodedInputString;
}


// Used by Sidebar Iframe to arrange the modification of the TOP navigation items with login/logout functions
// Functions need to be performed at the TOP window as we're located within 2 iframes
function SetIFrameLogin() {
    if (getURLParam("login")) {
        top.window.showIkBen(getURLParam("login"));
    }
}

//function not used, if sidebar is passed parameter logout=1 we'll see nav items as logged out.. and re-enable login functions
function SetIFrameLogout() {
	var logout = getURLParam("logout");
    if (logout && logout == "1") {
        top.window.SetLogout();
    }
}


function orderChangeAdditionalBundles(mainbundleid) {

    if (mainbundleid && mainbundleid > 0) {
        $('input').filter(function() { return $(this).attr('p80_additional'); }).each(function() {

            if (orderBundleCombinations[mainbundleid].contains($(this).attr('p80_additional'))) {
                $(this).parents("tr").removeClass("hide");
                $(this).parents("tr").next().removeClass("hide");
            } else {
                $(this).parents("tr").addClass("hide");
                $(this).parents("tr").next().addClass("hide");
            }
        });
    }

}


function orderChangeMainBundleType(mainbundleid) {
    var radio = $(".formTable input[name='Step1ProductId']:checked");
    $(radio).parents("tbody").find("tr").removeClass("attention");
    $(radio).parents("tr").addClass("attention");
}

function orderHasChanged() {

    var currentMainBundleId = $(".formTable input[name='Step1ProductId']:checked").val() || "";
    var currentHandsetId = $(".formTable input[name='handsetId']:checked").val() || "";
    var currentAdditionalBundles = "";
    var additionalIds = new Array();
    
    if (currentMainBundleId && currentMainBundleId.length > 0) 
    {
        $(".formTable input[name='step2additionalbundle']").each(function() {
            if (orderBundleCombinations[currentMainBundleId].contains($(this).attr('p80_additional'))) {
                if ($(this).is(":checked") || $(this).is(":disabled")) {
                    additionalIds.push($(this).val());
                }
            }
        });

        currentAdditionalBundles = additionalIds.join(",");
    }
    
    var currentSelection = currentMainBundleId + ";" + currentAdditionalBundles + ";" + currentHandsetId;

    if (orginalOrderSelection != currentSelection) {
        orginalOrderSelection = currentSelection;
        return true;
    } else {
        return false;
    }
}

if (!Array.prototype.contains) {
    Array.prototype.contains = function(obj) {
        var len = this.length;
        for (var i = 0; i < len; i++) {
            if (this[i] == obj) { return true; }
        }
        return false;
    };
}


function OrderStepSubmitHandler() 
{
    $("table.formTable .orderButton, table.formTable .btnChange").click(function() {
        var res = $(this).attr('class').match(/btnChangeStep([A-Za-z0-9]+)|orderStepButton([A-Za-z0-9]+)/)
        var step = 0;
        var blChangeAction = false;
        var blSubmitAction = false;
        
        if (res && res.length > 1) {
            step = res[1] || res[2];
            blChangeAction = (res[1])?true:false;
            blSubmitAction = (res[2])?true:false;
        }
        
        //if we're not in the order confirmation then check if the bundle/additionalbundle/handset changed
        if (step > 0 && step != 5) {
            if (orderHasChanged()) {
                OrderUpdateCalculationSidebar();
            }
            
            if (blChangeAction) {
                // make sure Nummerbehoud step is validated when going to Personal information
                if (step == 4 && !OrderValidateStep(3)) {
                    ChangeStep(3,step);
                } else {
                    ChangeStep(step,step);
                }
                
            } else {
                switch (Number(step))
                {
                    //last page (check data), if everything is ok, do postback
                    case 4:
                        if (OrderValidateStep(step)) {
                            return true;
                        }
                        break;
                       
                    default:
                        GotoNextStep(step);
                        break;
                }
            }
        } else {
            //Other steps (order confirmation step let the submit continue
            return true;
        }
        return false;
    });
   }
   

function GotoNextStep(step) 
{
    var next = true;
    var next_step = step;
    
    //Step 3 (Numberporting) && Step 4 (Person info) have to be valid)
    if ((Number(step)==3 || Number(step)==4) && !OrderValidateStep(step)) {
        next = false;
    }
    
    if (next) {
        for (var i=0; i<StepsList.length+1;i++) {
            if (step == StepsList[i] && StepsList[i+1] != undefined) {
                next_step = StepsList[i+1];
                break;
            }
        }
    }
    NextStep(next_step);
}


function ChangeStep(step, stepSitestat) {

	$.sitestatClick($.sitestatCode(ns_sitestatCodes.OrderStep.Change,stepSitestat)); 
	ShowStep(step);
}

function NextStep(step)
{
	if (step != 5) {
		$.sitestatClick($.sitestatCode(ns_sitestatCodes.OrderStep.Next,step)); 
        ShowStep(step);
	} else {
	    $.sitestatClick($.sitestatCode(ns_sitestatCodes.OrderStep.Check, step)); 
	}
}

function ShowStep(step,phoneonly,message) {

    $('#custom-message').remove();

    if (!phoneonly) {
        //Make sure we have an main bundle, otherwise go back to step 1
        if (step > 1) {
            var checkbundle = $("input[name='Step1ProductId']:checked").val();
            if (!(checkbundle && checkbundle.split(";").length > 0)) {
                step = 1;
            }
        }
    } else {
        var handsetId = Number($(".formTable input[name='handsetId']:checked").val()) || 0;
        if (!handsetId || handsetId < 1) {
            step = 6;   //go back to "Select Handset step"
        }
    }

    for (var i = 1; i <= 7; i++) {
        var table = $(".tableStep" + i);
        if (i == step) {
            table.find("tr").not(":first, .bottomValidationStepErrors").removeClass("hide"); //show all fields from this step, ignore the header
            table.find("tfoot tr div").removeClass("hide"); //show the submit button
        } else {
            table.find("tr").not(":first").addClass("hide"); //hide all fields from this step (except the header)
            table.find("tfoot tr div").addClass("hide"); //hide the submit button
        }

        //if Step 2 is called then show only the additional bundles for this mainbundel
        if (step == 2) {
            var currentMainBundleId = $("input[name='Step1ProductId']:checked").val();
            orderChangeAdditionalBundles(currentMainBundleId);
        }

        if (step == 3) {
            OrderCustomRulesNumberPorting();
        }
    
        CurrentStep = String(step);

    }
    
    if (message) {
        OnloadHandsetLockedMessage(step,message);
    }
    
}

function OnloadHandsetLockedMessage(step,message) {
    $('#custom-message').remove();
    $(".tableStep"+step+" tbody td").prepend("<div id=\"custom-message\" style=\"display:none;\"><span class=\"message\">"+message+"</span></div>");
    $('#custom-message').slideDown('slow');
}


function OrderCustomRulesNumberPorting(currentstep) {

    var initialExpand = false;
    if (!currentstep || currentstep == 3) {
        initialExpand = true;
    }
    
    var NumberPorting = OrderQuestionGetValueByFieldName("NumberPorting");

    if (NumberPorting == "Nee") {
        //All affected fields optional/hide them
        /*
        PrivateOrBusiness
        SubscriptionOrPrepaid
        CurrentMobileNumber
        CurrentSimcardNumber
        CurrentCustomerNumber
        CurrentProvider
        EndDateCurrentSubscription
        SubscriptionAlreadyCancelled
        */

        OrderModifyQuestionProperties("PrivateOrBusiness", "Required", false);
        OrderModifyQuestionProperties("SubscriptionOrPrepaid", "Required", false);
        OrderModifyQuestionProperties("CurrentMobileNumber", "Required", false);
        OrderModifyQuestionProperties("CurrentSimcardNumber", "Required", false);
        OrderModifyQuestionProperties("CurrentCustomerNumber", "Required", false);
        OrderModifyQuestionProperties("CurrentProvider", "Required", false);
        OrderModifyQuestionProperties("EndDateCurrentSubscription", "Required", false);
        OrderModifyQuestionProperties("SubscriptionAlreadyCancelled", "Required", false);

        if (initialExpand) {
            OrderModifyQuestionVisibility("NumberPorting", true);
            OrderModifyQuestionVisibility("PrivateOrBusiness", false);
            OrderModifyQuestionVisibility("SubscriptionOrPrepaid", false);
            OrderModifyQuestionVisibility("CurrentMobileNumber", false);
            OrderModifyQuestionVisibility("CurrentSimcardNumber", false);
            OrderModifyQuestionVisibility("CurrentCustomerNumber", false);
            OrderModifyQuestionVisibility("CurrentProvider", false);
            OrderModifyQuestionVisibility("EndDateCurrentSubscription", false);
            OrderModifyQuestionVisibility("SubscriptionAlreadyCancelled", false);
        }
    } else {
        var SubscriptionOrPrepaid = OrderQuestionGetValueByFieldName("SubscriptionOrPrepaid");

        if (SubscriptionOrPrepaid != "Abonnement") {
            OrderCustomRulePrepaid(initialExpand);
        } else {
            OrderCustomRuleAbonnement(initialExpand);
        }
        OrderNumberPortingCustomerNumber(initialExpand);
    }
}

function OrderCustomRulePrepaid(initialExpand)
{
    var SubscriptionOrPrepaid = OrderQuestionGetValueByFieldName("SubscriptionOrPrepaid");

	if (SubscriptionOrPrepaid == "Prepaid") {

	    if (initialExpand) {
	        //SHOW ALL, except: SubscriptionAlreadyCancelled
	        OrderModifyQuestionVisibility("PrivateOrBusiness", true);
	        OrderModifyQuestionVisibility("SubscriptionOrPrepaid", true);
	        OrderModifyQuestionVisibility("CurrentMobileNumber", true);
	        OrderModifyQuestionVisibility("CurrentProvider", true);
	        OrderModifyQuestionVisibility("EndDateCurrentSubscription", true);

	        //SubscriptionAlreadyCancelled  	HIDE
	        OrderModifyQuestionVisibility("SubscriptionAlreadyCancelled", false);
	    }

	    //ALL REQUIRED except EndDateCurrentSubscription and SubscriptionAlreadyCancelled
	    OrderModifyQuestionProperties("PrivateOrBusiness", "Required", true);
	    OrderModifyQuestionProperties("SubscriptionOrPrepaid", "Required", true);
	    OrderModifyQuestionProperties("CurrentMobileNumber", "Required", true);
	    OrderModifyQuestionProperties("CurrentProvider", "Required", true);
	    OrderModifyQuestionProperties("SubscriptionAlreadyCancelled", "Required", false);
		
	    //EndDateCurrentSubscription 		OPTIONAL
	    OrderModifyQuestionProperties("EndDateCurrentSubscription", "Required", false);

	} else {
		OrderCustomRuleAbonnement(initialExpand);
	}
}

function OrderCustomRuleAbonnement(initialExpand)
{
    var SubscriptionAlreadyCancelled = OrderQuestionGetValueByFieldName("SubscriptionAlreadyCancelled");

    if (initialExpand) {
        //SHOW ALL
        OrderModifyQuestionVisibility("PrivateOrBusiness", true);
        OrderModifyQuestionVisibility("SubscriptionOrPrepaid", true);
        OrderModifyQuestionVisibility("CurrentMobileNumber", true);
        
        OrderModifyQuestionVisibility("CurrentProvider", true);
        OrderModifyQuestionVisibility("EndDateCurrentSubscription", true);
        OrderModifyQuestionVisibility("SubscriptionAlreadyCancelled", true);
    }
	
    //ALL Required, except EndDateCurrentSubscription
    OrderModifyQuestionProperties("PrivateOrBusiness", "Required", true);
    OrderModifyQuestionProperties("SubscriptionOrPrepaid", "Required", true);
    OrderModifyQuestionProperties("CurrentMobileNumber", "Required", true);
    OrderModifyQuestionProperties("CurrentProvider", "Required", true);
    OrderModifyQuestionProperties("SubscriptionAlreadyCancelled", "Required", true);
	

    if (SubscriptionAlreadyCancelled == "Ja") {
        //EndDateCurrentSubscription OPTIONAL
        OrderModifyQuestionProperties("EndDateCurrentSubscription", "Required", true);
    } else {
        //EndDateCurrentSubscription REQUIRED
        OrderModifyQuestionProperties("EndDateCurrentSubscription", "Required", false);
        if (initialExpand) {
            OrderModifyQuestionVisibility("EndDateCurrentSubscription", true);
        }
    }
}

function OrderNumberPortingChangeHandler() {

    $("select[name='order_SubscriptionOrPrepaid'], select[name='order_PrivateOrBusiness']").change(function() {
        OrderCustomRulesNumberPorting();
    });

    $("input[name='order_NumberPorting']").click(function() {
        OrderCustomRulesNumberPorting();
    });

    $("input[name='order_SubscriptionAlreadyCancelled']").click(function() {
        OrderCustomRulesNumberPorting();
    });

}

function OrderNumberPortingCustomerNumber(initialExpand) {
    var PrivateOrBusiness = OrderQuestionGetValueByFieldName("PrivateOrBusiness");

    if (initialExpand) {
        if (PrivateOrBusiness == "Particulier") { 
            OrderModifyQuestionVisibility("CurrentSimcardNumber", true);
            OrderModifyQuestionVisibility("CurrentCustomerNumber", false);
        } else if (PrivateOrBusiness == "Zakelijk") { 
            OrderModifyQuestionVisibility("CurrentSimcardNumber", false);
            OrderModifyQuestionVisibility("CurrentCustomerNumber", true);
        } else {
            OrderModifyQuestionVisibility("CurrentSimcardNumber", true);
            OrderModifyQuestionVisibility("CurrentCustomerNumber", true);
        }
    }

    if (PrivateOrBusiness == "Particulier") { 
        OrderModifyQuestionProperties("CurrentSimcardNumber", "Required", true);
        OrderModifyQuestionProperties("CurrentCustomerNumber", "Required", false);
    } else if (PrivateOrBusiness == "Zakelijk") { 
        OrderModifyQuestionProperties("CurrentSimcardNumber", "Required", false);
        OrderModifyQuestionProperties("CurrentCustomerNumber", "Required", true);
    } else {
        OrderModifyQuestionProperties("CurrentSimcardNumber", "Required", true);
        OrderModifyQuestionProperties("CurrentCustomerNumber", "Required", true);
    }

    
}


function OrderValidateStep(step) {

    //First perform any custom changes
    OrderCustomJSRules();
    
    var valid = true;
    for (var i = 0; i <= validQuestions.length; i++) {
        if (typeof (validQuestions[i]) == 'object' && validQuestions[i].Step == step) {
          var curr = OrderValidateQuestion(validQuestions[i]);
          valid = ((valid & curr)==1);
        }
    }
    
    if (valid) {
        valid = ValidateOrderStep(step);
    }

    var stepclass = ".tableStep" + step
    if (!valid) {
        $(stepclass + ' .bottomValidationStepErrors').removeClass("hide");
    } else {
        $(stepclass + ' .bottomValidationStepErrors').addClass("hide");
    }
    
    return valid;

}

function OrderGetQuestionAnswers(step) {
    var valid = true;
    var questionStep = [];
    
    for (var i = 0; i <= validQuestions.length; i++) {
        if (typeof (validQuestions[i]) == 'object' && validQuestions[i].Step == step) {
          var qObj = validQuestions[i];
          qObj.Value = OrderQuestionGetValue(qObj);
          questionStep.push(qObj);
        }
    }
    return questionStep;
}

function OrderGetQuestionObject(fieldname) {
    for (var i = 0; i <= validQuestions.length; i++) {
        if (typeof(validQuestions[i]) == 'object' && validQuestions[i].FieldName == fieldname) {
            return validQuestions[i];
        }
    }
}

function OrderValidateQuestion(qObj) {

    if (qObj) {
        var skip = false;
        var isValid = false;
        var value = OrderQuestionGetValue(qObj);
        var regex = new RegExp(qObj.RegEx, "");
        var lblPostfix = null;

        //don't validate special fields..
        switch (qObj.FieldName) {

            //special cases
            case 'HouseNumberAddition':
                skip = true;
                break;
                
            case "Nationality":
                if (value != null && value != '' && (typeof(identities[value]) != "undefined")) {
                    isValid = true;
                }
                break;
        }
        
        
        if (isValid || ((value == null || value == '') && !qObj.Required)) {
            isValid = true;
        }
        else if (value == null || value == '' || !regex.test(value)) {
            isValid = false;
        } else {
            isValid = true;
        }


        switch (qObj.FieldName) {
            case "RepeatEmailAddress":
                //EmailAddress && RepeatEmailAddress should be the same
                var emailObj = OrderGetQuestionObject("EmailAddress");
                var emailvalue = OrderQuestionGetValue(emailObj);
                if (value && isValid && value != emailvalue) {
                    isValid = false;
                    if (emailvalue) {
                        lblPostfix = "DifferentRepeatEmailAddress";
                    }
                }
                break;
                
            case "DateOfBirth":
                var day = $("select[name='order_" + qObj.FieldName + "_day'] option:selected").val();
                var month = $("select[name='order_" + qObj.FieldName + "_month'] option:selected").val();
                var year = $("select[name='order_" + qObj.FieldName + "_year'] option:selected").val();
                if (day || month || year) {
                    var date = new Date(year, month-1, day);
                    var compDate = new Date();
                    compDate.setFullYear(compDate.getFullYear() - 18);
                    compDate.setHours(0);
                    compDate.setMinutes(0);
                    compDate.setSeconds(0);
                    if (date > compDate) {
                        isValid = false;
                        lblPostfix = "OutsideAgeLimit";
                    }
                }
                break;

            case "IdentificationExpirationDate":
            case "BankCardExpirationDate":
                var day = $("select[name='order_" + qObj.FieldName + "_day'] option:selected").val();
                var month = $("select[name='order_" + qObj.FieldName + "_month'] option:selected").val();
                var year = $("select[name='order_" + qObj.FieldName + "_year'] option:selected").val();
                if (day || month || year) {
                    var date = new Date(year, month - 1, day);
                    var compDate = new Date();
                    compDate.setMonth(compDate.getMonth() + 1);
                    compDate.setHours(0);
                    compDate.setMinutes(0);
                    compDate.setSeconds(0);
                    compDate.setMilliseconds(0);
                    if (compDate > date ) {
                        isValid = false;
                        lblPostfix = "DateExpired";
                    }
                }
                break;

            case "EndDateCurrentSubscription":
                //EndDateCurrentSubscription > datum +1 maand (? misschien bij vraag validatie doen)
                if (isValid) {
                    var day = $("select[name='order_" + qObj.FieldName + "_day'] option:selected").val();
                    var month = $("select[name='order_" + qObj.FieldName + "_month'] option:selected").val();
                    var year = $("select[name='order_" + qObj.FieldName + "_year'] option:selected").val();
                
                    if (qObj.Required) {
                        var date = new Date(year, month - 1, day);
                        var compDate = new Date();
                        compDate.setMonth(compDate.getMonth() + 1);
                        compDate.setHours(0);
                        compDate.setMinutes(0);
                        compDate.setSeconds(0);
                        compDate.setMilliseconds(0);
                        if (compDate > date) {
                            isValid = false;
                        }
                    }
                    //if EndDateCurrentSubscription is optional but is filled in 
                    // then it should be a date in the future, can't do numberporting in the past
                    else if (value != null && value.length > 0) {
                        var date = new Date(year, month - 1, day);
                        var compDate = new Date();
                        compDate.setHours(0);
                        compDate.setMinutes(0);
                        compDate.setSeconds(0);
                        compDate.setMilliseconds(0);
                        if (compDate > date) {
                            isValid = false;
                        }
                    }
                }
                break;
                
        }
        

        if (isValid && !skip) {
            OrderRevalidateQuestion(qObj); 
        } else if (!skip) {OrderInvalidateQuestion(qObj,value,lblPostfix); }

        return (isValid || skip);
    }
    return true;
}

// Add error class from questions
function OrderInvalidateQuestion(qObj, value, lblPostfix) {
    if (qObj) {
        errorLabel = OrderGetErrorLabel(qObj, value, lblPostfix);
        OrderQuestionSetInvalid(qObj,value,errorLabel);
    }
}

function OrderQuestionSetInvalid(qObj, value, errorLabel) {
    if (qObj) {
        if (!errorLabel || errorLabel.length == 0) {
            errorLabel = OrderGetErrorLabel(qObj, value, null);
        }
        
        var input = OrderQuestionGetInputfield(qObj.FieldName);
        var tr = input ? input.parents("tr") : null;
        if (tr) {
            tr.addClass("formValidationError").addClass("jsOrderError");
            var finddiv = tr.find("div.validationMessage");
            if (!finddiv || finddiv.length > 0) {
                finddiv.find("span.message").text(errorLabel);
            } else {
                var errorDiv = "<div class=\"validationMessage\"><span class=\"message\">"+errorLabel+"</span></div>";
                tr.find("td:last").append(errorDiv);
            }
        }
    } 
}

//Remove error class from questions
function OrderRevalidateQuestion(qObj) {
    if (qObj) {
        var input = OrderQuestionGetInputfield(qObj.FieldName);
        var tr = input ? input.parents("tr") : null;
    
        //only remove error class if the error came from JS functions, otherwise if might have been some other error..
        //if (tr && tr.hasClass("jsOrderError")) {
        if (tr) {
            tr.removeClass("formValidationError").removeClass("jsOrderError");
            tr.find("div.validationMessage").remove();
        }
    } 
    return;
}

function OrderQuestionGetInputfield(fieldname) {
    for (var i = 0; i <= validQuestions.length; i++) {
        var qObj = validQuestions[i];

        if (typeof (qObj) == 'object' && qObj.FieldName == fieldname) {
            var tr = "";
            switch (qObj.RenderName) {
                case 'Nationality':
                case 'BankType':
                case 'Provider':
                case 'IdentificationType':
                case 'Enum_PrivateBusiness':
                case 'Enum_SubscriptionPrepaid':
                    tr = $("select[name='order_" + qObj.FieldName + "']");
                    break;

                case 'Zipcode':
                    tr = $("input[name='order_" + qObj.FieldName + "_letters']");
                    break;

                case 'Date':
                case 'Birthday':
                    tr = $("select[name='order_" + qObj.FieldName + "_day']");
                    break;

                default:
                    tr = $("input[name='order_" + qObj.FieldName + "']");
                    break;
            }
            return tr;
        }
    }
}


function OrderQuestionGetValue(qObj) {
    var value = null;
    if (qObj) {
        switch (qObj.RenderName) {

            //special cases  
            case 'Zipcode':
                value = $("input[name='order_" + qObj.FieldName + "_cijfers']").val() + $("input[name='order_" + qObj.FieldName + "_letters']").val();
                break;

            case 'Date':
            case 'Birthday':
                var day = $("select[name='order_" + qObj.FieldName + "_day'] option:selected").val();
                var month = $("select[name='order_" + qObj.FieldName + "_month'] option:selected").val();
                var year = $("select[name='order_" + qObj.FieldName + "_year'] option:selected").val();
                if (day || month || year) {
                    value = day + '-' + month + '-' + year;
                }
                break;
                
            //dropdowns  
            case 'Nationality':
            case 'BankType':
            case 'Provider':
            case 'IdentificationType':
            case 'Enum_PrivateBusiness':
            case 'Enum_SubscriptionPrepaid':
                value = $("select[name='order_" + qObj.FieldName + "'] option:selected").val();
                break;

            //radio buttons  
            case 'Enum_Salutation':
            case 'Enum_YesNo':
                value = $("input[name='order_" + qObj.FieldName + "']:checked").val();
                break;

            case 'HouseNumber':
            case 'Text':
                value = $("input[name='order_" + qObj.FieldName + "']").val();
                break;

        }
    }
    
    return value;
}


function OrderQuestionGetValueByFieldName(fieldname) {
    var qObj = OrderGetQuestionObject(fieldname);
    return OrderQuestionGetValue(qObj);
}


function OrderCustomJSRules() {

    //all uppers for initials
    $("input[name='order_Initials']").val($("input[name='order_Initials']").val().toUpperCase());
    
    //starts with uppercase
    $("input[name='order_Forename']").val($.toFirstUpper($("input[name='order_Forename']").val()));
    $("input[name='order_MiddleName']").val($("input[name='order_MiddleName']").val().toLowerCase());
    $("input[name='order_Lastname']").val($.toFirstUpper($("input[name='order_Lastname']").val()));
    $("input[name='order_CityName']").val($.toFirstUpper($("input[name='order_CityName']").val()));
    $("input[name='order_Maidenname']").val($.toFirstUpper($("input[name='order_Maidenname']").val()));
    
    //phone numbers must not contain '-'
    $("input[name='order_CurrentMobileNumber']").val($("input[name='order_CurrentMobileNumber']").val().replace('-', ''));
    $("input[name='order_TelephoneNumber']").val($("input[name='order_TelephoneNumber']").val().replace('-', ''));

}

function OrderModifyQuestionProperties(fieldname, key, value) {
    for (var i = 0; i <= validQuestions.length; i++) {
        var qObj = validQuestions[i];
        if (typeof (qObj) == 'object' && qObj.FieldName == fieldname) {
            qObj[key] = value;
            
            
            //Questions that are Required should get the "*" behind the label
            var endWithReq;
            var strReq = "*";
            var label = $(".formTable label[for='order_" + qObj.FieldName + "']");

            //label ends with Required indicator
            if (!(label.text().substr(label.text().length - strReq.length, label.text().length) == strReq)) {
                endWithReq = false;
            } else {
                endWithReq = true;
            }

            if (!endWithReq && qObj.Required) {
                label.text(label.text() + strReq);
            } else if (endWithReq && !qObj.Required) {
              label.text(label.text().substr(0, label.text().length - strReq.length));
          }
            
        }
    }
}

function OrderModifyQuestionVisibility(fieldname, visible) {

    var tr = OrderQuestionGetInputfield(fieldname);

    if (visible) {
        tr.parents("tr").removeClass("hide");
    } else {
        tr.parents("tr").addClass("hide");
    }
}


function IgnoreEnterHandler(e) {
    var key = e.which ? e.which : e.keyCode;
    var src = e.target ? e.target : e.srcElement;
    if (key == 13 && !$(src).is("textarea")) {
        return false;
    }
}

function OrderRepeatEmailAddress() {
    $("input[name='order_RepeatEmailAddress']").bind('cut copy paste', function(e) {
        return false;
    });    
}



function VirtueleMedewerkerHandler() {
    $("#benQuestion").keyup(function(e) {
        var key = e.which ? e.which : e.keyCode;
        if (key == 13) {
            $('.virtualmedewerkerlink').click();      
            $('#benQuestion').val("");                       
        }
    });
}

function OrderGetErrorLabel(qObj, value, lblPostfix) {
    var label = null;
    var postfix = lblPostfix || "InvalidFormat";
    if (qObj) {
        var fullLabel = "";
        if (qObj.Required && (!value || value.length == 0 || value=="")) {
            fullLabel = "Order."+qObj.FieldName+".RequiredField";
        } else {
            fullLabel = "Order." + qObj.FieldName + "." + postfix;
        }
        
        if (typeof(labels[fullLabel])!= "undefined") {
          label = labels[fullLabel];
        }

        //if we cant find the specific label or the label has nog been filled then show the default label
        if (!label || label.substr(0,"[new ".length)=="[new ") {
            label = labels["InvalidFormat"].replace("{0}", qObj.ShortPresentationName.toLowerCase());
        }        
    }
    return label;
}

function TextImage() {
    $('#contentWrapper div.downloadList a').textimage({ tag: 'bullet', extension: 'png', width: 575, height: 30 });
}


(function($){
    $.fn.textimage = function(options) {
    var defaults = {
        width: null,
        height: null,
        dir: "/img",
        tag: "h1",
        extension: "gif"
    };
    
    var options = $.extend(defaults, options);
    $(this).each(function(){
        var text  = $(this).html();
        var img = '<img src="'+options.dir+'/'+options.tag+'/'+escape(text)+'.'+options.extension+'" width="'+options.width+'" height="'+options.height+'" alt="'+text+'" />';
        $(this).html(img);
    });
    return this;
    };
})(jQuery);

function showPhonePopup(alias) {
    var url = '/ajax/PhoneDetails.aspx';

    if (alias) {
        $.post(url, { alias: alias }, function(data) {
            $("body").append(data);
            $(".btnClose").click(function() {
                $("#popup").remove();
                $(".dimmedOverlayType1").remove();
            });
        }, "html");
    }
}

function showPhoneReminder(handset_id) {
    var url = '/ajax/PhoneReminder.aspx';

    if (handset_id) {
        $.post(url, { handset_id: handset_id }, function(data) {
            $("body").append(data);
            $(".btnClose").click(function() {
                $("#popup").remove();
                $(".dimmedOverlayType1").remove();
            });
		    $(".btnSend").click(function() {
		        savePhoneReminder(handset_id, $("#popup input[name='email']").val());
			});
			
        }, "html");
    }
}

function savePhoneReminder(handset_id, email) {
    var url = '/xml/savePhoneReminder';

    var regex = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/
    if (handset_id && regex.test(email)) {
        $.postSOAP(url, { handset_id: handset_id, email: email }, function(data) {
            if (data == true) {
                $("#popup").remove();
                $(".dimmedOverlayType1").remove();
                return false;
            } else {
                $("#popup .validationMessage").removeClass("hide");
            }
        });
    } else {
        $("#popup .validationMessage").removeClass("hide");    
    }
}

function showPhonePicture(picture,imgClass) {
    if (picture) {
        imgClass = imgClass ? imgClass : "productImgBig";
        $('.'+imgClass).attr('src',picture);
    }
    return false;
}

function showMorePhones() {
    $('.more_phones_link').remove();
    $('.hidden_more_phones').show();
    $("div.line").show();
    return false;    
}

function showPopupOrderLogin(action) {
    var url = '/ajax/OrderPopup.aspx';
    
    if (!action) {
        action = "choose";
    }

    $.post(url, { action: action }, function(data) {
        if ($(data).find("#unlocked").length > 0) {
            return true;
        }
        else if ($(data).find("#redirectto").length > 0) {
            window.location.href = $(data).find("#redirectto").text();
            return false;
        } else {
            $("body").append(data);
            $(".btnClose").click(function() {
                $("#popup").remove();
                $(".dimmedOverlayType1").remove();
                var tmp = showPopupOrderLogin("close");
                return false;
            });
        }
    }, "html");
    return false;
}

function LoginCustomer(phone,password) {
    if (phone && password) {
        var url = '/ajax/LoginCustomer.aspx';
        $.post(url, { Phone: phone, Password: password}, function(data) {
            if (data.Result == true) {
                window.location.href = data.RedirectTo;
            }  else {
                $(".popupShowLogin").show();
                $(".popupShowLogin p.validationMessage").text(data.Message);
                $(".popupShowLogin input").addClass("validationError");
            }
        },"json");
    }
}

function UpdateCustomer(phone,email) 
{
    var success = false;
    
    if (phone && email) 
    {
        var url = '/ajax/UpdateCustomer.aspx';
    
        $.ajax({
          global: false,
          async: false,
          type: 'POST',
          url: url,
          data:  { PhoneNumber: phone, EmailAddress: email},
          dataType: "json",
          success: updateCustomerSuccessHandler,
          error: function() {
                success = false;
            
                var url = '/ajax/OrderPopup.aspx';
                $.post(url, { Action: 'error_message', error_message: labels["PhoneOnlyCustomer.NoCustomer"]}, function(data) 
                {
                    $("body").append(data);
                    $(".btnClose").remove();            //remove the close button!
                    showPopupOrderLogin("close");       //and unlock the phone
                });
          }
        });
    }  
    return success;
}

function updateCustomerSuccessHandler(data) 
{
    if (data.Result == true && data.Customer != null) 
    {
        success = true;

        var email = $(".formTable input[name='email']");
        var tel = $(".formTable input[name='telefoonnummer']");
        
        tel.attr("ben_org",data.Customer.TelephoneNumber);
        tel.val(tel.attr("ben_org"));
        
        email.attr("ben_org",data.Customer.EmailAddress);
        email.val(email.attr("ben_org"));
    } else {
        success = false;

        var url = '/ajax/OrderPopup.aspx';
        $.post(url, { Action: 'error_message', error_message: labels["PhoneOnlyCustomer.NoCustomer"]}, function(data) {
            $("body").append(data);
            $(".btnClose").remove();    //remove the close button!
            showPopupOrderLogin("close");   //and unlock the phone
        });
    }
}

function SendForgottenPassword(phone) 
{
    var success = true;
    var message = "";
    
    if (phone) 
    {
        phone = phone.replace(/[- +()]+/ig,"");
        var url = '/ajax/SendForgottenPassword.aspx';
        var data = $.ajax({
          global: false,
          cache: false,
          async: false,
          type: 'POST',
          url: url,
          data:  { PhoneNumber: phone},
          dataType: 'json',
          success: function(data) {
            success = (data && data.Result == true);
            message = data.Message;
          },
          error:  function(data) {
            success = false;
            message = labels["SendPasswordReminder.Failed"];
          }
        });
                    
    } else {
        success = false;
        message = labels["PhoneNumber.Invalid"];
    } 
    
    if (success == false) {
        $('p.messagearea').text(message);
        $("p.messagearea").addClass("validationMessage");
        $("#popupCustomerPhoneNumber").addClass("validationError");
    } else {
        $('p.messagearea').text(message);
        $("p.messagearea").removeClass("validationMessage");
        $("#popupCustomerPhoneNumber").removeClass("validationError");
    }
    
    return success;
}


function PhoneOnlyCustomerShowStepHandler() {

    $('.btnChangeStep6').click(function() {
        if (orderHasChanged()) {
            OrderUpdateCalculationSidebar(true);
        }
        ShowStep(6,true);
        return false;
    });

    $('.btnChangeStep7').click(function() {
        if (orderHasChanged()) {
            OrderUpdateCalculationSidebar(true);
        }
        ShowStep(7,true);
        return false;
    });

    //toestel submit
    $('.orderStepButton6').click(function() {
        if (orderHasChanged()) {
            OrderUpdateCalculationSidebar(true);
        }
        ShowStep(7,true);
        return false;
    });

    //customer data submit
    $('.orderStepButton7').click(function(){
        if (orderHasChanged()) {
            OrderUpdateCalculationSidebar(true);
        }
    
        var isvalid = true;
        
        var email = $(".formTable input[name='email']");
        var tel = $(".formTable input[name='telefoonnummer']");
        
        //email or phonenumber changed
        if (email.val() != email.attr("ben_org") || tel.val() != tel.attr("ben_org") ) 
        {
            if (email.val().length < 2){
                email.parents("tr").addClass("formValidationError");
                email.next("div.validationMessage").show();
                isvalid = false;
            } else {
                email.parents("tr").removeClass("formValidationError");
                email.next("div.validationMessage").hide();
            }
            
            if (tel.val().length < 10){
                tel.parents("tr").addClass("formValidationError");
                tel.next("div.validationMessage").show();
                isvalid = false;
            } else {
                tel.parents("tr").removeClass("formValidationError");
                tel.next("div.validationMessage").hide();
            }
            
            if (isvalid) {
                isvalid = UpdateCustomer(tel.val(),email.val());
            }
        }

        var accepted = $(".formTable input[name='acceptedTerms']");
        if (accepted.val()==undefined || !accepted.is(":checked")){
            isvalid = false;
            accepted.parents("p").next("p").show();
        } else {
            accepted.parents("p").next("p").hide();
        }
        
        return isvalid;
    });
}


function OrderChangeInitialProduct(initialProduct) 
{
    var url = '/ajax/OrderChangeInitialProduct.aspx';
    var data = $.ajax({
                  async: false,
                  type: 'POST',
                  url: url,
                  data:  { InitialProduct: initialProduct},
                  dataType: "json",
                  success: function(json){  
                                if (json && json.Result == true) {
                                    window.location.href = json.RedirectTo;
                                }
                           }
                });
}

function ValidateOrderStep(step)
{
    var validStep = true;
    var questions = OrderGetQuestionAnswers(step);

    if (questions && questions.length > 0) {
        var json = JSON.stringify(questions);
        var url = '/ajax/ValidateOrderStep.aspx';
        ajaxLoading()
//IE fix for showing the please wait popup, but kills the ajax response in Firefox on big pages ??        
//        setTimeout(function() {
        var res = $.ajax({
          async: false,
          timeout: 100000,
          global: false,
          type: 'POST',
          url: url,
          data:  {'Questions': json, 'Step': step},
          dataType: "json",
          error: function() {
                    ajaxUnload();
                 }
        });
        
        eval('var e='+res.responseText); 
        if (e && e.InvalidQuestions) {
            $(e.InvalidQuestions).each(function() {
                if (this.Step == step) {
                    validStep = false;
                    OrderQuestionSetInvalid(this,this.Value,this.ErrorMessage);
                }
            });
        }
//        }, 10);
    }
    ajaxUnload();
    
    return validStep;
}

var blLoading = false;
function ajaxLoading()
{
    if (!blLoading) {
        blLoading = true;
        var overlay = $('<div class="dimmed" id="dimmedOverlay">&nbsp;</div>');
        var title = labels["Ajax.Loading.Title"];
        var text  = labels["Ajax.Loading.Text"];
        var loading = $('<div class="popupConfirmation" id="popup"><div class="header"><h3><img alt="" src="/img/h3/'+title+'.png" width="350" height="31"><span class="hide">'+title+'</span></h3></div><div class="body"><p>'+text+'</p></div></div>');
		$('body').append(overlay);
		$('body').append(loading);
		$("#popup").center(true);
    }
}
function ajaxUnload() {
        $('#dimmedOverlay').remove();
        $('#popup').remove();
        blLoading = false;
}

function OrderUpdateCalculationSidebar(phoneonly) {
    var rawparams = orginalOrderSelection.split(";");
    mainbundleid = rawparams[0] || "";
    additionalbundles = rawparams[1] || "";
    handsetid = rawparams[2] || "";

    var url = '/ajax/OrderChange.aspx';
    $.post(url, { mainbundleid: mainbundleid
                    , additionalbundles: additionalbundles
                    , handsetid: handsetid 
                    , disablehandset: true
                    , phoneonly: phoneonly
                 }, function(data) {
        $(".userCart div.body").html($("div.body",data).html());
        
        //added any extra javascript to remove sold out handsets..
        if ($("div#script_tag",data).length > 0) {
            $("body").append($("div#script_tag",data).html());
        }
    },"html");
}

function OrderDisableHandset(handset_id,step_number,phoneonly,message) 
{
    //var blCurrentlySelected = (handset_id == $(".formTable input[name='handsetId']:checked").val());
    if ($("div.shopRow #handsetId_"+handset_id).length > 0) {
        $("div.shopRow #handsetId_"+handset_id).attr('disabled', true);
        $("div.shopRow #handsetId_"+handset_id).attr('checked', false);
    } 
    
    //call orderHasChanged() to record the new handsetid
    var changed = orderHasChanged();    
    
    if ($("div.shopRow #handsetId_0").length > 0) {
        $("div.shopRow #handsetId_0").attr('checked', true);
    }
    
    ShowStep(step_number,phoneonly,message);
}


/* jQuery center div plugin */
jQuery.fn.center = function (absolute) {
    return this.each(function () {
        var t = jQuery(this);

        t.css({
            position:    absolute ? 'absolute' : 'fixed', 
            left:        '50%', 
            top:        '50%'
        }).css({
            marginLeft:    '-' + (t.outerWidth() / 2) + 'px', 
            marginTop:    '-' + (t.outerHeight() / 2) + 'px'
        });

        if (absolute) {
            t.css({
                marginTop:    parseInt(t.css('marginTop'), 10) + jQuery(window).scrollTop(), 
                marginLeft:    parseInt(t.css('marginLeft'), 10) + jQuery(window).scrollLeft()
            });
        }
    });
};