var _rc_ = {};
$('#memo_icon').remove();
$('<a>').attr('id', '_rc_claim').addClass('town_control').css({left: '322px', backgroundPosition: "-323px 9px"}).text('+').on('click', _rc_start).insertBefore($('#city_overview'));

function _rc_start () {
    if (webkitNotifications && webkitNotifications.checkPermission() != 0) {
        webkitNotifications.requestPermission();
    }

    if(!_rc_.hasOwnProperty(Game.townId)) {
        $('#_rc_claim').text('-').off('click', _rc_start).on('click', _rc_stop);
        var farms = $('.farmtown_owned_on_same_island a').map(function () { return JSON.parse(atob($(this).attr('href')).split(String.fromCharCode(0))[0]).id;});
        _rc_[Game.townId] = farms;
        console && console.log('Starting for town', Game.townId, 'with farms', farms);
        farms.each(function (i, e) {
            $('#farm_town_flag_' + e).css({backgroundColor: 'orangered'});
        });
        _rc_claim(Game.townId, farms.get());
    }
}
function _rc_stop () {
    if(_rc_.hasOwnProperty(Game.townId)) {
        $('#_rc_claim').text('+').off('click', _rc_stop).on('click', _rc_start);
        _rc_[Game.townId].each(function (i, e) {
            $('#farm_town_flag_' + e).css({backgroundColor: 'purple'});
        });
        delete _rc_[Game.townId];
    }
}

function _rc_claim(town_id, farms_queue) {
    var farm = farms_queue.shift();
    $('#farm_town_flag_' + farm).css({backgroundColor: 'black'});
    $.ajax({
        url: location.origin + '/game/farm_town_info?action=claim_load&town_id=' + town_id + '&h=' + Game.csrfToken,
        type: 'POST',
        data: {
            json: '{"target_id":"' + farm + '","claim_type":"normal","time":300,"town_id":' + town_id + ',"nlreq_id":0}'
        }
    }).done(function () {
        $('#farm_town_flag_' + farm).css({backgroundColor: 'blue'});
        if (farms_queue.length > 0) {
            setTimeout(function() {
                _rc_claim(town_id, farms_queue);
            }, parseInt(1000 * 10 * Math.random()));
        } else {
            var delay = 1000 * 60 * 5.2 + parseInt(1000 * 13 * Math.random()),
                next =  new Date((new Date().getTime() + delay)).toLocaleTimeString();
            console && console.log('Next: ' + next);
            setTimeout(function() {
                if(_rc_.hasOwnProperty(Game.townId)) {
                    _rc_claim(town_id, _rc_[town_id].get());
                } else {
                    console && console.log('Aborted');
                }
            }, delay);
        }
    }).fail(function () {
        $('#farm_town_flag_' + farm).css({backgroundColor: 'pink'});
    });
}

// Auto jump
$('#prev_city, #next_city').on('click', function (e) {
    setTimeout(function () {
        if (!e.shiftKey) {
            WMap.mapJump({'id': +Game.townId,'ix': WMap.islandPosition.x,'iy': WMap.islandPosition.y}, true);
        }
        if(_rc_.hasOwnProperty(Game.townId)) {
            $('#_rc_claim').text('-').off('click', _rc_start).on('click', _rc_stop);
        } else {
            $('#_rc_claim').text('+').off('click', _rc_stop).on('click', _rc_start);
        }
    }, 50);
});

// Desktop notification
var notif_label = {
    alliance_invitation: 'Alliance Invitation',
    all_building_finished: 'All Buildings Finished',
    awmessage: 'Message',
    backbone: 'Backbone',
    building_finished: 'Building Finished',
    incoming_attack: 'Incoming Attack!',
    incoming_support: 'Incoming Support',
    mass_notification: 'Mass Notification',
    newalliancepost: 'New Alliance Post',
    newaward: 'New Award',
    newmessage: 'New Message',
    newreport: 'New Report',
    newtempreport: 'New Temp Report',
    notassigned: 'Not Assigned',
    phoenician_salesman_arrived: 'Phoenician Salesman Arrived',
    planed_attack: 'Planed Attack',
    resourcetransport: 'Resource Transport',
    show_captcha: 'Show Captcha',
    systemmessage: 'System Message'
};

var old_notif = NotificationLoader.recvNotifyData;
NotificationLoader.recvNotifyData = function (retdata, game_initialization) {
    try {
        if (!game_initialization) {
            if (webkitNotifications && webkitNotifications.checkPermission() == 0) {
                if (retdata.notifications.length) {
                    for (var i = 0; i < retdata.notifications.length; i++) {
                        var notif = retdata.notifications[i],
                            title = notif_label[notif.type],
                            message = '';
                        if(notif.subject) {
                            message = $('<i>' + notif.subject +'</i>').text();
                        } else if (notif.type == 'building_finished') {
                            try {
                                var param = JSON.parse(notif.param_str);
                                message = param.building_name + ' at level ' + param.new_level + ' on ' + param.town_name;
                            } catch(e) {
                                message = 'Error in param_string';
                            }
                        }
                        if(notif.type != 'systemmessage') {
                            var popup = webkitNotifications.createNotification('http://cdn.grepolis.com/images/game/start/favicon.ico', 'Grepolis - ' + title, message);
                            popup.show();
                            console && console.log(notif.type, ' -> ', notif.subject, __ = $.extend({}, notif));
                            function cancel(pop) {
                                setTimeout(function(){
                                    console && console.log('Cancelling', pop);
                                    pop.cancel();
                                }, 15000);
                            }
                            cancel(popup);
                        }
                    }
                }
            }
        }
    } catch(e) {}
    old_notif(retdata, game_initialization);
};