var lastMouseX;
var lastMouseY;
var curPopupWindow = null;
var helpWindow = null;
var openListSetup = new Array();
var highlightForeSetup;
var highlightBackSetup;

function CheckAll(destino,valor)
    {
        var iCont ;
        var iTotal ;
        var nome ;
        var tipo ;
                        
        iTotal = document.frmPrincipal.length ;
                        
        for (iCont=0; iCont<iTotal; iCont++)
        {
            if(destino != '')
            {
            	if(destino != 'radio_')
				{
				    nome = document.frmPrincipal.elements[iCont].name ;
				 				
				    if(nome.substr(0,destino.length) == destino)
				 	{
				 	   document.frmPrincipal.elements[iCont].checked = valor ;
				 	}
								
				}
				else
				{
				      //eval('document.form1.radio[' + id + ']').checked ;
				}
			}	
			else
			{
				tipo = document.frmPrincipal.elements[iCont].type ;
				
				if(tipo == 'checkbox')
				{
					document.frmPrincipal.elements[iCont].checked = valor ;
				}
			}
                  
        }
    }
	
function setLastMousePosition(e) {
    if (navigator.appName.indexOf("Microsoft") != -1) e = window.event;
    lastMouseX = e.screenX;
    lastMouseY = e.screenY;
}

function openClickout(url) {
    window.open(url, "_blank", 'width=640,height=480,dependent=no,resizable=yes,toolbar=yes,status=yes,directories=yes,menubar=yes,scrollbars=1', false);
}

/**
 * Calls through to the openPopupFocus() with closeOnLoseFocus set to true.
 */
function openPopup(url, name, pWidth, pHeight, features, snapToLastMousePosition) {
    openPopupFocus (url, name, pWidth, pHeight, features, snapToLastMousePosition, true);
}

/**
 * Used for help popup links that need #'s escaped inline.
 */
function openPopupFocusEscapePounds(url, name, pWidth, pHeight, features, snapToLastMousePosition, closeOnLoseFocus) {
    openPopupFocus (url.replace("#","%23"), name, pWidth, pHeight, features, snapToLastMousePosition, closeOnLoseFocus);
}

/**
 * Handles popup windows.
 * If snapToLastMousePosition is true, then the popup will open up near the mouse click.
 * If closeOnLoseFocus is true, then it will close when the user clicks back into the browser window that opened it.
 */
function openPopupFocus(url, name, pWidth, pHeight, features, snapToLastMousePosition, closeOnLoseFocus) {
    closePopup();
    if (snapToLastMousePosition) {
		e = window.event;
    	lastMouseX = e.screenX;
    	lastMouseY = e.screenY;
        if (lastMouseX - pWidth < 0) {
            lastMouseX = pWidth;
        }
        if (lastMouseY + pHeight > screen.height) {
            lastMouseY -= (lastMouseY + pHeight + 50) - screen.height;
        }
        lastMouseX -= pWidth;
        lastMouseY += 10;
        features += "screenX=" + lastMouseX + ",left=" + lastMouseX + "screenY=" + lastMouseY + ",top=" + lastMouseY;
    }

    if (closeOnLoseFocus) {
        curPopupWindow = window.open(url, name, features, false);
        curPopupWindow.focus ();
    } else {
        // assign the open window to a dummy var so when closePopup() is called it won't be assigned to curPopupWindow
        win = window.open(url, name, features, false);
        win.focus ();
    }
}

function closePopup() {
    if (curPopupWindow != null) {
       
        if (!curPopupWindow.closed) {
            curPopupWindow.close();
        }
        curPopupWindow = null;
    }
}

function openLookup(baseURL,modified,searchParam) {
    if (modified == '1') baseURL = baseURL + searchParam;
    openPopup(baseURL, "lookup", 350, 300, "width=430,height=300,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,scrollable=no", true);
}

function pick(form,field,val) {
    eval("document."+form+"[\""+field+"\"].value=" + "\""+val+"\"");
    closePopup();
    return false;
}

function comboBoxPick (form, fieldName, comboBoxArrayName, index) {
    // get the field we are inserting the value into
    var field = eval ("document." +form+ "[\"" +fieldName+ "\"]"); 
    
    if (field != null) {
        // get to the javascript array for this combobox
        var comboBoxArray = eval (comboBoxArrayName);
        if (comboBoxArray != null) {
            
            if (index >= 0 && index < comboBoxArray.length) {
                // if we pass the bounds check, assign the value
                field.value = comboBoxArray[index];
            }
        }
    }
    closePopup ();
    return false;
}

function listProperties(obj) {
    var names = "";
    for (var i in obj) names += i + ", ";
    alert(names);
}


function lookupPick(formName, parentIdElementName, parentEditElementName, relatedFieldName, id, display, relatedFieldValue) {
    
    var parentIdElement = "document." + formName + "[\"" + parentIdElementName + "\"]";
    var parentEditElement = "document." + formName + "[\"" + parentEditElementName + "\"]";
    var parentEditOldValueElement = "document." + formName + "[\"" + parentEditElementName + "_lkold" + "\"]";
    var relatedFieldElement = "document." + formName + "[\"" + relatedFieldName + "\"]";

    if (eval(parentIdElement + ".type") == "select-one") {
        var found = false;
        for (i = 0; i < eval(parentIdElement + ".options.length"); i++) {
            if (eval(parentIdElement + ".options[" + i + "].value") == id ) {
                eval(parentIdElement + ".selectedIndex=" + i);
                found = true;
                break;
            }
        }
        if (!found) {
            eval(parentIdElement + ".options[" + parentIdElement + ".options.length] = new Option('" + display + "','" + id + "')");
            eval(parentIdElement + ".selectedIndex=" + parentIdElement + ".options.length - 1");
        }
        eval(parentEditElement + ".value = " + "\"" + display +"\"");    
        eval(parentEditOldValueElement + ".value = " + "\"" + display +"\"");
    } else {
        eval(parentIdElement + ".value = " + "\"" + id +"\"");    
        eval(parentEditElement + ".value = " + "\"" + display +"\"");
        eval(parentEditOldValueElement + ".value = " + "\"" + display +"\"");
    }

    if (relatedFieldName.length > 0) {
        eval(relatedFieldElement + ".value = " + "\"" + relatedFieldValue +"\"");
    }       

    var parentSubmitParam = parentEditElementName+"_lspf";      
    var doPost = eval("document."+formName+"[\""+ parentSubmitParam + "\"].value");
    if (doPost == '1') {
        eval("document."+formName+".submit()");    
    }
    closePopup();

    return false;
}

