/**
 * Created by IntelliJ IDEA.
 * User: mishka
 * Date: 11.05.2011
 * Time: 16:52:47
 * To change this template use File | Settings | File Templates.
 */
var navigate;
function gallery_show(n, name, cap, i, width, height) {
    arguments.callee.lastClicked = i;
    var img = $("#photo_pane").html("&nbsp;<img src=\"/gallery/item/" + n + "/" + name + "\" alt=\"" + cap + "\" title=\"" + cap + "\"/>&nbsp;");
    $("#photo_pane img").fadeTo(3000, 1);
    $("#photo_name").text("(" + (i + 1) + " θη " + ($("#photo_preview img").length) + ") " + cap);
    navigate(i);
}
jQuery(document).ready(function() {
    var div,cont,imgs;
    var onresize = function() {
        var h = $("#photo_pane").height() + "px";
        $("#photo_pane")[0].style.lineHeight = h;
    };

    $("a.gallery_show").click(function() {
        $.ajax({
            url: "/gallery.php",
            data: {
                n:$(this).attr("rel")
            },
            cache: false,
            context: document.body,
            success: function (data) {
                $("#photo_preview").html(data);
                $("#photo").show();
                div = $("#photo_preview div");
                cont = $("#photo_preview");
                imgs = $("#photo_preview div img");
                document.body.style.overflow="hidden";
                onresize();
                imgs[0].onclick();
            }
        });
    });



    $("#photo_exit").click(function() {
        $("#photo").hide();
        $("#photo_pane").html("");
        $("#map_pane").html("");
        $("#photo_preview").html("");
        $("#photo_name").text("")
        delete gallery_show.lastClicked;
        if(play)show_click();
        document.body.style.overflow="auto";
    });

    var move = function(to_pos, time){
        to_pos = Math.round(to_pos);
        var pos = parseInt(div.css("margin-left").replace("px",""));
        var limit = cont.width()-div.width();
        if(pos!=pos)pos=0;
//        if(to_pos>0)to_pos=0;
//        if(to_pos<limit)to_pos=limit;
        if(to_pos==pos)return;
        var dur;
        if(typeof(time)!="undefined" && time!==null) {
            div.animate({
                marginLeft: to_pos+"px"
            },time*1000);
        }
        else  {
            var speed = 300;
            dur = Math.abs((to_pos - pos)/speed);
            div.animate({
                marginLeft: to_pos+"px"
            },dur*1000,"linear");
        }
    };
    var animate = function(right){return function() {
        move(right?(cont.width()+$(imgs[imgs.length-1]).width())/2-div.width():(cont.width()-$(imgs[0]).width())/2);
    }};
    var clear = function(){
        div.stop();
    };
    var nextPhoto = function(right){return function(){
        clear();
        var cur,next;
        var animate;
        if(typeof(gallery_show.lastClicked)=="undefined"){
            cur = 0;
            next = 0;
        }
        else {
            cur = gallery_show.lastClicked;
            if(right)next = cur+1;
            else next = cur-1;
            if(next<0||next>= imgs.length)
            next=cur;
        }
        imgs[next].onclick();
    }};
    navigate = function(to) {
        var pos = -cont.width()/2;
        for (var i = 0; i <= to; i++) {
            var w = $(imgs[i]).width() + 30;
            if (i == to)
                w /= 2;
            pos += w;
        }
        move(-pos, 1);
    };
    $("#pnav_right").mousedown(animate(true));
    $("#pnav_left").mousedown(animate(false));
    $("#pnav_right").mouseup(clear);
    $("#pnav_right").mouseout(clear);
    $("#pnav_left").mouseup(clear);
    $("#pnav_left").mouseout(clear);
    $("#pnav_right1").click(nextPhoto(true));
    $("#pnav_left1").click(nextPhoto(false));
    var play = false;
    var show_click = function(){
        play = !play;
        if(play) {
            $("#pnav_show")[0].src = "/images/gallery/pause.png";
            setTimeout(playFun,3000);
        }
        else {
            $("#pnav_show")[0].src = "/images/gallery/play.png";
        }
    };
    var playFun = function(){
        if(!play) return;
        var cur;
        if(typeof(gallery_show.lastClicked)=="undefined") cur = 0;
        else cur = gallery_show.lastClicked+1;
        if(cur>=imgs.length) cur = 0;
        imgs[cur].onclick();
        setTimeout(playFun,5000);
    };
    $("#pnav_show").click(show_click);


    $("a.map_show").click(function() {
        var pane = $("#map_pane");
        var mapDiv = document.createElement("div");
        document.body.appendChild(mapDiv);
        mapDiv.style.left="20px";
        mapDiv.style.right="20px";
        mapDiv.style.top="20px";
        mapDiv.style.bottom="20px";
        mapDiv.style.position="absolute";
        pane[0].appendChild(mapDiv);

        document.body.style.overflow="hidden";
        var map = new google.maps.Map(mapDiv, {
            zoom: 2
            ,center: new google.maps.LatLng(44.08758487562074, 11.25)
            ,disableDefaultUI:true
            ,mapTypeId: google.maps.MapTypeId.ROADMAP
            //        mapTypeId: google.maps.MapTypeId.HYBRID
            //        mapTypeId: google.maps.MapTypeId.SATELLITE
            //        mapTypeId: google.maps.MapTypeId.TERRAIN
        });

        $("#photo").show();
        pane.show();

        window.map = map;
        google.maps.event.trigger(map, "resize");
        cont = $("#photo_preview");
        var preview_div = document.createElement("div");
        preview_div.style.width = "10000px";
        cont[0].appendChild(preview_div);
        div = $(preview_div);

//        onresize();
        $.ajax({
            url: "/geo.php",
            data: {
                n:$(this).attr("rel")
            },
            dataType: "json",
            cache: false,
            context: document.body,
            success: function (config) {
                var total = 0;
                for (var i = 0; i < config.length; ++i) {
                    var c = config[i];
                    var paths = getPaths(c.paths);
                    var minLat = paths[0][1].lat();
                    var minLng = paths[0][1].lng();
                    var maxLat = minLat;
                    var maxLng = minLng;
                    for(var j = 0; j<paths.length; ++j){
                        var path = paths[j];
                        for(var k = 0; k<path.length; ++k){
                            var p = path[k];
                            var lat = p.lat();
                            var lng = p.lng();
                            if(isNaN(lat)) ;
                            else if(minLat>lat) minLat = lat;
                            else if (maxLat<lat)maxLat = lat;
                            if(isNaN(lng)) ;
                            if(minLng>lng) minLng = lng;
                            else if (maxLng<lng)maxLng = lng;
                        }
                    }
                    var bounds = new google.maps.LatLngBounds(new google.maps.LatLng(minLat,minLng),new google.maps.LatLng(maxLat,maxLng));
                    var polygon = new google.maps.Polygon({
                        n:c.n,
                        title:c.title,
                        paths:paths,
                        strokeWeight: 1,
                        href: c.href,
                        fillColor:"#ffff00", fillOpacity: 0, strokeOpacity:0, strokeColor:"#ff0000"});
                    polygon.setMap(map);
                    //                if (c.lat || c.lng) {
                    //                    var cap = new google.maps.Marker({position:new google.maps.LatLng(c.lat, c.lng),icon:"/images/bullet.gif", polygon:polygon });
                    //                    cap.setMap(map);
                    //                    google.maps.event.addListener(cap, "mouseover", showMarker);
                    //                    google.maps.event.addListener(cap, "mouseout", hideMarker);
                    //                    google.maps.event.addListener(cap, "click", clickMarker);
                    //                }
                    google.maps.event.addListener(polygon, "mouseover", showPolygon);
                    google.maps.event.addListener(polygon, "mouseout", hidePolygon);
                    google.maps.event.addListener(polygon, "click", clickPolygon);
                    var img = document.createElement("img");
                    img.setAttribute("src","/images/geo/"+c.img+".png");
                    img.style.height = "70px";
                    img.onclick = (function(i, c, polygon, bounds) {return function(){
//                        showPolygon.call(polygon);
                        map.fitBounds(bounds);
                        gallery_show.lastClicked = i;
                        $("#photo_name").text("(" + (i + 1) + " θη " + ($("#photo_preview img").length) + ") " + c.title);
                        navigate(i);
                    }}(i,c,polygon,bounds));
                    preview_div.appendChild(img);
                    total+=parseInt(c.FLAG_WIDTH)+30;
                }
                preview_div.style.width = total+"px";
                imgs = $("#photo_preview div img");
            }
        });
    });
    function getPaths(str) {
        var parts = str.split(" ");
        var res = [];
        for (var i = 0; i < parts.length; ++i) {
            res[i] = google.maps.geometry.encoding.decodePath(parts[i]);
        }
        return res;
    }

    function showPolygon(e) {
//        var v = document.getElementById("country_name");
//        v.value = this.title;
        this.setOptions({ fillOpacity: 0.3, strokeOpacity:1})
    }

    function clickPolygon(e) {
        window.location = this.href;
    }

    function hidePolygon(e) {
        this.setOptions({ fillOpacity: 0, strokeOpacity:0})
    }

    $(window).resize(onresize);
});

