$(document).ready(function() {
    $('form.ajax :input').change(function () {
        $(this.form).ajaxSubmit({
            dataType: 'json',
            success: function(json) { 
                $(this).find('.errors').empty();
                if (json == true)
                {
                }
                else
                {
                    for (var key in json)
                    {
                        var e = json[key];
                        var input = $(this).find(' :input[@name="'+key+'"]');
                        var errorsBlock = input.next(".errors");
                        if (errorsBlock.length <= 0)
                        {
                            input.after('<ul class="errors"></ul>');
                            errorsBlock = input.next(".errors");
                        }
                        for (var errkey in e)
                            errorsBlock.append("<li>" + e[errkey] + "</li>");
                    }
                }
            }.bind(this.form)
        });
    });
    
    $('.who-is-online').click(function () {
	    $('#online-users').remove();
	    var offset = $(this).offset();
	    $('<'+'div id="online-users"><'+'h2 style="text-align:center">Loading ...<'+'/h2><'+'/div>')
	        .css({
	            margin: '2px',
	            width: '20%',
	            height: 'auto',
	            border: '1px #cccccc solid',
	            position: 'absolute',
	            left: offset.left,
	            top: offset.top + $(this).height(),
	            backgroundColor: 'white'
	        })
	        .appendTo(document.body)
	        .show();
	    $.getJSON('/users/on-line/', {}, function (json) {
	        if (json.ok) {
	            $('#online-users')
	                .empty()
	                .append(
	                    $('<'+'img src="/design/del.gif" alt="X" title="Close" style="cursor:pointer;margin:5px;float:right" />')
	                        .hover(function() {
	                            $(this).attr('src', '/design/del.hover.gif')
	                        }, function() {
	                            $(this).attr('src', '/design/del.gif')
	                        })
	                        .click(function() { $(this).parent().remove() })
	                )
	                .append(
	                    '<'+'h2 style="margin:3px 5px">Сейчас на сайте:<'+'/h2>' +
	                    '<'+'div style="margin:5px 20px;">' + json.html + '<'+'/div>'
	                );
	        } else {
	            alert(json);
	        }
	    });
	    
	    return false;
	});
});

function deletePM(id, tr) {
    $.post('/account/delete-personal-message', {id: id}, function(json) {
        $(tr).empty();
        var table = tr.parentNode;
        table.removeChild(tr);
        $(table).find('tr > td').removeClass('odd').removeClass('even');
        $(table).find('tr:even > td').addClass('even');
        $(table).find('tr:odd > td').addClass('odd');
    }, 'json');
}

function showPMWindow(userId, anchorNode) {
    var offset = $(anchorNode).offset();
    var left = offset.left - 200;
    if (left < 10)
        left = 10;
        
    var form = $('<div class="pmwriter">' +
                    '<p>Отправить личное сообщение</p>' +
                    '<textarea cols="65" rows="5" name="contents"></textarea><br />' +
                    '<button class="send">отправить</button>' +
                    '&#xa0;&#xa0;' +
                    '<button class="cancel">отменить</button>' +
                 '</div>');
                 
    $(form).css({
        left: left,
        top: offset.top 
    });
    
    $('button.cancel', form).click(function() {
        $(this).parents('.pmwriter:first').remove();
    });
    
    $('button.send', form).click(function() {
        $(":input", form).attr("disabled", "disabled");
        var data = {user_id: userId, message: $('textarea', form).val()};
        $.post('/account/send-personal-message', data, function(json) {
            if (json.ok) {
                var closeBtn = $('<a href="#">закрыть</a>').click(function() {
                    $(form).remove();
                }); 
                $(form)
                    .empty()
                    .append(json.message)
                    .append(' ')
                    .append(closeBtn);
           } else {
                window.alert(json.message);
           }
	    }, 'json');
    });
    
    $(document.body).append(form);
    $('textarea', form).focus();
}

function ajaxPreviousPod(date)
{
    $('#pictureOfDayContainer').fadeOut(300, function() {
        $("#pictureOfDayContainer").css ({display:'block', visibility:'hidden'});
        $.get('/ajax/previouspod.php?date='+date, {}, function(html) {
            $("#pictureOfDayContainer").css ({display:'none', visibility:'visible'});
            $('#pictureOfDayContainer').html(html ? html : '').fadeIn(300);
        });
    });
}

