/**
* $URL: svn+ssh://valentine/ordinace/branches/ostry/www/js/ajax.js $
* $Date: 2009-10-10 02:05:40 +0200 (Sat, 10 Oct 2009) $
* $Rev: 4516 $
* $Author: svec $
*/

/** 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
* @copyright Jakub Vrána, http://php.vrana.cz
*/
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;
}

/** zalogovani prechodu z URL na URL pres 'onclick' udalost na odkazech
* @param string stranka na ktere se kliklo (u nas)
* @param string externi url na kterou se ma prejit
* @return bool true v případě úspěchu, false jinak
*/
function logURL(strLoc,strURL)
{
    if (! send_xmlhttprequest(url_service, 'GET', '/inc/log-url/log.php?from=' + urlencode(strLoc.toString()) + '&url=' + urlencode(strURL))) {
        return false;
    }
    return true;
}

/** hlasovani v ankete - odesle hlas na server, a nasledne nacte aktualni data
* @param integer id ankety ve ktere se ma hlasovat
* @param integer id odpovedi pro kterou se ma hlasovat
* @return string novy stav ankety jako vygenerovany HTML dokument
*/
function anketaHlasuj(idAnkety,idOdpovedi)
{
    if (! send_xmlhttprequest(anketa_service, 'GET', '/inc/vote.php?anketaId=' + idAnkety + '&odpovedId=' + idOdpovedi)) {
        return false;
    }

    return true;
}

/** zmena zalozky v modulu NEJ-prehled na homepagi
* @param integer id sekce, kterou chceme zobrazit
* @return string novy stav modulu jako vygenerovany HTML dokument
*/
function changeContent(mode,target,items)
{
    if (! send_xmlhttprequest(content_service, 'GET', '/inc/change_most_section.php?mode=' + mode + '&target=' + target + '&items=' + items)) {
        return false;
    }

    return true;
}

/** podekovani za prispevek v diskusi - odesle hlas na server, a nasledne nacte aktualni data
* @param integer id prispevku
* @return string novy stav ankety jako vygenerovany HTML dokument
*/
function thankYou(id_reply)
{
    if (! send_xmlhttprequest(thankYou_service, 'GET', '/inc/thankYou.php?replyId=' + id_reply)) {
        return false;
    }

    return true;
}

/** obsluha http requestu pro nas pozadavek
* @param object instance xmlhttprequest 
* @return bool true v případě úspěchu, false jinak
*/
function url_service(xmlhttp)
{
    if (xmlhttp.readyState == 4) {
        return true;
    }
}

/** obsluha http requestu pro nas anketu
* @param object instance xmlhttprequest 
* @return bool true v případě úspěchu, false jinak
*/
function anketa_service(xmlhttp)
{
    if (xmlhttp.readyState == 4) {
        var odpovedi = xmlhttp.responseXML.getElementsByTagName('odpoved');
        for (var i=0; i < odpovedi.length; i++) {
            var txt = odpovedi[i].getElementsByTagName('text');
            var val = odpovedi[i].getElementsByTagName('hodnota');

            txt = txt[0].firstChild.data;
            val = val[0].firstChild.data;

            document.getElementById(odpovedi[i].getAttribute('id')).innerHTML = "<span class=\"href\">" + txt + " <span class=\"graph\" style=\"width: " + val + "%;\"></span></span> <em>" + val + " %</em>";

            // alert(txt + val);
            // var t = odpovedi[i].getElementsByTagName('text');
            // alert(t[i].firstChild.data);
            // alert(odpovedi[i].getElementsByTagName('text'));
            // document.getElementById(odpovedi[i].getAttribute('id')).innerHTML = odpovedi[i].innerHTML;
        }

        var celkem = xmlhttp.responseXML.getElementsByTagName('celkem');
        celkem = celkem[0].firstChild.data;
        document.getElementById('inquiry-celkem').innerHTML = "Dosud hlasovalo " + celkem + " lidí";

		  inquiry_check();

        return true;
    }
}

