var meterCount = 0; // meter regiong UID (auto-assigned via add_meter)
// X = metercount, meter count acts as a UID, 
//    the metercount at the time of that meter region's creation
// meter-X = the associated meter region
// meter-text-X = the meter text field
// meter-fields-X = the initially hidden meter fields div
// meter-serial-X = the div serial of the model
// meter-labels-X = the TR used to display the needed labels
// meter-error-X = the meter error div, displays associated errors

/**
 * shorthand to getElementById
 */
function _$(id) { return document.getElementById(id); }

/**
 * Adds a new meter region, sets up all the inner components, except for the meter labels
 * @param {dictionary} [dict] dictionary of options to configure the added meter region
 * @remark creates the Calendar object
 */
// pass one arg for default display (no 'add new device' button)
// pass two to show the alternative output (display 'add new device')
function add_meter(dict)
{
    var finalHTML = "";
    var meters_region   = document.getElementById("metersdiv");
    var newDiv          = document.createElement("div");
    var validatetagid = "validatetag"+meterCount;
    newDiv.id = "meter-"+meterCount;
    
    meters_region.appendChild(newDiv);
    
    newDiv.className = "meter-region";
        
    // setup add meter options
    var displayTable = "";
    var disablevalidatetagfield = "";
    var disablevalidatetagbutton = " disabled ";
    var tagvalue = "";
    var disablenotaglink = "";
    var hidetaginvokestyle = "";
    if (dict != null)
    {
        if (dict['tagfieldstyle'] == "hideborder")
        {
            // remove the dotted line border
            newDiv.style.border = "0px";
        }
        
        if (dict['showaddtag'] == "true")
        {
            displayTable = " style='display:none'";
        }    
        
        if (dict['disablevalidatetag'] == "true") // temp
        {
            //disablevalidatetagfield = " disabled ";
            disablevalidatetagbutton = " disabled ";
            //hidetaginvokestyle = "style='display:none'";
        }
    }
    
    // create the html block
    finalHTML += "<table class='linewtop' height='2' width='500' cellspacing='0' cellpadding='0' border='0' style='height: 2px;'>"+
                    "<tr>"+
                        "<td style='border-top: 2px dotted rgb(193, 192, 188); width: 500px; height: 2px;'> &nbsp;</td>"+
                    "</tr>"+
                "</table>"+ 
                "<table width='100%' cellpadding='0' cellspacing='0' class='form_table' id='device-table-"+meterCount+"' "+displayTable+"> "+
                    "<tr class='center' >"+
                        "<th width='108' id='entertag'>"+
                            "Enter TAG # <span class='required'>*</span>"+
                        "</th>"+
                        "<td width='397' >"+
                            "<input type='text' style='margin-bottom:2px;' "+disablevalidatetagfield+" fieldname='tag' id='"+validatetagid+"text'"+
                                " metercount='"+meterCount+"' value='"+tagvalue+"' onkeyup='validateTagTextChanged(this)' class='short' name='meta[tag_number]["+meterCount+"]'/>"+
                            // group elements
                            "<span class='aqua rightside'>" +
                                // add the validate tag button
                                "<input type='button'  id='"+validatetagid+"button' "+disablevalidatetagbutton+" "+
                                "metercount='"+meterCount+"' textboxid='"+validatetagid+"text' "+
                                "notaglinkid='notaglink-"+meterCount+"'  onclick='validate_tag(this)' value='Validate Tag'>"+
                                // add the "don't have a tag link"                                
                                "&nbsp;<a class='notaglink' href='javascript:void(0);' "+disablenotaglink+" id='notaglink-"+meterCount+"' metercount='"+meterCount+"' "+
                                            "onclick='if (checkContactFields()) { showSearchOptions(true, "+meterCount+");showValidateTagError(true, \"notag\");}'>Don\'t have a TAG</a>"+
                                            
                                "<span style='display:none' class='tagvalidatelabel' id='tagvalidate"+meterCount+"label'>TAG Validated</span>"+
                            "</span>"+
                        "</td>"+
                    "</tr>"+
                "</table>";

	
    finalHTML += "<span style='display:none;' id='meter-fields-"+meterCount+"'>";
    finalHTML += "<table class='form_table' cellpadding='0' cellspacing='0'  >";
   
   
   // serial number
   var serialFieldId = "model-serial-"+meterCount;
    finalHTML += "<tr id='"+serialFieldId+"' style='display:none'>"+   
             "<th width='108' >"+
                 "Enter Serial # <span class='required'>*</span>"+
             "</th>"+
             "<td>"+
                 "<input type='text' fieldname='serial' metercount='"+meterCount+"'"+
                     "class='short' value='' disabled id='"+serialFieldId+"-text' name='meta[serial_number]["+meterCount+"]'/>"+
             "</td>"+
         "</tr>";
    
    // model number
    finalHTML += "<tr>"+
                    "<th width='108'>"+
                        "Model"+
                    "</th>"+
                    "<td>"+
                        "<input type='text' id='model-text-"+meterCount+"' class='short' value='' name='meta[model_name]["+meterCount+"]'/>"+
                    "</td>"+
                "</tr>";
    finalHTML += "</table>";
    // labels
    finalHTML += "<div id='meter-labels-"+meterCount+"' class='meter-labels'></div>";
        
    // meter date
    finalHTML += createDateField(meterCount);
    
    // the delete meter
    finalHTML += "<div class='tag-btns' align='left'>"+    
                    "<input type='button' class='add_tag_button' fieldname='validate_button' value='Add Another TAG' onclick='add_new_device(this, "+meterCount+")' />&nbsp;"+
                    "<input class='remove' type='button' onclick=\"if (confirm('Are you sure?')) { delete_meter_div('meter-"+meterCount+"') }\" value='Remove' />"+
                "</div>";
    
    // add the error div
    finalHTML += "<div class='error-block' style='display:none;' id='meter-error-"+meterCount+"'></div>";
    
    // end
    finalHTML += "</span>";
    
    // assign the html
    newDiv.innerHTML = finalHTML;
    
    // setup calendar
    setupCalendar(meterCount);

    // prepare next id
    ++meterCount;
}

