var gDestinationListIATA = Array();
var gDestinationListCities = Array();
var gDestinationListCitiesIndex = Array();
var gDestinationListCountries = Array();
var gDestinationListCountriesIndex = Array();
var gDestinationListAirports = Array();
var gDestinationListAirportsIndex = Array();
var gDestinationListCountriesCode = Array();

var nMinOptionLinesCount;
var nMaxOptionLinesCount;
var nMaxAvailOptionsCount;

/**
 * Class AirportList
 *
 * @param string idActive
 * @param string idAirportList
 * @param string idTargetInput
 */
function AirportList(idActive, idAirportList, idAirportListData, reloadOnOpen) {

    /*
	 * @var reloadOnOpen boolean Pregenerovat data vzdy pri otevreni okna?
	 */
    this.reloadOnOpen = reloadOnOpen;
    /*
	 * @var idActive string ID DOM objektu, ktery zobrazi seznam letist - obrazek, span, input atp.
	 */
	this.idActive = '';
	/*
	 * @var idCal string ID DOM objektu, ktery obaluje seznam letist
	 */
	this.idAirportList = idAirportList;	
	/*
	 * @var idAirportListData string ID DOM seznamu, ktery obsahuje seznam zemi
	 */
	this.idAirportListData = idAirportListData;
	/*
	 * @var elAirportList DOMobjekt Obaluje kalendar
	 */
	this.elAirportList = null;
	/*
	 * @var destOpenAirportListId pole ID DOM objektu, ktere po kliknuti vyvolaji popup se seznamem letist
	 */
	this.destOpenAirportListId = null;
	/*
	 * @var idTargetInput string ID DOM objektu, kam se vlozi vybrana hodnota
	 */
	this.idTargetInput = '';
    /*
	 * @var identName string
	 */
	this.identName = '';
    /*
	 * @var integer
	 */
	this.loadIndex = 0;
	/*
	 * @var isTargetSelectElement oznaceni zda target ID odpovida HTML selectu
	 */
	this.isTargetSelectElement = false;
	/*
	 * @var idClickedEleToShowAirports ID elementu, na ktery uzivatel kliknul, aby otevrel seznam letist
	 */
	this.idClickedEleToShowAirports = '';
	/*
     * @var activeSelect je prave otevrene okno?
     */
	this.activeSelect = false;
	/*
     * @var activeCityClass trida, ktera se prida aktivnimu status
     */
	this.activeCityClass = 'active';
    /*
     * @var activeAirportClass trida, ktera se prida aktivnimu letisti
     */
	this.activeAirportClass = 'active';
    /*
     * @var activeAirportPopup ID prave otevreneho AirportListu
     */
	this.activeAirportPopup = '';
}
	
/*
 * Hlavni medota pro zavolani seznamu letist podle zeme
 */
AirportList.prototype.setAirportList = function(destOpenAirportListId) {
		var sIdDomElements = '';
		var thisObject = this;
		this.elAirportList = jQ(this.idAirportList);
        this.destOpenAirportListId = destOpenAirportListId;

		// Nastavuje udalost pro zobrazeni vyberu seznamu letist
		for(i = 0; i < this.destOpenAirportListId.length; i++){
		    if((destOpenAirportListId.length-1) != i) {
		        sIdDomElements += "#"+destOpenAirportListId[i]+", ";
		    } else {
		        sIdDomElements += "#"+destOpenAirportListId[i];
		    }
		}
		
		jQ("#closeAirportList" +  this.identName).unbind('click.closeAirportList').bind('click.closeAirportList',function(event){
		    thisObject.closeAirportList();
		});
		
		jQ(sIdDomElements).unbind('click').bind('click',function(event) {
            idTargetInput = jQ('#'+jQ(this).attr('id')).parent().find('input').attr('id');
		    thisObject.isTargetSelectElement = false;		    
		    
		    //neni input s timto ID - napr. korporatni profily - select box misto inputu
		    if ( typeof idTargetInput == 'undefined' ) {
		        thisObject.isTargetSelectElement = true;
		        thisObject.idClickedEleToShowAirports = jQ(this).attr('id');
		        idTargetInput = jQ('#'+jQ(this).attr('id')).parent().parent().find('select').attr('id');
		    }
		    thisObject.idTargetInput = '#'+idTargetInput;
		    	
            // Zavira ostatni kalendare  
            var activeAirportPopupLoc = thisObject.activeAirportPopup;
            jQ('body').click();
            event.stopPropagation();
		  
            idClickedElement = jQ(this).attr('id');
            //nastaveni class pro popup - fyzicky je v DOMu pouze jedno popup okno, ktere se
            //posouva podle toho, kde uzivatel popup okno airport list vyvolal
            var clickedElePositionInArray = thisObject.getIndexOfArrayElement(thisObject.destOpenAirportListId, idClickedElement);
            
            // neotevirat znovu okno, ktere je jiz otevrene
            if (activeAirportPopupLoc === clickedElePositionInArray) {
                return ;
            } else {
                thisObject.activeAirportPopup = clickedElePositionInArray; 
            }
            
            // Zobrazuje airpot list
            thisObject.openWithAjaxData(clickedElePositionInArray);
            jQ(this).addClass('active');
            
            jQ('body').bind('click.closeAirportList', function(event) {
                jQ('body').unbind('click.closeAirportList');
                if (jQ(thisObject.idAirportList).css('display') == 'block') {
                    thisObject.closeAirportList();
                }
            });
            
            jQ(thisObject.idAirportList).unbind('click.idAirportList').bind('click.idAirportList', function(event){
                event.stopPropagation();
            });
	      
		});		
}

