/*
 * $Id: partnerportal.js $
 *
 * Copyright (c) 2007 Logica. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of Logica
 * ("Confidential Information"). You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with Logica.
 *
 * LOGICA MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-
 * INFRINGEMENT. LOGICA SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
 * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES.
 */

/*
 * Constants.
 */
function _Constants() {
    // -- general --
    this.BLOCK = "block";
    this.BUTTON = "button";
    this.DIV = "div";
    this.FALSE = "false";
    this.HIDDEN = "hidden";
    this.HREF = "href";
    this.INPUT = "input";
    this.NONE = "none";
    this.ONCLICK = "onclick";
    this.SELECT = "select";
    this.SPAN = "span";
    this.SRC = "src";
    this.TEXT = "text";
    this.TRUE = "true";
    this.VISIBLE = "visible";

    // -- names --
    this.ACTION_CALCULATE = "calculate";
    this.ACTION_UNCONDITIONAL_SAVE = "unconditionalsave";
    this.ACTION_SAVE = "save";
    this.ACTION_TYPE = "actionType";
    this.ADD_BUTTON = "addButton";
    this.ALL_BUSINESS_REGISTERS = "allBusinessRegisters";
    this.AMOUNT = "amount";
    this.AREA_CODE = "areaCode";
    this.BUSINESS_REGISTER = "businessRegister";
    this.BUSINESS_REGISTER_CODE = "businessRegisterCode";
    this.BUSINESS_REGISTER_NAME = "businessRegisterName";
    this.BUSINESS_REGISTER_GROUP_CODE = "businessRegisterGroupCode";
    this.BUSINESS_REGISTER_OPTION_TEXT = "businessRegisterOptionText";
    this.BUSINESS_REGISTER_OPTION_VALUE = "businessRegisterOptionValue";
    this.BUTTON_CHANGE = "Ändra";
    this.CHOSEN_REGISTER_CODE = "chosenRegisterCode";
    this.CITY = "city";
    this.CLAIM_TYPE = "claimType";
    this.CLAIM_TYPE_NO = "claimTypeNo";
    this.CLIENT_NAME = "clientName";
    this.CLIENT_NO = "clientNo";
    this.CLIENT_TURNOVER = "clientTurnover";
    this.CONTRACT_NO = "contractNo";
    this.CONTRACT_SEARCH_PARAM = "contractSearchParam";
    this.DATE = "date";
    this.DESCRIPTION = "description";
    this.GROUP_CODE = "groupCode";
    this.GROUP_NO = "groupNo";
    this.GROUP_VERSION = "groupVersion";
    this.INVOICE_ADDRESS = "invoiceAddress";
    this.INVOICE_ADDRESS_AREA_CODE = "invoiceAddressAreaCode";
    this.INVOICE_ADDRESS_CITY = "invoiceAddressCity";
    this.IS_EXTERNAL_CLAIM = "isExternalClaim";
    this.IS_JOINT_STOCK_COMPANY = "isJointStockCompany";
    this.PERSONAL_COMPANY = "personalCompany";
    this.LEGAL_FORM = "legalForm";
    this.MUNICIPALITY_CODE = "municipalityCode";
    this.MUNICIPALITY_NAME = "municipalityName";
    this.ORGANIZATION_NO = "organizationNo";
    this.OK_BUTTON = "okButton";
    this.REAL_PROPERTY_UNIT = "realPropertyUnit";
    this.RISK_CLASS = "riskClass";
    this.RISK_CLASS_DESCRIPTION = "riskClassDescription";
    this.SEARCH_TEXT = "searchText";
    this.SELECTED_TAB = "selectedTab";
    this.SNI_CODE = "sniCode";
    this.SNI_DESCRIPTION = "sniDescription";
    this.STREET_ADDRESS = "streetAddress";
    this.SUB_BUSINESS_REGISTER_CODE = "subBusinessRegisterCode";
    this.SUB_BUSINESS_REGISTER_NAME = "subBusinessRegisterName";
    this.SUB_BUSINESS_REGISTER_GROUP_CODE = "subBusinessRegisterGroupCode";
    this.TURNOVER = "turnover";
    this.TURNOVER_EU = "turnoverEU";
    this.TURNOVER_NORDIC = "turnoverNordic";
    this.TURNOVER_WORLD = "turnoverWorld";
    this.VERSION_NO = "versionNo";
    this.TEMP_TABLE_ROW_INDEX = "tmpTableRowIndex";

    // -- elements --
    this.BTN_EXISTING_CLIENT = "btnExistingClient";
    this.BTN_NEW_CLIENT = "btnNewClient";
    this.BTN_NO_CLIENT = "btnNoClient";
    this.BTN_ADD = "addButton";

    this.FORM_CHANGE_INS_LOCS = "ChangeInsuranceLocationsForm";
    this.FORM_CHANGE_POLICY_FORM = "changePolicyForm";
    this.FORM_NEW_CONTRACT = "NewContractForm";
    this.FORM_VIEW_POLICY = "ViewPolicyForm";
    this.FORM_SEARCH_BUSINESS_REGISTER = "SearchBusinessRegisterForm";
    this.FORM_SEARCH_CONTRACTS = "SearchContractsForm";

    this.INPUT_BACK = "back";
    this.INPUT_SEARCH_TEXT = "searchText";

    this.DIV_SEARCH = "searchDiv";
    this.SPAN_SEARCH_RESULT = "searchResult";

    this.TABLE_BUSINESS = "businessTable";
    this.TABLE_CLAIM_TYPE = "claimTypeTable";
    this.TABLE_INSURANCE_LOCATIONS = "insuranceLocationsTable";
    
    // -- characters --
    this.AMPERSAND  ="&";
    this.EQUAL = "=";
    this.QUESTION_MARK = "?";
}

/*
 * Utility methods.
 */
