/* EVENT HANDLERS */
function addEventToObject(obj, evt, func) {
	var oldhandler = obj[evt];
	obj[evt] = (typeof obj[evt] != 'function') ? func : function(){oldhandler();func();};
}


/* GLOBALS */
var isIE = false;
var currentWidgetXML = null;
var currentWidgetIndex = null;
var currentWidget = null;
var currentCategory = null;
var currentMainCategory = null;
var safariBugFixCounter = null;
var active_id=null;
var mapRequest=null;
var workingWithEvents=0;
var alternate=0;
var prevId="fomenu01";


function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function emptyLocations(id){
obj=document.getElementById(id);
obj.options.length=0;
obj.options[0]=new Option('összes helyszín','0');
}

function getLocationsByTimespan(timespan){
	emptyLocations('e_location');
	url="xml/locationfilter.php?timespan="+timespan;

        var jsel = document.createElement('SCRIPT');
        jsel.type = 'text/javascript';
        jsel.src = url;
        document.body.appendChild (jsel);
        workingWithEvents=1;
        getEvents(timespan,selectedLocation);
        //alert(timespan);
        //getEvents(timespan,0);
}





/* ENGINES */
function ajaxRequest(url,func) {
    if (window.XMLHttpRequest) {
        var req = new XMLHttpRequest();
        if (func) {req.onreadystatechange = function() {func(req);}}
        req.open("GET", url, true);
        //if (browser.isSafari) {req.setRequestHeader('If-Modified-Since','Wed, 15 Nov 1995 00:00:00 GMT');}
        req.send(null);
    } else if (window.ActiveXObject) {
        isIE = true;
		try {var req = new ActiveXObject("Msxml2.XMLHTTP");}
		catch(e) {req = new ActiveXObject("Microsoft.XMLHTTP");}
        if (req) {
            if (func) {req.onreadystatechange = function() {func(req);}}
            req.open("GET", url, true);
            req.send();
        }
    }
}

function getElementTextNS(prefix, local, parentElem, index) {
    var result = "";
    if (prefix && isIE) {result = parentElem.getElementsByTagName(prefix + ":" + local)[index];} 
    else {result = parentElem.getElementsByTagName(local)[index];}
    if (result) {
        if (result.childNodes.length > 1) {return result.childNodes[1].nodeValue;} 
        else {return result.firstChild.nodeValue;}
    } else {return "";}
}

/* HANDLERS */
function initializeProcessReqChange(req) {
    if (req.readyState == 4) {
        if (req.status == 200) {buildMainCategoryList(req);} 
        else {alert("There was a problem retrieving the XML data:\n" + req.statusText);}
	}
	document.body.style.cursor = 'default';
    return true;
}

function mainCategoryProcessReqChange(req) {
    if (req.readyState == 4) {
        if (req.status == 200) {buildCategoryList(req);} 
        else {alert("There was a problem retrieving the XML data:\n" + req.statusText);}
	}
	document.body.style.cursor = 'default';
    return true;
}

function categoryProcessReqChange(req) {
    if (req.readyState == 4) {
        if (req.status == 200) {buildWidgetList(req);} 
        else {alert("There was a problem retrieving the XML data:\n" + req.statusText);}
	}
	document.body.style.cursor = 'default';
    return true;
}

function widgetProcessReqChange(req) {
    if (req.readyState == 4) {
        if (req.status == 200) {buildWidgetInfo(req);}
        else {alert("Sorry, there was a problem retrieving the Dashboard Widget information. Please click 'ok' to reload the page.");window.location.reload();}
	}
	document.body.style.cursor = 'default';
    return true;
}

/* LOADERS */

function mainCategoryLoad(xmlFile, a) {
	currentCategoryXML = xmlFile;
	clearOvers(document.getElementById('level-0'));
	if(currentMainCategory){currentMainCategory.className = "";}
	if(currentCategory && (currentCategory.className == "hi")){currentCategory.className = "open";}
	currentMainCategory = a;
	currentMainCategory.className = "hi";
	document.body.style.cursor = 'wait';
	ajaxRequest(xmlFile,mainCategoryProcessReqChange);
}