/** obsluha http requestu pro diskusni "diky"
* @param object instance xmlhttprequest
* @return bool true v případě úspěchu, false jinak
*/
function thankYou_service(xmlhttp)
{
	if (xmlhttp.readyState == 4) {
		var thank = xmlhttp.responseXML.getElementsByTagName('thankCount');
		var id = thank[0].getAttribute('id');
		var count = thank[0].firstChild.data;
		
		replyCollection.get(id).setThanks(count);
	}
}

function content_service(xmlhttp)
{
    if (xmlhttp.readyState == 4) {
			//trida "vybudujici" html pro kontejnery
			var builder = {
				target : null,
				items : new Array(),
				template : null,
				processor : null,

				//nastavi polozky
				setItems : function(nodeArray) {
					iNodes = nodeArray.childNodes.length;
					for(i=0;i<iNodes;i++) {
						node = nodeArray.childNodes.item(i);
						//zajimaji me jenom xml tagy, ne textovy ptakoviny
						if(node.tagName == 'article') {
							this.items.push(new Article(node));
						} else if(node.tagName == 'list') {
							this.items.push(new ListNode(node));
						}
					}
					//vratim, ze se zadarilo
					return true;
				},
				//nastavi template
				setTemplate : function(template) {
					this.template = template;
					return true;
				},
				//nastavi cilovy element
				setTarget : function(target) {
					this.target = document.getElementById(target);
					return true;
				},
				//vytvori novy procesor a necha zpracovat
				//podle zadane sablony vsechny polozky
				process : function() {
					switch(this.template) {
						case 'articles': this.processor = new Articles(); break;
						case 'doublecols': this.processor = new DoubleCols(); break;
					}
					this.processor.setItems(this.items);
					this.target.innerHTML = this.processor.createHTML();

					return true;
				}
			}

			//korenovy element XML
			var response = xmlhttp.responseXML.getElementsByTagName('HTTPrequest')[0];
			//informace z metadat
			var mode = response.getElementsByTagName('mode')[0];
			//nastavim builder engine
			builder.setItems(response.getElementsByTagName('items')[0]);
			builder.setTemplate(mode.getElementsByTagName('template')[0].firstChild.data);
			builder.setTarget(mode.getElementsByTagName('target')[0].firstChild.data);
			builder.process();

			return true;
    }
}

function Article(article) {
	//vytvorim nove pole s prazdnymi sloupci
	this.picture = '';
	this.title = '';
	this.href = '';
	this.date = '';
	this.perex = '';
	this.comments = 0;
	this.isDiscussion = 0;
	this.haveDiscussion = 0;
	this.related = new Array();

	/**
	 * nastavi tridovy atribut pomoci
	 * zadaneho jmena a obsahu
	 * 
	 * @param string nazev atributu
	 * @param string obsah atributu
	 */
	this.setAttr = function(name,value)
	{
		if(isNaN(value)) {
			eval('this.' + name + ' = value;');
		} else {
			eval('this.' + name + ' = parseInt(value);');
		}
		return true;
	}
	
	/**
	 * nastavi souvisejici clanky
	 */
	this.setRelated = function(related)
	{
		var node;
		var nodes;
		
		nodes = related.childNodes;
		for(var a=0;a<nodes.length;a++) {
			node = nodes.item(a);
			//zajima me jenom tag 'article'
			if(node.tagName == 'article') {
				this.related.push(new Article(node));
			}
		}
		return true;
	}
	
	/**
	 * gettery ...pomerne samovysvetlujici
	 */
	this.getPicture = function()
	{ return this.picture; }
	this.getTitle = function()
	{ return this.title; }
	this.getHref = function()
	{ return this.href; }
	this.getDate = function()
	{ return this.date; }
	this.getPerex = function()
	{ return this.perex; }
	this.getComments = function()
	{ return this.comments; }
	this.testDiscussion = function()
	{ return (this.isDiscussion ? true : false); }
	this.testEnabledDiscussion = function()
	{ return (this.haveDiscussion ? true : false); }
	this.getRelated = function(i)
	{
		if(i>=0 && i<this.related.length)
			return this.related[i];
		else return this.related;
	}

	/**
	 * 'konstruktor' tridy Article
	 */
	var node;
	var nodes;
	
	//poukladam hodnoty z XML
	nodes = article.childNodes;
	for(var a=0;a<nodes.length;a++)
	{
		node = nodes.item(a);

		if(node.tagName && node.hasChildNodes()) {
			if(node.tagName == 'related') {
				this.setRelated(node);
			} else {
				this.setAttr(node.tagName,node.firstChild.data);
			}
		}
	}
}

