/** odeslání XMLHttp požadavku
@param function obsluha funkce zajišťující obsluhu při změně stavu požadavku, dostane parametr s XMLHttp objektem
@param string method GET|POST|...
@param string url URL požadavku
@param string [content] tělo zprávy
@param array [headers] pole předaných hlaviček ve tvaru { 'hlavička': 'obsah' }
@return bool true v případě úspěchu, false jinak
*/

function set_backcolor(id_el, color)
{
	id(id_el).style.backgroundColor = color;
	return;
}

function send_xmlhttprequest(obsluha, method, url, content, headers)
{
    var xmlhttp = (window.XMLHttpRequest ? new XMLHttpRequest : (window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : false));
    if (!xmlhttp) {
        return false;
    }
    xmlhttp.open(method, url);
    xmlhttp.onreadystatechange = function() {
        obsluha(xmlhttp);
    };
    if (headers) {
        for (var key in headers) {
            xmlhttp.setRequestHeader(key, headers[key]);
        }
    }
    xmlhttp.send(content);
    return true;
}


function ax_send_hash()
{
	if(domReadyDetection == false) {return false;}; //if dom is not ready reloaded page 

	var params = 'hashX='+ HashCode;
	var headers= new Array();
	var url = js_pref_url + 'index.php';
	url= url + '?' + params;
	headers['Content-Type']='application/x-www-form-urlencoded';
	setTimeout('ax_send_hash()',200000);

	if (!send_xmlhttprequest(ax_send_hash_resp, 'GET', url)) {return false;}
    return true;
}

function ax_send_hash_resp(xmlhttp)
{
    if (xmlhttp.readyState == 4) {
		var hash_con = xmlhttp.responseXML.getElementsByTagName('connection')[0].firstChild;
	}
	return true;
}

function ax_book_remove_item(url, subtitl){
try
{
	url = url.replace('&amp;','&');
	if(domReadyDetection == false) {return false;}; //if dom is not ready reloaded page 

	// odeslání požadavku na aktualizaci dat
	if (!send_xmlhttprequest(ax_book_remove_item_resp, 'GET', url)) {return false;}
	doWkinPrgs(null, subtitl);
    return true;
}
catch(exception) {}
}

function ax_book_add_item(url, subtitl){
try
{
	url = url.replace('&amp;','&');
	if(domReadyDetection == false) {return false;}; //if dom is not ready reloaded page 
    // odeslání požadavku na aktualizaci dat
	if (!send_xmlhttprequest(ax_book_add_item_resp, 'GET', url)) {return false;}
	doWkinPrgs(null, subtitl);
    return true;
}
catch(exception) {}
}

function ax_book_add_item_resp(xmlhttp)
{
    if (xmlhttp.readyState == 4) {
        // aktualizace odpovědí na základě aktuálního stavu
		var num_item = xmlhttp.responseXML.getElementsByTagName("item_num")[0].firstChild;
        var price_sum = xmlhttp.responseXML.getElementsByTagName("item_price")[0].firstChild;
		
		ax_change_bask(num_item.nodeValue, price_sum.nodeValue, 'add');
		setTimeout("hide_ax_waiting_w()",1000);
	}
}

function ax_book_remove_item_resp(xmlhttp)
{
    if (xmlhttp.readyState == 4) {
        // aktualizace odpovědí na základě aktuálního stavu
		var el_bask_tx = document.getElementById('bask_tx');

		var num_item = xmlhttp.responseXML.getElementsByTagName("item_num")[0].firstChild;
        var price_sum = xmlhttp.responseXML.getElementsByTagName("item_price")[0].firstChild;
		var id_book	= xmlhttp.responseXML.getElementsByTagName("item_id")[0].firstChild;

		ax_rem_book_kos(id_book.nodeValue, price_sum);
		ax_change_bask(num_item.nodeValue, price_sum.nodeValue, 'rem');
		if(id('sum_price')){id('sum_price').innerHTML = price_sum.nodeValue;}

		setTimeout("hide_ax_waiting_w()",1000);
	}
}

