$dw = function(txt) { document.write(txt); }
function collapse( itemname, imgId )
{
	var item = document.getElementById( itemname );
	if ( !item )
	{
		return false;
	}

	if ( item.className == "show" )
	{
		item.className = "hide";
		if ( imgId ) setImage( imgId, "/img/plus.png" );
	}
	else
	{
		item.className = "show";
		if ( imgId ) setImage( imgId, "/img/minus.png" );
	}
	return false;
}

function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'none' ) {
        el.style.display = 'none';
    }
    else {
        el.style.display = '';
    }
}

function setImage( imgId, imgPath )
{
	if ( !document.images ) return;
	var imgObj = document.getElementById( imgId, imgPath );
	if ( imgObj )
	{
		imgObj.src = imgPath;
	}
}

function checkReview() {
	var ret = false;
	var form_obj = document.getElementById( "review_form" );
	if ( form_obj ) {
		if ( form_obj.review ) {
			if ( form_obj.review.value.length == 0 ) {
				alert( "Пожалуйста, аргуметируйте Вашу оценку в поле \"Ваш комментарий\"" );
			}
			else {
				ret = true;
			}
		}
		else {
			alert( "Element 'review' not found" );
		}
	}
	else {
		alert( "Form not found" );
	}
	
	return ret;
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/"+"; Domain=.freelance.ru";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


function popup(file) {
	var options ="width=640,height=480,dependent=yes,alwaysRaised=yes,location=no,menubar=no,resizable=yes,status=no,titlebar=no,toolbar=no,scrollbars=yes";
	var win = window.open(file,"rulez",options);
	win.focus();

	return false;
}

function InverseMessages(form_id)
{
	var f = document.getElementById(form_id);
	if (!f)
	{
		alert('Form "' + form_id + '" not found');
	}
	else
	{
		var msgs = f.msgs;
		if (!msgs.length || msgs.length == 1)
		{
			msgs.checked = !msgs.checked;
		}
		else
		{
			for (var i=0; i < msgs.length; i++)
			{
				msgs[i].checked = !msgs[i].checked;
			}
		}
	}
}

function countLetters(src_id,dst_id,limit)
{
	var dst = $(dst_id);
	if (dst)
	{
		var src = $(src_id);
		if (src)
		{
			var len = src.value.length;
			if (len > limit)
			{
				src.value = src.value.substring(0, limit);
				dst.update( "<b style='color:red'>" + limit + " из " + limit + "</b>" );
			}
			else
			{
				dst.update(src.value.length + " из " + limit);
			}
		}
		else
		{
			alert("Объект " + dst_id + " не найден");
		}
	}
	else
	{
		alert("Объект " + src_id + " не найден");
	}
}

function good_time()
{
	var cT = new Date();
	hours = cT.getHours();  
	if ( hours >= 6 && hours <= 11 )  
	document.write("Доброе утро");  
	if ( hours >= 12 && hours <= 17 )  
	document.write("Добрый день");  
	if (hours >= 18 && hours <= 23)  
	document.write("Добрый вечер");  
	if (hours >= 0 && hours <= 5)  
	document.write("Доброй ночи");  
}

function rmReview(reviewId, cmd)
{
	var confirm_text = "Удалить этот отзыв?";
	var url_cmd =  "rmReview";
	
	if( cmd == 'hide' )
	{
		confirm_text = "Скрыть этот отзыв?";
		url_cmd =  "hideReview";
	}
	else if ( cmd == 'restore' )
	{
		confirm_text = "Вернуть этот отзыв?";
		url_cmd =  "restoreReview";
	}
	else if ( cmd == 'negative' )
	{
		confirm_text = "Сделать отзыв отрицательным?";
		url_cmd =  "changeReview&ball=-1";
	}
	else if ( cmd == 'positive' )
	{
		confirm_text = "Сделать отзыв положительным?";
		url_cmd =  "changeReview&ball=1";
	}
	else if ( cmd == 'neutral' )
	{
		confirm_text = "Сделать отзыв нейтральным?";
		url_cmd =  "changeReview&ball=0";
	}
	if (confirm(confirm_text))
	{
		var url = '/responder/?cmd='+ url_cmd + '&id=' + reviewId;
		new Ajax.Request(url,
			{
				method: 'get',
				onSuccess: function(transport)
				{
					alert(transport.responseText);
					window.location.reload();
				},
				onFailure: function(transport)
				{
					alert(transport.status + " " + transport.statusText);
				}
			}
		);
	}
}

function addLoadEvents(func)
{	
	/*if (typeof func === 'function')
	{
		document.observe("dom:loaded", func); 
	} */
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
		window.onload = func;
	} else {
		window.onload = function(){
		oldonload();
		func();
		}
	}
	
	
}

