/*

Add/Edit form version 2 utilities (addEddit_v2_sa.js)

Author:           Anthony Blackshaw <ant@getme.co.uk>
Last modified:    10/21/2003 2:42PM
Copyright:        Getme Ltd (c)2003


Description:

This javascript include provides a set of utilities which facilitate the add/
edit form client side.

*/


// Date functions
monthList = new Array();

// Blank month
m = new Object();
m.longName = 'month';
m.shortName = 'mth';
m.veryShortName = '00';
m.dayCount = '31';
monthList.push( m );

// January month
m = new Object();
m.longName = 'January';
m.shortName = 'Jan';
m.veryShortName = '01';
m.dayCount = '31';
monthList.push( m );

// February month
m = new Object();
m.longName = 'February';
m.shortName = 'Feb';
m.veryShortName = '02';
m.dayCount = '29';
monthList.push( m );

// March month
m = new Object();
m.longName = 'March';
m.shortName = 'Mar';
m.veryShortName = '03';
m.dayCount = '31';
monthList.push( m );	

// April month
m = new Object();
m.longName = 'April';
m.shortName = 'Apr';
m.veryShortName = '04';
m.dayCount = '30';
monthList.push( m );	

// May month
m = new Object();
m.longName = 'May';
m.shortName = 'May';
m.veryShortName = '05';
m.dayCount = '31';
monthList.push( m );	

// June month
m = new Object();
m.longName = 'June';
m.shortName = 'Jun';
m.veryShortName = '06';
m.dayCount = '30';
monthList.push( m );	

// July month
m = new Object();
m.longName = 'July';
m.shortName = 'Jul';
m.veryShortName = '07';
m.dayCount = '31';
monthList.push( m );	

// August month
m = new Object();
m.longName = 'August';
m.shortName = 'Aug';
m.veryShortName = '08';
m.dayCount = '31';
monthList.push( m );	

// September month
m = new Object();
m.longName = 'September';
m.shortName = 'Sep';
m.veryShortName = '09';
m.dayCount = '30';
monthList.push( m );	

// October month
m = new Object();
m.longName = 'October';
m.shortName = 'Oct';
m.veryShortName = '10';
m.dayCount = '31';
monthList.push( m );	

// November month
m = new Object();
m.longName = 'November';
m.shortName = 'Nov';
m.veryShortName = '11';
m.dayCount = '30';
monthList.push( m );	

// December month
m = new Object();
m.longName = 'December';
m.shortName = 'Dec';
m.veryShortName = '12';
m.dayCount = '31';
monthList.push( m ); 

function buildDate( formCom, fieldName )
{
    // Builds the date information into the specified date field
    
    // Get a handle to the date components
    dateCom = formCom[ fieldName ];
    dayCom = formCom[ fieldName + '__day__' ];
    monthCom = formCom[ fieldName + '__month__' ];
    yearCom = formCom[ fieldName + '__year__' ];
    currentDayCom = formCom[ fieldName + '__currentDay__' ];
    
    // If a date is specified then split the date into seperate elements
    theDate = dateCom.value;
    
    day = 0;
    month = 0;
    year = 0;
    
    if ( theDate != '' )
    {
        // Split the date
        dateExp = /^(\d{4})\-(\d{2})\-(\d{2})$/;
	    dateMatch = theDate.match( dateExp );
	    
	    day   = Number( dateMatch[3] );
	    month = Number( dateMatch[2] );
	    year  = Number( dateMatch[1] );
    }
    
    // Set the date and the year value
    monthCom.value = month;
    
    if ( year > 0 )
    {
        yearCom.value = year;
    }
    
    // Build the day column
    dayCount = monthList[ month ].dayCount;
    
    // Deal with special case Feburary
    isLeap = true;
    
    if ( year > 0 )
    {
        isLeap = ( year % 4 == 0 && ( year % 100 != 0 || year % 400 == 0 ) );    
    }
    
    if ( month == 2 )
    {
        if ( !isLeap )
        {
            dayCount = 28;
        }    
    }
    
    // Build the days drop-down
    if ( currentDayCom[ 'options' ] )
    {
        for ( dayIndex = 1; dayIndex <= dayCount; dayIndex++ )
        {
            dayString = String( dayIndex );
            
            if ( dayIndex < 10 )
            {
                dayString = '0' + dayString;
            }
        
            opt = new Option( dayString, dayIndex );
            dayCom.options.add( opt, dayIndex );
        }
    }
    else
    {
        day = 1;
    }
    
    dayCom.value = day;  
    currentDayCom.value = day;      
}

