/* var userFields=new Array("username","password","email","firstname","lastname",
                         "team","level","status","var1","var2","var3","var4",
                         "var5","var6","address1","address2","city","state",
                         "county","zip","phone1","phone2","bin1","bin2",
                         "bin3","bin4","bin5","bin6");
*/
function restoreEditor(r) {
    //  Restore Editor after USER DETAILS field edit
    var nValue = document.getElementById(r.value_label);
    var nValueStatic = document.getElementById(r.static_display);
    if (r.modifiedfield=="password") {
        nValue.value = "";
    } else if (r.action=="passed") {
        nValueStatic.innerHTML = '<div class=\"ie-max-width-fix-A\">'+r.value+'<span class=\"catalyst\">&nbsp;</span></div>';
        if (r.modifiedfield=="station_id_number") {nValue.originalValue = r.value};
    } else { // :failed
        var replaceText = nValueStatic.innerText || nValueStatic.textContent || "";
        replaceText =  replaceText.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        if (nValue.type=="select-one") {
            // restore SELECTED option prior to failed edit
            updateSelect(nValue, replaceText);
        } else {
            nValue.value = replaceText;
        }
    }
    cellShifter('cancel', r.modifiedfield);
    updateMessage(r.message,true);
}

function editDetails(r) {
    // Update all values in USER DETAILS editor (when user is selected from USER LIST)
    var preHTML = '<div class=\"ie-max-width-fix-A\">';
    var postHTML = '<span class=\"catalyst\">&nbsp;</span></div>';
    eMode=true;
    update_details();

    for (var key in r.u) {
        if (r.u.hasOwnProperty(key)) {
            // update all values in the DETAIL editor
            if (key!="state_id"&&key!="county_id"&&key!="team_id"&&key!="active_id") {
                // first the visible values
                document.getElementById(key+'_static_display').innerHTML = preHTML+r.u[key]+postHTML;
                if (key=="password") {r.u[key]="";}
                // second the form values
                if (document.getElementById(key+'_value').type=="select-one") {
                    // select box
                    updateSelect(document.getElementById(key+'_value'),r.u[key]);
                } else {
                    // text box
                    document.getElementById(key+'_value').value = r.u[key];
                    if (key=="station_id_number") {document.getElementById(key+'_value').originalValue = r.u[key];}
                }
            }
        }
    }
    updateMessage(r.message,false);
}

function updateSelect(sel, opt) {
    for (var i=0; i<sel.options.length; i++){
    //      alert(nValue.options[i].text+":"+replaceText);
        if (sel.options[i].text==opt){
           sel.options[i].selected=true;
        } else {
           sel.options[i].selected=false;
        }
    }
}
function cellShifter(mode, field) {
    // Changes element.display CSS during field selection and edit
    switch (mode) {
        case "edit":
            document.getElementById(field+'_static').style.display = 'none';
            document.getElementById(field+'_active_A').style.display = (ie)?'block':'table-row';
            document.getElementById(field+'_active_B').style.display = (ie)?'block':'table-row';
            document.getElementById(field+'_value').style.display = 'inline';
            document.getElementById(field+'_active_save').style.display = 'none';
            break;
        case "add":
            document.getElementById(field+'_static').style.display = 'none';
            document.getElementById(field+'_active_A').style.display = (ie)?'block':'table-row';
            document.getElementById(field+'_active_B').style.display = 'none';
            document.getElementById(field+'_value').style.display = 'inline';
            document.getElementById(field+'_active_save').style.display = 'none';
            try{document.getElementById(field+'_value').focus();}
            catch(er){}// fergetaboutit - ie throws an error if element isn't visible when focus is attempted;
            break;
        case "save":
            document.getElementById(field+'_active_B').style.display = 'none';
            document.getElementById(field+'_value').style.display = 'none';
            document.getElementById(field+'_active_save').style.display = 'inline';
            break;
        case "cancel":
            document.getElementById(field+'_static').style.display = (ie)?'block':'table-row';
            document.getElementById(field+'_active_A').style.display = 'none';
            document.getElementById(field+'_active_B').style.display = 'none';
            break;
  //      case "active":
  //          document.getElementById(field+'_static').style.display = '';
 //           document.getElementById(field+'_active_A').style.display = 'none';
 //           document.getElementById(field+'_active_B').style.display = 'none';
 //           document.getElementById(field+'_value').style.display = '';
//            document.getElementById(field+'_active_save').style.display = 'none';
//            break;
    }
}

