// the current form page object
var objPage = null;

// set up the DHTML help content hash
var help_page = new Array();

/**
 * Shows form page.
 * 
 * @param int pageNum form page number.
 */
function showPage(pageNum) {
    
    // hide current form page
    if (objPage) {
        objPage.style.display = 'none';
    }
    
    objPage = document.getElementById("form_page_" + pageNum);
    objPage.style.display = 'block';
}

/**
 * Hides form page.
 * 
 * @param int pageNum form page number.
 */
function hidePage(pageNum) {
    objPage = document.getElementById("form_page_" + pageNum);
    objPage.style.display = 'none'
}

/**
 * Shows form help.
 * 
 * @param string elementId element id.
 */
function showHelp(elementId) {

    // don't show empty help
    if (help_page[elementId] == '' || help_page[elementId] == '<p></p>') {
        return;
    }
    
    // change CSS class of help elements ...
    document.getElementById("form_help").className += " visible";
    document.getElementById(elementId + "_container").className += " show-help";
    // ... and insert the help text
    document.getElementById("form_help").innerHTML = help_page[elementId];

    helpPosX = DL_GetElementLeft(document.getElementById("rightcontent"));
    helpPosY = DL_GetElementTop(document.getElementById(elementId + "_container"));
    document.getElementById("help").style.left = DL_GetElementLeft(document.getElementById(elementId + "_container")) + (document.getElementById(elementId + "_container").offsetWidth) + 'px';
    document.getElementById("help").style.top = helpPosY + 'px';
}

/**
 * Hides form help.
 * 
 * @param string elementId element id.
 */
function hideHelp(elementId) {
    document.getElementById("form_help").className = document.getElementById("form_help").className.replace(" visible", "");
    document.getElementById(elementId + "_container").className = document.getElementById(elementId + "_container").className.replace(" show-help", "");
}

/**
 * Clears the form.
 * 
 * @param string formName name of the form.
 */
function clearForm(formName) {
    document.getElementById(formName).reset();
    showPage(1);
}

/**
 * Submits form.
 * 
 * @param string formName name of the form.
 */
function submitForm(formName) {
    document.getElementById(formName).submit();
}

/**
 * ...
 */
function DL_GetElementLeft(eElement) {
    
    //initialize var to store calculations
    var nLeftPos = eElement.offsetLeft;

    //identify first offset parent element
    var eParElement = eElement.offsetParent;

    //move up through element hierarchy
    while(eParElement != null) {
        //appending left offset of each parent
        nLeftPos += eParElement.offsetLeft;
        //until no more offset parents exist
        eParElement = eParElement.offsetParent;
    }
    
    return nLeftPos;
}

/**
 * ...
 */
function DL_GetElementTop(eElement) {
    
    //initialize var to store calculations
    var nTopPos = eElement.offsetTop;
    //identify first offset parent element
    var eParElement = eElement.offsetParent;

    //move up through element hierarchy
    while (eParElement != null) {
        //ppending top offset of each parent
        nTopPos += eParElement.offsetTop;
        //until no more offset parents exist
        eParElement = eParElement.offsetParent;
    }
    
    return nTopPos;
}


// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// SHELL ADD-ONS
// Copyright 2007, Shell
// All Rights Reserved.
//
// Author: Wojciech Oledzki <wojciech.w.oledzki@shell.com>
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// set up the 'save cookie' config.
var save_cookie_config = new Array();

// set up the form name (done in page template).
var webform_name = '';

// current opened help text.
var current_help = '';

// form_field -> page number
var form_fields_map = new Array();

// validation error array.
var validation_errors = new Array();

/**
 * Initialize form.
 */
function initForm() {
    fillFormFromCookies();
    handleValidationErrors();
}

/**
 * Handles 'onfocus' event.
 * 
 * This function dispatch `onfocus` action to other functions like
 * `showHelp`.
 * 
 * @param object element usually input, select or textarea element.
 * @param string overwriteElementId ID of the element that should handle this event insead of the `element`.
 */
function onfocusHandler(element, overwriteElementId) {
    
    if (overwriteElementId) {
        //showHelp(overwriteElementId);
    }
    else {
       //showHelp(element.id);
    }
}

/**
 * Handles 'onblur' event.
 * 
 * This function dispatch `onfocus` action to other functions like
 * `hideHelp` and `saveCookie`.
 * 
 * @param object element usually input, select or textarea element
 * @param string overwriteElementId ID of the element that should handle this event insead of the `element`
 */
function onblurHandler(element, overwriteElementId) {
    
    if (overwriteElementId) {
        //hideHelp(overwriteElementId);
    }
    else {
        //hideHelp(element.id);
    }
    
    // radio buttons have to have extra 'onchange' action
    if (element.type != 'radio') {
        saveCookie(element);
    }
}

/**
 * Dekorator for showHelp function.
 *
 * @see showHelp(elementId)
 *
 * @param string elementId element id.
 */