function updateDate( formCom, fieldName )
{
    // Update the specified date field
    
    // Get a handle to the date components
    dateCom = formCom[ fieldName ];
    dayCom = formCom[ fieldName + '__day__' ];
    monthCom = formCom[ fieldName + '__month__' ];
    yearCom = formCom[ fieldName + '__year__' ];
    currentDayCom = formCom[ fieldName + '__currentDay__' ];
    
    // Update the drop downs to ensure they read correctly
    
    // Year
    year = 0;
    
    if ( yearCom.value.match( /^(\d{4})$/ ) )
    {
        year = yearCom.value;
    }
    
    // Month
    month = monthCom.value;
    dayCount = monthList[ month ].dayCount 
 
    // Check for special case leap year
    isLeap = true;
    
    if ( year > 0 )
    {
        isLeap = ( year % 4 == 0 && ( year % 100 != 0 || year % 400 == 0 ) );    
    }
    
    if ( month == 2 )
    {
        if ( !isLeap )
        {
            if ( day > 28 )
            {
                day = 28;
            }
            dayCount = 28;
        }    
    }
    
    // Day
    day = dayCom.value;
    
    // Limit the day to the months limit
    if ( Number( day ) > Number( dayCount ) )
    {
        day = dayCount;
    }
    
    // Check if we can update the date value
    if ( day > 0 && month > 0 && year > 0 )
    {
        // Build and update the date string
        strDay = String( day );
        if ( day < 10 )
        {
            strDay = '0' + strDay;
        }
        
        dateCom.value = String( year ) + '-' + monthList[ month ].veryShortName + '-' + strDay;
    }
    else
    {
        if ( day > 0 && month > 0 )
        {
            // Build and update the date string
            strDay = String( day );
            if ( day < 10 )
            {
                strDay = '0' + strDay;
            }
            
            dateCom.value = 'inva-' + monthList[ month ].veryShortName + '-' + strDay;        
        }
        else
        {
            dateCom.value = '';
        }
    }
    
    // Rebuild the days drop-down
    if ( currentDayCom[ 'options' ] )
    {
        if ( currentDayCom.value == day && ( dayCount + 1 ) == dayCom.options.length  )
        {   
            return;
        }
        else
        {
            currentDayCom.value = day;
        }
        
        while ( dayCom.options[ 1 ] != null )
        {
            dayCom.options[ 1 ] = null;
        }
        
        for ( dayIndex = 1; dayIndex <= dayCount; dayIndex++ )
        {
            dayString = String( dayIndex );
            
            if ( dayIndex < 10 )
            {
                dayString = '0' + dayString;
            }
        
            opt = new Option( dayString, dayIndex );
            dayCom.options.add( opt, dayIndex );
        }
    }
    
    dayCom.value = day;
}


// Link datatype utilities
function getLinkTableHeader()
{
    // Return an array of link table attributes for use when reading
    // writting hsd data.
    
    return new Array(
                'address',
                'commonLinkName',
                'commonLinkId',
                'internal',
                'languageId',
                'linkId',
                'linkTableId',
                'linkType',
                'memberTypeId',
                'memberTypeName',
                'sessionId',
                'ssl',
                'structureId',
                'structureName'
                    );
}

function getLinkParameterHeader()
{
    // Return an array of param attributes for use when reading
    // writting hsd data.
    
    return new Array(
                    'linkParamId',
                    'linkTableId',
                    'linkTableSessionId',
                    'paramName',
                    'paramValue',
                    'sessionId',
                    'view',
                    'viewExtra'
                    );
}

function createSelectLinkTable( fieldName, name, value, paramList )
{
    // Update the link selection box with the new link table value
    
    // Get a handle to the select component
    selectComponent = document.addEditForm[ fieldName + '__linkTableSelect__' ];  
    
    // Check for duplicate link member types
    hsdObject = readSingleHSD( value, getLinkTableHeader() );
    memberTypeId = hsdObject[ 'memberTypeId' ];
    
    for ( optionIndex = 0; optionIndex < selectComponent.options.length; optionIndex++ )
    {
        existingHsdObject = readSingleHSD( selectComponent.options[ optionIndex ].value, getLinkTableHeader() );

        if ( memberTypeId == existingHsdObject[ 'memberTypeId' ] )
        {
            alert( 'A link for the ' + hsdObject.memberTypeName + ' member type already exist!' );
            return false;
        }
    }
    
    // Create the link option
    opt = new Option( name, value );
    selectComponent.options.add( opt, 0 );
    selectComponent.value = value;
    
    // Update the HSD data for link tables and params
    addLinkTableData( fieldName, value );
    
    for ( param in paramList )
    {
        addLinkParamData( fieldName, paramList[ param ] );
    }
}