function _Util() {
    /* Adds a new option to the inparameter select list */
    this.addOptionToSelect = function(select, optionText, optionValue, optionIndex) {
    	var nextOptionIndex = select.options.length;

    	if(optionIndex != null) {
    		nextOptionIndex = optionIndex;
        }

        select.options[nextOptionIndex] = new Option(optionText, optionValue);
    	return select.options[nextOptionIndex];
    }

    /* Gets an event's key code. Works for both IE and Firefox. */
    this.getEventKeyCode = function(e) {
        return e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
    }

    /* Prevents an event. Works for both IE and Firefox. */
    this.preventEvent = function(e) {
        if (window.event) {
            e.returnValue = false;
        } else {
            e.preventDefault();
        }
    }

    /* Checks that an input value only contains integers and dashes. Use this
     * method on the event onkeypress. */
    this.checkDateCharsValid = function(e) {
        var keyCode = this.getEventKeyCode(e);

        // Allow only integers, dash (-), backspace and tab
        if (keyCode != 8 && keyCode != 9 && keyCode != 189 && (keyCode < 35 || keyCode > 57)) {
            this.preventEvent(e);
        }
    }

    /* Checks that the parameter has the form yyyy-mm-dd */
    this.checkDateFormatValid = function(date) {
    
        var isValid = false;
        
        // Check the date
        if (date != "") {
            isValid = true;
            
            var dateArr = date.split("-");

            // Check that there are two hyphens
            if (dateArr.length != 3) {
                isValid = false;
            }

            // Check that there only integers
            if (isNaN(dateArr[0]) || isNaN(dateArr[1]) || isNaN(dateArr[2])) {
                isValid = false;
            }

            // The year must be bigger then 1970.
            if (dateArr[0] < 1970) {
                isValid = false;
            }

            // Month must be 1-12
            if (dateArr[1] < 1 || dateArr[1] > 12) {
                isValid = false;
            }

            // Date must be 1-31
            if (dateArr[2] < 1 || dateArr[2] > 31) {
                isValid = false;
            }
        }
        
        return isValid;
    }
        
    /* Checks that an input value is a number. Use this method on the event
     * onkeypress. */
    this.checkNumberValid = function(e) {
        var keyCode = this.getEventKeyCode(e);

        // 8 = backspace,
        // 9 = tab,
        // 45 = delete,
        // > 35 && < 57 numbers
        if (keyCode != 8 && keyCode != 9 && (keyCode < 35 || keyCode > 57)) {
            this.preventEvent(e);
        }
    }
    
    /* Checks that the parameter is a digit and has the right form*/
    this.checkAmountFormatValid = function(amount) {
    
        var isValid = false;
        
        if (amount != "") {
            isValid = true;
            
            if (isNaN(amount)) {
                isValid = false;
            }

            /*if (amount.indexOf(".") > -1 || amount.indexOf(",") > -1) {
                isValid = false;
            }*/

            if (amount < 0) {
                isValid = false;
            }
        }
        
        return isValid;
    }
    
    this.formatNumber = function(e, oField) {
        var keyNO = this.getEventKeyCode(e);

        if (keyNO != 8 && (keyNO < 35 || keyNO > 57)) {
            this.preventEvent(e)
        }

        if (keyNO < 48 || keyNO > 57) {
            return;
        }

        var oldValue = oField.value.replace(/\./g, "");
        var length = oldValue.length;

        var newValue = "";
        var i = length;

        for( ; i > 3; i = i-3) {
            newValue = "." + oldValue.slice(i-3, i) + newValue;
        }

        // When i is smaller than 3 we loose this part of string. Then get it explicitly.
        newValue = oldValue.slice(0, i) + newValue;
        oField.value = newValue;
    }
    
    /* Block the enter and the back button */
    this.blockEnterAndBack = function(e) {
        /*
        var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;

        if (keyCode == 13) { // || event.keyCode == 8) {
            e.returnValue = false;
        }*/
    }

    /* Creates a new HTML element */
    this.createHTMLElement = function(tagName, type, name, id, value, size, className) {
    	if (tagName == null || tagName == "") {
    		return null;
        }
 
        var newElement = document.createElement(tagName);

    	if (type != null && type != "") {
    	  	newElement.type = type;
        }

        if (name != null && name != "") {
    	  	newElement.name = name;
        }

        if (id != null && id != "") {
    	  	newElement.id = id;
        }

        if (value != null && value != "") {
    	  	newElement.value = value;
        }

        if (size != null && size != "") {
    	  	newElement.size = size;
        }

        if (className != null && className != "") {
    		newElement.className = className;
        }

        return newElement;
    }

    /* Inserts a new cell at the end of the row if the index is not specified */
    this.insertCellToRow = function(row, index) {
    	var insertIndex = -1;

    	if(index != null) {
    		insertIndex = index;
        }

        return row.insertCell(insertIndex);
    }

    /* Inserts a new row at the end of the table if the index is not specified */
    this.insertRowToTable = function(table, index) {
    	var insertIndex = -1;

    	if(index != null) {
    		insertIndex = index;
        }

        return table.insertRow(insertIndex);
    }

    /* Open a confirm dialog */
    this.openConfirm = function(text) {
        // Show confirm dialog; returns true if OK button clicked
        return confirm(text);
    }

    /* Open a new window */
    this.openWindow = function() {

    }

    /* Get the value of the back element */
    this.getBack = function() {
        return document.getElementById(jsConst.INPUT_BACK).value;
    }

    /* Set the back input, indicating that the user has clicked a back button */
    this.setBack = function() {
        document.getElementById(jsConst.INPUT_BACK).value = jsConst.TRUE;
    }

    /* Submits a form */
    this.submitForm = function(oForm) {
        oForm.submit();
    }

    /* Removes trailing spaces from a string */
    this.trimTrailing = function(str) {
        return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
    }

    this.trimAll = function(what) {
        var tmp = new String(what);

        if (tmp.indexOf(" ") != -1) {
            if (tmp.indexOf(" ") == 0) {
                tmp = tmp.substring(1, tmp.length);
                this.trimTrailing(tmp);
            }
        }

        if (tmp.lastIndexOf(" ") != -1) {
            if (tmp.lastIndexOf(" ") >= tmp.length - 1) {
                tmp = tmp.substring(0, tmp.length - 1);
                this.trimTrailing(tmp);
            }
        }

        return tmp;
    }

    this.showLoadingDiv = function(loadingText) {
        if (loadingText != "") {
            var oTable = document.getElementById("loadingTable");
            oTable.rows[0].cells[0].innerText = loadingText;
            alert(oTable.tagName);
        }

        document.getElementById("loading").style.visibility = "visible";
    }

    this.hideLoadingDiv = function() {
        document.getElementById("loading").style.visibility = "hidden";
    }

    /* Prepares elements for submit */
    this.prepareElementsForSubmit = function(oForm) {
        var allInputElements = oForm.getElementsByTagName(jsConst.INPUT);
        var allSelectElements = oForm.getElementsByTagName(jsConst.SELECT);

        this.setDisabledToReadOnly(allInputElements);
        this.setDisabledToReadOnly(allSelectElements);
    }

    /* Sets disabled elements as readonly */
    this.setDisabledToReadOnly = function(elements) {
        for (var i = 0, j = elements.length; i < j; i++) {
            if (elements[i].disabled) {
                elements[i].disabled = false;
                elements[i].readonly = true;
            }
        }
    }

    this.initPopup = function() {
        var oElement = document.getElementById("popupValidated");

        if (oElement != null && oElement.value == "true") {
            var parent = window.opener;

    	    // Close the popup window
		    window.close();

		    // Call refresh to apply changes and focus parent window.
		    parent.focus();
        }
    }
}

/**
 * This is a timer class for executing a method with every given delay ( default 400 ms.).
 * What this class does more than the javascript startimer is that if the method is called 
 * before the delay is consumed the timer is resetted to the original delay and restarted.
 */
function Timer() {
           
    var delay = 400;
    var timerID = null;
    
    this.setDelay = function(newDelay) {
    
        delay = newDelay;
    }

    this.startTimer = function (fireUpMethod) {
        
        // If a timer has been started then stop it.
        if(timerID != null) {
            self.clearTimeout(timerID);
        }
        
        // Start a new timer.
        timerID = self.setTimeout(fireUpMethod, delay);
    }
}

/*
 * Handles information 
 */
function _Information() {

    /* Pops a new window that shows the information */
    this.showInfo = function(url, infoNo) {

        url = url + "?infoNo="+infoNo;

        var child = window.open(url, "HelpPopup", "resizable=0, scrollbars=1, status=0, left=200, top=100, height=350, width=350");

        child.focus();
    }
}

// Initiate helper classes
var jsConst = new _Constants();
var util = new _Util();
var objInfo = new _Information();

/*
 * Methods for menu.
 */
function _Menu() {

    /* Search contracts */
    this.searchContract = function() {
        var oForm = document.getElementById(jsConst.FORM_SEARCH_CONTRACTS);
        var oInput = document.getElementById(jsConst.CONTRACT_SEARCH_PARAM);

        if (util.trimTrailing(oInput.value).length > 0) {
            oForm.submit();
        } else {
            return false;
        }
    }
}

// Menu class
var menu = new _Menu();

/*
 * Methods for Contract summary pages.
 */
function ContractSummary() {
    // -- elements --
    this.oInputContractNo = document.getElementById(jsConst.CONTRACT_NO);
    this.oInputVersionNo = document.getElementById(jsConst.VERSION_NO);
    this.oForm = document.getElementById(jsConst.FORM_VIEW_POLICY);

    // -- methods --

    /* Calls action forward for policy summary */
    this.callActionForward = function(url) {
        window.location = url;
    }

    /* Set values and submit form */
    this.viewPolicy = function(contractNo, versionNo) {
        this.oInputContractNo.value = contractNo;
        this.oInputVersionNo.value = versionNo;

        this.oForm.submit();
    }
}

/*
 * Methods for step one of new policy.
 */
function NewCaseClientChoiceStep() {
    // -- elements --
    this.oBtnExistingClient = document.getElementById(jsConst.BTN_EXISTING_CLIENT);
    this.oBtnNewClient = document.getElementById(jsConst.BTN_NEW_CLIENT);
    this.oBtnNoClient = document.getElementById(jsConst.BTN_NO_CLIENT);

    this.oInputOrganizationNo = document.getElementById(jsConst.ORGANIZATION_NO);
    this.oSelectClientName = document.getElementById(jsConst.CLIENT_NO);
    this.oSelectLegalForm = document.getElementById(jsConst.LEGAL_FORM);

    this.oForm = document.getElementById(jsConst.FORM_NEW_CONTRACT);

    // -- methods --
    /* Init */
    this.init = function() {
        this.oBtnNewClient.disabled = (this.oInputOrganizationNo.value == "");
        this.oBtnExistingClient.disabled = (this.oSelectClientName.selectedIndex == 0);
        this.oBtnNoClient.disabled = (this.oSelectLegalForm.selectedIndex == 0);
    }

    /* Layout control. Enable/disable elements. */
    this.elementControl = function(oElement) {
        // New client button
        if (oElement.id == this.oInputOrganizationNo.id) {
            this.oBtnNewClient.disabled = (this.oInputOrganizationNo.value == "");

            this.disableExistingClient();
            this.disableNoClient();

        // Existing client button
        } else if (oElement.id == this.oSelectClientName.id) {
            this.oBtnExistingClient.disabled = (this.oSelectClientName.selectedIndex == 0);

            this.disableNewClient();
            this.disableNoClient();

        // No client button
        } else if (oElement.id == this.oSelectLegalForm.id) {
            this.oBtnNoClient.disabled = (this.oSelectLegalForm.selectedIndex == 0);

            this.disableNewClient();
            this.disableExistingClient();
        }
    }

    this.disableNewClient = function() {
        this.oInputOrganizationNo.value = "";
        this.oBtnNewClient.disabled = true;
    }

    this.disableExistingClient = function() {
        this.oSelectClientName.selectedIndex = 0;
        this.oBtnExistingClient.disabled = true;
    }

    this.disableNoClient = function() {
        this.oSelectLegalForm.selectedIndex = 0;
        this.oBtnNoClient.disabled = true;
    }
}

