/*
 * var autoRefresh = require('./autoRefresh.js');
 * autoRefresh.autoRefresh(searchResult);
 * searchResult is the function to search
 */

define(function(require,exports){
	var $ = require('jquery');
	require('dialog')($);
	exports.autoRefresh = initTimingRefreshing;
	
	
	var timeHtml = '<span style="vertical-align: middle;" >'+
		'<a href="#;" id="timer" class="bb"><div><span>'+i18n["Page.workOrder.timing"]+'</span></div></a>'+
		'<a href="#;" id="cancelTiming"  style="display: none" class="bb"><div><span></span></div></a>'+
		'<span id="timerSpan" style="display: none" >'+
			'<a href="#;" id="timerSet" class="bb"><div><span>'+i18n["Page.workOrder.timing.set"]+'</span></div></a>'+
			'<input type="text" id="time" style="width:40px;height:20px;margin-top:5px" value="10" /></span></span>';
	
	
	
	function initTimingRefreshing(searchFunc){
		var pos = $(".Btn");
		if(pos.length!=1){
			alert("init timing \n Cant not find the 'div' with class 'Btn' !");
			return;
		}
		pos.append(timeHtml);
		$("#timer").click(function(){
			$(this).hide();
			$("#timerSpan").show();
		});
		var interval1;
		var tick;
		$("#timerSet").click(function(){
			var time = $("#time").val();
			if(!(/^\d{1,}$/.test($("#time").val()))){
				$.msg.alert(i18n['Page.workOrder.timing.number.valid']);
				return;
			}
			var ms = Number(time)*60;
			var tickms = ms;
			interval1 = setInterval(searchFunc,ms*1000);
			var timingSpan = $("#cancelTiming").find("span");
			timingSpan.html(i18n['Page.workOrder.timing.cancel']+"("+(tickms)+")");
			tick = setInterval(function(){
				tickms = tickms-1;
				timingSpan.html(i18n['Page.workOrder.timing.cancel']+"("+(tickms)+")");
				if(tickms==1){
					tickms = ms+1;
				}
			}, 1000);
			$("#timer").hide();
			$("#timerSpan").hide();
			$("#cancelTiming").show();
		});
		$("#cancelTiming").click(function(){
			clearInterval(interval1);
			clearInterval(tick);
			$("#cancelTiming").hide();
			$("#timer").show();
		});
		
	}
});