/**
 * Slouzi k nacitani dat z jineho zdroje. 
 */
AirportList.prototype.openWithAjaxData = function(clickedElePositionInArray) {

    var thisObject = this;
    var isOpen = false;
        
    this.loadIndex++;
    
    // pojistka
    if (this.loadIndex > 20) {
        // pojistka pojistky - pokud dojde k ukonceni musi byt pote moznost znova opakovat akce
        this.loadIndex = 0;
        return false;
    }

    if (typeof(gDestinationListCountriesCode) != "undefined") {
        if (gDestinationListCountriesCode.length > 0) {
            isOpen = true;
        }
    }

    if (isOpen) {
        this.openAirportList(clickedElePositionInArray);        
        this.loadIndex = 0;
    } else {
        var t = setTimeout(function() {thisObject.openWithAjaxData(clickedElePositionInArray)}, 100);
    }
    
    return true;
}

/**
 * Najde v poli dany string (element) a vrati pozici v poli
 */
AirportList.prototype.getIndexOfArrayElement = function(aElements,idElement) {
	var indexElement = -1;

	for (var i = 0; i < aElements.length; i++){
		if(aElements[i] == idElement) {
		    indexElement = i; break;
		}
	}
	
	return indexElement;
}

AirportList.prototype.openAirportList = function(clickedElePositionInArray) {	
	
	var thisObject = this;
    var airportListUlObject = jQ(thisObject.idAirportListData + ' ul.list');
	
    //ziska vsechny class ze stejnojmeneho atributu class
    eleClasses = jQ(thisObject.idAirportList).attr('class').split(' ');
    
    //vlozi vsechny puvodni class + nova class pro posunuti okna
    var popupAirportListClass = 'pa_position'+(clickedElePositionInArray+1);
	
	//je combo pro specifikaci vyberu letiste
	//stava se v pripade pokud se do inputu zada napr. Francie - nejednoznacne letiste
	if(jQ('#airportListWithCombo').size() > 0) {
	    popupAirportListClass += ' airport_list_combo'+(clickedElePositionInArray+1);
	}
	
	if(eleClasses[3] != popupAirportListClass){               
        jQ(thisObject.idAirportList).removeAttr('class');
        jQ(thisObject.idAirportList).attr('class',eleClasses[0]+' '+eleClasses[1]+' '+eleClasses[2]+' '+popupAirportListClass);
        	    
	    //nastaveni nadpisu - kazdy sudy = 'Odkud', kazdy lichy = 'Kam'
        if((clickedElePositionInArray % 2) == 0) {
            jQ('#titleAirportList' + this.identName).empty().append('De');
        } else {
            jQ('#titleAirportList' + this.identName).empty().append('A');
        }
	} 
	
    //zobrazeni okna	
	jQ(this.idAirportList).show("slide", { direction: "up" }, 600);
    thisObject.activeSelect = true;
	
	// generovani seznamu
	this.generateCountriesCombo();
	            
    // auto scroll na aktualni letiste
    var targetValue = jQ(thisObject.idTargetInput).attr('value');
    if (targetValue != '') {
        var selectedAirportCode = this.getAirportCodeByString(targetValue);
        var selectedAirportPosition = this.setAirportPositionInList(selectedAirportCode);
    }
    
    // odchyceni klaves
    thisObject.setKeyEvent(airportListUlObject);
    
    // nastaveni hover efektu
    var elListCity = airportListUlObject.find('li.city');
    jQ(elListCity).hover(
        function() { jQ(this).addClass(thisObject.activeCityClass); },
        function() { jQ(this).removeClass(thisObject.activeCityClass); }
    );
    var elListAirports = airportListUlObject.find('li.city ul li a');
    jQ(elListAirports).hover(
        function() { jQ(this).addClass(thisObject.activeAirportClass); },
        function() { jQ(this).removeClass(thisObject.activeAirportClass); }
    );
}

