// подпись
window.defaultStatus="Developed by IT Avenue";
// определение браузера
var cmBrowser="";
if(/Gecko/.test(navigator.userAgent)) cmBrowser="gecko";
else if(/Opera/.test(navigator.userAgent)) cmBrowser="opera";
else if(/MSIE/.test(navigator.userAgent)) cmBrowser="ie";
// текущая страница
var cmPageUrl="";
var cmPageReferer="";
/*window.onunload=function(e){
	if(location.href.indexOf('index.php?m_code=infc_main'))
		location.href='index.php?m_code=infc_main&url='+escape(cmPageUrl);
	return false;
};*/
// можно отлавливать клавиши навигации ctrl+left, ctrl+right
/*window.onkeypress=function(e){
e=(e?e:window.event);
alert(e.shiftKey);
alert(e.altKey);
alert(e.ctrlKey);
}
document.onkeypress=function(e){
e=(e?e:window.event);
alert(e.shiftKey);
alert(e.altKey);
alert(e.ctrlKey);
}
document.onkeydown=function(e){
e=(e?e:window.event);
alert(e.altKey);
}*/

// доступ к элементам
function cmGetById(id){ // по id
	return document.getElementById(id);
}
function cmGetByName(id){ // по name
	return document.getElementsByName(id);
}
function cmGetByTag(id){ // по tagName
	return document.getElementsByTagName(id);
}

