var Cache = new Object();
function gebic(id)
{
  return (Cache[id]) ? Cache[id] : Cache[id] = document.getElementById(id);
}
function gebi(id) {
  return gebic(id);
  //return document.getElementById(id);
}

// Определение размеров видимой области окна браузера
function screenSize() {
  var w, h;
  w = (window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth));
  h = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
  return {w:w, h:h};
}

// Опрелеляем top - left координаты блока obj
function absPosition(obj) {
  this.x = 0;
  this.y = 0;
    while(obj) {
    this.x += obj.offsetLeft;
    this.y += obj.offsetTop;
    obj = obj.offsetParent;
  }
  return {x:this.x,y:this.y};
}

// Определение координат мыши
function defPosition(event) {
      var x = y = 0;
      if (document.attachEvent != null) { // Internet Explorer & Opera
            x = window.event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
            y = window.event.clientY + (document.documentElement.scrollTop  ? document.documentElement.scrollTop  : document.body.scrollTop);
      }
      if (!document.attachEvent && document.addEventListener) { // Gecko
            x = event.clientX + window.scrollX;
            y = event.clientY + window.scrollY;
      }
      return {x:x, y:y};
}

// Предотвращение всплывания событий
function cancelBubbling(evt) {
      evt = evt || window.event;
      evt.cancelBubble = true;
}

// Добавление событий
function addHandler(object, event, handler, useCapture) {
      if (object.addEventListener) {
            object.addEventListener(event, handler, useCapture ? useCapture : false);
      } else if (object.attachEvent) {
            object.attachEvent('on' + event, handler);
      } else alert("Add handler is not supported");
}

// Удаление событий
function removeHandler(object, event, handler) {
  if (object.removeEventListener) {
    object.removeEventListener(event, handler, false);
  } else if (object.detachEvent) {
    object.detachEvent('on' + event, handler);
  } else alert("Remove Handler is not supported");
}

// Аналог php-шного implode
function implode(delim, arr) {
  var out = "";
  for (var i = 0; i < arr.length; i++) {
    out += arr[i] + (i != (arr.length - 1) ? delim : "");
  }
  return out;
}

// Установка cookie
function setCookie(name, value) {
  var valueEscaped = escape(value);
  var expiresDate = new Date(); // get current time
  expiresDate.setTime(expiresDate.getTime() + 365 * 24 * 60 * 60 * 1000); // add 1 year lifetime
  var expires = expiresDate.toGMTString(); // get formatted date string
  var newCookie = name + "=" + valueEscaped + "; path=/; expires=" + expires;
  if (valueEscaped.length <= 4000) document.cookie = newCookie + ";";
}

// Получение cookie
function getCookie(name) {
  var prefix = name + "=";
  var cookieStartIndex = document.cookie.indexOf(prefix);
  if (cookieStartIndex == -1) return null;
  var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
  if (cookieEndIndex == -1) cookieEndIndex = document.cookie.length;
  return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
}

// Прелоад картинки
function newImage(path) {
  var image = new Image();
  image.src = path;
  return image;
}

