/*
	На чуть более чем полностью данный файл
	написан в казематах дизайн-студии Ремарк
*/
var maximgs = 5;   // Юзер-сайд ограничение (сыссла обходить нету — со стороны сервера тоже самое =) 
var modifer = -3;   // Комментарии скрываются при...   

// Всякие стафы
var IMG_trashcan = '<img src="style/trashcan.png">';
var OpenComment = 'Раскрыть комментарий';
var ExtLinks = [];

function count(rly) { var i=0; rly.each(function() {i++;}); return i; }
function trim(string) { return string.replace(/(^\s+)|(\s+$)/g, ""); }

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");
}

function cssFix(){ // by k0rzhik (icq:341179372)
  var u = navigator.userAgent.toLowerCase(),
  addClass = function(el,val){
    if(!el.className) {
      el.className = val;
    } else {
      var newCl = el.className;
      newCl+=(" "+val);
      el.className = newCl;
    }
  },
  is = function(t){return (u.indexOf(t)!=-1)};
  addClass(document.getElementsByTagName('html')[0],[
    (!(/opera|webtv/i.test(u))&&/msie (\d)/.test(u))?('ie ie'+RegExp.$1)
      :is('firefox/2')?'gecko ff2'
      :is('firefox/3')?'gecko ff3'
      :is('gecko/')?'gecko'
      :is('opera/9')?'opera opera9':/opera (\d)/.test(u)?'opera opera'+RegExp.$1
      :is('konqueror')?'konqueror'
      :is('applewebkit/')?'webkit safari'
      :is('mozilla/')?'gecko':'',
    (is('x11')||is('linux'))?' linux'
      :is('mac')?' mac'
      :is('win')?' win':''
  ].join(" "));
}


function vote(id,mark) {

    $('vm'+id).style.visibility!='hidden'?1:new Ajax(ExtLinks['host']+"/rvote&to="+id+"&mark="+mark, {method: 'get',update: $("vote"+id), onComplete: function() {new Fx.Style($('vm'+id),'opacity', {duration:5000, wait:false}).start(0); return false;}}).request();
 
}

function rec_vote(addr,id,mark) {
 
    $('vm'+id).style.visibility!='hidden'?1:new Ajax(addr+"\/"+id+"\/"+mark, {method: 'get',update: $("vote"+id), onComplete: function() {new Fx.Style($('vm'+id),'opacity', {duration:5000, wait:false}).start(0);}}).request();
} 
 
function changePage1(rly) {
	
	var mincount = $('mincount').getText().toInt();
    var maxcount = $('maxcount').getText().toInt();
	var count = $('count').getText().toInt(); 

	var t = 500; // время выполнения
	var w = 110; // ширина одной картинки

	if (rly==0) {
		if (count>mincount) {
			x = $('tableofpics').getStyle('margin-left').toInt()+w;
			new Fx.Style('tableofpics', 'margin-left', {duration:t}).start(x); 
			count--;
			$('count').setText(count);
			count <= mincount ? $('left_arrow').setStyle('display','none') :1;
			count < maxcount ? $('right_arrow').setStyle('display','inline') :1;
		}
	}
	else if (count<maxcount) {
			x = $('tableofpics').getStyle('margin-left').toInt()-w;
			new Fx.Style('tableofpics', 'margin-left', {duration:t}).start(x); 
			count++;
			$('count').setText(count);
			count == maxcount ? $('right_arrow').setStyle('display','none') :1;
			count >mincount ? $('left_arrow').setStyle('display','inline') :1;
	}		
}
 
function post_comment(rly) {

	var err = $('error_comment');
    if (err!=null) {
    	new Fx.Style(err,'opacity', {duration:1000, wait:false, onComplete: function(){
    	new Fx.Style(err,'height', {duration:1000, wait:false, onComplete: function(){err.remove();	}}).start(0);}}).start(0);
    }
    
	var arr = /(places|events|recipes|interesting|news)/.exec(location.href);
	rly = ExtLinks[arr[1]]+'/comment/'+rly;
	
    var com_text = $('com_text').getProperty('value'); 
    var mb_random = Math.round(Math.random() * 100000);
  
    var newPost = new Element('div', {'id': 'rand'+mb_random, 'class': 'disarc'}); 
    newPost.injectBefore($('newpost'));
    $('prepost').style.display = 'none';
    new Ajax(rly , {method: 'post', data:'comment='+com_text, update: newPost}).request();
    $('comform').style.display = 'none';
    $('com_text').setProperty('value','');  

}

