/*
 * Creating array of sports 
 */
var sportsArray = [];
$.getJSON("/facility/load/task/sports", function(data) {
    $.each(data, function(key, val) {
        sportsArray[key] = val;
    });
});


/*
 *  close menus after click out of them !!!!
 */

$(document).bind('click', function(e) {

    var $clicked = $(e.target);

    if ((! $clicked.parents().hasClass("menu-what")) && 
        (! $clicked.parents().hasClass("menu-where")) && 
        (! $clicked.parents().hasClass("menu-when")) && 
        (! $clicked.parents().hasClass("menu-who")) &&
        (! $clicked.parents().hasClass("menuOk")) &&
        (! $clicked.hasClass("hand")) &&
        (! $clicked.parents().hasClass("message"))
            )
        closeMenu();
});

/*
 *  ========================== MENU HANDLING ===================================
 */

function closeMenu() {
    $('#what-content').hide();
    $('li.menu-what').removeClass('open');
    $('#where-content').hide();
    $('li.menu-where').removeClass('open');
    $('#when-content').hide();
    $('li.menu-when').removeClass('open');
    $('#who-content').hide();
    $('li.menu-who').removeClass('open');
}

function openWhat() {
    closeMenu();
    $('#what-content').show();
    $('li.menu-what').addClass('open');
}

function openWhere() {
    closeMenu();
    $('#where-content').show();
    $('li.menu-where').addClass('open');
    $('#address_place_input').focus();
}

function openWhen() {
    closeMenu();
    $('#when-content').show();
    $('li.menu-when').addClass('open');
}

function openWho() {
    closeMenu();
    $('#who-content').show();
    $('li.menu-who').addClass('open');
}

function loadFacList() {
    $('#tab_list').load('/ajax/facility/faclist/all/' + $.cookie('allCities'));
}

function setSport(sport,id) {    
    closeMenu();
    $('#selected_sport').html(sport); // nastavi nazov sportu
    mc.clearMarkers();
    clearOverlays(); // zmaze existujuce markery
    loadSport(id); // zobrazi nove markery
    $.cookie('sportId', id, {
        expires: 365
    });
    $.cookie('sportName', sport, {
        expires: 365
    });
    loadFacList(); // reload list of facilities
    setHashURL();
}

function setTime(time,obj) {
    closeMenu();
    $('#current_time').attr("id", "");
    obj.id = "current_time";
    $('#selected_time').html(time + ":00");
}

function setSelectedPlace(name) {
    if(name.length > 12) {
        name = name.substring(0,12)+"...";
    }
    $('#selected_place').html(name);
}

function setPlace(place,address,zoom,cityId,cityUrl,e) {
    var all = 0;
    closeMenu();
    moveCenter(address,parseInt(zoom),cityId);
    input_sport = $("input[name=address_place]").val();
    if ( place == "other") {
        setSelectedPlace(input_sport);
    } else if (place == "byInput") {
        setSelectedPlace(address);
    } else if (place == "all") {
        setSelectedPlace(address);
        all = 1;
    } else {
        setSelectedPlace(place);
    }
    if (e == undefined || e.keyCode == 13) {
        $('#where-content').hide();
    }
    $.cookie('place', place, {
        expires: 365
    });
    $.cookie('address', address, {
        expires: 365
    });
    $.cookie('zoom', zoom, {
        expires: 365
    });
    $.cookie('cityId', cityId, {
        expires: 365
    });
    $.cookie('cityUrl', cityUrl, {
        expires: 365
    });
    $.cookie('allCities', all, {
        expires: 365
    });
    loadFacList();  // reload list of facilities
    setHashURL();
}



function setPlaceInput(place,e) {    
    input_sport = $("input[name=address_place]").val();
    if ( place == "other") {
        setSelectedPlace(input_sport);
    } else {
        setSelectedPlace(place);
    }
    if (e == undefined || e.keyCode == 13) {
        $.cookie('place', 'byInput', {
            expires: 365
        });
        $.cookie('address', input_sport, {
            expires: 365
        });
        closeMenu();
        loadFacList();
    }    
}


/* temp */