/**
 * Pole zacinajici g - z pohledu indexu jsou v pomeru 1:1 
 */
AirportList.prototype.getCountriesArray = function() {
	var countriesArray = gDestinationListCountries; //Array('Německo', 'Německo', 'Uzbekistán', , 'Dánsko', 
	return countriesArray;
}
AirportList.prototype.getCountriesIndexArray = function() {
	var countriesIndexArray = gDestinationListCountriesIndex; //Array('NEMECKO', 'NEMECKO', 'UZBEKISTAN', 'DANSKO',
	return countriesIndexArray;
}
AirportList.prototype.getCountriesCodeArray = function() {
	var countriesCodeArray = gDestinationListCountriesCode; //Array('DE', 'DE', 'UZ'
	return countriesCodeArray;
}

/**
 * Vrati kod letiste ze stringu cele lokace (Mesto, Nazev letiste (KOD))
 */
AirportList.prototype.getAirportCodeByString = function(locationString) {
    
    var airportCode = '';
    var strLen = locationString.length;
    
    // format "XXX"        
    if (strLen == 3) {
        airportCode = locationString; 
    // format "text (XXX)"; substr(-1) nefunguje v IE
    } else if (locationString.substring(strLen -1, strLen) == ')' && 
               locationString.substring(strLen -5, strLen -4) == '(') {
        airportCode = locationString.substring(strLen -4, strLen -1);
    }
    
    return airportCode.toUpperCase();
}

/**
 * Vygeneruje hlavni seznam status a jejich letist
 */
AirportList.prototype.generateCountriesCombo = function() {

	var thisObject = this;
	var countriesArray = this.getCountriesArray();
	var countriesCodeArray = this.getCountriesCodeArray();

	if(typeof countriesCodeArray != 'undefined') {
    	countriesArray = this.makeUnique(countriesArray);
    	countriesCodeArray = this.makeUnique(countriesCodeArray);
    																							
    	countriesCount = countriesArray.length; 
    	
    	// odmazani dat
    	if (thisObject.reloadOnOpen == true) {
    	    jQ(thisObject.idAirportListData).removeClass('filled');
    	    jQ(thisObject.idAirportListData + ' ul.list').find('li.city:not(.li_hide)').remove();
    	}
    	
    	if (!(jQ(thisObject.idAirportListData).hasClass('filled'))) {
    		jQ(thisObject.idAirportListData).addClass('filled'); 
    
            // generovani seznamu
    		for (var i = 0; i < countriesCount; i++) {
    		    // staty
    			airportHtmlList = '<li class="city"><span>'+countriesArray[i]+'</span><ul>';
    			var countryAirports = this.getAirportsByCountry(countriesCodeArray[i]);
    			// letiste
                for (var e = 0; e < countryAirports.length; e++) {
                    airportHtmlList += '<li><a href="javascript:dummy();" class="'+countryAirports[e][2]+'">'+
                                       countryAirports[e][0]+', '+countryAirports[e][1]+' ('+countryAirports[e][2]+')'+
                                       '</a></li>';
                }
    			airportHtmlList += '</ul></li>';
                jQ(thisObject.idAirportListData + ' ul.list').append(airportHtmlList);
    	    };

    		//pridani reakce na vyber statu
            jQ(thisObject.idAirportListData + ' ul a').click(function() {
                if( thisObject.isTargetSelectElement ) {
                    thisObject.isTargetSelectElement = false;
                    thisObject.setInputFromSelect();
                }
                jQ(thisObject.idTargetInput).attr('value', jQ(this).text());
                jQ(thisObject.idTargetInput).change();
                thisObject.closeAirportList();
            });
            
            jQ(thisObject.idAirportListData).jScrollPane({
                showArrows: true,
                dragMinHeight: 10,
                scrollbarWidth: 17,
                enableKeyboardNavigation: false,
                scrollbarMargin: 0,
                maintainPosition: true
            });
    	}
	
	} else {
	    alert('predict_new.txt musi obsahovat pole - gDestinationListCountriesCode');
	}

}

/**
 * Nastavi pozici letiste v seznamu
 */
