var __isIE = navigator.appVersion.match(/MSIE/);
var __userAgent = navigator.userAgent;
var __isFireFox = __userAgent.match(/firefox/i);
var __isFireFoxOld = __isFireFox && (__userAgent.match(/firefox\/2./i) || __userAgent.match(/firefox\/1./i));
var __isFireFoxNew = __isFireFox && !__isFireFoxOld;

function __parseBorderWidth(width) {
  var res = 0;
  if (typeof (width) == "string" && width != null && width != "") {
    var p = width.indexOf("px");
    if (p >= 0) {
      res = parseInt(width.substring(0, p));
    }
    else {
      //do not know how to calculate other values (such as 0.5em or 0.1cm) correctly now
      //so just set the width to 1 pixel
      res = 1;
    }
  }
  return res;
}

//returns border width for some element
function __getBorderWidth(element) {
  var res = new Object();
  res.left = 0; res.top = 0; res.right = 0; res.bottom = 0;
  if (window.getComputedStyle) {
    //for Firefox
    var elStyle = window.getComputedStyle(element, null);
    res.left = parseInt(elStyle.borderLeftWidth.slice(0, -2));
    res.top = parseInt(elStyle.borderTopWidth.slice(0, -2));
    res.right = parseInt(elStyle.borderRightWidth.slice(0, -2));
    res.bottom = parseInt(elStyle.borderBottomWidth.slice(0, -2));
  }
  else {
    //for other browsers
    res.left = __parseBorderWidth(element.style.borderLeftWidth);
    res.top = __parseBorderWidth(element.style.borderTopWidth);
    res.right = __parseBorderWidth(element.style.borderRightWidth);
    res.bottom = __parseBorderWidth(element.style.borderBottomWidth);
  }

  return res;
}

//returns absolute position of some element within document
function getAbsolutePos(element) {
  var res = new Object();
  res.x = 0; res.y = 0;
  if (element !== null) {
    res.x = element.offsetLeft;
    res.y = element.offsetTop;

    var offsetParent = element.offsetParent;
    var parentNode = element.parentNode;
    var borderWidth = null;

    while (offsetParent != null) {
      res.x += offsetParent.offsetLeft;
      res.y += offsetParent.offsetTop;

      var parentTagName = offsetParent.tagName.toLowerCase();

      if ((__isIE && parentTagName != "table") || (__isFireFoxNew && parentTagName == "td")) {
        borderWidth = __getBorderWidth(offsetParent);
        res.x += borderWidth.left;
        res.y += borderWidth.top;
      }

      if (offsetParent != document.body && offsetParent != document.documentElement) {
        res.x -= offsetParent.scrollLeft;
        res.y -= offsetParent.scrollTop;
      }

      //next lines are necessary to support FireFox problem with offsetParent
      if (!__isIE) {
        while (offsetParent != parentNode && parentNode !== null) {
          res.x -= parentNode.scrollLeft;
          res.y -= parentNode.scrollTop;

          if (__isFireFoxOld) {
            borderWidth = kGetBorderWidth(parentNode);
            res.x += borderWidth.left;
            res.y += borderWidth.top;
          }
          parentNode = parentNode.parentNode;
        }
      }

      parentNode = offsetParent.parentNode;
      offsetParent = offsetParent.offsetParent;
    }
  }
  return res;
}

function FindObject( oName, oFrame, oDoc ) {
  if( !oDoc ) { if( oFrame ) { oDoc = oFrame.document; } else { oDoc = window.document; } }
  if( oDoc[oName] ) { return oDoc[oName]; } if( oDoc.all && oDoc.all[oName] ) { return oDoc.all[oName]; }
  if( oDoc.getElementById && oDoc.getElementById(oName) ) { return oDoc.getElementById(oName); }
  for( var x = 0; x < oDoc.forms.length; x++ ) { if( oDoc.forms[x][oName] ) { return oDoc.forms[x][oName]; } }
  for( var x = 0; x < oDoc.anchors.length; x++ ) { if( oDoc.anchors[x].name == oName ) { return oDoc.anchors[x]; } }
  for( var x = 0; document.layers && x < oDoc.layers.length; x++ ) {
    var theOb = FindObject( oName, null, oDoc.layers[x].document ); if( theOb ) { return theOb; } }
  if( !oFrame && window[oName] ) { return window[oName]; } if( oFrame && oFrame[oName] ) { return oFrame[oName]; }
  for( var x = 0; oFrame && oFrame.frames && x < oFrame.frames.length; x++ ) {
    var theOb = FindObject( oName, oFrame.frames[x], oFrame.frames[x].document ); if( theOb ) { return theOb; } }
  return null;
}

