var sliderInterval;
var sliderIte = 1;

$(document).ready(function(){

    //sliderInterval = setInterval(switchTab, 10000);

    $("#ajaxSearch-input-container input").cleaner();
    if($("#flowplayer").length){
        flowplayer("flowplayer", {
            src: "js/flowplayer-3.2.5.swf",
            wmode: 'opaque'
        });
    }
    interactiveHeader();
    curiosityEvents();

    calcFormEvents();
    jForm();
    popupFadeIn();
});

function switchTab(){
    sliderIte++;
    var len = $(".interactive-header-menu ul li").length;
    if(sliderIte > len){
        $(".interactive-header-menu ul li:first-child a").dblclick();
        clearInterval(sliderInterval);
    }else{
        $(".interactive-header-menu ul li:nth-child(" + sliderIte + ") a").dblclick();
    }
}

function curiosityChange(count){
    $("#curiosity p").hide();
    var active = Math.round(Math.random() * count);
    if (active == 0){
        active = 1;
    }
    if (active > count){
        active = count;
    }
    $("#curiosity p:nth-child(" + active + ")").fadeIn();
}

function curiosityEvents(){
    var count = $("#curiosity p").length;
    $("#next-btn").click(function(){
        curiosityChange(count);
        return false;
    });
    $("#next-btn").click();
}

function interactiveHeader(){
    $(".interactive-header-menu ul li a").dblclick(function(){

        var no = $(".interactive-header-menu ul li a").index($(this)) + 1;
        
        $(".interactive-header-menu ul li a.active").removeClass("active");
        $(this).addClass("active");

        $(".interactive-header-visual-element:visible").fadeOut("fast");

        $('.interactive-header-item-description').animate({
                marginLeft: "-352px"
            }, 200, "linear", function(){

                $(".interactive-header-item-description:visible").hide();
                $(".interactive-header-item-description:nth-child(" + (no+1) + ")").show();

                $(".interactive-header-visual-element:nth-child(" + no + ")").fadeIn("fast");
                $('.interactive-header-item-description').animate({
                    marginLeft: "0"
                }, 200);
        });
    });

    $("#flowplayer").click(function(){
        clearInterval(sliderInterval);
    });

    $(".interactive-header-menu ul li a").click(function(){
        clearInterval(sliderInterval);
        $(this).dblclick();
    });

    $(".interactive-header-menu ul li:nth-child(1) a").dblclick();
}

function lata(v){
    if(v == 1){ret = "rok";}
    else if((v % 100) >= 10 && (v % 100) <= 20){ret = "lat";}
    else if((v % 10) == 0 || (v % 10) == 1 || (v % 10) ==  5 || (v % 10) ==  6 || (v % 10) ==  7 || (v % 10) ==  8 || (v % 10) ==  9) {ret = "lat";}
    else if((v % 10) ==  2 || (v % 10) ==  3 || (v % 10) ==  4){ret = "lata";}
    else{
        ret = "lata";
    }
    return " "+ret;
}

function jForm() {
    $(".select-ext-item").click(function(){

        var wynik = 0;
        
        var obszar;
        var obszarPrzybrzezny;
        var obszarPrzemyslowy;

        if($("#obszar").val() == "miejski"){
            obszar = 0.85;
        } else if($("#obszar").val() == "wiejski"){
            obszar = 0.95;
        }

        if($("#obszar-przybrzezny").val() == "tak"){
            obszarPrzybrzezny = 0.7;
        } else if($("#obszar-przybrzezny").val() == "nie"){
            obszarPrzybrzezny = 1;
        }

        if($("#obszar-przemyslowy").val() == "tak"){
            obszarPrzemyslowy = 0.6;
        } else if($("#obszar-przemyslowy").val() == "nie"){
            obszarPrzemyslowy = 1;
        }
        wynik = 100 * obszar * obszarPrzybrzezny * obszarPrzemyslowy;
        wynik = Math.round(wynik/10)*10;
        $("#wynik").val(wynik + lata(wynik));
    });
    
    $(".select-ext-item").click();
}


/* Google Maps Events */

var geocoder;
var map;
var yourMarker;

var directionDisplay;
var directionsService;

function initialize() {
    $("#twoja-lokalizacja").val("");
    $("#najblizsza-cynkownia").val("");
    $("#odleglosc").val("");

    geocoder = new google.maps.Geocoder();
    directionsService = new google.maps.DirectionsService();
    directionsDisplay = new google.maps.DirectionsRenderer();
    directionsDisplay.suppressMarkers = true;

    var latlng = new google.maps.LatLng(52.10853835031443, 19.195757812500002);
    var myOptions = {
        zoom: 6,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map-canvas"),myOptions);
    directionsDisplay.setMap(map);



    pokazLokalizacjeUzytkownika();
    wyswietlCynkownie();

}


function calcRoute(start, end) {
  var request = {
    origin:start,
    destination:end,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(result);
      //console.log(directionsDisplay.map);
    }
    var route = result.routes[0];
    distance = route.legs[0].distance.text;
    $("#odleglosc").val(distance);
  });
}

//var shadowY = new google.maps.MarkerImage('images/map-you-shadow.png',
//            new google.maps.Size(35, 17),
//            new google.maps.Point(0,0),
//            new google.maps.Point(0, 17)
//        );