function NewCaseClientStep() {
    // -- elements --
    this.oHiddenPersonalCompany = document.getElementById(jsConst.PERSONAL_COMPANY);
    this.oInputClientName = document.getElementById(jsConst.CLIENT_NAME);
    this.oSelectLegalForm = document.getElementById(jsConst.LEGAL_FORM);
    this.oInputOrgNo = document.getElementById(jsConst.ORGANIZATION_NO);
    this.oInputRisk = document.getElementById(jsConst.RISK_CLASS);
    this.oInputTurnover = document.getElementById(jsConst.TURNOVER);
    this.oInputSniCode = document.getElementById(jsConst.SNI_CODE);

    this.oForm = document.getElementById(jsConst.FORM_NEW_CONTRACT);

    // -- methods --
    /* Enable select boxes for the submit */
    this.enableElements = function() {
        this.oInputClientName.disabled = false;
        this.oSelectLegalForm.disabled = false;
        this.oInputOrgNo.disabled = false;
        this.oInputRisk.disabled = false;
        this.oInputTurnover.disabled = false;
        this.oInputSniCode.disabled = false;
    }
}

function NewCaseBusinessStep() {
    // -- elements --
    this.addButtonText = "";
    this.oTableBusiness = document.getElementById(jsConst.TABLE_BUSINESS);

    // -- methods --
    /* Init */
    this.init = function() {
        // Get the businesses for the selected branch
        this.getBusinessRegisters(true);

        var oBranches = document.getElementById(jsConst.BUSINESS_REGISTER_GROUP_CODE);

        if (oBranches.value != "") {
            oBranches.onchange();

            var oBusiness = document.getElementById(jsConst.BUSINESS_REGISTER_CODE);
            oBusiness.value = document.getElementById(jsConst.CHOSEN_REGISTER_CODE).value;
        }
    }

    /* Gets the businesses for a speccific branch */
    this.getBusinessRegisters = function(isMainBusiness) {
        var oAllBusinessRegisters = document.getElementById(jsConst.ALL_BUSINESS_REGISTERS);
        var oBranches = document.getElementById(isMainBusiness ? jsConst.BUSINESS_REGISTER_GROUP_CODE : jsConst.SUB_BUSINESS_REGISTER_GROUP_CODE);
        var oBusiness = document.getElementById(isMainBusiness ? jsConst.BUSINESS_REGISTER_CODE : jsConst.SUB_BUSINESS_REGISTER_CODE);

        // Clear all options except the first
        oBusiness.options.length = 1;

        // Loop through all businesses in the hidden select
        for (var i = 0, j = oAllBusinessRegisters.options.length; i < j; i++) {
            // Get current option
            var oOption = oAllBusinessRegisters.options[i];

            // Split the option's value into an array. The number before the
            // hyphen is the business' group code.
            var valueArr = oOption.value.split("-");

            // If chosen group has the same code as the current option, add it
            // to the business select
            if (valueArr[0] == oBranches.value) {
                oBusiness.options[oBusiness.options.length] = new Option(oOption.text, valueArr[1]);
            }
        }

        // Enable/disable the select element for businesses
        oBusiness.disabled = oBusiness.options.length < 2;
    }

    /* Adds a business to the table and prepares it for submit */
    this.addBusiness = function(oAddButton) {
        var oBranch = document.getElementById(jsConst.SUB_BUSINESS_REGISTER_GROUP_CODE);
        var oBusiness = document.getElementById(jsConst.SUB_BUSINESS_REGISTER_CODE);
        var oBusinessOption = oBusiness.options[oBusiness.selectedIndex];

        var businessCode = oBusinessOption.value;
        var businessName = oBusinessOption.text;

        // Create row
        var oRow = util.insertRowToTable(this.oTableBusiness);

        // Create two cells for the row
        var oCell0 = util.insertCellToRow(oRow);
        var oCell1 = util.insertCellToRow(oRow);

        // Create remove button
        var oButton = util.createHTMLElement(jsConst.INPUT, jsConst.BUTTON, null, null, "Ta bort", null, jsConst.BUTTON);
        //oButton.setAttribute(jsConst.ONCLICK, "obj.removeBusiness(this)");
        oButton.onclick = function() { obj.removeBusiness(oButton) };

        // Add the sub-business' name to cell 1
        oCell0.appendChild(document.createTextNode(businessName));
        oCell0.appendChild(util.createHTMLElement(jsConst.INPUT, jsConst.HIDDEN, jsConst.SUB_BUSINESS_REGISTER_CODE, null, businessCode, null, "hiddenelement"));
        oCell0.appendChild(util.createHTMLElement(jsConst.INPUT, jsConst.HIDDEN, jsConst.SUB_BUSINESS_REGISTER_NAME, null, businessName, null, "hiddenelement"));

        // Add remove button to cell 2
        oCell1.appendChild(oButton);

        // Clear
        oBranch.value = "";
        oBusiness.options.length = 1;
        oBusiness.disabled = true;
        oAddButton.disabled = true;
    }

    /* Remove a business */
    this.removeBusiness = function(oBtn) {
        var oRow = oBtn.parentNode.parentNode;
        this.oTableBusiness.deleteRow(oRow.rowIndex);
    }

    /* Disable/enable the add button */
    this.setAddButton = function(oSelect) {
        var oBtn = document.getElementById(jsConst.ADD_BUTTON);
        oBtn.disabled = (oSelect.value == "");
    }
}

function NewCaseClaimStep() {
    // -- elements --
    this.oTableClaimType = document.getElementById(jsConst.TABLE_CLAIM_TYPE);

    // -- methods --
    /* Adds a claim to the table and prepares it for submit */
    this.addClaim = function(oAddBtn) {
        if (!this.validateFields()) {
            return;
        }

        var oClaimType = document.getElementById(jsConst.CLAIM_TYPE);
        var oDate = document.getElementById(jsConst.DATE);
        var oAmount = document.getElementById(jsConst.AMOUNT);

        var claimTypeNo = oClaimType.options[oClaimType.selectedIndex].value;
        var claimTypeDesc = oClaimType.options[oClaimType.selectedIndex].text;

        var oRow = util.insertRowToTable(this.oTableClaimType);
        var oCell1 = util.insertCellToRow(oRow);
        var oCell2 = util.insertCellToRow(oRow);
        var oCell3 = util.insertCellToRow(oRow);
        var oCell4 = util.insertCellToRow(oRow);

        oCell1.appendChild(document.createTextNode(claimTypeDesc));
        oCell1.appendChild(util.createHTMLElement(jsConst.INPUT, jsConst.HIDDEN, "externalClaimTypeNo", null, claimTypeNo, null, "hiddenelement"));
        oCell1.appendChild(util.createHTMLElement(jsConst.INPUT, jsConst.HIDDEN, "externalClaimTypeDesc", null, claimTypeDesc, null, "hiddenelement"));

        oCell2.appendChild(document.createTextNode(oDate.value));
        oCell2.appendChild(util.createHTMLElement(jsConst.INPUT, jsConst.HIDDEN, "externalClaimDate", null, oDate.value, null, "hiddenelement"));

        oCell3.appendChild(document.createTextNode(oAmount.value));
        oCell3.appendChild(util.createHTMLElement(jsConst.INPUT, jsConst.HIDDEN, "externalClaimTotalCost", null, oAmount.value, null, "hiddenelement"));

        // Create remove button
        var oButton = util.createHTMLElement(jsConst.INPUT, jsConst.BUTTON, null, null, "Ta bort", null, jsConst.BUTTON);
        oButton.onclick = function() { obj.removeClaim(oButton) };

        oCell4.appendChild(oButton);

        // Clear
        oClaimType.value = oDate.value = oAmount.value = "";
        oAddBtn.disabled = true;
    }

    /* Removes a claim */
    this.removeClaim = function(oBtn) {
        var oRow = oBtn.parentNode.parentNode;
        this.oTableClaimType.deleteRow(oRow.rowIndex);
    }

    /* Disables/enables the add button */
    this.setAddButton = function() {
        var oBtn = document.getElementById(jsConst.ADD_BUTTON);
        var oClaimType = document.getElementById(jsConst.CLAIM_TYPE);
        var oDate = document.getElementById(jsConst.DATE);
        var oAmount = document.getElementById(jsConst.AMOUNT);

        oBtn.disabled = (oClaimType.value == "" || oDate.value == "" || oAmount.value == "");
    }

    this.validateFields = function() {
        var oDate = document.getElementById(jsConst.DATE);
        var oAmount = document.getElementById(jsConst.AMOUNT);

        var date = util.trimTrailing(oDate.value);
        var isValid = true;

        // Check the date
        if (date != "") {
            var dateArr = date.split("-");

            // Check that there are two hyphens
            if (dateArr.length != 3) {
                isValid = false;
            }

            // Check that there only integers
            if (isNaN(dateArr[0]) || isNaN(dateArr[1]) || isNaN(dateArr[2])) {
                isValid = false;
            }

            // Month must be 1-12
            if (dateArr[1] < 1 || dateArr[1] > 12) {
                isValid = false;
            }

            // Date must be 1-31
            if (dateArr[2] < 1 || dateArr[2] > 31) {
                isValid = false;
            }

            if (!isValid) {
                alert("Datum är inte angivet korrekt.");
                oDate.focus();
            }

            if (!isValid) {
                return isValid;
            }
        }

        var amount = util.trimTrailing(oAmount.value);

        if (amount != "") {
            if (isNaN(amount)) {
                isValid = false;
            }

            if (amount.indexOf(".") > -1 || amount.indexOf(",") > -1) {
                isValid = false;
            }

            if (amount < 0) {
                isValid = false;
            }

            if (!isValid) {
                alert("Bruttoskadekostnad är inte angivet korrekt.");
                oAmount.focus();
            }

            if (!isValid) {
                return isValid;
            }
        }

        return true;
    }
}

