c = {}
c.d = document;
c.$ = function (i){return c.d.getElementById(i)};
c.newElement = function (type,props){el=c.d.createElement(type);for(pr in props){el[pr]=props[pr]}return el};

//________________

auto_tags = function(i){
	this.o = c.$(i);
	this.server = false;
	this.last = false;
	this.span = false;
	this.result = [];
	this.create();
}

auto_tags.prototype.create = function(){
	this.span = c.newElement('ul',{'className':'tag_tip'} );
	o = this.o;
	o.onkeyup = auto_tags.check;
	o.auto_tags_obj = this;
}

auto_tags.prototype.load = function(t){
	o = this;
	
	JsHttpRequest.query(
		this.server, {'tag':t}, function(rst, err){
		if ( err!='' ){
			o.error(err); 
			return false;
		 }else if ( rst!='' ){
			
			o.result =	eval('(' + rst + ')')
			o.render();
			return true;
		}
		},true
	);
	

}


auto_tags.check = function(e){
	o = this.auto_tags_obj;
	txt = this.value;
	tags = txt.split(',');
	txt = tags[tags.length-1];
	txt = txt.replace(/\s/g,'');
	o.result = [];
	if ( txt.length>1 ){
		if ( txt!=this.last ){
			o.load(txt);
		}
	}
	o.render();
}

auto_tags.prototype.render = function()
{
	
	if ( this.result.length==0 ){
		this.span.style.display="none";
		return false;
	}
		
	this.span.innerHTML = '';
	//lst = c.newElement('ul',{});
	for(i=0;i<this.result.length;i++){
		if ( this.result[i]==undefined ){
			continue;
		}
		
		el = c.newElement('li',{'innerHTML':this.result[i]});
		el.onclick = auto_tags.add;
		el.auto_tags_obj = this;
		this.span.appendChild(el);
	}
	//=this.result
	
	this.span.style.display = 'inline';
	
	points = absPosition(this.o);
	this.span.style.left=points.x+'px';
	
	this.span.style.top=points.y+20+'px';
	
	document.body.appendChild(this.span);
	
}
auto_tags.prototype.error = function(e)
{
	alert(e);
}


auto_tags.add = function(){
	
	value = this.innerHTML;
	o = this.auto_tags_obj;
	tags = txt.split(',');
	txt = tags[tags.length-1];
	if ( txt.length>1 ){
		
		reg_ex = new RegExp().compile(txt+"$","");
		o.o.value = o.o.value.replace(reg_ex,value+', ');
		
		o.span.style.display="none";
		o.o.focus();
	}else{
		o.o.value=value+', ';
	}
}


function absPosition(obj) { 
      var x = y = 0; 
      while(obj) { 
            x += obj.offsetLeft; 
            y += obj.offsetTop; 
            obj = obj.offsetParent; 
      } 
      return {x:x, y:y}; 
}


city = {}
city.load = function(){
	
	JsHttpRequest.query(
		city.server, {'country_id':c.$('u_country').options[c.$('u_country').selectedIndex].value}, function(rst, err){
		if ( err!='' ){
			city.error(err); 
			return false;
		 }else if ( rst!='' ){
			c.$('u_city').innerHTML = rst['u_city'];
		}
		},true
	);
}

city.error = function(msg){
	alert(msg);
}

win_obj = {};
win_obj.back_func = false;
win_obj.resize = function(){this.$.style.height = c.$('window_content').style.height+70}
win_obj.keydown=function(e){e=e || window.event;key=e.charCode || e.keyCode;if(key==27)win_obj.close()}
win_obj.content=function(m){this.wcontent=m}
win_obj.title=function(m){this.wtitle=m}

win_obj.load = function(server,w,h){
  
  JsHttpRequest.query(
    server, {}, function(rst, err){
	 // win_obj.load_img(0);
	  if ( err!='' ){
		
	    alert(err); 
		return false;
      }else if ( rst!='' ){
	    win_obj.content(rst.content);
		win_obj.title(rst.title);
		win_obj.show(w,h);
		win_obj.resize();
	  }
	},true
  );
  return false;
  //win_obj.load_img(1);	
}


win_obj.close = function(){


if(c.$('modal_wnd')){c.$('modal_wnd').parentNode.removeChild(c.$('modal_wnd'))}if(c.$('background')){c.$('background').parentNode.removeChild( c.$('background') );}

return false;

}