function categoryLoad(xmlFile, a, ctitle, m) {
	currentWidgetXML = xmlFile;
	clearOvers(document.getElementById('level-1'),m);
	if(currentCategory){currentCategory.className = "";}
	if(currentWidget && (currentWidget.className == "hi")){currentWidget.className = "open";}
	if(currentMainCategory && (currentMainCategory.className == "hi")){currentMainCategory.className = "open";}
	currentCategory = a;
	currentCategory.className = "hi";
	document.body.style.cursor = 'wait';
	//document.getElementById('map').href='map.php?cat='+ctitle;
	mapRequest=xmlFile.replace(".xml","");
	mapRequest=mapRequest.substring(4);
	ajaxRequest(xmlFile,categoryProcessReqChange);
}

function widgetLoad(index, a, wid,m) {

	currentWidgetIndex = index;
	clearOvers(document.getElementById('level-2'),m);
	if(currentWidget){currentWidget.className = "";}
	if(currentCategory && (currentCategory.className == "hi")){currentCategory.className = "open";}
	currentWidget = a;
	currentWidget.className = "hi";
	//document.body.style.cursor = 'wait';

	/*if (browser.isSafari) {
		safariBugFixCounter = Math.floor(Math.random() * 89999) + 10000;
		ajaxRequest(currentWidgetXML+'?'+safariBugFixCounter,widgetProcessReqChange);
	}
	else {ajaxRequest(currentWidgetXML,widgetProcessReqChange);}*/
active_id=wid;
	rnd=Math.floor(Math.random()*1000);	if(workingWithEvents==0)
document.getElementById('locationbox').src="xml/getcard.php?id="+wid+"&rnd="+rnd;else
document.getElementById('locationbox').src="xml/getcard.php?e=1&id="+wid+"&rnd="+rnd;
}

/* CONSTRUCTORS */
function buildMainCategoryList(req) {

    var ul = document.getElementById("level-0").getElementsByTagName('ul')[0];
    var categories = req.responseXML.getElementsByTagName("category");
    alternate=0;

    var m=categories.length;
    for (var i = 0; i < m; i++) {
    	var content = document.createTextNode(getElementTextNS("","title",categories[i],0)+" ("+getElementTextNS("","records",categories[i],0)+")");
    	//var target = "xml/"+city+"/" + getElementTextNS("", "xml_file", categories[i], 0);
    	var target = "xml/"+ getElementTextNS("", "xml_file", categories[i], 0);
        appendToList(ul, content, target, 0,0);
        alternate++;
    }
    document.getElementById('locationbox').src=blankpage;
    if(m==0 && workingWithEvents==1) {getEvents('ma');} else {
    if(m==1) mainCategoryLoad(target,false);else
    selecta('Válasszon főkategóriát!','level-1');}
}


function buildCategoryList(req) {
var lastanchor;
    var ul = document.getElementById("level-2").getElementsByTagName('ul')[0];
    clearList(ul);
    ul = document.getElementById("level-1").getElementsByTagName('ul')[0];
    clearList(ul);
    alternate=0;
    var categories = req.responseXML.getElementsByTagName("category");
    var m=categories.length;
    for (var i = 0; i < m; i++) {
    	var content = document.createTextNode(getElementTextNS("","title",categories[i],0)+" ("+getElementTextNS("","records",categories[i],0)+")");
    	
    	//var target = "xml/"+city+"/" + getElementTextNS("", "xml_file", categories[i], 0);
    	var target = "xml/"+getElementTextNS("", "xml_file", categories[i], 0);
        lastanchor=appendToList(ul, content, target, 1,getElementTextNS("","title",categories[i],0),getElementTextNS("","highprio_inside",categories[i],0));
        alternate++;
    }

    document.getElementById('locationbox').src=blankpage;
    if(m==1) {
categoryLoad(target,false,getElementTextNS("","title",categories[0],0),m);
return;}
    if(workingWithEvents==1){
	categoryLoad(target,lastanchor,getElementTextNS("","title",categories[categories.length-1],0),m);
return;  
    } 
    selecta('Válasszon alkategóriát!','level-2');
}

