

var geocoder;

function googlemap_init(ratio) {
  if (GBrowserIsCompatible()) {
    // build an array with data from the DOM
    var markers = new Array();
    var center = 0;

    if ($('dl dd span.latitude').size() == 1){
        center = 1;
    }
    $('#googlemap dl dt.title').each(
        function(i) {
                markers.push({"title":$(this).html()});
        });
    $('#googlemap dl dt.marker img').each(
        function(i) {
                markers[i]['icon_url'] = $(this).attr('src');
        });
    $('#googlemap dl dd span.latitude').each(
        function(i) {
                markers[i]['latitude'] = $(this).text();
        });
    $('#googlemap dl dd span.longitude').each(
        function(i) {
                markers[i]['longitude'] = $(this).text();
        });
    $('#googlemap dl dd.tab').each(
        function(i) {
                markers[i]['description'] = $(this).html();
        });

    var map = new GMap2(document.getElementById("googlemap"));

    if (center != 0){
        map.setCenter(new GLatLng(markers[0]['latitude'], markers[0]['longitude']), 12);
    }
    else{
        map.setCenter(new GLatLng(48.859294, 2.335741), 12);
    }
    map.setUIToDefault();

    function create_marker(marker_info) {
        // create a GMark from an array of data
        var customIcon = new GIcon(G_DEFAULT_ICON);
        customIcon.image = marker_info['icon_url'];
        var point = new GLatLng(marker_info['latitude'], marker_info['longitude']);
        var marker = new GMarker(point, { icon:customIcon });
        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(marker_info['title']+marker_info['description'], {maxWidth : 400});
        });
        return marker;
    }

    // add markers to the map
    $(markers).each(function() {
        map.addOverlay(create_marker(this));
    });

    // function to refresh the map size
    function map_resize() {
        document.getElementById('googlemap').style.height = document.getElementById('googlemap').offsetWidth/ratio + 'px';
        map.checkResize();
    }

    // resize the map when the window is resized
    $(window).bind('resize', map_resize)
    // also resize the map now
    map_resize()
    if (center != 0){
        map.setCenter(new GLatLng(markers[0]['latitude'], markers[0]['longitude']), 12);
    }
    else{
        map.setCenter(new GLatLng(48.859294, 2.335741), 12);
    }

  }
  // remove the animated gif to save the planet
  $('#map').css('background-image', 'None')
  $('#fullmap').css('background-image', 'None')
}

jQuery.fa.extend({
    radius: function(field, plugin, options) {
        plugin.remove();
        field.parents('div.fa_field').addClass('hidden');
        var loctype = field.getFaField('loctype');
        loctype.change(function() {
            if (loctype.val() == 'demande') {
                field.parents('div.fa_field').removeClass('hidden');
            } else {
                field.parents('div.fa_field').addClass('hidden');
            }
        });
    },
    address: function(field, plugin, options) {

        if (!GBrowserIsCompatible()) return;

        if (!geocoder) geocoder = new GClientGeocoder();

        field.css('width', '20em');
        plugin.css('margin', '0.2em');
        plugin.css('width', '22em');
        plugin.css('height', '10em');

        var field_wrapper = field.parents('.fa_field');
        field_wrapper.css('width', '23em');

        var fieldmap = new GMap2(plugin[0]);
        fieldmap.setUIToDefault();

        var form = field.parents('form');
        var lat = field.getFaField("lat");
        var lng = field.getFaField("lng");

        // load address on change (keypress ?)
        var update_map = function() {
            if (field.val()) {
                geocoder.getLatLng(
                   field.val()+', France',
                   function(point) {
                      if (point) {
                        lng.val(point.lng());
                        lat.val(point.lat());
                        fieldmap.setCenter(point, 15);
                       }
                });
             }
        }
        go_button = $('span.lookup', field_wrapper);
        go_button.click(update_map);
        address_field = $('#Location--address');
        address_field.blur(update_map);
        form.submit(function() {if (!lat.val()) update_map();});

        // restore center from point after submit
        if (lat.val() && lng.val()) {
            var point = GLatLng.fromUrlValue(lat.val()+','+lng.val());
            fieldmap.setCenter(point, 15);
        } else {
            fieldmap.setCenter(new GLatLng(48.8421807, 2.3430892), 13);
        }

        // save lat/lng on move
        /*
        GEvent.addListener(fieldmap, "moveend", function() {
            var center = fieldmap.getCenter();
            lat.val(center.lat());
            lng.val(center.lng());
        });
        */
    }
});

function submit_eventform() {
    $.post('/events/add?formonly', $('#event_form').serialize(), function(data) {
        $('#ajax_event_form').html(data);
        bind_eventform();
    });
}
function submit_locationform() {
    $.post('/locations/add?formonly', $('#location_form').serialize(), function(data) {
        $('#ajax_location_form').html(data);
        bind_locationform();
    });
}


function bind_eventform() {
    $('#event_form').submit( function() {
            submit_eventform();
            return false;
    });
}
function bind_locationform() {
    $('#location_form').submit( function() {
            submit_locationform();
            return false;
    });
}

function ajaxforms_init() {
    // bring the form
    bind_eventform();
    bind_locationform();

    var options = {width:'25em', modal:true, resizable:false, bgiframe:true, autoOpen:false};
    $("#ajax_location_form").dialog(options);
    $("#ajax_event_form").dialog(options);

}

function flashmessage_init() {
    $('#flashmessage').dialog({modal: true, draggable: false });
}