win_obj.show = function(width,height){

  if ( !c.d.body ){return false} //IE не поддерживает
  this.$ = false;
 
  this.background = false;
  if ( c.$('modal_wnd') ){
	this.close();
  }
 
  this.$ = c.d.createElement("div");
  this.background = c.d.createElement('div');
  //  вешаем события
 
  this.background.onclick = "win_obj.close()";
  
  window.onkeydown = function(e){ win_obj.keydown(e) };
  //return false;
	//устанавливаем бэкграунд
  this.background.id =  this.background.className = 'background';
 
  this.background.style.height = c.d.body.scrollHeight+'px'; 
  this.background.style.width = c.d.body.scrollWidth+'px'; 
 
  c.d.body.appendChild(this.background);
  // формируем окно
  this.$.className='message';
  this.$.style.display = 'none';
  this.$.id='modal_wnd';
  c.d.body.appendChild(this.$);
  this.$.innerHTML ='<span style="float:right;color:#626456;margin:5px;"><a  style="text-decoration:none;cursor:pointer"  onclick="return win_obj.close()"><img src="/source/img/close.gif"></a></span>';
  this.$.style.width=width+'px' ;
  this.$.style.height=height+'px' ;
 
  
  this.$.innerHTML+= '<div class="message_title" id="window_title">'+ this.wtitle+'</div> ';
 
 
  
  
  this.$.innerHTML+= '<div id="window_content" >'+this.wcontent+'</div>';
  
  this.$.style.left = ( this.inner_width() - width)/2+'px';
  this.$.style.top = (this.inner_height()  - height)/ 2+this.page_y_offset()+'px';

  this.background.style.display = 'block';
  this.$.style.display = 'block';
  
  this.background.style.height = c.d.body.scrollHeight+'px'; 
  this.background.style.width = c.d.body.scrollWidth+'px'; 
  c.$('window_content').style.height=(height-70)+'px' ;
 
  if ( this.back_func ){
	eval( this.back_func+'()');
  }
  
}


win_obj.inner_width = function(){if ( !window.innerWidth){return (c.d.documentElement && c.d.documentElement.clientWidth) || (c.d.body && c.d.body.clientWidth);}return window.innerWidth}
win_obj.inner_height = function(){if ( !window.innerHeight){return (c.d.documentElement && c.d.documentElement.clientHeight) || (c.d.body && c.d.body.clientHeight);}return window.innerHeight}
win_obj.page_y_offset = function(){return self.pageYOffset || (c.d.documentElement && c.d.documentElement.scrollTop) || (c.d.body && c.d.body.scrollTop);}

