function Place(Parent, Uri) {
    var pv;
    var place;

    var fillMergeChoices = function(uri) {
        $.getJSON('/api/'+uri, [],
                  function(data) {
                      $('div.mergechoices', pv).show()
                          .find('span.placeid').text(data.id).end()
                          .find('span.placename').text(data.name).end()
                          .find('span.website').text(data.website || 'unknown').end()
                          .find('span.thislocations').text(place.locations.length).end()
                          .find('span.otherlocations').text(data.locations.length).end()
                          .find('span.thisbeers').text(place.beers.length).end()
                          .find('span.otherbeers').text(data.beers.length).end()
                          .find('span.thiscomments').text(place.comments.length).end()
                          .find('span.othercomments').text(data.comments.length);
                  });
    };

    var merge = function() {
        var mdiv = $('div.mergechoices', pv);
        var props = {};
        var fields = mdiv.find('input[type=checkbox]');
        for (var i = fields.length-1; i >= 0; i--) {
            props[fields.eq(i).attr('name')] = !!fields.eq(i).attr('checked');
        }

        var postplace = place.id;

        if (props.placeid) {
            for (k in props) { props[k] = !props[k]; }

            var temp = props.thiscomments;
            props.thiscomments = !props.othercomments;
            props.othercomments = !temp;

            temp = props.thislocations;
            props.thislocations = !props.otherlocations;
            props.otherlocations = !temp;

            props.otherbeers = true;
            props.thisbeers = true;

            props.placeid = place.id;
            postplace = mdiv.find('span.placeid').text();
        } else {
            props.placeid = mdiv.find('span.placeid').text();
        }

        props.cmd = 'merge';

        $.ajax({url:'/api/place/'+postplace,
                type:'POST',
                data:props,
                success:function(newp) { window.location = '/place/'+newp.id; },
                dataType:'json'});
    };

    var mergeCancel = function() {
        $('.placemerge', pv).hide();
    };

    var showMerge = function() {
        $('.placemerge', pv).show();
    };

    var cancel = function() {
        $('.placeedit', pv).hide();
        return false;
    };

    var save = function() {
        var name = $('.placeedit .name', pv).val();
        if (name.length <= 0) { alert('Enter a new name for the place.'); return false; }

        var website = $('.placeedit .website', pv).val();

        var data = {cmd:'edit',
            name:name,
            website:website};

        var locations = $('.placeedit .location', pv);
        for (var i = locations.length-1; i >= 0; i--) {
            var val = $.trim(locations.eq(i).val());
            if (val.length > 0) data['l'+i] = val;
        }

        $.post('/api/place/'+place.id,
               data,
               function(place) { window.location = '/place/'+place.id; },
               'json');
        return false;
    };

    var edit = function() {
        $('.placeedit .name', pv).val(place.name);
        if (place.locations.length > 0) {
            var lines = $('.placeedit .location', pv);
            if (lines.length < place.locations.length) {
                var temp = lines.eq(0).parents('div.popupformline').eq(0);
                for (var i = (place.locations.length-lines.length)-1; i >= 0; i--) {
                    temp.clone().insertAfter(temp);
                }
                lines = $('.placeedit .location', pv);
            }
            for (var i = place.locations.length-1; i >= 0; i--)
                lines.eq(i).val(place.locations[i].location);
        } else {
            $('.placeedit .location', pv).val('');
        }
        if (place.website) {
            $('.placeedit .website', pv).val(place.website);
        } else {
            $('.placeedit .website', pv).val('');
        }

        $('.placeedit', pv).show();
        return false;
    };

    var showOtherLocations = function() {
        $('.placeloc .moreloc', pv).hide()
        $('.placeloc .otherloc', pv).show();
        return false;
    };

    var hideAddLocation = function(o) {
        $(o.target).parents('div.addlocform').hide().prev().show();
        return false;
    };

    var showAddLocation = function(o) {
        $(o.target).hide().next().show();
        return false;
    };

    var addLocation = function() {
        var loc = $.trim($('.placeloc input.location', pv).val());
        if (loc.length > 0) {
            $.post('/api/place/'+place.id,
                   {cmd:'addloc',
                    loc:loc},
                   function(newplace) {
                       place = newplace;
                       $('.placeloc .primaryloc').clone().removeClass('primaryloc').show()
                       .find('span').text(loc).end()
                       .find('a.mapit').attr('href', '/local?address='+encodeURIComponent(loc)).end()
                       .insertBefore('.placeloc .otherloc a.addloc');

                       $('.placeloc input.location', pv).val('');
                       $('.placeloc .addlocform').hide().prev().show();
                   },
                   'json');
        }
        return false;
    };

    var setSession = function() {
        if (GSession === null) { return; }

        if (GSession.id) {
            ReportForm(data_uri, $('div.report', pv));

            $('.placeloc', pv)
            .find('a.addloc').click(showAddLocation).show().end()
            .find('a.submit').attr('href', '/place/'+place.id)
            .click(addLocation).end()
            .find('a.cancel').click(hideAddLocation);
        }
        
        if (GSession.admin) {
            add_edit_button('/place/'+place.id, 'edit', edit);

            $('div.admin', pv).show()
                .find('.save').attr('href', '/place/'+place.id).click(save).end()
            .find('.cancel').attr('href', '#').click(cancel);

            add_edit_button('/place/'+place.id, 'merge', showMerge, 'merge');

            $('div.merge', pv).show()
            .find('.merge').attr('href', '/place/'+place.id).click(merge).end()
            .find('.cancel').attr('href', '#').click(mergeCancel).end()
            .find('.othername').autocomplete('/api/autocomplete/place',
                                             {dataType:'json',
                                              parse:function(data) {
                                                  var res = [];
                                                  for (var i = 0; i < data.results.length; i++) {
                                                      res[i] = {data:data.results[i],
                                                                value:data.results[i].title,
                                                                result:data.results[i].title};
                                                  }
                                                  return res;
                                              },
                                              formatItem: function(row) { return row.title; }
                                             })
            .result(function(ev, row) {
                fillMergeChoices(row.uri);
                return row.title;
            });
        }
    };

    var loadPlace = function(data) {
        place = data;
        $('.placename', pv).text(data.name);

        if (data.locations.length == 0) {
            $('.placeloc', pv).find('.primaryloc').hide().end()
            .find('.moreloc').hide().end()
            .find('.otherloc').show();
        } else {
            $('.placeloc', pv).find('.primaryloc')
            .find('span').text(data.locations[0].location).end()
            .find('a').attr('href', '/local?address='+encodeURIComponent(data.locations[0].location));
            
            if (data.locations.length > 1) {
                $('.placeloc', pv)
                .find('.moreloc').click(showOtherLocations).show()
                .find('span.count').text(data.locations.length-1).end().end()
                .find('.otherloc').hide();

                var temp = $('.placeloc .primaryloc', pv);
                var list = $('.placeloc .otherloc', pv);
                for (var i = data.locations.length-1; i >= 1; i--) {
                    temp.clone().removeClass('primaryloc')
                    .find('span').text(data.locations[i].location).end()
                    .find('a').attr('href', '/local?address='+encodeURIComponent(data.locations[i].location)).end()
                    .prependTo(list);
                }
            } else {
                $('.placeloc', pv).find('.moreloc').hide().end()
                .find('.otherloc').show();
            }
        }

        if (data.website) {
            $('.placeweb a', pv).attr('href', data.website).text(data.website);
        }
        else {
            $('.placeweb .webdata', pv).text('');
        }

        ViewTabber($('.placeitems', pv),
                   [{name:'beers',
                     label:'beers',
                     createView:function(viewdiv) {
                         var adderdiv = $('<div/>').appendTo(viewdiv);
                         var bt = BeerTable($('<div/>').appendTo(viewdiv),
                             [{fun:function() {
                                 if (GSession) {
                                     var scored = [];
                                     for (var i = data.beers.length-1; i >= 0; i--) {
                                         var score = find_score(data.beers[i]);
                                         if (score || score == 0)
                                             scored.push({'id':data.beers[i],
                                                          'score':score});
                                     }
                                     return map(function(b) { return b.id; },
                                                scored.sort(function(b1, b2) { return b2.score - b1.score; }));
                                 }
                                 return [];
                             },
                               uri:data_uri+'?sort=score',
                               label:'score'
                              },
                              {uri:data_uri+'?sort=atoz',
                               label:'name',
                               field:'beers',
                               current:true
                              },
                              {uri:data_uri+'?sort=adddate',
                               label:'add date',
                               field:'beers'
                              },
                              {uri:data_uri+'?sort=lastcomm',
                               label:'last comment',
                               field:'beers'
                              }]);
                         get_user('beeradder', function() { BeerAdder(adderdiv, data.id, bt); });
                     }},
                    {name:'comments',
                     label:'comments',
                     createView:function(viewdiv) {
                         CommentTable(viewdiv, data.comments);
                     }}]);

        get_session('place', setSession);
    };

    var loadTemplate = function(data) {
        pv = $(data).appendTo(Parent);
        $.getJSON(Uri, [], loadPlace);
    };

    $.get('/'+stv+'/html/place.html', [], loadTemplate);
};