function ajaxUpdatePicturePerspective(form)
{
  form.submitButton.value = 'сохраняем ... ';

  var picutreId = form.pictureId.value;
  var perspectiveId = form.perspectiveId.options[form.perspectiveId.selectedIndex].value;
  var action = form.elements['action'].value;

  var url = '/ajax/moder.php?action='+action+'&pictureId='+picutreId+'&perspectiveId='+perspectiveId;

  var ajax = getHTTPRequestObject();
  ajax.open('GET', url, true);
  ajax.onreadystatechange =
    function ()
    {
      if (ajax.readyState == 4)
      {
        if (ajax.status == 200)
        {
          this.submitButton.value = ajax.responseText;
        }
      }
    }.bind(form);
  ajax.send(null);
}

function addHandler(object, event, handler)
{
  if (typeof object.addEventListener != 'undefined')
    object.addEventListener(event, handler, false);
  else if (typeof object.attachEvent != 'undefined')
    object.attachEvent('on' + event, handler);
  else
    throw "Incompatible browser";
}


function showPictureBehaviour(a, id)
{
    var bounds = getBounds(a);
    var tableJQ = $('#picture'+id+'behaviour');
    var table = tableJQ[0];
    if (table.timer)
        clearTimeout(table.timer);
    if (table.pictureId != id)
        tableJQ.fadeOut(300);
    table.pictureId = id;
    table.over = true;
    if (table.style.display == '')
        return;
    tableJQ.css({left:bounds.left + 'px', top: (bounds.top+bounds.height-2) + 'px'});
    tableJQ.fadeIn(300);
}

function doHidePictureBehaviour(id)
{
  var tableJQ = $('#picture'+id+'behaviour');
  var table = tableJQ[0];
  if (!table.over)
    tableJQ.fadeOut(300);
}

function hidePictureBehaviour(id)
{
  var tableJQ = $('#picture'+id+'behaviour');
  var table = tableJQ[0];
  table.over = false;
  if (table.style.display != 'none')
  {
    if (table.timer)
      clearTimeout(table.timer);
    table.timer = setTimeout('doHidePictureBehaviour('+id+')', 2000);
  }
}


function getPictureLinkDiv()
{
  var div = $('#pictureLinkDiv')[0];
  if (!div)
  {
    var div = document.createElement('div');
    div.id = 'pictureLinkDiv';
    $(div).css({display: 'none', position: 'absolute', width: '170px', padding: '10px', backgroundColor: 'white'});
    //div.style.border = '1px #cccccc solid';
    document.body.appendChild(div);
    addHandler(div, 'mouseout', function() {var div = getPictureLinkDiv(); div.over = false; hidePictureLink()});
    addHandler(div, 'mouseover', function() {var div = getPictureLinkDiv(); div.over = true; if (div.timer) clearTimeout(div.timer);});
  }
  return div;
}

function showPictureLink(a, id)
{
    var bounds = $(a).offset();
    var div = getPictureLinkDiv();
    if (div.timer)
        clearTimeout(div.timer);
    if (div.pictureId != id)
        div.style.display = 'none';
    div.pictureId = id;
    div.over = true;
    if (div.style.display == 'block')
        return;
        
    $(div)
        .css({
            left: bounds.left + 'px',
            top: (bounds.top+$(a).height()) + 'px',
            display: 'block'
        })
        .html('<p style="margin:100px auto;text-align:center">загрузка ...</p>');

    $.getJSON('/widget/picture-preview', {picture_id: id}, function(json) {
        if (json.ok) {
            $(div).html(json.html);
        } else {
            $(div).remove();
            window.alert('Error');
        }
    });
}

function doHidePictureLink()
{
    var div = getPictureLinkDiv();
    if (!div.over)
    {
        div.style.display = 'none';
        //div.over = false;
    }
}

function hidePictureLink()
{
  var div = $('#pictureLinkDiv')[0];
  div.over = false;
  if (div.style.display == 'block')
  {
    if (div.timer)
      clearTimeout(div.timer);
    div.timer = setTimeout('doHidePictureLink()', 2000);
  }
}

