var LoadingState = false;

function SetLoadingState()
{
	LoadingState = true;

	try {
		// zavrit kalendare
		CloseCalendar (14);
		CloseCalendar (15);
	} catch (e) {};

	document.getElementById('Hledac').className='Loading';
	var resultsElm = document.getElementById('zl-no-results-counts');
	var text = "<span style='text-decoration:blink;'>Počítám zájezdy...</span>";
	resultsElm.innerHTML = text;	
}


function StopLoadingState()
{
	LoadingState = false;

	document.getElementById('Hledac').className='Ready';
	document.getElementById('zl-no-rc-box').className='Changed';

	try {
		HiliteShowResults();
	}
	catch (e) {}
}

function makeRequest( url , ResponseHandler ) {

	var http_request = false;

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();

		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/plain');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert('Cannot create an XMLHTTP instance');
		return false;
	}

	try {
		http_request.onreadystatechange = function() { ResponseHandler(http_request); };
		http_request.open( 'GET', url, true);
		http_request.send( null );
	}
	catch (e) {
		alert ( e );
	}
}


function HandleSearchSuggest ( http_request )
{
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			ProcessNextOffers(http_request.responseText);
		} else {
			//posralo se
		}
	}
}

//Levely
var Criteria = new Array( 10, 4, 3, 5, 6, 7, 8, 9 , 12, 18 );
	
//Jen datumy
var DatumCriteria = new Array ( 14, 15 );

function ProcessNextOffers ( NOText )
{
	StopLoadingState();

	NOLines = NOText.split('\n');

	var LineNo;
	var Line;
	var Fields;
	var AfterSeparator = false;

	for (LineNo in NOLines)
	{
		Line = NOLines[LineNo];
		Fields = Line.split('#');

		if ( Fields[0] =='ResultCounts')
		{
			var ZajezdCount = Fields[1];
			var TurnusCount = Fields[2];
			var MinPrice = Fields[3];
			InjectResultsCounts ( ZajezdCount, TurnusCount, MinPrice );
		}
		else if ( IsDatumConstraint ( Fields[0] ) )
		{
			var ConstraintID = Fields[0];
			var Datum = Fields[1];
			var MinDate = Fields[2];
			var MaxDate = Fields[3];
			var OFMinDate = Fields[4];
			var OFMaxDate = Fields[5];

			document.getElementById( 'c_' + ConstraintID + '_mindate' ).value = MinDate;
			document.getElementById( 'c_' + ConstraintID + '_maxdate' ).value = MaxDate;
			document.getElementById( 'c_' + ConstraintID + '_ofmindate' ).value = OFMinDate;
			document.getElementById( 'c_' + ConstraintID + '_ofmaxdate' ).value = OFMaxDate;

//			alert ( 'datum: ' + Line );
		}
		else 
		{
			var ConstraintID = Fields[0];
			var LevelNo = Fields[1];
			var Value = Fields[2];
			var OptionText = Fields[3];
			var Count = Fields[4];
			var MinPrice = Fields[5];
			var IsSelected = Fields [6];
			var LocalDepth = Fields [7];

			var BoldIt = false;
			
			/* Category Spacer Effect */
			/*					
			if ( ( ConstraintID == '4' ) && ( LevelNo == '0' ) && ( LocalDepth == '0' ) )
			{
				if ( ! AfterSeparator )
					InjectNextOffer( ConstraintID, LevelNo, "", "&nbsp;", 0, 0, false, true, false );
				BoldIt = true;
			}
			*/	

			InjectNextOffer( ConstraintID, LevelNo, Value, OptionText, Count, MinPrice, IsSelected, false, BoldIt );

			/* Separator Effect */
			AfterSeparator = false;
			if ( Value == '---' )
			{
				AfterSeparator = true;
				InjectNextOffer( ConstraintID, LevelNo, "", "&nbsp;&nbsp;---------------------------------------", 0, MinPrice, false, true, false );
			}
		}
	}
}

function InjectResultsCounts ( ZajezdCount, TurnusCount, MinPrice )
{
	var resultsElm = document.getElementById('zl-no-results-counts');

	ZajezdCount = parseInt ( ZajezdCount );

	if ( ZajezdCount > 0 )
	{ 			
		var ZajezdSklon;
		
		if ( ZajezdCount > 4 )
			ZajezdSklon = 'zájezdů';
		else if ( ZajezdCount > 1 )
			ZajezdSklon = 'zájezdy';
		else if ( ZajezdCount = 1 )
			ZajezdSklon = 'zájezd';

		var TurnusSklon;
		
		if ( TurnusCount > 4 )
			TurnusSklon = 'termínů';
		else if ( TurnusCount > 1 )
			TurnusSklon = 'termíny';
		else if ( TurnusCount = 1 )
			TurnusSklon = 'termín';


		
		var text = "<b>" + ZajezdCount + "</b>&nbsp;" + ZajezdSklon + 
				   " / <b>" + TurnusCount + "</b>&nbsp;" + TurnusSklon + 
				   " <span class='bx'>od&nbsp;<b>" + MinPrice + ' Kč</b></span>';
	}
	else
	text = '<b>ľádné vyhovující zájezdy</b>';


	resultsElm.innerHTML = text;
}