function update_details(toggle) {
    // Toggles DETAILS dialog between ADD and EDIT
    document.getElementById('detail_main').style.display = 'block';
    if(toggle)eMode=!eMode;
    display_help();
    var formName="";
    if (document.getElementById('adminUser')) formName='adminUser';
    if (document.getElementById('adminSS')) formName='adminSS';
    change_state(formName);
    document.getElementById(formName).reset();
    if (rowsel&&!eMode) document.getElementById(rowsel).style.fontWeight = 'normal';
}

function display_help() {
    if (eMode) {
        document.getElementById('detail_help_add').style.display = 'none';
        document.getElementById('detail_help_edit').style.display = 'block';
        document.getElementById('cmdButtons_add').style.display = 'none';
        document.getElementById('cmdButtons_edit').style.display = 'block';
        changecss('.editMode','background-color','#FFFF99');
    } else {
        document.getElementById('detail_help_add').style.display = 'block';
        document.getElementById('detail_help_edit').style.display = 'none';
        document.getElementById('cmdButtons_add').style.display = 'block';
        document.getElementById('cmdButtons_edit').style.display = 'none';
        changecss('.editMode','background-color','#FFFFEE');
    }
}
function row_selected(userrow) {
    document.getElementById(userrow).style.fontWeight = 'bold';
}
function updateselect(state) {
    newstatepending=false;
    var scl=document.getElementById('county_value');

    for (i = scl.length; i > 0; i--)  // clear old list
      {scl.options[i-1] = null};
    scl.options[0] = new Option(" --- Updating - StandBy --- ",0)

 //   .innerHTML="<OPTION value=\"\"> --- Updating - StandBy --- </OPTION>";
    scl.disabled = true;
    sendData('POST',sharedHost+'/auth/updateSelect_county.php',{'state':state});
}
function updateselect_complete(cl) {
    var scl=document.getElementById('county_value');

    scl.options[0] = null;  // clear temp list with new header

    scl.options[0] = new Option(" --- SELECT COUNTY --- ",0);
    for (var key in cl) {
        scl.options[key] = new Option(cl[key], key);
    }

    scl.selectedIndex = 0;
    scl.disabled = false;
    scl.focus() = true;
}
function updateMessage(mText,flashIt) {
    function_message = document.getElementById('detail_control_message').innerHTML;
    document.getElementById('detail_control_message').innerHTML = mText;
    if (flashIt) InitializeMessageFlasher();
}
function flashRow(obj) {
 //   if (eMode) {
        obj.bgColor = "#FFFF99";
        obj.style.background = "#FFFF99";
        obj.style.cursor = "pointer";
 //   }
}
function unFlashRow(obj) {
    obj.bgColor = "#E6F6F6";
    obj.style.background = "#E6F6F6";
    obj.style.cursor = "default";
}
function unFlashRow_odd_row(obj) {
    obj.bgColor = "#FFFFF6";
    obj.style.background = "#FFFFF6";
    obj.style.cursor = "default";
}
function unFlashRow_even_row(obj) {
    obj.bgColor = "#F6F6F6";
    obj.style.background = "#F6F6F6";
    obj.style.cursor = "default";
}
function isArray(obj) {
    if (obj.constructor.toString().indexOf("Array") == -1)
        return false;
    else
        return true;
}
function change_state(formName) {
    if(eMode){
        if(hideXtra) {
            change_rows(/.*static$/gi,formName);
        } else {
            change_rows(/.*((?:static)|(?:static.*hidden))$/gi,formName);
        }
    } else {
        if(hideXtra) {
            change_rows(/.*active_A$/gi,formName)
        } else {
            change_rows(/.*((?:active\_A)|(?:active\_A.*hidden))$/gi,formName)
        }
    }
}
function change_rows(seekClass,formName) {
    var fObj = document.getElementById(formName).getElementsByTagName("tr");
    var val = ((ie)?'block':'table-row');
    for(var i=0; i<fObj.length; i++)
    {
        if (fObj[i].className.match(seekClass)) fObj[i].style.display = val;
        else fObj[i].style.display = "none";
    }
}
function toggle_hidden() {
    if (hideXtra) {
        document.getElementById('showextra').style.display = 'none';
        document.getElementById('hideextra').style.display = '';
    } else {
        document.getElementById('showextra').style.display = '';
        document.getElementById('hideextra').style.display = 'none';
    }
    hideXtra=!hideXtra;
    change_state();
}
/*
function changecssid (arr, el, val) {
    var idid;
    for (var c = 0; c < arr.length; c++) {
   //   alert(arr[c]);
        idid = arr[c]+el;
        if (hiddenfields && document.getElementById(idid).className=="editCell hidden") {
          document.getElementById(idid).style.display = "none";
        } else {
          document.getElementById(idid).style.display = val;
        }

      //  alert(document.getElementById(idid).className);
    }
}
 */
