if (document.images) {
}
function imgOn(imgName) {
	if (document.images) {
		oSrc=document[imgName].src;
		document[imgName].src = eval(imgName + "on.src");
	}
}
function imgOff(imgName) {
	if(oSrc){
		document[imgName].src = oSrc;
	}
}

// ------------------------------------
// -------- showPopupBox --------------
// ------------------------------------
function showPopupBox(url,params) {
	new Ajax.Request(url,{
		method: 'get',
		onComplete: function(transport) {
			var dim = document.viewport.getDimensions();
			var scr = document.viewport.getScrollOffsets();
			$('popupBox').style.display = 'none';
			$('popupBoxContent').innerHTML = '';
			$('popupBox').style.left = ((dim['width']-params['width']-20)/2+scr['left']) + 'px';
			$('popupBox').style.top = ((dim['height']-params['height']-20)/2+scr['top']) + 'px';
			$('popupBox').style.width = '0px';
			$('popupBox').style.width = 1;// (params['width']+20) + 'px';
			$('popupBox').style.height = 1;// (params['height']+20) + 'px';
			$('popupBox').style.display = '';
			$('popupBox').style.overflow = 'hidden';
			
			new Effect.Scale($('popupBox'),100, { 
				duration: 0.2,
				//from: 0.7, to: 1,
				scaleContent: true, 
				scaleFrom: 50, 
				scaleMode: {originalHeight: params['height']+20, originalWidth: params['width']+20},
				afterFinish: function(ef) {
//					$('popupBoxContentHolder').style.width = (params['width']-30) + 'px';
					$('popupBoxContentHolder').style.height = (params['height']-30) + 'px';
					$('popupBoxContentHolder').style.overflow = 'auto';
					$('popupBoxContent').innerHTML = transport.responseText;

					if (params['closeOnClick']) {
						Event.observe(window, 'click', function() {
							$('popupBox').style.display = 'none';
							$('popupBoxContent').innerHTML = '';
						});
					} else {
						Event.observe($('popupBoxClose'), 'click', function() {
							$('popupBox').style.display = 'none';
							$('popupBoxContent').innerHTML = '';
						});
					}
				}
			});
			/*
			new Effect.Scale($('popupBox'), 100, {
				duration: 0.4,
				scaleContent: true, 
				scaleFrom: 50, 
				scaleFromCenter: true, 
				scaleMode: {originalHeight: params['height']+20, originalWidth: params['width']+20},
				afterFinish: function(ef) {
					$('popupBoxContent').innerHTML = transport.responseText;

					Event.observe($('popupBox'), 'click', function() {
						$('popupBox').style.display = 'none';
						$('popupBoxContent').innerHTML = '';
					});

				}
			});
			*/
		}
	});
}

// ------------------------------------
// ------- populateCategoryTree -------
// ------------------------------------
function populateCategoryTree(categoryId){
	var fs;
	var c=document.getElementById("ctg");

	var cid = categoryId;
	cid = parseInt(cid);
	
	c.options.length =0;
	c.options[0] = new Option('Loading ...','',false,false);

  new Ajax.Request('../ajax_functions.php?action=get_categories', {
                    asynchronous:true,
                    onComplete:function(request){
                        var json, i;
                            eval('json = ' + request.responseText);
                                c.options.length =0;
                                c.options[0] = new Option('-- Select Category --','',false,false);
                                for (i=0;i<json.length;i++) {
                                prefix ='';
                                for (j=0;j<json[i].prefix_lenght;j++) prefix=prefix + '--';
										  c.options[i+1] = new Option(prefix + json[i].category_name,json[i].category_id,false,false);                                                      
										  if (json[i].category_id == cid || json.lenght == 1) c.selectedIndex = i+1;
										  if(json[i].prefix_lenght == 0){
											  c.options[i+1].style.fontSize = '110%';
											  c.options[i+1].style.fontWeight="700";											
											} else if (json[i].prefix_lenght < 4 ){
												fs = 110 - (json[i].prefix_lenght * 10);
												fs = fs + '%'	
										  		c.options[i+1].style.fontSize = fs ;										
											} else c.options[i+1].style.fontSize = '80%';

										 }
                    }
	});

}



