;(function($) {
$.NetworkConnection = function (settings) {
$.NetworkConnection = new NetworkConnection(settings);
}
function NetworkConnection(settings) {
this.pingURL = "hello.txt";
this.pingTimeout = 2000;
this.pingInterval = this.pingTimeout + 100;
this.connectionStatus = null;
this.timeout = null;
this.lastTextStatus = null;
this.lastErrorThrown = null;
this.testCount = 0;
$.extend(this, settings);
this.isConnected = function () {
var self = this;
return (self.connectionStatus == 'connected') ? true : false;
}
this.run = function () {
var self = this;
self.doTest();
self.timeout = setInterval(function () {
self.doTest();
}, self.pingInterval)
}
this.doTest = function () {
var self = this;
var objTest = {
testNumber : self.testCount++,
startTime : (new Date()).getTime()
};
self.beforetest && self.beforetest(objTest);
$.ajax({
url : self.pingURL,
type : 'GET',
timeout : self.pingTimeout,
dataType : 'text',
cache : false,
success : function (data, textStatus) {
objTest.endTime = (new Date()).getTime();
objTest.rtt = objTest.endTime - objTest.startTime;
objTest.textStatus = textStatus;
self.lastTextStatus = textStatus
self.lastErrorThrown = null;
self.connectionStatus != 'connected' && self.gainedConnection && self.gainedConnection();
self.connectionStatus = objTest.connectionStatus = 'connected';
self.success && self.success(objTest);
self.complete && self.complete(objTest);
},
error : function (XMLHttpRequest, textStatus, errorThrown) {
objTest.endTime = (new Date()).getTime();
objTest.rtt = objTest.endTime - objTest.startTime;
objTest.textStatus = textStatus;
objTest.errorThrown = errorThrown;
self.lastTextStatus = textStatus
self.lastErrorThrown = errorThrown;
self.connectionStatus != 'disconnected' && self.lostConnection && self.lostConnection();
self.connectionStatus = objTest.connectionStatus = 'disconnected';
self.fail && self.fail(objTest);
self.complete && self.complete(objTest);
}
})
}
this.run();
}
})(jQuery);