function formatDate(date, fmt) {
	function pad(value) {
		return (value.toString().length < 2) ? '0' + value : value;
	}
	return fmt.replace(/%([a-zA-Z])/g, function (_, fmtCode) {
		switch (fmtCode) {
			case 'Y': return date.getUTCFullYear();
			case 'M': return pad(date.getUTCMonth() + 1);
			case 'd': return pad(date.getUTCDate());
			case 'H': return pad(date.getUTCHours());
			case 'm': return pad(date.getUTCMinutes());
			case 's': return pad(date.getUTCSeconds());
			default: throw new Error('Unsupported format code: ' + fmtCode);
		}
	});
};
function populateOptions(json, select) {
	$.each(json, function (index, item) {
		if (!item.attributes["suppress"]) {
			if (!item.attributes["disabled"]) {
				if (item.attributes["selected"]) {
					$(select).append($('<option selected="selected"></option>').val(item.code).html(item.description));
				} else {
					$(select).append($('<option></option>').val(item.code).html(item.description));
				}
			} else {
				$(select).append($('<option disabled="disabled"></option>').val(item.code).html(item.description));
			}
		}
	});
}
function checkLength(o, n, min, max) {
	if (o.val().length > max || o.val().length < min) {
		o.addClass("ui-state-error");
		updateTips($.sprintf(resourceStrings.ERR_CHKLENGTH, n, min, max));
		return false;
	} else {
		return true;
	}
};
function updateTips(t) {
	$(".validateTips")
				.text(t)
				.addClass("ui-state-highlight");
	setTimeout(function () {
		$(".validateTips").removeClass("ui-state-highlight", 1500);
	}, 500);
};

function queryPeriod( month, year){
    return (month < 10 ? "0" + month.toString() : month.toString()) + "/" + year;  
}

function ltrim(s, q){
	var l=0;
	while(l < s.length && s[l] == q)
	{	l++; }
	return s.substring(l, s.length);
}

function queryPeriodExtract( flag, period){
    return ltrim(period.split("/")[(flag == "m" ? 0 : 1)], "0");
}

var paper;

var title, yaxis, xaxis, comment, NorfolkPopn, NorfolkTotal, NorfolkRate, NorfolkRateStr, HEScode, surgeryList, PoissonPracticeSize, PoissonExpectedRate, PoissonLimitsLo2s, PoissonLimitsHi2s, PoissonLimitsLo3s, PoissonLimitsHi3s, ourSurgeries;

var syncService = new rpc.ServiceProxy("server.php", {
	asynchronous: false,
	protocol: "JSON-RPC",
	sanitize: true,
	methods: ['defaultSvg', 'OutPatient']
});

var webService = new rpc.ServiceProxy("server.php", {
	asynchronous: true,
	protocol: "JSON-RPC",
	sanitize: true,
	methods: ['susQueries', 'hesCodes', 'referralSources', 'attendanceCodes', 'outpatientToken', 'OutPatient']
});

webService.outpatientToken({
	params: [{ "timeStamp": formatDate(new Date(Date.now()), '%Y-%M-%d %H:%m:%s')}],
	onSuccess: function (json) {
		$("#execFQP").val(json.execFQP);
		$("#dbFQP").val(json.dbFQP);
		$("#overrides").val(json.overrides);
		$("#sindex").val(json.parms["sindex"]);
		$("#sdate").val(json.parms["sdate"]);
		$("#edate").val(json.parms["edate"]);
		$("#hescodes").val(json.parms["hescodes"]);
		$("#source").val(json.parms["source"]);
		$("#attendance").val(json.parms["attendance"]);
        $("#txtSMonth").val(queryPeriodExtract("m", $("#sdate").val()));
        $("#txtEMonth").val(queryPeriodExtract("m", $("#edate").val()));
        $("#txtSYear").val(queryPeriodExtract("y", $("#sdate").val()));
        $("#txtEYear").val(queryPeriodExtract("y", $("#edate").val()));
        
	},
	onException: function (errorObj) {
		alert("Unable to get token because: " + errorObj);
	}
});

$("#txtType").ready( function (event) {
	webService.susQueries({
		params: [{ "timeStamp": formatDate(new Date(Date.now()), '%Y-%M-%d %H:%m:%s')}],
		onSuccess: function (json) {
			populateOptions(json, "#txtType");
		},
		onException: function (errorObj) {
			alert("Unable to add options because: " + errorObj);
		},
		onComplete: function (responseObj) {
			$("#sindex").val($("#txtType :selected").val());
		}
	});
});            
$("#txtType").change( function (event) {
	$("#sindex").val(this.value);
});

$("#txtSource").ready( function (event) {
	webService.referralSources({
		params: [{ "timeStamp": formatDate(new Date(Date.now()), '%Y-%M-%d %H:%m:%s')}],
		onSuccess: function (json) {
			populateOptions(json, "#txtSource");
		},
		onException: function (errorObj) {
			alert("Unable to add options because: " + errorObj);
		},
		onComplete: function (responseObj) {
			$("#source").val($("#txtSource :selected").val());
		}
	});
});            
$("#txtSource").change( function (event) {
	$("#source").val(this.value);
});