function setFocus() {
    var sidebarSearch;
    // search for a tabIndexed field to focus on
    for(var firstIndex=1; firstIndex < 5; firstIndex ++ ){
        var nextIndex = firstIndex;
        for (var frm = 0; frm < document.forms.length; frm++) {
            for (var fld = 0; fld < document.forms[frm].elements.length; fld++) {
                var elt = document.forms[frm].elements[fld];
                if ( elt.tabIndex != nextIndex) continue;
                if ((elt.type == "text" || elt.type == "textarea" || elt.type == "password") && !elt.disabled
                   && elt.name != "sbstr" &&  elt.name.indexOf("owner") != 0 && elt.name.indexOf("tsk1") != 0 && elt.name.indexOf("evt1") != 0) {
                    elt.focus();
                    if (elt.type == "text") {
                        elt.select();
                    }
                    return true;
                } else {
                    nextIndex++;
                    fld = 0;
                }
            }
        }
    }

    // failed to find a tabIndexed field, try to find the field based on it's natural position.
    for (var frm = 0; frm < document.forms.length; frm++) {
        for (var fld = 0; fld < document.forms[frm].elements.length; fld++) {
            var elt = document.forms[frm].elements[fld];
            // skip buttons, radio, or check-boxes
            // to skip "select" types, remove from if statement
            if ((elt.type == "text" || elt.type == "textarea" || elt.type == "password") && !elt.disabled) {
                if (elt.name == "sbstr" && document.forms[frm].name == "sbsearch") { 
                    sidebarSearch = elt; 
                } else if (elt.name.indexOf("owner") != 0) {
                    elt.focus();
                    // select text in text field or textarea
                    if (elt.type == "text") {
                        elt.select();
                    }
                    return true;
                }
            }
        }
    }

    return true;
}

function setNamedFocus(element_name) {
    for (var frm = 0; frm < document.forms.length; frm++) {
        for (var fld = 0; fld < document.forms[frm].elements.length; fld++) {
            var elt = document.forms[frm].elements[fld];
            if (elt.name == element_name) {
                elt.focus();
                if (elt.type == "text") {
                    elt.select();
                }
                return true;
            }
        }
    }
    return true;
}

// removes the leading and trailing spaces from a string, 
// similar to the java.lang.String.trim() function
// added by lturetsky, taken from http://www.voy.com/1888/58.html
function trim(st) {
    var len = st.length
    var begin = 0, end = len - 1;
    while (st.charAt(begin) == " " && begin < len) {
        begin++;
    }
    while (st.charAt(end) == " " && begin < end) {
        end--;
    }
    return st.substring(begin, end+1);
}


function formatPhone (field) {
    field.value = trim(field.value);

    var ov = field.value;
    var v = "";
    var x = -1;

    // is this phone number 'escaped' by a leading plus?
    if (0 < ov.length && '+' != ov.charAt(0)) { // format it
        // count number of digits
        var n = 0;
        if ('1' == ov.charAt(0)) {  // skip it
            ov = ov.substring(1, ov.length);
        }

        for (i = 0; i < ov.length; i++) {
            var ch = ov.charAt(i);

            // build up formatted number
            if (ch >= '0' && ch <= '9') {
                if (n == 0) v += "(";
                else if (n == 3) v += ") ";
                else if (n == 6) v += "-";
                v += ch;
                n++;
            }
            // check for extension type section; 
            // are spaces, dots, dashes and parentheses the only valid non-digits in a phone number?
            if (! (ch >= '0' && ch <= '9') && ch != ' ' && ch != '-' && ch != '.' && ch != '(' && ch != ')') {
                x = i;
                break;
            }
        }
        // add the extension
        if (x >= 0) v += " " + ov.substring(x, ov.length);

        // if we recognize the number, then format it
        if (n == 10 && v.length <= 40) field.value = v;
    }
    return true;
}

function clearcols () {
    for (var frm = 0; frm < document.forms.length; frm++) {
        for (var fld = 0; fld < document.forms[frm].elements.length; fld++) {
            var elt = document.forms[frm].elements[fld];
            if (elt.name == "c" || elt.name.substring(0,2) == "c_") {
                elt.checked = false;
            }
        }
    }
}

function setcols () {
    for (var frm = 0; frm < document.forms.length; frm++) {
        for (var fld = 0; fld < document.forms[frm].elements.length; fld++) {
            var elt = document.forms[frm].elements[fld];
            if (elt.name == "c" || elt.name.substring(0,2) == "c_") {
                elt.checked = true;
            }
        }
    }
}