function NewCaseObjectCoverStep() {

    this.textBase = "";
    this.textRec = "";
    this.textAdd = "";
    this.imgPath = "";
    this.msie = false;
    this.warningDoSaveMsg = "";
    this.errObjectNo = 0;
    this.errFieldNo = 0;
    this.questActionType= "";

    this.init = function() {
        // Check if there is a message
        if (this.warningDoSaveMsg != "") {
            // Show a confirm dialog
            var retval = confirm(this.warningDoSaveMsg);

            if (retval) {
                // If the user clicked yes/ok, submit the form
                this.setActionType(jsConst.ACTION_UNCONDITIONAL_SAVE);
                util.submitForm(document.getElementById(jsConst.FORM_NEW_CONTRACT));
            }
        } else if (this.errObjectNo > 0 && this.errFieldNo > 0) {
            // If an error was returned, higlight the object where it occured

            // Find the object and open the term group
            var oTermGroup = document.getElementById("objectlabel_" + this.errObjectNo);
            var oTab = oTermGroup.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;

            // Open correct tab
            if (oTab.id == "tab_contents_base") {
                this.openTabContent("tabBase");
            } else if (oTab.id == "tab_contents_recommended") {
                this.openTabContent("tabRec");
            } else if (oTab.id == "tab_contents_additional") {
                this.openTabContent("tabAdd");
            }
            
            oTermGroup.onclick();

            // Find the field
            var oField = document.getElementsByName("F-" + this.errFieldNo)[0];

            // If the element is an input field, select the value
            if (oField.tagName == "INPUT") {
                oField.select();
            }

            // Set focus to the field
            oField.focus();
        }
    }

    this.doSubmit = function() {
        var str = "";
        var actionType = document.getElementById(jsConst.ACTION_TYPE).value;

        if (actionType == jsConst.ACTION_CALCULATE) {
            str = "Beräknar premie...";
        } else if (actionType == jsConst.ACTION_SAVE) {
            str = "Sparar...";
        }

        var oSpan = document.getElementById("loadingSpan");
        oSpan.innerHTML = str;
        oSpan.style.visibility = "visible";
    }

    this.commissionChanged = function() {
        document.getElementById("annualCommissionCell").innerHTML = "<span style='color: red'>####</span>";
        document.getElementById("annualPremiumGrossCell").innerHTML = "<span style='color: red'>####</span>";
    }

    this.openTabContent = function(tabId) {
        var oTabs = new Array(3);
        oTabs[0] = document.getElementById("tabBase");
        oTabs[1] = document.getElementById("tabRec");
        oTabs[2] = document.getElementById("tabAdd");

        var oTabContents = new Array(3);
        oTabContents[0] = document.getElementById("tab_contents_base");
        oTabContents[1] = document.getElementById("tab_contents_recommended");
        oTabContents[2] = document.getElementById("tab_contents_additional");

        var i = 0;

        while (i < 3) {
            oTabs[i].innerHTML = "";

            if (oTabs[i].id == tabId) {
                var oSpan = document.createElement("span");
                oSpan.innerHTML = this.getText(oTabs[i].id);
                oTabs[i].appendChild(oSpan);

                // Open tab contents
                oTabContents[i].style.visibility = jsConst.VISIBLE;
                oTabContents[i].style.display = jsConst.BLOCK;
            } else if (oTabs[i].childNodes.length < 3) {
                var oLink = document.createElement("a");
                var href = "javascript:obj.openTabContent('" + oTabs[i].id + "')";
                oLink.setAttribute(jsConst.HREF, href);
                oLink.innerHTML = this.getText(oTabs[i].id);
                oTabs[i].appendChild(oLink);

                // Close tab contents
                oTabContents[i].style.visibility = jsConst.HIDDEN;
                oTabContents[i].style.display = jsConst.NONE;
            }

            i++;
        }
    }

    this.getText = function(tabId) {
        var text = "";

        switch (tabId) {
            case "tabBase":
                text = this.textBase;
                break;
            case "tabRec":
                text = this.textRec;
                break;
            case "tabAdd":
                text = this.textAdd;
                break;
        }

        return text;
    }

    this.openTermGroup = function(oSpan, id) {
        var oElement = document.getElementById("object_" + id);
        var oImg = this.msie ? oSpan.childNodes[0] : oSpan.childNodes[1];

        if (oElement.style.visibility == jsConst.HIDDEN) {
            oElement.style.visibility = jsConst.VISIBLE;
            oElement.style.display = jsConst.BLOCK;
            oImg.src = this.imgPath + "/images/arrow_down.gif";
        } else {
            oElement.style.visibility = jsConst.HIDDEN;
            oElement.style.display = jsConst.NONE;
            oImg.src = this.imgPath + "/images/arrow_right.gif";
        }
    }

    this.openTermGroupChkBox = function(oChkBox, oSpan, id) {
        var oElement = document.getElementById("object_" + id);
        var oImg = this.msie ? oSpan.childNodes[0] : oSpan.childNodes[1];

        if (oElement.style.visibility == jsConst.HIDDEN & oChkBox.checked == true) {
            oElement.style.visibility = jsConst.VISIBLE;
            oElement.style.display = jsConst.BLOCK;
            oImg.src = this.imgPath + "/images/arrow_down.gif";
        } else if (oElement.style.visibility == jsConst.VISIBLE & oChkBox.checked == false) {
            oElement.style.visibility = jsConst.HIDDEN;
            oElement.style.display = jsConst.NONE;
            oImg.src = this.imgPath + "/images/arrow_right.gif";
        }
    }
    
    this.setActionType = function(type) {
        var oElement = document.getElementById(jsConst.ACTION_TYPE);
        oElement.value = type;
    }

    /* Open a popup window showing a questionnaire */
    this.openQuestionnaireWindow = function(url) {
        var wind = window.open(url, "Questionnaire", "resizable=0, scrollbars=1, status=0, left=200, top=100, height=670, width=465");
        wind.focus();
    }
}

/*
 * General methods for View policy.
 */
function ViewPolicy() {
    this.cancelChangesOnContractText = "";
    this.changeAdditionalInfoText = "";
    this.cancelChangesOnContractButtonText = "";
    this.cancelRenewalContractText = "";
    this.cancelRenewalContractButtonText = "";

    this.deleteQuote = function(oButton) {

        // Check if the trigger button is in the cancel contract changes' state?
        if( this.cancelChangesOnContractButtonText == oButton.value) {
        
            // if it's not the OK button that's been clicked then return
            if(!util.openConfirm(this.cancelChangesOnContractText)) {
                return
            }
        }
        // Check if the trigger button is in the cancel contract renewals state? 
        else if( this.cancelRenewalContractButtonText == oButton.value) {
        
            // if it's not the OK button that's been clicked then return
            if(!util.openConfirm(this.cancelRenewalContractText)) {
                return
            }
        }
            
        // Set the action of the form to the buttons value.
        oButton.form.action = oButton.form.action + "?method=" + oButton.value;

        // Submit the form with updated action.
        oButton.form.submit();
    }

    this.changeAdditionalInfo = function() {
        var oForm = document.getElementById(jsConst.FORM_CHANGE_POLICY_FORM);
        
        oForm.action += "?method=" + this.changeAdditionalInfoText;
        oForm.submit();
    }
    
    this.fireCalculateAction = function(button) {
        var oForm = document.getElementById(jsConst.FORM_CHANGE_POLICY_FORM);
        
        oForm.action += "?method=" + button.value;
        oForm.submit();
    }
}