function FindObjectInForm(oName, oForm) {
  if (oForm) {
    var oDoc = window.document;
    if (oDoc.forms[oForm][oName]) {
      return oDoc.forms[oForm][oName];
    }
    return (null);
  } else {
    return (FindObject(oName));
  }
}

function ToggleMaximizeMinimize(aName) {
  divobj = FindObject('div_' + aName);
  imgobj = FindObject('img_' + aName);
  if (divobj != null) {
    if (divobj.style.display != 'none') {
      divobj.style.display = 'none';
      if (imgobj != null) imgobj.src = '/local/images/template/window_maximize.gif';
      setCookie('status_' + aName, 'N', 30);
    } else {
      divobj.style.display = 'block';
      if (imgobj != null) imgobj.src = '/local/images/template/window_minimize.gif';
      setCookie('status_' + aName, 'Y', 30);
    }
  }
}

function SetObjectClass(aObject, aClass) {
	var obj = FindObject(aObject);
	if (obj) {
		obj.setAttribute("class", aClass); 
	}
}

function ShowHideRegion(aName, aMode) {
  divobj = FindObject(aName);
  if (divobj) {
    if (aMode) {
      divobj.style.display = '';
    } else {
      divobj.style.display = 'none';
    }
  }
}

function ToggleRegionVisibility(aName) {
  divobj = FindObject(aName);
  if (divobj) {
    ShowHideRegion(aName, !(divobj.style.display != 'none'));
  }
}

function AppendTextToField(aField, aText) {
  var edt = FindObject(aField);
  if (edt) {
    edt.value = edt.value + aText;
  }
}

function ValidEmailAddress(EmailAddr) {
	Filtro = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
    if (Filtro.test(EmailAddr)) {
      	return true;
    } else {
      	return false;
    }
}

function LTrim( value ) {
  if (value) {
    var re = /\s*((\S+\s*)*)/;
  	return value.replace(re, "$1");
  } else {
    return ("");
  }
}

function RTrim( value ) {
  if (value) {
    var re = /((\s*\S+)*)\s*/;
    return value.replace(re, "$1");
  } else {
    return ("");
  }
}

function Trim(value) {
	return LTrim(RTrim(value));
}

