// Вызывается по тайм-ауту или при щелчке на кнопке.
function doToggleComments(ctype, id) {
	// Создаем новый объект JSHttpRequest.
	var req = new JsHttpRequest();
	// Код, АВТОМАТИЧЕСКИ вызываемый при окончании загрузки.
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.responseJS) {
				document.getElementById('do_receive_comments_up').value = req.responseJS.res;
				document.getElementById('do_receive_comments_down').value = req.responseJS.res;
			}
			// Отладочная информация.
//			document.getElementById('debug').innerHTML =
//				req.responseText;
		}
	}
	// Разрешаем кэширование (чтобы при одинаковых запросах
	// не обращаться к серверу несколько раз).
//        req.caching = true;
	// Подготваливаем объект.
	req.open('POST', '/index.php?action=toggle_comments', true);
	// Посылаем данные запроса (задаются в виде хэша).
	req.send({ ctype: ctype, id: id });
} 

function Udaff_Form_Sections(instanceName, openSection)
{
    /* Set up this class instance for function calls from the page. */
    this._instanceName = instanceName;

    /* The currently showed section. */
    var _openSection;

    this.toggle = function(sectionId)
    {
        /* Get the currently open section object. */
        openSectionId = this._get();
        if (document.getElementById('_section_' + openSectionId)) {
            document.getElementById('_section_' + openSectionId).style.display = 'none';
        }
        document.getElementById('_tab_' + openSectionId).className = null;

        /* Get the newly opened section object. */
        if (document.getElementById('_section_' + sectionId)) {
            document.getElementById('_section_' + sectionId).style.display = 'block';
        }
        document.getElementById('_tab_' + sectionId).className = 'activeTab';

        /* Store the newly opened section. */
        this._set(sectionId);
    }

    this._get = function()
    {
        return this._openSection;
    }

    this._set = function(sectionId)
    {
        var form = eval('document.' + this._instanceName);
        if (typeof form != 'undefined' &&
            typeof form.__formOpenSection != 'undefined') {
            form.__formOpenSection.value = escape(sectionId);
        }
        this._openSection = sectionId;
    }

    this._set(openSection);
}

document.onkeydown = NavigateThrough;

function NavigateThrough (event)
{
	if (!document.getElementById) return;

	if (window.event) event = window.event;

	if (event.ctrlKey)
	{
		var link = null;
		switch (event.keyCode ? event.keyCode : event.which ? event.which : null)
		{
			case 0x25:
				link = document.getElementById ('NextLink');
				break;
			case 0x27:
				link = document.getElementById ('PrevLink');
				break;
			case 0x26:
				link = document.getElementById ('UpLink');
				break;
			case 0x28:
				link = document.getElementById ('DownLink');
				break;
		}

		if (link && link.href) document.location = link.href;
	}			
}

var MAX_DUMP_DEPTH = 10;

function dumpObj(obj, name, indent, depth) {
      if (depth > MAX_DUMP_DEPTH) {
             return indent + name + ": <Maximum Depth Reached>\n";
      }
      if (typeof obj == "object") {
             var child = null;
             var output = indent + name + "\n";
             indent += "\t";
             for (var item in obj)
             {
                   try {
                          child = obj[item];
                   } catch (e) {
                          child = "<Unable to Evaluate>";
                   }
                   if (typeof child == "object") {
                          output += dumpObj(child, item, indent, depth + 1);
                   } else {
                          output += indent + item + ": " + child + "\n";
                   }
             }
             return output;
      } else {
             return obj;
      }
}

function convertToMegaBytes( bytes ) 
{
	var mb = Math.round((bytes/[Math.pow(1024,2)])*1000000)/1000000;
	var mbStr = String(mb);
	var mbArr = mbStr.split('.');
 	var rhs = mbArr[1];
 	mbStr = mbArr[0] + '.' + rhs.substr(0,2) + 'Mb';
	return mbStr;
}    

var iidx = 0;
function add_image_field()
{
	document.getElementById("image" + iidx).onchange = null;
	
	iidx++;

    var filelist = document.getElementById("title0").parentNode;
    filelist.appendChild(document.createElement("br"));
    
	var newField = document.createElement("input");

    newField.type = "input";
    newField.name = "title[]";
    newField.size = "40";
    newField.id = "title" + iidx;
    newField.value = iidx + 1;
    
    filelist.appendChild(newField);

    
    filelist = document.getElementById("image0").parentNode;
    if(iidx > 1)
    	filelist.appendChild(document.createElement("br"));
    
    newField = document.createElement("input");

    newField.type = "file";
    newField.size = "30";
    newField.onchange =  function() 
    {
      add_image_field();
    }
    newField.name = "image[]";
    newField.id = "image" + iidx;

    filelist.appendChild(newField);
}

function boxesToggle (name) {
	var boxes = new Array();
	boxes = document.getElementsByName(name);

	var i; var boxesCount = boxes.length;	
	for (i = 0; i < boxesCount; i++) {
		boxes[i].checked = !boxes[i].checked;	
	}
	return true;
}

function doSetRandomPassword() 
{
	// Создаем новый объект JSHttpRequest.
	var req = new JsHttpRequest();
	// Код, АВТОМАТИЧЕСКИ вызываемый при окончании загрузки.
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.responseJS) {
				document.getElementById('password_field').value = req.responseJS.res;
			}
			// Отладочная информация.
//			document.getElementById('debug').innerHTML =
//				req.responseText;
		}
	}
	// Разрешаем кэширование (чтобы при одинаковых запросах
	// не обращаться к серверу несколько раз).
//        req.caching = true;
	// Подготваливаем объект.
	req.open('POST', 'index.php?js_action=random_password', true);
	// Посылаем данные запроса (задаются в виде хэша).
	req.send();
}

function reply_to(id, quote)
{
	if(document.getElementById('reply_to').style.display == 'none')
		new Effect.SlideDown('reply_to');

	if (quote)
	{
		var message=document.getElementById('c_msg_'+id).innerText;
		if (!message)
			message=document.getElementById('c_msg_'+id).textContent;
		var strings=message.split('\n')
		document.guestbook_footer.msg.value = ">" + strings.join("\n>") + "\n";
	}
	else
		document.guestbook_footer.msg.value = '';

	document.getElementById('reply_to_comment').innerHTML = '<a style="text-decoration:none;" href="#' + id + '">' + document.getElementById('c_date_'+id).innerHTML + '  ' + document.getElementById('c_name_'+id).innerHTML + '</a>';
	document.getElementById('reply_to_id').value = id;
	setTimeout("document.getElementById('gfm').focus()",1);
};

function cancel_reply()
{
	document.getElementById('reply_to_id').value = '';
	document.getElementById('reply_to').style.display = 'none';
}

function show_image(id, path, w, h)
{
	var wtf = document.createElement('SPAN');
	$('ai_'+id).parentNode.insertBefore(wtf, $('ai_'+id));
	wtf.innerHTML = '<img id="cp_' + id + '" class="progress" src="/wog/img/progress.gif" width="200" height="19">';
	
	var wtf = document.createElement('div');
	wtf.id = "di_"+id;
	wtf.style.display = 'none';
	var ni = document.createElement("img");
	ni.src = path;
	ni.width= w;
	ni.height = h;
	ni.onload = function () { $('di_'+id).show(); ip=$('cp_'+id); ip.parentNode.removeChild(ip);};
	wtf.appendChild(ni);

	$('ai_'+id).parentNode.insertBefore(wtf, $('ai_'+id).nextSibling);
	$('ai_'+id).hide();
	
	return false;
}