/*
 * Methods for tabs for View policy.
 */
function ViewPolicyTabs() {
    // -- elements --
    this.oInputSelectedTab = document.getElementById(jsConst.SELECTED_TAB);
    this.oForm = document.getElementById(jsConst.FORM_VIEW_POLICY);

    // -- methods --

    /* Submits form when user clicks a tab */
    this.tabClick = function(tab) {
        this.oInputSelectedTab.value = tab;
        this.oForm.submit();
    }
}


/*
 * Methods for Change Insurance Locations
 */
function ChangeInsLocs() {

	this.url = "";
	this.isMainInsuranceLoc = "";
	this.realPropertyUnit = "";
	this.municipalityCode = "";
	this.municipalityName = "";
	this.streetAddress = "";
	this.areaCode = "";
	this.city = "";
	this.ttIndex = "";
	this.triggerButton = null;

    this.popUpMaintainWindow = function(url,
    									theEventTrigger,
    									isMainInsuranceLoc,
    									unit,
    									municipalityCode,
    									streetAddress,
    									code,
    									city,
    									index) {

    	this.url = url;
    	this.isMainInsuranceLoc = isMainInsuranceLoc;
    	this.realPropertyUnit = unit;
		this.municipalityCode = municipalityCode;
		this.streetAddress = streetAddress;
		this.areaCode = code;
		this.city = city;
		
		// If it is a new location then the index send will be null. Set it to 0.
		if(index == null)
			index = "0";
		this.ttIndex = index;

		this.triggerButton = theEventTrigger;

    	var child = window.open(url, "InsLocPopup", "resizable=0, status=no, titlebar=yes, left=200, top=100, height=425, width=310");
     	child.focus();
    }

    this.updateOnclickEvent = function(button, object) {

   		var url = object.url;
		var isMainInsuranceLoc = object.isMainInsuranceLoc;
		var realProperty = object.realPropertyUnit;
		var municipalityCode = object.municipalityCode;
		var streetAddress = object.streetAddress;
		var areaCode = object.areaCode;
		var city = object.city;
		var index = object.ttIndex;
		var theEventTrigger = object.triggerButton;

		button.onclick = function(){object.popUpMaintainWindow(url,
															   theEventTrigger,
															   isMainInsuranceLoc,
															   realProperty,
															   municipalityCode,
															   streetAddress,
															   areaCode,
															   city,
															   index)};
    }

    this.saveLocation = function() {

    	// New insurance Location...
    	if(this.isMainInsuranceLoc == null)
    	{

    		this.isMainInsuranceLoc = jsConst.FALSE;

    		// Get the table with the insurance locations.
	   		var table = document.getElementById(jsConst.TABLE_INSURANCE_LOCATIONS);

	   		// The trigger button for adding new locations is (must be) the last row.
            // Get the row index for that button and add the new row before it. 
            index = (this.triggerButton.parentNode.parentNode).rowIndex;

            // Create a new row.
            var newRow = util.insertRowToTable(table, index);

			// Create four cells and add appropriate inputs to these cells.
			var cell1 = util.insertCellToRow(newRow);
			var element = util.createHTMLElement("input", "text", jsConst.REAL_PROPERTY_UNIT, jsConst.REAL_PROPERTY_UNIT, this.realPropertyUnit);
			element.disabled = jsConst.TRUE;
            cell1.appendChild(element);

            var cell2 = util.insertCellToRow(newRow);
            element = util.createHTMLElement("input", "text", jsConst.MUNICIPALITY_NAME, jsConst.MUNICIPALITY_NAME, this.municipalityName);
            element.disabled = jsConst.TRUE;
            cell2.appendChild(element);

            element = util.createHTMLElement("input", "hidden", jsConst.MUNICIPALITY_CODE, jsConst.MUNICIPALITY_CODE, this.municipalityCode);
            cell2.appendChild(element);

            var cell3 = util.insertCellToRow(newRow);
            element = util.createHTMLElement("input", "text", jsConst.STREET_ADDRESS, jsConst.STREET_ADDRESS, this.streetAddress);
            element.disabled = jsConst.TRUE;
            cell3.appendChild(element);

			element = util.createHTMLElement("input", "hidden", jsConst.AREA_CODE, jsConst.AREA_CODE, this.areaCode);
	 		cell3.appendChild(element);

			element = util.createHTMLElement("input", "hidden", jsConst.CITY, jsConst.CITY, this.city);
	 		cell3.appendChild(element);
	 		
	 		element = util.createHTMLElement("input", "hidden", jsConst.TEMP_TABLE_ROW_INDEX, jsConst.TEMP_TABLE_ROW_INDEX, "0");
            cell3.appendChild(element);

			var cell4 = util.insertCellToRow(newRow);
			// Create the button
			element = util.createHTMLElement("input", "button", "modifyInsLocButton", "modifyInsLocButton", jsConst.BUTTON_CHANGE, "", "button");

			// Set the trigger to the newly created button. And update the onclick event for this button.
			this.triggerButton = element;
			this.updateOnclickEvent(this.triggerButton, this);

	 		cell4.appendChild(element);

    	}
    	else// if(this.isMainInsuranceLoc == jsConst.FALSE)
    	{
    		//Get the parent(tr) of the parent(td) of the trigger button.
    		var parentRow = this.triggerButton.parentNode.parentNode;

    		// Get table cells for the selected row.
    		var cellList = parentRow.cells;

    		for(var cellNo = 0; cellNo < cellList.length; cellNo++)
    		{
    			// Get the input nodes for the every cell.
    			var inputList = cellList[cellNo].getElementsByTagName(jsConst.INPUT);

    			// Iterate the list and edit the value for the found input fields.
    			for(var nodeNo = 0; nodeNo < inputList.length; nodeNo++)
    			{
    				if(inputList[nodeNo].id == jsConst.REAL_PROPERTY_UNIT)
    				{
    					inputList[nodeNo].value = this.realPropertyUnit;
    				}
	    			else if(inputList[nodeNo].id == jsConst.MUNICIPALITY_CODE)
	    			{
	    				inputList[nodeNo].value = this.municipalityCode;
	    			}
	    			else if(inputList[nodeNo].id == jsConst.MUNICIPALITY_NAME)
	    			{
	    				inputList[nodeNo].value = this.municipalityName;
	    			}
	    			else if(inputList[nodeNo].id == jsConst.STREET_ADDRESS)
	    			{
	    				inputList[nodeNo].value = this.streetAddress;
	    			}
	    			else if(inputList[nodeNo].id == jsConst.AREA_CODE)
	    			{
	    				inputList[nodeNo].value = this.areaCode;
	    			}
	    			else if(inputList[nodeNo].id == jsConst.CITY)
	    			{
	    				inputList[nodeNo].value = this.city;
	    			}
	    			else if(inputList[nodeNo].id == "modifyInsLocButton")
	    			{
	    				this.triggerButton = inputList[nodeNo];
   						this.updateOnclickEvent(this.triggerButton, this);
	    			}
    			}
    		}
    	}
    }

    this.removeLocation = function() {

    	var table = document.getElementById(jsConst.TABLE_INSURANCE_LOCATIONS);

        var oRow = this.triggerButton.parentNode.parentNode;
        
    	if(objChangeInsLocs.isMainInsuranceLoc != jsConst.TRUE && objChangeInsLocs.isMainInsuranceLoc != null)
    	{
            table.deleteRow(oRow.rowIndex);
    	}
    }
    
    this.enableElements = function() {
        
        var elems = document.getElementsByName(jsConst.REAL_PROPERTY_UNIT);
        for(var index = 0; index < elems.length; index++)
        {
            elems[index].disabled = false;
        }
        
        var elems = document.getElementsByName(jsConst.MUNICIPALITY_NAME);
        for(var index = 0; index < elems.length; index++)
        {
            elems[index].disabled = false;
        }
        
        var elems = document.getElementsByName(jsConst.STREET_ADDRESS);
        for(var index = 0; index < elems.length; index++)
        {
            elems[index].disabled = false;
        }
    }
}

/*
 * Pop the maintain insurance location window.
 */