function SetCookie(name, value, expires, path, domain, secure ) {
  var today = new Date();
  today.setTime( today.getTime() );
  if ( expires ) {
    expires = expires * 1000 * 60 * 60 * 24;
  }
  var expires_date = new Date( today.getTime() + (expires) );
  document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

function GetCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else {
    begin += 2;
  }
  var end = document.cookie.indexOf(";", begin);
  if (end == -1) end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

function SaveAbsolutePagePosition(aName) {
  var db = (document.body) ? 1 : 0;
  var scroll = (window.scrollTo) ? 1 : 0;
  if (scroll) {
    var x = (db) ? document.body.scrollLeft : pageXOffset;
    var y = (db) ? document.body.scrollTop : pageYOffset;
    SetCookie('xy_'+aName, x + '_' + y, 0);
  }
}

function LoadAbsolutePagePosition(aName) {
  var db = (document.body) ? 1 : 0;
  var scroll = (window.scrollTo) ? 1 : 0;
  if (scroll) {
    var xy = GetCookie('xy_'+aName);
    if (xy) {
      var ar = xy.split('_');
      if (ar.length == 2) {
        scrollTo(parseInt(ar[0]), parseInt(ar[1]));
      }
    }
  }
}

function getObjectAbsoluteYPosition(aName) {
  var obj = FindObject(aName);
  if (obj) {
    return(getAbsolutePos(obj).y)
  }
}

function ScrollToObject(aName) {
  if (window.scrollTo) {
    window.scrollTo(0, getObjectAbsoluteYPosition(aName));
  }
}

function HexEncode(s) {
  var hi,
        lo,
        i = 0;
  var sret = "";
  for (i = 0; i < s.length; i++) {
    hi = s.charCodeAt(i) >> 4;
    lo = s.charCodeAt(i) & 0x0F;
    sret += hi.toString(16) + lo.toString(16);
  }
  return (sret);
}

function GetXmlHttp() {
  var xmlHttp = null;
  try {
    xmlHttp = new XMLHttpRequest();
    xmlHttp.overrideMimeType('text/xml; charset=iso-8859-1');
  } catch (e) {
    try {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
  return (xmlHttp);
}

function GetContentByUrl(aUrl) {
  var xmlhttp = null;
  xmlhttp = GetXmlHttp();
  if (xmlhttp != null) {
    xmlhttp.open("GET",aUrl,false);
    xmlhttp.send(null);
    if (xmlhttp.status==200) {
      return(xmlhttp.responseText);
    } else {
      alert("HTTP ERROR " + xmlhttp.status + ": accessing [" + aUrl + "]");
      return("GetContentByUrl ERROR!");
    }
  }
}

function ActionManager(aUrl, aReloadUrl) {
  var s = GetContentByUrl(aUrl);
  if (s == "OK") {
    if (aReloadUrl) {
      window.location.href = aReloadUrl;
    } else {
      window.location.reload();
    }
  } else {
    alert(s);
  }
}

function InjectHtmlInRegion(aRegion, aHtml) {
  var obj = FindObject(aRegion);
  if (obj) {
    obj.innerHTML = aHtml;
    return(true);
  } else {
    return(false);
  }
}

function InjectHtmlInRegionByUrl(aUrl, aRegion) {
  var obj = FindObject(aRegion);
  if (obj) {
    var s = GetContentByUrl(aUrl);
    if ( s != "GetContentByUrl ERROR!") {
      obj.innerHTML = s;
      return(true);
    } else {
      return(false);
    }
  } else {
    return(false);
  }
}

function InjectHtmlInEmptyRegionByUrl(aRegion, aUrl) {
  var obj = FindObject(aRegion);
  if (obj) {
    if (obj.innerHTML == "") {
      var s = GetContentByUrl(aUrl);
      if (s != "GetContentByUrl ERROR!") {
        obj.innerHTML = s;
        return (true);
      }
    }
  }
  return (false);
}

function SetComboValue(aName, aValue) {
  var retval = false
  var obj = FindObject(aName);
  if (obj) {
    if(obj.options) {
      for(var i=0; i<obj.options.length; i++) {
        if (obj.options[i].value == aValue) {
          retval = (!obj.options[i].selected);
          obj.options[i].selected = true;
        }
      }
    }
  }
  return (retval);
}

function SetFieldValue(aName, aValue) {
  var retval = false
  var obj = FindObject(aName);
  if (obj) {
    retval = (obj.value != aValue);
    obj.value = aValue;
  }
  return (retval);
}

function CheckCheckbox(aName, aChecked) {
  var obj = FindObject(aName);
  if (obj) {
    obj.checked = aChecked;
  }
}

function GetFieldValue(aName) {
  var obj = FindObject(aName);
  if (obj) {
    return(obj.value);
  } else {
    alert("Missing object " + aName);
  }
}

function SetFieldStyleBackground(aName, aValue) {
  var obj = FindObject(aName);
  if (obj) {
    obj.style.background='url('+aValue+')';
  }
}

function ccwsPopupWindow (url, win, width, height, options) {
  var leftPos = (screen.availWidth - width) / 2;
  var topPos = (screen.availHeight - height) / 2;
  options += 'width=' + width + ',height=' + height + ',left=' + leftPos + ',top=' + topPos;
  options += 'width=' + width + ',height=' + height;
  return window.open(url, win, options);
}

function UploadFileDialog(aName) {
  ccwsPopupWindow('/system/dialogs/uploaddialog.aspx?pid='+aName, 'UploadFile', 400, 130, '');
}

function UploadImageDialog(aName) {
  ccwsPopupWindow('/system/dialogs/uploadimage.aspx?pid='+aName, 'UploadImage', 400, 135, '');
}

function UploadPrivateDialog(aName) {
  ccwsPopupWindow('/system/dialogs/UploadPrivateResource.aspx?pid=' + aName, 'UploadPrivateResource', 400, 335, '');
}

function ccwsShowMessage(aMessage) {
  alert(aMessage);
}

function ccwsShowWarningMessage(aMessage) {
  alert(aMessage);
}

function ccwsShowErrorMessage(aMessage) {
  alert(aMessage);
}

function ccwsAjaxCombo(aComboName, aUrl, aDefault) {
  var i,
      comboobj,
      strRes,
      arrValori,
      opt = null,
  comboobj = FindObject(aComboName);
  if (comboobj) {
    if (comboobj.options) {
      comboobj.options.length = 0;
      strRes = GetContentByUrl(aUrl);
      arrValori = strRes.split("|");
      if (arrValori.length > 1) {
        for (i = 0; i < arrValori.length; i += 2) {
          opt = new Option();
          opt.value = arrValori[i];
          opt.text = arrValori[i + 1];
          if ((opt.value == aDefault) && (aDefault != "")) {
            opt.selected = true;
          }
          comboobj.options[comboobj.options.length] = opt;
        }
      }
    }
  }
}

function TableSortNamager(aTableName, aFieldName, aReloadUrl) {
  var s = GetContentByUrl("/system/ajax/actionmanager.aspx?cmd=tablesort&tablename=" + aTableName + "&fieldname=" + aFieldName);
  if (s == "OK") {
    window.location.replace(aReloadUrl);
  } else {
    alert(s);
  }
}
