var submenuMask = null;
var submenuMaskCenter = null;

function SubmenuMask() {
  if (submenuMask == null) {
    submenuMask = document.getElementById('menu_mask');
  }
  return submenuMask;
}

function SubmenuMaskCenter() {
  if (submenuMaskCenter == null) {
    submenuMaskCenter = document.getElementById('mask-center');
  }
  return submenuMaskCenter;
}

var opacity = null;
var interval = null;

function subMenuActivated(submenu) {
  var mask = SubmenuMask();
  var centerMask = SubmenuMaskCenter();
  if (submenu.parentElement) {
    mask.style.left = submenu.offsetLeft - 10 + submenu.parentElement.offsetLeft + "px";
  } else {
    mask.style.left = submenu.offsetLeft - 10 + submenu.parentNode.offsetLeft + "px";
  }
  var IE = '\v'=='v';
  var maskWidth = submenu.clientWidth - 16 * 2 + 4;
  mask.style.width = maskWidth + 29 * 2 + "px";
  centerMask.style.width = submenu.clientWidth - 28 + "px";
  if (!IE) {
    opacity = 0;
    setOpacity(mask, 0);
    if (interval != null) {
      clearInterval(interval);
    }
    interval = setInterval('SetOpacity()', 150);
  }
  mask.style.display = 'block';
}

function SetOpacity() {
  opacity++;
  var mask = SubmenuMask();
  setOpacity(mask, opacity);
  if (opacity == 100) {
    clearInterval(interval);
  }
}

function setOpacity(obj, value) {
   obj.style.opacity = value / 10;
   obj.style.filter = 'alpha(opacity=' + value * 10 + ')';
}


function subMenuDisactivated() {
  var mask = SubmenuMask();
  mask.style.display = 'none';
}

function resizeBackground() {
  if (container.clientHeight > window.screen.availHeight) {
    bg.style.height = container.clientHeight + "px";
  } else {
    bg.style.height = '100%';
  }
  resizeBody();
}

/* AJAX Downloader */

var holderId = false;
function doLoad(url, holder) {
  req = false;
  try {
    req = new ActiveXObject('Msxml2.XMLHTTP');
  } catch (e) {
    try {
      req = new ActiveXObject('Microsoft.XMLHTTP');
    } catch (e) {
      if (window.XMLHttpRequest) {
         req = new XMLHttpRequest();
      }
    }
  }
  if (req) {
    holderId = holder;
    req.onreadystatechange = readystate;
    req.open("GET", url, true);
    req.send(null);
  }
}

function readystate() {
  if (req.readyState == 4) {
    if (req.status == 200) {
      if (holderId) {
        var holder = document.getElementById(holderId);
        if (document.all) {
          holder.innerHTML = req.responseText;
        } else {
          holder.innerHTML = req.responseText;
        }
      }
    } else {
      alert("Произошла ошибка "+ req.status+":\n" + req.statusText);
    }
  }
}

/* Utils */

function removeClassName(classString, className) {
  return classString.replace(className, "");
}

/* Controls Validators */

function checkLengthValue(control) {
  var holder = document.getElementById('maxlength_' + control.name);
  if (holder) {
    var length = control.value.length;
    if (document.all) {
      holder.innerText = length;
    } else {
      holder.textContent = length;
    }
  } else {
    throw new Error('Control length holder not found');
  }
}

/*  Advice */

var expandedID = null;
var questionID = null;
function adviceQuestionExpand(span, language) {
  if (expandedID != null) {
    var expandedBlock = document.getElementById(expandedID);
    expandedBlock.className = 'novisible';
    var expandedButton = document.getElementById('b_' + questionID);
    expandedButton.className = 'visible';
  }
  var id = span.id;
  var holder = 'p_' + id;
  var block = document.getElementById(holder);
  block.className = 'visible';
  var expandedButton = document.getElementById('b_' + id);
  expandedButton.className = 'novisible';
  expandedID = holder;
  questionID = id;
  if (block.innerHTML == '') {
    doLoad('php/get_advice_question.php?id=' + id + '&language=' + language, holder);
  }
}

/* Bubbles */

var imagesSrc = ['b1.png', 'b2.png', 'b3.png', 'b4.png', 'b5.png'];
var maxSizeImage = 80;
var headerZone;
var leftZone;
var rightZone;

function StartBubbles() {
  for(var i = 1; i <=10; i++) {
    CreateBubble(3);
  }
  setInterval('headerZone.moveBubbles();leftZone.moveBubbles();rightZone.moveBubbles();', 50);
}

function Object(px, py, pwidth, pheight) {
  return {
    x : px,
    y : py,
    width : pwidth,
    height : pheight
  }
}