function ListNode(listNode) {
	//definuju tridni promenne
	this.href = '';
	this.title = '';
	
	/**
	 * nastavi tridovy atribut pomoci
	 * zadaneho jmena a obsahu
	 * 
	 * @param string nazev atributu
	 * @param string obsah atributu
	 */
	this.setAttr = function(name,value)
	{
		eval('this.' + name + ' = value;');
		return true;
	}

	//gettery
	this.getHref = function()
	{ return this.href; }
	this.getTitle = function()
	{ return this.title; }
	
	/**
	 * 'konstruktor' tridy atribut
	 */
	var node;
	var nodes;
	
	//poukladam hodnoty z XML
	nodes = listNode.childNodes;
	for(var a=0;a<nodes.length;a++)
	{
		node = nodes.item(a);

		if(node.tagName && node.hasChildNodes()) {
			this.setAttr(node.tagName,node.firstChild.data);
		}
	}
}

function Articles() {
	//vystupni retezec
	this.output = '';
	//pole s polozkami predanymi ke zpracovani
	this.items = new Array();
	//nacte ze vstupu polozky
	this.setItems = function(items) {
		this.items = items;
	}
	//vytvori zobrazitelne html
	this.createHTML = function() {
		var counter = 0;
		var itemCount = this.items.length;
		for(var i in this.items) {
			counter++;
			//zajimaji me jenom xml tagy, ne textovy ptakoviny
			this.output += '<div class="perex">';
			this.output += '	<h2 class="title"><a href="' + this.items[i].getHref() + '">' + this.items[i].getTitle() + '</a></h2>';
			this.output += '  <div class="wrapper">';
			this.output += '		<img src="' + this.items[i].getPicture() + '" alt="' + this.items[i].getTitle() + '" title="' + this.items[i].getTitle() + '" height="72" width="72" />';
			this.output += '		<p>';
			this.output += '			<span class="date">' + this.items[i].getDate() + '</span><span class="pipe">|</span>';
			this.output += '		' + this.items[i].getPerex();
			this.output += '		</p>';
			this.output += '		<div class="related">';
			this.output += '			<ul>';
			this.output += '				<li class="read-all">';
			this.output += '					<a href="' + this.items[i].getHref() + '">Číst celý článek</a>';
			if(this.items[i].testEnabledDiscussion())
			this.output += '					| <a class="discuss" href="' + this.items[i].getHref() + 'diskuse/">Diskuse (' + this.items[i].getComments() + ')</a>';
			this.output += '				</li>';
			//souvisejici
			/*
			for(related in this.items[i].getRelated()) {
				if(this.items[i].testDiscussion())
				this.output += '		<li><a href="' + this.items[i].getRelated(related).getHref() + '">Diskuse: ' + this.items[i].getRelated(related).getTitle() + '</a>';
				else
				this.output += '		<li><a href="' + this.items[i].getRelated(related).getHref() + '">' + this.items[i].getRelated(related).getTitle() + '</a>';
				if(this.items[i].testEnabledDiscussion())
				this.output += '					| <a class="discuss" href="' + this.items[i].getRelated(related).getHref() + 'diskuse/">(' + this.items[i].getRelated(related).getComments() + ')</a>';
				this.output += '		</li>';
			}*/
			this.output += '			</ul>';
			this.output += '		</div>';
			this.output += '	</div>';
			this.output += '	<div class="cistic"></div>';
			this.output += '</div>';
			if(counter!=itemCount) {
				this.output += '<div class="divider"></div>';
			}
		}
		
		return this.output;
	}
}

