$(document).ready(function()
    {
        $('body').gwGraincenters();
    });
function flashSetRegion(id)
{
    $('body').trigger('flashSetRegion', id)
}
(function($){
    $.fn.gwGraincenters = function(options)
    {
        var defaults = {
            gmap : $('#gmapMap'),
            gmapCenter : {
                lat:46.802071,
                lng: -71.244926,
                zoom: 5
            },
            flashmap : $('#regionMap')
        };
        var options = $.extend(defaults, options)
        var goToMap = false // Indicate if we already have scroll to map with anchor #
        var gmap = null
        var markers = new Array()
        var latlngs = new Array()
        var gwicons = new Array()
        var gwiconsSize = [8,16,24,32,48];
        // Build gwicons
        for(i=0; i<gwiconsSize.length; i++)
        {
            gwicons[i] = new GIcon()
            gwicons[i].image = "/img/graincenters/pin"+gwiconsSize[i]+".png";
            gwicons[i].shadow ="/img/graincenters/pin"+gwiconsSize[i]+"_shadow.png";
            gwicons[i].gwiconsize = new GSize(-gwiconsSize[i], -gwiconsSize[i]);
            gwicons[i].shadowSize = new GSize(gwiconsSize[i], gwiconsSize[i]);
            gwicons[i].iconAnchor  = new GPoint(Math.floor(gwiconsSize[i]/2), gwiconsSize[i]);
            gwicons[i].infoWindowAnchor  = new GPoint(Math.floor(gwiconsSize[i]/2), 0);
        }
			
        /**
		* Flash specifics event functions
		*/
        // Handles the click on a region of flash
        $(this).bind('flashSetRegion', function(event, id)
        {
            $('#GraincentersRegion').val(id) // Set Google Map select region too
            $.get('/acheteurs/region:'+id, {}, function(data){
                GraincentersLoaded(data, true)
                if(!goToMap)
                {
                    document.location.href = '#goToMap'
                    goToMap = true
                }
                document.location.href = '#/acheteurs/region:'+id
            },'json')
            return "1"
        })
				
        /**
		* Google Map specifics functions
		*/
        // get default icon for a given map
        function getIcon()
        {
            zoom = gmap.getZoom()
            if(zoom<8){
                return gwicons[0];
            }
            if(zoom<10){
                return gwicons[1];
            }
            if(zoom<12){
                return gwicons[2];
            }
            if(zoom<14){
                return gwicons[3];
            }
            return gwicons[4];
        }
		
        // create marker for a graincenter
        function createMarker(latlng, graincenter)
        {
            if(gmap != null)
            {
                var marker = new GMarker(latlng);
                GEvent.addListener(marker,"click", function() {
                    gmap.openInfoWindowHtml(latlng, graincenter.html);
                });
                gmap.addOverlay(marker);
                markers.push(marker);
            }
        }
        // City or Produce or Bid Change select
        var produceChange =  function()
        {
            city = $('#GraincentersCity').val();
            region = $('#GraincentersRegion').val();
            produce = $('#GraincentersProduce').val();
            bid = $('#GraincentersBid').val();
            service = $('#service').val();
            url = '/acheteurs/region:'+region+'/city:'+city+'/produce:'+produce+'/bid:'+bid+'/service:'+service;
            $.get(url, {}, function(data){
                GraincentersLoaded(data, true);
            },'json');
            return true;
        }
        // City or Produce or Bid Change select
        var anyFieldChange =  function()
        {
            city = $('#GraincentersCity').val();
            region = $('#GraincentersRegion').val();
            produce = $('#GraincentersProduce').val();
            subproduce = $('#GraincentersSubproduce').val();
            service = $('#service').val();
            bid = $('#GraincentersBid').val();
            url = '/acheteurs/region:'+region+'/city:'+city+'/produce:'+produce+'/subproduce:'+subproduce+'/bid:'+bid+'/service:'+service;
            $.get(url, {}, function(data){
                GraincentersLoaded(data, true);
            },'json');
            return true;
        }
        // Switch between two maps types (gmap|flash)
        mapSwitchClick = function()
        {
            elem = $(this)
            $('#GraincentersMapSwitch a').removeClass('active');
            if(elem.hasClass('gmap'))
            {
                options.gmap.show();
                options.flashmap.hide();
                $('#GraincentersMapSwitch .gmap').addClass('active');
            }
            else
            {
                options.gmap.hide();
                options.flashmap.show();
                $('#GraincentersMapSwitch .region').addClass('active');
            }
            return false
        }
				
        // Handles the click on paginator anchors
        var paginateClick = function()
        {
            $.get($(this).attr("href"), {}, function(data){
                GraincentersLoaded(data, false)
            },'json');
            goToMap = true
            document.location.href = '#'+ $(this).attr("href")
            return false;
        }
		
        var loadGraincenters = function(graincenters)
        {
            if (GBrowserIsCompatible())
            {
                if(gmap==null)
                {
                    gmap = new GMap2(options.gmap.get(0));
                    gmap.setCenter(new GLatLng(options.gmapCenter.lat, options.gmapCenter.lng), options.gmapCenter.zoom);
                    gmap.setUIToDefault();
                /*
		            GEvent.addListener(gmap,"zoomend",function(){
		                gmap.clearOverlays();
		                markers = new Array();
		                for (i in latlngs) {
		                    createMarker(latlngs[i], graincenters[i].Graincenter);
		                }
		            });
                            */
                }
                else
                {
                    gmap.clearOverlays();
                    markers = new Array();
                }
                if(graincenters == null || graincenters.length == 0)
                {
                    $('#gmapMap').css('opacity',0.5);
                    gmap.clearOverlays();
                    markers = new Array();
                }
                else
                {
                    $('#gmapMap').css('opacity',1);
                    latlngs = new Array();
                    var latlng;
                    for(i=0; i<graincenters.length; i++)
                    {
                        if(graincenters[i].Graincenter.lat!=null&&graincenters[i].Graincenter.lng!=null)
                        {
                            latlng = new GLatLng(graincenters[i].Graincenter.lat,graincenters[i].Graincenter.lng);
                            latlngs[i] = latlng;
                        }
                    }
                    var gPolygon = new GPolygon(latlngs);
                    var bounds = gPolygon.getBounds();
                    var zoom = gmap.getBoundsZoomLevel(bounds);
                    if(zoom>15)zoom = 15;
                    
                    gmap.setCenter(bounds.getCenter(), zoom);
                    var span = bounds.toSpan();
                    var span2 = gmap.getBounds().toSpan();
                    while(span2.lat()/span.lat() < 1.1 || span2.lng()/span.lng() < 1.1)
                    {
                        zoom--;
                        gmap.setCenter(bounds.getCenter(), zoom);
                        span2 = gmap.getBounds().toSpan();
                    }

                    for(i=0; i<graincenters.length; i++)
                    {
                        if(graincenters[i].Graincenter.lat!=null&&graincenters[i].Graincenter.lng!=null)
                        {
                            createMarker(latlngs[i], graincenters[i].Graincenter);
                        }
                    }
                }
            }
        }
		
        var GraincentersLoaded = function(data, reloadMap)
        {
            if(data)
            {
                $('#Graincenters').html(data.html)
                // Update city list
                if(data.changeSubproduce)
                {
                    var nbSubproduce = 0;
                    if(data.listSubproduce != null)
                    {
                        var subproduce = $('#GraincentersSubproduce');
                        subproduce.html('');
                        for (var i in data.listSubproduce) {
                            subproduce.append(new Option(data.listSubproduce[i], i));
                            nbSubproduce++;
                        }
                        $('#subproduceSpan').show();
                    }
                    if(data.listSubproduce == null || nbSubproduce < 2)
                    {
                        $('#subproduceSpan').hide();
                    }
                }
                if(data.cityOptions !=null)
                {
                    selectElem = document.getElementById('GraincentersCity')
                    selectVal = $('option:selected',selectElem).html()
                    while (selectElem.options.length > 0)
                    {
                        selectElem.options[0] = null;
                    }
                    for(i in data.cityOptions)
                    {
                        selectElem.options.add(new Option(data.cityOptions[i], i, (selectVal == data.cityOptions[i])))
                    }
                }
                if(reloadMap)
                {
                    loadGraincenters(data.GraincentersList);
                }
            }
            $('#paging a').unbind('click').click(paginateClick);
            $('#GraincentersBack').unbind('change').click(paginateClick);
            $('#GraincentersCity').unbind('change').change(anyFieldChange)
            $('#GraincentersProduce').unbind('change').change(produceChange);
            $('#GraincentersBid').unbind('change').change(anyFieldChange);
            $('#GraincentersSubproduce').unbind('change').change(anyFieldChange);
            $('#service').unbind('change').change(anyFieldChange);
            updateAutoComplete();
        }
		
        var updateAutoComplete  = function()
        {
            // Autocomplete field
            $('#GraincentersKeywords').searchField()
            $("#GraincentersKeywords").autocomplete({
                data : GraincentersQuick,
                width: 400,
                scrollHeight:300,
                minChars: 2,
                autoFill: false,
                selectFirst:false,
                matchSubset : true,
                matchContains: true,
                formatItem:function(row)
                {
                    return row.Enterprise.name + ((row.Graincenter.city.length>0) ? ' (' + row.Graincenter.city + ')' : '')
                },
                formatMatch:function(row)
                {
                    return row.Enterprise.name + row.Graincenter.city
                },
                formatResult:function(row)
                {
                    return "Recherche rapide"
                },
                result:function(event, data, formatted)
                {
                    $.get('/acheteurs/id:'+data.Graincenter.id, {}, function(data){
                        GraincentersLoaded(data, true)
                    }, 'json')
                    return ""
                }
            });
            $("#GraincentersKeywords").keypress(function(e){
                if (e.keyCode == 13) return false;
            });
        }

        var addProduce = function()
        {
            var optionList = ''
            for each(var i in list_produce){
                optionList += '<option value="'+i+'">'+list_produce[i]+'</option>'
            }
            $('#myTable tr:last').after('<tr'+(nb_produce%2?class="altrow":"")+'>'+
                '<td class="left">'+
                '<div class="input select"><select id="GProduce'+nb_produce+'Id" name="data[GProduce]['+nb_produce+'][id]">'+optionList+'</select></div>'+
                '</td>'+
                '<td class="center">'+
                '<div class="input checkbox"><input type="hidden" value="0" id="GProduce'+nb_produce+'GraincentersProduceSell_" name="data[GProduce]['+nb_produce+'][GraincentersProduce][sell]"><input type="checkbox" id="GProduce'+nb_produce+'GraincentersProduceSell" value="1" name="data[GProduce]['+nb_produce+'][GraincentersProduce][sell]"></div>'+
                '</td>'+
                '<td class="center">'+
                '<div class="input checkbox"><input type="hidden" value="0" id="GProduce'+nb_produce+'GraincentersProduceBuy_" name="data[GProduce]['+nb_produce+'][GraincentersProduce][buy]"><input type="checkbox" id="GProduce'+nb_produce+'GraincentersProduceBuy" value="1" name="data[GProduce]['+nb_produce+'][GraincentersProduce][buy]"></div>'+
                '</td>'+
                '<td class="actions">X</td>'+
                '</tr>');
            nb_produce++;
        }
        /**
		 * Initialization
		 */
			
        $('#regionMap').hide();
        $('#GraincentersMapSwitch .gmap').addClass('active');
        $('#GraincentersMapSwitch a').click(mapSwitchClick)
		
        GraincentersLoaded({
            GraincentersList:GraincentersList
        },true);
	    
        $('#alternateFilter a').click(paginateClick)
        $('#GraincentersRegion').change(anyFieldChange)
	    	    
        // Check for a page in the anchor
        url = document.location.toString()
        if (url.match('#'))
        {
            pageUrl = '' + url.split('#')[1]
            $.get(pageUrl, {}, function(data){
                GraincentersLoaded(data, true)
            }, 'json')
	
        }
        updateAutoComplete()
	    
        // jQuery chaining
        return this
    };
})(jQuery);