function ax_change_bask(num, price, action)
{
	var el_bask_tx = id('bask_tx');
	if(num == -1)
	{
		
//		empty( 'bask_tx' );
//	    var p_empty=doc.createElement('p');
//	    p_empty.setAttribute('id','bask_tx_empt');
//		create(p_empty);


//		var div_kos = id('bask_top') = document.createElement('td');
//		div_kos.appendChild = p_empty;
//		id('p_empty').innerHTML = empty_bas_tx;
	}
	else
	{
		if(((num > 2)) || (action='rem'))
		{
			id('bas_num_item').innerHTML = num;
			id('bas_price_item').innerHTML = price;
		}
		else
		{
		}
	}
}


function ax_rem_book_kos(id_book, price_sum)
{
	var id_book = "book_" + id_book;
	var empted_line = id(id_book);

	empty( empted_line );
	remove( empted_line );
}

function ax_rem_book_list(id_book)
{
	var id_book = "book_" + id_book;
	var empted_line = id(id_book);
	empty( empted_line );
	remove( empted_line );
}

/*
function ax_move_item()
{
	var tx_item = xmlhttp.responseXML.getElementsByTagName("new_ctg")[0].firstChild;
	id(new_ctg).innerHTML = tx_item.nodeValue;

}
*/

function ax_put_to_bask_and_fill(url, inp){
try
{
//	var params = 'id_knihy='+inp.value+'&id_knihyOld='+inp.OldValue;
	var headers= new Array();
	headers['Content-Type']='application/x-www-form-urlencoded';

	re = new RegExp("^[0-9]*$");
	if (!re.test(inp.value)) {inp.value=inp.OldValue;  return false;};
	if (!re.test(inp.OldValue)) {inp.value=inp.OldValue; return false;}; 

	if(inp.OldValue == inp.value) {return false;};
	if(inp.OldValue =='') {inp.OldValue=0; params = 'id_knihy='+inp.value+'&id_knihyOld=0';};
	if(inp.value=='') {inp.value=''; params = "id_knihy=0&id_knihyOld="+inp.OldValue;};
    // odeslání požadavku na aktualizaci dat
	if (!send_xmlhttprequest(ax_put_to_bask_and_fill_resp, 'POST', url, params, headers)) {return false;};

    return true;
}
catch(exception) {}
}


function ax_put_to_bask_and_fill_resp(xmlhttp)
{
    if (xmlhttp.readyState == 4) {

		var Title = GetValueTextElement(xmlhttp,'nazev', null);
		var Author = GetValueTextElement(xmlhttp,'autor', null);
		var Price = GetValueTextElement(xmlhttp,'cena', null);
		var Id_item = GetValueTextElement(xmlhttp,'id_item', '0');
		var NumItems = GetValueTextElement(xmlhttp,'bas_num_item', '0');
		var SumPrice = GetValueTextElement(xmlhttp,'bas_price_item', '0');
		var Currenci = GetValueTextElement(xmlhttp,'currenci', '');
		var inx = compare_inputs('sell_form',Id_item);
		if(inx>-1)
		{
			if(((Title!=null)||(Author!=null))&&(Price!=null))
			{
				id('sTr'+ inx +'_2').innerHTML = Title + ' (' + Author + ')';
				id('sTr'+ inx +'_3').innerHTML = Price + Currenci;

				set_backcolor('sTr'+ inx +'_0', '#BDAA8B'); 
				set_backcolor('sTr'+ inx +'_1', '#BDAA8B');
				set_backcolor('sTr'+ inx +'_2', '#BDAA8B'); 
				set_backcolor('sTr'+ inx +'_3', '#BDAA8B');

				/*pokud byl modifikovan posledni radek, tj. nebylo by kam psat*/
				if(inx == (get_count_imput('sell_form')-1))
				{
					addRowToTable('sell_tb','sell_form');
				};
			}
			else
			{
				set_backcolor('sTr'+ inx +'_0', '#FF0000');
				set_backcolor('sTr'+ inx +'_1', '#FF0000');
				set_backcolor('sTr'+ inx +'_2', '#FF0000');
				set_backcolor('sTr'+ inx +'_3', '#FF0000');

				id('sTr'+ inx +'_2').innerHTML = '-';
				id('sTr'+ inx +'_3').innerHTML = '-';
			}
			ax_change_bask(SumPrice, NumItems, 'add');
		}
		else{alert('nastala chyba v aplikaci');};
	}

    return true;
}