function updateSelectLinkTable( fieldName, name, value, paramList )
{
    // Update the link table selection box with the link table value
    
    // Get a handle to the select component
    selectComponent = document.addEditForm[ fieldName + '__linkTableSelect__' ];  

    // Check for duplicate link member types
    selectedIndex = selectComponent.selectedIndex;
    hsdObject = readSingleHSD( value, getLinkTableHeader() );
    memberTypeId = hsdObject[ 'memberTypeId' ];
    
    for ( optionIndex = 0; optionIndex < selectComponent.options.length; optionIndex++ )
    {
        existingHsdObject = readSingleHSD( selectComponent.options[ optionIndex ].value, getLinkTableHeader() );

        if ( memberTypeId == existingHsdObject[ 'memberTypeId' ] )
        {
            if ( selectedIndex != optionIndex )
            {
                alert( 'A link for the ' + hsdObject.memberTypeName + ' member type already exist!' );
                return false;
            }
        }
    }
    
    // Create the link option
    linkTableObj = readSingleHSD( selectComponent.value, getLinkTableHeader() );
       
    opt = new Option( name, value );
    selectComponent.options[ selectedIndex ] = opt;
    selectComponent.options[ selectedIndex ].selected = true;

    // Remove the link table from hsd data
    deleteLinkTableData( fieldName, linkTableObj.sessionId );
    deleteLinkParamData( fieldName, linkTableObj.sessionId );

    // Update the HSD data for link tables and params
    addLinkTableData( fieldName, value );
    
    for ( param in paramList )
    {
        addLinkParamData( fieldName, paramList[ param ] );
    }
}

function addLinkParamData( fieldName, linkParam )
{
    // Add a link param to the parameter HSD string
    
    // Get a handle to a component storing the data
    hsdData = document.addEditForm[ fieldName + '__linkParameterData__' ];
    
    // Add the linkParam
    hsdData.value += linkParam;
}

function deleteLinkParamData( fieldName, sessionId )
{
    // Delete any link param from the parameter HSD string that belongs to the
    // specified link table.
    
    // Get a handle to a component storing the data
    hsdData = document.addEditForm[ fieldName + '__linkParameterData__' ];
    
    // Read the data into seperate hsdObjects
    hsdObjectList = readMultipleHSD( hsdData.value, getLinkParameterHeader() );

    // Clear and rebuild the hsdData value excluding any params belonging to 
    // the specified link table.
    hsdData.value = '';
    
    for ( objectIndex in hsdObjectList )
    {
        if ( hsdObjectList[ objectIndex ].linkTableSessionId != sessionId )
        {
            hsdData.value += writeSingleHSD( hsdObjectList[ objectIndex ], getLinkParameterHeader() );
        }
    }
}

function addLinkTableData( fieldName, linkTable )
{
    // Add a link table to the parameter HSD string

    // Get a handle to a component storing the data
    hsdData = document.addEditForm[ fieldName + '__linkTableData__' ];
    
    // Add the linkTable
    hsdData.value += linkTable;
}

function deleteLinkTableData( fieldName, sessionId )
{
    // Delete a link table from the parameter HSD string
    
    // Get a handle to a component storing the data
    hsdData = document.addEditForm[ fieldName + '__linkTableData__' ];
    
    // Read the data into seperate hsdObjects
    hsdObjectList = readMultipleHSD( hsdData.value, getLinkTableHeader() );

    // Clear and rebuild the hsdData value excluding the specified link table
    hsdData.value = '';
    
    for ( objectIndex in hsdObjectList )
    {
        if ( hsdObjectList[ objectIndex ].sessionId != sessionId )
        {
            hsdData.value += writeSingleHSD( hsdObjectList[ objectIndex ], getLinkTableHeader() );
        }
    }
}

function sqlStoreList()
{
    // Open a popup window with the store SQL queries
    var win = openNewWindow
                        (
                        '/cgi-bin/sa/tools/sqlStoreList.cgi',
                        'sqlStoreListWindow',
                        'width=500, height=300, status=yes'
                        );
                        
    // Give the window focus                        
    win.focus();    
}