function InjectNextOffer( ConstraintID, LevelNo, Value, OptionText, Count, MinPrice, IsSelected, Disabled, BoldIt )
{

	levelElement = document.getElementById ( 'c' + ConstraintID + '_' + LevelNo );
			
	if ( levelElement == null )
		return;


	if ( ! Disabled )	
		OptionText += ' (' + Count + ')'

	if ( Value == levelElement.value)
	{
		var newEmptyOption = levelElement.options[levelElement.selectedIndex];
		newEmptyOption.innerHTML = OptionText ;
	}
	else
	{
		var newEmptyOption = document.createElement ('option');
		newEmptyOption.value = Value;
		newEmptyOption.innerHTML = OptionText ;

		if ( IsSelected == '1' ) newEmptyOption.selected=true;
	}
	
	if ( Disabled )
		newEmptyOption.disabled=true;
		
	if ( BoldIt ) newEmptyOption.style.fontWeight='bold';

	levelElement.appendChild ( newEmptyOption );
	levelElement.disabled = false;
	levelElement.className='';
}
	

function GenerateFilterString ()
{
	var FilterString = '';
	
	for ( key in Criteria )
	{
		var critVal = FindValueForConstraint ( Criteria[key] );
		if ( critVal != null )
		{
			if ( FilterString != '' )
				FilterString += ','
			FilterString += Criteria[key] + '~' + critVal;
		}
	}

	for ( key in DatumCriteria )
	{
		levelElement = document.getElementById ( 'c' + DatumCriteria[key] );
		
		if ( levelElement == null )
			continue;
		
		if ( levelElement.disabled )
			continue;
		
		if ( levelElement.value=='' )
			continue;

		if ( FilterString != '' )
			FilterString += ','
		
		FilterString += DatumCriteria[key] + '~' + levelElement.value;
	}

	return FilterString;
}


function SetEnabledDepth ( ConstraintID, LevelNo )
{
	var d;
	var levelElement;

	for ( d=2; d > LevelNo; d-- )
	{
		levelElement = document.getElementById ( 'c' + ConstraintID + '_' + d );
		if ( levelElement != null )
		{
			levelElement.disabled=true;
			levelElement.className='zl-sel-disabled';
			levelElement.innerHTML = '';
		} 
	}

	for ( d=LevelNo; d >= 0 ; d-- )
	{
		levelElement = document.getElementById ( 'c' + ConstraintID + '_' + d );
		if ( levelElement != null )
			levelElement.disabled=false; 
	}
}

function RemoveUnselectedOptions ()
{
	var d;
	var i;

	for ( key in Criteria )
	{
		for ( d=2; d >= 0; d-- )
		{
			var levelElement = document.getElementById ( 'c' + Criteria [ key ] + '_' + d );
			if ( levelElement == null ) continue;
			if ( levelElement.disabled ) continue;

			for (i = levelElement.length - 1; i>=0; i--) 
			   	if (! levelElement.options[i].selected) 
			     	levelElement.remove(i);
		}
	}			
}

function FindValueForConstraint ( ConstraintID )
{
	var d;

	for ( d=2; d >= 0; d-- )
	{
		levelElement = document.getElementById ( 'c' + ConstraintID + '_' + d );
		if ( levelElement == null ) continue;
		if ( levelElement.disabled ) continue;
		if ( levelElement.value=='---' ) continue;
		return levelElement.value;
	}
	
	return null;			
}

var SearchSuggestURL = '/SearchSuggestF.php?filter=';

function HandleChange( ConstraintID, LevelNo )
{
	SetLoadingState();
	SetEnabledDepth ( ConstraintID, LevelNo );
	RemoveUnselectedOptions();
	var FS =  GenerateFilterString();
	var URL = SearchSuggestURL + FS;
	makeRequest (URL , HandleSearchSuggest );
}

/*
 *	Testy pro datum z kalendare (odjezd/navrat)
*/

function HandleDateChange ( ConstraintID )
{
	SetLoadingState();
	/* tady to zatim pracuje jen s NOHoldrama*/
	RemoveUnselectedOptions ();
	var FS =  GenerateFilterString();
	var URL = SearchSuggestURL + FS;
	makeRequest (URL , HandleSearchSuggest );
}

function IsDatumConstraint ( ConstraintID )
{
	for (i=0; i<DatumCriteria.length; i++)
	{
		if ( DatumCriteria [i] == ConstraintID )
			return true;
	}
	
	return false;
}