/*addOverSelector = function() 
{ 
	if (document.all&&document.getElementById) 
	{ 
		if(navRoot = document.getElementById("rss_list"))
		{
			for (i=0; i<navRoot.childNodes.length; i++) 
			{ 
				node = navRoot.childNodes[i]; 
				if (node.nodeName=="LI") 
				{ 
					node.onmouseover=function() { this.className+=" over"; } 
					node.onmouseout=function() { this.className=this.className.replace (" over", ""); } 
				} 
			} 
		}
	}
}

addLoadEvents(addOverSelector);	*/


//Edit in place

makeEditable = function ()
{
	$$('.editMe').each(function(s) {
	 s.writeAttribute('title', 'Кликните для редактирования');
     Event.observe(s, 'click', function(){editMe($(s))}, false);
     Event.observe(s, 'mouseover', function(){showAsEditable($(s))}, false);
     Event.observe(s, 'mouseout', function(){showAsEditable($(s), true)}, false);
	});
}

function showAsEditable(obj, clear){
     if (!clear){
          Element.addClassName(obj, 'editable');
     }else{
          Element.removeClassName(obj, 'editable');
     }
 }
 
function editMe(obj){
     
	 var par = obj.id.split('_');
	 if(par.length !=2 || par[0].lenghth<1 || par[1]<0)
	 {
		alert('Ошибочка вышла, невозможно редактировать этот элемент: ' + obj.id );
		return false;
	 }
	 Element.hide(obj);

	var textarea ='<div id="' + obj.id + '_editor" class="js_editor"><textarea id="' + obj.id + '_edit" name="' + obj.id + '" rows="4" cols="60">' + obj.innerHTML + '</textarea>';

     var button = '<input id="' + obj.id + '_save" value="Сохранить" type="button"  class="button"> или <input id="' + obj.id + '_cancel" value="Отмена" type="button" class="button"></div>';

     new Insertion.After(obj, textarea+button);
     Event.observe(obj.id+'_save', 'click', function(){EditMesaveChanges(obj,par[1],par[0])}, false);
     Event.observe(obj.id+'_cancel', 'click', function(){cleanupEditMe(obj)}, false);
	 $(obj.id+'_editor').focus();
	 

}
function cleanupEditMe(obj, keepEditable){
     Element.remove(obj.id+'_editor');
     Element.show(obj);
     if (!keepEditable) showAsEditable(obj, true);
 }

 function EditMesaveChanges(obj,id,type,text)
 {
	var eobj = $(obj.id+'_edit');
	var new_content = eobj.value.stripTags();
	eobj.setStyle({background:'url(/img/lightbox/loading.gif) no-repeat center center'});
	
	var url = '/responder/?cmd=saveNote';
	var pars = 'id=' + id + '&type=' + type +'&content=' + new_content;
	new Ajax.Request(url,
	{
		method: 'post',
		postBody:pars,
		onSuccess: function(transport)
		{
			if (transport.responseText.search(/^OK\s*/) >= 0)
			{
				obj.innerHTML = new_content;
				//eobj.setStyle({background:'none'});
				cleanupEditMe(obj);	
			}
			else
			{
				//eobj.setStyle({background:'none'});
				alert('Ошибка: ' + transport.responseText);
				cleanupEditMe(obj);
			}
		},
		onFailure: function(transport)
		{
			eobj.setStyle({background:'none'});
			alert("Не удалось сохранить " + ": " + transport.status + " " + transport.statusText);
			cleanupEditMe(obj);
		}
	}
	);
}

