// JavaScript Document
function todo(){
	this.action=[];
	this.execute=function(){if(!this.action)return;for(var i in this.action)try{this.action[i]();}catch(er){alert('todo >> "'+er.message+'" in "'+er.fileName+'" on "'+er.lineNumber+'"');};this.action=null;};
	var onLoadAction=function(o){return function(){o.execute();}}(this);
	if(document.addEventListener)document.addEventListener('DOMContentLoaded',onLoadAction,false);
	else if(document.attachEvent)document.attachEvent('onreadystatechange',function(){if(document.readyState==='complete')onLoadAction();});
	else if(window.addEventListener)window.addEventListener('load',onLoadAction,false);
	else if(window.attachEvent)window.attachEvent('onload',onLoadAction);
};
todo.prototype.get=function(id){return document.getElementById(id);};
todo.prototype.getNextNode=function(e){var n=e;while(n=n.nextSibling)if(todo.isTag(n))return n;return null;};
todo.prototype.getFirstChild=function(e){var n=e.firstChild;while(!todo.isTag(n)){n=n.nextSibling;if(!n)return null;};return n;};
todo.prototype.getAncestor=function(e,tagName){var n=e;while(n=n.parentNode){if(n.tagName.toLowerCase()==tagName.toLowerCase())return n;};return null;};
todo.prototype.isTag=function(n){var nn=n.nodeName.toLowerCase();switch(nn){case '#text':case '#comment':return false;};return true;};
todo.prototype.create=function(tag,attrs,text,style){var e=document.createElement(tag);if(attrs)for(var i in attrs)switch(i){case 'class': e.className=attrs[i];break;case 'id': e.id=attrs[i];break;default: e.setAttribute(i,attrs[i]);break;};if(text)e.appendChild(document.createTextNode(text));if(style)for(var i in style)e.style[i]=style[i];return e;};
todo.prototype.onload=function(func){this.action[this.action.length]=func;};
todo.prototype.importScript=function(src){document.getElementsByTagName('head')[0].appendChild(this.create('script',{'type':'text/javascript','src':src}));};
todo.prototype.stopEvent=function(e){var e=e || window.event;if(e.stopPropagation)e.stopPropagation();else e.cancelBubble=true;if(e.preventDefault)e.preventDefault();else e.returnValue=false;}
todo=new todo();

