// ------------------------
// 2004-2006 White Gull CMS
// ------------------------

// -----
function openImage(imgName, imgTitle, wt, ht, top, left) {
  wscroll = "no";

  if (imgTitle == "::") {
    ht_addon = 30;
  }
  else {  // надо расчитывать от длины imgTitle и wt
    ht_addon = 80;
  }

  wwt = wt + 40;
  wht = ht + ht_addon;

  if (wht > screen.height - 60)  {
    wht = screen.height - 60;
    wscroll = "yes"
  }

  if (wwt > screen.width) {
    wwt=screen.width;
    wscroll = "yes"
  }

//  if (!top) top = (screen.height) ? Math.floor((screen.height - ht) / 2) - 30 : 0;
//  if (!left) left = (screen.width) ? Math.floor((screen.width - wt) / 2) - 30 : 0;

  if (!top) top = Math.floor((screen.height - wht) / 2) - 40
  if (!left) left = Math.floor((screen.width - wwt) / 2)
  if (top < 0) top = 0;
  if (left < 0) left = 0;

  image=window.open("", "fullImage_" + wt, "width=" + wwt + ",height=" + wht + ",top=" + top + ",left=" + left + ",scrollbars=" + wscroll + ",toolbar=no,location=no,status=no,menubar=no,resizable=yes");
  image.focus();

  // интересная штука: clientHeight не равен размеру, заданному в window.open, а вот clientWidth -- равен
//  client_mult = image.document.body.clientHeight / ht;
//  wt = Math.floor(image.document.body.clientWidth * client_mult);
//  ht = image.document.body.clientHeight;

  image.document.open();
  image.document.write("<html>\n<head>\n<title>" + imgTitle + "</title>\n");
  image.document.write("<meta name=\"robots\" content=\"noindex,nofollow\">\n");
  image.document.write("<body>\n\n");
  image.document.write("<center><a href=\"javascript: window.close();\"><img src=\"" + imgName + "\" width=" + wt + " height=" + ht + " border=0 alt=\"щелкните, чтобы закрыть окно\"></a></center>\n\n");
  if (imgTitle != "::") image.document.write("<p style=\"font-weight: bold; text-align: center;\">" + imgTitle + "</p>\n");
  image.document.write("\n</body></html>");
  image.document.close();
}

// -----
function openWindow(url, nm, wt, ht, top, left) {
  if (!wt) wt = 600;
  if (!ht) ht = 600;

  if (!top) top = screen.height ? (screen.height - ht)/2 - 30 : 0;
  if (!left) left = screen.width ? (screen.width - wt)/2 - 30 : 0;

  myWin = window.open(url, nm, "width=" + wt + ",height=" + ht + ",top=" + top + ",left=" + left + ",toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes");
  myWin.window.focus();

/* Эта хрень банально не работает
   if (document.body.scrollHeight > document.body.clientHeight)
   myWin.resizeTo(document.body.clientHeight+document.body.scrollLeft, document.body.clientWidth);

  if (document.body.scrollWidth > document.body.clientWidth)
    myWin.resizeTo(document.body.clientHeight, document.body.scrollWidth);*/
}

// -----
function formSubmit(formName) {
  eval('document.' + formName + '.submit()');
}

function frameResize() {
  width = self.document.body.scrollWidth;
  height = self.document.body.scrollHeight;
  self.resizeTo(width, height + 5);
}

// Сохранить локальный путь добавляемого документа
function saveLastPath(formname) {
  if (formname.last_path.value=formname.d_body.value) return true;
  return false;
}

// Проверить на заполненность поля формы
function checkForm(frm_field, msg) {
  if (frm_field.value == "") {
    alert(msg);
    return false;
  }

  return true;
}

function setValue(elementId, value) {
  document.getElementById(elementId).value = value;
}

function setTrValue(elementId, state) {
  if (state > 1) {
    state = (eval('document.' + elementId + '.style.display') == "none") ? ("block") : ("none");
  }
  else
    state = (state == 1) ? "block" : "none";

  eval('document.' + elementId + '.style.display = ' + state);
}

// защита от спам-роботов
function code_email(login, server, domain) {
  eml = login + "@" + server + "." + domain;
  return eml;
}

function code_mailto(login, server, domain, subj) {
  eml = "mailto:" + code_email(login, server, domain);
  if (subj) eml += subj;

  window.location.href = eml;
}