function shellShowHelp(elementId) {
    
    // when we want to hide the already opened help
    if (current_help == elementId) {
        hideHelp(current_help);
        current_help = '';
        return;
    }
    
    // hide previous opend help text
    if (current_help != '') {
        hideHelp(current_help);
    }
    
    current_help = elementId;
    showHelp(elementId);
}

/**
 * Dekorator for showPage function.
 * 
 * @see showPage(pageNum)
 *
 * @param int pageNum form page number to show.
 */
function shellShowPage(pageNum) {
    
    // hide previous opend help text
    if (current_help != '') {
        hideHelp(current_help);
    }
    
    showPage(pageNum);
}

/**
 * Fills form with data from cookies.
 */
function fillFormFromCookies() {

    var cookies = document.cookie.split(';');
    
    for (var i = 0; i < cookies.length; i++) {
        loadCookie(cookies[i]);
    }
}

/**
 * Handles validation errors.
 *
 * This function uses global array 
 *
 */
function handleValidationErrors() {

    var firstErrorPage = 999;
    
    for (var i = 0; i < validation_errors.length ; i++) {
        if (form_fields_map[validation_errors[i]] < firstErrorPage) {
            firstErrorPage = form_fields_map[validation_errors[i]];
        }
    }
    
    if (firstErrorPage < 999) {
        showPage(firstErrorPage);
    }
}

/**
 * Saves form item value into cookie.
 * 
 * This function is using `save_cookie_config` array to determine if
 * the value should be save in cookie or not.
 * 
 * @param object element usually input, select or textarea element
 */
function saveCookie(element) {
    
    var defaultPeriod = 30;
    var prefix = 'shell_form-' + webform_name + '-';
    
    // ...
    if (save_cookie_config[element.name] == false || typeof save_cookie_config[element.name] == 'undefined') {
        eraseCookie(prefix + element.name);
        return;
    }
    
    // if no value - erase cookie.
    if (element.value == null || element.value == '') {
        eraseCookie(prefix + element.name);
        return;
    }
    
    switch (element.type) {
        case 'checkbox':
        case 'radio':
            if (element.checked) {
                createCookie(prefix + element.name, element.value, defaultPeriod);
            }
            else {
                eraseCookie(prefix + element.name);
            }
            break;
        
        default:
            createCookie(prefix + element.name, element.value, defaultPeriod);
            break;
    }
}

/**
 * Loads form item value from cookie.
 * 
 * @param string formItemName the form item name.
 */
function loadCookie(formItemName) {

    formItemName = formItemName.match(/shell_form[^=]*/);
    var regExp = new RegExp('shell_form\\-' + webform_name + '\\-', 'g');
    
    if(formItemName == null) {
        return;
    }
    
    // cast to string
    formItemName += '';
    
    var formItemValue = readCookie(formItemName);
    var formItemId = formItemName.replace(regExp, '');

    // if no element, erase the cookie and skip the iteration
    if (formItemId == null) {
        eraseCookie(formItemName);
        return;
    }
    
    var formItem = document.forms["MailForm"].elements[formItemId];
    
    // if no element, erase the cookie and skip the iteration
    if (formItem == null) {
        eraseCookie(formItemName);
        return;
    }

    // in case of multiple radio buttons and multi checkboxes
    if (typeof formItem.type == 'undefined') {
        
        for (i = 0; i < formItem.length; i++) {
            if (formItem[i].value == formItemValue) {
                formItem[i].checked = true;
            }
        }
        
        return;
    }
    
    switch (formItem.type) {
        
        case 'checkbox':
        case 'radio':
            formItem.checked = true;
            break;
        
        case 'select-one':
            for (var j = 0; j < formItem.options.length; j++) {
                if (formItem.options[j].value == formItemValue) {
                    formItem.selectedIndex = formItem.options[j].index;
                    // IE hack
                    selected_var[formItemId] = formItem.options[j].index;
                }
            }
            break;
        
        default:
            formItem.value = formItemValue;
            break;
    }
}

/**
 * Creates new cookie
 * 
 * @param string name
 * @param string value
 * @param int days
 */
function createCookie(name, value, days) {
    
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else {
        var expires = "";
    }
    
    document.cookie = name + "=" + escape(value) + expires + "; path=/";
}

/**
 * Returns the cookie value.
 * 
 * @param string name
 */
function readCookie(name) {
    
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    
    for (var i = 0; i < ca.length; i++) {
        
        var c = ca[i];
        
        while (c.charAt(0) == ' ') {
            c = c.substring(1, c.length);
        }
        
        if (c.indexOf(nameEQ) == 0) {
            return unescape(c.substring(nameEQ.length, c.length));
        }
    }
    
    return null;
}

/**
 * Erase the cookie.
 *
 * @param string name
 */
function eraseCookie(name) {
    createCookie(name, "", -1);
}