// Определение высоты скролла
function defScroll() {
  var x = y = 0;
  x = (window.scrollX) ? window.scrollX : (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
  y = (window.scrollY) ? window.scrollY : (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
  return {x:x, y:y};
}
// ========= Контекстные подсказки ==========
// Массив с подсказками
var helpData = [
  "Тестовая подсказка", //0
  "Тестовая подсказка 1", //
  "Нажмите кнопку <Обзор...> и выберите в появившемся окне файл с фото, который вы хотите загрузить. Файл должен иметь формат JPEG (JPG)",
  "Краткое название фото.",
  "Краткое опишите фото: что на нем изображено, где и когда вы сделали этот снимок и т.д. Введите любую информацию, которую вы сочтете интересной и полезной для тех, кто увидит ваше фото.",
  "Выберите категорию, наиболее подходящую сюжету вашего фото.",
  "В SMS-лидеры попадают фото, за размещение которых пользователи заплатили с помощью SMS-сообщения на короткий номер. Самые старые фото вытесняются самыми новыми.",
  "Сюда попадают фото, загруженные пользователями в течение последних нескольких минут.", //7
];
// Показать контекстную подсказку
function contextHelp(evt, img, id, right, top) {
  cancelBubbling(evt);
  
  //убираем подсказку к рейтингу (цветы и медали)
  //awardHelpHide();

  if (img.childNodes)
  {
    var arrChildIMG = img.childNodes;
    arrChildIMG = arrChildIMG.length ? arrChildIMG : [arrChildIMG];
    arrChildIMG_length = arrChildIMG.length;
    var varIMG;
    for (var i = 0; i < arrChildIMG_length; i++)
      {if (arrChildIMG[i].nodeName == 'IMG') {varIMG = arrChildIMG[i];}}
  }
  img = varIMG;

  var rightFlag = typeof right == 'undefined' || !right ? false : true;
  var topFlag = typeof top == 'undefined' || !top ? false : true;
  top = parseInt(top);
  top = top == 1 ? -50 : top;
  if (screenSize().w - absPosition(img).x < 300) rightFlag = true;//

  var targetDiv;
  if (!gebi("helpDiv")){
    var div = document.createElement("div");
    div.id = "helpDiv";
    div.className = "help_div";
    div.style.top = "0px";
    div.style.left = "0px";
    div.style.display = "none";
    div.style.zIndex = "100000000";
    document.body.appendChild(div);
  }
  targetDiv = gebi("helpDiv");
  targetDiv.innerHTML="<a onclick=\"contextHelpHide();return false;\" href=\"\"><img src=/images/ico_close.gif height=7 width=7 border=0 align=right alt=\"Закрыть\"><\/a><br /><div>" + helpData[id] + "<\/div>";
  var xRemainder = (rightFlag) ? -238 - img.width + 2 : 0;
  var yRemainder = (topFlag) ? top : 0;
  targetDiv.style.top = (absPosition(img).y + yRemainder) + img.height + 2 + "px";
  targetDiv.style.left = (absPosition(img).x + xRemainder) + "px";
  targetDiv.onclick = cancelBubbling;
  targetDiv.style.display = "block";
  return false;
}
// Скрыть контекстную подсказку
function contextHelpHide() {
  if (gebi("helpDiv")) gebi("helpDiv").style.display = "none";
}
addHandler(document, 'click', contextHelpHide);
// ========= /Контекстные подсказки ==========

function AddCommText(text, inpt_name) {
  var output = gebi(inpt_name);
  output.value = output.value + ' ' +text;
}

function AddSmile(id,inpt_name) { 
  var s="#:"+id+":# ";
  AddCommText(s, inpt_name)
}
function AddNick(id, inpt_name) {
  var s="#%2"+id+"%# ";
  AddCommText(s, inpt_name)
}

var cropflag=false;
var currentside=null;
var x0=0;
var y0=0;
var w=0;
var h=0;

function MouseDown(side)
{
 currentside=side;
 ev=window.event;
 x0=ev.x;
 y0=ev.y;
}

function MouseUp()
{
 currentside=null;
}

function MouseMove()
{
 ev=window.event;
 if((currentside==null)||(ev.button!=1)) return;
 dx=ev.x-x0;
 dy=ev.y-y0;
 sleft=gebi('left').style;
 sright=gebi('right').style;
 stop=gebi('top').style;
 sbottom=gebi('bottom').style;
 w=(gebi('mainpic').width+16-sright.pixelWidth-sleft.pixelWidth);
 h=(gebi('mainpic').height+16-sbottom.pixelHeight-stop.pixelHeight);
 style=document.all[currentside].style;
 switch(currentside)
 {
  case "area":
   if(w<gebi('mainpic').width)
   {
    if(sleft.pixelWidth+dx<8) { sleft.pixelWidth=8; sright.pixelWidth=gebi('mainpic').width-w+8; }
    else
    if(sright.pixelWidth-dx<8) { sright.pixelWidth=8; sleft.pixelWidth=gebi('mainpic').width-w+8; }
    else
    { sleft.pixelWidth+=dx; sright.pixelWidth-=dx; x0=ev.x; }
   }
   if(h<gebi('mainpic').height)
   {
    if(stop.pixelHeight+dy<8) { stop.pixelHeight=8; sbottom.pixelHeight=gebi('mainpic').height-h+8; }
    else
    if(sbottom.pixelHeight-dy<8) { sbottom.pixelHeight=8; stop.pixelHeight=gebi('mainpic').height-h+8; }
    else
    { stop.pixelHeight+=dy; sbottom.pixelHeight-=dy; y0=ev.y; }
   }
   break;
  case "top":
   if(style.pixelHeight+dy>gebi('mainpic').height) style.pixelHeight=gebi('mainpic').height;
   else
   if(style.pixelHeight+dy>gebi('mainpic').height-sbottom.pixelHeight+8) style.pixelHeight=gebi('mainpic').height-sbottom.pixelHeight+8;
   else
   {
    if(style.pixelHeight>=8) style.pixelHeight+=dy;
    if(style.pixelHeight<8) style.pixelHeight=8;
    else {x0=ev.x; y0=ev.y;}
   }
   break;
  case "bottom":
   if(style.pixelHeight-dy>gebi('mainpic').height) style.pixelHeight=gebi('mainpic').height;
   else
   if(style.pixelHeight-dy>gebi('mainpic').height-stop.pixelHeight+8) style.pixelHeight=gebi('mainpic').height-stop.pixelHeight+8;
   else
   {
    if(style.pixelHeight>=8) style.pixelHeight-=dy;
    if(style.pixelHeight<8) style.pixelHeight=8;
    else {x0=ev.x; y0=ev.y;}
   }
   break;
  case "left":
   if(style.pixelWidth>=8) style.pixelWidth+=dx;
   if(style.pixelWidth<8) style.pixelWidth=8;
   else {x0=ev.x; y0=ev.y;}
   break;
  case "right":
   if(style.pixelWidth>=8) style.pixelWidth-=dx;
   if(style.pixelWidth<8) style.pixelWidth=8;
   else {x0=ev.x; y0=ev.y;}
   break;
 }
}

function setcrop(left,top,right,bottom)
{
 if(!cropflag) flipcrop();
 gebi('left').style.pixelWidth=left+8;
 gebi('right').style.pixelWidth=right+8;
 gebi('top').style.pixelHeight=top+8;
 gebi('bottom').style.pixelHeight=bottom+8;
 window.scrollTo(0,0);
}

function addcrop()
{
 x1=gebi('left').style.pixelWidth-8; if(x1<0) x1=0;
 y1=gebi('top').style.pixelHeight-8; if(y1<0) y1=0;
 x2=gebi('right').style.pixelWidth-8; if(x2<0) x2=0;
 y2=gebi('bottom').style.pixelHeight-8; if(y2<0) y2=0;
 s='[CROP]'+x1+','+y1+','+x2+','+y2+'[/CROP]';
 AddCommText(s, 'comtext');
 gebi('comtext').focus();
}

function flipcrop()
{
 gebi('crop').width=gebi('mainpic').width+16;
 gebi('crop').height=gebi('mainpic').height+16;
 cropflag=!cropflag;
 if(cropflag)
 {
  gebi('cropper').style.display="";
 }
 else
 {
  gebi('cropper').style.display="none";
 }
}

var exifflag = false;
function flipexif()
{
  exifflag = !exifflag;
  if (exifflag) {
    gebi('exifinfo').style.display = "";
  } else {
    gebi('exifinfo').style.display = "none";
  }
}
var moderflag = false;
function flipreport()
{
  moderflag = !moderflag;
  if (moderflag) {
    gebi('moderator_report').style.display = "";
    gebi('reporttext').focus();
  } else {
    gebi('moderator_report').style.display = "none";
  }
}
var emailflag = false;
function flipemail()
{
  emailflag = !emailflag;
  if (emailflag) {
    gebi('email_form').style.display = "";
  } else {
    gebi('email_form').style.display = "none";
  }
}
var coduerlflag = false;
function flipcoduerl()
{
  coduerlflag = !coduerlflag;
  if (coduerlflag) {
    gebi('coduerl_div').style.display = "";
  } else {
    gebi('coduerl_div').style.display = "none";
  }
}