function buildWidgetList(req) {
    var widgets;
    var loadfirst=false;
    widgets = req.responseXML.getElementsByTagName("location");
    if(widgets.length==0) {widgets = req.responseXML.getElementsByTagName("event");
   	workingWithEvents=1;
    } else 	workingWithEvents=0;
    var ul = document.getElementById('level-2').getElementsByTagName('ul')[0];
    clearList(ul);
    var m=widgets.length;
    for (var i = 0; i < m; i++) {
    appendToWList(ul, document.createTextNode(stripDashboardTest(getElementTextNS("", "location_name", widgets[i], 0))), i, widgets[i].getAttribute("id"),getElementTextNS("", "priority", widgets[i], 0));
    if(getElementTextNS("", "priority", widgets[i], 0)=='2') loadfirst=true;
    }
        

    if(m==1 || loadfirst) widgetLoad(i,false,widgets[0].getAttribute("id"),m);else document.getElementById('locationbox').src="chooselocation.html";
    if(workingWithEvents==0) {
    	
 /*   li = document.createElement("li");
   	a = document.createElement("a");
    a.setAttribute('href','javascript:void(0);');
    a.className="suggestCompany";
    //a.setAttribute("style", "background:none;text-align:center;padding-top:10px;");
	//a.style.cssText = "background:none;text-align:center;padding-top:10px;";
    a.appendChild(document.createTextNode('Cég ajánlása'));
    a.appendChild(document.createElement('br'));
    a.appendChild(document.createTextNode('ebbe a kategóriába'));
    addEventToObject(a,'onclick', function() {alert('ok');});
    li.appendChild(a);
    ul.appendChild(li); */	
    }
}




var fields=new Array("name","city","address","phone","mobile","fax","description","tags","opening","email");


function buildDetails(req){
	var data = req.responseXML.getElementsByTagName("location")[0];
	var i,s;
	for(i=0;i<10;i++){	
	s="document.getElementById('m_"+fields[i]+"').innerHTML=getElementTextNS(\"\", \""+fields[i]+"\", data, 0);";
	eval(s);
	}
	if(getElementTextNS("", "web", data, 0)=="-") document.getElementById('m_web').innerHTML="Kérem hívjon!";else {
	document.getElementById('m_web').href=getElementTextNS("", "web", data, 0);
	document.getElementById('m_web').innerHTML=getElementTextNS("", "web", data, 0);}
	if(getElementTextNS("", "email", data, 0)=="-")document.getElementById('m_email').innerHTML="Kérem hívjon!";else 
	document.getElementById('m_email').href="mailto:"+getElementTextNS("", "email", data, 0);
	if(getElementTextNS("", "coords", data, 0)=="-") document.getElementById('m_coords').href="javascript:getMap()";else document.getElementById('m_coords').href="javascript:showMap("+active_id+")";
	document.getElementById('active_logo').src=getElementTextNS("", "img_src", data, 0);
	displayAlphaBg();
	
	document.getElementById('details').style.display='block';	centerPos();
}

function parseDetails(req){
    if (req.readyState == 4) {
        if (req.status == 200) {buildDetails(req);}
        else {
        alert("Elnézését kérjük, rendszerünk a kérést nem teljesítette. Kérjük töltse újra lapunkat!");window.location.reload();
        }
	}
	document.body.style.cursor = 'default';
    return true;
}

function getDetails(id){
ajaxRequest("getdetails.php?id="+id,parseDetails);
}

var efields=new Array("e_name","e_description","showtimes","e_city","e_address","e_phone","e_mobile","e_fax","locname","e_email");

function buildEventDetails(req){
	var data = req.responseXML.getElementsByTagName("event")[0];
	var i,s;
	for(i=0;i<10;i++){	s="document.getElementById('m_"+efields[i]+"').innerHTML=getElementTextNS(\"\", \""+efields[i]+"\", data, 0);";
	eval(s);
	}
	if(getElementTextNS("", "e_web", data, 0)==" ") document.getElementById('m_e_web').innerHTML="Kérem hívjon!";else {
	document.getElementById('m_e_web').href=getElementTextNS("", "e_web", data, 0);
	document.getElementById('m_e_web').innerHTML=getElementTextNS("", "e_web", data, 0);}
	if(getElementTextNS("", "e_email", data, 0)==" ")document.getElementById('m_e_email').innerHTML="Kérem hívjon!";else 
	document.getElementById('m_e_email').href="mailto:"+getElementTextNS("", "e_email", data, 0);
	if(getElementTextNS("", "coords", data, 0)==" ") document.getElementById('m_e_coords').href="javascript:getMap()";else document.getElementById('m_e_coords').href="javascript:showMap("+getElementTextNS("", "locid", data, 0)+")";
	displayAlphaBg();
	document.getElementById('eventdetails').style.display='block';	centerPos();
}


function parseEventDetails(req){
    if (req.readyState == 4) {
        if (req.status == 200) {buildEventDetails(req);}
        else {
        alert("Elnézését kérjük, rendszerünk a kérést nem teljesítette. Kérjük töltse újra lapunkat!");
        //window.location.reload();
        }
	}
	document.body.style.cursor = 'default';
    return true;
}

