(function ($) {
$.fn.liveChannel = function(opts) {
    var self = $(this);

    var eventStack = [];
    var lastUpdate = 0;
    var hndlr = true;

    var t0 = 0;
    var t1 = 0;

    var options = $.extend({
        lastEventId : 0,
        cityId : 0,
        channel : 0,
        updateInterval : 10000,
        renderInterval : 5000,
        parentSelector : '.feeds',
        auto : false
    }, opts);

    setInterval(updateEvents, options.updateInterval);
    setInterval(renderEvent, options.renderInterval);
    if(options.auto) {
    	updateEvents();
    }

    function updateEvents() {
        if(eventStack.length > 2) {
            return false;
        }
        lastUpdate = new Date().getTime();
        $.ajax({
            url: PUBLIC_URL + 'ajax-feeds/live-channel-events',
            type: 'POST',
            dataType: 'json',
            data: {channel : options.channel, cityId: options.cityId , fromId: options.lastEventId },
            beforeSend: function() {
                hndlr = false;
            },
            success: function(jSon) {
                if(jSon.result == 'success') {                    
                    if( jSon.lastEventId > 0 ) {
                        options.lastEventId = jSon.lastEventId;
                    }
                    var newEvents = parseInt(jSon.newEvents);
                    if(newEvents > 0) {
                        $.each(jSon.stack, function(idx,item) {
                            eventStack.push(item);
                        });
                        if(options.auto) {
                        	renderEvent();
                        }
                    }
                }
            },
            complete: function() {
                hndlr = true;
            }
        });
    }

    function renderEvent() {
        var updated = new Date().getTime() - lastUpdate;
        if( eventStack.length < 2 && updated > options.updateInterval && hndlr) {
            updateEvents();
        }
        var v = eventStack.pop();
        if(!v || v=='undefined' || ($('#'+v.id).length > 0)) {
            return false;
        }
        $(options.parentSelector).prepend(v.html);
        $('#'+v.id).fadeIn();
        $('#'+v.id).channelFeedItem();
        $(options.parentSelector).children(':gt(50)').remove();
    }
    return $(this);
}})(jQuery);

(function ($) {
	$.saveCitySettings = function() {
		if($('#cityId').val() > 0) {
			var date = new Date();
			date.setTime(date.getTime()+365*24*60*60*1000);
			var expires = "; expires="+date.toGMTString();
			document.cookie = "_city="+escape($('#cityId').val())+expires+"; path=/; domain=."+DOMAIN_NAME;
		}

		$('#citySettingsBox').hide();
		window.location = PUBLIC_URL;
	};
})(jQuery);