upload_ajax = {};
	upload_ajax.result_name = false;		//	результат работы
	upload_ajax.result_crop_image = false; 	//	результат работы кропа
	upload_ajax.back_func = false; 			//	функция обратного вызова
	upload_ajax.FLAG_REQUEST = false;		//	флаг посылки запроса
	upload_ajax.FLAG_CROP = false;			//	флаг обрезания изображения
	upload_ajax.max_size=500000;			// 500 кб
	upload_ajax.max_width=false;		
	upload_ajax.max_height=false;		
	upload_ajax.server = '/?p_name=ajax_upload_img';
	
		//	загрузка изображения размера x,y с возвращением результата работ в 
	upload_ajax.load_images = function(e){
		if (!e)e=window.event;
		if ( !e.srcElement) e.srcElement=e.target
			//	получаем объект по которому кликнули 
		o = e.srcElement;
			//	изображение требует обрезания
		if ( o.upl_FLAG_CROP ){
			upload_ajax.x = o.upl_x;
			upload_ajax.y = o.upl_y;
			upload_ajax.FLAG_CROP = true;
		}
			// устанавливаем с каким объектом нам сейчас работать
		upload_ajax.back_obj = o.upl_back_func
		
			//	куда сообщать о успешной загрузки окна
		win_obj.back_func = 'upload_ajax.init';
			//	выводим окно диалога для пользователя
		win_obj.load("/?p_name=ajax_upload_img&act=form&max_size="+upload_ajax.max_size,500,570);
		
	}
	
		//	выполняется в случае удачной загрузки всплывающего окна 
		//	с формой загрузки изображения
	upload_ajax.init = function(){
		c.$('ua_file').onchange = function(e){upload_ajax.select(e)};
		c.$('ua_button').onclick = function(){upload_ajax.load()};
		c.$('ua_button').disabled = true;
		
		c.$('ua_error').style.display='none';
		c.$('ua_frame').style.display = 'none';
		c.$('ua_status').style.display = 'none';
		upload_ajax.FLAG_REQUEST = false;
	}
	
		//	реакция на выбор файла с компьютра пользователя
	upload_ajax.select = function(e){
		if ( c.$('ua_file').value ){
			c.$('ua_button').disabled = false;
		}else{
			c.$('ua_button').disabled = true;
		}
	}
	
		//	реакция на клик по кнопке загрузки
	upload_ajax.load = function(){
		c.$('ua_button').disabled = true;
		c.$('ua_status').style.display = 'block';
		c.$('ua_error').style.display = 'none';
		upload_ajax.FLAG_REQUEST = true;
		
		JsHttpRequest.query( 
			upload_ajax.server, 
			{ 'max_width':upload_ajax.max_width,'max_height':upload_ajax.max_height,'ua_file':c.$('ua_file'),'act':'upload','max_size':upload_ajax.max_size },
			function(rst, err){ upload_ajax.result(rst, err) },
			true
		);
	}
	
		//	обработка результата
		//	скрипт возвращает имя загруженнго полноразмерного файла
		//	и его пропорционально уменьшенные высоту и ширину
	upload_ajax.result = function(rst, err){
		
		c.$('ua_status').style.display = 'none';
		if ( err!='' ){
			upload_ajax.error(err);
		}else{
			//	пишем имя полученного файла
			upload_ajax.result_name = rst.name
			
			//upload_ajax.preview_name = rst.preview
				//	если нужен кроп и изображение не пропорционально
			if ( upload_ajax.FLAG_CROP && !rst.proportions ){
				//	выводим фрейм
				c.$('ua_frame').src="/?p_name=ajax_upload_img&act=frame&crop_width="+upload_ajax.x+"&crop_height="+upload_ajax.y+"&name="+ rst.name+'&preview_width='+rst.width+'&preview_height='+rst.height;
				c.$('ua_frame').style.display='block';
				c.$('ua_file').disabled = true;
			}else{
					//	возвращаем результат
				upload_ajax.end_work(true)
			}
		}
	}
		
		//	 обрезание изображение
	upload_ajax.save_crop = function(w,h,l,r){
		
		JsHttpRequest.query( 
				upload_ajax.server, 
				{ 'name':upload_ajax.result_name,
				'act':'crop','w':w,'h':h,'l':l,'r':r ,
				'size_x':upload_ajax.x,'size_y':upload_ajax.y
				},
				function(r,e){
					if ( e!='' ){
						upload_ajax.error(e);
					}else{
						
						upload_ajax.result_crop_image = r.crop_image;
						upload_ajax.end_work(true);
					}
				},
				true
		);
	}
		//	возвращение результата в функцию обратного вызова
	upload_ajax.end_work = function(flag){
		if ( upload_ajax.back_obj){
			upload_ajax.back_obj.result(flag,upload_ajax.result_name,upload_ajax.result_crop_image);
		}
		win_obj.close();
	}
	
	upload_ajax.delete_image = function(name){
		if ( name ){
			JsHttpRequest.query( 
				upload_ajax.server, 
				{ 'name':name,'act':'delete' },
				function(r,e){},
				true
			);
		}else if( upload_ajax.result_name ){
			
			JsHttpRequest.query( 
				upload_ajax.server, 
				{ 'name':upload_ajax.result_name,'act':'delete' },
				function(r,e){
					if ( e!='' ){
						upload_ajax.error(e);
					}else{
							// сообщаем что файл удалён
						upload_ajax.error(r.result);
						upload_ajax.result_name = false;
					}
				},
				true
			);
		}
	}
	
			//	вывод ошибок
	upload_ajax.error = function(error){
		upload_ajax.result_name = false;
		c.$('ua_error').innerHTML = error;
		c.$('ua_error').style.display = 'block';
		c.$('ua_button').disabled = false;
		c.$('ua_frame').style.display='none';
		c.$('ua_file').disabled = false;
	}
	
	//___________________________________________
	
	
	//	функция создаёт объект для загрузки одного или нескольки изображения 
	
	upload = function(name){
	  this.max_files = 1;
	  this.files=0;
	  this.active_img = this.load = this.btn = this.img = false;
	  if ( !c.$(name) ) {
		alert('Ошибка: контейнер "'+name+'" не существует!');
		return false;
	  }
	  this.prnt = c.$(name);
	  this.def_url = '/source/tmpl/img/upload.gif';
	  this.elements = new Array();
	  this.FLAG_CROP = false;
	}
	
	
	upload.prototype.create = function(){
			//	если картинка присутствует, то удаляем её
		if ( this.control ){
			this.control = false
		}
			
		this.elements[ this.elements.length ] = false;
		if ( this.max_files==this.files ){ return false }
		this.control = c.newElement('img',{
			'id':'upl_img_'+ this.elements.length,
			'src':this.def_url,
			'onclick':function(e){ upload_ajax.load_images(e) }
			}
		);
		this.control.style.cursor='pointer';
		this.prnt.appendChild(this.control);
			//	используем созданное изображение как контейнер некоторых переменных
		this.control.upl_x = this.x;
		this.control.upl_y = this.y
		this.control.upl_FLAG_CROP = this.FLAG_CROP;
		this.control.upl_back_func = this;
			//	изображение готово
		this.active_img = true;
	}
	
	
	upload.prototype.result = function(flag,name,crop_name){
		
		if ( !crop_name){
			 crop_name = name;
		}
		
		if ( flag ){
			
			//name = upload_ajax.result_name
			//crop_name = 'crop_'+name;
			
				//	заносим элемент в список
			this.elements[  this.elements.length-1 ] = {'img':name,'crop_img':crop_name};
			
				//	обновляем изображение
			this.control.src="/source/modules/ajax/tmp/"+crop_name;
			this.control.style.width='100';
			this.control.onclick=function(){window.open("/source/modules/ajax/tmp/"+name,'',''); return false}
				//	создаём ссылку для удаления
		
			lnk = c.newElement('img',{
				'id':'del_img_'+this.elements.length,
				'src':'/source/tmpl/img/false.png',
				'upl_obj':this,
				'upl_control_id':this.elements.length,
				'onclick':function(e){ upload.prototype.delete_image(e) }
				
				} 
			);
			
			this.prnt.appendChild(lnk);
			lnk.style.position='relative';
			lnk.style.cursor='pointer';
			
			lnk.style.left=(lnk.style.left-20)+'px'
			
			
				//	создаём контрол для передачи на сервер
			lnk = c.newElement('input',{
				'id':this.name_control+'['+this.elements.length+']',
				'type':'hidden',
				'name':this.name_control+'['+this.elements.length+']',
				'value':name
			} );
			this.prnt.appendChild(lnk);
			
			this.files++;
			this.active_img = false;
			this.create();
		}
	}
	upload.prototype.delete_image = function(e){
		if (!e)e=window.event;
		if ( !e.srcElement) e.srcElement=e.target
		
		o = e.srcElement.upl_obj;
		id = e.srcElement.upl_control_id;
		
		o.prnt.removeChild( c.$('upl_img_'+id) );
		o.prnt.removeChild( c.$('del_img_'+id) );
		o.prnt.removeChild( c.$( o.name_control+'['+id+']') );
		upload_ajax.delete_image( o.elements[id].result_name );
		if ( o.elements[id].result_crop_image ){
			upload_ajax.delete_image( o.elements[id].result_crop_image );
		}
		o.files--;
		
		if ( !o.active_img)
		o.create();
		
	}
	
	upload.prototype.set_output = function(name){
		this.name_control = name;
	}
	
	upload.prototype.set_crop = function(x,y){
		this.FLAG_CROP = true;
		this.x = x;
		this.y = y;
	}
	upload.prototype.set_max_size = function(s){
		upload_ajax.max_size = s;
	}
	upload.prototype.set_max_height = function(s){
		upload_ajax.max_height = s;
	}
	upload.prototype.set_max_width = function(s){
		upload_ajax.max_width = s;
	}
	