$("#txtAttendance").ready( function (event) {
	webService.attendanceCodes({
		params: [{ "timeStamp": formatDate(new Date(Date.now()), '%Y-%M-%d %H:%m:%s')}],
		onSuccess: function (json) {
			populateOptions(json, "#txtAttendance");
		},
		onException: function (errorObj) {
			alert("Unable to add options because: " + errorObj);
		},
		onComplete: function (responseObj) {
			$("#attendance").val($("#txtAttendance :selected").val());
		}
	});
});            
$("#txtAttendance").change( function (event) {
	$("#attendance").val(this.value);
});

$("#txtHesCode").ready( function (event) {
    webService.hesCodes({
        params: [{ "timeStamp": formatDate(new Date(Date.now()), '%Y-%M-%d %H:%m:%s')}],
        onSuccess: function (json) {
            populateOptions(json, "#txtHesCode");
        },
        onException: function (errorObj) {
            alert("Unable to add options because: " + errorObj);
        },
        onComplete: function (responseObj) {
            $("#hescodes").val($("#txtHesCode :selected").val());
        }
    });            
});            
$("#txtHesCode").change( function (event) {
	$("#hescodes").val(this.value);
});


$(document).ready(function () {
    $('#loading').show();

	$.each($(".resText"), function (index, item) {
		item.innerHTML = eval("resourceStrings." + item.id);
	});
	$.each($(".tip"), function (index, item) {
		item.title = eval("resourceStrings." + item.id);
	});

    $("#txtSMonth").spinbox({ min: 1, max: 12, step: 1 });
    $("#txtSMonth").change( function(event){
        $("#sdate").val(queryPeriod($("#txtSMonth").val(), $("#txtSYear").val()));
    });
    
	$("#txtSYear").spinbox({ min: 2006, max: 2011, step: 1 });
    $("#txtSYear").change( function(event){
        $("#sdate").val(queryPeriod($("#txtSMonth").val(), $("#txtSYear").val()));
    });
    
	$("#txtEMonth").spinbox({ min: 1, max: 12, step: 1 });
    $("#txtEMonth").change( function(event){
        $("#edate").val(queryPeriod($("#txtEMonth").val(), $("#txtEYear").val()));
    });
    
	$("#txtEYear").spinbox({ min: 2006, max: 2011, step: 1 });
    $("#txtEYear").change( function(event){
        $("#edate").val(queryPeriod($("#txtEMonth").val(), $("#txtEYear").val()));
    });

	var paper = Raphael("svgSus", $("#svgSus").width(), $("#svgSus").height(), {
		type: "rect",
		x: 0,
		y: 0,
		width: $("#svgSus").width(),
		height: $("#svgSus").height(),
		stroke: "#000"
	}).initZoom();

    $( "#slider-range-max" ).slider({
        range: "max",
        min: 20,
        max: 800,
        value: 80,
        slide: function( event, ui ) {
            $("#amount").val($.sprintf(resourceStrings.lblZoom, ui.value));
            paper.setZoom(ui.value/100);
        }
    }).hide();
    $( "#amount" ).val($.sprintf(resourceStrings.lblZoom, $("#slider-range-max").slider("value"))).hide();

    paper.setZoom(0.8);
    
	var initText = paper.text($("#svgSus").width()/2, $("#svgSus").width()/3, "SVG Placeholder");
    
    $("#btnExec").click(function () {
        $('#loading').show();
		var toExec = $.sprintf(
                                "%s -i %s %s -q %s --start %s --end %s --source %s --attendance %s -s %s",
                                $("#execFQP").val(),
                                $("#dbFQP").val(),
                                $("#overrides").val(),
                                $("#txtType :selected").val(),
                                $("#sdate").val(),
                                $("#edate").val(),
                                $("#txtSource :selected").val(),
                                $("#txtAttendance :selected").val(),
                                $("#txtHesCode :selected").val()
                                );
        var setVars = syncService.OutPatient({"timeStamp": formatDate(new Date(Date.now()),'%Y-%M-%d %H:%m:%s'), "fqExec": toExec}).replace("var", "");
        eval(setVars);
        paper.clear();
        svgInit(paper, title, yaxis, xaxis, comment, NorfolkPopn, NorfolkTotal, NorfolkRate, NorfolkRateStr, HEScode, surgeryList, PoissonPracticeSize, PoissonExpectedRate, PoissonLimitsLo2s, PoissonLimitsHi2s, PoissonLimitsLo3s, PoissonLimitsHi3s, ourSurgeries);
        $('#loading').hide();
        $().add($("#slider-range-max")).add($("#amount")).show();
        if(typeof console != 'undefined' && console != null) {
            console.debug("Executed: %s)\n", toExec);
        }
	});

    $('#loading').hide();

});