// ---------------------------------------
// ------- populateCategories   -------
// ---------------------------------------
function populateCategories(category_id,prefix,selCatId) {
  var i,cat_id,cid,st,fs,scid;

	var scid = parseInt(selCatId) + 0;
	var selected_categories = ',' + scid + ',';
  category_id = parseInt(category_id) + 0;

  if (parents[category_id]) {
    for (i=0;i<parents[category_id].length;i++) {
      cid = parents[category_id][i];

      if (selected_categories.indexOf(',' + cid + ',') >= 0){
      	sel = 'SELECTED';
      }
      else{ 
      	sel = '';
      }      

			// make root categories bigger and bold
			if (categories[cid].level == 0) st = 'style="font-size: 110%; font-weight: bold;"';
			else if (categories[cid].level < 4){
				fs = 110 - (categories[cid].level)*10 ;
				st = 'style="font-size: ' + fs + '%; font-weight: normal;"';
			} else st = 'style="font-size: 80%; font-weight: normal;"';
			
      document.write('<option value="' + cid + '" ' + sel + ' ' + st + '>' + prefix + categories[cid].name +'</option>\n');
      populateCategories(cid,prefix + '--',scid);
    }
  }
}


//-------------------------------
// generateGetString
// ------------------------------
function generateGetString(parentNode){
	
	var field;
	var url_request='';
	var prefix='';

	//walkTree(table);

	//alert(table.getElementsByTagName('select').length);
	var select_fields = parentNode.getElementsByTagName('select');
	if(select_fields){
		for(i=0; i<select_fields.length; i++){
			//alert(select_fields[i].multiple);
			field = select_fields[i];
			for(j=0; j<field.options.length; j++){
				if(field.options[j].selected){
					//alert(field.options[j].value);
					url_request = url_request + '&' + field.name + '=' + escape(field.options[j].value);
				}
			}		
		}
	}

	//alert(table.getElementsByTagName('input').length);
	var input_fields = parentNode.getElementsByTagName('input');
	if(input_fields){
		for(i=0; i<input_fields.length; i++){
			field = input_fields[i];
			switch(field.type){
				case 'text':{
					url_request = url_request + '&' + field.name + '=' + escape(field.value);
				  break;   
				}   
				case 'checkbox':{
					if(field.checked){
						//alert(field.value);			  
						url_request = url_request + '&' + field.name + '=' + escape(field.value);
					}
				  break;
				}
				case 'radio':{
					url_request = url_request + '&' + field.name + '=' + escape(field.value);
				  break;
				}
				case 'hidden':{
					url_request = url_request + '&' + field.name + '=' + escape(field.value);
				  break;   
				}
				default:{
				}
			}
		}
	}

	//alert(table.getElementsByTagName('textarea').length);
	var textarea_fields = parentNode.getElementsByTagName('textarea');
	if(textarea_fields){
		for(i=0; i<textarea_fields.length; i++){
			field = textarea_fields[i];
			url_request = url_request + '&' + field.name + '=' + escape(field.value);
		}
	}

	return(url_request);
}

//----------------------------------
// changeRelatedContent(el,url)
//----------------------------------
function changeRelatedContent(el,url) {
	new Ajax.Request(url,{
	  method: 'get',
	  onComplete: function(transport) {
	  	$('related_loading').style.display = 'none';

	  	var realEl = $(el);
	  	var p = document.createElement('div');
	  	p.innerHTML = transport.responseText;

	  	if (p.firstChild && p.firstChild.innerHTML) {
		  	realEl.innerHTML = p.firstChild.innerHTML;
		  } else {
		  	realEl.innerHTML = p.innerHTML;
		  }  	
	  }
	  }
	);
}