//____________

comments = {};

comments.ini = function(a,e,d){

	this.view_answer = a;
	this.view_edit = e;
	this.view_delete = d;
		//когда документ загрузится
	
	if (document.addEventListener) {
		document.addEventListener("DOMContentLoaded", comments.load, false);
	}else{
		window.onload = comments.load;
	}
	
}

	//	скрываем и раскрываем списки
comments.status = function(o){
	li=o.parentNode;
	if ( li.className=='' ){li.className='close'}else{li.className=''}
}
	
	//	нужно решить, какие ссылки показывать пользователю
	//	по-этому мы получаем все ссылки связанные с классами 
comments.load = function(){
	if(c.$('answer_msg') == null)
	{
		return;
	}
	c.$('answer_msg').innerHTML = '';
	
	c.$('comment_btn').onclick = function(){ comments.add(false ) }
	links = document.getElementsByTagName('A');
	l = links.length;
	for(i=0;i<l;i++){
		switch(links[i].className){
			case('answer_link'):
				if ( comments.view_answer ){
					links[i].style.display="inline";
				}
				break;
			case('edit_link'):
			if ( comments.view_edit ){
					links[i].style.display="inline";
				}
				break;
			case('del_link'):
			if ( comments.view_delete ){
					links[i].style.display="inline";
				}
				break;
		}
		
	}
}
	//	добавление нового комментария/ответ на комментарий
	//	id - номер комментария на который отвечаюь
	//	если id пуст, то значит просто добавляют новый комментарий