function virtualSqlWizard( query )
{
    // Open a popup window with the virtual SQL wizard
    var win = openNewWindow
                        (
                        '/cgi-bin/sa/tools/virtualSqlWizard.cgi?query=' + query,
                        'virtualSqlWizardWindow',
                        'width=500, height=500, status=yes'
                        );
                        
    // Give the window focus                        
    win.focus();    
}

function createLink( fieldName )
{
    // Open a popup window with the create link dialog
    var win = openNewWindow
                        (
                        '/cgi-bin/sa/tools/createUpdateLink.cgi?action=create&fieldName=' + fieldName,
                        'linkWindow',
                        'width=400, height=500, status=yes'
                        );
                        
    // Give the window focus                        
    win.focus();
}

function updateLink( fieldName )
{
    // Open a popup window with the update link dialog
    
    // Get the value of the selected link table
    linkTableData = document.addEditForm[ fieldName + '__linkTableSelect__' ].value;
    
    if ( !linkTableData )
    {
        alert( 'No link table selected!' );
        return;
    }
    
    // Make the string ASCII transportable
    linkTableData = escape( linkTableData );    

    var win = openNewWindow
                        (
                        '/cgi-bin/sa/tools/createUpdateLink.cgi?action=update&fieldName=' + fieldName + '&linkTableData=' + linkTableData,
                        'linkWindow',
                        'width=400, height=500, status=yes'
                        );
                        
    // Give the window focus                        
    win.focus();
}

function clearLink( fieldName )
{
    // Clear an existing link from its selection
    selectComponent = document.addEditForm[ fieldName + '__linkTableSelect__' ];
  
    // Get the value of the selected link parameter
    tableData = selectComponent.value;
    
    if ( !tableData )
    {
        alert( 'No link table selected!' );
        return;
    }
    
    linkTableObj = readSingleHSD( selectComponent.value, getLinkTableHeader() );
    selectComponent.remove( selectComponent.selectedIndex );         
    
    // Remove the link table from hsd data
    deleteLinkTableData( fieldName, linkTableObj.sessionId );
    deleteLinkParamData( fieldName, linkTableObj.sessionId );
}


// General utilities