function compare_inputs(form_name, value_form)
{
	var form = id(form_name);
	var fVal;

	for(var i=(form.length-1); i>=0; i--)
	{
		fVal=form.elements[i].value;
		if((fVal == value_form)||((fVal == '')&&(parseInt(value_form) == 0)&&(i<(form.length-1))))
		{
			return i;
		}
	}
	return -1;
}

function GetValueTextElement(xmlhttp, el, Default)
{
	var Val = xmlhttp.responseXML.getElementsByTagName(el)[0].firstChild;
	if((Val!=null)&&(Val.nodeType==3))
	{
		return Val.nodeValue;
	}
	else
	{
		return Default;
	};
}


function rem_empty_lines(form_name)
{
	var form = id(form_name);
	for(var i=0; i<form.length; i++)
	{
		if((parseInt(form.elements[i].value == 0)))
		{
			form.elements[i].value = 100;
//			return i;
		}
	}
//	return -1;
}


function get_count_imput(form_name)
{
	return 	id(form_name).length;
}


function addRowToTable(tbname, formname)
{
	var tbl = document.getElementById(tbname);
	var lastRow = tbl.rows.length;

	/*vypraparuje ciselnou hodnotu posledniho radku v tabulce, prevede na int a inkrementuje*/
	var idLastRowId=parseInt(tbl.rows[lastRow-1].id.substr(3,2))+1;
	
	/*pocet radku v tabulce*/
	var lastCell = tbl.rows.length;

	/*vlozeni radky do tabulky*/
	var row = tbl.insertRow(lastRow);
	row.id='sTr'+idLastRowId;

	// id cell
	var cellNo = document.createElement('td');
	cellNo.id='sTr'+idLastRowId+'_0';
	cellNo = row.insertCell(0);
	var textNode = document.createTextNode(lastCell +'.');
	cellNo.appendChild(textNode);

	// id cell
	var cellId = document.createElement('td');
	cellId.id='sTr'+idLastRowId+'_1';
	cellId = row.insertCell(1);
	
	/*naklonujeme stejny element jako byl predtim*/
	var clone = id(formname).elements[1].cloneNode(false);
	clone.value='';
	cellId.appendChild(clone);				//insert in the end of douther elements

	/*bunka pro titul a autora*/
	var cellTitle = row.insertCell(2);
	cellTitle.id='sTr'+idLastRowId+'_2';
	textNode = document.createTextNode('-');
	cellTitle.appendChild(textNode);

	/*bunka pro cenu*/
	var cellPrice = row.insertCell(3);
	cellPrice.id='sTr'+idLastRowId+'_3';
	textNode = document.createTextNode('-');
	cellPrice.appendChild(textNode);
}


/*	vytvoreni klasickeho input v DOM a pridani udalosti
var el = document.createElement('input');
	el.type = 'text';
	el.name = 'sell_imput';
	el.className = 'text';
	el.className = 'text';
	el.setAttribute("onblur", "ax_put_to_bask_and_fill('http://localhost/Stranka/Antikvariat/13_6_07/addkosX-shop.html?hash=a38e5a07ab76136e73ddabedd007c2d0', this)");
	el.setAttribute("onfocus", "this.OldValue=this.value");
	cellId.appendChild(clone);				//insert in the end of douther elements
*/

function hide_ax_waiting_w()
{
	if(document.getElementById('wkinprgs'))
	{
		document.getElementById('wkinprgs').style.visibility='hidden';
	};
	if(document.getElementById('wkinprgs_ifr'))
	{
		document.getElementById('wkinprgs_ifr').style.visibility='hidden';
	};
}


