;
(function($) {
    $.fn.lcSearch = function(options) {
        if (lang && lang == 'en'){
            $.fn.lcSearch.defaults.datePickerOptions = {
                dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wendesday', 'Thursday', 'Friday', 'Saturday'],
                dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
                dayNamesMin: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
                monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
                monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
                closeText: 'Close',
                currentText: 'Today',
                nextText: 'Next',
                prevText: 'Prev',
                dateFormat: 'yy-mm-dd',
                firstDay: '1',
                minDate : new Date()
            };
        }
        var opts = $.extend({}, $.fn.lcSearch.defaults, options);
        var gmap = false;
        var cities = Array();
        var overlayLine;
        var clocksTimeout;
        var weatherTypes = {
            clouds : {
                SKC : "clear sky",
                CLR : "clear sky",
                FEW : "few clouds",
                SCT : "scattered clouds",
                BKN : "broken clouds",
                OVC : "overcast",
                VV : "vertical visibility"
            },
            condition : {
                DZ : "drizzle",
                RA : "rain",
                SN : "snow",
                SG : "snow grains",
                IC : "ice crystals",
                PL : "ice pellets",
                GR : "hail",
                GS : "small hail/snow pellets",
                UP : "unknown precipitation",
                BR : "mist",
                FG : "fog",
                FU : "smoke",
                VA : "volcanic ash",
                SA : "sand",
                HZ : "haze",
                PY : "spray",
                DU : "widespread dust",
                SQ : "squall",
                SS : "sandstorm",
                DS : "duststorm",
                PO : "well developed dust/sand whirls",
                FC : "funnel cloud",
                //FC : "tornado/waterspout",
                light : "light",
                heavy : "heavy",
                VC : "in vicinity:",
                MI : "shallow",
                BC : "patches",
                SH : "showers",
                PR : "partial",
                TS : "thunderstorm",
                BL : "blowing",
                DR : "drifting",
                FZ : "freezing"
            }
        }
        if (window.google){
            google.maps.LatLng.prototype.kmTo = function(a){
                var e = Math, ra = e.PI/180;
                var b = this.lat() * ra, c = a.lat() * ra, d = b - c;
                var g = this.lng() * ra - a.lng() * ra;
                var f = 2 * e.asin(e.sqrt(e.pow(e.sin(d/2), 2) + e.cos(b) * e.cos
                    (c) * e.pow(e.sin(g/2), 2)));
                return f * 6378.137;
            }
            google.maps.Polyline.prototype.inKm = function(n){
                var a = this.getPath(n), len = a.getLength(), dist = 0;
                for(var i=0; i<len-1; i++){
                    dist += a.getAt(i).kmTo(a.getAt(i+1));
                }
                return dist;
            }
        }
        return this.each(function() {
            var firstDatepickerOpts = $.extend({}, {
                onClose : function(date){
                    var minDate = dateFromString(date);
                    if ($('input.datumSelect:eq(1)').val() != ''){
                        if (dateFromString($('input.datumSelect:eq(1)').val()) < minDate){
                            $('input.datumSelect:eq(1)').val('');
                        }
                    }
                    $('input.datumSelect:eq(1)').datepicker('option', 'minDate', minDate);
                }
            }, opts.datePickerOptions);
            $(this).find('input.datumSelect:eq(0)').datepicker(firstDatepickerOpts);
            $(this).find('input.datumSelect:eq(1)').datepicker(opts.datePickerOptions);
            $(this).submit(getResults);
            $(this).find("input[name=round_trip]").change(handleRoundTrip);
            $(this).find('select[name=id_start]').change(handleStartSelect);
            $(this).find('select[name=id_end]').change(handleEndSelect);
            if ($(this).find('input[type=checkbox]').attr("checked")){
                $($('.dateWrapper').show());
            }
            var startSelect = $(this).find("select[name=id_start]");
            var endSelect = $(this).find("select[name=id_end]");
            $.getJSON(SITE_URL + "async/cities.php?id=" + startSelect.val() + '&lang=' + lang,
                function(data){
                    endSelect.html('');
                    $.each(data, function(i,item){
                        $("<option/>").html(item.name).val(item.value).appendTo(endSelect);
                    });
                    if (jQuery.url.param("id_end")){ // returns 2
                        endSelect.find('option[value=' + jQuery.url.param('id_end') +']').attr("selected", true);
                    }
                    $.getJSON(SITE_URL + "async/cities.php?lang="+lang,
                        function(data){
                            cities = data;
                            initMap();
                        });
                });
            function initMap(){
                if (document.getElementById("gmapWrapper")){
                    var city = getCityByName($('select[name=id_start] option:selected').html());
                    gmap = new google.maps.Map(document.getElementById("gmapWrapper"), opts.gMapOptions);
                    drawLine();
                    google.maps.event.addListener(gmap, 'dragstart', function() {
                        $(cities).each(function(i,city){
                            hideCityDetails(city);
                        });
                    });

                }
            }
            function removeMarkers(){
                $(cities).each(function(i,city){
                    if (city.marker){
                        city.marker.setVisible(false);
                        hideCityDetails(city);
                    }
                });
            }
            function resetCityMarkers(){
                removeMarkers();
                var endCity = getCityByName($("select[name=id_end] option:selected").html());
                var startCity = getCityByName($("select[name=id_start] option:selected").html());
                if (startCity){
                    populateCityDetails(startCity);
                }
                if (endCity){
                    populateCityDetails(endCity);
                }
            }
            function populateCityDetails(city){
                if (!city.marker){
                    city.marker = new google.maps.Marker({
                        position: getCityLatLng(city),
                        map: gmap,
                        icon: SITE_URL + 'images/airport_icon.png'
                    });
                    city.marker.city = city;
                } else {
                    city.marker.setVisible(true);
                }
                google.maps.event.addListener(city.marker, 'click', function(){
                    showCityDetails(city);
                });
            }
            function showCityDetails(city){
                if (!city.infoWindow){
                    city.infoWindow = new google.maps.InfoWindow({
                        content: getCityDetailsHtml(city),
                        maxWidth:110
                    });
                    city.infoWindow.city = city;
                    city.infoWindow.setPosition(getCityLatLng(city));
                    city.infoWindow.open(gmap);
                } else {
                    city.infoWindow.open(gmap);
                }
            }
            function hideCityDetails(city){
                if (city.infoWindow){
                    city.infoWindow.close()
                }
            }
            function getCityDetailsHtml(city){
                if (lang && lang == "en"){
                    var startHtml = '<h3 class="cityDetailsName">' + city.name + '</h3><ul class="cityDetailsList">';
                    startHtml += '<li>Population: <strong>' + city.population + '</strong></li>';
                    startHtml += '<li>Area: <strong>' + city.area + '</strong> km<sup>2</sup></li>';
                    startHtml += '<li>Altitude: <strong>' + city.elevation + ' m</strong></li>';
                    startHtml += '<li>Time zone: <strong>GMT ' + (city.timezone > 0 ? '+' : '-') + city.timezone + '</strong></li>';
                    startHtml += '<li>Time zone (DST): <strong>GMT ' + (city.timezone_dst > 0 ? '+' : '-') + city.timezone_dst + '</strong></li>';
                    startHtml += '<li>Postal code: <strong>' + city.postal_code + '</strong></li>';
                    startHtml += '<li>Area code: <strong>' + city.area_code + '</strong></li>';
                    startHtml += '<li>Website: <a href=' + city.website + ' target="_blank">' + city.website + '</a></li>';
                    startHtml += '</ul>';
                } else {
                    var startHtml = '<h3 class="cityDetailsName">' + city.name + '</h3><ul class="cityDetailsList">';
                    //startHtml += '<li>Ime: <strong>' + city.name + '</strong></li>';
                    startHtml += '<li>Populacija: <strong>' + city.population + '</strong></li>';
                    startHtml += '<li>Povr\u0161ina: <strong>' + city.area + '</strong> km<sup>2</sup></li>';
                    startHtml += '<li>Nadmorska visina: <strong>' + city.elevation + ' m</strong></li>';
                    startHtml += '<li>Vremenska zona: <strong>GMT ' + (city.timezone > 0 ? '+' : '-') + city.timezone + '</strong></li>';
                    startHtml += '<li>Vremenska zona (letnja): <strong>GMT ' + (city.timezone_dst > 0 ? '+' : '-') + city.timezone_dst + '</strong></li>';
                    startHtml += '<li>Po\u0161tanski broj: <strong>' + city.postal_code + '</strong></li>';
                    startHtml += '<li>Pozivni broj: <strong>' + city.area_code + '</strong></li>';
                    startHtml += '<li>Sajt: <a href=' + city.website + ' target="_blank">' + city.website + '</a></li>';
                    startHtml += '</ul>';
                }
                return startHtml;
            }
            function handleStartSelect(e){
                if (overlayLine){
                    overlayLine.setMap(null);
                }
                var element = $(e.target);
                var other = $(this).parents('form').find('select[name=id_end]');
                element.find('option[value=]').remove();
                element.find('option').attr("disabled", false);
                other.html('');
                $.getJSON(SITE_URL + "async/cities.php?id=" + element.val() + "&lang=" + lang,
                    function(data){
                        $.each(data, function(i,item){
                            $("<option/>").html(item.name).val(item.value).appendTo(other);
                        });
                        if (gmap){
                            drawLine();
                        }
                    });
            }
            function handleEndSelect(e){
                var element = $(e.target);
                var other = $(this).parents('form').find('select[name=id_start]');
                if (gmap){
                    drawLine();
                }
            }
            function loadCityData(){
                $.getJSON(SITE_URL + "async/cities.php?id=" +  $(this).find('select[name=id_start]').val() + "&lang=" + lang,
                    function(data){
                        $.each(data, function(i,item){
                            $("<option/>").html(item.name).val(item.value).appendTo($(this).find('select[name=id_end]'));
                        });
                    });
            }
            function handleRoundTrip(e){
                var element = e.target;
                e.preventDefault();
                var dateWrapper = $(element).parents('form').find(".dateWrapper");
                if ($(element).attr("checked")){
                    $(dateWrapper.show());
                } else {
                    $(dateWrapper.hide());
                }
            }
            function getCityByName(name){
                var theCity;
                $(cities).each(function(i,city){
                    if (name && city.name.toLowerCase() == name.toLowerCase()){
                        theCity = city;
                    }
                });
                return theCity;
            }
            function drawLine(){
                if (gmap){
                    if (overlayLine){
                        overlayLine.setMap(null);
                    }
                    var endCity = getCityByName($("select[name=id_end] option:selected").html());
                    var startCity = getCityByName($("select[name=id_start] option:selected").html());
                    if (endCity && startCity){
                        var flightPath = [getCityLatLng(startCity), getCityLatLng(endCity)];
                        var lineOptions = $.extend({}, opts.gMapStrokeLineOptions, {
                            path:flightPath
                        });
                        overlayLine = new google.maps.Polyline(lineOptions);
                        overlayLine.setMap(gmap);
                        var newBounds = new google.maps.LatLngBounds();
                        newBounds.extend(getCityLatLng(startCity));
                        newBounds.extend(getCityLatLng(endCity));
                        gmap.fitBounds(newBounds);
                    }
                    resetCityMarkers();
                    loadCityWeather(startCity, 0);
                    loadCityWeather(endCity, 1);
                    populateDistance();
                    populateClocks(startCity, endCity);
                }
            }
            function getResults(e){
                if (gmap){
                    var form = e.target;
                    var validForm = true;
                    if (!$(form).find('input[name=datum_polaska]').val()){
                        $(form).find('input[name=datum_polaska]').addClass("red_shadow");
                        e.preventDefault();
                        validForm = false;
                        if (lang && lang == "en"){
                            $(form).parents('div').find('.searchResults').html('<div class="no_search_results">You have to choose departure date</div>');
                        } else {
                            $(form).parents('div').find('.searchResults').html('<div class="no_search_results">Morate izabrati datum polaska</div>');
                        }
                    }
                    if ($(form).find('input[type=checkbox]').attr('checked') && !$(form).find('input[name=datum_povratka]').val()){
                        if (lang && lang =="en"){
                            $(form).parents('div').find('.searchResults').html('<div class="no_search_results">You have to choose returning date</div>');
                        } else {
                            $(form).parents('div').find('.searchResults').html('<div class="no_search_results">Morate izabrati datum dolaska</div>');
                        }
                        e.preventDefault();
                        validForm = false;
                    }
                    if (validForm){
                        e.preventDefault();
                        $(form).parents('div').find('.searchResults').html('');
                        $(form).parents('div').find('.searchResults').addClass('loader_fff_666').css('height','100px');
                        var query = $(form).serialize();
                        $.get(SITE_URL + 'async/search.php', query, function(data, textStatus){
                            $(form).parents('div').find('.searchResults').html(data);
                            $(form).parents('div').find('.searchResults .flightsTable').tablesorter({
                                cssHeader:'tableHeader',
                                sortList:[[0,0],[1,0]]
                            });
                            $(form).parents('div').find('.searchResults').removeClass('loader_fff_666').css('height', 'auto');
                        });
                    }
                } else {
                    $(form).find('.box_shadow').children('.no_search_results').remove();
                    var form = e.target;
                    var validForm = true;
                    if (!$(form).find('input[name=datum_polaska]').val()){
                        $(form).find('input[name=datum_polaska]').addClass("red_shadow");
                        e.preventDefault();
                        validForm = false;
                        if (lang && lang =="en"){
                            $(form).find('.box_shadow').append('<div class="no_search_results fix" style="margin-bottom:10px; margin-top:10px;">You have to choose departure date</div>');
                        } else {
                            $(form).find('.box_shadow').append('<div class="no_search_results fix" style="margin-bottom:10px; margin-top:10px;">Morate izabrati datum polaska</div>');
                        }
                    }
                    if ($(form).find('input[type=checkbox]').attr('checked') && !$(form).find('input[name=datum_povratka]').val()){
                        if (lang && lang == "en"){
                            $(form).find('.box_shadow').append('<div class="no_search_results fix" style="margin-bottom:10px; margin-top:10px;">Morate izabrati datum povratka</div>');
                        } else {
                            $(form).find('.box_shadow').append('<div class="no_search_results fix" style="margin-bottom:10px; margin-top:10px;">You have to choose returning date</div>');
                        }
                        e.preventDefault();
                        validForm = false;
                    }
                    if (validForm){
                        return true;
                    }
                }
            }
            function getDistance(startCity, endCity){
                return getCityLatLng(startCity).kmTo(getCityLatLng(endCity)).toFixed(3);
            }
            function getCityLatLng(city){
                if (!city.latlng){
                    city.latlng = new google.maps.LatLng(city.latitude, city.longitude);
                }
                return city.latlng
            }
            function loadCityWeather(city, index){
                $(".weatherData").eq(index);//.addClass("loader_fff_666").html('');
                $(".clocksWrapper .clock:eq("+index+")").hide();
                if (city){
                    if(!city.weather){
                        $.getJSON(SITE_URL + 'include/search/cityWeather.php?id_city=' + city.value, function(data, textStatus){
                            if (!data.weatherObservation || textStatus != "success"){
                                populateCityWeather(city, index);
                                return;
                            }
                            city.rawWeather = data.weatherObservation;
                            var windDir;
                            var wd = city.rawWeather.windDirection;
                            if (wd>=338 && wd<23){
                                if (lang && lang == "en"){
                                    windDir = "N, ";
                                } else {
                                    windDir = "S, ";
                                }
                            } else if (wd>=23 && wd<68){
                                if (lang && lang == "en"){
                                    windDir = "NW, ";
                                } else {
                                    windDir = "SZ, ";
                                }
                            }
                            else if (wd>=68 && wd<113){
                                if (lang && lang == "en"){
                                    windDir = "W, ";
                                } else {
                                    windDir = "Z, ";
                                }
                            } else if (wd>=113 && wd<158){
                                if (lang && lang == "en"){
                                    windDir = "SW, ";
                                } else {
                                    windDir = "JZ, ";
                                }
                            } else if (wd>=158 && wd<203){
                                if (lang && lang == "en"){
                                    windDir = "S, ";
                                } else {
                                    windDir = "J, ";
                                }
                            } else if (wd>=203 && wd<248){
                                if (lang && lang == "en"){
                                    windDir = "SE, ";
                                } else {
                                    windDir = "JI, ";
                                }
                            } else if (wd>=248 && wd<293){
                                if (lang && lang == "en"){
                                    windDir = "E, ";
                                } else {
                                    windDir = "I, ";
                                }
                            } else if (wd>=293 && wd<338){
                                if (lang && lang == "en"){
                                    windDir = "NE, ";
                                } else {
                                    windDir = "SI, ";
                                }
                            } else {
                                windDir = '';
                            }
                            var wType;
                            var bgPos;
                            switch(city.rawWeather.clouds){
                                case weatherTypes.clouds.CLR :
                                    wType = 'bez oblaka';
                                    bgPos = 30;
                                    break;
                                case weatherTypes.clouds.FEW :
                                    wType = 'blaga obla\u010dnost';
                                    bgPos = 60;
                                    break;
                                case weatherTypes.clouds.BKN :
                                    wType = 'prete\u017eno obla\u010dno';
                                    bgPos = 90;
                                    break;
                                case weatherTypes.clouds.OVC :
                                    wType = 'obla\u010dno';
                                    bgPos = 120;
                                    break;
                                default :
                                    wType = false;
                                    bgPos = 0;
                            }
                            if (!city.rawWeather.temperature || city.rawWeather.temperature == 'false'){
                                city.rawWeather.temperature = '';
                            }
                            if (!city.rawWeather.windSpeed || city.rawWeather.windSpeed == 'false'){
                                city.rawWeather.windSpeed = '';
                            }
                            if (!city.rawWeather.windDirection || city.rawWeather.windDirection == 'false'){
                                city.rawWeather.windDirection = '';
                            }
                            if (!city.rawWeather.humidity || city.rawWeather.humidity == 'false'){
                                city.rawWeather.humidity= '';
                            }
                            if (!city.rawWeather.wType || city.rawWeather.wType == 'false'){
                                city.rawWeather.wType= '';
                            }
                            city.weather = {
                                temperature : city.rawWeather.temperature,
                                windSpeed : city.rawWeather.windSpeed,
                                humidity : city.rawWeather.humidity,
                                windDirection : windDir,
                                weatherType : wType,
                                weatherTypeBgPosition : bgPos
                            }
                            populateCityWeather(city, index);
                        });
                    } else {
                        populateCityWeather(city, index);
                    }
                } else {
                    if (lang && lang == "en"){
                        $(".weatherData").eq(index).html('<div class="errorMessage">We cannot display weather data at the moment.</div>');
                    } else  {
                        $(".weatherData").eq(index).html('<div class="errorMessage">Trenutno nismo u mogu\u0107nosti da prika\u017eemo podatke.</div>');
                    }

                }
            }
            function populateCityWeather(city, index){
                if (city && city.weather){
                    $('.weatherData .cityName .dataColumn:eq(' + index + ') *:first').html(city.name);
                    $('.weatherData .weatherType .dataColumn:eq(' + index + ') .weatherImage').css('background-position', '-' + city.weather.weatherTypeBgPosition + 'px 0px');
                    $('.weatherData .temperature .dataColumn:eq(' + index + ')').html(city.weather.temperature + ' &deg;C');
                    $('.weatherData .wind .dataColumn:eq(' + index + ')').html(city.weather.windDirection  + city.weather.windSpeed.replace(/^[0]*/, '')  + ' m/s');
                    $('.weatherData .humidity .dataColumn:eq(' + index + ')').html(city.weather.humidity + '%');
                } else {
                    $(".weatherData:eq("+index+")").removeClass("loader_fff_666").html('<div class="errorMessage">Trenutno nismo u mogu\u0107nosti da prika\u017eemo podatke.</div>');
                }
            }
            function populateDistance(){
                $('.citiesWidget .distance').remove();
                if (gmap){
                    var distance = overlayLine.inKm().toFixed(3);
                    $('<div class="distance"><span>' + overlayLine.inKm().toFixed(3) + ' km</span></div>').appendTo('.citiesWidget');
                }
            }
            function populateClocks(startCity, endCity){
                if (gmap){
                    if (clocksTimeout){
                        clearInterval(clocksTimeout);
                    }
                    clocksTimeout = setInterval(refreshClocks, 1000);
                    $(".citiesWidget .clock").show();
                }
            }
            function refreshClocks(){
                var cities = Array();
                var currentDate;
                var minutes;
                var seconds;
                var hours;
                cities.push(getCityByName($('select[name=id_start] option:selected').html()));
                cities.push(getCityByName($('select[name=id_end] option:selected').html()));
                for(i=0;i<cities.length;i++){
                    currentDate = getCityTime(cities[i]);
                    hours = currentDate.getHours();
                    minutes = currentDate.getMinutes();
                    seconds = currentDate.getSeconds();
                    if (hours <= 9){
                        hours = '0' + new String(hours);
                    }
                    if (minutes <= 9){
                        minutes = '0' + new String(minutes);
                    }
                    if (seconds <= 9){
                        seconds = '0' + new String(seconds);
                    }
                    $('.weatherData .clocksWrapper .dataColumn:eq(' + i + ')').html('<span class="hours">' + hours + '</span>:<span class="minutes">' + minutes + '</span>:<span class="seconds">' + seconds + '</span>');
                }
            }
            function getCityTime(city){
                d = new Date();
                utc = d.getTime() + (1000*60*d.getTimezoneOffset());
                nd = new Date(utc + (1000*60*60*city.timezone));
                return nd;
            }
            function dateFromString(dateString){
                var date = new Date();
                var fragments
                if (dateString.match(/\./)){
                    fragments = dateString.split('.');
                    date.setFullYear(fragments[2], parseInt(fragments[1])-1, fragments[0]);
                } else {
                    fragments = dateString.split('-');
                    date.setFullYear(fragments[0], parseInt(fragments[1])-1, fragments[2]);
                }
                return date;
            }
        });
    }
    $.fn.lcSearch.defaults = {
        datePickerOptions : {
            dayNames: ['Nedelja', 'Ponedeljak', 'Utorak', 'Sreda', '\u010cetvrtak', 'Petak', 'Subota'],
            dayNamesShort: ['Ned', 'Pon', 'Uto', 'Sre', '\u010cet', 'Pet', 'Sub'],
            dayNamesMin: ['N', 'P', 'U', 'S', '\u010c', 'P', 'S'],
            monthNames: ['Januar', 'Februar', 'Mart', 'April', 'Maj', 'Jun', 'Jul', 'Avgust', 'Septembar', 'Oktobar', 'Novembar', 'Decembar'],
            monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'Maj', 'Jun', 'Jul', 'Avg', 'Sep', 'Okt', 'Nov', 'Dec'],
            closeText: 'Zatvori',
            currentText: 'Danas',
            nextText: 'Sled',
            prevText: 'Pret',
            dateFormat: 'dd.mm.yy',
            firstDay: '1',
            minDate : new Date()
        },
        trophyCoords : [],
        gMapOptions : {
            zoom: 6,
            disableDefaultUI: true,
            mapTypeId: 'roadmap'
        },
        jScrollPaneOptions : {
            showArrows:true,
            scrollbarWidth:15,
            animateTo:true
        },
        gMapStrokeLineOptions : {
            strokeColor: "#666666",
            strokeOpacity: 0.8,
            strokeWeight: 4
        }
    }
})(jQuery);
