// For SMB order form, step 2

function contactAsUser(isChecked, cellphone, fname, lname, bdate, email){
        if(isChecked){
                document.getElementById('CELLPHONE').value = cellphone;
                document.getElementById('FIRSTNAME').value = fname;
                document.getElementById('LASTNAME').value = lname;
                document.getElementById('BIRTHDAY').value = bdate;
                document.getElementById('EMAIL').value = email;
        }else{
                document.getElementById('CELLPHONE').value = '';
                document.getElementById('FIRSTNAME').value = '';
                document.getElementById('LASTNAME').value = '';
                document.getElementById('BIRTHDAY').value = '';
                document.getElementById('EMAIL').value = '';
        }
}

function showHide_element(id) {
        var element = document.getElementById(id);

        if (element.style.display == 'none') {element.style.display = ''; }
        else {element.style.display = 'none';}
}

function hide_element(idHide) {
        var element = document.getElementById(idHide);

        if (element.style.display =='') {element.style.display = 'none'; }
}

function show_element(idShow) {
        var element = document.getElementById(idShow);

        if (element.style.display =='none') {element.style.display = ''; }
}



// ORDERFORM - Front page order form functionality

var currentProduct;
var choosenSubscription;
var currentSubscription;

//swfObject variables passed to flash
var siteRoot = "http://www.onecall.no/";
var readMoreURL = "abonnementinfo.php?content=article";

// var siteRoot = "http://dev.plastikk.no/onecall_2-0/";
// var readMoreURL = "index.php?content=article";
var flashvars = {}; 
flashvars.siteRoot = siteRoot;
//flashvars.readMoreURL = readMoreURL;

// Emulate menu click
function activateSubscription(subscriptionId) {
	showCampaignElement(subscriptionId);
	$('#orderform #' + subscriptionId).click();
	$('#leftmenu #' + subscriptionId).click();
	$('#phoneinput').focus();
}

function order_addservice(servicename, sid, checksum, elementid){
        $(document).ready(function(){
                $.get("ajaxfunctions.php", { func: "order_addservice", subscriber: sid, cs: checksum, thisservice: servicename }, function(data){$("#"+elementid).html(data);}, "html");
        });
}


// gull nummer and nytt nummer renewals
function refresh_numbers(neworgold, elementid){
        $(document).ready(function(){
                $.get("gullognyttnummer.php", { func: "get_msisdnnumbers", criteria: neworgold ,jj : elementid }, function(data){$("#"+elementid).html(data);}, "html");
        });
}




// Show campaign element based on selected subscription type
function showCampaignElement(campaignId) {
	
	// If mid_orderform isn't displayed
	// if ($("#orderform .mid_orderform").css("display") == "none") {}
	$('#campain_field_over').fadeIn();
	var display = false;
	var html;
	var $campain_field = $('#campain_field');
	var $campaign_prod = $('#campaign_prod');

		switch(campaignId) {
			case '_input_privat' :
				break;
			case '_input_privat_full_pakke' :
				if (currentProduct != 0) {
					if (isOpera || !flashEnabled) {
						$campaign_prod.empty();
						$campaign_prod.html('<div class="order_btn" href=""></div><a class="readmore_btn" href="' + readMoreURL + "&param=" + campaignId + '"></a>');
						$("#campaign_prod .order_btn").click(function() {
							activateSubscription(campaignId);
						});
						$campaign_prod.css("background-image","url(" + siteRoot + "img/campaign/campaign_prod_fullpakke.jpg)");
					} else {
						flashvars.readMoreURL = (readMoreURL + "%26param=" + campaignId); //specify url here
						swfobject.embedSWF(siteRoot + "flash/campaign_prod_fullpakke.swf", "campaign_prod", "696", "338", "9.0", "http://www.onecall.no/flash/expressinstall.swf",flashvars,{wmode:"opaque"},{});
					}
				}
				currentProduct = 0;
				break;
			case '_input_privat_mobil_aktiv' :
				if (currentProduct != 1){
					if (isOpera || !flashEnabled) {
						$campaign_prod.empty();
						$campaign_prod.html('<div class="order_btn" href=""></div><a class="readmore_btn" href="' + readMoreURL + "&param=" + campaignId + '"></a>');
						$("#campaign_prod .order_btn").click(function() {
							activateSubscription(campaignId);
						});
						$campaign_prod.css("background-image","url("+siteRoot+"img/campaign/campaign_prod_aktiv.jpg)");
					} else {
						flashvars.readMoreURL = readMoreURL + "%26param=mobilaktiv"; //specify url here
						swfobject.embedSWF(siteRoot + "flash/campaign_prod_aktiv.swf", "campaign_prod", "696", "338", "9.0", "http://www.onecall.no/flash/expressinstall.swf",flashvars,{wmode:"opaque"},{});
					}
				}
				currentProduct = 1;
				break;
			case '_input_privat_mobil_faktura' :
				if (currentProduct != 2) {
					if (isOpera || !flashEnabled) {
						$campaign_prod.empty();
						$campaign_prod.html('<div class="order_btn" href=""></div><a class="readmore_btn" href="' + readMoreURL + "&param=" + campaignId + '"></a>');
						$("#campaign_prod .order_btn").click(function() {
							activateSubscription(campaignId);
						});
						$campaign_prod.css("background-image","url("+siteRoot+"img/campaign/campaign_prod_faktura.jpg)");
					} else {
						flashvars.readMoreURL = (readMoreURL + "%26param=" + campaignId); //specify url here
						swfobject.embedSWF(siteRoot + "flash/campaign_prod_faktura.swf", "campaign_prod", "696", "338", "9.0", "http://www.onecall.no/flash/expressinstall.swf",flashvars,{wmode:"opaque"},{});
					}
				}
				currentProduct = 2;
				break;
			case '_input_privat_mobil_kontant' :
				if (currentProduct != 3) {
					if (isOpera || !flashEnabled) {
						$campaign_prod.empty();
						$campaign_prod.html('<div class="order_btn" href=""></div><a class="readmore_btn" href="' + readMoreURL + "&param=" + campaignId + '"></a>');
						$("#campaign_prod .order_btn").click(function() {
							activateSubscription(campaignId);
						});
						$campaign_prod.css("background-image","url("+siteRoot+"img/campaign/campaign_prod_kontant.jpg)");
					} else {
						flashvars.readMoreURL = (readMoreURL + "%26param=" + campaignId); //specify url here
						swfobject.embedSWF(siteRoot + "flash/campaign_prod_kontant.swf", "campaign_prod", "696", "338", "9.0", "http://www.onecall.no/flash/expressinstall.swf",flashvars,{wmode:"opaque"},{});
					}
				}
				currentProduct = 3;
				break;
			case '_input_privat_mobilt_bredbaand_paa_tur' :
				if (currentProduct != 4) {
					if (isOpera || !flashEnabled) {
						$campaign_prod.empty();
						$campaign_prod.html('<div class="order_btn" href=""></div><a class="readmore_btn" href="' + readMoreURL + "&param=" + campaignId + '"></a>');
						$("#campaign_prod .order_btn").click(function() {
							activateSubscription(campaignId);
						});
						$campaign_prod.css("background-image","url("+siteRoot+"img/campaign/campaign_prod_mobilt_bredband.jpg)");
					} else {
						flashvars.readMoreURL = (readMoreURL + "%26param=" + campaignId); //specify url here
						swfobject.embedSWF(siteRoot + "flash/campaign_prod_mobilt_bredband.swf", "campaign_prod", "696", "338", "9.0", "http://www.onecall.no/flash/expressinstall.swf",flashvars,{wmode:"opaque"},{});
					}
				}
				currentProduct = 4;
				break;
			case '_input_privat_xxl' :
				if (currentProduct != 5) {
					if (isOpera || !flashEnabled) {
						$campaign_prod.empty();
						$campaign_prod.html('<div class="order_btn" href=""></div><a class="readmore_btn" href="' + readMoreURL + "&param=" + campaignId + '"></a>');
						$("#campaign_prod .order_btn").click(function() {
							activateSubscription(campaignId);
						});
						$campaign_prod.css("background-image","url("+siteRoot+"img/campaign/campaign_prod_xxl.jpg)");
					} else {
						flashvars.readMoreURL = (readMoreURL + "%26param=" + campaignId); //specify url here
						swfobject.embedSWF(siteRoot+"flash/campaign_prod_xxl.swf", "campaign_prod", "696", "338", "9.0", "http://www.onecall.no/flash/expressinstall.swf",flashvars,{wmode:"opaque"},{});
					}
				}
				currentProduct = 5;
				break;
			case '_input_privat_folkepakka' :
				if (currentProduct != 6) {
					if (isOpera || !flashEnabled) {
						$campaign_prod.empty();
						$campaign_prod.html('<div class="order_btn" href=""></div><a class="readmore_btn" href="' + readMoreURL + "&param=" + campaignId + '"></a>');
						$("#campaign_prod .order_btn").click(function() {
							activateSubscription(campaignId);
						});
						$campaign_prod.css("background-image","url("+siteRoot+"img/campaign/campaign_prod_folkepakka.jpg)");
					} else {
						flashvars.readMoreURL = null;
						flashvars.readMoreURL = (readMoreURL + "%26param=" + campaignId); //specify url here
						swfobject.embedSWF(siteRoot+"flash/campaign_prod_folkepakka.swf", "campaign_prod", "696", "338", "9.0", "http://www.onecall.no/flash/expressinstall.swf",flashvars,{wmode:"opaque"},{});
					}
				}
				currentProduct = 6;
				break;
			case '_input_bedrift_paa_jobben' :
				if (currentProduct != 7) {
					if (isOpera || !flashEnabled){
						$campaign_prod.empty();
						$campaign_prod.html('<div class="order_btn" href=""></div><a class="readmore_btn" href="' + readMoreURL + "&param=" + campaignId + '"></a>');
						$("#campaign_prod .order_btn").click(function() {
							activateSubscription(campaignId);
						});
						$campaign_prod.css("background-image","url("+siteRoot+"img/campaign/campaign_prod_paa_jobben.jpg)");
					} else {
						flashvars.readMoreURL = null;
						flashvars.readMoreURL = (readMoreURL + "%26param=" + campaignId); //specify url here
						swfobject.embedSWF(siteRoot+"flash/campaign_prod_paa_jobben.swf", "campaign_prod", "696", "338", "9.0", "http://www.onecall.no/flash/expressinstall.swf",flashvars,{wmode:"opaque"},{});
					}
				}
				currentProduct = 7;
				break;
			default:
				break;
		}

		if (display) {
			if ($.browser.msie) {
				$('#campain_field_over').fadeOut(); // Only non-alpha images, otherwise use show
			} else {
				$('#campain_field_over').fadeOut();
			}
		}
	}

	// POPUP
	// Show popups - Texts are loaded from php files
	function showPopup(questionMark) {

		if (questionMark.hasClass("privat_help")) {
			$("#orderform_popup").load("inc/helptext/privat_help.php");
		}
		/*
		else if (questionMark.hasClass("bedrift_help")) {
			$("#orderform_popup").html("<div><h3>Hjelp til bedriftsabonnement</h3><p>Nulla tristique, purus eu molestie elementum, diam enim dignissim orci, sit amet lobortis leo odio eget arcu. Cras tincidunt eros non quam. Praesent tempus, orci eu facilisis iaculis, tellus nulla iaculis eros, id sagittis sapien odio eget nulla. Morbi lacus. Vivamus interdum diam ultricies sapien. Nam auctor semper felis. Curabitur laoreet ipsum ac metus. Vestibulum congue urna ac purus tempor scelerisque. Nullam mauris mauris, convallis in, lobortis ac, laoreet quis, sapien. Aliquam fringilla lorem et tortor. Duis quis eros. Cras nisl. Suspendisse non velit. Integer mollis iaculis massa. Proin sodales adipiscing quam. Donec venenatis, felis eu commodo feugiat, leo libero rutrum mauris, quis iaculis elit sapien non ante. Aenean quis metus. Donec sed mi ut metus lobortis dapibus. Aliquam eget lorem vel eros tristique eleifend. </p></div>");
		}
		*/
	
		else if (questionMark.hasClass("address_help")) {
			$("#orderform_popup").load("inc/helptext/address_help.php");
		}
	
		else if (questionMark.hasClass("birthnumber_help")) {
			$("#orderform_popup").load("inc/helptext/birthnumber_help.php");

		}
	
		else if (questionMark.hasClass("email_help")) {
			$("#orderform_popup").load("inc/helptext/email_help.php");
		}
	
		else if (questionMark.hasClass("creditcard_help")) {
			$("#orderform_popup").load("inc/helptext/creditcard_help.php");
		}
	
		else if (questionMark.hasClass("invoice_help")) {
			$("#orderform_popup").load("inc/helptext/invoice_help.php");
		}
	
		else if (questionMark.hasClass("invoice_mail_help")) {
			$("#orderform_popup").load("inc/helptext/invoice_mail_help.php");
		}
	
		else if (questionMark.hasClass("invoice_email_help")) {
			$("#orderform_popup").load("inc/helptext/invoice_email_help.php");
		}
	
		else if (questionMark.hasClass("creditcard_type_help")) {
			$("#orderform_popup").load("inc/helptext/creditcard_type_help.php");
		}
	
		else if (questionMark.hasClass("cardnumber_help")) {
			$("#orderform_popup").load("inc/helptext/cardnumber_help.php");
		}
	
		else if (questionMark.hasClass("expiry_date_help")) {
			$("#orderform_popup").load("inc/helptext/expiry_date_help.php");
		}
	
		else if (questionMark.hasClass("cvv2_help")) {
			$("#orderform_popup").load("inc/helptext/cvv2_help.php");
		}

		else if (questionMark.hasClass("terms_help")) {
			$("#orderform_popup").load("inc/helptext/terms_help.php");
		}

 else if (questionMark.hasClass("getnumber")) {
                        $("#orderform_popup").load("inc/helptext/nyttnummer_help.php");
                }
 else if (questionMark.hasClass("goldennumber")) {
                        $("#orderform_popup").load("inc/helptext/gullnummer_help.php");
                }




		else {
			$("#orderform_popup").html("<div><h3>Hjelp til utfylling</h3><p></p></div>");
		}
	
		if ($.browser.msie) {
			$("#orderform_popup").show();
		} else {
			$("#orderform_popup").fadeIn();
		}
	}