/**
 *  Sets up the calender
 * @param {integer} [count] then number assigned to the element
 */
 function setupCalendar(count)
 {
    var d = new Date();
    var current_year = d.getFullYear();
    
    // now setup the calendar
    Calendar.setup({
            inputField  : 'meter-date-'+count,
            button      : 'meter-date-btn-'+count,
            ifFormat     : '%m/%d/%Y',
            align       : 'Bl',
            firstDay    : 0,
            weekNumbers : false,
            range       : [2000, current_year],
            disableFunc : disallowDate,
            singleClick : true,
            cache       : true
        });
    
 }

// right now our date validate calls for nothing in the future
function disallowDate(date)
{
    var currentDate = new Date();
    return date.getTime() > currentDate.getTime();
}

/**
 *  shows the hidden meter fields, populates data, and add a new meter region
 *  @param {dictionary} [dict] multi-param arg (labels = integer, model = string, metercount = integer, disablemodel = boolean, addserial = boolean)
 */
function showMeterFields(dict)
{
    var addSerial = false;
    var labels = null;
    var model  = '';    
    var mCount = 0;
    var doAddMeter = true;
    var disableModel = false;
    
    if (dict != null)
    {
        labels = dict['labels'];
        model = dict['model'];
        addSerial = (dict['addserial'] === true);
        mCount = dict['metercount'];
        disableModel = (dict['disablemodel'] === true);
    }
    
    // populate existing meter information
    _$("meter-fields-"+mCount).style.display = "block";
    var modelField = _$("model-text-"+mCount);
    modelField.value = model;
    
    if (disableModel)
    {
        modelField.readOnly = true;
        modelField.style.backgroundColor = "#eae9e5";
    }
    
    if (addSerial)
    {
        _$("model-serial-"+mCount).style.display = "";
        _$("model-serial-"+mCount+"-text").disabled = false;
    }
    
    if (labels != null)
        _$("meter-labels-"+mCount).innerHTML = createLabels(labels);
        
    // ensure the 'submit' and 'reset' buttons are shown
    Ext.get("formButtons").show();
    _$("submitBt").disabled = false;

    
    //set tag to "" from N/A
    //_$('validatetag'+mCount+'text').value = "";

    //validatetagtext.value = "";
    
}

/**
 * Creates the date field input element and label
 * @param {integer} [metercount] the specified meter count used by this date field
 */