function toUTM(x,y) {
    /* PP varianta */
    var lng = x*Math.pow(2,-5) + (-3700000); /* v UTM */
    var lon = y*Math.pow(2,-5) + 1300000; /* v UTM */
    return [lng, lon];

    /* WGS varianta */
    var pi = Math.PI;
    //var zone = Math.round((lonD + 183)/6);
    zone = 33;

    var lonR = x * pi / 180;
    var latR = this.y * pi / 180;
 	
    var pi = Math.PI;
    var units = 1;

    var k = 0.9996;  //scale factor (k)
    var a = 6378137;  //semi-major axis (a)
    var f = 1 / 298.257223563;  //flattening (f)

    var b = a * (1 - f);    //semi-minor axis
    var e2 = (a * a - b * b)/(a * a);  //eccentricity squared
    var e = Math.sqrt(e2);  //eccentricity
    var ei2 = (a * a - b * b)/(b * b); //second eccentricity squared
    var ei = Math.sqrt(ei2); //second eccentricity
    var n = (a - b)/(a + b);
    var G = a * (1 - n) * (1 - n * n) * (1 + (9 / 4) * n * n + (255 / 64) * Math.pow(n,4)) * (pi / 180);  //Mean length of an arc of one degree of the meridian

    var w = x - (zone * 6 - 183);  //longitude difference from CM
    w = w * pi / 180;  //convert to radians
    var t = Math.tan(latR);  //tan of latitude
    var rho = a * (1 - e2) / Math.pow(1 - (e2 * Math.sin(latR) * Math.sin(latR)),(3/2)); //radius of curvature in plane of meridian
    var nu = a / Math.sqrt(1 - (e2 * Math.sin(latR) * Math.sin(latR))); //radius of curvature in prime vertical
    var psi = nu / rho;
    var coslat = Math.cos(latR);
    var sinlat = Math.sin(latR);

    // calculate meridian distance
    var A0 = 1 - (e2/4) - (3 * e2 * e2 / 64) - (5 * Math.pow(e2, 3) / 256);
    var A2 = (3 / 8) * (e2 + (e2 * e2 /4) + (15 * Math.pow(e2, 3) /128));
    var A4 = (15 / 256) * (e2 * e2 + (3 * Math.pow(e2, 3) / 4));
    var A6 = 35 * Math.pow(e2, 3) / 3072;
    var m = a * ((A0 * latR) - (A2 * Math.sin(2 * latR)) + (A4 * Math.sin(4 * latR)) - (A6 * Math.sin(6 * latR)));

    // calculate easting
    var eterm1 = (w * w / 6) * coslat * coslat * (psi - t * t);
    var eterm2 = (Math.pow(w,4) / 120) * Math.pow(coslat,4) * (4 * Math.pow(psi,3) * (1 - 6 * t * t) + psi * psi * (1 + 8 * t * t) - psi * 2 * t * t + Math.pow(t,4));
    var eterm3 = (Math.pow(w,6) / 5040) * Math.pow(coslat,6) * (61 - 479 * t * t + 179 * Math.pow(t, 4) - Math.pow(t,6));
    var dE = k * nu * w * coslat * (1 + eterm1 + eterm2 + eterm3);

    var lng = 500000 + (dE / units);

    // calculate northing
    var nterm1 = (w * w /2) * nu * sinlat * coslat;
    var nterm2 = (Math.pow(w,4) / 24) * nu * sinlat * Math.pow(coslat, 3) * (4 * psi * psi + psi - t * t);
    var nterm3 = (Math.pow(w,6) / 720) * nu * sinlat * Math.pow(coslat, 5) * (8 * Math.pow(psi, 4) * (11 - 24 * t * t) - 28 * Math.pow(psi, 3) * (1 - 6 * t * t) + psi * psi * (1 - 32 * t * t) - psi * 2 * t * t + Math.pow(t, 4));
    var nterm4 = (Math.pow(w,8)/40320) * nu * sinlat * Math.pow(coslat,7) * (1385 - 3111 * t * t + 543 * Math.pow(t, 4) - Math.pow(t, 6));
    var dN = k * (m + nterm1 + nterm2 + nterm3 + nterm4);

    var lon = dN / units;

    return [x, y];

}

