if (!django)
    var django = {jQuery:jQuery};

if (!LANG)
    var LANG = 'fr';

(function($) {

var geocoder;

$.fn.extend({
    translate: function() {
        if (typeof(google)!='undefined') {
            this.each(function() {
                var self = $(this);
                google.language.translate(self.text(), "", $.defaultLanguage, function(result) {
                  if (!result.error) { self.html(result.translation) }
                });
            });
        }
        return this;
    },
    gmap: function(ratio) {
      $(this).each(function() {
          if (GBrowserIsCompatible()) {
            // build an array with data from the DOM
            var markers = new Array();
            var center = 0;

            var self = $(this);

            $('dl dt.title', self).each(function(i) {
                markers.push({"title":$(this).html()});
            });
            $('dl dt.marker img', self).each(function(i) {
                markers[i]['icon_url'] = $(this).attr('src');
            });
            $('dl dd span.lat_lng', self).each(function(i) {
                var lat_lng = $(this).text();
                if (lat_lng) {
                    lat_lng = lat_lng.split(',');
                    markers[i]['lat'] = lat_lng[0];
                    markers[i]['lng'] = lat_lng[1];
                    center = 1;
                }
            });
            $('dl dd.tab', self).each(function(i) {
                markers[i]['description'] = $(this).html();
            });

            var map = new GMap2(this);
            var set_center = function() {
                if (center != 0){
                    map.setCenter(new GLatLng(markers[0]['lat'], markers[0]['lng']), 3);
                }
                else{
                    map.setCenter(new GLatLng(48.859294, 2.335741), 3);
                }
            }
            GEvent.addListener(map, "load", function() {
                set_center();
            });

            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['lat'], marker_info['lng']);
                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() {
                self.css('height', self.attr('offsetWidth')/ratio + 'px');
                map.checkResize();
            }

            // resize the map when the window is resized
            $(window).bind('resize', map_resize)
            // also resize the map now
            set_center()
          }
          // remove the animated gif to save the planet
          self.css('background-image', 'None')
        });
        return this;
    },
    latlngField: function(options) {
        if (!GBrowserIsCompatible()) return;

        if (!geocoder) geocoder = new GClientGeocoder();
    
        $(this).each(function() {
            var is_admin = false;
            var field = $(this);
            var field_wrapper = field.parents('p');
            if (!field_wrapper.length) {
                var field_wrapper = field.parents('div.lat_lng');
                is_admin = true;
            } else {
                field_wrapper.append('<div class="lat_lng_wrapper"></div>'),
                field_wrapper.append('<a class="refresh-map ui-state-default ui-corner-all"><span class="ui-icon ui-icon-refresh"></span></a>');
                field_wrapper = $('.lat_lng_wrapper', field_wrapper);
                field_wrapper
                    .removeClass('textInput')
                    .css('float', 'left')
                    .css('padding-left', '10px');
            }

            field_wrapper.append('<div class="googlemap-field"></div>');
            var plugin = $('.googlemap-field', field_wrapper);

            if (is_admin) {
                plugin.css('width', '50em');
                plugin.css('height', '30em');
                plugin.css('margin', '0.2em');
                plugin.css('margin-top', '2em');
            } else {
                plugin.css('width', '23em');
                plugin.css('height', '23em');
                plugin.css('margin', '0.2em');
            }

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

            var form = field.parents('form');

            var address = $('.latlngtext_widget', form);

            address.change(function() {
                geocoder.getLocations(address.val(), function(data) {
                    var place = data.Placemark[0];
                    var point = new GLatLng(place.Point.coordinates[1],
                                            place.Point.coordinates[0]);
                    fieldmap.setCenter(point, 11);
                    fieldmap.zoomIn();
                });
            });

            // restore center from point after submit
            if (field.val()) {
                var point = GLatLng.fromUrlValue(field.val());
                fieldmap.setCenter(point, 11);
            } else if (address.val()) {
                address.change();
            } else if ($('#latlng').val()) {
                var point = GLatLng.fromUrlValue($('#latlng').val());
                fieldmap.setCenter(point, 9);
            } else {
                fieldmap.setCenter(new GLatLng(50.736455137010665,-13.359375), 2);
            }

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

$.extend({missing: {

    onload: function(node) {
        // stuff loaded for caching facility
        if ($('body.change-form').length == 0) {
            $('.username').load('/username/');
            $('.csrftoken').load('/csrftoken/');
        } else {
            $('.username').hide();
        }

        // admin
        $('td.delete:empty').parents('tr').remove();
        $('img.person-image').parents('td').removeClass('original');

        // ugly html fixes
        $('p > label[for="id_sex_0"]').parent().append($('#id_sex_0').parents('ul'));
        $('label[for="id_creator_id"]').parents('p').hide();

        // map
        var show = $('.show', '#mapctl');
        var hide = $('.hide', '#mapctl');
        var toggleMap = function() {
            show.toggleClass('hidden');
            hide.toggleClass('hidden');
            $('#googlemap').toggleClass('hidden');
            $('#disasters').toggleClass('hidden');
        };
        show.click(toggleMap);
        hide.click(toggleMap);

        person_form = $('form.person-form');
        if (person_form.length) {
            $('input', person_form).change(function() {
                var popup = $('<div></div>');
                $('body').append(popup);
                $.get('/guess_double/',
                    person_form.formSerialize(),
                    function(data) {
                         if (/message/.test(data)) {
                             popup.append(data);
                             popup.dialog({
                                 modal: true,
                                 resizable:false,
                                 close: function(e, ui) {
                                     popup.dialog('destroy');
                                     popup.remove();
                                 }
                             });
                        }
                    }
                );
            });
        }
    },

    bind_table_filter: function(node) {
        node = $('#criteria', node);
        if (!node.length) return;

        var val = jQuery('input#criteria_value', node);
        $('input[name="criteria"]', node).click(function() { 
            val.val($(this).attr('id'), node);
            $(this).parents('form').submit();
        });
        if (val.val()) {
            var current = $('#'+val.val(), node);
        } else {
            var current = $('#displayAll', node);
        }
		current.parents('span').addClass('active').find('input:radio').attr('checked','checked').end().siblings().removeClass('active')
    },
    bind: function(node) {
        $('input.latlng_widget', node).latlngField();
        if (node.hasClass('change-form'))
            // admin
            return;

        if (!$('.jNiceWrapper, .jNiceInputWrapper', node).length) {
            $('form input:text, form input:password, fieldset input:text, fieldset input:password', node).not('.dateInput').wrap('<span class="textInput"></span>');
            $('form textarea, fieldset textarea', node).wrap('<span class="textArea"></span>');
            $('form :submit, fieldset :submit', node).wrap('<span class="submitInput"></span>');
            $('fieldset.jNice, form.jNice', node).jNice();
            $('.date_widget', node).datepicker({
                showOn: 'both',
                buttonImage: '/media/html/images/calendar.gif',
                beforeShow: function() { setTimeout(function(){$('#ui-datepicker-div').css('z-index', '1000')}, 100); }
                }).parents('p').addClass('short');
            $('.field_required').each(function() {
               var label = $('label', $(this).parents('p'));
               label.text(label.text()+' *');
            });
        }

        $('#googlemap', node).gmap();

        $('ul.errorlist', node).addClass('ui-widget ui-corner-all ui-state-error').prev('p').each(function() {
           var self = $(this);
           self.append(self.next('ul'));
        });

        $('.reload', node).each(function() {
            var self = $(this);
            // FIXME
            $.get(self.attr('href'), function(data) {
               var reload = $(self.text());
               reload.empty();
               data = $(data);
               reload.append(data);
               $.missing.bind(reload);
            });
        }); 

        $('#searchPerson, #criteriaPerson').attr('action', window.location.href);

        if ($.datepicker) {
            $.datepicker.setDefaults($.extend({dateFormat:'yy-mm-dd'}, $.datepicker.regional[LANG]));
            $('.date_widget', node).datepicker({"dateFormat":'yy-mm-dd'});
        }

        $('.contribution', node).click(function() {
            $('.contribution-body', this).toggleClass('hidden')
        });

        $('.tooltiped', node).each(function() {
            // FIXME
            $(this).simpletip({fixed: true, position: 'bottom', content: $('.tooltip', this).html()})
        });

        $('.popup_form', node).click($.missing.ajaxForm);

        $('.add-attachment-link', node).click(function() {
            var self = $(this);
            var form = $('.add-attachment').clone();
            $('label', form).remove();
            var title = $('span', self[0]).text();
            form.jup({
                    json: false,
                    onComplete : function(response, formId) {
                        form.dialog('close');
                        form.dialog('destroy');
                        form.remove();
                        var att = $('.xhr-attachments');
                        att.load(att.attr('alt'), function() {
                            $('#thumbs a').click(function() {
                                var src= $(this).attr('rel');
                                $('#bigPic img').attr('src', src);
                            });
                        });
                    }
                  })
                .dialog({modal:true, width:400,
                         title:title,
                         resizable:false,
                         close: function(e, ui) {
                             form.dialog('destroy');
                             form.remove();
                         }
                        });
            return false;
        });

        $('.add-video-link', node).click(function() {
            var self = $(this);
            var form = $('.add-video').clone();
            $('label', form).remove();
            var title = $('span', self[0]).text();
            form.jup({
                    json: false,
                    onComplete : function(response, formId) {
                        form.dialog('close');
                        form.dialog('destroy');
                        form.remove();
                        var att = $('.xhr-videos');
                        att.load(att.attr('alt'));
                    }
                  })
                .dialog({modal:true, width:400,
                         title:title,
                         resizable:false,
                         close: function(e, ui) {
                             form.dialog('destroy');
                             form.remove();
                         }
                        });
            return false;
        });

        $("#lang a, ul.lang a").click(function() {
            var lang = $(this).attr('href').replace(/#/, '');
            var form = $('#lang form');
            $('#setlang', form).val(lang);
            form.submit();
        });

        $('.translatable').translate();
        $('.lazy-translate').click(function() {
            $('.lazy-translatable').translate();
            return false;
        });

    },
    autoclose: function() {
        if ($('.autoclose').length) {
            $('.autoclose').remove();
            setTimeout(function() {
                $('.ui-icon-closethick').click();
                $('.ui-dialog').remove();
            }, 3000);
        }
    },
    ajaxForm: function() {
        var self = $(this);
        if (IS_ANONYMOUS)
            window.location.href = '/accounts/login?next=' + window.location.href;
        if (self.attr('href')) {
            // link click - create popup and initialize form
            var action = self.attr('href');
            var popup = $('<div class="ajax_form"></div>');
            $('body').append(popup);
            $.ajax({
                type: 'GET',
                url: action,
                dataType: 'html',
                success: function(data) {
                    var form = $(data);
                    form.attr('action', action);
                    form.submit($.missing.ajaxForm);
                    popup.append(form);
                    $.missing.bind(form);
                    popup.dialog({modal: true, resizable:false, width:571, title: form.attr('title')});
                    $.missing.autoclose();
                }
            }); 
        } else {
            // form submit - reload form or display message
            var action = self.attr('action');
            var popup = self.parents('.ajax_form');
            $.ajax({
                type: 'POST',
                url: action,
                data: self.formSerialize(),
                dataType: 'html',
                success: function(data) {
                    var form = $(data);
                    popup.empty();
                    popup.append(form);
                    $.missing.bind(form);
                    if (!/message/.test(data)) {
                        form.attr('action', action);
                        form.submit($.missing.ajaxForm);
                        popup.dialog({modal: true, resizable:false, title: form.attr('title')});
                    }
                    $.missing.autoclose();
                }
            }); 
        }
        return false;
    }

}});

$(function() {
    $.missing.onload($('body'));
    $.missing.bind($('body'));
    $.missing.bind_table_filter($('body'));
});

if (typeof(google)!='undefined') {
    $.defaultLanguage = GLanguage.getLanguageCode().split('-')[0];
    if ($.defaultLanguage != LANG)
        $.defaultLanguage = LANG;
}

$(function() {
if (typeof(CRAWLER_DATA)!='undefined' && CRAWLER_URL) {
    $.getScript(CRAWLER_URL+'?callback=crawler_callback&data='+encodeURI(JSON.stringify(CRAWLER_DATA)).replace(/#/, ''));
}
});

}(django.jQuery));

var crawler_callback = function(data) {
        var got_results = false;
        if (data['results']) {
            var results = data['results'];
            for (var i = 0; results.length; i++) {
                got_results = true;
                var item = results[i];
                jQuery('ul.news-items').append('<li class="'+item['category']+'"><a target="_blank" href="'+item['url']+'">'+item['title']+'</a></li>');
            }
        }
        if (!got_results) {
            jQuery('div.news').empty();
        }
}