function wyswietlCynkownie(){
    $("#map-markers-data div.comp-container").each(function(){
        pokazLokalizacjeCynkowni($(this));
    });
}

var positionAct;

function pokazLokalizacjeUzytkownika(){
    $("#pokaz-trase").click(function(){
        var address = $("#twoja-lokalizacja").val();
        var image = 'images/map-you.png';
        geocoder.geocode( {'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {

                if(yourMarker) yourMarker.setMap(null);

                map.setCenter(results[0].geometry.location);
                $("#najblizsza-cynkownia").val(results[0].geometry.location);
                yourMarker = new google.maps.Marker({
                    map: map,
                    title: "Twoja lokalizacja",
                    position: results[0].geometry.location,
                    icon: image//,
                    //shadow: shadowY
                });
                map.setZoom(8);
                
                var posit = $("#najblizsza-cynkownia").val();
                $("#najblizsza-cynkownia").val("");

                posit = posit.substring(1, (posit.length-1));
                posit = posit.split(", ");

                var start = new google.maps.LatLng(posit[0], posit[1]);
                var end = findNearest(posit[0], posit[1]);
                calcRoute(start, end);

            } else {
                alert("Wystąpił błąd. Sprawdź poprawność adresu i spróbuj jeszcze raz.");
            }
        });
        
    });
}

function findNearest(posX, posY){

    var nearestIndex = 10000;
    var nearestPos = new Array();
    var arrayPos;

    $("#map-markers-data-search div.comp-container.cynkuje-tak").each(function(){
        var posit = $(this).find("div.comp-pos").html();
        posit = posit.substring(1, (posit.length-1));
        posit = posit.split(", ");

        v = Math.sqrt(Math.pow((posit[0] - posX), 2) + Math.pow((posit[1] - posY), 2));

        if(v < nearestIndex){
            nearestPos[0] = posit[0];
            nearestPos[1] = posit[1];
            nearestIndex = v;
            arrayPos = $(this);
            //arrayPos = $(this).find("div.comp-name strong").html();
        }
    });
    //console.log(arrayPos);
    
    posit = arrayPos.find("div.comp-pos").html();
    posit = posit.substring(1, (posit.length-1));
    posit = posit.split(", ");

    //postaw marker w miejscu najblizszej cynkowni
    var image = 'images/map-ptc.png';
    var contentString = arrayPos.find("div.comp-name").html();

    var infowindow = new google.maps.InfoWindow({
        content: contentString
    });

    companyMarker = new google.maps.Marker({
        map: map,
        position: new google.maps.LatLng(posit[0], posit[1]),
        icon: image//,
        //shadow: shadowY
    });
    google.maps.event.addListener(companyMarker, 'click', function() {
        infowindow.setContent(contentString);
        infowindow.open(map, this);
    });

    $("#najblizsza-cynkownia").val(arrayPos.find("div.comp-name strong").html());
    nearest = new google.maps.LatLng(nearestPos[0], nearestPos[1]);
    return nearest;
}

function pokazLokalizacjeCynkowni(obj){
    var adres = obj.find("div.comp-address").html();
    var nazwa = obj.find("div.comp-name").html();
    var posit = obj.find("div.comp-pos").html();

    if(posit != ""){
        posit = posit.substring(1, (posit.length-1));
        posit = posit.split(", ");
        var contentString = nazwa;

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });


        if(obj.hasClass("cynkuje-nie")) {
            var image = 'images/map-ptc-niecynk.png';
            companyMarker = new google.maps.Marker({
                map: map,
                position: new google.maps.LatLng(posit[0], posit[1]),
                icon: image
            });
        }else{
            var image = 'images/map-ptc.png';
            companyMarker = new google.maps.Marker({
                map: map,
                position: new google.maps.LatLng(posit[0], posit[1]),
                icon: image
            });
        }

        google.maps.event.addListener(companyMarker, 'click', function() {
          infowindow.setContent(contentString);
          infowindow.open(map, this);
        });
    }else{
        
        geocoder.geocode( {'address': adres}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                //map.setCenter(results[0].geometry.location);

                var contentString = nazwa + "<br/>pozycja: " + results[0].geometry.location;

                var infowindow = new google.maps.InfoWindow({
                    content: contentString
                });
                
                Marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    icon: image//,
                    //shadow: shadowY
                });

                google.maps.event.addListener(Marker, 'click', function() {
                    infowindow.setContent(contentString);
                    infowindow.open(map, this);
                });
                //map.setZoom(10);
            }else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                //alert(adres);
            }else {
                //alert("Wystąpił błąd. Sprawdź poprawność adresu i spróbuj jeszcze raz.");
            }
        });
    }
}



function calcFormEvents(){
    $("#calc .pole-select").toggle(function(){
        $(this).find(".select-ext").slideDown("fast");
    }, function(){
        $(this).find(".select-ext").slideUp("fast");
    });

    $(".select-ext-item").click(function(){
        $(this).parent().parent().find("input[type='text']").val($(this).html());
    });
}

function popupFadeIn(){
	var speed = "slow";
	$("#popup-bg").fadeIn(speed);
	$("#popup-main").fadeIn(speed);

	$("#popup-close").click(function(){
		$("#popup-bg").fadeOut(speed);
		$("#popup-main").fadeOut(speed);
	});
}