function MaintainInsLocs() {

    this.oAreaCode = "";
    this.oCaptionMainLoc = "";
    this.oCaptionOtherLoc = "";
     
    this.init = function(captionMainLoc, captionOtherLoc) {
        
        this.oCaptionMainLoc = captionMainLoc;
        this.oCaptionOtherLoc = captionOtherLoc;
    }

	/* Gets the object containing the values send to popup window and fill the fields. */
    this.fillPopUpFormFields = function(){

		var objChangeInsLoc = window.opener.objChangeInsLocs;
        
		//If this is maininsurance we receive true, than disable the remove button. Or if null we create a new one
		if(objChangeInsLoc.isMainInsuranceLoc == jsConst.TRUE) {
        
            document.getElementById("mainheading").innerHTML = this.oCaptionMainLoc;
			document.getElementById("removeButton").disabled = true;
		} else if(objChangeInsLoc.isMainInsuranceLoc == null){
        
            document.getElementById("mainheading").innerHTML = this.oCaptionOtherLoc;
            document.getElementById("removeButton").disabled = true;
		} else {
        
            document.getElementById("mainheading").innerHTML = this.oCaptionOtherLoc;
			document.getElementById("removeButton").disabled = false;
		}

		// If the value of the element "popupValidated" is empty the page is loaded first time then 
		// if this is a new location set the popup window's fields' values to the object's.
		if("" == document.getElementById("popupValidated").value && objChangeInsLoc.isMainInsuranceLoc != null)
		{
			document.getElementById(jsConst.REAL_PROPERTY_UNIT).value = objChangeInsLoc.realPropertyUnit;
			document.getElementById(jsConst.MUNICIPALITY_CODE).value = objChangeInsLoc.municipalityCode;
			document.getElementById(jsConst.STREET_ADDRESS).value = objChangeInsLoc.streetAddress;
			document.getElementById(jsConst.AREA_CODE).value = objChangeInsLoc.areaCode;
            this.oAreaCode = objChangeInsLoc.areaCode;
            document.getElementById("cityDiv").innerHTML = objChangeInsLoc.city;
			document.getElementById(jsConst.CITY).value = objChangeInsLoc.city;
			document.getElementById(jsConst.TEMP_TABLE_ROW_INDEX).value = objChangeInsLoc.ttIndex;
		}
    }

    /* Save the values from the form fields into object from parent window */
    this.saveValuesAndClosePopup = function() {

		var objChangeInsLoc = window.opener.objChangeInsLocs;
		
		objChangeInsLoc.realPropertyUnit = document.getElementById(jsConst.REAL_PROPERTY_UNIT).value;
		objChangeInsLoc.municipalityCode = document.getElementById(jsConst.MUNICIPALITY_CODE).value;

		var selectedIndex = document.getElementById(jsConst.MUNICIPALITY_CODE).selectedIndex;
		var selectedRegion = document.getElementById(jsConst.MUNICIPALITY_CODE).options[selectedIndex];;
		objChangeInsLoc.municipalityName = selectedRegion.text;
		
		objChangeInsLoc.streetAddress = document.getElementById(jsConst.STREET_ADDRESS).value;
		objChangeInsLoc.areaCode = document.getElementById(jsConst.AREA_CODE).value;
		objChangeInsLoc.city = document.getElementById(jsConst.CITY).value;

		this.closePopUpWindow();
		objChangeInsLoc.saveLocation();
	}

	this.removeLocation = function() {

		var objChangeInsLoc = window.opener.objChangeInsLocs;

		this.closePopUpWindow();
		objChangeInsLoc.removeLocation();
	}

	this.closePopUpWindow = function(){

    	var parent = window.opener;

    	//Close the popup window
		window.close();

		//Call refresh to apply changes and focus parent window.
		parent.focus();
    }
    
    this.deleteCity = function() {
        
        if(this.oAreaCode != document.getElementById(jsConst.AREA_CODE).value) {
        
            document.getElementById("cityDiv").innerHTML = "";
            document.getElementById(jsConst.CITY).value = "";
            document.getElementById(jsConst.MUNICIPALITY_CODE).selectedIndex = 0;
        }
    }
}

function ChangeClientInfo() {
    // -- elements --
    this.oInputClientName = document.getElementById(jsConst.CLIENT_NAME);
    this.oInputLegalForm = document.getElementById(jsConst.LEGAL_FORM);
    this.oInputInvoiceAddress = document.getElementById(jsConst.INVOICE_ADDRESS);
    this.oInputAreaCode = document.getElementById(jsConst.INVOICE_ADDRESS_AREA_CODE);
    this.oInputCity = document.getElementById(jsConst.INVOICE_ADDRESS_CITY);
    this.oInputRiskClass = document.getElementById(jsConst.RISK_CLASS);

    // -- methods --
    
    this.enableElements = function() {
    
		document.getElementById(jsConst.ORGANIZATION_NO).disabled = false;
		document.getElementById(jsConst.LEGAL_FORM).disabled = false;
		document.getElementById(jsConst.RISK_CLASS_DESCRIPTION).disabled = false;
		document.getElementById(jsConst.CLIENT_TURNOVER).disabled = false;
		document.getElementById(jsConst.SNI_CODE).disabled = false;
		document.getElementById(jsConst.SNI_DESCRIPTION).disabled = false;
    }
}

function ChangeBusinessRegister() {

    this.addButtonText = "";
    this.oTableBusiness = document.getElementById(jsConst.TABLE_BUSINESS);
    
    var searchObj = null;

    this.init = function(sObj) {
        
        searchObj = sObj;
    }
    
    this.addBusiness = function(oAddButton) {
        var oBusiness = document.getElementById(jsConst.BUSINESS_REGISTER);
        var oBusinessOption = oBusiness.options[oBusiness.selectedIndex];

        var businessCode = oBusinessOption.value;
        var businessName = oBusinessOption.text;

        // Create row
        var oRow = util.insertRowToTable(this.oTableBusiness);

        // Create three cells for the row
        var oCell0 = util.insertCellToRow(oRow);
        var oCell1 = util.insertCellToRow(oRow);
        var oCell2 = util.insertCellToRow(oRow);
        var oCell3 = util.insertCellToRow(oRow);
        var oCell4 = util.insertCellToRow(oRow);

        // Create remove button
        var oButton = util.createHTMLElement(jsConst.INPUT, jsConst.BUTTON, null, null, "Ta bort", null, jsConst.BUTTON);
        //oButton.setAttribute(jsConst.ONCLICK, "obj.removeBusiness(this)");
        oButton.onclick = function() { obj.removeBusiness(oButton) };

        // Add the sub-business' name to cell 1
        oCell0.appendChild(document.createTextNode(businessName));
        oCell0.appendChild(util.createHTMLElement(jsConst.INPUT, jsConst.HIDDEN, jsConst.BUSINESS_REGISTER_CODE, null, businessCode, null, "hiddenelement"));
        oCell0.appendChild(util.createHTMLElement(jsConst.INPUT, jsConst.HIDDEN, jsConst.BUSINESS_REGISTER_NAME, null, businessName, null, "hiddenelement"));
        // Add an index input element with 0 value.
        oCell0.appendChild(util.createHTMLElement(jsConst.INPUT, jsConst.HIDDEN, jsConst.TEMP_TABLE_ROW_INDEX, null, "0", null, "hiddenelement"));
        
        // Add input text...
        oCell1.appendChild(util.createHTMLElement(jsConst.INPUT, "text", "turnoverNordic", null, "0", null, "layoutInput"));
        oCell2.appendChild(util.createHTMLElement(jsConst.INPUT, "text", "turnoverEU", null, "0", null, "layoutInput"));
        oCell3.appendChild(util.createHTMLElement(jsConst.INPUT, "text", "turnoverWorld", null, "0", null, "layoutInput"));
        
        // Add remove button to last cell
        oCell4.appendChild(oButton);

        // Clear
        oBusiness.value = "";
        oAddButton.disabled = true;
    }

    this.removeBusiness = function(oBtn) {
        var oRow = oBtn.parentNode.parentNode;
        this.oTableBusiness.deleteRow(oRow.rowIndex);
    }

    this.setAddButton = function(oSelect) {
        var oBtn = document.getElementById(jsConst.ADD_BUTTON);
        oBtn.disabled = (oSelect.value == "");
    }
    
    this.setBusiness = function(industryCode) {
        
        var oBusiness = document.getElementById(jsConst.BUSINESS_REGISTER);
        document.getElementById(jsConst.BTN_ADD).disabled = false;
        
        oBusiness.value = industryCode;
    }
    
    this.resetSelect = function() {
        
        document.getElementById(jsConst.BUSINESS_REGISTER).value = "";
        document.getElementById(jsConst.BTN_ADD).disabled = true;
    }
    
    this.executeSearching = function() {
        
        var selectObject = document.getElementById(jsConst.BUSINESS_REGISTER);
        var selectedBusiness = selectObject.options[selectObject.selectedIndex];
        
        if(selectedBusiness.value != "") {
            document.getElementById(jsConst.BTN_ADD).disabled = false;
            
            if (searchObj != null) {
                searchObj.submitFormOnSelect(selectedBusiness.value, selectedBusiness.text);
                searchObj.resetInputSearchText();
            }
        }
        else {
            document.getElementById(jsConst.BTN_ADD).disabled = true;
            document.getElementById(jsConst.SPAN_SEARCH_RESULT).innerHTML = "";
        }
    }
    
    
    this.startTimer = function(objTimer) {
        
        objTimer.startTimer(this.executeSearching);
    }
    
    this.useTheAnswer = function(value) {
        
        document.getElementById(jsConst.SPAN_SEARCH_RESULT).innerHTML = value;
    }
}