function isEmail(email){
	var pattern = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	return pattern.test(email);
};
/**
* Сортировка
* сохраняем сортировку для заданного формата
* таблицы в cookies и обновляем страницу
*/
function srt(type,col,dest){
	var cookies=new Cookie('offer_list_sort',null,'/')
		new_cookie=col+(dest?'asc':'desc');
	cookies.load();
	if(new_cookie!=cookies[type]){
		cookies[type]=new_cookie;
		cookies.store();
		window.location.reload();
	}
};
todo.onload(function(){
	// ---------- FAVORITS
	try{
		var cookies = new Cookie('favorites',null,'/'),
			favorites=[]; /* массив с отмеченными звездами */
		cookies.load();
		if(cookies.favorites)favorites=cookies.favorites.split(',');
		todo.get('chooseSize').innerHTML=favorites.length;
		favorites._check=function(value){
			for(var i=0;i<this.length;i++)if(this[i]==value)return true;
			return false;
		};
	}catch(er){};
	/**
	* раздел избранное
	*/
	var tbl=document.getElementsByTagName('table');
	for(var k=0;k<tbl.length;k++){
		if(tbl[k].className!='table_favorites')continue;
		var img=tbl[k].getElementsByTagName('img');
		for(var i=0;i<img.length;i++){
			if(img[i].className!='favorites_button')continue;
			img[i]._cookies=cookies;
			img[i]._id=function(){return this.id.substr(6);};
			img[i].style.cursor='pointer';
			img[i].onclick=function(){
				if(!confirm('Подтвердите удаление!'))return;
				var ar=[],
					favorites=[],
					tr=this.parentNode.parentNode;
				if(this._cookies.favorites)favorites=this._cookies.favorites.split(',');
				for(var i=0;i<favorites.length;i++)
					if(favorites[i]==this._id() || !favorites[i])continue;
					else ar[ar.length]=favorites[i];
				this._cookies.favorites=ar.join(',');
				this._cookies.store();
			}
		}
	};
	var delete_all=todo.get('favorites_delete_all');
	if(delete_all){
		delete_all._cookies=cookies;
		delete_all.onclick=function(){
			if(!confirm('Подтвердите удаление!'))return;
			this._cookies.favorites='';
			this._cookies.store();
			return true;
		}
	};
	/**
	* таблица заявок
	*/
	try{
		var table=document.getElementsByTagName('table');
		for(var k=0;k<table.length;k++){
			if(table[k].id!='table_list'
				&& table[k].className!='table_favorites')continue;
			var td = table[k].getElementsByTagName('td');
			for(var i=0;i<td.length;i++){
				if(td[i].className=='star' || td[i].className=='star_selected'){
					/* устанавливает состояние звезды */
					td[i]._setState=function(value){
						this.className='star'+(value ? '_selected' : '');
						try{this.getElementsByTagName('img')[0].src='/images/ico_star'+(value ? '_s' : '')+'.gif';}catch(er){}
					};
					/* возвращает состояние звезды */
					td[i]._getState=function(){
						if(this.className=='star_selected')return true;
						return false;
					};
					/* возвращает айди */
					td[i]._id=function(value){
						var img=this.getElementsByTagName('img')[0],
							id=0;
						if(img){
							img.src='/images/ico_star'+(value ? '_s' : '')+'.png';
							id=img.className.substr(6);
						};
						return id;
					};
					if(favorites._check(td[i]._id()))td[i]._setState(true);
					else td[i]._setState(false);
					td[i]._cookies=cookies;
					td[i].onclick=function(){
						var favorites=[];
						if(this._cookies.favorites)favorites=this._cookies.favorites.split(',');
						if(this._getState()){
							var ar=[];
							for(var i=0;i<favorites.length;i++)
								if(favorites[i]==this._id() || !favorites[i])continue;
								else ar[ar.length]=favorites[i];
							this._cookies.favorites=ar.join(',');
							todo.get('chooseSize').innerHTML=ar.length;
						}else{
							favorites[favorites.length]=this._id();
							this._cookies.favorites=favorites.join(',');
							todo.get('chooseSize').innerHTML=favorites.length;
						};
						this._setState(!this._getState());
						this._cookies.store();
					}
				}else if(!td[i].className){
					/* расставляем ссылки на ячейки таблицы */
					td[i].style.cursor='pointer';
					td[i].onclick=function(){
						var a=this.parentNode.getElementsByTagName('a'),
							_link=null;
						for(var i=0;i<a.length;i++){
							if(a[i].className!='row_link')continue;
							window.location.href=a[i].href;
							return;
						}
					}
				}
			}
		}
	}catch(err){};
	// ---------- TOP MENU
	var table = document.getElementById('menu');
	var td = table.getElementsByTagName('td');
	var links=[];
	
	var open_menu = function(id){
		links[id].ul.style.display = 'block';
		//if(links[id].span.parentNode.className != 'selected') links[id].span.style.backgroundColor = '#2675d6';
	}
	
	var close_menu = function(id){
		if(links[id].td_over) return;// если мыш еще не вышла за границы ячейки
		if(links[id].ul_over) return;// если мыш еще не вышла за границы списка
		links[id].ul.style.display = 'none';
		//if(links[id].span.parentNode.className != 'selected') links[id].span.style.backgroundColor = '#014ba7';
	}
	
	for(var i=0; i<td.length; i++){
		td[i].ul = td[i].getElementsByTagName('div');
		if (td[i].ul.length == 0) continue;
		
		var span = td[i].getElementsByTagName('span');
		span = span[0];
		
		var ul = td[i].ul[0];
		var id = links.length;
		
		var width = parseInt(td[i].offsetWidth) - 50;
		var a_links = td[i].ul = td[i].getElementsByTagName('a');
		if( width > 60){
			for(var d = 0; d< a_links.length; d++){
				a_links[d].style.width = width+ 'px';
			}
		}
		
		links.push({ 'td':td[i], 'ul':ul, 'span':span, 'td_over':false, 'ul_over':false });
		td[i].id = id;
		ul.id = id;
		
		td[i].onmouseover = function(e){
			links[this.id].td_over = true;
			open_menu(this.id);
		}
		ul.onmouseover = function(e){
			links[this.id].ul_over = true;
			open_menu(this.id);
		}
		td[i].onmouseout = function(e){
			links[this.id].td_over = false;
			close_menu(this.id);
		}
		ul.onmouseout = function(e){
			links[this.id].ul_over = false;
			close_menu(this.id);
		}
	}
	// ---------/TOP MENU


	// --------- LEFT MENU
	var li=todo.get('leftbar').getElementsByTagName('li'),
		a,
		flag,
		flag_level=false;
	for(var i=0,l=li.length;i<l;i++){
		a=li[i].getElementsByTagName('a')[0];
		flag=a.className=='selected';
		switch(li[i].className){
			case 'level_1':
				flag_level=flag;
				break;
			case 'level_2':
				if(!flag_level){
					li[i].style.height='0';
					li[i].style.overflow='hidden';
				};
			default:
				continue;
		};
		
		if(flag)li[i]._isOpen=function(){return true;}
		else li[i]._isOpen=function(){return false;}
		li[i]._roll=function(display){
			if(!this._nn){
				this._nn=this;
				this._timerId=window.setInterval(function(e,display){return function(){e._roll(display);}}(this,display),70);
			}
			this._nn=todo.getNextNode(this._nn);
			if(this._nn && (this._nn.className=='level_2')){
				if(display=='none'){
					this._nn.style.height='0';
					this._nn.style.overflow='hidden';
				}else{
					this._nn.style.height='auto';
					this._nn.style.overflow='auto';
				}
			}else if(this._nn && this._nn.className=='level_3'){
				this._nn.style.display=display;
			}else if(this._timerId){
				window.clearInterval(this._timerId);
				this._timerId=this._nn=null;
				if(display=='none')this._isOpen=function(){return false;}
				else this._isOpen=function(){return true;}
			}
		};
		li[i]._hasChildren=function(){
			var nn=todo.getNextNode(this);
			if(nn && nn.className=='level_2') return true;
			return false;
		}
		
		if(li[i]._hasChildren()){
			a.onclick=function(){
				if(this.parentNode._isOpen())this.parentNode._roll('none');
				else this.parentNode._roll('block');
				return false;
			}
		}
	}
});