AirportList.prototype.setAirportPositionInList = function(airportCode) {

    var thisObject = this;
    var elAirportBoxUl = jQ(thisObject.idAirportListData + ' ul.list');
    var searchEl = jQ(elAirportBoxUl).find('.'+airportCode);
    
    var searchElPosition = this.getAirportPositionInList(searchEl);
    
    // rezerva
    if (searchElPosition > 0) {
        searchElPosition -= 20;
    } 
    
    searchEl.addClass(thisObject.activeAirportClass);
    jQ(elAirportBoxUl).parent().parent().find('.scroll-pane')[0].scrollTo(searchElPosition);
}

/**
 * Vrati pocet pixelu ve scrollListu od zacatku k hledanemu elementu 
 */
AirportList.prototype.getAirportPositionInList = function(searchedElement) {
    
    var scrollIndex = 0;
    
    // prochazi seznam predchozich statu
    searchedElement.parent().parent().parent().prevAll().each(function(index) {
        scrollIndex = scrollIndex + jQ(this).height();  
    });
    
    // prochazi predchozi letiste statu hledaneho elementu
    searchedElement.parent().prevAll().each(function(index) {
        scrollIndex = scrollIndex + jQ(this).height();  
    });
    
    return scrollIndex;
}

/**
 * Vrati pole jen s unikatnimi prvky
 */
AirportList.prototype.makeUnique = function(oldArr) {
	var tmpArr = oldArr.slice(0);	//slice(0) vytvori kopii puvodniho pole, abych i to puvodni nechtene neseradil
	//tmpArr.sort();
	var j=0;
	var newArr = new Array()

	for (var i = 0; i < tmpArr.length;i++){
		newArr[j] = tmpArr[i];
		j++;
		if ((i>0) && (tmpArr[i] == tmpArr[i-1])){
			newArr.pop();j--;
		}
	}
	return newArr;
}

AirportList.prototype.getAirportStringsByCountry = function(country) {
	var listCountriesCode = this.getCountriesCodeArray();
	var countryAirports = new Array();

	for (var i = 0; i < listCountriesCode.length; i++) {
		if (listCountriesCode[i] == country) {
			countryAirports.push(gDestinationListCities[i] + ', ' + gDestinationListAirports[i] + ' (' + gDestinationListIATA[i] + ')');  
		} 
	}
	return countryAirports;
} 

AirportList.prototype.getAirportsByCountry = function(country) {
	var listCountriesCode = this.getCountriesCodeArray();
	var countryAirports = new Array();

	for (var i = 0; i < listCountriesCode.length; i++) {
		if (listCountriesCode[i] == country) {
			countryAirports.push(new Array(gDestinationListCities[i], gDestinationListAirports[i], gDestinationListIATA[i]));  
		} 
	}
	return countryAirports;
} 

AirportList.prototype.closeAirportList = function() {
    
    var thisObject = this;
    var sIdDomElements = '';
    this.activeAirportPopup = '';
        
    jQ(thisObject.idAirportList).hide("slide", { direction: "up" }, 600);
    thisObject.activeSelect = false;
    
    // reset data list
    var elAirportBoxUl = jQ(thisObject.idAirportListData + ' ul.list');
    jQ(elAirportBoxUl).parent().parent().find('.scroll-pane')[0].scrollTo(0);
    
    var elListCity = elAirportBoxUl.find('li.city');
    var elListAirport = elAirportBoxUl.find('li a');
    jQ(elListAirport).each(function(index) {
        if (jQ(this).hasClass(thisObject.activeAirportClass)) {
            jQ(this).removeClass(thisObject.activeAirportClass);
        }
    });
    jQ(elListCity).each(function(index) {
        if (jQ(this).hasClass(thisObject.activeCityClass)) {
            jQ(this).removeClass(thisObject.activeAirportClass);
        }
    });
    
	for(i = 0; i < this.destOpenAirportListId.length; i++){
	    if((this.destOpenAirportListId.length-1) != i) {
	        sIdDomElements += "#"+this.destOpenAirportListId[i]+", ";
	    } else {
	        sIdDomElements += "#"+this.destOpenAirportListId[i];
	    }
	}
	jQ(sIdDomElements).removeClass('active');
}