function nl2br(str) { return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br />$2'); }
function br2nl(str) { return (str + '').replace(/([^>\r\n]?)<br \/>(\r\n|\n\r|\r|\n)/g, '$1$2'); }

function pub_keys() 
{
  var title = encodeURIComponent(document.title);
  var href = encodeURIComponent(document.location);
  var html = encodeURIComponent(document.title + "<br>\n" + "<a href=\""+document.location+"\">"+document.location+"</a>")
   
  var s= '';
  s += '<li class="title">Поделиться:</li>';
  s += '<li><a href="http://twitter.com/home?status='+title+'%20'+href+'" class="twitter" title="Опубликовать в Twitter" target="_blank">Опубликовать в Twitter</a></li>';
  s += '<li><a href="http://vkontakte.ru/share.php?url='+href+'&title='+title+'" class="vkontakte" title="Опубликовать в ВКонтакте" target="_blank">Опубликовать в ВКонтакте</a></li>';
  s += '<li><a href="http://www.livejournal.com/update.bml?subject='+title+'&event='+html+'" class="livejournal" title="Опубликовать в LiveJournal" target="_blank">Опубликовать в Livejournal</a></li>';
  s += '<li><a href="http://www.liveinternet.ru/journal_post.php?action=n_add&cntitle='+title+'&cnurl='+href+'" class="liveinternet" title="Опубликовать в LiveInternet" target="blank">Опубликовать в LiveInternet</a></li>';
  s += '<li><a href="http://connect.mail.ru/share?share_url='+href+'" class="mail_ru" title="Опубликовать в Mail.ru" target="_blank">Опубликовать в Mail.ru</a></li>';
  s += '<li><a href="http://www.facebook.com/share.php?u='+href+'" class="facebook" title="Опубликовать в Facebook" target="_blank">Опубликовать в Facebook</a></li>';
  s += '<li><a href="http://my.ya.ru/posts_add_link.xml?URL='+href+'&amp;title='+title+'" class="ya_ru" title="Поделиться ссылкой — я.ру" target="_blank">Поделиться ссылкой — я.ру</a></li>';
  
  s += '<li><g:plusone size="small" annotation="none"></g:plusone></li>';
  s += "\n"+ '<script type="text/javascript" src="https://apis.google.com/js/plusone.js">' + "\n{lang: 'ru'}\n</script>\n";
  
  return s;
}
function print_pubkeys()
{
    document.write('<ul class="pub_keys">');
    document.write(pub_keys());
    document.write('</ul>');
}
addLoadEvents(makeEditable);

/**
* Returns the value of the selected radio button in the radio group, null if
* none are selected, and false if the button group doesn't exist
*
* @param {radio Object} or {radio id} el
* OR
* @param {form Object} or {form id} el
* @param {radio group name} radioGroup
*/
function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }

    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}

function getUsersCount(obj_id)
 {
	if($(obj_id))
	{
		$(obj_id).update("...");
		var url = '/responder/?cmd=get_users_count';
		//var pars = 'cmd=get_users_count';
		new Ajax.Request(url,
		{
			//method: 'post',
			//postBody:pars,
			onSuccess: function(transport)
			{
				$(obj_id).update(transport.responseText);
			},
			onFailure: function(transport)
			{
				$(obj_id).update("&nbsp;");
			}
		}
		);
	}
}
WritegetUsersCount = function() { getUsersCount('usr_count'); }
addLoadEvents(WritegetUsersCount);



var $buoop = { vs:{i:7,f:2,o:9.64,s:2, n:9}, reminder: 24, test:false} 
$buoop.ol = window.onload; 
window.onload=function(){ 
 if ($buoop.ol) $buoop.ol(); 
 var e = document.createElement("script"); 
 e.setAttribute("type", "text/javascript"); 
 e.setAttribute("src", "http://browser-update.org/update.js"); 
 e.setAttribute("charset", "UTF-8"); 
 document.body.appendChild(e); 
}

//freelance search_form
var fs_cur_spec_id = 0;
var fs_cur_parent_spec = 0;
function fs_search_submit()
{
	var fobj = $('fs_search');
	if(fobj)
	{
		var url = "http://" + document.location.hostname + "/freelancers/";
		var spec = parseInt($('fs_spec').getValue());
		if(spec>0)
		{
			url += '?spec='+spec;
		}
		else
		{
			spec = parseInt($('fs_parent_spec').getValue());
			if(spec>0)
			{
				url += '?spec='+spec;
			}
		}
		document.location = url;
	}
	return false;
}

function fs_get_childspecs(obj)
{
	if(obj)
	{
		for(var i =0; i<obj.options.length; i++)
		{
			if(obj.options[i].selected)
			{
				//alert('http://freelance.ru/ajax/specfilter/index/spid/'+ obj.options[i].value);
				new Ajax.Updater('fs_spec','/ajax/specfilter/index/spid/'+ obj.options[i].value,
				{
					method:'post',
					onCreate:function(){ obj.disabled= true; $('fs_spec').update(); },
					onFailure:function(){ alert('Ajax.Updater fs_spec error') },
					onComplete:function()
					{
						obj.disabled= false;
						if(fs_cur_spec_id && fs_cur_parent_spec>1)
						{
							obj2 = $('fs_spec');
							if(obj2)
							{
								for(var i =0; i<obj2.options.length; i++)
								{
									if(obj2.options[i].value == fs_cur_spec_id )
									{
										obj2.options[i].selected = true;
										break;
									}
								}
							}		
						}
					}
				}
				)
				break;
			}
		}
	}
}