function recordSearch()
{
    // Determine which search to perform
    f = document.getElementById( 'searchForm' );
    sc = f[ 'searchColumn' ];
    ss = f[ 'searchString' ];
    sql = f[ 'sqlString' ];    
    query = f[ 'whereQuery' ];
    
    if ( ss.disabled )
    {
        // SQL search
        query.value = sql.value;
    }
    else
    {
        // Simple search
        ssValue = ss.value;
        ssValue = ssValue.replace( /\\/g, "\\\\" );
        ssValue = ssValue.replace( /\'/g, "\\\'" );
        
        sql.value = 'WHERE `' + sc.options[ sc.selectedIndex ].text + '` LIKE \'%' + ssValue + '%\'';
        
        query.value = sql.value;
    }
    
    f.submit();
}

function toggleSearchArea( image )
{
    // Get a local handle to the search group area
    searchGroupDivision = document.getElementById( 'searchGroup' );
    
    // Show or hide
    if ( searchGroupDivision.style.overflow == 'hidden' )
    {
        // Show
    
        // Set the toggle image
        image.src = '/cgi-bin/sa/gfx/hide.gif';
        
        // Show the search area
        searchGroupDivision.style.overflow = 'visible';
    }
    else
    {
        // Hide
    
        // Set the toggle image    
        image.src = '/cgi-bin/sa/gfx/show.gif';
    
        // Hide the search area
        searchGroupDivision.style.overflow = 'hidden';
    }
    
    return;
}

function toggleAdvancedSearchOptions()
{
    // Get a local handle to the advanced search options area
    searchGroupDivision = document.getElementById( 'advancedSearchOptions' );
    
    // Show or hide
    if ( searchGroupDivision.style.visibility == 'hidden' )
    {
        // Show
        
        // Disable simple search and enable SQL search
        f = document.getElementById( 'searchForm' );
        sc = f[ 'searchColumn' ];
        ss = f[ 'searchString' ];
        sql = f[ 'sqlString' ];   
        sc.disabled = 1;
        ss.disabled = 1;
        sql.disabled = 0;
        
        ssValue = ss.value;
        ssValue = ssValue.replace( /\\/g, "\\\\" );
        ssValue = ssValue.replace( /\'/g, "\\\'" );
        
        if ( ss.value != '' )
        {
            sql.value = 'WHERE `' + sc.options[ sc.selectedIndex ].text + '` LIKE \'%' + ssValue + '%\'';
        } 
        
        // Show the advanced search area
        searchGroupDivision.style.visibility = 'visible';
        searchGroupDivision.style.overflow = 'visible';
    }
    else
    {
        // Hide
        
        // Disable SQL search and enable simple search
        f = document.getElementById( 'searchForm' );
        sc = f[ 'searchColumn' ];
        ss = f[ 'searchString' ];
        sql = f[ 'sqlString' ];       
        sc.disabled = 0;
        ss.disabled = 0;
        sql.disabled = 1;
    
        // Hide the advanced search area
        searchGroupDivision.style.visibility = 'hidden';
        searchGroupDivision.style.overflow = 'hidden';
    }
    
    return;
}

function hideHint( hint )
{
	hintLayer = document.getElementById( hint );
	hintLayer.style.visibility = "hidden";

    return;
}

function showHint( eventHandle, hint )
{
	hintLayer = document.getElementById( hint );

	hintLayer.style.visibility = "visible";

	if ( eventHandle )
	{
	    x = -16;
	    y = -16;

	    if ( !document.all )
	    {
	        x = x + eventHandle.pageX;
	        y = y + eventHandle.pageY;
	    }
	    else
	    {
	        x = x + ( eventHandle.x + document.body.scrollLeft );
            y = y + ( eventHandle.y + document.body.scrollTop );
	    }

	    hintLayer.style.left = x;
	    hintLayer.style.top = y;
	}

    return;
}

function openNewWindow( url, windowName, options )
{
    // Open a new window 
    
    return window.open( url, windowName, options );
}


// User defined form utilities

function addUserDefinedFormField( userDefinedFormName )
{
    /*
    
    Open the user defined form field builder window to add.
    
    UDF fields are built using a popup window which changes data within the 
    opener windows calling UDF datatype field.
    
    */
    
    // Open the field creation popup and focus it
    win = openNewWindow
            ( 
            '/cgi-bin/sa/structure/newField.cgi?action=add&formName=' + userDefinedFormName,
            'fieldBuilder',
            'width=500,height=345,status=yes'
            );
    win.focus();    
}

function editUserDefinedFormField( userDefinedFormName )
{
    /*
    
    Open the user defined form field builder window to edit.
    
    UDF fields are built using a popup window which changes data within the 
    opener windows calling UDF datatype field.
    
    */

    // Get a handle to the form for clarity
    var theForm = document.addEditForm;
    
    // Get a handle to the field select component for clarity
    var fieldSelect = theForm[ userDefinedFormName + '__select__' ];
    
    // Check that the user has selected a field
    if( fieldSelect.selectedIndex > -1 )
    {
        win = openNewWindow
                ( 
                '/cgi-bin/sa/structure/newField.cgi?action=edit&formName=' + userDefinedFormName,
                'fieldBuilder',
                'width=500,height=345'
                );
        win.focus();   
    }
    else
    {
        alert( 'Please select a user defined form field to edit!' );
    }
}

function validateList( listName, minSelect, maxSelect, required )
{

    var theForm = document.addEditForm;
    
    // Get local handle to the list select element
    var selectElement = theForm[ listName ];                             
    var optionList = selectElement.options;
    
    // Count the number of selected options
    var selectedCount = '';
    for ( var optionIndex = 0; optionIndex < optionList.length; optionIndex++ )
    {
        if ( optionList[ optionIndex ].selected )
        {
            selectedCount++;
        }
    }


    if ( required )
    {
        if ( selectedCount < 1 )
        {
            return 'is required!';
        }

        if ( selectedCount < minSelect )
        {
            return 'requires at least ' + String( minSelect ) + ' selected options!';
        }
        else if ( selectedCount > maxSelect )
        {
            return 'accepts no more than ' + String( maxSelect ) + ' selected options!';
        }
        
    }
    else
    {
        if ( selectedCount > 0 )
        {
            if ( selectedCount < minSelect )
            {
                return 'requires at least ' + String( minSelect ) + ' selected options!';
            }
            else if ( selectedCount > maxSelect )
            {
                return 'accepts no more than ' + String( maxSelect ) + ' selected options!';
            }
        }
    }
    
    return '';
}

function updateList( listName )
{
    // Builds the option value for the specified form using all the options in 
    // the specified select.

    // Get a handle to the form for clarity
    var theForm = document.addEditForm;
    
    // Get local handle to the list select element
    var selectElement = theForm[ listName ];                       
          
    var optionList = selectElement.options;                                

    // Build the field list
    var itemListSource = '';
    for ( var optionIndex = 0; optionIndex < optionList.length; optionIndex++ )
    {
        itemListSource = itemListSource + optionList[ optionIndex ].value;
    }
    
    // Set the field list value
    theForm[ listName + '_prevListing' ].value = itemListSource;                                                           
}

function validateUserDefinedForm( userDefinedFormName, required )
{
    // Builds the option value for the specified form using all the options in 
    // the specified select.

    // Get a handle to the form for clarity
    var theForm = document.addEditForm;
    
    // Get local handles the the forms values
    var nameOfForm = theForm[ userDefinedFormName + '__name__' ].value;
    var emailOfForm = theForm[ userDefinedFormName + '__notificationEmailAddress__' ].value;
    var scriptOfForm = theForm[ userDefinedFormName + '__customScript__' ].value;
    var selectElement = theForm[ userDefinedFormName + '__select__' ];                             

    // First make sure the form needs validation
    if ( required || nameOfForm.length || emailOfForm.length || scriptOfForm.length )
    {
        // Validate a form name has been provided
        var errorMsg = validationMgr.exist( nameOfForm, '1', '255' );
        
        if ( errorMsg )
        {
            alert( 'Form name ' + errorMsg );
            return;
        } 

        // If an email address has been provided, check the format is correct
        if ( emailOfForm.length )
        {
            errorMsg = validationMgr.email( emailOfForm );
            
            if ( errorMsg )
            {
                alert( 'Form email ' + errorMsg );
                return;
            }
        }                     
    }
    else
    {
        return 1;
    }
    
    return 1;
}


// Form submission utilities

function clearImageFromForm( image )
{
    /*
    
    Clear an image.
 
    */    

    // Update the form ready for submission
    updateForm();

    // Get a handle to the form for clarity
    var theForm = document.addEditForm;

    // Specify the image we are editing
    theForm.clearImage.value = image;

    // Set image edit flag
    theForm.imageEdit.value = 1;
    
    theForm.submit();      
}
function uploadImageToForm( image )
{
    /*
    
    Upload an image.
 
    */    

    // Update the form ready for submission
    updateForm();

    // Get a handle to the form for clarity
    var theForm = document.addEditForm;

    // Specify the image we are editing
    theForm.uploadImage.value = image;

    // Set image edit flag
    theForm.imageEdit.value = 1;
            
    theForm.submit();        
}

function saveForm()
{
    /*
    
    Save the current form data.
    
    Attempts to save the data within the form.
    
    */    

    // Update the form ready for submission
    updateForm();

    // Get a handle to the form for clarity
    var theForm = document.addEditForm;

    // Check the forms data is valid
    if ( validateForm() )
    {
        // Open in this window
        theForm.target = '';

        // Set save flag
        theForm.save.value = 1;
        
        theForm.submit();       
    }  
}

function previewForm()
{
    /*
    
    Preview the current form data.
    
    Allows the user to preview what the current data they have entered will
    look like when published.
    
    */


    // Update the form ready for submission
    updateForm();
    
    // Get a handle to the form for clarity
    var theForm = document.addEditForm;

    // Check the forms data is valid
    if ( validateForm() )
    {
        // Send the data to preview structure
        theForm.action = 'previewStructure.cgi';
        
        // Force the form submission to use a new window
        theForm.target = '_blank';
    
        // Set preview flag
        theForm.preview.value = 1;
        
        theForm.submit();  
    }
}

function cancelForm()
{
    /*
    
    Cancel the add/edit.
    
    If the user decides not to add or edit the record then the form is 
    submitted with cancel set to true. The add/edit script then relocates
    the user back to their previous location.
    
    This cannot be done by simply reverting the user to the previous page
    stored in history as with earlier versions of the function since the 
    user may already have submitted this form, either to upload a file or
    simply unsuccessfully.
    
    */


    // Update the form ready for submission
    updateForm();
    
    // Get a handle to the form for clarity
    var theForm = document.addEditForm;

    // Open in this window
    theForm.target = '';

    // Set cancel flag
    theForm.cancel.value = 1;
    
    theForm.submit();    
}


// View utilities

function addViewElementTypeTemplate( viewName )
{
    /*
    
    Open the view element type template builder window to add.
    
    */
    
    // Open the element type template builder  creation popup and focus it
    win = openNewWindow
            ( 
            '/cgi-bin/sa/structure/viewElementTypeTemplateBuilder.cgi?action=add&viewName=' + viewName,
            'viewElementTypeTemplateBuilder',
            'width=500,height=221,status=yes'
            );
    win.focus();
}


function editViewElementTypeTemplate( viewName )
{
    /*
    
    Open the user defined form field builder window to edit.
    
    UDF fields are built using a popup window which changes data within the 
    opener windows calling UDF datatype field.
    
    */

    // Get a handle to the form for clarity
    var theForm = document.addEditForm;
    
    // Get a handle to the field select component for clarity
    var fieldSelect = theForm[ viewName + '__select__' ];
    
    // Check that the user has selected a field
    if( fieldSelect.selectedIndex > -1 )
    {
        win = openNewWindow
                ( 
                '/cgi-bin/sa/structure/viewElementTypeTemplateBuilder.cgi?action=edit&viewName=' + viewName,
                'viewElementTypeTemplateBuilder',
                'width=500,height=345,status=yes'
                );
        win.focus();   
    }
    else
    {
        alert( 'Please select a element type to edit!' );
    }
}


function deleteViewElementTypeTemplate( viewName )
{
    // Delete a user defined form field
    
    // Get a handle to the form for clarity
    var theForm = document.addEditForm;
    
    // Get a handle to the field select component for clarity
    var fieldSelect = theForm[ viewName + '__select__' ];
    
    // Check that the user has selected a field
    if( fieldSelect.selectedIndex > -1 )
    {
        // Ask the user to confirm that they want to remove the field
		var prompt = 'Do you really wish to delete `' + fieldSelect.options[ fieldSelect.selectedIndex ].text + '`!';
		
		if ( confirm( prompt ) ) 
		{  
		    // Remove the field from the field list select
	  		fieldSelect.options[ fieldSelect.selectedIndex ] = null;
	  	}                                        

    }
    else
    {
        alert( 'Please select an element type to delete!' );
    }
}


function validateView( viewName, required )
{
    // Validates a view.

    // Get a handle to the form for clarity
    var theForm = document.addEditForm;
    
    // Get local handles the the forms values
    var initialQuery_fv = theForm[ viewName + '__initialQuery__' ].value;
    var elementsPerPage_fv = theForm[ viewName + '__elementsPerPage__' ].value;
    var stripeFrequency_fv = theForm[ viewName + '__stripeFrequency__' ].value;
    var fixed_fv = 0;
    
    if ( theForm[ viewName + '__fixed__' ].checked )
    {
        fixed_fv = 1;
    }        
    
    var viewElementTypeTemplateSelect_fv = theForm[ viewName + '__select__' ];
    var viewElementTypeTemplateList_fv = viewElementTypeTemplateSelect_fv.options;

    // First make sure the form needs validation
    if ( required || initialQuery_fv.length || viewElementTypeTemplateList_fv.length )
    {
        // Validate...
        var errorMsg = validationMgr.exist( initialQuery_fv, '1', '64000' );
        
        if ( errorMsg )
        {
            alert( 'Initial query ' + errorMsg );
            return;
        }

        var errorMsg = validationMgr.integer( elementsPerPage_fv, '1', '1000' );
        
        if ( errorMsg )
        {
            alert( 'Elements per page ' + errorMsg );
            return;
        }        

        var errorMsg = validationMgr.integer( stripeFrequency_fv, '0', '1000' );
        
        if ( errorMsg )
        {
            alert( 'Stripe frequency ' + errorMsg );
            return;
        }     
        
        if ( viewElementTypeTemplateList_fv.length < 1 )
        {
            alert( 'Views are required to support at least one element type!' );
            return;                                            
        }                        
    }
    
    return 1;
}


function updateViewSource( viewName )
{
    // Builds the option value for the specified form using all the options in 
    // the specified views select.

    // Get a handle to the form for clarity
    var theForm = document.addEditForm;
    
    // Get local handle to the list select element
    var selectElement = theForm[ viewName + '__select__' ];                       
          
    var optionList = selectElement.options;                                

    // Build the field list
    var itemListSource = '';
    for ( var optionIndex = 0; optionIndex < optionList.length; optionIndex++ )
    {
        itemListSource = itemListSource + optionList[ optionIndex ].value;
    }
    
    // Set the field list value
    theForm[ viewName + '__viewElementTypeTemplateSource__'  ].value = itemListSource;   
}


function updateView( selectElement, selectIndex, name, value )
{
    // Check for duplicate field labels
    
    // Parse new field for data
    var elementTypeRecord = formattingMgr.readHsdSingle( value );
    
    // Get a list of the current fields
    var elementTypeList = selectElement.options;
    

    // Add or update the value
    selectElement.options[ selectIndex ] = new Option( name, value );
}

function updatePassword( fieldName )
{
    // Update the hidden password value from the entry box

    // Get a handle to the form for clarity
    var theForm = document.addEditForm;
    
    // Get a handle to the password value and entry box
    var passwordValue = theForm[ fieldName ];
    var entryBox = theForm[ fieldName + '__entry__' ];
    
    // If there is a value in the entry box then update the password value
    if ( entryBox.value )
    {
        passwordValue.value = entryBox.value;
    }
}

function colourPick( fieldName )
{
    // Open a colour selector    
    
    // Get a handle to the form for clarity
    var theForm = document.addEditForm;    
    
    // Store the name of the colour field to adjust
    theForm[ '__colourFieldName__' ].value = fieldName;

    var colourWindow = window.open
        ( 
        '/html/colourPicker.html', 
        'colourPicker', 
        'width=128, height=160'
        );
        
     colourWindow.focus();   
}

function updateColour( fieldName )
{
    // Update a colour tab

    // Get a handle to the form for clarity
    var theForm = document.addEditForm;  
    
    colour = document.addEditForm[ fieldName ].value;
    tab = document.getElementById( fieldName + '__box__' );

    if ( !validationMgr.colour( colour, 3 ) )
    {
        tab.style.backgroundColor = '#' + colour; 
    }
}

function externalListElements( fieldName, query, required, multiple )
{
    // Update an element list selection externally

    var elementListWindow = window.open
        ( 
        'externalListElements.cgi?fieldName=' + fieldName + '&query=' + query + '&required=' + required + '&multiple=' + multiple, 
        'externalListElements', 
        'width=420, height=366, status=yes'
        );
        
     elementListWindow.focus();      
}

function popupRecordSelect( fieldName, fieldLabel, formId, formName, query, required, multiple )
{
    // Update a record list selection in a popup window

    var popupRecordSelectWindow = window.open
        ( 
        '/cgi-bin/sa/tools/popupRecordSelect.cgi?fieldName=' + fieldName + '&fieldLabel=' + fieldLabel + '&formId=' + formId + '&formName=' + formName + '&query=' + query + '&required=' + required + '&multiple=' + multiple, 
        'popupRecordSelect', 
        'width=600, height=366, status=yes'
        );
        
     popupRecordSelectWindow.focus();      
}

function closeVEwindow()
{
    self.close();
}    
function closeAndRefresh()
{
    window.opener.location.reload();
       
    self.close();
}
function VisualSaveForm()
{
    /*
    
    Save the current form data.
    
    Attempts to save the data within the form.
    
    */    

    // Update the form ready for submission
    updateForm();

    // Get a handle to the form for clarity
    var theForm = document.addEditForm;

    // Check the forms data is valid
    if ( validateForm() )
    {
        // Open in this window
        theForm.target = '';

        // Set save flag
        theForm.save.value = 1;
        
        theForm.submit();       
    } 
    
    setTimeout( 'closeAndRefresh()', 5000 );    
    
}
function updateElementList( fieldName, elementIdList, elementTextList )
{
    // Update an element select list
    
    var theForm = document.addEditForm;  
    var theElementSelectWrite = theForm[ fieldName ];
    var theElementSelectRead = theForm[ fieldName + '__readOnly__' ];
    
    // Remove the previous selections
    while ( theElementSelectRead.options[ 0 ] != null )
    {
        theElementSelectRead.options[ 0 ] = null;
    }

    while ( theElementSelectWrite.options[ 0 ] != null )
    {
        theElementSelectWrite.options[ 0 ] = null;
    }
    
    // Rebuild the lists
    for ( i = 0; i < elementIdList.length; i++ )
    {
        theElementSelectWrite.options[ i ] = new Option( elementTextList[ i ], elementIdList[ i ] );
        theElementSelectWrite.options[ i ].selected = true;
    }

    for ( i = 0; i < elementTextList.length; i++ )
    {
        theElementSelectRead.options[ i ] = new Option( elementTextList[ i ], '' );
    }
    
    if ( elementIdList.length == 0 )
    {
        theElementSelectWrite.options[ 0 ] = new Option( '', '' );
        theElementSelectWrite.options[ 0 ].selected = true;        
    }
    
}