AirportList.prototype.setInputFromSelect = function() {
    var nameAttr = jQ(this.idTargetInput).attr('name'); 
    var idAttr = jQ(this.idTargetInput).attr('id');
    var idFinalInputToShow = '#hide_input_'+this.idTargetInput.substring(1,this.idTargetInput.length);
    
    //nastaveni hodnot pro redesign input, ktery nahradi select box
    jQ(idFinalInputToShow).attr('name',nameAttr);
    oHideInput = jQ(idFinalInputToShow);
    oHideInput.removeAttr('id');
    oHideInput.attr('id',idAttr);
        
    oRedesignSelectToRemove = jQ(this.idTargetInput).parent().parent();
    oRedesignSelectToRemove.remove();
    
    //odstranění spanu s iconou pro seznam letist
    jQ('#'+this.idClickedEleToShowAirports).remove();
    
    oHideInput.parent().find('span').attr('id',this.idClickedEleToShowAirports);
    oHideInput.parent().show();
    
    //nasetovani udalosti click na jednotlive icony pro vyvolani popupu seznam letist
    this.setAirportList(this.destOpenAirportListId);
}

AirportList.prototype.setKeyEvent = function(elBox) {

    var thisObject = this;
    var elListCity = elBox.find('li.city');
    var elListAirport = elBox.find('li a');

    jQ(document).unbind('keydown');
    jQ(document).bind('keydown', function(e) {
    
        if (thisObject.activeSelect != true) {
            return true;
        }
    
        e.stopPropagation();

        selectIndexAirport = null;
        selectIndexCity = 0;
        
        jQ(elListAirport).each(function(index) {
            if (jQ(this).hasClass(thisObject.activeAirportClass)) {
                selectIndexAirport = index;
                return false;
            }
        });
        jQ(elListCity).each(function(index) {
            if (jQ(this).hasClass(thisObject.activeCityClass)) {
                selectIndexCity = index;
                return false;
            }
        });
            
        var code = (e.keyCode ? e.keyCode : e.which);
        
        // Ovladani sipkami
        if (code == 38 || code == 40)  {
           
            if (selectIndexAirport == null) {
                selectIndexAirport = 0;
            }else if (code == 38) {
                selectIndexAirport--;
            } else if (code == 40) {
                selectIndexAirport++;
            }

            if (0 <= selectIndexAirport) {
                var searchEl = jQ(elListAirport).eq(selectIndexAirport); 

                jQ(elListAirport).trigger('mouseleave');
                searchEl.triggerHandler('mouseenter');
                
                var scrollIndex = thisObject.getAirportPositionInList(searchEl);
                // rezerva
                if (scrollIndex > 0) {
                    scrollIndex -= 20;
                } 
                jQ(elBox).parent().parent().find('.scroll-pane')[0].scrollTo(scrollIndex);
            }
        } else if (48 <= code && code <= 90) {
            findIndex = null;
            jQ(elListCity).eq(selectIndexCity).nextAll().each(function(index) {
                var textVal = jQ(this).text();
                if (textVal.charCodeAt(0) == code) {
                    findIndex = selectIndexCity + index + 1;
                    return false;
                }
            });
            if (findIndex == null) {
                jQ(elListCity).each(function(index) {
                    var textVal = jQ(this).text();
                    if (index >= selectIndexCity) {
                        return false;
                    } else if (textVal.charCodeAt(0) == code) {
                        findIndex = index;
                        return false;
                    }
                });
            }

            if (findIndex != null) {
                jQ(elListCity).trigger('mouseleave');
                jQ(elListCity).eq(findIndex).triggerHandler('mouseenter');
                element = jQ(elListCity).eq(findIndex).find('ul li a').eq(0);
                elListAirport.trigger('mouseleave');
                element.triggerHandler('mouseenter');
                
                var scrollIndex = 0;
                jQ(elListCity).eq(findIndex).prevAll().each(function(index) {
                    scrollIndex = scrollIndex + jQ(this).height();  
                });
                
                // rezerva
                if (scrollIndex > 0) {
                    scrollIndex -= 20;
                } 
                if (scrollIndex < 0) {
                    scrollIndex = 0;
                }

                jQ(elBox).parent().parent().find('.scroll-pane')[0].scrollTo(scrollIndex);
            }
        } else if (code == 13 && selectIndexAirport != null) {
            jQ(elListAirport).eq(selectIndexAirport).triggerHandler('click');
        // page up - @fixme - zrejme nefunguje      
        } else if (code == 33) {
            jQ(elBox).parent().parent().find('.scroll-pane')[0].scrollTo({top: '-=40px'});
        // page down - @fixme - zrejme nefunguje
        } else if (code == 34) {
            jQ(elBox).parent().parent().find('.scroll-pane')[0].scrollTo({top: '+=40px'});
        // end        
        } else if (code == 35) {
            jQ(elBox).parent().parent().find('.scroll-pane')[0].scrollTo(elBox.height());
        // home        
        } else if (code == 36) {
            jQ(elBox).parent().parent().find('.scroll-pane')[0].scrollTo(0);
        }
        return false;
    });
}