function DoubleCols() {
	//vystupni retezec
	this.output = '';
	//pole s polozkami predanymi ke zpracovani
	this.items = new Array();
	//nacte ze vstupu polozky
	this.setItems = function(items) {
		this.items = items;
	}
	//vytvori zobrazitelne html
	this.createHTML = function() {
		var counter = 0;
		var half = Math.ceil(this.items.length/2);

		this.output += '	<div class="edge">';
		for(var i in this.items) {
			counter++;
			//otevreni noveho sloupce, pokud jsme na zacatku, nebo v pulce
			if(counter == 1 || counter - 1 == half) {
				this.output += '		<div class="pulka">';
				this.output += '			<ul class="list">';
			}
			this.output += '<li><a href="' + this.items[i].getHref() + '">' + this.items[i].getTitle() + '</a></li>';
			//uzavreni vypisu, pokud jsme se dostali do pulky a nebo nakonec
			if(counter == half || counter == this.items.length) {
				this.output += '			</ul>';
				this.output += '		</div>';
			}
		}
		this.output += '		<div class="cistic"></div>';
		this.output += '	</div>';

		return this.output;
	}
}

/** Funkce ktera zakoduje retezec tak aby se dala poslat pres GET.
* @param  string    retezec ktery se ma kodovat
* @return string    zakokovany retezec
*/
function urlencode(str) {
    str = str.replace(/\//g,'%2F');
    str = str.replace(/\?/g,'%3F');
    str = str.replace(/=/g,'%3D');
    str = str.replace(/&/g,'%26');
    str = str.replace(/\:/g,'%3A');
    return str;
}

/** Funkce ktera na vsechny externi odkazy automaticky navaze javascriptovy kod pro zalogovani.
*
* @param  document    dokument na kterem se maji linky zpracovat
* @return nic nevraci
*/
function linkLinks(doc) {
    for (i = 0; i < doc.links.length; i++) {
        regEx = new RegExp('www.ordinace.cz','i');
        regEx2 = new RegExp('ordinace.cz','i');
        regEx3 = new RegExp('javascript:','i');
        regEx4 = new RegExp('vyvoj-svn.ordinace.cz','i');
        regEx5 = new RegExp('preview.ordinace.cz','i');

        //odkazy smerujici mimo ordinace
        if ((! doc.links[i].href.match(regEx)) && (! doc.links[i].href.match(regEx2)) && (! doc.links[i].href.match(regEx3)) && (! doc.links[i].href.match(regEx4)) && (! doc.links[i].href.match(regEx5))) {
            doc.links[i].onclick = function onclick(event) {
                window.open(this.href,'_blank');
                logURL(window.location,this.href);
                return false;
            };
        
        //odkazy smerujici na PR clanek
        } else if (doc.links[i].href.match(new RegExp('mate-potize-s-pohybovym-aparatem','i'))) {
            doc.links[i].onclick = function onclick(event) {
                logURL(window.location,this.href);
            }
        }
    }

    return;
}

function inquiry_check() {
       spans = document.getElementsByTagName("SPAN");
       for (i=0; i<spans.length; i++) {
           node = spans[i];
           if (node.className=="href") {
              node.onmouseover=function() {
                 this.className+="over";
              }
              node.onmouseout=function() {
                 this.className=this.className.replace("over", "");
              }
           }
       }
}

function checkButton(id) {
       id = 'b' + id;
       button = document.getElementById(id);
       if (! button.checked) {
	   button.checked = ! button.checked;
       }
}

function showInput(id) {
	o = document.getElementById('t' + id);
	o.style.visibility = 'visible';
}