function getEventDetails(id){
ajaxRequest("/geteventdetails.php?id="+id,parseEventDetails);
}


function buildWidgetInfo(req) {
	var li,wImg,wImgH,wImgW,wTitle,wDate,wWare,wTxt,wSize,wURLInfo,wURLDL,priority,wImgStyle,phone,h2="h2";
	var widget = req.responseXML.getElementsByTagName("location")[currentWidgetIndex];
	//alert(req.responseXML.getElementsByTagName("location")[currentWidgetIndex].getAttribute("id"));
	var id=widget.getAttribute("id");
	active_id=id;
	wImg = getElementTextNS("", "image", widget, 0);
	wImgH = 132;
	wImgW = 175;
	wTitle = getElementTextNS("", "location_name", widget, 0);
	
	var wDate = new Date(getElementTextNS("", "pub_date", widget, 0));
	var months = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
	wDate = months[wDate.getMonth()]+' '+wDate.getDate()+', '+wDate.getFullYear();
	wWare = getElementTextNS("", "address", widget, 0);
	wTxt = getElementTextNS("", "general_info", widget, 0);
	if(getElementTextNS("", "phone", widget, 0)!="-") phone = getElementTextNS("", "phone", widget, 0);else phone="";
	wURLInfo = getElementTextNS("", "file_name", widget, 0);
	wURLDL = getElementTextNS("", "download_link", widget, 0);
	if (wImgH/2>100) {wImgW = wImgW*100/wImgH; wImgH = 100;}
	else {wImgH = wImgH/2; wImgW = wImgW/2; wImgStyle = "margin-top: "+(100-wImgH)/2+"px;";}
	wTitle = stripDashboardTest(wTitle);
	li = document.createElement("li");
	li.innerHTML = '<a class="wid" href="'+wURLInfo+'"><img src="" id="the_logo"  border="0" style="margin-bottom:10px;"><\/a><'+h2+' style=\"text-align:center\"><a  href="'+wURLInfo+'">'+wTitle+'<\/a><\/h2><h4>'+wWare+'<\/h4><h5>'+phone+'<\/h5><p class="desc">'+wTxt+'<\/p><a class="more" href="javascript:getDetails(\''+id+'\');">Részletek...<\/a>';
    var ul = document.getElementById('level-3').getElementsByTagName('ul')[0];
    clearList(ul);
    ul.appendChild(li);
    getLogo();
}


function selecta(str,col) {
	str = str.split(' ');
	var str1 = document.createTextNode(str[0]);
	var str2 = document.createTextNode(str[1]);
	if(str.length>2) var str3 = document.createTextNode(' '+str[2]);
	var br = document.createElement('br');
	var li = document.createElement('li');
	li.id = "selecta";
	li.appendChild(str1);
	li.appendChild(br);
	li.appendChild(str2);
	if(str.length>2) li.appendChild(str3);
	var ul = document.getElementById(col).getElementsByTagName('ul')[0];
	ul.appendChild(li);
}

function appendToList(list, content, target, level, ctitle, hpi) {
    var li, a;
    li = document.createElement("li");
    a = document.createElement("a");
    a.setAttribute('href','javascript:void(0);');
    if(alternate%2==0) a.className="odd";
    if(hpi==1) a.className="highpriority";
    a.appendChild(content);
    li.appendChild(a);
    if (/xml/.test(target)) {
    if(level==0) addEventToObject(a,'onclick', function() {mainCategoryLoad(target,a);});
    else addEventToObject(a,'onclick', function() {categoryLoad(target,a,ctitle);});
    }	
    list.appendChild(li);
    return a;
}

function appendToWList(list, content, target, wid, wpriority) {
    var li,a;
    li = document.createElement("li");
    a = document.createElement("a");
    a.setAttribute('href','javascript:void(0);');
    if(alternate%2==0) a.className="odd";
    alternate++;
    if(wpriority==3) a.className="highpriority";
    a.appendChild(content);
    li.appendChild(a);
    addEventToObject(a,'onclick', function() {widgetLoad(target,a,wid)});      	
    list.appendChild(li);
}

function incompatible() {
	var div = document.getElementById('categoriesnew');
	div.parentNode.removeChild(div);
	var wbh2 = document.getElementById('wbh2');
	wbh2.parentNode.removeChild(wbh2);
}