// -----
// state - показать(1) / спрятать (0) / переключить (2)
function setDIVDisplay(divId, state, display_on) {
  state1 = false; state2 = false;
  if (!display_on) display_on = 'block';

  display = document.getElementById(divId).style.display;
  vis = document.getElementById(divId).style.visibility;

  if(state === false) state = 2;

  if (state == 2) {
    if (bw.ie && display_on == 'table-row')  // IE не знает этого значения
      display_on = 'block';

    if (display)
      state1 = (display == 'none') ? display_on : 'none';
    else
      state1 = 'none';

    if (vis)
      state2 = (vis == 'hidden') ? 'visible' : 'hidden';
  }
  else {
    state1 = (state == 1) ? display_on : 'none';
    state2 = (state == 1) ? 'visible' : 'hidden';
  }

  document.getElementById(divId).style.display = state1;
  if (vis) document.getElementById(divId).style.visibility = state2;
}

// ------
// parent - элемент, который содержит слои. можно использовать document для всех слоев
function setAllDIVDisplay(parent, state) {
  var divcount = parent.getElementsByTagName('div');

  for (var i=0; i < divcount.length; i++) {
    divcount[i].style.display = state ? 'block' : 'none';
    divcount[i].style.visibility = state ? 'visible' : 'hidden';
 }
}

// отменяет вызов функции родительского элемента
function cancelBubble() {
  if (typeof(event.stopPropagation) == 'function') event.stopPropagation();  // Mozilla
  if (typeof(event.cancelBubble) == 'boolean') event.cancelBubble = true;  // IE & Opera
}

// ----------------------------------------------------
// проверка расширения на соответствие какому-либо типу
function checkExt(validExt, str) {
  eval("ext_pattern = /.+\.(" + validExt + ")/;");

  if (ext_pattern.test(str)) {
    return true;
  }
  else {
    alert("Недопустимый формат файла");
  }

  return false;
}

function stripPath(flname) {
  slash_idx = flname.lastIndexOf("\\");
  ret = flname.slice(slash_idx + 1);

  return ret;
}

// -----------------------------
// -- Возвращает версию браузера
bw = new bwl();
function bwl() {
  this.ver = navigator.appVersion;
  this.agent = navigator.userAgent.toLowerCase();
  this.dom = document.getElementById ? 1 : 0;
  this.ns4 = (!this.dom && document.layers) ? 1 : 0;
  this.op = window.opera;
  this.moz = (this.agent.indexOf("gecko") > -1 || window.sidebar);
  this.ie = this.agent.indexOf("msie") > -1 && !this.op;

  if(this.op) {
    this.op5 = (this.agent.indexOf("opera 5") > -1 || this.agent.indexOf("opera/5") > -1);
    this.op6 = (this.agent.indexOf("opera 6") > -1 || this.agent.indexOf("opera/6") > -1);
    this.op7 = this.dom && !this.op5 && !this.op6;
  }
  else if (this.moz)
    this.ns6 = 1;
  else if (this.ie) {
    this.ie4 = !this.dom && document.all;
    this.ie5 = (this.agent.indexOf("msie 5") > -1);
    this.ie55 = (this.ie5 && this.agent.indexOf("msie 5.5") > -1);
    this.ie6 = this.dom && !this.ie4 && !this.ie5 && ! this.ie55;
  }
  this.bw = (this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.op5 || this.op6 || this.op7);
  this.px = this.dom && !this.op5 ? "px" : "";

  return this;
}

// -----
// Скопировать текст в буфер
function text2clip(text2copy) {
  if (window.clipboardData) {  // работает только в IE
    prompt('Нажмите OK, чтобы скопировать нижеследующий код и затем вставьте его в свой документ', text2copy);
    window.clipboardData.setData("Text", text2copy);
  } else {
/*    var flashcopier = 'flashcopier';

    if(!document.getElementById(flashcopier)) {
      var divholder = document.createElement('div');
      divholder.id = flashcopier;
      document.body.appendChild(divholder);
    }
    document.getElementById(flashcopier).innerHTML = '';

    var divinfo = '<embed src="/js/text2clipboard.swf" flashvars="clipboard=' + escape(text2copy) + '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashcopier).innerHTML = divinfo;*/

    prompt('Скопируйте нижеследующий код с помощью Ctrl+C и затем вставьте его в свой документ', text2copy);
  }
}
