$.fn.isOrderRefresh = function(){
	var self = this;
	var url = self.attr('href');
	var data = $.parseJSON(self.attr('data'));
	if (!url) {
		return;
	}
	if (!data) {
		data = {
			'delay': 10
		}
	}
	function refresh () {
		function callback(response) {
			var newCount = 
				document.title.replace(/^\(([^)]*[0-9])\)\s+.*$/gi,"$1");
			if (newCount == document.title) {
				newCount = 0;
			}
			for (var i = 0; i < response.length; i++) {
				var order = response[i];
				var orderBubble = $("#order_" + order.id);
				if (orderBubble.find(".order_progress").size() == 0) {
					continue;
				}
				if (orderBubble.size() > 0) {
					for (var j = 0; j < order.progress.length; j++) {
						var progress = order.progress[j];
						if ($('#order_progress_' + progress.id).size() > 0) {
							continue;
						}
						var li = $($('#order_progress_prototype').html());
						li.attr('id', 'order_progress_' + progress.id);
						li.addClass('new');
						li.find('.time span').html(progress.timestamp);
						li.find('.activity').html(progress.activity);
						li.appendTo($("#order_" + order.id 
							+ " .order_progress"));
						newCount++;
						//action changed after status changed
						if (progress.type == 1) {
							orderBubble.find('.order_actions').attr('class', 'order_actions new_order');
						}
						if (progress.type == 2) {//通过了验证，隐藏验证码输入mobile_verify_
							orderBubble.find('#mobile_verify_'+order.id).hide();
							orderBubble.find('.order_actions').attr('class', 'order_actions order_confirm');
						}
						if (progress.type == 5) {
							orderBubble.find('.order_actions').attr('class', 'order_actions on_the_way');
						}
						if (progress.type == 9 || progress.type == 10 || progress.type == 11) {
							orderBubble.find('.order_actions').attr('class', 'order_actions killed_by_admin');
							li.addClass('killed_by_admin');
						}
						if (progress.type == 12) {
							orderBubble.find('.order_actions').attr('class', 'order_actions new_order');
					 		$('.flash_notification').remove();
						}
					}
				}
				if (orderBubble.find(' li.new').size() > 0) {
					orderBubble.find('.progress_section').isProgressBoxWithNewItems();
				}
			}
			document.title = (newCount?"("+newCount+") ":"")
				+ document.title.replace(/\([^)]*[0-9]\)\s+/gi,"");
			setTimeout(refresh, data['delay'] * 1000);
		}
		$.get(url, {ajax:1}, callback, 'json');
	}
	refresh();
};

$.fn.isProgressBoxWithNewItems = function() {
	var self = this;
	function clearNew() {
		self.find('li.new').removeClass('new');
		self.removeClass('has_new');
		document.title = document.title.replace(/\([^)]*[0-9]\)\s+/gi,"");
	}
	self.addClass('has_new');
	$('body').one('mouseover', clearNew);
};

$(function(){
	$('#refresh_link').isOrderRefresh();
});