//---------------------------------
// CopyToClipboard()
// --------------------------------
function CopyToClipboard() {
   CopiedTxt = document.selection.createRange();
   CopiedTxt.execCommand("Copy");
}

function populateTopCountries(country) {
	var f = document.forms.search_top;
	var el = f.elements['country'];
	var i;

	el.options.length = 0;
	for (i in countries) {
		el.options[el.options.length] = new Option(countries[i].name,countries[i].code);
		if (country == countries[i].code)
			el.selectedIndex = el.options.length-1;
	}
}

function populateTopCities(city_id) {
	var f = document.forms.search_top;
	var cEl = f.elements['country'];
	var el = f.elements['data[city_id]'];
	var i, country_id = 0;
	
	if (cEl.selectedIndex >= 0) {
		country = cEl.options[cEl.selectedIndex].value;
	}
	
	el.options.length = 0;
	el.options[el.options.length] = new Option('Svi gradovi','',false,false);
	if (country != '') {
		for (i in city_by_parent[country]) {
			cid = city_by_parent[country][i];
			if (!cities[cid]) continue;
			el.options[el.options.length] = new Option(cities[cid].name,cid);
			if (cid == city_id)	
				el.selectedIndex = el.options.length - 1;
		}
	}
}

function changeFormAction(el) {
	var f = document.forms.search_top;
	
	//f.action = '/zemlja/' + el.options[el.selectedIndex].value + '/';
	
	window.location = '/zemlja/' + el.options[el.selectedIndex].value + '/';
	
}

// AJAX category selection functions
function populateSubCategories(pid,params) {
	var fs;
	if(!pid) pid=0;
	
	if (params && params['catSelectEl'])
		var c=$(params['catSelectEl']);

	pid = parseInt(pid);
	if (c && c.options) {
		c.options.length =0;
		c.options[0] = new Option('Loading ...','',false,false);
	}

	if (!params['rootPrefix']) params['rootPrefix'] = '../';

	var url = params['rootPrefix']+'ajax_functions.php?action=get_subcategories&data[parent_id]='+pid;
	if (params['activeOnly'] && params['activeOnly'] == true) url += '&data[active]=yes';

  new Ajax.Request(url, {
                    asynchronous:true,
                    onComplete:function(request){
											var json, i;
											eval('json = ' + request.responseText);
											c.options.length =0;
											c.options[0] = new Option('-- Select Category --','',false,false);
											for (i=0;i<json.length;i++) {
												prefix ='';
												//for (j=0;j<json[i].prefix_lenght;j++) prefix=prefix + ' -- ';
											  c.options[i+1] = new Option(prefix + json[i].category_name,json[i].category_id,false,false);
											  /*
											  if(json[i].prefix_lenght == 0){
												  c.options[i+1].style.fontSize = '110%';
												  c.options[i+1].style.fontWeight="700";											
												} else if (json[i].prefix_lenght < 4 ){
													fs = 110 - (json[i].prefix_lenght * 10);
													fs = fs + '%'	
											  		c.options[i+1].style.fontSize = fs ;										
												} else c.options[i+1].style.fontSize = '80%';
												*/
											}
											if (json.length == 0) {
												c.style.display = 'none';
											} else {
												c.style.display = '';
											}
                   }
	});

}