function prepost_place_comment() {
    var com_text = $('com_text').getProperty('value');
    
    if (trim(com_text)!='') {
    	var tab = '<table class="comment"><tr><td rowspan="2" class="ava"><img src="images/avataar1.jpg" width="34" height="34"></td><td class="comuser"><b>Так будет выглядеть ваш комментарий</b></td><td class="comvoting"></td></tr><tr><td rowspan="2">'+com_text+'</td></tr></table>';
   
    	$('prepost').setHTML(tab);
    	$('prepost').style.display = 'block';
    }
}

function colorVotes(rly) {
     if (rly.getText().toInt() > 0) {rly.setText('+'+rly.getText()); rly.style.color = '#339900' } else if (rly.getText().toInt() < 0) {rly.style.color = '#CC0000' ; };
}

function com_vote(tp,rat,rly) {
	var arr = /(places|events|recipes|interesting|news)/.exec(location.href);

	rly = ExtLinks[arr[1]]+'/commentvote/'+rly;
		
    new Ajax(rly , {method: 'get' }).request();
    var rate = $('rate'+rat);
    var suf1= ''; var suf2='';
    if (tp == 1) { rate.setHTML(rate.getText().toInt()+1); suf2='_max';}
    else { rate.setHTML(rate.getText().toInt()-1); suf1='_max';}
    
    colorVotes(rate);
    $('rate'+rat+'it').setHTML('<img src="style/plus_ina'+suf1+'.jpg" height="15" width="15"  align="left"><img src="style/min_ina'+suf2+'.jpg" height="15" width="15">');
 }
 
function getCommentForm() {
	$('comform').style.display = 'block';
}

function modifyComments() {
    
    var news = -10000;
    if ($('new_comm') != null) news=$('new_comm').getText().toInt();
    var total = $('total_comm').getText().toInt() - news;
    var comlist = $$('div.gg');
  
  	total==0?total=-1:1;
    var i = 0;    
        
    comlist.each(function(element) 
    {
        colorVotes(element);
        
        if (i==total) 
        {
        	var a = element.getParent().getParent().getParent().getParent();
        	var hr = new Element('hr', {'class':'newCommentsLime'});
        	hr.injectBefore(a);
        }
		
		if (element.getText().toInt() <= modifer) 
		{                       
            var a = element.getParent().getParent().getParent().getParent();
            a = a.getLast().getLast();
            a = a.getFirst();
            var buff = a.getText();
            a.setText('');  
            buff = trim(buff);
            var b = new Element('a', { 'events': {'click': function(){  a.setText(buff); }},'class': 'closeComment'});
            b.setHTML(OpenComment);             
            b.injectInside(a);
        }
        i++;
    }); 
 }
 
 function addNickToComment(nick) {
       $('comform').style.display=='block'?$('com_text').setProperty('value', $('com_text').getProperty('value')+nick+', '):1;
 }
  
 function toggleMenu() {
    someToggle('fullmenu_container');
    someToggle('comments_container'); 
    var rly = $('fullmenu_container').style.display=='block'?'отзывы':'меню';
    $('toggleThat').setHTML('Показать '+rly);
 }
 
function showMeMenu() {
    $('fullmenu_container').style.display='block';
    $('comments_container').style.display='none'; 
    var rly = $('fullmenu_container').style.display=='block'?'отзывы':'меню';
    $('toggleThat').setHTML('Показать '+rly);
}
  
function toggleImgSrc(tog, id,mode) { // сменить тип картинки при редактировании
    var value,s;
    
    if (mode==0)  {
        s=""; value="";
    }
    else {
        s='<div class="trashcan_container"> <a onclick="deleteImg('+id+');">'+IMG_trashcan+'</a></div>';
        tog==1?value=$('urlimg'+id).getProperty('value'):value=$('fileimg'+id).getProperty('title');
    }
    
    if (value='null') {value='';}
      
    if (tog==1){ 
    
        $('srcfield'+id).setHTML('<p class="label">Выберите фотографию:</p><input name="fileimg'+id+'" title="'+value+'" id="fileimg'+id+'" type="file" size="27" class="file"> '+s+'<p class="reg_request" style="margin-top:4px;"><a onclick="toggleImgSrc(0,'+id+','+mode+');">Указать адрес картинки в интернете</a></p>')
    }
    else {$('srcfield'+id).setHTML('<p class="label">Адрес фотографии в интернете:</p><input type="text" value="'+value+'" id="urlimg'+id+'"name="urlimg'+id+'" class="inputs"> '+s+'<p class="reg_request" style="margin-top:4px;"><a onclick="toggleImgSrc(1,'+id+','+mode+');">Загрузить свою картинку</a></p>');
    }
}
 
 
function addImgField(tog) {
    var rly = $('fieldcounter').getText();
  
    if (rly <=maximgs) {
        var newField = new Element('div', {'id': 'srcfield'+rly}); 
        
        if (tog == 1) 
        {
        	newField.setHTML('<p class="label">Адрес фотографии в интернете:</p><input type="text" value="" name="urlimg'+rly+'" class="inputs"><p class="reg_request"><a onclick="toggleImgSrc(1,'+rly+',0);">Загрузить свою картинку</a></p>');
        }
        else
        {
        	newField.setHTML('<p class="label">Выберите фотографию:</p><input name="fileimg'+rly+'" title="" id="fileimg'+rly+'" type="file" size="35" style="margin-bottom:11px;"><p class="reg_request"><a onclick="toggleImgSrc(0,'+rly+',0);">Указать адрес картинки в интернете</a></p>');
        }
        
        newField.injectAfter($('srcfield'+(rly.toInt()-1)));
         
        $('fieldcounter').setText((rly.toInt()+1));
        rly==maximgs?$('addImgField').setText(''):1;
    }  
}