function createDateField(meterount)
{   
    var currentDate = getCurrentDate();
    
    // create the html
    var finalHTML = "<table class='form_table' cellpadding='0' cellspacing='0' ><tr>"+
                        "<th width='108'>"+
                            "Meter Date <span class='required'>*</span>"+
                        "</th>"+
                        "<td>"+
                            "<input type='text' class='short' id='meter-date-"+meterount+"' value='"+currentDate+"' readonly=true name='meta[meter_date]["+meterount+"]'/> "+
                            "<img  class='label-name' id='meter-date-btn-"+meterount+"' style='display:inline;cursor:pointer;padding-left:0px;' align='absbottom' src='images/calendar_popup.gif' />"+
                        "</td>"+
                    "</tr></table>";
                    
    return finalHTML;
}

/**
 * Gets the current date as a string.
 * @return current date (05/04/2008)
 */
function getCurrentDate()
{
    // build the current date string
    var today = new Date();
    var month = today.getMonth() + 1;
    var date = today.getDate();
    var year = today.getFullYear();
    
    // now the numbers are strings
    if (month < 10)
        month = "0"+month;
    if (date < 10)
        date = "0"+date;
        
    // build date string
    var currentDate = month +"/"+ date +"/"+ year;
    
    return currentDate;
}

/**
 * Creates the meter label fields
 * @param {string array} [labels] array of labels to create
 * @return HTML of created label fields
 */
function createLabels(labels)
{
    var str = '';
    str += "<table class='form_table' cellpadding='0' cellspacing='0' >";
    for (var i = 0 ; i < labels.length ; ++i)
    {
        var label = labels[i];
        var meterid = meterCount - 1;
        
        // create the html block
        str += "<tr>";
            str += "<th width='108' >Required Meter <span class='required'>*</span></th>";
            str += "<td style='clear:both'> ";
            str += "<input type='text' fieldname='meter' "+
                    "class='short' onkeypress='return onlyNumeric(event);' "+
                    "metercount='"+meterid+"' "+ // store the meter UID
                    "name='meta[label_"+(i+1)+"]["+meterid+"]'/>";
            str += "<span class='label-name rightside' label='true'>"+label+"</label>";
            str += "<input type='hidden' metercount='"+meterid+"' name='meta[label_"+(i+1)+"_name]["+meterid+"]' value='"+label+"'/></td>";
                    
        str += "</tr>";
    }
    str += "</table>";
    return str;
}

/**
 * ensures the event represents numeric data only
 * @param {event} [e] the event to check
 */