function GetQuote() {
    
    this.submifForm = function() {
        
        /*if(document.getElementById("getQuoteAction").value == "true") {
        
            // Increase the version number with one because when we get an offert the version number is increased!.
            document.getElementById("versionNo").value = document.getElementById("versionNo").value++;
            
        }*/

        // Submit the form.
        document.getElementById("backToViewPolicy").submit();
    }
    
    this.disableGetQuoteAction = function(text) {

        document.getElementById("getQuoteDiv").innerHTML = text;
        document.getElementById("getQuoteForm").submit();
    }
}

function ChangeClaimHistory() {
// -- elements --
    this.oTableClaimType = document.getElementById(jsConst.TABLE_CLAIM_TYPE);

    // -- methods --
    /* Adds a claim to the table and prepares it for submit */
    this.addClaim = function(oAddBtn) {
        if (!this.validateFields()) {
            return;
        }

        var oClaimType = document.getElementById(jsConst.CLAIM_TYPE);
        var oDate = document.getElementById(jsConst.DATE);
        var oAmount = document.getElementById(jsConst.AMOUNT);

        var claimTypeNo = oClaimType.options[oClaimType.selectedIndex].value;
        var claimTypeDesc = oClaimType.options[oClaimType.selectedIndex].text;

        var oRow = util.insertRowToTable(this.oTableClaimType);
        var oCell1 = util.insertCellToRow(oRow);
        var oCell2 = util.insertCellToRow(oRow);
        var oCell3 = util.insertCellToRow(oRow);
        var oCell4 = util.insertCellToRow(oRow);

        oCell1.appendChild(document.createTextNode(claimTypeDesc));
        oCell1.appendChild(util.createHTMLElement(jsConst.INPUT, jsConst.HIDDEN, "claimTypeDescription", null, claimTypeDesc, null, "hiddenelement"));
        oCell1.appendChild(util.createHTMLElement(jsConst.INPUT, jsConst.HIDDEN, "claimTypeNo", null, claimTypeNo, null, "hiddenelement"));
        // Add an index input element with 0 value
        oCell1.appendChild(util.createHTMLElement(jsConst.INPUT, jsConst.HIDDEN, jsConst.TEMP_TABLE_ROW_INDEX, null, "0", null, "hiddenelement"));
        
        var dateInput = util.createHTMLElement(jsConst.INPUT, jsConst.TEXT, "claimDate", null, oDate.value, null, null);
        dateInput.onkeyup = function() { obj.checkDateValue(dateInput) };
        oCell2.appendChild(dateInput);
        
        var amountInput = util.createHTMLElement(jsConst.INPUT, jsConst.TEXT, "claimCost", null, oAmount.value, null, null);
        amountInput.onkeyup = function() { obj.checkAmountValue(amountInput) };
        oCell3.appendChild(amountInput);
        
        // Create remove button
        var oButton = util.createHTMLElement(jsConst.INPUT, jsConst.BUTTON, null, null, "Ta bort", null, jsConst.BUTTON);
        oButton.onclick = function() { obj.removeClaim(oButton) };

        oCell4.appendChild(oButton);

        // Clear
        oClaimType.value = oDate.value = oAmount.value = "";
        oAddBtn.disabled = true;
    }

    /* Removes a claim */
    this.removeClaim = function(oBtn) {
        var oRow = oBtn.parentNode.parentNode;
        this.oTableClaimType.deleteRow(oRow.rowIndex);
    }

    /* Disables/enables the add button */
    this.setAddButton = function() {
        var oBtn = document.getElementById(jsConst.ADD_BUTTON);
        var oClaimType = document.getElementById(jsConst.CLAIM_TYPE);
        var oDate = document.getElementById(jsConst.DATE);
        var oAmount = document.getElementById(jsConst.AMOUNT);

        oBtn.disabled = (oClaimType.value == "" || oDate.value == "" || oAmount.value == "");
    }

    this.checkDateValue = function(object) {

        var oBtn = document.getElementById(jsConst.OK_BUTTON);
        oBtn.disabled = false;

        // if the date field is not validated then disable the ok button.
        if(!util.checkDateFormatValid(object.value)) {
            oBtn.disabled = true;
        }
    }

    this.checkAmountValue = function(object) {

        var oBtn = document.getElementById(jsConst.OK_BUTTON);
        oBtn.disabled = false;
        
        // if the date field is not validated then disable the ok button.
        if(!util.checkAmountFormatValid(object.value)) {
            oBtn.disabled = true;
        }
    }
        
    this.validateFields = function() {
    
        var oDate = document.getElementById(jsConst.DATE);
        var oAmount = document.getElementById(jsConst.AMOUNT);

        var date = util.trimTrailing(oDate.value);
        var isValid = util.checkDateFormatValid(date);

        if (!isValid) {
            alert("Datum är inte angivet korrekt.");
            oDate.focus();
            return isValid;
        }

        var amount = util.trimTrailing(oAmount.value);
        isValid = util.checkAmountFormatValid(amount);
        
        if (!isValid) {
            alert("Bruttoskadekostnad är inte angivet korrekt.");
            oAmount.focus();
                return isValid;
        }

        return true;
    }
}

function SignContract() {

    this.oBDate = document.getElementById("formattedInceptionDate");
    this.oEDate = document.getElementById("formattedEffectiveToDate");
    
    this.validateInceptionDate = function() {
        
        var date = util.trimTrailing(this.oBDate.value);
        date = date.replace(/-/g, "");
        
        var newValue = "";
        if(date.length == 8) {
        
            newValue = date.slice(0,4) +"-"+ date.slice(4,6) +"-"+ date.slice(6,8);
            date=newValue;

            // Check the date
            var dateArr = date.split("-");
            var isValid = true;

            // Check that there only integers
            if (isNaN(dateArr[0]) || isNaN(dateArr[1]) || isNaN(dateArr[2])) {
                isValid = false;
            }

            // Year must
            if (dateArr[0] < 2000) {
                isValid = false;
            }
            
            // Month must be 1-12
            if (dateArr[1] < 1 || dateArr[1] > 12) {
                isValid = false;
            }

            // Date must be 1-31
            if (dateArr[2] < 1 || dateArr[2] > 31) {
                isValid = false;
            }

            // Because of the calendar you have to see over the button disabling system. Right now remove this functionality.
            //document.getElementById("submitButton").disabled = true;
            
            if (isValid) {
            
                var eDate = parseInt(dateArr[0], 10) + 1;
                this.oBDate.value = date;
                //if( this.oEDate.value == "") {
                    this.oEDate.value = eDate + "-" + dateArr[1] + "-" + dateArr[2];
                //}
                // Because of the calendar you have to see over the button disabling system. Right now remove this functionality.
                //document.getElementById("submitButton").disabled = false;
            }
        } else {
            
            this.oEDate.value = "";
            // Because of the calendar you have to see over the button disabling system. Right now remove this functionality.
            //document.getElementById("submitButton").disabled = true;
        }
    }
    
    this.validateEffectiveToDate = function() {
        
        var date = util.trimTrailing(this.oEDate.value);
        date = date.replace(/-/g, "");
        
        var newValue = "";
        if(date.length == 8) {
        
            newValue = date.slice(0,4) +"-"+ date.slice(4,6) +"-"+ date.slice(6,8);
            date=newValue;

            // Check the date
            var dateArr = date.split("-");
            var isValid = true;

            // Check that there only integers
            if (isNaN(dateArr[0]) || isNaN(dateArr[1]) || isNaN(dateArr[2])) {
                isValid = false;
            }

            // Year must
            if (dateArr[0] < 2000) {
                isValid = false;
            }
            
            // Month must be 1-12
            if (dateArr[1] < 1 || dateArr[1] > 12) {
                isValid = false;
            }

            // Date must be 1-31
            if (dateArr[2] < 1 || dateArr[2] > 31) {
                isValid = false;
            }

            // Because of the calendar you have to see over the button disabling system. Right now remove this functionality.
            //document.getElementById("submitButton").disabled = true;
            
            if (isValid) {
            
                var eDate = parseInt(dateArr[0], 10) + 1;
                this.oEDate.value = date;
                // Because of the calendar you have to see over the button disabling system. Right now remove this functionality.
                //document.getElementById("submitButton").disabled = false;
            }
        }
    }
    
    this.enableElements = function() {
        
        var elems = document.getElementsByName(jsConst.REAL_PROPERTY_UNIT);
        for(var index = 0; index < elems.length; index++)
        {
            elems[index].disabled = false;
        }
        
        var elems = document.getElementsByName(jsConst.MUNICIPALITY_NAME);
        for(var index = 0; index < elems.length; index++)
        {
            elems[index].disabled = false;
        }
        
        var elems = document.getElementsByName(jsConst.STREET_ADDRESS);
        for(var index = 0; index < elems.length; index++)
        {
            elems[index].disabled = false;
        }
        
        var distMObj = new DistributionMethod();
        distMObj.enableElements();
    }
}

