//Common variables
var _popupWidth = 650;
var _popupHeight = 450;
var _popupLeft = (screen.width - _popupWidth) / 2;
var _popupTop = (screen.height - _popupHeight) / 2;
var _popupSpecs = "width="+_popupWidth+", height="+_popupHeight+", left="+_popupLeft+", top="+_popupTop+", resizable=yes, menubar=no, status=no, titlebar=no, toolbar=no, scrollbars=yes";

String.prototype.trim = function() { return this.replace(/^\s+/, '').replace(/\s+$/, ''); };

function indexOf(list, obj){
  for(var i = 0; i < list.length; i++)
    if(list[i] == obj)
      return i;

  return -1;
}

function loading(){
  window.parent.startingTime = new Date();
}

// If Array.slice doesn't exist, add it.
if (Array.prototype.slice == null) {
  Array.prototype.slice = function(start,end){

   if (start<0) start=this.length+start; //'this' refers to the object to which the prototype is applied

   if (end==null) end=this.length;

   else if (end<0) end=this.length+end;

   var newArray=[];

   for (var ct=0,i=start;i<end;i++) newArray[ct++]=this[i];

   return newArray;
  }
}

// If Array.indexOf doesn't exist, add it.
if (Array.prototype.indexOf == null) {
  //Get index of element in array. -1 if it doesn't exist.
  Array.prototype.indexOf = function(val){
    for(i=0; i < this.length; i++){
      if(this[i] == val){
        return i;
      }
    }

    return -1;
  }
}



//Replaces all occurrences of "original" for "replacement".
String.prototype.core_replaceAll = function (original, replacement){
  var copy = this;
  var result = "";

  while((pos = copy.indexOf(original)) != -1){
    result += copy.substring(0, pos);
    result += replacement;
    copy = copy.substring(pos + original.length);
  }

  result += copy;

  return result;
}

//Swap two nodes in the document.
function core_swapNodes(node1, node2) {
  var nextSibling = node1.nextSibling;
  var parentNode = node1.parentNode;
  node2.parentNode.replaceChild(node1, node2);
  parentNode.insertBefore(node2, nextSibling);
}

//Get the absolute coordinates of the given object.
function core_absoluteCoordinates(obj) {
  var curleft = curtop = 0;
  if (obj.offsetParent) {
    curleft = obj.offsetLeft;
    curtop = obj.offsetTop;
    while (obj = obj.offsetParent) {
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
    }
  } else {
    curLeft += obj.x;
    curTop += obj.y;
  }
  return [curleft,curtop];
}

//Get the size of the given object.
function core_size(obj) {
  return [obj.clientWidth,obj.clientHeight];
}


// Dinamically include another javascript file.
function corinclude(script_filename) {
    document.write('<' + 'script');
    document.write(' language="javascript"');
    document.write(' type="text/javascript"');
    document.write(' src="' + script_filename + '">');
    document.write('</' + 'script' + '>');
}

//Disables the option of selecting text in the page.
function core_disableSelectText(){
  document.onselectstart = function() { return false; }
  document.onmousedown = function() { return false; };
  document.onclick = function() { return true; };
}

function submitForm(){
  f = document.forms[0];

  valid = true;
  if(validateForm){
    valid = validateForm(f);
  }

  if(valid){
    f.submit();
  }
}

/*
 * width:
 *   Width of the textarea.
 *
 * height:
 *   Height of the textarea.
 *
 * level_detail:
 *   Level of detail. 1 is the lowest and default, 3 is the highest.
 */
function loadDefaultTinyMCE(level_detail){
  level_detail = level_detail ? level_detail : 1;

  if(level_detail == 1){
    tinyMCE.init({
      plugins         : "advlink,xhtmlxtras",
      extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
      theme_advanced_buttons1 : "undo,redo,separator,cut,copy,paste,pastetext,separator,bold,italic,underline,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,separator,forecolor,backcolor",
      theme_advanced_buttons2 : "",
      theme_advanced_buttons3 : "",
      theme_advanced_path_location      : "bottom",
      theme_advanced_resize_horizontal  : false,
      theme_advanced_resizing           : true,
      theme_advanced_styles             : "Grey Border=grey_border", // the separator is ;
      theme_advanced_toolbar_align      : "left",
      theme_advanced_toolbar_location   : "top",

      button_tile_map : true,
      content_css     : "../../../css/tiny_mce.css",
      mode            : "textareas",
      theme           : "advanced",
      height          : "300",
      width           : "100%"
    });
  } else if(level_detail == 2) {
    tinyMCE.init({
      plugins : "advimage,advlink,imagemanager,paste,style",
      extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
      theme_advanced_buttons1 : "styleselect,separator,cut,copy,paste,pastetext,separator,undo,redo,separator,link,unlink,xhtmlxtras,separator,bold,italic,underline,separator,sub,sup,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,separator,forecolor,backcolor,image,separator,code",
      theme_advanced_buttons2 : "",
      theme_advanced_buttons3 : "",
      theme_advanced_path_location     : "bottom",
      theme_advanced_resize_horizontal : false,
      theme_advanced_resizing          : true,
      theme_advanced_styles            : "Grey Border=grey_border", // the separator is ;
      theme_advanced_toolbar_align     : "left",
      theme_advanced_toolbar_location  : "top",

      button_tile_map : true,
      content_css     : "../../../css/tiny_mce.css",
      mode            : "textareas",
      theme           : "advanced",
      height          : "100",
      width           : "100%"
    });
  } else if(level_detail == 3) {
    tinyMCE.init({
      plugins : "advimage,advlink,contextmenu,imagemanager,media,paste,searchreplace,style,table,xhtmlxtras",
      extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
      theme_advanced_buttons1 : "styleselect,fontselect,fontsizeselect,separator,cut,copy,paste,pastetext,separator,undo,redo,separator,outdent,indent,separator,link,unlink,separator,forecolor,backcolor,image,media,separator,code", //pasteword,
      theme_advanced_buttons2 : "bold,italic,underline,strikethrough,separator,sub,sup,separator,styleprops,separator,search,replace,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,separator,tablecontrols", //charmap,
      theme_advanced_buttons3 : "",
      theme_advanced_path_location      : "bottom",
      theme_advanced_resize_horizontal  : false,
      theme_advanced_resizing           : true,
      theme_advanced_styles             : "Grey Border=grey_border", // the separator is ;
      theme_advanced_toolbar_align      : "left",
      theme_advanced_toolbar_location   : "top",
      media_use_script                  : true,
      table_default_cellpadding : 2,
      table_default_cellspacing : 2,

      button_tile_map : true,
      content_css     : "../../../css/tiny_mce.css",
      mode            : "textareas",
      theme           : "advanced",
      height          : "300",
      width           : "100%"
    });
  } else {
    // Do nothing.
  }
}