function setUsername(uname, fname, lname, suffix) {
    if (uname.value.length == 0) {
        uname.value = 
                    fname.value.substring(0,1).toLowerCase() 
                    + lname.value.toLowerCase()
                    + "@"
                    + suffix.value;
    }
}
function setAlias(alias, fname, lname) {
    if (alias.value.length == 0) {
        alias.value = fname.value.substring(0,1).toLowerCase() +
                      lname.value.substring(0,4).toLowerCase();
    }
}

// POPUP WINDOW NUMBER 1 
function popWin(url) {
    closePopup();
    curPopupWindow = window.open(url,"win","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=550,height=300",false);
}
/**
 * Do NOT remove this function!
 * This function is used from within our help docs.
 */
function popWin2(url) {
   win = window.open(url,"win","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=720,height=500",false);
}

/**
 * Do NOT remove this function! 
 * Our help docs tell our customers to use this call to open links up in a new browser window.
 */
function adminWin(url) {
   win = window.open(url,"win","toolbar=1,location=1,directories=0,status=1,menubar=1,scrollbars=1,resizable=1,width=800,height=600",false);
}

// Changed name of window for printWin so that Printable views do not disappear
// Newname is popWin, Oldname(changed) was curPopupWindow
function printWin(url) {
  popWin = window.open(url,"win","dependent=no,toolbar=1,directories=0,location=0,status=1,menubar=1,scrollbars=1,resizable=1,width=705,height=400",false);
  popWin.focus();
}


function moveSelectElement3(sourceSelect, targetSelect, sourceLabel, targetLabel, keepTarget) {
    if (sourceSelect.selectedIndex > -1) {
        for (i=0; i < sourceSelect.length; ++i) {  
            var selectedOption = sourceSelect.options[i];
            if (selectedOption.selected) {
                if (selectedOption.text != sourceLabel) {
                    var newOption = new Option(selectedOption.text, selectedOption.value);
                    if (targetSelect.options.length > 0 && targetSelect.options[0].text == targetLabel) {
                        targetSelect.options[0] = newOption;
                        targetSelect.selectedIndex = 0;
                    } else {
                        targetSelect.options[targetSelect.options.length] = newOption;
                        targetSelect.selectedIndex = targetSelect.options.length - 1;
                    }
                } else {
                    sourceSelect.selectedIndex = -1;
                }
            }
        }
        if(!keepTarget)
        {   removeSelectElement3(sourceSelect, sourceLabel);
        }
    }
}

function moveOption (sourceSelect, targetSelect, 
                     keepSourceLabel, unmovableSourceValues, 
                     keepTargetLabel) {

    var sourceOptions = sourceSelect.options;
    
    var canMove;
    var option;
    
    // find which ones are selected...
    var selectedIds = new Array ();
    var index = 0;
    for (var i = 0; i < sourceSelect.length; i++) {
        option = sourceOptions[i];
        if (option.selected) {
            canMove = (option.text != keepSourceLabel);
            if (canMove && unmovableSourceValues != null) {
                // make sure we don't move any options defined as unmovable
                for (var j = 0; j < unmovableSourceValues.length; j++) {
                    if (unmovableSourceValues[j] == option.value) {
                        canMove = false;
                        break;
                    }
                }
            }

            // if this option can be moved we add it to our array of elements to move
            if (canMove) {
                selectedIds[index] = i;
                index++;
            } else {
                // if we can't move this option, then unselect it
                option.selected = false;
            }
        }
    }

    // move them over one by one
    var targetOptions = targetSelect.options;
    if (selectedIds.length > 0) {
        targetSelect.selectedIndex = -1;
        for (var i = 0; i < selectedIds.length; i++) {
            option = new Option (sourceOptions[selectedIds[i]].text, sourceOptions[selectedIds[i]].value);
            
            // replace the target value if its the last one
            if (targetOptions.length == 1 && targetOptions[0].text == keepTargetLabel) {
                targetOptions[0] = option;
                targetOptions[0].selected = true;
            } else {
                targetOptions[targetOptions.length] = option;
                targetOptions[targetOptions.length-1].selected = true;
            }
        }
    }

    // notify the Select Elements that their contents have changed
    if (targetSelect["onchange"]) {
        targetSelect.onchange();
    }
    if (sourceSelect["onchange"]) {
        sourceSelect.onchange();
    }

    // remove selected values from the source, starting with the last one selected
    for (var i = selectedIds.length - 1; i > -1; i--) {
        sourceSelect.remove(selectedIds[i]);
    }

    // Workaround here for a bug in IE:
    // If you have a select element with many values, and you've scrolled to 
    // the bottom and move an option from the top-most element you can now see,
    // IE would not refresh the select element, leaving a hole in the list. 
    // By forcing the select element disabled and back, it seems to refresh the
    // element properly.
    sourceSelect.disabled = true;
    sourceSelect.disabled = false;

    // make sure we don't get an empty list
    if (sourceOptions.length == 0) {
        sourceOptions[0] = new Option (keepSourceLabel, keepSourceLabel);
    }

    // if we moved anything, put the focus on the target list box
    if (selectedIds.length > 0) targetSelect.focus ();
}

function removeSelectElement3(sourceSelect, sourceLabel)
{   if (sourceSelect.selectedIndex > -1)
    {   for (i=sourceSelect.length-1; i > -1; i--) 
        {   if (sourceSelect.options[i].selected) sourceSelect.options[i] = null;
        }
        if (sourceSelect.length == 0) 
        {   var placeHolder = new Option(sourceLabel, sourceLabel);
            sourceSelect.options[0] = placeHolder;
        }
    }
}