function toWGS84 (aaa,bbb) {
    /* PP varianta */
    var utm = toUTM(aaa,bbb);
    var x = utm[0];
    var y = utm[1];

    var pi = Math.PI;
    var units = 1;
    var zone = 33;

    var k = 0.9996;  //scale factor (k)
    var a = 6378137;  //semi-major axis (a)
    var f = 1 / 298.257223563;  //flattening (f)

    var b = a * (1 - f);    //semi-minor axis
    var e2 = (a * a - b * b)/(a * a);  //eccentricity squared
    var e = Math.sqrt(e2);  //eccentricity
    var ei2 = (a * a - b * b)/(b * b); //second eccentricity squared
    var ei = Math.sqrt(ei2); //second eccentricity
    var n = (a - b)/(a + b);
    var G = a * (1 - n) * (1 - n * n) * (1 + (9 / 4) * n * n + (255 / 64) * Math.pow(n,4)) * (pi / 180);  //Mean length of an arc of one degree of the meridian
    var north = (y - 0) * units;  //northing from the equator
    var east = (x - 500000) * units; //easting from the CM
    var m = north / k;  //meridian distance
    var sigma = (m * pi) / (180 * G);

    // calculate the foot point latitude and constants for that latitude
    var footlat = sigma + ((3 * n / 2) - (27 * Math.pow(n, 3) / 32)) * Math.sin(2 * sigma) + ((21 * n * n / 16) - (55 * Math.pow(n, 4) / 32)) * Math.sin(4 * sigma) + (151 * Math.pow(n, 3) / 96) * Math.sin(6 * sigma) + (1097 * Math.pow(n, 4) / 512) * Math.sin(8 * sigma);
    var rho = a * (1 - e2) / Math.pow(1 - (e2 * Math.sin(footlat) * Math.sin(footlat)),(3/2)); //radius of curvature in plane of meridian
    var nu = a / Math.sqrt(1 - (e2 * Math.sin(footlat) * Math.sin(footlat))); //radius of curvature in prime vertical
    var psi = nu / rho;
    var t = Math.tan(footlat);  //tan of latitude

    // calculate latitude
    var x = east / (k * nu);
    var laterm1 = (t / (k * rho )) * ( east * x / 2);
    var laterm2 = (t / (k * rho )) * ( east * Math.pow(x, 3) / 24) * (-4 * psi * psi + 9 * psi * (1 - t * t) + 12 * t * t );
    var laterm3 = (t / (k * rho )) * ( east * Math.pow(x, 5) / 720) * (8 * Math.pow(psi, 4) * (11 - 24 * t * t) - 12 * Math.pow(psi, 3) * (21 - 71 * t * t) + 15 * psi * psi * (15 - 98 * t * t + 15 * Math.pow(t, 4)) + 180 * psi * (5 * t * t - 3 * Math.pow(t, 4)) + 360 * Math.pow(t, 4));
    var laterm4 = (t / (k * rho )) * ( east * Math.pow(x, 7) / 40320) * (1385 + 3633 * t * t + 4095 * Math.pow(t, 4) + 1575 * Math.pow(t, 6));
    var latrad = footlat - laterm1 + laterm2 - laterm3 + laterm4;
    var lat = latrad * 180 / pi;


    // calculate longitude
    var seclat = 1 / Math.cos(footlat);
    var loterm1 = x * seclat;
    var loterm2 = (Math.pow(x, 3) / 6) * seclat * (psi + 2 * t * t);
    var loterm3 = (Math.pow(x, 5) / 120) * seclat * (-4 * Math.pow(psi, 3) * (1 - 6 * t * t) + psi * psi * (9 -68 * t * t) + 72 * psi * t * t + 24 * Math.pow(t, 4));
    var loterm4 = (Math.pow(x, 7) / 5040) * seclat * (61 + 662 * t * t + 1320 * Math.pow(t, 4) + 720 * Math.pow(t, 6));
    var w = loterm1 - loterm2 + loterm3 - loterm4;

    zone = ((zone * 6) - 183);
    var longrad = zone * pi / 180 + w;
    var lon = longrad * 180 / pi;

    return [lon, lat];

    /* WGS varianta */
    return this._formatWGS84([this.x, this.y], format);
}


function showWelcomeHelper() {
    if($.cookie('welcomeHelper') == undefined) {
        $.cookie('welcomeHelper', true, {
            expires: 365
        });
    }
    if($.cookie('welcomeHelper') == 'true') {
        $("#welcomeHelper").show();
        $("#how_does_it_work").hide();
    }
}
function showHintHelper() {
        $("#welcomeHelper").show();
        $("#how_does_it_work").hide();
}

function hideWelcomeHelper(){
    $.cookie('welcomeHelper', false, {
        expires: 365
    });
    $("#welcomeHelper").hide();
    $("#how_does_it_work").show();
}


function setHashURL() {
    var sportName;
    var cityId = $.cookie('cityId');
    var sportId = $.cookie('sportId');
    var cityUrl = $.cookie('cityUrl');
    if(cityUrl == null || cityUrl == '')  {
        cityUrl='no-city-selected';
    }

    $.getJSON("/ajax/facility/urlname/id/" + sportId, function(data) {
       sportName = data.SPO_cName;
       if(sportName == undefined) {
           sportName = 'no-sport-selected';
       }
       location.hash =  cityUrl + '/' + sportName;
    });


}