function addImgField_edit() {	// добавление картинки при редактировании
    var counter = $('fieldcounter');
    var k = counter.getText().toInt();
        
    var y;
    if (k>=maximgs) {alert('oops!')}
    else {
    	
        for(i=maximgs;i>0;i--) { $('img_recipe_edit'+i)?1:y=i;   }
        var b = new Element('div',{'class': 'img_recipe_edit', 'id':'img_recipe_edit'+y});
        b.setHTML('<div class="img_container"><img src="recipes/images/none.jpg" width="90" height="63" align="left"></a></div>	<div id="srcfield'+y+'">  <p class="label">Выберите фотографию:</p><input name="fileimg'+y+'" id="fileimg'+y+'" type="file" size="27" class="file"><p class="reg_request" style="margin-top:4px;"><a onclick="toggleImgSrc(0,'+y+',1);">Указать адрес картинки в интернете</a></p> </div>');
        
        b.injectBefore($('fieldcounter'));  
        counter.setText(k+1);
         
        k==4?addAddImg(0):1;  
    }
}

function addAddImg(rly) {
    rly==1?$('addImgLink').setHTML ('<p class="reg_request" id="addImgField">+ &nbsp;<a onclick="addImgField_edit(1);">Добавить ещё картинку</a></p>'):$('addImgLink').setHTML('');
}

function deleteImg(rly) {
    var curElement = $('img_recipe_edit'+rly);
    var count = $('fieldcounter');
    var i = count.getText().toInt()-1;
    
    curElement.remove();
    count.setText(i);
    i<=maximgs?addAddImg(1):1;    
}

function checkAll(rly, name) {
    var chklist = $$('#'+name + ' input');
        
    chklist.each(function(element) {  
       element.setProperty("checked", rly);
    }); 
}

function checkOne(rly) {
    $(rly).getProperty('checked')?$(rly).setProperty('checked',""):$(rly).setProperty('checked','checked');
}

function someToggle(rly) {
    var obj = $(rly);
    obj.style.display=='block'?obj.style.display="none":obj.style.display="block";
}

function whatToFind(rly) {
    var opt = $$('#whattofind a');
    var k;   
    
    for(var i=0;i<4;i++){
       opt[i].hasClass('find_selected')?k=i:1;
    }
    
   opt[k].removeClass('find_selected');
   $('whattofind'+k).style.display='none';
   
   opt[rly].addClass('find_selected');
   $('whattofind'+rly).style.display='block';
}
 
 
// diamant (http://diamant.habrahabr.ru/)
 
function areaHeight(textarea){
    var dif = textarea.scrollHeight - textarea.clientHeight;
   
    if (dif>=0){
        if (isNaN(parseInt(textarea.style.height))){ 
		  textarea.style.height = textarea.scrollHeight + "px"
        }else{
          textarea.style.height = parseInt(textarea.style.height) + dif + "px"
        }
    }
}
// ---------------------------------------

function getPlaceList() {
	placelist = $('hiddenPlaceList').getText().split('|');
	for(i=0;i<count(placelist);i++) { placelist[i] = trim(placelist[i]); } 
}
 