/*
    Written by Jonathan Snook, http://www.snook.ca/jonathan
    Add-ons by Robert Nyman, http://www.robertnyman.com

    - To get all a elements in the document with a "info-links" class.
        getElementsByClassName(document, "a", "info-links");

    - To get all div elements within the element named "container", with a "col" and a "left" class.
        getElementsByClassName(document.getElementById("container"), "div", ["col", "left"]);
*/
function getElementsByClassName(oElm, strTagName, oClassNames){
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements   = [];
    var arrRegExpClassNames = [];
    if(typeof oClassNames == "object"){
        for(var i=0; i<oClassNames.length; i++){
            arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
        }
    }
    else{
        arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
    }
    var oElement;
    var bMatchesAll;
    for(var j=0; j<arrElements.length; j++){
        oElement = arrElements[j];
        bMatchesAll = true;
        for(var k=0; k<arrRegExpClassNames.length; k++){
            if(!arrRegExpClassNames[k].test(oElement.className)){
                bMatchesAll = false;
                break;
            }
        }
        if(bMatchesAll){
            arrReturnElements.push(oElement);
        }
    }
    return (arrReturnElements)
}

/*
 * Toogles display mode for block objects.
 * Parameter can be the object ID or the object itself.
 * If the object doesn't have the display property in the style parameter,
 * it's treated as if it were visible. That is, if the object is hidden
 * because of a property inside a CSS class, this function ignores that.
 */
function toogle(obj){
  if(typeof obj == "string"){
    obj = Coomsy.$(obj);
  }

  if(obj){
    if(obj.style.display == "none"){
      obj.style.display = "";
    } else {
      obj.style.display = "none";
    }
  }
}


////////////////////////////////////////////////////////////////////////////////
// Set of functions used to make a field have a hint inside that disappears   //
// when the user clicks on in, and re-appears when the field blurs            //
// and no text has been entered.                                              //
////////////////////////////////////////////////////////////////////////////////
function coomsy_field_hint(field, hint_text){
  field = Coomsy.$(field);
  field.coomsy_hint_text = hint_text;
  field.onblur = coomsy_field_hint_blur;
  field.onfocus = coomsy_field_hint_focus;
  field.onblur();
}

function coomsy_field_hint_focus(){
  if(this.value == this.coomsy_hint_text){
    this.value = "";
    this.style.color = "";
  }
}

function coomsy_field_hint_blur(){
  if(this.value == ""){
    this.style.color = "#999999";
    this.value = this.coomsy_hint_text;
  }
}


function core_popup(url, width, height){
  if(!width)  width  = screen.width;
  if(!height) height = screen.height;

  var _popupLeft = (screen.width  - width)  / 2;
  var _popupTop  = (screen.height - height) / 2;;

  var _popupSpecs = "width="+width+", height="+height+", left="+_popupLeft+", top="+_popupTop+", resizable=yes, menubar=no, status=no, titlebar=no, toolbar=no, scrollbars=yes";

  //tb_show(null, url+"&KeepThis=true&TB_iframe=true&&width="+width+"&height="+height, false);
  window.open(url, "_blank", _popupSpecs);
}

function showLoading(){
  if ( String($.blockUI) != "undefined" ) {
    $.blockUI.defaults.pageMessage = '<img src="'+_configVars.dirImg+'wait_indicators/wait_indicator.gif" alt="please wait" style="width; 16px; height: 16px; vertical-align: middle; margin-right: 5px;" />'+_lang.please_wait_while_loading;
    $.extend($.blockUI.defaults.overlayCSS, { backgroundColor: '#000000' });
    $.extend($.blockUI.defaults.pageMessageCSS, { color: '#000000', backgroundColor: '#FFFFFF', border: '2px solid #999999', padding: '2em', textAlign: 'center' });
    $.blockUI();
  }
}

function urlencode(str) {
  str = escape(str);
  str = str.replace('+', '%2B');
  str = str.replace('%20', '+');
  str = str.replace('*', '%2A');
  str = str.replace('/', '%2F');
  str = str.replace('@', '%40');
  return str;
}

function urldecode(str) {
  str = str.replace('+', ' ');
  str = unescape(str);
  return str;
}