/********************
* PRIVATE FUNCTIONS *
********************/
$(document).ready(function() {


	// Vars
	var orgNumberOrigVal, orgNameOrigVal, firstNameOrigVal, lastNameOrigVal, addressOrigVal, zipCodeOrigVal, placeOrigVal, birthDateOrigVal, birthNumberOrigVal, contactPhoneOrigVal, emailOrigVal, confirmEmailOrigVal, cardNumberOrigVal, expiryDateOrigVal, cvv2OrigVal;

	// jQuery object references reducing DOM traversal
	var $orgnumber_input = $('#orderform .mid_orderform .orgnumber_input');
	var $orgname_input = $('#orderform .mid_orderform .orgname_input');
	var $firstname_input = $('#orderform .mid_orderform .firstname_input');
	var $lastname_input = $('#orderform .mid_orderform .lastname_input');
	var $address_input = $('#orderform .mid_orderform .address_input');
	var $zipcode_input = $('#orderform .mid_orderform .zipcode_input');
	var $place_input = $('#orderform .mid_orderform .place_input');
	var $birthdate_input = $('#orderform .mid_orderform .birthdate_input');
	var $birthnumber_input = $('#orderform .mid_orderform .birthnumber_input');
	var $contactphone_input = $('#orderform .mid_orderform .contactphone_input');
	var $email_input = $('#orderform .mid_orderform .email_input');
	var $confirm_email_input = $('#orderform .mid_orderform .confirm_email_input');


	// ERROR MESSAGE
	function displayError(errorTxt) {
		$("#error_messages").text(errorTxt);
		$("#error_messages").fadeIn("slow");
		setTimeout("$('#error_messages').fadeOut('slow')", 6000);
	}

	// Hide popup
	function hidePopup() {
		if ($.browser.msie) {
			$("#orderform_popup").hide();
		} else {
			$("#orderform_popup").fadeOut();
		}
	}

	// Show or hide input text fields based on selected subscription type
	function toggleInputFields(id) {
		switch (id) {

			case '_input_privat' :
				$('#orderform .left_orderform .number_chooser').hide();
				$('.subscription_chooser').show();

				break;

			case '_input_privat_full_pakke' :
			case '_input_privat_mobil_aktiv' :
			case '_input_privat_mobil_faktura' :
			case '_input_privat_xxl' :
			case '_input_privat_folkepakka' :
				$('#orderform .left_orderform .number_chooser').show();
				$('.subscription_chooser').hide();
				$orgnumber_input.hide();
				$orgname_input.hide();
				$firstname_input.show();
				$lastname_input.show();
				$address_input.show();
				$zipcode_input.show();
				$place_input.show();
				$birthdate_input.hide();
				$birthnumber_input.show();
				$contactphone_input.hide();
				$email_input.show();
				$confirm_email_input.show();
				break;

			case '_input_privat_mobilt_bredbaand_paa_tur' :
				$('#orderform .left_orderform .number_chooser').hide();
				$('.subscription_chooser').hide();
				$orgnumber_input.hide();
				$orgname_input.hide();
				$firstname_input.show();
				$lastname_input.show();
				$address_input.show();
				$zipcode_input.show();
				$place_input.show();
				$birthdate_input.hide();
				$birthnumber_input.show();
				$contactphone_input.hide();
				$email_input.show();
				$confirm_email_input.show();
				break;

			case '_input_bedrift_paa_jobben' :
				$('#orderform .left_orderform .number_chooser').show();
				$('.subscription_chooser').hide();
				$orgnumber_input.show();
				$orgname_input.show();
				$firstname_input.show();
				$lastname_input.show();
				$address_input.hide();
				$zipcode_input.hide();
				$place_input.hide();
				$birthdate_input.show();
				$birthnumber_input.hide();
				$contactphone_input.show();
				$email_input.show();
				$confirm_email_input.show();
				break;
				
			case '_input_privat_mobil_kontant' :

				$('#orderform .left_orderform .number_chooser').show();
				$('.subscription_chooser').hide();
				$orgnumber_input.hide();
				$orgname_input.hide();
				$firstname_input.show();
				$lastname_input.show();
				$address_input.show();
				$zipcode_input.show();
				$place_input.show();
				$birthdate_input.show();
				$birthnumber_input.hide();
				$contactphone_input.hide();
				$email_input.show();
				$confirm_email_input.show();
				break;
		}
		
	/* workaround to keep value from abbonement select */	
			switch (id) {

			case '_input_privat_full_pakke' :
				$("#orderform .abbon_holder").val("Full pakke");
				break;
				
			case '_input_privat_mobil_aktiv' :
				$("#orderform .abbon_holder").val("Aktiv");
				break;
	
			case '_input_privat_mobil_faktura' :
				$("#orderform .abbon_holder").val("Faktura");
				break;
                        case '_input_privat_xxl' :
                                $("#orderform .abbon_holder").val("XXL");
                                break;
                        case '_input_privat_folkepakka' :
                                $("#orderform .abbon_holder").val("Folkepakka");
                                break;

			case '_input_privat_mobilt_bredbaand_paa_tur' :
				$("#orderform .abbon_holder").val("På tur");
				break;

			case '_input_bedrift_paa_jobben' :
				$("#orderform .abbon_holder").val("På jobben");
				break;

				
			case '_input_privat_mobil_kontant' :
				$("#orderform .abbon_holder").val("Kontant");
				break;
		}
		

	}

	// Set validation options
	function setValidationRules(id) {

		// Reset options if not on init (id == "")
				
		// Set validation rules depending on chosen product
		switch (id) {
			case '_input_privat_mobilt_bredbaand_paa_tur' :
				$("#orderform form").validate({
					rules: {
						phone_number:  { minlength: 8, maxlength: 8, digits: true },
						orgnumber:     { }, // minlength: 9, maxlength: 9, digits: true, required: true
						orgname:       { }, // required: true
						firstname:     { required: true },
						lastname:      { required: true },
						address:       { required: true },
						zipcode:       { required: true, minlength: 4, maxlength: 4 },
						place:         { required: true },
						birthdate:     { required: true, digits: true, minlength: 8, maxlength: 8 },
						birthnumber:   { required: true, digits: true, minlength: 11, maxlength: 11 },
						contactphone:  { }, // required: true, digits: true, minlength: 8, maxlength: 8
						email:         { email: true, required: true },
						confirm_email: { email: true, required: true, equalTo: $("#orderform input.email_input") }
						//cardnumber:    { required: true, digits: true, minlength: 16, maxlength: 16 },
						//expirydate:    { required: true, digits: true, minlength: 4, maxlength: 4 },
						//cvv2:          { required: true, digits: true, minlength: 3, maxlength: 3 }
					}
				});
				break;

			case '_input_bedrift_paa_jobben' :
				$("#orderform form").validate({
					rules: {
						phone_number:  { }, //minlength: 8, maxlength: 8, digits: true },
						orgnumber:     { minlength: 9, maxlength: 9, digits: true, required: true },
						orgname:       { required: true },
						firstname:     { required: true },
						lastname:      { required: true },
						address:       { }, // required: true
						zipcode:       { }, // required: true, minlength: 4, maxlength: 4
						place:         { }, // required: true
						birthdate:     { required: true, digits: true, minlength: 8, maxlength: 8 },
						birthnumber:   { }, // required: true, digits: true, minlength: 11, maxlength: 11
						contactphone:  { required: true, digits: true, minlength: 8, maxlength: 8 },
						email:         { email: true, required: true },
						confirm_email: { email: true, required: true, equalTo: $("#orderform input.email_input") }
						//cardnumber:    { required: true, digits: true, minlength: 16, maxlength: 16 },
						//expirydate:    { required: true, digits: true, minlength: 4, maxlength: 4 },
						//cvv2:          { required: true, digits: true, minlength: 3, maxlength: 3 }
					}
				});
				break;

			case '_input_privat_mobil_kontant' :
				$("#orderform form").validate({
					rules: {
						phone_number:  { minlength: 8, maxlength: 8, digits: true },
						orgnumber:     { }, // minlength: 9, maxlength: 9, digits: true, required: true
						orgname:       { }, // required: true 
						firstname:     { required: true },
						lastname:      { required: true },
						address:       { required: true },
						zipcode:       { required: true, minlength: 4, maxlength: 4 },
						place:         { required: true },
						birthdate:     { required: true, digits: true, minlength: 8, maxlength: 8 },
						birthnumber:   { }, // required: true, digits: true, minlength: 11, maxlength: 11
						contactphone:  { }, // required: true, digits: true, minlength: 8, maxlength: 8
						email:         { email: true, required: true },
						confirm_email: { email: true, required: true, equalTo: $("#orderform input.email_input") }
						//cardnumber:    { required: true, digits: true, minlength: 16, maxlength: 16 },
						//expirydate:    { required: true, digits: true, minlength: 4, maxlength: 4 },
						//cvv2:          { required: true, digits: true, minlength: 3, maxlength: 3 }
					}
				});
				break;

			case '_input_privat_full_pakke' :
			case '_input_privat_mobil_aktiv' :
			case '_input_privat_mobil_faktura' :
			default :
				$("#orderform form").validate({
					rules: {
						phone_number:  { minlength: 8, maxlength: 8, digits: true },
						orgnumber:     { }, // minlength: 9, maxlength: 9, digits: true, required: true
						orgname:       { }, // required: true
						firstname:     { required: true },
						lastname:      { required: true },
						address:       { required: true },
						zipcode:       { required: true, minlength: 4, maxlength: 4 },
						place:         { required: true },
						birthdate:     { }, // required: true, digits: true, minlength: 8, maxlength: 8
						birthnumber:   { required: true, digits: true, minlength: 11, maxlength: 11 },
						contactphone:  { }, // required: true, digits: true, minlength: 8, maxlength: 8
						email:         { email: true, required: true },
						confirm_email: { email: true, required: true, equalTo: $("#orderform input.email_input") }
						//cardnumber:    { required: true, digits: true, minlength: 16, maxlength: 16 },
						//expirydate:    { required: true, digits: true, minlength: 4, maxlength: 4 },
						//cvv2:          { required: true, digits: true, minlength: 3, maxlength: 3 }
					}
				});
				break;
		}
	}
	
	// LEFT ORDERFORM //
	// Enable and allow editing of the	 left column
	function enableLeftOrderform() {
		$('#orderform .left_orderform input').attr("disabled", false);
//		$('#orderform .left_orderform input').removeAttr("readOnly");
		$('#orderform .tab').removeClass('active');
		$('#orderform .left_orderform .tab').addClass('active');
		$('#orderform .buttons_left .next').show();
		
		$('#orderform .new_number_radio.orderform_checkbox + span.ui-radio:first').show();
		$('#orderform .golden_number_radio.orderform_checkbox + span.ui-radio:first').show();
		$('#orderform .update_mark.goldennumber').show();
		$('#orderform .update_mark.getnumber').show();
		
		$("#orderform .new_number_text").show();
		$("#orderform .golden_number_text").show();
		$("#phoneinput").show();
		$("#orderform .numbertransfer").show();

	}

	// Disable and disallow editing of the left column
	function disableLeftOrderform() {
		$('#orderform .left_orderform input').attr("disabled", true);
		$('#orderform .buttons_left .next').hide();
		$('#orderform .new_number_radio.orderform_checkbox + span.ui-radio:first').hide();
		$('#orderform .golden_number_radio.orderform_checkbox + span.ui-radio:first').hide();
		$('#orderform .update_mark.goldennumber').hide();
		$('#orderform .update_mark.getnumber').hide();
		}


	// Calculate the recommended subcscription in the subscription chooser based
	// on slider positions
	function calculateRecommendedSubscription() {
//alert("calculateRecommendedSubscription()");
		if (upperSliderValue > 4) {
			upperSliderValue = 4;
		}
		
		if (lowerSliderValue > 4) {
			lowerSliderValue = 4;
		}

		var desiredCampaignElement;
		var desiredTxt;
		
		// TODO: Example functionality for switching campaign element, here based on
		// upper slide position
			switch (upperSliderValue) {
			case 0 :
				switch (lowerSliderValue) {
					
					case 0:
						desiredCampaignElement = '_input_privat_mobil_faktura';
						desiredTxt = 'Faktura';
					break;
					case 1:
						desiredCampaignElement = '_input_privat_mobil_faktura';
						desiredTxt = 'Faktura';
					break;
					case 2:
						desiredCampaignElement = '_input_privat_mobil_faktura';
						desiredTxt = 'Faktura';
					break;
					case 3:
						desiredCampaignElement = '_input_privat_mobil_faktura';
						desiredTxt = 'Faktura';
					break;
					case 4:
						desiredCampaignElement = '_input_privat_mobil_faktura';
						desiredTxt = 'Faktura';
					break;
					default:
						break;
				}	
			break;
			
			case 1 :
				switch (lowerSliderValue) {
					case 0:
						desiredCampaignElement = '_input_privat_mobil_faktura';
						desiredTxt = ' Faktura';
					break;
					case 1:
						desiredCampaignElement = '_input_privat_mobil_faktura';
						desiredTxt = 'Faktura';
					break;
					case 2:
						desiredCampaignElement = '_input_privat_mobil_faktura';
						desiredTxt = 'Faktura';
					break;
					case 3:
						desiredCampaignElement = '_input_privat_folkepakka';
						desiredTxt = 'Folkepakka';
					break;
					case 4:
						desiredCampaignElement = '_input_privat_folkepakka';
						desiredTxt = 'Folkepakka';
					break;
					default:
						break;

				}
			break;
			case 2 :
					switch (lowerSliderValue) {
					
					case 0:
						desiredCampaignElement = '_input_privat_folkepakka';
						desiredTxt = 'Folkepakka';
					break;
					case 1:
						desiredCampaignElement = '_input_privat_folkepakka';
						desiredTxt = 'Folkepakka';
					break;
					case 2:
						desiredCampaignElement = '_input_privat_folkepakka';
						desiredTxt = 'Folkepakka';
					break;
					case 3:
						desiredCampaignElement = '_input_privat_folkepakka';
						desiredTxt = 'Folkepakka';
					break;
					case 4:
						desiredCampaignElement = '_input_privat_folkepakka';
						desiredTxt = 'Folkepakka';
					break;
					default:

				}
		break;
			case 3 :
				switch (lowerSliderValue) {
					
					case 0:	
						desiredCampaignElement = '_input_privat_full_pakke';
						desiredTxt = 'Full pakke';
					break;
					case 1:
						desiredCampaignElement = '_input_privat_full_pakke';
						desiredTxt = 'Full pakke';
					break;
					case 2:
						desiredCampaignElement = '_input_privat_folkepakka';
						desiredTxt = 'Folkepakka';
					break;
					case 3:
						desiredCampaignElement = '_input_privat_folkepakka';
						desiredTxt = 'Folkepakka';
					break;
					case 4:
						desiredCampaignElement = '_input_privat_xxl';
						desiredTxt = 'XXL';
					break;
					default:
				}
		break;
			case 4 :
				switch (lowerSliderValue) {
					case 0:
						desiredCampaignElement = '_input_privat_full_pakke';
						desiredTxt = 'Full Pakke';
					break;
					case 1:
						desiredCampaignElement = '_input_privat_full_pakke';
						desiredTxt = 'Full Pakke';
					break;
					case 2:
						desiredCampaignElement = '_input_privat_full_pakke';
						desiredTxt = 'Full Pakke';
					break;
					case 3:
						desiredCampaignElement = '_input_privat_xxl';
						desiredTxt = 'XXL';
					break;
					case 4:
						desiredCampaignElement = '_input_privat_xxl';
						desiredTxt = 'XXL';
					break;
					default:
				}
			break;
		}

		$('.subscription_chooser .order_btn').show();

	  //$subcriptionText.text(desiredTxt);

		choosenSubscription = desiredCampaignElement;

		$('.subscription_chooser .subscription').css("background","url(/img/orderform/subscription_chooser/"+desiredCampaignElement+".png)");

		showCampaignElement(desiredCampaignElement);
	}

	// Hide the campaign element
	function hideCampaignElement() {
		$("#orderform .campaign_element").hide();
	}


	/*
	// Reset the "bedrift" dropdown menu
	function resetBedrift() {
		$("#orderform .left_orderform .selectbox:eq(0)").css("color", "#000000");
		$("#orderform .left_orderform .selectbox:eq(1)").css("color", "#AAAAAA");
		$("#orderform li[id='_input_bedrift']").click();
	}
	*/

	// Validate the phone input in the left column
	// skipNextButtonCheck flag for avoiding infinite validation loop
	function validatePhoneInput(skipNextButtonCheck) {
		console.log("validatePhoneInput(" + skipNextButtonCheck + ")");
		var firstNumberValidated = (($("#phoneinput").val().charAt(0) == "4") || ($("#phoneinput").val().charAt(0) == "9")) ? true : false;
		if ($("#orderform form").validate().element("#phoneinput") && firstNumberValidated) {
			console.log("phoneinput validated, calling function enablePhoneNumber()");
			enablePhoneNumber();

			if (skipNextButtonCheck == false) {
				checkLeftNextButton();
			}
			return true;
		} else {
			console.log("phoneinput did not validate, calling function disablePhoneNumber()");
			disablePhoneNumber();
			return false;
		}
	}

	// Turn on green check mark in the phone input box
	function enablePhoneNumber() {

		// Hide newnumber and goldennumber text and checkboxes when transfer number validates
		$("#orderform .new_number_text").hide();
		$("#orderform .golden_number_text").hide();
		$("#orderform input.new_number_radio + span.ui-radio:first").hide();
		$("#orderform input.golden_number_radio + span.ui-radio:first").hide();
		$("#golden_number_selectors").hide();
		$("#new_number_selectors").hide();

		$("#orderform #phoneinput").css("background", "url(/img/general/phone_input_hover.png) no-repeat top left");
		/*
		if ($("#orderform input.new_number_radio:checked").length > 0) { // If checked
			$("#orderform input.new_number_radio + span.ui-radio:first").click();
			$("#orderform input.new_number_radio + span.ui-radio:first").removeClass("ui-radio-state-checked-hover");
		}
		 */

		// if ($("#orderform input.new_number_radio:checked").length > 0) { // If checked
		if ($("#orderform input.new_number_radio + span.ui-radio:first").hasClass("ui-radio-state-checked") || $("#orderform input.new_number_radio + span.ui-radio:first").hasClass("ui-radio-state-checked-hover")) { // If checked
			// $("#orderform input.new_number_radio + span.ui-radio:first").click();
			$("#orderform input.new_number_radio + span.ui-radio:first").removeClass("ui-radio-state-checked ui-radio-state-checked-hover");
		}

		// if ($("#orderform input.golden_number_radio:checked").length > 0) { // If checked
		if ($("#orderform input.golden_number_radio + span.ui-radio:first").hasClass("ui-radio-state-checked") || $("#orderform input.golden_number_radio + span.ui-radio:first").hasClass("ui-radio-state-checked-hover")) { // If checked
			// $("#orderform input.golden_number_radio + span.ui-radio:first").click();
			$("#orderform input.golden_number_radio + span.ui-radio:first").removeClass("ui-radio-state-checked ui-radio-state-checked-hover");
		}
	}

	// Turn off green check mark in the phone input box
	function disablePhoneNumber() {
		$("#new_number_selectors").hide();
		$("#golden_number_selectors").hide();

		// show newnumber and goldennumber text and checkboxes when transfer number dont validate
		$("#orderform .new_number_text").show();
		$("#orderform .golden_number_text").show();
		$("#orderform input.new_number_radio + span.ui-radio:first").show();
		$("#orderform input.golden_number_radio + span.ui-radio:first").show();

		$("#orderform #phoneinput").css("background", "url(/img/general/phone_input.png) no-repeat top left");
		
	}

	// Turns on check mark in new number checkbox
	function enableNewNumber() {

			$("#new_number_selectors").css("display", "block");
			$("#golden_number_selectors").css("display", "none");		
			$("#orderform #phoneinput").css("background", "url(/img/general/phone_input.png) no-repeat top left");
			$("#orderform #phoneinput").val("");

			checkLeftNextButton();

	}
	
	// Turns on check mark in new number checkbox
	function enableGoldenNumber() {

			$("#golden_number_selectors").css("display", "block");
			$("#new_number_selectors").css("display", "none");
			$("#orderform #phoneinput").css("background", "url(/img/general/phone_input.png) no-repeat top left");
			$("#orderform #phoneinput").val("");

			checkLeftNextButton();

	}

	// Checks whether next button in left column shoul be highlighted or not
	function checkLeftNextButton() {

		if (validateLeftForm(false)) {
			$("#orderform .buttons_left .next").css("background", "url(/img/orderform/orderflow_next_active.png) no-repeat scroll right top");
		} else {
			$("#orderform .buttons_left .next").css("background", "url(/img/orderform/orderflow_next_inactive.png) no-repeat scroll right top");
		}
	}

	// Validate the left column
	function validateLeftForm(isFinal) {

		console.log("validateLeftForm(" + isFinal + ")");
		var valid = true;
		var newNumberChecked = false;
		var goldenNumberChecked = false;

		// Check if the nytt nummberradiobutton is checked
		if ($("#orderform input.new_number_radio + span.ui-radio:first").hasClass("ui-radio-state-checked") || $("#orderform input.new_number_radio + span.ui-radio:first").hasClass("ui-radio-state-checked-hover")) {
			console.log("new_number registered as checked");
			newNumberChecked = true;
		}
		
		// Check if the gullnummer radiobutton is checked
		if ($("#orderform input.golden_number_radio + span.ui-radio:first").hasClass("ui-radio-state-checked") || $("#orderform input.golden_number_radio + span.ui-radio:first").hasClass("ui-radio-state-checked-hover")) {
			console.log("golden_number registered as checked");
			goldenNumberChecked = true;
		}

// Make validation final (progress to next section) if not set to false
		isFinal = typeof(isFinal) == 'undefined' ? true : false;
	
		// Abonnement
		// If private subscription not chosen
		
		if (newNumberChecked && ($("#orderform .select_container.new_number input").val() == "Velg nytt nummer") ) { // && ($("#orderform .select_container.bedrift input").val() == "Bedrift")
			if (isFinal) {
				displayError("Vennligst velg et nytt nummer.");
			}
			return false;
		}

		
		if (goldenNumberChecked && ($("#orderform .select_container.golden_number input").val() == "Velg gullnummer") )		
		{ 	if (isFinal) {
				displayError("Vennligst velg et gullnummer.");
			}
	
			return false;
		}
	
		// Mobilnummer
		if ($("#orderform .number_chooser").css("display") != "none") {
			// If number input does NOT validate, and the first and second checkbox after new_number input hasn't been selected (ie. has the class "ui-radio-state-checked")

			if (!($("#orderform form").validate().element("#phoneinput")) && 
					!($("#orderform input.new_number_radio + span.ui-radio:first").hasClass("ui-radio-state-checked")) &&
					!($("#orderform input.golden_number_radio + span.ui-radio:first").hasClass("ui-radio-state-checked")) ) 
			{
				if (isFinal) {
					displayError("Vennligst skriv inn nummeret du vil overføre til OneCall, eller opprett et nytt nummer.");
				}
				return false;
			}
		}

		// hide golden number and transfer number text if not choosen
		if ($("#orderform input.new_number_radio + span.ui-radio:first").hasClass("ui-radio-state-checked"))
		{
			if (isFinal) {
				$("#orderform .golden_number_text").hide();
				$("#phoneinput").hide();
				$("#orderform .numbertransfer").hide();
			}
		}

		// hide new number and transfer number text if not choosen
		if ($("#orderform input.golden_number_radio + span.ui-radio:first").hasClass("ui-radio-state-checked"))
		{
			if (isFinal) {
				$("#orderform .new_number_text").hide();
				$("#phoneinput").hide();
				$("#orderform .numbertransfer").hide();
			}
		}

		// Mobilnummer - siffer
		if ($("#orderform .number_chooser").css("display") != "none") {
			// If number validates, but does not start w/ 4 or 9
			if ($("#orderform form").validate().element("#phoneinput") && !(validatePhoneInput(true))) {
				if (isFinal) {
					displayError("Nummeret du skal overføre må begynne på 4 eller 9.");
				}
				return false;
			}
		}
				
		if ($("#orderform .select_container.privat input").val() == "Velg et abonnement") 	{
			if (isFinal) {
				displayError("Vennligst velg et abonnement.");
			}
	
			return false;
		}
	
		// Check if valid
		if (isFinal) {

			hideCampaignElement();
			disableLeftOrderform();
			enableMidOrderform();
			if ($.browser.msie) {
				$('#orderform .separator_vertical_left').show();
				$('#orderform .mid_orderform').show();
				$('#orderform .separator_vertical_right').show();
				$('#orderform .right_helper').show();
			} else {
				$('#orderform .separator_vertical_left').fadeIn();
				$('#orderform .mid_orderform').fadeIn();
				$('#orderform .separator_vertical_right').fadeIn();
				$('#orderform .right_helper').fadeIn();
			}
		}
		return true;
	}
	
	// MIDDLE ORDERFORM //
	// Enable and allow editing of the left column
	function enableMidOrderform() {

  	$('#content_wrapper').css("display","none");
//		$('#contentform').attr("readOnly",false);
		$('#orderform .mid_orderform input').attr("readOnly",false);
		$('#new_number_radio').css("display","none");

		$('#golden_number_radio').attr("disabled",true);
		$('#orderform .tab').removeClass('active');
		$('#orderform .mid_orderform .tab').addClass('active');
		$('#orderform .buttons_mid .previous').show();
		$('#orderform .buttons_mid .next').show();
	}
	
	// Disable and disallow editing of the left column
	function disableMidOrderform() {
		$('#orderform .mid_orderform input').attr("readOnly",true);
		$('#orderform .buttons_mid .previous').hide();
		$('#orderform .buttons_mid .next').hide();
	}


	function getPostalName() {

		// Padded JSON (JSONP) used due to crossdomain limitation
		$.ajaxSetup({ cache: false });
		$.getJSON('http://www.onecall.no/services/postal_codes.php?post_no=' + $zipcode_input.val() + '&callback=?', function(data) {
			$place_input.val(data.postalName);
			// $("#orderform .birthdate_input").select(); // Creates numerous tabindex issues...
		});
	}

	// When postal name has been received
	function onPostalNameReceived(data) {
		// alert("Data loaded: " + data);
	}

	// Set all input backgrounds in middle column to default
	function resetMidBgImages() {
		$("#orderform .mid_orderform input").css("background-image", "url('/img/orderform/inputL.png')");
	}

	// Check whether next button should be highlighted or not
	function checkMidNextButton() {

		// alert("checkLeftNextButton!: " + validateMidForm(false));
		if (validateMidForm(false)) {

			$("#orderform .buttons_mid .next").css("background", "url(/img/orderform/orderflow_next_active.png) no-repeat scroll right top");
		} else {
		
			$("#orderform .buttons_mid .next").css("background", "url(/img/orderform/orderflow_next_inactive.png) no-repeat scroll right top");
		}
	}

	// Birtdate validation function
	function validateBirthdate(birthdate) {

		var bnString = new String(birthdate);

		var bnDay = Number(bnString.substr(0, 2));
		var bnMonth = Number(bnString.substr(2, 2));
		var bnYear = Number(bnString.substr(4, 4));
		// log.debug('validateBirthnumber - ' + bnDay + ' - ' + bnMonth + ' - ' + bnYear);

		if(isNaN(bnDay) || isNaN(bnMonth) || isNaN(bnYear)){
                        return false;
                }

		if (bnDay < 1 || bnDay > 31) {
			return false;
		}

		if (bnMonth < 1 || bnMonth > 12) {
			return false;
		}

		if (bnYear < 1899 || bnYear > 2020) {
			return false;
		}

		switch (bnMonth) {
			case 4 :
			case 6 :
			case 9 :
			case 11 :
				if (bnDay > 30) {
					return false;
				}
				break;
			case 2 :
				if (bnDay > 29) {
					return false;
				}
		}

		// log.debug('Validated!');
		return true;
	}



	// Birtdate validation function
	function validateBirthnumber(birthnumber) {

		var bnString = new String(birthnumber);

		var bnDay = Number(bnString.substr(0, 2));
		var bnMonth = Number(bnString.substr(2, 2));
		var bnYear = Number(bnString.substr(4, 2));
		// log.debug('validateBirthnumber - ' + bnDay + ' - ' + bnMonth + ' - ' + bnYear);

		if (bnDay < 1 || bnDay > 31) {
			return false;
		}

		if (bnMonth < 1 || bnMonth > 12) {
			return false;
		}

		switch (bnMonth) {
			case 4 :
			case 6 :
			case 9 :
			case 11 :
				if (bnDay > 30) {
					return false;
				}
				break;
			case 2 :
				if (bnDay > 29) {
					return false;
				}
		}

		// log.debug('Validated!');
		return true;
	}



	// Validate the middle column
	function validateMidForm(isFinal) {
		// Make validation final (progress to next section) if not set to false
		isFinal = typeof(isFinal) == 'undefined' ? true : false;

		// Reset bg images
		resetMidBgImages();
	
		// Reset flags
		var boxToSelect = undefined;
		var errorMsg = '';

		// Organization number
		if ($orgnumber_input.css("display") != "none" ) {
			if (($orgnumber_input.val() == orgNumberOrigVal) || !($("#orderform form").validate().element("#orderform input.orgnumber_input"))) {


				if (isFinal) {
					$orgnumber_input.val(orgNumberOrigVal);
					$orgnumber_input.css("background-image", "url('/img/orderform/inputL_error.png')");
					errorMsg = "Vennligst skriv inn organisasjonsnummer - 9 siffer.";
				}
				boxToSelect = (boxToSelect == undefined) ? $orgnumber_input : boxToSelect;
			}
		}

		// Organization name
		if ($orgname_input.css("display") != "none" ) {

			if ($orgname_input.val() == "")
				$orgname_input.val(orgNameOrigVal);
			
			if (($orgname_input.val() == orgNameOrigVal) || !($("#orderform form").validate().element("#orderform input.orgname_input"))) {

				if (isFinal) {
					$orgname_input.css("background-image", "url('/img/orderform/inputL_error.png')");
					errorMsg = "Vennligst skriv inn bedriftens navn .";
				}
				boxToSelect = (boxToSelect == undefined) ? $orgnumber_input : boxToSelect;
			}
		}


		// First name
		if ($firstname_input.css("display") != "none" ) {
			if (($firstname_input.val() == firstNameOrigVal) || !($("#orderform form").validate().element("#orderform input.firstname_input"))) {
				if (isFinal) {
					$firstname_input.val(firstNameOrigVal);		
					$firstname_input.css("background-image", "url('/img/orderform/inputL_error.png')");
					errorMsg = "Vennligst skriv inn fornavnet ditt.";
				}
				boxToSelect = (boxToSelect == undefined) ? $firstname_input : boxToSelect;
			}
		}
		
		// Last name
		if ($lastname_input.css("display") != "none" ) {
			if (($lastname_input.val() == lastNameOrigVal) || !($("#orderform form").validate().element("#orderform input.lastname_input"))) {
				if (isFinal) {
					$lastname_input.val(lastNameOrigVal);
					$lastname_input.css("background-image", "url('/img/orderform/inputL_error.png')");
					errorMsg = (errorMsg == '') ? "Vennligst skriv inn etternavnet ditt." : errorMsg;
				}
				boxToSelect = (boxToSelect == undefined) ? $lastname_input : boxToSelect;
			}
		}
		
		// Address
		if ($address_input.css("display") != "none" ) {
			if (($address_input.val() == addressOrigVal) || !($("#orderform form").validate().element("#orderform input.address_input"))) {				
				if (isFinal) {
					$address_input.val(addressOrigVal);
					$address_input.css("background-image", "url('/img/orderform/inputL_error.png')");
					errorMsg = (errorMsg == '') ? "Vennligst skriv inn adressen din." : errorMsg;
				}
				boxToSelect = (boxToSelect == undefined) ? $address_input : boxToSelect;
			}
		}
	
		// Zip code
		if ($zipcode_input.css("display") != "none" ) {
			if (($zipcode_input.val() == zipCodeOrigVal) || !($("#orderform form").validate().element("#orderform input.zipcode_input"))) {
				if (isFinal) {
					$zipcode_input.val(zipCodeOrigVal);
					$zipcode_input.css("background-image", "url('/img/orderform/inputL_error.png')");
					errorMsg = (errorMsg == '') ? "Vennligst skriv inn et gyldig postnummer - 4 siffer." : errorMsg;
				}
				boxToSelect = (boxToSelect == undefined) ? $zipcode_input : boxToSelect;
			}
		}
	
		// Place
		if ($place_input.css("display") != "none" ) {
			if (($place_input.val() == placeOrigVal) || !($("#orderform form").validate().element("#orderform input.place_input"))) {
				if (isFinal) {
					$place_input.val(placeOrigVal);
					$place_input.css("background-image", "url('/img/orderform/inputL_error.png')");
					errorMsg = (errorMsg == '') ? "Vennligst skriv inn poststed" : errorMsg;
				}
				boxToSelect = (boxToSelect == undefined) ? $place_input : boxToSelect;
			}
		}
	
		// Birth date
		if ($birthdate_input.css("display") != "none" ) {
			if (($birthdate_input.val() == birthDateOrigVal) || !validateBirthdate($birthdate_input.val()) || !($("#orderform form").validate().element("#orderform input.birthdate_input"))) {
				if (isFinal) {
					$birthdate_input.val(birthDateOrigVal);
					$birthdate_input.css("background-image", "url('/img/orderform/inputL_error.png')");
					errorMsg = (errorMsg == '') ? "Vennligst skriv inn gyldig fødselsdato - 8 siffer (ddmmåååå)" : errorMsg;
				}
				boxToSelect = (boxToSelect == undefined) ? $birthdate_input : boxToSelect;
			}
		}

		// Birth number
		if ($birthnumber_input.css("display") != "none" ) {
			if (($birthnumber_input.val() == birthNumberOrigVal) || !($("#orderform form").validate().element("#orderform input.birthnumber_input"))) {
				if (isFinal) {
					$birthnumber_input.val(birthNumberOrigVal); 
					$birthdate_input.css("background-image", "url('/img/orderform/inputL_error.png')");
					errorMsg = (errorMsg == '') ? "Vennligst skriv inn gyldig fødselsnummer - 11 siffer" : errorMsg;
				}
				boxToSelect = (boxToSelect == undefined) ? $birthnumber_input : boxToSelect;
			}
		}

		// Contact phone
		if ($contactphone_input.css("display") != "none" ) {
			if (($contactphone_input.val() == contactPhoneOrigVal) || !($("#orderform form").validate().element("#orderform input.contactphone_input"))) {			
				if (isFinal) {
						$contactphone_input.val(contactPhoneOrigVal);
						$contactphone_input.css("background-image", "url('/img/orderform/inputL_error.png')");
						errorMsg = (errorMsg == '') ? "Vennligst skriv inn telefonnummer vi kan kontakte deg på - 8 siffer" : errorMsg;
				}
				boxToSelect = (boxToSelect == undefined) ? $contactphone_input : boxToSelect;
			}
		}
	
		// If email not changed or not valid
		if ($email_input.css("display") != "none" ) {
			if (($email_input.val() == emailOrigVal) || !($("#orderform form").validate().element("#orderform input.email_input"))) {

				if (isFinal) {
					$email_input.val(emailOrigVal);
					$confirm_email_input.val(confirmEmailOrigVal);
					$email_input.css("background-image", "url('/img/orderform/inputL_error.png')");
					errorMsg = (errorMsg == '') ? "Vennligst skriv inn gyldig mailadresse" : errorMsg;
				}
				boxToSelect = (boxToSelect == undefined) ? $email_input : boxToSelect;
			}
		}
	
		// If confirm email not changed or not valid
		if ($confirm_email_input.css("display") != "none" ) {
			if (($confirm_email_input.val() == confirmEmailOrigVal) || !($("#orderform form").validate().element("#orderform input.confirm_email_input"))) {

				if (isFinal) {
					$email_input.val(emailOrigVal);
					$confirm_email_input.val(confirmEmailOrigVal);
					$confirm_email_input.css("background-image", "url('/img/orderform/inputL_error.png')");
					errorMsg = (errorMsg == '') ? "Vennligst se over og bekreft mailadressen" : errorMsg;
				}
				boxToSelect = (boxToSelect == undefined) ? $confirm_email_input : boxToSelect;
			}
		}

		if (boxToSelect != undefined) {
			if (isFinal) {
				displayError(errorMsg);
				boxToSelect.select();
			}
			return false;
		}

		if (isFinal) {
		
			disableMidOrderform();
			enableRightOrderform();
			if ($.browser.msie) {
				$('#orderform .separator_vertical_right').show();
				$('#orderform .right_orderform').show();
				if($("#orderform .abbon_holder").val() == 'Kontant'){
					$('#orderform .right_orderform .payment_section').hide();
					$('#orderform .right_orderform .terms .terms_txt').show();
				}else{
					$('#orderform .right_orderform .payment_section').show();
					$('#orderform .right_orderform .terms .terms_txt').hide();
				}
				$('#orderform .right_helper').hide();
			} else {
				$('#orderform .separator_vertical_right').fadeIn();
				$('#orderform .right_orderform').fadeIn();
				if($("#orderform .abbon_holder").val() == 'Kontant'){
					//$("#orderform .abbon_holder").val("Full pakke");
					$('#orderform .right_orderform .payment_section').hide();
					$('#orderform .right_orderform .terms .terms_txt').show();
				}else{
					$('#orderform .right_orderform .payment_section').show();
					$('#orderform .right_orderform .terms .terms_txt').hide();
				}
				$('#orderform .right_helper').hide();
			}
		}
		return true;
	}

	// Reset the right column helper texts
	function resetRightHelper() {
		$('#orderform .right_helper .right_helper_1').removeClass('active');
		$('#orderform .right_helper .right_helper_2').removeClass('active');
		$('#orderform .right_helper .right_helper_3').removeClass('active');
		$('#orderform .right_helper .right_helper_4').removeClass('active');
	}

	// Highlight right helper text corresponding to passed section parameter
	function highlightRightHelper(section) {
		resetRightHelper();
		$('#orderform .right_helper .right_helper_' + section).addClass('active');
	}
	
	// RIGHT ORDERFORM //
	// Enable and allow editing of the right column
	function enableRightOrderform() {
		$('#orderform .right_orderform input').attr('readOnly',false);
		$('#orderform .tab').removeClass('active');
		$('#orderform .right_orderform .tab').addClass('active');
	}

	// Disable and disallow editing of the left column
	function disableRightOrderform() {
		$('#orderform .right_orderform input').attr('readOnly',true);
	}

	// Enable the credit card section
	function enableCreditCard() {
		if ($.browser.msie) {
			$('#orderform .right_orderform .invoice_section .separator_horizontal_medium').hide();
			$('#orderform .credit_card').show();
			$('#orderform .invoice_section').hide();
		} else {
			$('#orderform .right_orderform .invoice_section .separator_horizontal_medium').hide();
			$('#orderform .invoice_section').hide();
			$('#orderform .credit_card').fadeIn();
		}
	}

	// Enable the invoice section
	function enableInvoice() {
		if ($.browser.msie) {
			$('#orderform .right_orderform .separator_horizontal_medium').show();
			$('#orderform .credit_card').hide();
			$('#orderform .invoice_section').show();
		} else {
			$('#orderform .right_orderform .separator_horizontal_medium').fadeIn();
			$('#orderform .credit_card').hide();
			$('#orderform .invoice_section').fadeIn();
		}
	}

	// Check whether or not to heighlight the right submit button
	function checkRightSubmitButton() {
		if (validateRightForm(false)) {
			$("#orderform .buttons_right .submit").css("background", "url(/img/orderform/orderflow_submit_active.png) no-repeat scroll right top");
		} else {
			$("#orderform .buttons_right .submit").css("background", "url(/img/orderform/orderflow_submit_inactive.png) no-repeat scroll right top");
		}
	}

	// Validate the right column
	function validateRightForm(isFinal) {
		
		// Make validation final (progress to next section) if not set to false
		isFinal = (typeof(isFinal) == 'undefined') ? true : false;

		// If creditcard checked
		if ($("#orderform input.creditcard_radio + span.ui-radio:first").hasClass("ui-radio-state-checked")) {
			// If type VISA/MasterCard not chosen
			/*if ($("#orderform .credit_card input").val() == "Velg") {
				if (isFinal) {
					displayError("Vennligst velg bankkorttype - Visa eller MasterCard");
				} else {
				}
				return false;
			}
	
			// If creditcard number not changed or not valid
			if (($("#orderform input.cardnumber_input").val() == cardNumberOrigVal) || !($("#orderform form").validate().element("#orderform input.cardnumber_input"))) {
				
				if (isFinal) {
					$("#orderform input.cardnumber_input").val(cardNumberOrigVal);
					displayError("Vennligst skriv inn et gyldig kredittkortnummer");
					$("#orderform input.cardnumber_input").select();
				} else {
				}
				return false;
			}
	
			// If expiry date not changed or not valid
			if (($("#orderform input.expirydate_input").val() == expiryDateOrigVal) || !($("#orderform form").validate().element("#orderform input.expirydate_input"))) {
				
				if (isFinal) {
					$("#orderform input.expirydate_input").val(expiryDateOrigVal);
					displayError("Vennligst skriv inn gyldig utløpsdato");
					$("#orderform input.expirydate_input").select();
				} else {
				}
				return false;
			}
	
			// If cvv2 not changed or not valid
			if (($("#orderform input.cvv2_input").val() == cvv2OrigVal) || !($("#orderform form").validate().element("#orderform input.cvv2_input"))) {
				
			 	if (isFinal) {
				  $("#orderform input.cvv2_input").val(cvv2OrigVal);
					displayError("Vennligst skriv inn cvv2");
					$("#orderform input.cvv2_input").select();
				} else {
				}
				return false;
			}
			*/
		// If invoice checked
		} else if ($("#orderform input.invoice_radio + span.ui-radio:first").hasClass("ui-radio-state-checked") && $("#orderform .abbon_holder").val() != 'Kontant') {

			// If neither invoice_mail or invoice_email
			if (!($("#orderform input.mail_radio + span.ui-radio:first").hasClass("ui-radio-state-checked")) && !($("#orderform input.email_radio + span.ui-radio:first").hasClass("ui-radio-state-checked"))) {
				if (isFinal) {
					displayError("Vennligst velg betalingsmåte med faktura, post eller e-post");
				} else {
				}
				return false;
			} else {

				// If terms not accepted
				if (!($("#orderform input.terms_radio + span.ui-checkbox:first").hasClass("ui-checkbox-state-checked"))) {
					if (isFinal) {
						displayError("Vennligst godta vilkår for å fullføre bestillingen.");
					} else {
					}
					return false;
				}
				if (isFinal) $("#orderform form").rules("remove");
				return true;
			}
			
		// If none at all checked
		} else if($("#orderform .abbon_holder").val() != 'Kontant') {
			if (isFinal) {
				displayError("Vennligst velg betalingsmåte for månedlig forbruk.");
			} else {
			}
			return false;
		}
		
		if (!($("#orderform input.terms_radio + span.ui-checkbox:first").hasClass("ui-checkbox-state-checked"))) {
			if (isFinal) {
				displayError("Vennligst godta vilkår for å fullføre bestillingen.");
			} else {
			}
			return false;
		}
		
		if (isFinal) $("#orderform form").rules("remove");
		return true;
	}
	

	/*******
	* INIT *
	*******/

	// GENERAL ORDERFORM //
	// Selectboxes
	$('#orderform .orderform_select_abbon').selectbox(); // {debug: true}
	$('#orderform .orderform_select_new').selectbox(); // {debug: true}
	$('#orderform .orderform_select_golden').selectbox(); // {debug: true}
	$('#orderform .orderform_select_creditcard').selectbox(); // {debug: true}
//	$('#leftmenu .orderform_select').selectbox(); // {debug: true}


	// Checkboxes and radiobuttons
	$('#orderform .orderform_checkbox, #leftmenu .orderform_checkbox').checkBox();
	$('#orderform .orderform_radiobutton').checkBox();
	

	// Load product flashes
	$('#new_number_selectors').css("display","none");
	$('#golden_number_selectors').css("display","none");

  // Form validation
	
	// Remember original texts
	orgNumberOrigVal = $orgnumber_input.val();
	orgNameOrigVal = $orgname_input.val();
	firstNameOrigVal = $firstname_input.val();
	lastNameOrigVal = $lastname_input.val();
	addressOrigVal = $address_input.val();
	zipCodeOrigVal = $zipcode_input.val();
	placeOrigVal = $place_input.val();
	birthDateOrigVal = $birthdate_input.val();
	birthNumberOrigVal = $birthnumber_input.val();
	emailOrigVal = $email_input.val();
	contactPhoneOrigVal = $contactphone_input.val();
	confirmEmailOrigVal = $confirm_email_input.val();

	cardNumberOrigVal = ''; //$("#orderform input.cardnumber_input").val();
	expiryDateOrigVal = ''; //$("#orderform input.expirydate_input").val();
	cvv2OrigVal = ''; //$("#orderform input.cvv2_input").val();
	

	setValidationRules("");

		// Sifr header replacement must be placed here
	
	if (flashEnabled) {
		$('#orderform h3, #leftmenu h3').sifr({
				path: '/fonts/',
				font: 'vag-rounded_bold',
				fontSize: '14px', // Works only with version from http://plugins.jquery.com/project/Sifr
				color: '#333333',
				offsetTop: 2
		});
	}
	// Set element visibility (must be done after sifr header replacement)
	$('#orderform .campaign_element').show();
	$('#orderform .mid_orderform').hide();
	$('#orderform .separator_vertical_right').hide();
	$('#orderform .right_orderform').hide();
	$('#orderform .credit_card').hide();

	// Set questionmark and terms_link behaviour
	$("#orderform .question_mark").click(function() {
		showPopup($(this));
	});

	$("#orderform .terms_link").click(function() {
		showPopup($(this));
	});

	// Popup close button
	$("#orderform_popup").click(function() {
		hidePopup();
	});

	// LEFT ORDERFORM //
	
	// If dropdown menus clicked
	$('#orderform li').click(function() {

// COMMENT OUT NEXT THREE LINES 
//if ($(this).attr("id") != "Velg et abonnement") {
//                        window.location.href = "maintainence.html";
//                }

  // If "paa jobben" subscription, navigate to special page


		if ($(this).attr("id") == "_input_bedrift_paa_jobben") {
			window.location.href = "bestill_bedriftsabonnement.php";
		}
	



	
		toggleInputFields($(this).attr("id"));
		setValidationRules($(this).attr("id"));
	

		// Reset other field
		/*
		switch ($(this).attr("id")) {
			case '_input_privat_full_pakke' :
			case '_input_privat_mobil_aktiv' :
			case '_input_privat_mobil_faktura' :
			case '_input_privat_mobil_kontant' :
			case '_input_privat_mobilt_bredbaand_paa_tur':
				resetBedrift();
				break;
			case '_input_bedrift_paa_jobben' :
				resetPrivat();
				break;
		}
	
		*/
		checkLeftNextButton();

	});

	// If dropdown menus hovered over
	$('#orderform li').hover(
		function() {
			showCampaignElement($(this).attr("id"));
		},
		function() {}
	);
	
	

	// Hide number chooser
	$("#orderform .number_chooser").hide();

	// If text entered in phone input
	$('#orderform #phoneinput').keyup(function(event) {
		if(validatePhoneInput(false))
						$("#orderform .numbertype_holder").val("transfer number");
	});
	/*
	$('#orderform .phoneinput').keyup(function(event) {
		validatePhoneInput();
	});
	*/

	// If new number checkbox clicked
	$("#orderform input.new_number_radio + span.ui-radio:first").click(function() {
			if ($("#orderform input.new_number_radio:checked").length == 1) { // If going from unchecked to checked
					enableNewNumber();
					$("#orderform .numbertype_holder").val("new number");
			}
	});

// If golden number checkbox clicked
	$("#orderform input.golden_number_radio + span.ui-radio:first").click(function() {
			if ($("#orderform input.golden_number_radio:checked").length == 1) { // If going from unchecked to checked
					enableGoldenNumber();
					$("#orderform .numbertype_holder").val("golden number");
			}
	});

	// Rush change of radio button in order to validate on click
	$("#orderform input.new_number_radio + span.ui-radio:first").mousedown(function() {
		if (!$(this).hasClass("ui-radio-state-checked-hover") && !$(this).hasClass("ui-radio-state-checked")) {
				$(this).addClass("ui-radio-state-checked-hover");
		} else {
			$(this).removeClass("ui-radio-state-checked-hover");
			checkLeftNextButton();
		}
});
	
	// Rush change of ui-radio-buttons
	$("#orderform input.golden_number_radio + span.ui-radio:first").mousedown(function() {
			$("#orderform input.new_number_radio + span.ui-radio:first").removeClass("ui-radio-state-checked-hover");
	});

	// Rush change of ui-radio-buttons
	$("#orderform input.new_number_radio + span.ui-radio:first").mousedown(function() {
			$("#orderform input.golden_number_radio + span.ui-radio:first").removeClass("ui-radio-state-checked-hover");
	});

	// Show subscription chooser
	$(".subscription_chooser").show();

	// Declare vars for storing slider values
	var upperSliderValue = 0;
	var lowerSliderValue = 0;

	// Enable upper slider functionality
	$(".subscription_chooser .upper.slider").slider({
			range: "min",
			value: 0,
			min: 0,
			max: 5,
			// stepping: 1, // Does not look good...
			stop: function(event, ui) {
				upperSliderValue = ui.value;
				calculateRecommendedSubscription();
			}
		});


	// Enable lower slider functionality
	$(".subscription_chooser .lower.slider").slider({
			range: "min",
			value: 0,
			min: 0,
			max: 5,
			// stepping: 1, // Does not look good...
			stop: function(event, ui) {
				lowerSliderValue = ui.value;
				calculateRecommendedSubscription();
			}
		});


	// If left next button clicked
	$('#orderform .buttons_left a.next').click(function () {
      validateLeftForm();
			 
  });

	// Prevent default submit action on enter key, and trigger left orderform next button instead
	$('#orderform .left_orderform').keypress(function(event) {
		if (event.keyCode == 13) {
			event.preventDefault();
			$('#orderform .buttons_left a.next').click();
		}
	});
	
	// MIDDLE ORDERFORM //
	// Select all text within input textfield on click
	$("#orderform input[type='text']").click(function() {
		$(this).select();
	});

	// Trigger postal name service on valid post number
	$("#orderform input.zipcode_input").keyup(function() {
		if ($("#orderform form").validate().element(this)) {
			getPostalName();
		}
	});

	// If middle previous button clicked
	$('#orderform .buttons_mid a.previous').click(function () {
		enableLeftOrderform();
		disableMidOrderform();
		disableRightOrderform();
		if ($.browser.msie) {
			$('#orderform .campaign_element').fadeIn();
			$('#orderform .mid_orderform').hide();
			$('#orderform .separator_vertical_right').hide();
			$('#orderform .right_orderform').hide();
			$('#orderform .right_helper').hide();
		} else {
			$('#orderform .campaign_element').fadeIn();
			$('#orderform .mid_orderform').hide();
			$('#orderform .separator_vertical_right').hide();
			$('#orderform .right_orderform').hide();
			$('#orderform .right_helper').hide();
		}
	});
	
	// Trigger different right helpers and check next button on text input focus
	$orgnumber_input.focus(function() {
		resetRightHelper();
		checkMidNextButton();
	});
	$orgname_input.focus(function() {
		resetRightHelper();
		checkMidNextButton();
	});
	$firstname_input.focus(function() {
		highlightRightHelper(1);
		checkMidNextButton();
	});
	$firstname_input.focus(function() {
		highlightRightHelper(1);
		checkMidNextButton();
	});
	$lastname_input.focus(function() {
		highlightRightHelper(1);
		checkMidNextButton();
	});
	$address_input.focus(function() {
		highlightRightHelper(2);
		checkMidNextButton();
	});
	$zipcode_input.focus(function() {
		highlightRightHelper(2);
		checkMidNextButton();
	});
	$place_input.focus(function() {
		highlightRightHelper(2);
		checkMidNextButton();
	});
	$birthdate_input.focus(function() {
		highlightRightHelper(3);
		checkMidNextButton();
	});
	$birthnumber_input.focus(function() {
		highlightRightHelper(3);
		checkMidNextButton();
	});
	$contactphone_input.focus(function() {
		resetRightHelper();
		checkMidNextButton();
	});
	$email_input.focus(function() {
		highlightRightHelper(4);
		checkMidNextButton();
	});
	$confirm_email_input.focus(function() {
		highlightRightHelper(4);
		checkMidNextButton();
	});

	// On text input
	$('#orderform .mid_orderform').keyup(function() {
		checkMidNextButton();
	});
	
		// On text input
	$('#confirm_email_input').keyup(function() {
		checkMidNextButton();
	});
	
	// If middle next button clicked
	$('#orderform .buttons_mid a.next').click(function() {
		validateMidForm();
	});

	// Prevent default submit action on enter key, and trigger left orderform next button instead
	$('#orderform .mid_orderform').keypress(function(event) {
		if (event.keyCode == 13) {
			event.preventDefault();
			$('#orderform .buttons_mid a.next').click();
		}
	});
	
	// RIGHT ORDERFORM // 

	// If invoice button clicked
	$("#orderform input.invoice_radio + span.ui-radio:first").click(function() {
		enableInvoice();
	});

	// If credit card checkbox clicked
	$("#orderform input.creditcard_radio + span.ui-radio:first").click(function() {
		enableCreditCard();
	}); 	

	// If right previous button clicked
	$('#orderform .buttons_right a.previous').click(function () {
		enableMidOrderform();
		disableRightOrderform();
		
		if ($.browser.msie) {
			$('#orderform .right_orderform').hide();
			$('#orderform .right_helper').fadeIn();
		} else {
			$('#orderform .right_orderform').hide();
			$('#orderform .right_helper').fadeIn();
		}
	});

	// If credit card checkbox
	$('#orderform .credit_card').keyup(function() {
		checkRightSubmitButton();
	});

	// Rush change of radio button in order to validate on click
	// #orderform input.new_number_radio + span.ui-radio:first
	$("#orderform input.terms_radio + span.ui-checkbox:first").mousedown(function() {

		if (!$(this).hasClass("ui-checkbox-state-checked-hover") && !$(this).hasClass("ui-checkbox-state-checked")) {
			//$("orderform .terms span.ui-radio").removeClass("ui-radio-state-checked-hover");
			$(this).addClass("ui-checkbox-state-checked");
			checkRightSubmitButton();
		} else {
			$(this).removeClass("ui-checkbox-state-checked");
			checkRightSubmitButton();
		}
	});

	// If invoice radio buttons mouse down
	$("#orderform .invoice_section span.ui-radio").mousedown(function(event) {
		if (!$(event.target).hasClass("ui-radio-state-checked-hover") && !$(event.target).hasClass("ui-radio-state-checked")) {
			$("#orderform .invoice_section span.ui-radio").removeClass("ui-radio-state-checked-hover ui-radio-state-checked");
			$(event.target).addClass("ui-radio-state-checked");
		} else {
			$(event.target).removeClass("ui-radio-state-checked");
		}
	});
	// If invoice radio buttons mouse click
	$("#orderform .invoice_section span.ui-radio").click(function() {
		checkRightSubmitButton();
	});
	
	// If form submission attempted
	$('#orderform form').submit(function() {
 		$('#orderform .left_orderform input').attr("disabled", false);

		if (validateRightForm()) {
			return true;
		} else {
			return false;
		}
	});

	// mouseover effect on "bestill" button
	$('#orderform .subscription_chooser .order_btn').mouseover(function()
	{
		$(this).css("background","url(/img/orderform/bestill_btn_over.png) no-repeat top left");
	});

	$('#orderform .subscription_chooser .order_btn').mouseout(function()
	{
		$(this).css("background","url(/img/orderform/bestill_btn.png) no-repeat top left");
	});

	$('#leftmenu .subscription_chooser .order_btn').mouseover(function()
	{
		$(this).css("background","url(/img/orderform/bestill_btn_over.png) no-repeat top left");
	});

	$('#leftmenu .subscription_chooser .order_btn').mouseout(function()
	{
		$(this).css("background","url(/img/orderform/bestill_btn.png) no-repeat top left");
	});

});