/*// редирект на заданный url
function cmRedirect(url,noloading){
	if(!noloading) cmLoadingShow();
	location.href=url;
}
// отправка фомры на заданный url
function cmFormSubmit(form,url,noloading){
	if(!noloading) cmLoadingShow();
	var f=document.forms[form];
	f.action=url;
	f.submit();
}*/
// выбрать все галочки (checkbox)
function cmRecordSelectAll(form){
	var f=document.forms[form],selected=false;
	for(i=0; i<f.elements.length; i++)
		if(f.elements[i].name && f.elements[i].name.substr(0,3)=="Id[")
			if(f.elements[i].checked)
				selected=true;
	for(i=0; i<f.elements.length; i++)
		if(f.elements[i].name && f.elements[i].name.substr(0,3)=="Id[")
			f.elements[i].checked=!selected;
}
// проверить все галочки (checkbox)
function cmRecordCheckAll(form){
	var f=document.forms[form],count=0;
	for(i=0; i<f.elements.length; i++){
		if(f.elements[i].name && f.elements[i].name.substr(0,3)=="Id[")
			if(f.elements[i].checked)
				count++;
	}
	if(count)
		return confirm("Кол-во выбранных записей: "+count+".\nУдалить?");
	return true;
}
// показать объект в определенной позиции
function cmShow(name,l,t){
	name=name.toString();
	if(document.getElementById(name)&&document.getElementById(name).style){
		if(!document.getElementById(name).style.left)
			document.getElementById(name).style.left=l;
		if(!document.getElementById(name).style.top)
			document.getElementById(name).style.top=t;
		document.getElementById(name).style.display="block";
	}
}
// спрятать объект
function cmHide(name){
	if(document.getElementById(name)&&document.getElementById(name).style)
		document.getElementById(name).style.display="none";
}
// id для меню
var mnId="";
// показать меню
function mnShow(mId,content,l,t){
	mnId=mId;
	var menuName='menu_'+mnId;
	var menuParentName='menu_parent_'+mnId;
	//document.getElementById(menuParentName).style.position="relative";
	cmShow(menuName,(l?l:0),(t?t:document.getElementById(menuParentName).offsetHeight));
	document.getElementById(menuParentName).style.zIndex=499;
	document.getElementById(menuName).style.zIndex=500;
	if(cmBrowser=='ie') document.getElementById(menuName).style.width='1px';
	if(content) document.getElementById(menuName).innerHTML=content;
	if(window.event) window.event.returnValue=false;
}
// спрятать меню
function mnHide(){
	if(mnId){
		var menuName='menu_'+mnId;
		var menuParentName='menu_parent_'+mnId;
		if(document.getElementById(menuName)&&document.getElementById(menuParentName)){
			//document.getElementById(menuParentName).style.position="";
			document.getElementById(menuParentName).style.zIndex=1;
			document.getElementById(menuName).style.zIndex=1;
			cmHide(menuName);
		}
	}
}
// меню действий для записи
function mnActionsShow(mId,actions){
	var menu='';
	for(i in actions){
		if(menu) menu+='<tr><td class="spl">&nbsp;</td></tr>';
		menu+='<tr><td onclick="cmActionRedirect(\''+actions[i]['Url']+'\',\''+actions[i]['Code']+'\');" class="el" onmouseover="this.className=\'act\';" onmouseout="this.className=\'el\';">'+actions[i]['Name']+'</td></tr>';
	}
	menu='<table cellpadding="0" cellspacing="0" onselectstart="return false;" class="actions">'+menu+'</table>';
	mnShow(mId,menu,'5px','0px');
}
// редирект действия
function cmActionRedirect(url,code,noloading){
	if(code=='Delete')
		if(!confirm("Вы уверены, что хотите удалить запись?"))
			return false;
	cmPageLoad(url,noloading);
}
// отправка формы действия
function cmActionFormSubmit(form,url,code,noloading){
	if(code=='Delete'){
		if(!cmRecordCheckAll(form))
			return false;
	}
	cmFormSend(form,url,noloading);
}
// покрыть окно (сделать недоступным)
function cmCover(hideLoading){
	var pageSize=cmGetPageSize();
	document.getElementById("cover_frame").style.width=pageSize[0]+'px';
	document.getElementById("cover_frame").style.height=pageSize[1]+'px';
	document.getElementById("cover_frame").style.display="block";
	if(window.frames["cover_frame"]&&window.frames["cover_frame"].document&&window.frames["cover_frame"].document.getElementById("loading")){
		// показывать или нет иконку загрузки
		var w=282;
		var h=159;
		var l=parseInt((pageSize[2]-w)/2);
		var t=parseInt((pageSize[3]-h)/2);
		if(l<0) l=0;
		if(t<0) t=0;
		l+=(document.documentElement.scrollLeft?document.documentElement.scrollLeft:document.body.scrollLeft);
		t+=(document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop);
		window.frames["cover_frame"].document.getElementById("loading").style.left=l+'px';
		window.frames["cover_frame"].document.getElementById("loading").style.top=t+'px';
		window.frames["cover_frame"].document.getElementById("loading").style.display=(hideLoading?"none":"");
	}
}
// раскрыть окно (сделать доступным)
function cmUncover(){
	document.getElementById("cover_frame").style.display="none";
}
// показать загрузку
function cmLoadingShow(){
	if(cmGetById('content_main'))
		cmCover();
}
// спрятать загрузку
function cmLoadingHide(){
	if(cmGetById('content_main'))
		cmUncover();
}

// поправляет все ссылки (перед переходом показать иконку загрузки)
function cmFixLinks(){
	var links=cmGetByTag('A');
	for(var i=0; i<links.length; i++){
		if(!links[i].onclick&&links[i].rel!='nofix'&&links[i].target!='_blank'){
			links[i].onclick=function(){
				cmPageLoad(this.href,(this.rel=='noloading'?true:false));
				return false;
			};
		}
	}
}
// устанавливает контента в div content_main
function cmSetContent(text){
	var work=true;
	var p1=0,p2,p11,p12,p13;
	while(work){
		work=false;
		p11=text.indexOf('<!--script:',p1);
		p12=text.indexOf('<!--style:',p1);
		p13=text.indexOf('<!--eval:',p1);
		if(p11!=-1&&(p12==-1||p11<p12)&&(p13==-1||p11<p13)){
			if((p1=text.indexOf('<!--script:',p1))!=-1){ // подгрузка js
				work=true;
				p1+=11;
				p2=text.indexOf('-->',p1);
				cmLoadScript(text.substr(p1,p2-p1));
				p1=p2;
			}
		}else if(p12!=-1&&(p13==-1||p12<p13)){
			if((p1=text.indexOf('<!--style:',p1))!=-1){ // подгрузка css
				work=true;
				p1+=10;
				p2=text.indexOf('-->',p1);
				cmLoadStyle(text.substr(p1,p2-p1));
				p1=p2;
			}
		}else{
			if((p1=text.indexOf('<!--eval:',p1))!=-1){ // исполнение js
				work=true;
				p2=text.indexOf('-->',p1+9);
				res=eval(text.substr(p1+9,p2-p1-9));
				text=text.substr(0,p1)+(res?res:'')+text.substr(p2+3);
				//p1=p2;
			}
		}
	}
	cmGetById('content_main').innerHTML=text;
}