function admin_listing() {
    $('.admin-delete').click(function() {
        var link = $(this);
        $.getJSON(link.attr('href'),
                  function(data) {
                    if (data.status) {
                        alert(data.error);
                    } else {
                        link.parents('tr').remove();
                    }
                  });
        return false;
        });
}


$(function() {
    $.datepicker.setDefaults($.extend({showMonthAfterYear:false}, $.datepicker.regional['fr']));
    if ($(document).width() <= 1024) {
        $('#wrapper').css('width','100%');
    }
});

monthNames =  ['janvier', 'février', 'mars', 'avril', 'mai', 'juin',
               'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre']
dayNames = ['dimanche', 'lundi', 'mardi', 'mercredi',
            'jeudi', 'vendredi', 'samedi']
monthNamesShort = ['jan', 'fév', 'mars', 'avr', 'mai', 'juin',
                   'juil', 'août', 'sept', 'oct', 'nov', 'déc']
dayNamesShort = ['dim', 'lun', 'mar', 'mer', 'jeu', 'ven', 'sam']
buttonText =  {today: 'aujourd\'hui',
               month: 'mois',
               week: 'semaine',
               day: 'jour' }


function fetch_events(events) {
    // build the events array from elements on the page
    $('#fullcalendar div.event').each(
        function(i) {
          events.push( {
            "id":         $(this).get(0).id,
            "allDay":     false,
            "title":      $(this).children("div.title").text(),
            "url":        $(this).children('div.title').children().attr('href'),
            "where":      $(this).children("div.where").text(),
            "start":      $(this).children("div.starttime").text(),
            "end":        $(this).children("div.endtime").text(),
            "description":$(this).children("div.description").html(),
            "contact":    $(this).children("div.contact").html()
            });
        }
    );
};

var x0, y0, e, popup, show=0;
function showPopup(calEvent, jsEvent, view) {
    if (!popup) popup=document.getElementById("calendar_popup");
    show=0
    $(popup).html(calEvent.description);
    popup.style.visibility="visible"
};

function hidePopup(calEvent, jsEvent, view) {
    /* popup.innerHTML=txt */
    if (!popup) popup=document.getElementById("calendar_popup");
    popup.style.visibility="hidden"
    show=0
};

// borrowed from http://www.howtocreate.co.uk/tutorials/javascript/browserwindow // very useful
function getSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [myWidth, myHeight]
}

function movePopup(e) {
    if (!popup) popup=document.getElementById("calendar_popup");
    if (show==1) popup.style.visibility="visible"
    if (e || navigator.userAgent.indexOf('Mozilla')) {
        var xo=window.pageXOffset
        var yo=window.pageYOffset
    } else {
        if (!e) e = event
            var xo=document.documentElement.scrollLeft
            var yo=document.documentElement.scrollTop
    }
    if (e.clientY+15 + popup.clientHeight > getSize()[1]) {
        popup.style.top=e.clientY+yo-15-popup.clientHeight+"px"
    }
    else {
        popup.style.top=e.clientY+yo+15+"px"
    }

    popup.style.left=Math.min( Math.max(10, e.clientX+xo-120),
    getSize()[0]-popup.clientWidth-28)+"px"
};

function fullcalendar_init(ratio) {
    var events = new Array();
    fetch_events(events);

    $('#fullcalendar').fullCalendar({
        events: events,
        eventMouseover: showPopup,
        eventMouseout: hidePopup,
        aspectRatio: ratio,
        theme: true,
        timeFormat: { 'agenda': 'HH:mm{ - HH:mm}',
                      '': 'HH:mm{ - HH:mm}' },
        columnFormat: {month: 'ddd',
                      week: 'dddd d MMM',
                      day: 'dddd d MMM yyyy'},
        titleFormat: {month: 'MMMM yyyy',
                      week: "d MMMM 'au' {d MMMM} yyyy",
                      day: 'dddd d MMMM yyyy'},
        header: { left:'title',
                  center:'basicDay basicWeek month',
                  right:'today prev,next' },
        firstDay: 1,
        theme: true,
        buttonText: buttonText,
        monthNames: monthNames,
        dayNames: dayNames,
        monthNamesShort: monthNamesShort,
        dayNamesShort: dayNamesShort
    });
  // remove the animated gif to save the planet
  $('#fullcalendar').css('background-image', 'None')

  document.getElementById("fullcalendar").onmousemove=movePopup;
};


function homecalendar_init(ratio) {
    var events = new Array();
    fetch_events(events);

    $('#fullcalendar').fullCalendar({
        events: events,
        eventMouseover: showPopup,
        eventMouseout: hidePopup,
        aspectRatio: ratio,
        theme: true,
        defaultView: 'basicWeek',
        columnFormat: {month: 'ddd',
                      week: 'ddd d/MM',
                      day: 'dddd d MMM yyyy'},
        timeFormat: { 'agenda': 'HH:mm{ - HH:mm}',
                      '': 'HH:mm{ - HH:mm}' },
        header: { left:'',
                  center:'',
                  right:'' },
        firstDay: 1,
        buttonText: buttonText,
        monthNames: monthNames,
        dayNames: dayNames,
        monthNamesShort: monthNamesShort,
        dayNamesShort: dayNamesShort
    });
    // remove the animated gif to save the planet
    $('#fullcalendar').css('background-image', 'None')

    document.getElementById("fullcalendar").onmousemove=movePopup;
};