fs_update_childspecs = function()
{
	if ($('fs_spec') && $('fs_parent_spec').getValue() && parseInt($('fs_parent_spec').getValue()) && !parseInt($('fs_spec').getValue()))
	{
		fs_get_childspecs($('fs_parent_spec'))
	}
}

fs_childspecs_init = function()
{
	
	if ($('fs_spec') && $('fs_parent_spec'))
	{
		if(fs_cur_spec_id || fs_cur_parent_spec  )
		{
			if(obj = $('fs_parent_spec'))
			{
				for(var i =0; i<obj.options.length; i++)
				{
					if(obj.options[i].value == fs_cur_parent_spec || obj.options[i].value == fs_cur_spec_id )
					{
						obj.options[i].selected = true;
						break;
					}
				}
			}	
		}
		fs_update_childspecs();
	}
}
addLoadEvents(fs_childspecs_init);

function show_have_new_mail_notification() 
{
	if(!readCookie('not_show_inbox_warn'))
	{
		if(document.location.pathname.indexOf('/inbox/') < 0)
		{	
			var h_body = '<div>';
			h_body += '<p><b>Есть непрочитанные личные сообщения</b></p>';
			h_body += '<p><a href="http://freelance.ru/inbox/" target="_blank" onClick="hide_popw(); set_inbox_warn_ck();">Перейти к личным сообщениям</a> <br>';
			h_body += '<a href="javascript:void(0);" target="_blank" onClick="hide_popw(); set_inbox_warn_ck(); return false;">Напомнить позже</p></div>';
			show_popw(h_body);
		}
	}
}
function set_inbox_warn_ck()
{
	var date = new Date();
	date.setTime(date.getTime()+ (15*60*1000)); //15 минут
	var expires = ";expires="+date.toGMTString();
	var kuka = "not_show_inbox_warn=1" + expires+"; path=/"+";Domain=.freelance.ru";
	document.cookie = kuka;
}

function show_popw(txt)
{
	if($('popw'))
	{
		$('popw').update(txt);
		if(typeof(Effect) != "undefined") {
			Effect.Appear('popw');
		}
		else
			$('popw').show();
	}
}
function hide_popw(txt)
{
	if($('popw'))
	{
		if(typeof(Effect) != "undefined")
			Effect.Fade('popw');
		else
			$('popw').hide();
	}
}
ajax_have_newmail = function()
{
	obj = $('newmail_flag');
	if(obj)
	{
		var url = '/ajax/newmail/';
		new Ajax.Request(url,
		{
			onSuccess: function(transport)
			{
				if(transport.responseText == 1)
				{
					obj.update('<a href="/inbox/" class="new_messages" title="есть непрочитанные личные сообщения">&nbsp;</a>');
					// show_have_new_mail_notification();	
				}
				else
				{
					obj.update('<a href="/inbox/" class="no_new_messages" title="непрочитанных личных сообщений нет">&nbsp;</a>');
				}
				setTimeout(ajax_have_newmail, 60000);
			},
			/*onFailure: function(transport)
			{
				obj.update("ajax error");
			}*/
		}
		);
	}

					
}
addLoadEvents(ajax_have_newmail);

function slideMenu() 
{
	if(typeof SDMenu !== 'undefined')
	{
		var myMenu = new SDMenu("slide_menu"); // ID of the menu element
		// Default values...
		myMenu.speed = 3;                     // Menu sliding speed (1 - 5 recomended)
		myMenu.remember = true;               // Store menu states (expanded or collapsed) in cookie and restore later
		myMenu.oneSmOnly = false;             // One expanded submenu at a time
		myMenu.markCurrent = true;            // Mark current link / page (link.href == location.href)
		myMenu.init();
	}
}
//if(typeof SDMenu !== 'undefined') addLoadEvents(slideMenu);
/*document.observe("dom:loaded", function() { if (document.body.className.length) { document.body.className = document.body.className + " js_hide"; 
} else { document.body.className = "js_hide"; }  });*/