// загрузка страницы (ajax)
function cmPageLoad(url,noloading){
	cmPageReferer=cmPageUrl;
	if(url) cmPageUrl=url;
	//cmGetById('head_page_url').value=location.href+'&url='+escape(cmPageUrl);
	if(cmGetById('content_main')){
		if(!noloading) cmLoadingShow();
		var exchanger = new Ajax();
		exchanger.onLoaded=function(ajaxObject){
			var url=ajaxObject.request.getResponseHeader('PageUrl');
			url=url.substr(url.lastIndexOf('/')+1);
			if(url) cmPageUrl=url;
			//cmGetById('head_page_url').value=location.href+'&url='+escape(cmPageUrl);
			cmSetContent(ajaxObject.request.responseText);
			scrollTo(0,0);
			cmFixLinks();
			cmLoadingHide();
		};
		exchanger.onError=function(ajaxObject){
			cmLoadingHide();
		};
		exchanger.sendData({},cmPageUrl);
	}else{
		location.href=cmPageUrl;
	}
}
// обновление страницы (ajax)
function cmPageReload(){
	cmPageLoad(cmPageUrl);
}
// загрузка предыдущей страницы (ajax)
function cmPageBack(){
	cmPageLoad(cmPageReferer);
}
// отправка фомры на заданный url
function cmFormSend(form,url,noloading){
	if(typeof(form)=='string') // если тип строка значит это id или name формы
		form=(document.getElementById(form)?document.getElementById(form):document.forms[form]);
	cmPageReferer=cmPageUrl;
	if(url) cmPageUrl=url;
	if(cmGetById('content_main')){
		if(!noloading) cmLoadingShow();
		var exchanger = new Ajax();
		exchanger.onLoaded=function(ajaxObject){
			if(ajaxObject.resultIframe){
				var url=ajaxObject.frame.contentWindow.location.pathname+ajaxObject.frame.contentWindow.location.search;
				url=url.substr(url.lastIndexOf('/')+1);
				if(url) cmPageUrl=url;
				cmSetContent(ajaxObject.frame.contentWindow.document.body.innerHTML);
			}else{
				var url=ajaxObject.request.getResponseHeader('PageUrl');
				url=url.substr(url.lastIndexOf('/')+1);
				if(url) cmPageUrl=url;
				cmSetContent(ajaxObject.request.responseText);
			}
			scrollTo(0,0);
			cmFixLinks();
			cmLoadingHide();
		};
		exchanger.onError=function(ajaxObject){
			cmLoadingHide();
		};
		exchanger.sendForm(form,true,cmPageUrl);
	}else{
		form.action=cmPageUrl;
		form.submit();
	}
}
/*// отправка данных ajax
function cmAjaxSendData(url,fields,action,elementId){
	var exchanger = new Ajax();
	if(typeof(action)=='function'){
		exchanger.onLoaded=action;
	}else{
		exchanger.resultAction=action;
		exchanger.resultElementId=elementId;
	}
	exchanger.sendData(fields,url);
}
// отправка формы ajax
function cmAjaxSendForm(url,form,iframe,action,elementId){
	var exchanger = new Ajax();
	if(typeof(action)=='function'){
		exchanger.onLoaded=action;
	}else{
		exchanger.resultAction=action;
		exchanger.resultElementId=elementId;
	}
	exchanger.sendForm(form,iframe,url,method,async);
}*/