function moveUp(sourceSelect) {
    if (sourceSelect.length > 1) {
        var options = sourceSelect.options;

        // find which ones are selected...
        var selectedIds = new Array ();
        var index = 0;
        for (var i = 1; i < sourceSelect.length; i++) {
            if (options[i].selected) {
                selectedIds[index] = i;
                index++;
            }
        }

        // move each selected option up 
        var selId;
        for (var i = 0; i < selectedIds.length; i++) {
            selId = selectedIds[i];
            privateMoveUp (options, selId);
            options[selId].selected = false;
            options[selId-1].selected = true;
        }

        sourceSelect.focus ();
    }
}

function moveDown(sourceSelect) {
    if (sourceSelect.length > 1) {
        var options = sourceSelect.options;

        // find which ones are selected
        var selectedIds = new Array ();
        var index = 0;
        for (var i = sourceSelect.length-2; i >= 0; i--) {
            if (sourceSelect.options[i].selected) {
                selectedIds[index] = i;
                index++;
            }
        }

        // move each selected element down
        var selId;
        for (var i = 0; i < selectedIds.length; i++) {
            selId = selectedIds[i];
            privateMoveDown (options, selId);
            options[selId].selected = false;
            options[selId+1].selected = true;
        }
        
        sourceSelect.focus ();
    }
}


function moveTop(sourceSelect) {
    var selIndex = sourceSelect.selectedIndex;

    if (sourceSelect.length > 1 && selIndex > 0) {
        var options = sourceSelect.options;

        for (var i = selIndex; i > 0; i--) {
            privateMoveUp (options, i);
        }
        
        sourceSelect.focus ();
        sourceSelect.selectedIndex = 0;
    }
}

function moveBottom(sourceSelect) {
    var selIndex = sourceSelect.selectedIndex;

    // gots to have at least 2 items and something selected, but not the last one 
    if (sourceSelect.length > 1 && selIndex > -1 && selIndex < sourceSelect.length - 1) {
        var options = sourceSelect.options;
      
        for (var i = selIndex; i < sourceSelect.length - 1; i++) {
            privateMoveDown (options, i);
        }

        sourceSelect.focus ();
        sourceSelect.selectedIndex = sourceSelect.length - 1;
    }
}

/*
 * Do not call this function directly. 
 * As it does NO bounds checking.
 * Please use the moveUp or moveTop calls.
 */
function privateMoveUp (options, index) {
    var newOption = new Option (options[index-1].text, options[index-1].value);
    options[index-1].text = options[index].text;
    options[index-1].value = options[index].value;
    options[index].text = newOption.text;
    options[index].value = newOption.value;
}

/*
 * Do not call this function directly. 
 * As it does NO bounds checking.
 * Please use the moveDown or moveBottom calls.
 */
function privateMoveDown (options, index) {
    var newOption = new Option (options[index+1].text, options[index+1].value);
    options[index+1].text = options[index].text;
    options[index+1].value = options[index].value;
    options[index].text = newOption.text;
    options[index].value = newOption.value;
}


/**
 * Used when submitting a dueling list boxes element. 
 * Stores all the values into hidden form parameters so we can get them out
 */
function saveAllSelected (fromSelectArray, toArray, delim, escape, emptyLabel) {
    var i,j,escapedValue;
    // loop through all the select elements
    for (i = 0; i < fromSelectArray.length; i++) {
        toArray[i].value = ''; // clear out the value to start
        // now loop through all the values in the select element
        for (j = 0; j < fromSelectArray[i].length; j++) {
            // copy over the value as long as it is not the emptyLabel
            if (!(fromSelectArray[i].length == 1 && fromSelectArray[i].options[0].value == emptyLabel)) {
                toArray[i].value += fromSelectArray[i].options[j].value.replace(new RegExp(delim,"g"), escape+delim);
            }

            // add the delimiter (except after the last one)
            if (j + 1 < fromSelectArray[i].length) {
                toArray[i].value += delim;
            }
        }
    }
}