/* DESTRUCTORS */
function clearList(target) {
   	while (target.childNodes.length > 0) {target.removeChild(target.childNodes[target.childNodes.length - 1]);}
}

function clearOvers(target,m) {
	target = target.getElementsByTagName('a');
	alternate=0;
	for (var i=0;i<target.length;i++) {
	if(target[i].className!="highpriority" && m!=1) {
	if(alternate%2==1) target[i].className="";else target[i].className="odd";
	} else {if(m==1) target[i].className='open';}
	alternate++;}
}

function stripDashboardTest(str) {
	if (/Dashboard /.test(str)) {var strTemp = str.split("Dashboard "); str = strTemp[0] + strTemp[1];}
	return str;
}

/* INITIALIZE */
function initialize_(supercategory) {
if(document.getElementById('eventbar')) document.getElementById('eventbar').style.display='none';
workingWithEvents=0;document.getElementById('level2text').innerHTML='Cégek / intézmények';
	if ((browser.isMac && browser.isIE)||(browser.isSafari && (browser.isSafari2 == false))) {incompatible();}
	else {
	var ul = document.getElementById("level-0").getElementsByTagName('ul')[0];
    clearList(ul);
	ul = document.getElementById("level-2").getElementsByTagName('ul')[0];
    clearList(ul);
    ul = document.getElementById("level-1").getElementsByTagName('ul')[0];
    clearList(ul);
	rnd=Math.floor(Math.random()*1000);
	ajaxRequest('xml/'+city+'/index_main_'+supercategory+'.xml?rnd='+rnd,initializeProcessReqChange);}
}


function getSearchResults(q){
if(document.getElementById('eventbar')) document.getElementById('eventbar').style.display='none';
document.getElementById('features').style.display='none';
document.getElementById('main').style.display='block';
workingWithEvents=0;
	if ((browser.isMac && browser.isIE)||(browser.isSafari && (browser.isSafari2 == false))) {incompatible();}
	else {
	var ul = document.getElementById("level-0").getElementsByTagName('ul')[0];
    clearList(ul);
	ul = document.getElementById("level-2").getElementsByTagName('ul')[0];
    clearList(ul);
    ul = document.getElementById("level-1").getElementsByTagName('ul')[0];
    clearList(ul);
    var url='xml/getsearchresults.php?query='+q;
	ajaxRequest(url,initializeProcessReqChange);}	
}

function getEvents(timespan,loc_id){
	workingWithEvents=1;
	document.getElementById('level2text').innerHTML='Rendezvények';
	if ((browser.isMac && browser.isIE)||(browser.isSafari && (browser.isSafari2 == false))) {incompatible();}
	else {
	var ul = document.getElementById("level-0").getElementsByTagName('ul')[0];
    clearList(ul);
	ul = document.getElementById("level-2").getElementsByTagName('ul')[0];
    clearList(ul);
    ul = document.getElementById("level-1").getElementsByTagName('ul')[0];
    clearList(ul);
   
    rnd=Math.floor(Math.random()*1000);
    var url='xml/getevents.php?rnd='+rnd+'&timespan='+timespan+'&loc_id='+loc_id;
	ajaxRequest(url,initializeProcessReqChange);}	
}

function changeClass(id){
document.getElementById(prevId).className=prevId;
document.getElementById(id).className=id+"_selected";
prevId=id;
}

function initialize(catid){
document.getElementById('features').style.display='none';
document.getElementById('main').style.display='block';
workingWithEvents=0;
document.getElementById('locationbox').src=blankpage;
if(document.getElementById('eventbar')) document.getElementById('eventbar').style.display='none';
workingWithEvents=0;document.getElementById('level2text').innerHTML='Cégek / intézmények';
if ((browser.isMac && browser.isIE)||(browser.isSafari && (browser.isSafari2 == false))) {incompatible();}
	else {
	var ul = document.getElementById("level-0").getElementsByTagName('ul')[0];
    clearList(ul);
	ul = document.getElementById("level-2").getElementsByTagName('ul')[0];
    clearList(ul);
    ul = document.getElementById("level-1").getElementsByTagName('ul')[0];
    clearList(ul);
   
    rnd=Math.floor(Math.random()*1000);
    var url='xml/getcategories.php?rnd='+rnd+'&catid='+catid;
	ajaxRequest(url,initializeProcessReqChange);}	
}



//addEventToObject(window,'onload',initialize);

 
	