function createPath(pid,params) {
	
	if(!pid) pid=0;
	var x=document.getElementById("ctg");
	pid = parseInt(pid);
	
	if (!params['categoryPathEl']) params['categoryPathEl'] = '';
	if (params['categoryPathEl'] && params['categoryPathEl'] != '')
		var y=document.getElementById(params['categoryPathEl']);
	else
		var y=document.getElementById("categoryPath");

	if (!params['rootPrefix']) params['rootPrefix'] = '../';
	var url = params['rootPrefix'] + 'ajax_functions.php?action=get_category_path&data[category_id]='+pid;
	
  texts = '<a href="#" onclick="createPath(0,{categoryPathEl: \''+params['categoryPathEl']+'\',catSelectEl: \''+params['catSelectEl']+'\',catFieldEl: \''+params['catFieldEl']+'\',rootPrefix: \''+params['rootPrefix']+'\',activeOnly: \''+params['activeOnly']+'\'}); return false;">start</a> ';

  new Ajax.Request(url, {
	                  asynchronous:true,
	                  onComplete:function(request){
											var json, i;
											eval('json = ' + request.responseText);

											for (i=0;i<json.length;i++) {
												texts=texts+' &#187; <a href="#" onclick="createPath('+json[i].category_id+',{categoryPathEl: \''+params['categoryPathEl']+'\',catSelectEl: \''+params['catSelectEl']+'\',catFieldEl: \''+params['catFieldEl']+'\',rootPrefix: \''+params['rootPrefix']+'\',activeOnly: \''+params['activeOnly']+'\'}); return false;" >';
												texts=texts + json[i].category_name;
												texts=texts+'</a> ';											 
											}
											y.innerHTML = texts;	
										}
	});

	if (params && params['catFieldEl'])
		$(params['catFieldEl']).value = pid;
	
	if (params && params['catSelectEl']) {
		populateSubCategories(pid,params);
	}
		
//	var z=document.getElementById("catId");
//	z.value = pid;

}

function drawLine(lineObjectHandle, Ax, Ay, Bx, By)
{
    /*
     *	lineObjectHandle = an IMG tag with position:absolute
     */
    //alert(Ax + ' ' + Ay + ' ' + Bx + ' ' + By);
    var
        xMin        = Math.min( Ax, Bx ),
        yMin        = Math.min( Ay, By ),
        xMax        = Math.max( Ax, Bx ),
        yMax        = Math.max( Ay, By ),
        boxWidth    = Math.max( xMax-xMin, 1 ),
        boxHeight   = Math.max( yMax-yMin, 1 ),
        tmp         = Math.min( boxWidth, boxHeight ),
        smallEdge   = 1,
        lineImgPath = '../images/lines/',
        newSrc;

    while( tmp>>=1 )
        smallEdge<<=1;

    newSrc = lineImgPath+ smallEdge +( (Bx-Ax)*(By-Ay)<0?"up.gif":"down.gif" );
    if( lineObjectHandle.src.indexOf( newSrc )==-1 )
        lineObjectHandle.src = newSrc;

    with( lineObjectHandle.style )
    {
        width   = boxWidth	+"px";
        height  = boxHeight	+"px";
        left    = xMin		+"px";
        top     = yMin		+"px";
        display = '';
    }
}

// Filter form visibility toggle
function toggleFilterFormVisibility(formEl,buttonEl) {
	if (formEl.style.display == 'none') {
		formEl.style.display = '';
		buttonEl.src = 'images/button-hideFilter.png';
	  new Ajax.Request('ajax_functions.php?action=set_category_filter&status=yes', {asynchronous:true});	  
	} else {
		formEl.style.display = 'none';
		buttonEl.src = 'images/button-showFilter.png';
	  new Ajax.Request('ajax_functions.php?action=set_category_filter&status=no', {asynchronous:true});
	}
}

/*
 * Handlers for automated loading
 */ 
 _LOADERS = Array();

function callAllLoaders() {
	var i, loaderFunc;
	for(i=0;i<_LOADERS.length;i++) {
		loaderFunc = _LOADERS[i];
		if(loaderFunc != callAllLoaders) loaderFunc();
	}
}

function appendLoader(loaderFunc) {
	if(window.onload && window.onload != callAllLoaders)
		_LOADERS[_LOADERS.length] = window.onload;

	window.onload = callAllLoaders;

	_LOADERS[_LOADERS.length] = loaderFunc;
}