function insertPlaces(rly,e) {
	obj = $(rly);

	values = obj.getProperty('value').split(',');
	value = trim(values[count(values)-1]);
	

	if (/(13|27)/.test(e.keyCode)) {
		 $('popup').setStyle('display','none');
		 obj.focus(); 
	}
	else
	
	if (value!='') 
	{
		var buff = new RegExp("^"+value+".+","ig");
		var listlength = 0;
		ul = $('ul_pop');
		ul.setHTML('');
		
		placelist.each(function(place) { 
			
			if (buff.test(place))
			{
				var li = new Element('li'); 
				var a = new Element('a', { 'events': { 'click': function(){
											
											var k=1;
											var tmp = obj.getProperty('value').match(/,/);
											if ((tmp!=null)&&(count(tmp)==(count(values))))	k=0;
											 
											tmp = '';
											for (i=0;i<count(values)-k;i++)
											{
												tmp += trim(values[i])+', ';
											}
											tmp += place+', '
											
											obj.setProperty('value',tmp);
											
											obj.focus();
											values = obj.getProperty('value').split(',');
											$('popup').setStyle('display','none');
										 } 
									   }
									 });
				a.setText(place);
        		a.injectInside(li);
        		li.injectInside(ul);
        		listlength++;
        	}
    	});
    	
    	if (listlength!=0) $('popup').setStyle('display','block');
    } 

}

function releaseForm() {
	if ($('popup').getStyle('display')=='block')  $('popup').setStyle('display','none');
}
  
function inputState(kind,obj,rly) {
	if (kind==1) {
		trim($(obj).getProperty('value'))==rly ? $(obj).setProperty('value','') : 1;
	}
	else {
		trim($(obj).getProperty('value'))=='' ? $(obj).setProperty('value',rly) : 1;
	}
}  

function showMenu() {
	var places = $$('div.menu_header a');
	var loc = location.hash.substring(1); 
    Sliders  = new Array(); 
        
    places.each(function(element)  
    {  
	   	var n = element.getProperty('title');
       	Sliders[n] = new Fx.Slide('slide'+n);
	
       	element.addEvent('click', function(e)   
      	{
          	e = new Event(e);
            Sliders[n].toggle();
            e.stop();
        });
        
        hideit = true;
                
        if (loc>0)
		{
    	    var items = $$('#slide'+n+' td');
      		items.each(function(item)  
    		{  
    			item.hasClass('item'+loc)?hideit=false:1;
			});
        } 
                               
        hideit==true?Sliders[n].hide():1;
      
	});
	
	if (loc>0)
	{
		toggleMenu(); 
		location = location;
		window.scrollBy(0,-100); 
		$('item'+loc).setStyle('background-color','#fcf3f3')
	} 

}

function hideSliders() {
 
	Sliders.each( function(item){
		item.slideOut();
		
	});
}
 
function showHints() {	
	var options = $$('#places_options div');
	var opt = $('options');
	options.each(function(item)
	{    	
		item.addEvent('mouseover',function() {
			opt.setText(item.getFirst().getProperty('title'));
		});
        	
		item.addEvent('mouseleave',function() {
			opt.setText('');
		});
	});
}

function deleteComment(rly,id) {
	var comm = $('comm_number_'+id);
	var buff = new Element('div');    

	buff.setStyle('opacity',0);       
	var b = new Element('div');     
	b.injectAfter(comm);
	
	
	new Ajax(rly ,{method: 'get', update: buff, onComplete: function() { 
		new Fx.Style(comm,'opacity', {duration:1000, wait:false,onComplete: function(){ 
			comm.remove();
			buff.injectAfter(b);
			new Fx.Style(buff,'opacity', {duration:1000, wait:false}).start(1);
			
			
		}}).start(0);
	
	}}).request();

}

function copyToBuffer(text)
{
  if (window.clipboardData) window.clipboardData.setData('Text',text);
  else
  {
    var flashcopier = 'flashcopier';
    if(!document.getElementById(flashcopier))
    {
      var divholder = document.createElement('div');
      divholder.id = flashcopier;
      
      document.body.appendChild(divholder);
      divholder.setStyle('display','none');
    }
    document.getElementById(flashcopier).innerHTML = '';
    var divinfo = '<embed src="style/clipboard.swf" FlashVars="clipboard='+escape(text)+
      '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashcopier).innerHTML = unescape(divinfo);
    $('copylink').setStyle('color','green'); 
  }

}

function doKrug() {
	
	function disableTime(obj) {
		obj.setStyle('background-color','#333333');
		obj.setProperty('readonly','true');
		obj.setProperty('value','0');
	}
	
	function enableTime(obj) {
		obj.setStyle('background-color','white');
		obj.setProperty('readonly','false'); 
		obj.setProperty('value','');
	}
	
	
	if ($('krug').getProperty('checked')) {
		
		disableTime($('utro'));
		disableTime($('vecher'));
		 
	}
	else
	{
		 enableTime($('utro'));
		enableTime($('vecher'));
	}
}