// подгрузка js-скрипта
function cmLoadScript(url){
	// проверяем не подгружен ли еще
	var nodes=document.getElementsByTagName('HEAD')[0].getElementsByTagName('SCRIPT');
	var exists=false;
	for(i=0; i<nodes.length; i++)
		if(nodes[i].getAttribute('src')==url)
			exists=true;
	// если нет, то подгружаем
	if(!exists){
		var s=document.createElement('SCRIPT');
		s.type='text/javascript';
		s.src=url;
		document.getElementsByTagName('HEAD')[0].appendChild(s);
	}
}
// подгрузка css-стиля
function cmLoadStyle(url){
	// проверяем не подгружен ли еще
	var nodes=document.getElementsByTagName('HEAD')[0].getElementsByTagName('LINK');
	var exists=false;
	for(i=0; i<nodes.length; i++)
		if(nodes[i].getAttribute('href')==url)
			exists=true;
	// если нет, то подгружаем
	if(!exists){
		var s=document.createElement('LINK');
		s.rel='stylesheet';
		s.type='text/css';
		s.href=url;
		document.getElementsByTagName('HEAD')[0].appendChild(s);
	}
}

// окрытие нового окна
function cmOpenWindow(url,name,width,height,options){
	var sizes="";
	if(width) sizes+='width='+width+',';
	if(height) sizes+='height='+height+',';
	if(options) options=','+options;
	if(sizes || options){
		var leftPos=(screen.availWidth-width)/2;
		var topPos=(screen.availHeight-height)/2;
		options=sizes+'left='+leftPos+',top='+topPos+options;
	}
	var NewWindow=window.open(url,name,options);
	NewWindow.focus();
	return NewWindow;
}
// открытие диалогового окно
function cmOpenDialog(url,arguments,width,height,options){
	var leftPos=(screen.availWidth-width)/2;
	var topPos=(screen.availHeight-height)/2;
	var sizes="";
	if(width) sizes+='dialogWidth:'+width+'px;';
	if(height) sizes+='dialogHeight:'+height+'px;';
	if(options) options=';'+options;
	options=sizes+'dialogLeft:'+leftPos+'px;dialogTop:'+topPos+'px'+options;
	return window.showModalDialog(url,arguments,options);
}

// размеры страницы
function cmGetPageSize(){
	var xScroll,yScroll;
	if(window.innerHeight&&window.scrollMaxY){ xScroll=window.innerWidth+window.scrollMaxX; yScroll=window.innerHeight+window.scrollMaxY; }
	// all but Explorer Mac
	else if(document.body.scrollHeight>document.body.offsetHeight){ xScroll=document.body.scrollWidth; yScroll=document.body.scrollHeight; }
	// Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
	else{ xScroll=document.body.offsetWidth; yScroll=document.body.offsetHeight; }
	var windowWidth, windowHeight;
	// all except Explorer
	if(self.innerHeight){ windowWidth=(document.documentElement.clientWidth?document.documentElement.clientWidth:self.innerWidth); windowHeight=self.innerHeight; }
	// Explorer 6 Strict Mode
	else if(document.documentElement&&document.documentElement.clientHeight){ windowWidth=document.documentElement.clientWidth; windowHeight=document.documentElement.clientHeight; }
	// other Explorers
	else if(document.body){ windowWidth=document.body.clientWidth; windowHeight=document.body.clientHeight; }
	// for small pages with total height less then height of the viewport
	pageHeight=(yScroll<windowHeight?windowHeight:yScroll);
	// for small pages with total width less then width of the viewport
	pageWidth=(xScroll<windowWidth?windowWidth:xScroll);
	// result
	arrayPageSize=new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	return arrayPageSize;
}