function showYouTubeVideo(a, code)
{
  bounds = getBounds(a);

  var div = document.createElement('div');
  div.className = 'youtubeScreen';
  div.style.left = bounds.left + 'px';
  var top = bounds.top - 400;
  if (top < 0)
    top = 0;
  div.style.top = top + 'px';

  div.innerHTML = '<div>' +
                    '<object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/'+code+'"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/'+code+'" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350"></embed></object>' +
                    '<br /><a href="#" onclick="var div = this.parentNode.parentNode;div.innerHTML = \'\';;div.ownerDocument.body.removeChild(div);return false;">закрыть</a>'+
                  '</div>';
  document.body.appendChild(div);

  return true;
}

function removeHandler(object, event, handler)
{
  if (typeof object.removeEventListener != 'undefined')
    object.removeEventListener(event, handler, false);
  else if (typeof object.detachEvent != 'undefined')
    object.detachEvent('on' + event, handler);
  else
  {
    var handlersProp = '_handlerStack_' + event;
    if (typeof object[handlersProp] != 'undefined')
    {
      for (var i = 0; i < object[handlersProp].length; i++)
      {
        if (object[handlersProp][i] == handler)
        {
          object[handlersProp].splice(i, 1);
          return;
        }
      }
    }
  }
}

function pushHandler(object, event, handler)
{
  if (typeof object.addEventListener != 'undefined')
    object.addEventListener(event, handler, false);
  else
    if (typeof object.attachEvent != 'undefined')
      object.attachEvent('on' + event, handler);
    else
    {
      var handlersProp = '_handlerStack_' + event;
      var eventProp = 'on' + event;
      if (typeof object[handlersProp] == 'undefined')
      {
        object[handlersProp] = [];
        if (typeof object[eventProp] != 'undefined')
          object[handlersProp].push(object[eventProp]);
        object[eventProp] = function(e)
          {
            var ret = true;
            for (var i = 0; ret != false && i < object[handlersProp].length; i++)
              ret = object[handlersProp][i](e);
            return ret;
          }
      }
      object[handlersProp].push(handler);
    }
}

function removeNode(dest)
{
  cleanNode(dest);
  dest.parentNode.removeChild(dest);
}

function cleanNode(dest)
{
  while (dest.firstChild)
    dest.removeChild(dest.firstChild);
}

Function.prototype.bind = function(object)
{
  var method = this
  return function()
  {
    return method.apply(object, arguments)
  }
}

function getBounds(element)
{
  var left = element.offsetLeft;
  var top = element.offsetTop;
  for (var parent = element.offsetParent; parent; parent = parent.offsetParent)
  {
    left += parent.offsetLeft;
    top += parent.offsetTop;
  }
  return {left: left, top: top, width: element.offsetWidth, height: element.offsetHeight};
}

function showAjaxPicturePreview(element, pictureId)
{
  var ajax = getHTTPRequestObject();
  ajax.open('GET', '/ajax/picturePreview.php?pictureId='+pictureId, true);
	ajax.onreadystatechange =
	  function ()
	  {
	    if (ajax.readyState == 4)
    	{
    		if (ajax.status == 200)
    		{
    		  var bounds = getBounds(element);
    		  var doc = ajax.responseXML;
    		  var picture = doc.documentElement;
    		  var div = document.createElement('div');
    		  div.setAttribute('id', 'picture'+pictureId+'preview');
    		  div.style.position = 'absolute';
    		  div.style.left = bounds.left+'px';
    		  div.style.top = (bounds.top+bounds.height)+'px';
    		  div.style.width = '122px';
    		  div.style.height = '162px';
    		  div.style.backgroundColor = '#436078';
    		  div.style.padding = '1px';
    		  var img = document.createElement('img');
    		  img.alt = picture.getAttribute('caption');
    		  img.src = picture.getAttribute('thumbUrl');
    		  img.width = 160;
    		  img.height = 120;
    		  img.style.border = '1px black solid';
    		  div.appendChild(img);

    		  document.documentElement.appendChild(div);
    		  alert(div);
    		}
    	}
	  }.bind(element);
	ajax.send(null);
}