var $ = function (id, doc) {if((id)&&((typeof id == "string")||(id instanceof String))){if (!doc) { doc = document; }var ele = doc.getElementById(id);if (ele && (ele.id != id) && doc.all) {ele = null;eles = doc.all[id];if (eles) {if (eles.length) {for (var i=0; i < eles.length; i++) {if (eles[i].id == id) {ele = eles[i];break;}}} else { ele = eles; }}}return ele;}return id;}

/* 
Определяем через паренты начало элемента по оси Х
Входной парметр, АйДи элемента
Возвращает Int
*/

function findPosX(obj){
	var curleft = 0;
	if(obj.offsetParent)
		while(1) {
			curleft += obj.offsetLeft;
			if(!obj.offsetParent)break;
			obj = obj.offsetParent;
		}
	else if(obj.x) curleft += obj.x;
	return curleft;
}

/* 
Определяем Не Ие ли Броузер :)
Возвращает Bool
*/
function isIE (){return navigator.userAgent.toLowerCase().indexOf("msie") > -1;}

/* 
Определяем через паренты начало элемента по оси Y
Входной парметр, АйДи элемента
Возвращает Int
*/
function findPosY(obj){
    var curTop= 0;
    if(!isIE) curTop= obj.offsetHeight;
    if(obj.offsetParent)
        while(1){
          curTop+= obj.offsetTop;
          if(!obj.offsetParent) break;
          obj= obj.offsetParent;
        } 
    else if(obj.y) curTop+= obj.y; 
    return curTop;
} 

/* 
Определяем через функции findPosХ и findPosY координаты елемента
Входной парметр, АйДи элемента
Возвращает масив координат array {x,y}
*/

function getPositionMy(e){
	return {x:findPosX(e), y:findPosY(e)};
}

/*
Скрипт для поиска в шапке сайта
Рисует планку (отметку - марк) над направлением поиска (НП) 
и изменяет стиль названия НП
Тип функции Void
*/

function getStyle(oElm, strCssRule){
	var strValue = "";
	if(document.defaultView && document.defaultView.getComputedStyle){
		strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	}
	else if(oElm.currentStyle){
		strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
			return p1.toUpperCase();
		});
		strValue = oElm.currentStyle[strCssRule];
	}
	return strValue;
}
			
function makeMark (id) {
	if (typeof id == "string") {
		id = $(id);
		if (id.id == "companies") {
			var markscroll = "186px";
			var mark = "118px";
		}
	}
	var tagaelm = id.parentNode.getElementsByTagName('a');
	for(var i=0; i < tagaelm.length; i++) {
		//addinput = $(tagaelm[i].id + "_");
		//addinput.setAttribute("class","");
		if (id.id != tagaelm[i].id) {
			tagaelm[i].setAttribute("class","");
			tagaelm[i].setAttribute("className","");
		}
		else {
			tagaelm[i].setAttribute("class","selected");
			tagaelm[i].setAttribute("className","selected");
			//addinput.setAttribute("class","selected");
		}
	}
	
	if (typeof markscroll == "string") $("markscroll").style.width = markscroll;
	else $("markscroll").style.width = (findPosX(id) - findPosX($("markscroll"))) + "px";
	if (typeof mark == "string") $("mark").style.width = mark;
	else $("mark").style.width = $(id).offsetWidth + "px";
	document.forms["searchform"].type.value = id.id;
	return true;
}

/*
*/
function parseXML(dest, node){
	try { //Internet Explorer 
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	} catch(e) { //Firefox, Mozilla, Opera, etc.
		try {
			xmlDoc=document.implementation.createDocument("","",null);
		} catch(e) {
			alert(e.message);
			return;
		}
	}
	
	xmlDoc.async=false;
	xmlDoc.load(dest);
	var x = xmlDoc.getElementsByTagName(node);
	var theData = new Array(x.length);
		for (i=0;i<x.length;i++)	{
			theData[i] = new Array(x[0].childNodes);
			for (j=0;j<x[0].childNodes.length;j++)	{
				if (x[0].childNodes[j].nodeType != 1) continue;
					theData[i][x[i].childNodes[j].nodeName] = x[i].childNodes[j].firstChild.nodeValue;
			}
			delete theData[i][0];
		}
	return (theData);
}

/* 
замена search на replace в строке subject 
входные параметры - масивы/строки search и replace, текст/хтмл subject
если search и replace заменяет элементы в соот. с айдишниками
Возвращает текст/хтмл
*/
function str_ireplace ( search, replace, subject ) {
    var i;
    if(!(replace instanceof Array)){
        replace=new Array(replace);
        if(search instanceof Array){
            while(search.length>replace.length){
                replace[replace.length]=replace[0];
            }
        }
    }
    if(!(search instanceof Array))search=new Array(search);
    while(search.length>replace.length){
        replace[replace.length]='';
    }
    if(subject instanceof Array){
        for(k in subject){
            subject[k]=str_replace(search,replace,subject[k]);
        }
        return subject;
    }
    for(var k=0; k<search.length; k++){
        reg = new RegExp(search[k], 'gi');
        subject = subject.replace(reg, replace[k]);
    }
    return subject;
}