comments.add = function(id){
	text = c.$('msg').value;
	if ( text=='' ){
		comments.error('EMPTY_MSG');
		return false;
	}
		
	if ( false==id){
		id = comments.comment_id
	}
	JsHttpRequest.query(
		comments.server+'&act=ajax_articles_add_comment', {'msg':text,'c_id':id}, function(rst, err){
		if ( err!='' ){
			comments.error(err); 
			return false;
		 }else if ( rst!='' ){
			comments.insert_before(rst['id'],rst['html']);
		}
		},true
	);
	c.$('msg').value = '';
}

comments.insert_before= function(id,html){
	o =c.$('l'+id);
	if ( o.tagName=='UL' ){
		//для комментария
		o.innerHTML = o.innerHTML+html;
	}else if( o.tagName=='LI'  ){
		//	для ответа
		list = o.childNodes
		ul = false;
		for( pr in list ){
			if ( list[pr].tagName=='UL'){
				//	если уже есть ответы, то находим список, в котором они хранятся
				ul=list[pr];
				break;
			}
		}
		if ( ul==false){
			//это первый ответ на комментарий, нужно для него создать список
			ul = c.newElement('ul');
			o.appendChild(ul);
		}
			//	добавляем новый комментарий в конец списка
		ul.innerHTML = ul.innerHTML+html;
	}
	comments.load();
}

comments.error = function(type){
	switch(type){
		case('EMPTY_MSG'):
			alert('Нужно написать текст комментария!')
			break;
		default:
			alert(type);
			break;
	}
}
	//	фокус указывает на редактор
comments.answer = function(id,name){
	c.$('comment_btn').onclick = function(){ comments.add(id) }
	c.$('answer_msg').innerHTML = 'Ответить на комментарий <b>'+name+'</b>';
	c.$('msg').focus();
}

	//	в редакторе выводится текст комментария
comments.edit = function(id){
	o =c.$('l'+id);
	list = o.childNodes
	text = '';
	for( pr in list ){
		if ( list[pr].tagName=='DIV' && list[pr].className=='comment' ){
			text=list[pr].innerHTML;
			break;
		}
	}
	c.$('msg').value=undohtmlspecialchars(undobr(text));
	c.$('comment_btn').onclick = function(){ comments.save(id) }
	c.$('msg').focus();
}


	//	удаление комментария с id