function BeerAdder(Parent, PlaceId, Table) {
    var ba;

    var hide = function() {
        $('div.form', ba).hide();
        $('a.show', ba).show();
        return false;
    };

    var submit = function() {
        var id = $('input[name=beerid]', ba).val();
        
        if (id.length > 0) {
            $.post('/api/place/'+PlaceId,
                   {cmd:'add_beer', beer:id},
                   function(data) {
                       hide();
                       Table.loadSort(data_uri+'?sort=adddate', 'asc',
                                      0, data.beers);
                   },
                   'json');
        }
        return false;
    };

    var loadTemplate = function(data) {
        ba = $(data).appendTo(Parent);

        $('a.show', ba).click(
            function() { $('a.show', ba).hide();
                         $('div.form', ba).show();
                         $('input', ba).focus();
                         return false;});

        $('a.cancel', ba).click(hide);

        $('a.submit', ba).attr('href', '/place/'+PlaceId).click(submit);

        $('input[name=name]', ba).autocomplete(
            '/api/autocomplete/beer',
            {dataType:'json',
             parse:function(data) {
                 var res = [];
                 for (var i = 0; i < data.results.length; i++) {
                     res[i] = {data:data.results[i],
                               value:data.results[i].title,
                               result:data.results[i].title};
                 }
                 return res;
             },
             formatItem: function(row) {
                 return [row.title, "&nbsp;&ndash;&nbsp;",
                         row.brewery_name].join('');
             },
             mustMatch: true,
             selectFirst: true
            })
        .result(function(ev, row) {
            $('input[name=beerid]', ba).val(row.uri.substring(6));
            return row.title;
        });
    };

    $.get('/'+stv+'/html/beeradder.html', [], loadTemplate);
};

$(function() { Place($('#view'), data_uri); });