function openwizard(url, name, resizable) {
  var win = window.open('', name, 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable='+resizable+',width=675,height=550,screenx=50,screeny=10,left=50,top=10',false)
  if ((win.document.URL == '') || (win.document.URL == 'about:blank')) win.location = url; 
  win.focus ();
}

function escapeUTF(src) {
    var ret = "";
    for (i = 0; i < src.length; i++) {
        var ch = src.charCodeAt(i);
        if (ch <= 0x7F) {
            ret += escape(src.charAt(i));
        } else if (ch <= 0x07FF) {
            ret += '%' + ((ch >> 6) | 0xC0).toString(16) + '%' + ((ch & 0x3F) | 0x80).toString(16);
        } else if (ch >= 0x0800) {
            ret += '%' + ((ch >> 12) | 0xE0).toString(16) +
                   '%' + (((ch >> 6) & 0x3F) | 0x80).toString(16) + '%' + ((ch & 0x3F) | 0x80).toString(16);
        }
    }
    return ret;
}

function openRefer(url) {
    window.open(url, 'referv2', 'resizable=no,toolbar=no,status=no,directories=no,scrollbars=yes,width=420,height=500', false); 
}

function changeOpenerWindowLocation (url) {
    if ((window.top.opener == null) || window.top.opener.closed) {
        window.top.open (url);
    } else {
        window.top.opener.location.href = url;
        window.top.opener.focus ();
    }   
}

function verifyChecked(form, element_name, errorMessage) {
    for (i = 0; i < form.elements.length; i++) {
        if ((form.elements[i].name == element_name) && form.elements[i].checked) {
            return true;
        }
    }

    // if we haven't returned yet, it's not checked
    alert(errorMessage);
    return false;
}

function submitFormActionURL (form, url) {
    form.action = url;
    form.submit();
}

function SelectChecked(form, element_name, value)
{
    var i = 0;
    for (i = 0; i < form.elements.length; i++) {
        if (form.elements[i].name == element_name) {
            form.elements[i].checked = value;
        }
    }
}

function getLoginCookieValue() 
{
    var c = document.cookie;
    var idx = c.indexOf('login=');
    if ( idx == -1) return "";
    idx += 'login='.length;
    var end = c.indexOf(';',idx);
    if ( end == -1) end = c.length;
    return c.substring(idx,end);
}
        
function loader() 
{
     var username = getLoginCookieValue();
     if (username.length > 0) {
         document.login_noop.un_noop.value = username;
         document.login.un.value = username;
         document.login.pw.focus();
     } else {
         document.login_noop.un_noop.focus();
     }
     document.login.width.value=screen.width;
     document.login.height.value=screen.height;
}
function FormataNumero(ConteudoCampo)
{
if (((event.keyCode) > 47) && ((event.keyCode) < 58))
{
   NumDig = ConteudoCampo.value;
   TamDig = NumDig.length;
   Contador = 0;
   if (TamDig < 16)
   {
   if (TamDig > 1)
      {numer = "";
      for (i = TamDig; (i >= 0); i--){
          if ((parseInt(NumDig.substr(i,1))>=0) && (parseInt(NumDig.substr(i, 1))<=9))
            {
             Contador++;
             if ((Contador == 2) && ((TamDig -i) < 4))
              {numer = ","+numer;
               Contador = 0;
               }
             else if (Contador == 3)
              {numer = "."+numer;
               Contador = 0;
              }
             numer = NumDig.substr(i, 1)+numer;
            }
           }
      ConteudoCampo.value = numer;
      };
   return(true)}
   else return(false)
	}
	}
function FormataPorcento(ConteudoCampo)
{
if (((event.keyCode) > 47) && ((event.keyCode) < 58))
{
   NumDig = ConteudoCampo.value;
   TamDig = NumDig.length;
   Contador = 0;
   if (TamDig < 16)
   {
   if (TamDig > 1)
      {numer = "";
      for (i = TamDig; (i >= 0); i--){
          if ((parseInt(NumDig.substr(i,1))>=0) && (parseInt(NumDig.substr(i, 1))<=9))
            {
             Contador++;
             if ((Contador == 2) && ((TamDig -i) < 4))
              {numer = ","+numer;
               Contador = 0;
               }
             numer = NumDig.substr(i, 1)+numer;
            }
           }
      ConteudoCampo.value = numer;
      };
   return(true)}
   else return(false)
	}
	}
function FormataNum(ConteudoCampo)
{
	if (((event.keyCode) > 47) && ((event.keyCode) < 58))
	{
   		NumDig = ConteudoCampo.value;
   		TamDig = NumDig.length;
   		Contador = 0;
   		ConteudoCampo.value = NumDig;
   		return(true)
	}
   	else 
	{
		return(false)
	}		
}	
function CheckEmail(varEmail) 
{
  	if (varEmail.length >= 1) 
	{
		if ((varEmail.indexOf("@") < 1 && varEmail.indexOf("@") >1) || varEmail.indexOf(".") < 1)
		{
	  		alert('Digite um endereço válido de e-mail.');
			return false
		}
  	}
}
function FormataCep(ConteudoCampo)
{
	if (((event.keyCode) > 47) && ((event.keyCode) < 58))
	{
		NumDig = ConteudoCampo.value;
   		TamDig = NumDig.length;
	   	Contador = 0;
   if (TamDig < 9)
   {

   		if (TamDig > 1)
	    {
			numer = "";
			for (i = TamDig; (i >= 0); i--)
			{
          		if ((parseInt(NumDig.substr(i,1))>=0) && (parseInt(NumDig.substr(i, 1))<=9))
            	{
             		Contador++;
             		if ((Contador == 3) && ((TamDig -i) < 4))
              		{
			  			numer = "-"+numer;
               			Contador = 0;
               		}
             		numer = NumDig.substr(i, 1)+numer;
            	}
           	}
      		ConteudoCampo.value = numer;
      	};
   		return(true)
	}
   	else 
   	{
   		return(false)
	}
}
}
function FormataHora(ConteudoCampo)
{
	if (((event.keyCode) > 47) && ((event.keyCode) < 58))
	{
		NumDig = ConteudoCampo.value;
   		TamDig = NumDig.length;
	   	Contador = 0;
	 if (TamDig < 5)
   	{

   		if (TamDig > 1)
	    {
			numer = "";
			for (i = TamDig; (i >= 0); i--)
			{
          		if ((parseInt(NumDig.substr(i,1))>=0) && (parseInt(NumDig.substr(i, 1))<=9))
            	{
             		Contador++;
             		if ((Contador == 2) && ((TamDig -i) < 3))
              		{
			  			numer = ":"+numer;
               			Contador = 0;
               		}
             		numer = NumDig.substr(i, 1)+numer;
            	}
           	}
      		ConteudoCampo.value = numer;
      	};
   		return(true)
	}
   	else 
   	{
   		return(false)
	}
}
}
function FormataData(ConteudoCampo)
{
	if (((event.keyCode) > 47) && ((event.keyCode) < 58))
	{
		NumDig = ConteudoCampo.value;
   		TamDig = NumDig.length;
	   	Contador = 0;
   if (TamDig < 10)
   {

   		if (TamDig > 1 && TamDig < 8)
	    {
			numer = "";
			for (i = TamDig; (i >= 0); i--)
			{
				//alert(TamDig)
				//alert(parseInt(NumDig.substr(i,1)))
          		if ((parseInt(NumDig.substr(i,1))>=0) && (parseInt(NumDig.substr(i, 1))<=9))
            	{
             		Contador++;
             		if ((Contador == 2) && ((TamDig -i) < 3) )
              		{
			  			numer = "/"+numer;
               			Contador = 0;
               		}
             		else if ((Contador == 2) )
              		{
						//alert('Aqui')
			  			numer = "/"+numer;
               			Contador = 0;
              		}
             		numer = NumDig.substr(i, 1)+numer;
            	}
           	}
      		ConteudoCampo.value = numer;
      	}
   		return(true)
	}
   	else 
   	{
   		return(false)
	}
}
}
	function ValidaData(varData,campo)
	{
		
	if(campo.value!='')
	{
		var dateStr=varData
		var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
		var matchArray = dateStr.match(datePat);
		if (matchArray == null) 
		{
			alert('Data invalida')
			return("false");
		}
		else
		{
			month = matchArray[3];
			month++;month--;month1=month-1;
			day = matchArray[1];
			day++;day--;day1=day+1;
			year = matchArray[4];
			if (year.substr(0,2)==20 || year.substr(0,2)==19)
			{
				if (month < 1 || month > 12) 
				{
					alert('Data invalida')
campo.focus()
campo.value=''
					return("false");
				}
				else
				{
					if (day < 1 || day > 31) 
					{
						alert('Data invalida')
campo.focus()
campo.value=''
						return("false");
					}
					else
					{
						if ((month==4 || month==6 || month==9 || month==11) && day==31) 
						{
							alert('Data invalida')
campo.focus()
campo.value=''
							return("false");
						}
						else
						{
							if (month == 2) 
							{
								var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
								if (day>29 || (day==29 && !isleap)) 
								{
									alert('Data invalida')
campo.focus()
campo.value=''
									return("false");
								}
							}
						}
					}
				}
			}
			else
			{
				alert('Data invalida')
				campo.focus()
				campo.value=''
				return("false");
			}
		}
	}
	
	}
	function ValidaHora(varHora,campo)
	{

if(campo.value!='')
{
		if (varHora.length <5)
		{
			alert('Hora invalida')
campo.focus()
campo.value=''
			return('false')
		}
	
		varChar = varHora.substring(2,3);
		
		if (varChar != ':')
		{
			alert('Formato de hora invalido')
campo.focus()
campo.value=''
			return('false')
		}		
		numero = varHora.substring(2,0) + varHora.substring(3,5)
		if (Valida_Numero(numero,'Digite somente numeros') == 'false')
		{
			return('false');
		}
		if (varHora.substring(2,0)>23)
		{
			alert('Hora invalida')
campo.focus()
campo.value=''
			return('false');
		}
		if (varHora.substring(5,3)>59)
		{
			alert('Hora invalida')
campo.focus()
campo.value=''
			return('false');
		}
	
		return('true');
}
	}

	function ChecarEvento()
	{
		if (document.frmPrincipal.assunto.value == '')
		{
			alert('Assunto  é obrigatório')
			return false;
		}
		if (document.frmPrincipal.DataIni.value == '')
		{
			alert('Data é obrigatória')
			return false;
		}
		else
		{
			if (ValidaData(document.frmPrincipal.DataIni.value)== 'false')
			{
				return false;
			}
		}
//		if (document.frmPrincipal.Hora1.value == '')
//		{
//			alert('Hora é obrigatória')
//			return false;
//		}
//		else
//		{
//			if (ValidaHora(document.frmPrincipal.Hora1.value)== 'false')
//			{
//				return false;
//			}
//		}
				
		return true;
	}
	function ChecarRelacionamento()
	{
		if (document.frmPrincipal.objetivo.value == '')
		{
			alert('Objetivo  é obrigatório')
			return false;
		}
		if (document.frmPrincipal.data_fechamento.value == '')
		{
			alert('Data é obrigatória')
			return false;
		}
		else
		{
			if (ValidaData(document.frmPrincipal.data_fechamento.value)== 'false')
			{
				return false;
			}
		}
		
		return true;
	}	
	function Valida_Numero(numero,varMsg)
	{ 
	flag="";
    for(x=0;x<=numero.length;x++)
    {
	    if(parseInt(numero.substring(x,x+1)))
            flag = flag + numero.substring(x,x+1);
         else
          {
              if(numero.substring(x,x+1)== 0)
                 flag = flag + 0;
              else
                {
                   alert(varMsg);
                   return("false");
                 }
          }
    }
   	return(flag); 
	}
	function TrocaSenha()
	{
		document.frmPrincipal.action = "trocasenha1.asp";
		document.frmPrincipal.method = "post";
		document.frmPrincipal.target = "";
		document.frmPrincipal.submit();
	}
	function Tamanho(ConteudoCampo, varMaxLength)
	{
		NumDig = ConteudoCampo.value;
		TamDig = NumDig.length;
		if(TamDig <= varMaxLength)
		{
   			Contador = 0;
   			ConteudoCampo.value = NumDig;
   			return(true)
		}
		else
		{
			alert('O tamanho maximo para este campo é de ' + varMaxLength +' caracteres')
			return(false)
		}
	}	
	function listaPais(vartipoBusca,varTituloHead, varTipo)
	{
		window.status="AGUARDE ! Pesquisando . . ."; 
		retorno =window.showModalDialog("../crm_LovLista.asp?busca=" + vartipoBusca +"&TituloHead="+ varTituloHead+"&Tipo="+varTipo,1,"Dialogwidth:25;Dialogheight:14;Center:1;help:0");   
   
   
		if (retorno != null)
		{
			if (retorno[0] != "")
			{
				varCodigo = 0
				varPos = 0
				varIndCep = ''
				varIndUF = ''
				varString = retorno[0]
				varPos = varString.indexOf('|')
				varCodigo = varString.substring(0,varPos)
				varString1 = varString.substring(varPos+1,99)
				varPos = varString1.indexOf('|')
				varIndCep = varString1.substring(0,1)
				varString2 = varString1.substring(varPos+1,99)
				varPos = varString2.indexOf('|')
				varIndUF = varString2.substring(1,varPos)
				if(varIndCep=='S')
				{
					MM_showHideLayers('CEPBusca','','show');
					MM_showHideLayers('CEP','','hide');
				}
				else
				{
					MM_showHideLayers('CEPBusca','','hide');		
					MM_showHideLayers('CEP','','show');
				}
				if(varIndUF =='S')
				{
					MM_showHideLayers('Estado','','show');
				}
				else
				{
					MM_showHideLayers('Estado','','hide');		
				}
				document.frmPrincipal.CepBusca.disabled=false
				document.frmPrincipal.Cep.disabled=false
				document.frmPrincipal.Endereco.disabled=false
				document.frmPrincipal.Numero.disabled=false
				document.frmPrincipal.Complemento.disabled=false
				document.frmPrincipal.Bairro.disabled=false
				document.frmPrincipal.Cidade.disabled=false
				document.frmPrincipal.Estado.disabled=false
				
				document.frmPrincipal.hdnIndCep.value = varIndCep
				document.frmPrincipal.hdnIndUF.value = varIndUF
      			document.frmPrincipal.hdnPais.value = varCodigo
				document.frmPrincipal.Pais.value =retorno[1]
			}
		}
		else
		{	
      			document.frmPrincipal.hdnPais.value =""
				alert(document.frmPrincipal.hdnPais.value)
      			document.frmPrincipal.Pais.value =""
		}	
		window.status="";    
	}
	function listaEstado(vartipoBusca,varTituloHead)
	{
		window.status="AGUARDE ! Pesquisando . . ."; 
		retorno =window.showModalDialog("../crm_LovLista.asp?busca=" + vartipoBusca +"&TituloHead="+ varTituloHead+"&Tipo=20&Param="+document.frmPrincipal.hdnPais.value,1,"Dialogwidth:25;Dialogheight:14;Center:1;help:0");   
   
		if (retorno != null)
		{
			if (retorno[0] != "")
			{
      			document.frmPrincipal.hdnEstado.value =retorno[0]
      			document.frmPrincipal.Estado.value =retorno[1]
			}
	
		}
		else
		{	
      			document.frmPrincipal.hdnEstado.value =""
      			document.frmPrincipal.Estado.value =""

		}	
		window.status="";    
	}
	function textCounter(field, countfield, maxlimit) 
	{
		if (field.value.length > maxlimit)
		{
			field.value = field.value.substring(0, maxlimit);
		}
		else 
		{
			countfield.value = maxlimit - field.value.length;
		}
	}
function BuildMask(mask,sValue,slen,isparam) {	 	
	
	if (isparam) {
		if ((event.keyCode==8)||(event.keyCode==13)) {		
			commandClick("changeField",sValue);
		}
	}	
	var Len = sValue.value.length;	
	if (slen >= Len) {		
		switch (mask.substr(Len,1)) {
			case "#":
						if(((event.keyCode>=0x30)&&(event.keyCode<=0x39))||(event.keyCode==8)||(event.keyCode==13)) {								
							return true;
						}			
						break;
			case "?":
						if( ((event.keyCode>=65)&&(event.keyCode<=90)) ||((event.keyCode>=97)&&(event.keyCode<=127))||
							(event.keyCode==8)||(event.keyCode==13)) {																									
								return true																	
						}	
						break;
			case "a":						
						return true					
						break;
			case "A":					
						if (event.keyCode!=32) {											
							return true																	
						}
						break;
			case "9":								
						if(((event.keyCode>=0x30)&&(event.keyCode<=0x39))||(event.keyCode==8)||(event.keyCode==13)|| (event.keyCode==32)) {																	
							return true;
						}			
						break;
			case "C":
						if ((event.keyCode==32)||((event.keyCode>=65)&&(event.keyCode<=90)) ||((event.keyCode>=97)&&(event.keyCode<=127))||
							(event.keyCode==8)||(event.keyCode==13)) {										 			
							 return true;							 													
						}
						break;
			case "":
				return true;
			default:			
				
				sValue.value = sValue.value + mask.substr(Len,1);				
				return true;
				/*Len = sValue.value.length + 1;				
				var sKey = String.fromCharCode(event.keyCode);
				alert(sKey);
				if ((event.keyCode!=8)||(event.keyCode!=13)){							
					if (slen >= Len) {					
						sValue.value +=  new String(sKey);								
					}																					
				}*/									
		}	
	}
	event.keyCode=0;						
}
function validaCPF (varCPF)
{
	numcpf = limpa_string(varCPF)
	x=0; soma=0; dig1=0; dig2=0; texto=''; numcpf1='';
	len = numcpf.length; x = len -1;
	for (var i=0; i <= len - 3; i++)
	{
    	y = numcpf.substring(i,i+1); soma = soma + ( y * x);
	    x = x - 1; texto = texto + y;
	}
	dig1 = 11 - (soma % 11);
	if (dig1 == 10) dig1=0 ; 
	if (dig1 == 11) dig1=0 ;
	numcpf1 = numcpf.substring(0,len - 2) + dig1 ;
	x = 11; soma=0;
	for (var i=0; i <= len - 2; i++)
	{
    	soma = soma + (numcpf1.substring(i,i+1) * x); x = x - 1;
	}
	dig2= 11 - (soma % 11);
	if (dig2 == 10) dig2=0;
	if (dig2 == 11) dig2=0;
	if ((dig1 + '' + dig2) == numcpf.substring(len,len-2))
	{
    	return true;
	}
	alert('CPF invalido!');

} 

function validaCNPJ(numCNPJ)
{
 	var i;	
    numCNPJ = limpa_string(numCNPJ);
    var c = numCNPJ.substr(0,12);
    var dv = numCNPJ.substr(12,2);
    var d1 = 0;
    for (i = 0; i < 12; i++)
    {
        d1 += c.charAt(11-i)*(2+(i % 8));
    }
	if (d1 == 0) return false;
	d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(0) != d1)
    {
        return false;
    }

    d1 *= 2;
    for (i = 0; i < 12; i++)
    {
        d1 += c.charAt(11-i)*(2+((i+1) % 8));
    }
    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(1) != d1)
    {
	alert('CNPJ invalido!');
    }
	return true;
}
	function limpa_string(varNumero)
	{
		numero = varNumero
		clean = ''
		tamNum = numero.length
		for(i = 0; i < tamNum;i++)
		{
			carac = numero.substring(i,i+1);
			if (carac != '1' && carac != '2' && carac != '3' && carac != '4' && carac != '5' && carac != '6' && carac != '7' && carac != '8' && carac != '9' && carac != '0')
			{
				carac = '';
			}
			clean = clean + carac;
		}	
		return clean
	}