comments.del = function(id){
	o =c.$('l'+id);
	list = o.childNodes
	text = '';
	for( pr in list ){
		if ( list[pr].tagName=='DIV' && list[pr].className=='comment' ){
			o = list[pr];
			continue;
		}
	}
	list =	o.childNodes
	
	for( pr in list ){
		if ( !list[pr] ){
			continue;
		}
		if ( list[pr] && list[pr].tagName=='A' && list[pr].className=='edit_link' ){
			list[pr].parentNode.removeChild(list[pr]);
		}
		if ( list[pr] && list[pr].tagName=='A' && list[pr].className=='' ){
			list[pr].parentNode.removeChild(list[pr]);
		}
		if ( list[pr] && list[pr].tagName=='A' && list[pr].className=='del_link' ){
			list[pr].parentNode.removeChild(list[pr]);
		}
		if ( list[pr] && list[pr].tagName=='IMG' && list[pr].className=='ava' ){
			list[pr].parentNode.removeChild(list[pr]);
		}
		if ( list[pr] && list[pr].tagName=='A' && list[pr].className=='answer_link' ){
			list[pr].parentNode.removeChild(list[pr]);
		}
	}
	
	JsHttpRequest.query(
		comments.server+'&act=ajax_articles_del_comment', {'c_id':id}, function(rst, err){
		if ( err!='' ){
			comments.error(err); 
			return false;
		 }else if ( rst!='' ){
			
			list = c.$('l'+id).childNodes
			div = false;
			for( pr in list ){
				if ( list[pr].tagName=='DIV' && list[pr].className=='comment' ){
					div=list[pr]
					break;
				}
			}
			div.innerHTML = rst['html']
		}
		},true
	);
	
}
	//	id номер изменяемого комментария
comments.save = function(id){
	text = c.$('msg').value;
	if ( text=='' ){
		comments.error('EMPTY_MSG');
		return false;
	}
		
	JsHttpRequest.query(
		comments.server+'&act=ajax_articles_mod_comment', {'msg':text,'c_id':id}, function(rst, err){
		if ( err!='' ){
			comments.error(err); 
			return false;
		 }else if ( rst!='' ){
			list = o.childNodes
			div = false;
			for( pr in list ){
				if ( list[pr].tagName=='DIV' && list[pr].className=='comment' ){
					div=list[pr]
					break;
				}
			}
			div.innerHTML = rst['html']
		}
		},true
	);
	c.$('msg').value = '';
	comments.load();
}
function undohtmlspecialchars(text)
{
   var  replacements= Array("&", "<", ">", '"', "'");
   var chars  = Array("&amp;", "&lt;", "&gt;", "&quot;", "'");
   for (var i=0; i<chars.length; i++)
   {
       var re = new RegExp(chars[i], "gi");
       if(re.test(text))
       {
           text = text.replace(re, replacements[i]);
       }
   }
   return text;
}

function undobr(text)
{
   var  chars = Array("<br/>","<br />","<br>");
   var  replacements=  Array("\n","\n","\n");
   for (var i=0; i<chars.length; i++)
   {
       var re = new RegExp(chars[i], "gi");
       if(re.test(text))
       {
           text = text.replace(re, replacements[i]);
       }
   }
   return text;
}function domReady(f)
{
    // Если DOM уже загружена, немедленно выполнить функцию
    if (domReady.done) return f();
 
    // Если мы уже дополнили функцию
    if (domReady.timer) {
        // внести ее в список исполняемых
        domReady.ready.push(f);
    }else{
        // Подключение события завершения загрузки страницы
        // на тот случай, если ее загрузка закончится первой.
        addEvent(window, 'load', isDOMReady);
        test = function() {alert(111);}
        addEvent(window, 'load', test);
        // Инициализация массива исполняемых функций
        domReady.ready = [f];
 
        // Проверка DOM на готовность, проводимая как можно быстрее
        domReady.timer = setInterval(isDOMReady, 13);
    }
}
// Проверка DOM на готовность к перемещению по ее структуре
function isDOMReady()
{
    // Если мы уже определили готовность страницы - проигнорировать
    // дальнейшее выполнение
    if (domReady.done) return false;
 
    // Проверка доступности некотрых функций и элементов
    if(document && document.getElementsByTagName && document.getElementById && document.body) {
    alert(document.getElementById('search_module'))
        // Если они готовы, можно прекратить проверку
        clearInterval(domReady.timer);
        domReady.timer =  null;
        //removeEvent(window, 'load', isDOMReady);
 
        // Выполнение всех ожидавших функций
        for (var i = 0; i< domReady.ready.length; i++) {
            domReady.ready[i]();
        }
 
        // Сохранение того, что только что было сделано
        domReady.ready = null;
        domReady.done = true;
    }
}