function doWkinPrgs(windowName, caption) {
try
{
	var win = window;
	var nadpisek='			Probíhá zpracování formuláře...';
	var Browser = getBrowserName();
	if (caption){ nadpisek=caption;}

	if (windowName && windowName.substring(0,1) != '_')
		win=window.open('',windowName);
	if (!win)
		win = window;
//	if (! win.document.getElementById('wkinprgs') ) {
		var doc = win.document;
		var b = doc.body;
		if (doc.getElementById('wkinprgs_ifr')) 
		{
		    IFrameObj = doc.getElementById('wkinprgs_ifr');

		}
		else {
			if (Browser == 'Internet Explorer') 
			{
				var tempIFrame=doc.createElement('iframe');
				tempIFrame.setAttribute('id','wkinprgs_ifr');
				tempIFrame.setAttribute('frameborder','0');
				tempIFrame.setAttribute('scrolling','no');
				tempIFrame.setAttribute('src','/blank.html');
				tempIFrame.style.border='0px';
				tempIFrame.style.width='220pt';
				tempIFrame.style.height='65pt';
				tempIFrame.style.zindex=98;
				tempIFrame.style.position='absolute';
				tempIFrame.style.visibility='hidden';
				IFrameObj = b.appendChild(tempIFrame);
			}
		}
		
		if (doc.getElementById('wkinprgs')) {
		    DIVObj = doc.getElementById('wkinprgs');
		    doc.getElementById('progress_caption').innerHTML=nadpisek;
		}
		else {
		    var tempDIV=doc.createElement('div');
		    tempDIV.setAttribute('id','wkinprgs');
		    tempDIV.style.border='solid 1px';
		    tempDIV.style.width='220pt';
		    tempDIV.style.height='65pt';
		    tempDIV.style.zindex=99;
		    tempDIV.style.position='absolute';
		    tempDIV.style.visibility='hidden';
			tempDIV.style.backgroundColor='white';
		    tempDIV.innerHTML =
			'<div style="width: 220pt" onclick="document.getElementById(\'wkinprgs\').style.visibility=\'hidden\';document.getElementById(\'wkinprgs_ifr\').style.visibility=\'hidden\';return false">'
+				'<div>'
+					'<table style="width:100%;" cellspacing="0">'
+						'<tr><td id="progress_caption" style="font: caption; font-size: 12pt; background-color:#C2AB81; background-image:url('+js_pref_url+'/images/top_menu.jpg);">'+ nadpisek +'</td></tr>'
+					'</table><div><img style="margin-top:20px" src="'+js_pref_url+'images/progress.gif">'
+				'</div>'
			'</div>';

		    DIVObj = b.appendChild(tempDIV);
		}

		var o = DIVObj;
		windowHeight = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
		if (o && o.style) 
		{
			var x=10; y=10;
			if (isNaN(window.screenX)) 
			{
				//alert(getY() + ' _ ' + win.document.body.clientHeight + ' _ ' + document.body.scrollTop + '___' + document.documentElement.scrollTop);
				
//				x=getX()+(win.document.body.clientWidth-220)/2;
				x=getX()/2;
				y=getY()+((windowHeight-100)/2);
			}
			else 
			{
				x=(win.innerWidth-220)/2+win.pageXOffset;
				y=(windowHeight-65)/2+win.pageYOffset;
			}
			o.style.left=x;
			o.style.top=y;
			o.style.visibility='visible';
		}
		o = IFrameObj;
		if (o && o.style) 
		{
			o.style.left=x;
			o.style.top=y;
			o.style.visibility='visible';
		}
	}
catch(exception) {}
}




function getBrowserName() {
	var detect = navigator.userAgent.toLowerCase();
	var OS,browser,version,total,thestring;

	if (checkIt('konqueror'))
	{
		browser = "Konqueror";
		OS = "Linux";
	}
	else if (checkIt('safari')) browser = "Safari"
	else if (checkIt('firefox')) browser = "Firefox"
	else if (checkIt('omniweb')) browser = "OmniWeb"
	else if (checkIt('opera')) browser = "Opera"
	else if (checkIt('webtv')) browser = "WebTV";
	else if (checkIt('icab')) browser = "iCab"
	else if (checkIt('msie')) browser = "Internet Explorer"
	else if (!checkIt('compatible'))
	{
		browser = "Netscape Navigator"
		version = detect.charAt(8);
	}
	else browser = "An unknown browser";

	if (!version) version = detect.charAt(place + thestring.length);

	if (!OS)
	{
		if (checkIt('linux')) OS = "Linux";
		else if (checkIt('x11')) OS = "Unix";
		else if (checkIt('mac')) OS = "Mac"
		else if (checkIt('win')) OS = "Windows"
		else OS = "an unknown operating system";
	}
	
	return browser;

	function checkIt(string)
	{
		place = detect.indexOf(string) + 1;
		thestring = string;
		return place;
	}
}

// funkce najde prvni formular a nastavi focus na prvni prvek, vola se onLoad na formulari