function Zone() {
  var me = Object();
  var bubbles = Array();
  
  function checkTopBorder(bubble) {
    alert(1);
  }
  
  me.IsNotInSideBorders = function(bubble) {
    var w = bubble.imageWidth();
    return (bubble.x <= me.x || bubble.x + w + 5 >= me.x + me.width);
  }
  me.updateCoordinates = function(px, py, pwidth, pheight) {
    me.x = px;
    me.y = py;
    me.width = pwidth;
    me.height = pheight;
    var i = 0;
    var bubble;
    while (i < bubbles.length) {
      bubble = bubbles[i];
      if (me.IsNotInSideBorders(bubble)) {
        bubble.x = me.x + 1;
      }
      i++;
    }
  }
  me.creareBubble = function() {
    var sx = GenerateRandom(me.width) + me.x;
    while (sx + maxSizeImage > me.x + me.width) {
      sx = sx - maxSizeImage;
    }
    var sy = GenerateRandom(me.height) + me.y;
    while (sy + maxSizeImage > me.y + me.height) {
      sy = sy - maxSizeImage;
    }
    var b = BubbleLinear(sx, sy);
    me.addBubble(b);
  }
  me.moveBubbles = function() {
    var i = 0;
    while (i < bubbles.length) {
      bubbles[i].move();
      if (!checkTopBorder(bubbles[i], i)) {
        i++;
      }
    }
  }
  me.set_checkTopBorder = function(method) {
    checkTopBorder = method;
  }
  me.addBubble = function(bubble) {
    bubbles.push(bubble);
    bubble.zone = me;
  }
  me.removeBubble = function(index) {
    bubbles.splice(index, 1);
  }
  var visibleDiv = null;
  me.showZone = function() {
    if (visibleDiv == null) {
      visibleDiv = document.createElement("DIV");
      document.body.appendChild(visibleDiv);
      visibleDiv.style.position = 'absolute';
      visibleDiv.style.border = '1px solid red';
    }
    visibleDiv.style.left = me.x + 'px';
    visibleDiv.style.top = me.y + 'px';
    visibleDiv.style.width = me.width + 'px';
    visibleDiv.style.height = me.height + 'px';
  }
  me.constructor = arguments.callee;
  return me;
}

function SideZone() {
  var me = Zone();
  
  function checkTopBorder(bubble, index) {
    if (bubble.y <= me.y) {
      me.removeBubble(index);
      headerZone.addBubble(bubble);
      return true;
    } else {
      return false;
    }
  }
  
  me.set_checkTopBorder(checkTopBorder);
  me.constructor = arguments.callee;
  return me;
}

function HeaderZone() {
  var me = Zone();

  function checkTopBorder(bubble, index) {
    var h = bubble.imageHeight();
    if (bubble.y + h <= me.y) {
      bubble.destructor();
      me.removeBubble(index);
      CreateBubble(2);
      return true;
    } else {
      return false;
    }
  }
  me.set_checkTopBorder(checkTopBorder);
  me.constructor = arguments.callee;
  return me;
}

var vowel = ['a', 'e', 'i', 'o', 'u', 'y'];
var consonant = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z'];

function BubbleLinear(x, y) {
  var me = Object();
  me.x = x;
  me.y = y;
  me.name = GenerateLetter(consonant) + GenerateLetter(vowel) + GenerateLetter(consonant) + GenerateLetter(vowel);
  var image = new Image();
  var div = document.createElement('div');
  div.style.position = 'absolute';
  div.style.left = me.x + 'px';
  div.style.top = me.y + 'px';
  div.zIndex = 2000;
  document.body.appendChild(div);
  var bubbleNumber = GenerateRandom(imagesSrc.length);
  image.src = 'images/' + imagesSrc[bubbleNumber - 1];
  div.appendChild(image);
  function GenerateLetter(array) {
    var i;
    do {
      i = GenerateRandom(array.length) - 1;
    } while (i < 0 || i >= array.length);
    return array[i];
  }
  
  var dx = 0;
  while (dx == 0) { dx = GenerateRandom(10) - 5; }
  var dy = 0;
  while (dy == 0) { dy = - GenerateRandom(3); }
  
  me.move = function() {
    me.x = me.x + dx;
    me.y = me.y + dy;
    div.style.left = me.x + 'px';
    div.style.top = me.y + 'px';
    if (me.zone.IsNotInSideBorders(me)) {
      dx = -dx;
    }
  }
  me.zone = null;
  me.imageWidth = function() {
    return image.offsetWidth;
  }
  me.imageHeight = function() {
    return image.offsetHeight;
  }
  me.removeImage = function() {
    document.body.removeChild(image);
  }
  me.constructor = arguments.callee;
  me.destructor = function() {
    div.parentNode.removeChild(div);
  }
  return me;
}

function CreateZones() {
  headerZone = HeaderZone(); leftZone = SideZone(); rightZone = SideZone();
  UpdateZonesCoordinates();
}

function GenerateRandom(max) {
  return Math.floor(Math.random() * max) + 1;
}

function CreateBubble(zones) {
  var zoneNum = GenerateRandom(zones);
  var zone;
  switch(zoneNum) {
    case 1: zone = rightZone; break;
    case 2: zone = leftZone; break;
    case 3: zone = headerZone; break;
    default: throw ('Unknown zone number: ' + zoneNum);
  }
  zone.creareBubble();
}

function resizeBody() {
  UpdateZonesCoordinates();
}

function getClientWidth() {
  return document.compatMode == 'CSS1Compat' && !window.opera? document.documentElement.clientWidth : document.body.clientWidth;
}
function UpdateZonesCoordinates() {
  var divHeader = document.getElementById('header');
  var divCenter = document.getElementById('content');
  leftZone.updateCoordinates(divHeader.clientLeft, divHeader.clientHeight, divCenter.offsetLeft + 35, divCenter.offsetHeight - 50);
  //leftZone.showZone();
  //alert(leftZone.x + ' ' + leftZone.y + ' ' + leftZone.width + ' ' + leftZone.height);
  rightZone.updateCoordinates((leftZone.width + divCenter.clientWidth) - 70, divHeader.clientHeight, getClientWidth() - (leftZone.width + divCenter.clientWidth) + 65, leftZone.height);
  //rightZone.showZone();
  //alert(rightZone.x + ' ' + rightZone.y + ' ' + rightZone.width + ' ' + rightZone.height);
  headerZone.updateCoordinates(divHeader.clientLeft, divHeader.clientTop, rightZone.x + rightZone.width, divHeader.clientHeight);
  //alert(headerZone.x + ' ' + headerZone.y + ' ' + headerZone.width + ' ' + headerZone.height);
  //headerZone.showZone();
}