// переключение вкладок
function cmSwitchTab(tableNum,tablesetNum){
	var nodes=document.getElementById('tableset_'+tablesetNum).getElementsByTagName('DIV');
	var s1='table_'+tablesetNum+'_';
	var l1=s1.length;
	var s2='table_tab_'+tablesetNum+'_';
	var l2=s2.length;
	for(i in nodes){
		if(nodes[i].id){
			if(nodes[i].id.substr(0,l1)==s1)
				nodes[i].style.display='none';
			if(nodes[i].id.substr(0,l2)==s2)
				nodes[i].className='another';
		}
	}
	document.getElementById(s1+tableNum).style.display='block';
	document.getElementById(s2+tableNum).className='act';
}
// переключение вкладок
function cmSwitchRowClass(id,class1,class2){
	if(!class1) class1='dark';
	if(!class2) class2='';
	if(cmGetById('row_'+id).className!=class1)
		cmGetById('row_'+id).className=class1;
	else
		cmGetById('row_'+id).className=class2;
}

/*function cmGetCookies(){
	var arr=document.cookie.split(";");
	for(i in arr){
		tmp=arr[i].split('=');
		cookies[tmp[0]]=tmp[1];
	}
	return cookies;
}
function cmSetCookies(cookies){
	var str='';
	for(i in cookies){
		str+=(str?';':'').i+'='+cookies[i];
	}
	document.cookie=str;
}*/

// выделение текста внутри элемента el
function cmSelectText(el){
	if(cmBrowser=='ie'){
		var range = document.body.createTextRange();
		range.moveToElementText(el);
		range.select();
  }else{
		var selection = window.getSelection();
		var range = document.createRange();
		range.selectNodeContents(el);
		selection.addRange(range);
	}
}

var cmPageUrlClicked=false;
// щелчок на page_url
function cmPageUrlClick(el){
	cmPageUrlClicked=true;
	var url=location.href.substr(0,location.href.lastIndexOf('/')+1);
	el.innerHTML=url+cmPageUrl;
	cmSelectText(el);
	if(cmBrowser=='ie') el.focus();
	setTimeout(function(){cmPageUrlClicked=false;},1);
}
// потеря фокуса на page_url
function cmPageUrlBlur(el){
	if(!cmPageUrlClicked) el.innerHTML=(cmPageUrl.length>50?cmPageUrl.substr(0,50)+'...':cmPageUrl);
}

// проверка сообщений от сервера
function cmNotifyCheck(){
	var exchanger = new Ajax();
	exchanger.sendData({},'index.php?m_code=usr_notify');
	setTimeout(function(){cmNotifyCheck();},5000);
}
// свернуть
function cmNotifyMinimize(){
	cmGetById('notify_minimize').innerHTML='Развернуть';
	cmGetById('notify_minimize').onclick=function(){cmNotifyMaximize(); return false;};
	cmGetById('notify_content').style.display='none';
}
// развернуть
function cmNotifyMaximize(){
	cmGetById('notify_minimize').innerHTML='Свернуть';
	cmGetById('notify_minimize').onclick=function(){cmNotifyMinimize(); return false;};
	cmGetById('notify_content').style.display='block';
}
// открыть
function cmNotifyOpen(){
	cmGetById('notify').style.display='block';
}
// закрыть
function cmNotifyClose(){
	cmGetById('notify').style.display='none';
	cmGetById('notify_content').innerHTML='';
}
// добавить уведомление
function cmNotifyAdd(text){
	var node=document.createElement('DIV');
	node.innerHTML=text;
	if(cmGetById('notify_content').firstChild){
		cmGetById('notify_content').insertBefore(node,cmGetById('notify_content').firstChild);
	}else{
		cmGetById('notify_content').appendChild(node);
	}
	cmFixLinks();
	cmNotifyOpen();
	cmNotifyMaximize();
}
// пометить
function cmNotifyMark(id,mark){
	var exchanger = new Ajax();
	exchanger.sendData({},'index.php?m_code=usr_notify&notify='+id+'&mark='+mark);
}