/* 
*/
function array_keys( input, search_value, strict ) {
    var tmp_arr = new Array(), strict = !!strict, include = true, cnt = 0;
    for ( key in input ){
        include = true;
        if ( search_value != undefined ) {
            if( strict && input[key] !== search_value ){
                include = false;
            } else if( input[key] != search_value ){
                include = false;
            }
        }
        if( include ) {
            tmp_arr[cnt] = key;
            cnt++;
        }
    }
    return tmp_arr;
}

/* 
*/
function array_values( input ) {
    var tmp_arr = new Array(), cnt = 0;
    for ( key in input ){
        tmp_arr[cnt] = input[key];
        cnt++;
    }
    return tmp_arr;
}
/* 
*/
function NewsHeadLinesTop(categoryId, id) {
		
		xml = parseXML("/html/xml/" + categoryId + ".xml", 'top');
		$("topheadlines").innerHTML = print_r(xml);
		return 0;
		
		var nextid = id+1;
		var previd = id-1;
		if (nextid > 2) nextid = 0;
		if (previd < 0) previd = 2;
		
		
			var ra = Array("image_domain","image","ttl");
			var rba = Array("http://img.news.tut.ua/150x115", "img","title");
			html = '<table class="headlinestop"><tr><td class="arrow" onclick="NewsHeadLinesTop(' + categoryId + ', ' + previd + ');">&#9668;</td><td id="headtop"><a href="link" ttl="title"><image height="115" width="150" aling="left" src="image_domain/img" alt="title"></a><span>date</span><br><a href="link" ttl="title">title</a><br>desc</td><td class="arrow" onclick="NewsHeadLinesTop(' + categoryId + ', ' + nextid + ');">&#9658;</td></tr></tbody></table>';
			html = str_ireplace(array_keys(xml[id]),array_values(xml[id]),html);
			html = str_ireplace(ra,rba,html);
		
		$("topheadlines").innerHTML = html;	
}

/* 
*/
function NewsHeadLinesLast(categoryId) {
		xml = parseXML("/html/xml/" + categoryId + ".xml", 'item');
		$("lastheadlines").innerHTML = print_r(xml);
		return 0;
		var ra = Array("image_domain","image","ttl");
		var rba = Array("http://img.news.tut.ua/150x115", "img","title");
		thtml = '<div class="headlineslast"><a href="link" ttl="title"><image aling="left" src="image_domain/img" alt="title"></a><a href="link" ttl="title">title</a><br><span>date</span></div>';
		html_ = "";
		for (i=0;i<xml.length;i++)	{
			html = str_ireplace(array_keys(xml[i]),array_values(xml[i]),thtml);
			html_ += str_ireplace(ra,rba,html);
		}
		
		
		//$("lastheadlines").innerHTML = html_;
}

/* 
*/
function changetab(id, startId){
	categoryId = id;
	NewsHeadLinesTop(categoryId, startId);
	NewsHeadLinesLast(categoryId);
}

/* 
*/
function makeStyle (id, idhead) {
	
	tdid = id.parentNode;
	tableid = id.parentNode.parentNode.parentNode.parentNode;
	cellnumber = tdid.cellIndex;
	style2change = tableid.rows[0].cells;
	
	for(var i=0; i < style2change.length; i++) {
			var chk = new RegExp('select');
			var dwn = new RegExp('_');
  		var re = new RegExp('select[^x][^x]');
		  if (style2change[i].className.match(chk)) {
		  	style2change[i].setAttribute("class", style2change[i].className.replace(re, ""));
		  	style2change[i].setAttribute("class", style2change[i].className.replace(chk, ""));
		  	style2change[i].setAttribute("class", style2change[i].className.replace(dwn, ""));
		  }
	}

	if (cellnumber > 1) style2change[cellnumber - 2].setAttribute("class","xborderR_ selectR_");
	if (cellnumber > 1) style2change[cellnumber - 1].setAttribute("class","xborderL_ selectL_");	
	style2change[cellnumber].setAttribute("class","center select");
	if (cellnumber < style2change.length-1) style2change[cellnumber + 1].setAttribute("class","xborderR selectR");	
	if (cellnumber < style2change.length) style2change[cellnumber + 2].setAttribute("class","xborderL selectL");

	if (cellnumber == 1) style2change[cellnumber - 1].setAttribute("class","xborderB selectB");	
	
	changetab(idhead, 0);
}

var loop=0;
function process() {
    var num=jQuery("ul.ln > li").get().length;        
    jQuery("ul.ln > li").each(function(i) {            
        if(i==loop) jQuery(this).show();
        else jQuery(this).hide();
    });        
    if(loop==num-1) loop=0
    else loop++;        
}    


function pr() {
    var num=jQuery("ul.ln > li").get().length;
    if(num>0) {
        jQuery("ul.ln > li").hide();
        jQuery("ul.ln > li:first-child").show();
        setInterval('process()', 5000); 
    }
}