function SearchBusinessRegisters() {

    /** the javascript method to be called for executing the struts action */
    var ajaxJSProc = null;
    /** the struts action path to be executed */
    var ajaxStrutsUrl = null;
    /** the object that belongs to the page where the search tile is inserted. */
    var objParent = null;
    /** the method to be called for processing the text reponse */
    var textResponseProc = null;
    /** the method to be called for processing the text reponse */
    var xmlResponseProc = null;
    
    /** this method must be called first before we can use submitting.
      * The obj is the parent object where we'll call some methods.
      * The tProc and xProc are the methods for text and xml response processing. They can be null.
      */
    this.init = function(proc, url, obj, tProc, xProc){
        ajaxJSProc = proc;
        ajaxStrutsUrl = url;
        objParent = obj;
        textResponseProc = tProc;
        xmlResponseProc = xProc;
    }
    
    this.resetInputSearchText = function() {
        document.getElementById(jsConst.INPUT_SEARCH_TEXT).value = "";
    }
    
    this.submitForm = function() {
        
        var searchText = escape(document.getElementById(jsConst.INPUT_SEARCH_TEXT).value);
        
        if (ajaxJSProc != null) {
            ajaxJSProc(ajaxStrutsUrl + jsConst.QUESTION_MARK + jsConst.SEARCH_TEXT + jsConst.EQUAL +  searchText,
                       textResponseProc,
                       xmlResponseProc);
            
            if (objParent != null && objParent.resetSelect != null) {
                objParent.resetSelect();
            }
        }
    }
    
    this.submitFormOnEnter = function(e) {
        
        var keyCode = util.getEventKeyCode(e);

        // 13 = return,
        if (keyCode == 13) {
        
            this.submitForm();
        }
    }
    
    this.submitFormOnSelect = function(selectValue, selectText) {
        
        if (ajaxJSProc != null) {
            ajaxJSProc(ajaxStrutsUrl + jsConst.QUESTION_MARK + jsConst.SEARCH_TEXT + jsConst.EQUAL + escape(selectText) +
                       jsConst.AMPERSAND + jsConst.BUSINESS_REGISTER + jsConst.EQUAL + escape(selectValue) ,
                       textResponseProc,
                       xmlResponseProc);
        }
    }
}

/**
 *
 */
function PDFViewerForm() {
    
    this.oForm = null;
    this.oFormAction = null;
    this.oMethodKey = "";
     
    this.init = function(form, getPDFMethodKey) {
        
        this.oForm = form;
        this.oFormAction = this.oForm.action;
        this.oMethodKey = getPDFMethodKey;
    }
    
    this.getPDF = function(value) {
        
        this.oForm.action = this.oFormAction + "?" + "method" + "=" + this.oMethodKey;
        this.oForm.action += "&" + "documentNo" + "=" + value;
        
        this.oForm.submit();
    }
    
    this.submit = function(oButton) {
        
        this.oForm.action = this.oFormAction + "?" + "method" + "=" + oButton.value;
        
        this.oForm.submit();
    }
}

function DistributionMethod() {
    
    this.enableElements = function() {
        
        document.getElementById("emailRadio").disabled = false;
        document.getElementById("mailRadio").disabled = false;
        document.getElementById("emailInput").disabled = false;
    }
}

function ChooseBusiness() {

    var searchObj = null;

    this.init = function(sObj) {
        
        searchObj = sObj;
    }

    this.startTimer = function(objTimer) {
        
        objTimer.startTimer(this.execSearching);
    }
    
    var resetSearchResult = function() {
    
        document.getElementById(jsConst.SPAN_SEARCH_RESULT).innerHTML = "";
    }
    
    this.resetSelect = function() {
        
        document.getElementById(jsConst.BUSINESS_REGISTER).value = "";
    }
    
    this.execSearching = function() {

        var selectObject = document.getElementById(jsConst.BUSINESS_REGISTER);
        var selectedBusiness = selectObject.options[selectObject.selectedIndex];
        
        if(selectedBusiness.value != "") {

            if (searchObj != null) {
                searchObj.submitFormOnSelect(selectedBusiness.value, selectedBusiness.text);
                searchObj.resetInputSearchText();
            }
        }
        else {

            resetSearchResult();
        }
    }
    
    this.useTheAnswer = function(text) {
    
        document.getElementById(jsConst.SPAN_SEARCH_RESULT).innerHTML = text;
    }
}

function GuidelinesList() {

    var actionUrl = null;
    
    this.init = function(aUrl) {
        
        actionUrl = aUrl;
    }
    
    this.getInfoText = function(groupNo, groupVersion) {
        
        var url = actionUrl + jsConst.QUESTION_MARK + jsConst.GROUP_NO + jsConst.EQUAL +  groupNo 
                            + jsConst.AMPERSAND + jsConst.GROUP_VERSION + jsConst.EQUAL +  groupVersion;
        
        ajaxObj.executeAction(url, processTextResponse);
    }
    
    var processTextResponse = function(text) {
    
        document.getElementById("explanationBox").innerHTML = text;
    }
}

function GuidelinesTermGroups() {

    var actionUrl = null;
    
    this.init = function(aUrl) {
        
        actionUrl = aUrl;
    }
    
    this.getInfoText = function(groupNo, groupVersion) {
        
        this.moveGroupAtTop(groupNo);
        
        var url = actionUrl + jsConst.QUESTION_MARK + jsConst.GROUP_NO + jsConst.EQUAL +  groupNo 
                            + jsConst.AMPERSAND + jsConst.GROUP_VERSION + jsConst.EQUAL +  groupVersion;
        
        ajaxObj.executeAction(url, processTextResponse);
    }
    
    this.moveGroupAtTop = function(chosenGroupNo) {
    
        // if chosenGroupNo is set (thus it is not the first time we run this page) then scroll to the chosen group.
        var chosenGroupOffsetTop = document.getElementById(chosenGroupNo).offsetTop;
        var parentNodeOffsetTop = document.getElementById(chosenGroupNo).parentNode.offsetTop;
             
        document.getElementById("listDiv").scrollTop = chosenGroupOffsetTop - parentNodeOffsetTop;
        if(document.getElementById("caption") != null) {
            document.getElementById("caption").innerHTML = document.getElementById(chosenGroupNo).innerHTML;
        } 
    }
    
    var processTextResponse = function(text) {
    
        document.getElementById("explanationText").innerHTML = text;
    }
}

function Error() {

    var actionUrl = null;
    var hideInfoText = "";
    var showInfoText = "";
    
    this.init = function(aUrl, hideInfoText, showInfoText) {
        
        this.actionUrl = aUrl;
        this.hideInfoText = hideInfoText;
        this.showInfoText = showInfoText;
    }
    
    this.sendEmail = function() {
        
        var url = this.actionUrl
                   + jsConst.QUESTION_MARK + "causeException" + jsConst.EQUAL + getValue("causeException") 
                   + jsConst.AMPERSAND + "callingAction" + jsConst.EQUAL +  getValue("callingAction")
                   + jsConst.AMPERSAND + "exceptionMessage" + jsConst.EQUAL +  getValue("errors")
                   + jsConst.AMPERSAND + "stackTrace" + jsConst.EQUAL +  getValue("stackTrace")
                   + jsConst.AMPERSAND + "clientMessage" + jsConst.EQUAL +  document.getElementById("clientMessage").value;

        ajaxObj.executeAction(url, processTextResponse);
    }
    
    this.showStackTrace = function() {
    
        var elem = document.getElementById('errorStackTrace');
        
        if (elem.style.visibility == jsConst.HIDDEN) {
            elem.style.visibility = jsConst.VISIBLE;
            elem.style.display = jsConst.BLOCK;
            document.getElementById('showStackTraceAnchor').innerHTML = this.hideInfoText;
        } else {
            elem.style.visibility = jsConst.HIDDEN;
            elem.style.display = jsConst.NONE;
            document.getElementById('showStackTraceAnchor').innerHTML = this.showInfoText;
        }
    }
    
    var getValue = function(elemId) {
        return escape(util.trimTrailing(document.getElementById(elemId).innerHTML));
    }
    
    var processTextResponse = function(text) {
    
        document.getElementById("response").innerHTML = text;
        
    }
}