/*function toggleSetup(item) 
	{
       var obj=document.getElementById(item + "_child");
       if (obj != null) 
	   {
           visible=(obj.style.display!="none")
           var key=document.getElementById(item + "_icon");
           if (visible) 
		   {
             obj.style.display="none";
             key.innerHTML="<IMG BORDER=0 width=\"15\" height=\"17\" align=\"texttop\" SRC=\"../img/setup_plus.gif\">";
           } 
           else 
		   {
              obj.style.display="block";
              key.innerHTML="<IMG BORDER=0 width=\"15\" height=\"17\" align=\"texttop\" SRC=\"../img/setup_minus.gif\">";
           }
       }
    }
*/

    function addToOpenSetup (item) {
        for (var i = 0; i < openListSetup.length; i++) {
            if (openListSetup[i] == null) {
                openListSetup[i] = item;    
                updateCookiesSetup();
                return;     
            }
        }
        openListSetup[openListSetup.length] = item;
        updateCookiesSetup();
    }
    
    function removeFromOpenSetup (item) {   
        for (var i = 0; i < openListSetup.length; i++) {
            if (openListSetup[i] == item) {
                openListSetup[i] = null;            
            }
        }
        updateCookiesSetup();
    }

    function updateCookiesSetup() {
        var stringlist = "";
        for (var i = 0; i < openListSetup.length; i++) {
            if (openListSetup[i] != null) {
                stringlist = stringlist + openListSetup[i] + ":";
            }
        }
                
        SetCookieSetup("setupopen", stringlist, null, "/");     
    }
    
    function toggleSetup(item) {

		var obj=document.getElementById(item + "_child");
       	if (obj != null) {
           visible=(obj.style.display!="none")
           var key=document.getElementById(item + "_icon");
           if (visible) {
             obj.style.display="none";
             key.innerHTML="<IMG BORDER=0 width=\"15\" height=\"17\" align=\"texttop\" SRC=\"../img/setup_plus.gif\">";
             removeFromOpenSetup (item);
           } 
           else {
              obj.style.display="block";
              key.innerHTML="<IMG BORDER=0 width=\"15\" height=\"17\" align=\"texttop\" SRC=\"../img/setup_minus.gif\">";
              addToOpenSetup(item);
           }
       }
    }

    function expandSetup(item) {
       var obj=document.getElementById(item + "_child");
       if (obj != null) {
           visible=(obj.style.display!="none")
           var key=document.getElementById(item + "_icon");
           if (!visible) {
              obj.style.display="block";
              key.innerHTML="<IMG BORDER=0 width=\"15\" height=\"17\" align=\"texttop\" SRC=\"../img/setup_minus.gif\">";
           }
       }
    }

    function getCookieValSetup(offset) {
        var endstr = document.cookie.indexOf (";", offset);
        if (endstr == -1)
            endstr = document.cookie.length;
        return unescape(document.cookie.substring(offset, endstr));
    }

    function GetCookieSetup (name) {  

        var arg = name + "=";  
        var alen = arg.length;  
        var clen = document.cookie.length;  
        var i = 0;  

        while (i < clen) {    
            var j = i + alen;    
            if (document.cookie.substring(i, j) == arg)     
                return getCookieValSetup (j);    
            i = document.cookie.indexOf(" ", i) + 1;    
            if (i == 0) break;   
        }  
        return null;
    }


    function SetCookieSetup (name, value) {  
        var argv = SetCookieSetup.arguments;  
        var argc = SetCookieSetup.arguments.length;  
        var expires = (argc > 2) ? argv[2] : null;  
        var path = (argc > 3) ? argv[3] : null;  
        var domain = (argc > 4) ? argv[4] : null;  
        var secure = (argc > 5) ? argv[5] : false;  

        document.cookie = name + "=" + value + 
            ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + 
            ((path == null) ? "" : ("; path=" + path)) +  
            ((domain == null) ? "" : ("; domain=" + domain)) +    
            ((secure == true) ? "; secure" : "");
        }

    function DeleteCookieSetup (name) {  
    
        var cval = GetCookieSetup("setupopen");
        if (cval == null) {
            return;
        }
    
        var exp = new Date(); 
        exp.setTime(exp.getTime() - 1);

        SetCookieSetup("setupopen", "", exp, "/");
    }


function Menu(varPagina)
{
	document.frmPrincipal.action = varPagina;
	document.frmPrincipal.method = "post";
	document.frmPrincipal.target = "";
	document.frmPrincipal.submit();
}