function changecss(theClass,element,value) {
    var cssRules;
    var added = false;

	for (var S = 0; S < document.styleSheets.length; S++){

        if (document.styleSheets[S]['rules']) {
            cssRules = 'rules';
        } else if (document.styleSheets[S]['cssRules']) {
            cssRules = 'cssRules';
        } else {
             //no rules found... browser unknown
        }

        for (var R = 0; R < document.styleSheets[S][cssRules].length; R++) {

	        if (document.styleSheets[S][cssRules][R].selectorText == theClass) {
	      //    alert(document.styleSheets[S][cssRules][R].ID);
            if(document.styleSheets[S][cssRules][R].style[element]){
                    document.styleSheets[S][cssRules][R].style[element] = value;
                    added=true;
                    break;
                }
            }
        }

        if(!added){
            if(document.styleSheets[S].insertRule){
                document.styleSheets[S].insertRule(theClass+' { '+element+': '+value+'; }',document.styleSheets[S][cssRules].length);
            } else if (document.styleSheets[S].addRule) {
                document.styleSheets[S].addRule(theClass,element+': '+value+';');
            }
        }
    }
}
var detail_flashes;
var detail_timerID = null;
var detail_timerRunning = false;
var detail_delay = 333;
var function_message = "";

function InitializeMessageFlasher()
{
    // Set the length of the timer, in seconds
    detail_flashes = 6;
    StopMessageFlasher();
    StartMessageFlasher();
    document.getElementById('detail_control_message').style.fontWeight = 'bold';
}

function StopMessageFlasher()
{
    if(detail_timerRunning)
        clearTimeout(detail_timerID);
    detail_timerRunning = false;
}

function StartMessageFlasher()
{
    if (detail_flashes==0)
    {
        document.getElementById('detail_control_message').style.fontWeight = 'normal';
        StopMessageFlasher();
        document.getElementById('detail_control_message').innerHTML = function_message;
    }
    else
    {
        self.status = detail_flashes;
        detail_flashes = detail_flashes - 1;
        detail_timerRunning = true;
        switch (detail_flashes) {
          case 4:
          case 2:
          case 0:
            document.getElementById('detail_control_message').style.color = '#990000';
            document.getElementById('detail_control_message').style.backgroundColor = '#F6E6F6';
            break;
          case 5:
          case 3:
          case 1:
            document.getElementById('detail_control_message').style.color = '#F6E6F6';
            document.getElementById('detail_control_message').style.backgroundColor = '#990000';
            break;
        }

        detail_timerID = self.setTimeout("StartMessageFlasher()", detail_delay);
    }
}

function replaceDiv( eName )
{
    var el = document.getElementById(eName);
    var iPage = document.getElementById('featureContainer').innerHTML;
    el.value = iPage;
    document.getElementById('featureContainer').style.display = 'none';
    document.getElementById('editTab').style.display = 'none';
    editElementID = eName;
    // Get the element object and remove the first child
    // which would be the EDIT button added onload
//    el.removeChild(el.firstChild);

    if ( editor )
		editor.destroy();
    if (sub) {
            editor = CKEDITOR.replace( el,{customConfig : sharedHost+'/ckeditor/custom/config_sub.js'});
        } else {
            editor = CKEDITOR.replace( el,{customConfig : sharedHost+'/ckeditor/custom/config_main.js'});
        }
    editor.on('afterCommandExec', handleAfterCommandExec);
}
function cke_end() {
    var el = document.getElementById('dummyEditor');
    var iPage = document.getElementById('featureContainer');
    iPage.innerHTML = el.value;

    editor.destroy();
    editor = null;

    document.getElementById('featureContainer').style.display = '';
    document.getElementById('editTab').style.display = '';
    return false;
}
function handleAfterCommandExec(event) {
    //grab the button that was pressed
    var commandName = event.data.name;
    // check to see if it was the save
    if (commandName == 'save')
    {
//         var eName = editElementID;
//       var el = document.getElementById(eName);
//      alert('holy crap ... I found it');
      var jURL = "auth/updatePageContent.php";
      var jData = { "cName" : cName,
                    "pName" : pName,
                    "pContent" : escape(encodeURI(editor.getData()))
      };
 //     jData = json_parse(jData);
//      alert('cName='+jData.cName+'\npName='+jData.pName+'\npContent='+jData.pContent);
 //     alert('JSON='+jData.JSON);
      sendData('POST', jURL, jData);
      //add ajax call here.
      // this one however breaks it
      cke_end();
    }
    return false;
}