function onlyNumeric(e)
{    
    var keynum;
    var keychar;
    var numcheck;
    
    if(window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    
//     alert(keynum);
    
    // if the backspace key was pressed
    if (keynum == 8)
        return true;
    
    keychar = String.fromCharCode(keynum);
    numcheck = /\D/;
    return !numcheck.test(keychar);
}

/**
 * Deletes the target meter field region
 * @param {string} [id] the id of the meter region to delete
 * @return null
 */
function delete_meter_div(id)
{
    var meters_region = document.getElementById("metersdiv");
    var childdiv = document.getElementById(id);
    meters_region.removeChild(childdiv);

    // if this is the last meter region add an blank one
    // and remove the submit buttons
    if (!hasMeterRegions())
    {            
        meterCount = 0;
        add_meter({
            disablevalidatetag : (!checkContactFields()).toString()
        }); 

      // ensure the 'submit' and 'reset' buttons are not shown
      //Ext.get("formButtons").hide();
      _$("formButtons").style.display = "none";
      _$("formButtons").style.visibility = "hidden";
      _$("submitBt").disabled = true;

    }
    
    // if we remove one and there is a previous meter div then we need to enable its
    // add tag button
    var last_div = get_last_meter_region();
    if (last_div)
    {
    	var inputs = last_div.getElementsByTagName('input');
    	var validate_button = getField(inputs, 'validate_button');
         if (validate_button)   
    	    validate_button.disabled = null;
	}    
}

/**
 * Determines if this page has meter regions displayed
 * @return true if meter regions are displayed, false otherwise
 */
function hasMeterRegions()
{
         // loop over all meter regions
    var containsMeterRegions = false;
    var meterRegions = _$("metersdiv").getElementsByTagName("div");
    for (var i = 0 ; i < meterRegions.length ; ++i)
    {        
        var meterRegion = meterRegions[i];
        if (meterRegion.id.match(/meter-\d$/))
        {
            containsMeterRegions = true;
            break;
        }
            
    }
    
    return containsMeterRegions;
}

/**
 * shows or hides the validate tag error message
 * @param {boolean} [show] true to show validate tag error div, false otherwise
 * @param {string} [reason] the validate error reason (must be: "notag", "invalidtag")
 * @return null
 */
function showValidateTagError(show, reason)
{
    Ext.get("validate-tag-error-notag").dom.style.display = "none";
    Ext.get("validate-tag-error-invalidtag").dom.style.display = "none";
    
    switch(reason)
    {
        case "notag":
        if (show)
            Ext.get("validate-tag-error-notag").show();
        break;
        
        case "invalidtag":
        if (show)
            Ext.get("validate-tag-error-invalidtag").show();
        break;
    }
    
    var vError = Ext.get("validate-tag-error");
    
    if (show)
        vError.show();
    else
        vError.dom.style.display = "none";
}

/**
 * called after a successful async response when validating the tag
 * @return null
 */
function updateValidateTag(response, ajaxObject)
{
    var button = Ext.get(ajaxObject.params.button_id).dom;
    var metercount = button.getAttribute("metercount");
    var resultsDict = null;
    
    eval(response.responseText);
    if (resultsDict == null)
    {
        return;
    }
    
    var validstring = resultsDict['validstring'];
    
    // DMX requested to validate the serials too, so we do it right here :)
    var validserial = resultsDict['validserial'];
    
	// If the user entered a valid Serial number we just change the values of the input fields	
	if ( validserial == "true" )
	{
		switchTagToSerialFields( metercount );
	}
    
    if (validstring == "true")
    { // if the tag was valid
        showSearchOptions(false, metercount);
        showValidateTagError(false, null);
        
        resultsDict['metercount'] = metercount;
        resultsDict['disablemodel'] = true;
        
        button.style.display = "none";
        
        // get the associated text box
        var textboxid = button.getAttribute("textboxid");
        var textbox = Ext.get(textboxid).dom;
        textbox.readOnly = true;
        // set the validated flag 
        textbox.setAttribute("validated", "true");
        
        // get the 'tag' link        
        var notaglinkid = button.getAttribute("notaglinkid");
        var notaglink = Ext.get(notaglinkid).dom;
        notaglink.style.display = "none";
        
        // show the validated tag label
        Ext.get("tagvalidate"+metercount+"label").show();
        
        resultsDict['addserial'] = false;
        showMeterFields(resultsDict);
    }
    else if (validstring == "false")
    {
        button.value = "Validate Tag";
        showSearchOptions(true, metercount);
        showValidateTagError(true, "invalidtag");
        //button.style.backgroundColor = "red";    // you could change the color of the validate button when it fails here. If you so inclined.
    }
    
}

/**
 * called when the user clicks "Validate Tag"
 * @return null
 */
function validate_tag(button)
{
    if (!checkContactFields())
    {
        showSearchOptions(false, null);
        showValidateTagError(false, null);
        return;
    }
        
    // get the value of the validate tag text box
    var textboxid = button.getAttribute("textboxid");
    var tag = Ext.get(textboxid).dom.value;
    button.value = "Validating...";
      // make the async request
    Ext.Ajax.request({
        url: PHP_FILE, // '../ajaxlivesearch.php'
        success: updateValidateTag,
        failure: null,
        params: {
                    input_value : tag,
                    input_id : "validatetag",
                    button_id : button.id
                }
    });
}

/**
 * Determines if the specified email is valid
 * @param {string} [value] the email to test
 * @return true if the email is valid, false otherwise
 */
function isEmailValid(value)
{
    regex = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    return regex.test(value);
}

/**
 * Checks the contact fields, highlights invalid fields
 * @return true if all fields are valid, false otherwise
 */
function checkContactFields()
{
    clearContactError();
    
    // loop over contact info
    isvalid = checkFields(_$("contact-region").getElementsByTagName("input"));
    
    var emailField = _$("contact_email_address");
    
    if (_$("contact_name").value == "")
    {
        addContactError("Invalid Name", "Enter a valid contact name.");
    }

    // validate the email format explicitly (so it doesn't have to validate on the server)
    if (!isEmailValid(emailField.value))
    {        
        emailField.style.backgroundColor = errColor;
        emailField.style.color = errTextColor;
        addContactError("Invalid Email", "Enter a valid email address.");
        
        isvalid = false;
    }
    
    if (_$("company_name").value == "")
    {
        addContactError("Invalid Company Name", "Enter a valid company name.");
    }
    
    return isvalid;
}

var errColor = "#D1F4F4";
var errTextColor = "#000";
/**
 * called when the form attempts to post to 'meter_submit'
 * @return null
 */
function validate_meter_form(form)
{
    var isvalid = true;
    var vError = _$("validate-errors");
    var errorHtml = "";
    var mCount = 0;
    
    // loop over contact info
    isvalid = checkContactFields();//checkFields(_$("contact-region").getElementsByTagName("input"));
    if (!isvalid)
    {
        if (errorHtml == "")
            errorHtml = "Please check required contact form fields.";
        
//         vError.style.display = "block";
//         vError.innerHTML = errorHtml;
    } 
    else
    {
        var emailField = _$("contact_email_address");
        
        // validate the email format explicitly (so it doesn't have to validate on the server)
        if (!isEmailValid(emailField.value))
        {        
            if (errorHtml == "")
                errorHtml = "Please enter a valid email address.";
            emailField.style.backgroundColor = errColor;
            emailField.style.color = errTextColor;
            isvalid = false;
        }
    }
    
    // loop over all meter regions
    var meterRegions = _$("metersdiv").getElementsByTagName("div");
    var lastRegion = get_last_meter_region();
    
    for (var i = 0 ; i < meterRegions.length ; ++i)
    {        
        var meterRegion = meterRegions[i];

        // make sure we are checking a meter region div
        if (meterRegion.id != "meter-"+mCount)
        {
            continue;
        }
        
        //if it is the last meter region see if it is blank
        if (meterRegion.id == lastRegion.id
            && (_$("meter-fields-"+mCount).style.display != "block"))
        {            
            continue;
        }
        
        clearMeterError(mCount);
            
        // get all the input fields
        var formFields = meterRegion.getElementsByTagName("input");
        
        var formFieldsOk = checkFields(formFields, false);
        
        var tagField = getField(formFields, "tag");
        var serialField = getField(formFields, "serial");
        var fieldsvalid = true;
        tagField.style.backgroundColor = "";
        serialField.style.backgroundColor = "";
       
        // if both fields are empty
        if (tagField.value == ""
            && serialField.value == "")
        {
            fieldsvalid = false;
            isvalid = false;
            tagField.style.backgroundColor = errColor;
            tagField.style.color = errTextColor;
            serialField.style.backgroundColor = errColor;
            serialField.style.color = errTextColor;
            
            if (errorHtml == "")
                errorHtml = "Please check required form fields. Enter a Tag Number or Serial Number.";
//             addMeterError("Check fields", "Enter a Tag Number or Serial Number", mCount);
        }
        
        // if either is not empty (valid)
        if (tagField.value != ""
            || serialField.value != "")
        {
            fieldsvalid = true;
        }
                
        // if the tag field is populated, make sure the contents have been validated
        if (tagField.value != ""
            && tagField.value != "N/A"
            && (tagField.getAttribute("validated") != "true"))
        {            
            tagField.style.backgroundColor = errColor;
            tagField.style.color = errTextColor;
            if (errorHtml == "")
                errorHtml = "Please validate all tags.";
            addMeterError("Validate Tag", "Please validate the tag.", mCount);
            
            isvalid = false;
        }
        
        // display the meter errors?
        if (formFieldsOk)
            clearMeterError(mCount);
            
        if (isvalid)
            isvalid = formFieldsOk;
            
        if (!isvalid)
        {
            if (errorHtml == "")
                errorHtml = "Please check required form fields.";
        }
        
        ++mCount;
    }
        
    // display the error div?
//     vError.style.display = (!isvalid) ? "block" : "none";
//     vError.innerHTML = errorHtml;
    
    return isvalid;
}

/**
 * Gets the field that has the target field name (checks "fieldname" attribute)
 * @return the target field DOM element
 */
function getField(formFields, fieldName)
{
    for (var i = 0 ; i < formFields.length ; ++i)
    {
        var field = formFields[i];
        if (field.getAttribute("fieldname") == fieldName)
            return field;
    }
}

/**
 * Checks the specified fields
 * @param {array} [formFields] An array of form field elements (from getElementsByTagName)
 * @return true if all fields are valid, false otherwise
 */
function checkFields(formFields)
{
    var isvalid = true;
    var tagField = getField(formFields, "tag");
    var serialField = getField(formFields, "serial");
    var meterid = null;
    var tagShown = true;
    
    if (tagField)
        meterid = tagField.getAttribute("metercount");
    if (meterid)
        tagShown = (_$("device-table-"+meterid).style.display != "none");
    
    // iterate over all form fields
    var max = formFields.length;
    for (var j = 0 ; j < max ; ++j)
    {
        var field = formFields[j];
        if (field == tagField
            && !tagShown)
            continue;
            
        if (field.disabled)
            continue;
        
        if (meterid != null
            && (field == serialField))
        {
            // if the "validate tag" region is hidden
            if (!tagShown)
            {                
                // check the serial # field
                if (field.value == "")
                {
                    addMeterError("Serial Number", "Enter a valid serial number.", meterid);
                    isvalid = false;
                    //alert(field.id + ", 1 \n" + isvalid);
                }
            }
        }
        
        // if this is a meter label field
        if (field.getAttribute("fieldname") == "meter")
        {
            // check for the numeric value
            if (field.value.match(/[A-z]/))
            {
                // invalidate the field
                field.value = "";
            }                
            // force parseInt to interpret as decimal, otherwise a value starting with 0 will be interpreted as octal
            else if (parseInt(field.value, 10) < 1 ) // check for greater then zero
            {
                field.value = "";
            }
            
        }
        
        if (field.value == "")
        {
            isvalid = false;
            //alert(field.id + ", 2 \n" + isvalid);
            field.style.backgroundColor = errColor;
            field.style.color = errTextColor;
            
            if (field.nextSibling)
            {
                // make sure this is only a "label" fields
                if (field.nextSibling.nodeName.toUpperCase() == "SPAN"
                    && (field.nextSibling.getAttribute("label") == "true"))
                {
                    // get the label name
                    var labelName = field.nextSibling.innerHTML;
                    // add the error
                    addMeterError("Required Meter", labelName +" is required.", meterid);
                }
            }
        }
        else
        {
            field.style.backgroundColor = "";
            field.style.color = "";
        }
    }
    
    return isvalid;
}


/**
 * disable devices so that they are not submitted
 *
 * @param integer device_count
 */


function disable_device(device_count)
{
    var checked = _$("submit-later-"+device_count).checked;
    var device_fields = _$("meter-"+device_count).getElementsByTagName("input");
    var max = device_fields.length;
    var tag = _$("validatetag"+device_count+"text");
    var question = new Array();

    if (tag.value == "")
    {
        question['validatetag'+device_count+'text'] = '';
    }
    else
    {
        question['model-serial-'+device_count+'-text'] = '';
    }

    for (var j = 0 ; j < max ; ++j)
    {
        var field = device_fields[j];

        //need to really make this generic, but no time .... need to dis regard all originally disabled fields
        if(field.id !== "submit-later-"+device_count && !(field.id in question))
        {
            simulate_disabled_field(field,checked, device_count)
        }
    }
}


/**
 * disable devices so that they are not submitted
 *
 * @param integer device_count
 */


function remove_device(device_count)
{
    var checked = _$("remove-"+device_count).checked;
    
    if(checked)
    {
        if(!confirm("Are you sure?  This device will no longer be viewable for you to manage and will be removed from future MeterReminders."))
        {
            _$("remove-"+device_count).checked = false;
            return false;
        }
    }
    
    var device_fields = _$("meter-"+device_count).getElementsByTagName("input");
    var max = device_fields.length;
    var tag = _$("validatetag"+device_count+"text");
    var question = new Array();

    if (tag.value == "")
    {
        question['validatetag'+device_count+'text'] = '';
    }
    else
    {
        question['model-serial-'+device_count+'-text'] = '';
    }

    for (var j = 0 ; j < max ; ++j)
    {
        var field = device_fields[j];

        //need to really make this generic, but no time .... need to dis regard all originally disabled fields
        if(field.id !== "remove-"+device_count && !(field.id in question))
        {
            simulate_disabled_field(field,checked, device_count)
        }
    }
}

function simulate_disabled_field(field,checked, device_count)
{
    if(field.getAttribute('fieldname') == "meter")
    {
        field.style.backgroundColor = "";
        field.value= ""; 
    }
    
    if(checked)
    {
        if(field.id != "remove-"+device_count && field.id != "submit-later-"+device_count)
        {
            field.style.backgroundColor = "eae9e5";
        }
        field.disabled = true;
    }
    else
    {
        field.disabled = false;
        if(field.id == "meter-date-"+device_count)
        {
            field.style.backgroundColor = "";
        }
    }
}

/**
 * Shows the associated tag field
 * @param {Element} [button] the DOM button object
 * @param {integer} [meterid] target meter id
 * @remark occurs usually when the user clicks "Add Another Tag"
 * @return null
 */
function add_new_device(button, meterid)
{    
    clearMeterError(meterid);
    
    // get all the input fields for the meter region
    var formFields = _$("meter-"+meterid).getElementsByTagName("input");
    var isvalid = checkFields(formFields);
    
    if (!isvalid)
        return;
        
    button.disabled = true;
    clearMeterError(meterid);
//     _$("device-table-"+metercount).style.display = "block";
    add_meter(null);
}

/**
 * Gets the last meter region displayed
 * @return the last meter region div element
 */
function get_last_meter_region()
{
    var lastMeterRegion = null;
	// loop over all meter regions
    var meterRegions = _$("metersdiv").getElementsByTagName("div");
    for (var i = 0 ; i < meterRegions.length ; ++i)
    {
        var region = meterRegions[i];
        if (region.id.match(/^meter-\d/))
        {
            lastMeterRegion = region;
        }
    }
    
    return lastMeterRegion;
}

/**
 * Resets the current form, by reloading the page
 * @param {Element} [bt] the reset button dom element object
 * @return null
 */
function resetForm(bt)
{
    bt.value = 'Resetting...'; 
    location.href = location.href;
}

/**
 * Adds an error to the target meter region
 * @param {string} [title] the title of the error
 * @param {string} [msg] the error message
 * @param {integer} [metercount] the associated metercount
 * @return null
 */
function addMeterError(title, msg, metercount)
{
    // get the error div associated with the meter
    var meterErrorDiv = _$("meter-error-"+metercount);
    var html = "<div class='validate-meter-error'>"+
                    "<span>"+title+".</span>&nbsp;"+msg+
                "</div>";
    // add the error
    meterErrorDiv.innerHTML += html;
    // show the error div
    meterErrorDiv.style.display = "block";
}

/**
 * Adds an error to the contact region
 * @param {string} [title] the title of the error
 * @param {string} [msg] the error message
 * @return null
 */
function addContactError(title, msg)
{
    // get the error div
    var contactErrorDiv = _$("validate-contact-errors");
    var html = "<div class='validate-meter-error'>"+
                    "<span>"+title+".</span>&nbsp;"+msg+
                "</div>";
    // add the error
    contactErrorDiv.innerHTML += html;
    // show the error div
    contactErrorDiv.style.display = "block";
}

/**
 * Clears and hides the target meter region errors
 * @param {integer} [meterid] the meter id
 * @return null
 */
function clearMeterError(meterid)
{
    // clear prev errors, and hide
    var meterErrorDiv = _$("meter-error-"+meterid);
    meterErrorDiv.innerHTML = "";
    meterErrorDiv.style.display = "none";
}

/**
 * Clears and hides the contact error
 * @return null
 */
function clearContactError()
{
    // clear prev errors, and hide
    var contactErrorDiv = _$("validate-contact-errors")
    contactErrorDiv.innerHTML = "";   
    contactErrorDiv.style.display = "none";
}


function validateTagTextChanged(field)
{
    var isEmpty = (field.value == "");
    
    var btValidate = _$("validatetag"+field.getAttribute("metercount")+"button");
    btValidate.disabled = isEmpty;
}

// When the user enters a Serial instead of a Tag we change the field names and ids
function switchTagToSerialFields( index )
{
	// Change the Description of the table header (The one at the left of the field)
    $("#entertag").html("Enter Serial # <span class=\"required\">*</span>");
    // Now change the Name of the field
    $("#validatetag" + index + "text").attr("name", "meta[serial_number][" + index + "]");
    // The text of the button
    $("#validatetag" + index + "button").val("Validate Serial");
    // ... finally the validated text
    $("#tagvalidate" + index + "label").html("Serial Validated");
    
    
}

/**
 * Resets the contact meter form.
 * @param [form] the form object to reset
 */
function reset_meter_contact_form(form)
{
    // iterate all form fields
    
    var fields = form.getElementsByTagName("input");
    
    for (var i = 0 ; i < fields.length ; ++i)
    {
        var field = fields[i];
        
        // find the "Required Meter" field only
        var fieldname = field.getAttribute("fieldname");
        if (fieldname == "meter")
        {
            // clear the field value
            field.value = "";
        }
    }   
}

