var proto = 'http';
var host = '';
var port = 80;
var path = '';

var check_avail_credits = function (data) {
	var have_credits = true;
	if(typeof data.code != 'undefined' && data.code==0) {
		var idx = 0;
		for (var i = 0; i < data.result.credits.length; i++) {
			if(data.result.credits[i].type=='check') {
				idx = i;
			}
		}
		
		if(typeof data.result.credits[0].available != 'undefined' && data.result.credits[idx].available>=10) {
			hide_message(function callback() {
				show_message('inform', youMayProceed.replace('%1$s',Math.floor(data.result.credits[idx].available/10)));
				undisable_form();
			});
		} else {
			hide_message(function callback() {
				show_message('error', noMoreCreditsForToday);
				disable_form();
			});
			have_credits = false;
		}
	} else {
		hide_message(function callback() {
			show_message('error', 'API refused to cooperate. Please try again later. (err '+data.code+')');
			reportError('API refused to cooperate. Please try again later. (err '+data.code+')');
			disable_form();
		});
		have_credits = false;
	}
	if(start_check_now==true && have_credits==true) {
		initCheck();
	}
};

var disable_form = function (){
	$('#maincolumn input', document).attr('disabled', 'disabled');
	$('#maincolumn input[type=submit]').addClass('formbtn-disabled');

};

var undisable_form = function (){
	$('#maincolumn input', document).attr('disabled', '');
	$('#maincolumn input[type=submit]').removeClass('formbtn-disabled');
};

var show_message = function (type, msg, callback) {
	$('tr#status_row').attr('class',type);	
	$('li#noteRowLi_0').html(msg);	
	$('tr#status_row').fadeIn(0, callback);	
};

var hide_message = function (callback) {
	$('tr#status_row').fadeOut(0, callback);	
};

var clearFirstTimeHostField = function () {
	if(clearTextbox) {
		$('input#vhost').val('http://');
		clearTextbox = 0;
	}
};

var report_error = function (errMessage) {
    var errMesage_encoded = encodeURIComponent(errMessage);
    var url = 'checkit.php?vajaxerror=1&verrormessage='+errMesage_encoded;
	jQuery.ajax({
           url: url,
           dataType: 'text',
           method: 'POST',
           timeout: 2000,
           success: function (data){
           }
      });
};

var form_validation = function () {
	
	// Check host value
	host = $('input#vhost').val();
	host = decodeURIComponent(host);
	if(host=='') {
		return false;
	}

	url_invalid_chars = /[\!|\#|\$|\%|\^|\*|\(|\)]/;
	var host_check_array=host.match(url_invalid_chars);

	if(host_check_array!=null) {
		return false;
	}
	
	var url_array = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((\[.*\])|([^:\/?#]*))(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(host);
	
	if(url_array[1]) proto = url_array[1]; else proto = "http";
	if(url_array[6]) host = url_array[6]; else host = "";
	if(url_array[9]) port = url_array[9]; else port = 80;
	if(url_array[10]) path = url_array[10]; else path = "";
	host = host.replace('[', '');
	host = host.replace(']', '');
	
	if(proto!='http' && proto!='https') {
		return false;
	}
	var host_invalid_chars = /[\!|\#|\$|\%|\^|\*|\(|\)|\@]/;
	var host_check_array2=host.match(host_invalid_chars);
	if(host_check_array2!=null) {
		return false;
	}
	if(host=='') {
		return false;
	}

	return true;
};

var start_check = function () {
	disable_form();
	hide_message(function callback() {
		show_message('inprogress', IN_PROGRESS);
	});
	for (var i = 0; i < CPList.length; i++)
		CPList[i].response = 0;
	
	proto = encodeURIComponent(proto);
	host = encodeURIComponent(host);
	path = encodeURIComponent(path);
	port = encodeURIComponent(port);
	
	for (var i = 0; i < CPList.length; i++)
	{
		$('span#status_'+CPList[i].loc).html(CHECKING);
		$('img#spinning_'+CPList[i].loc).attr('class','trans25');
		$('img#spinning_'+CPList[i].loc).attr('src','/assets/img/loading-greybg.gif');
		$('img#spinning_'+CPList[i].loc).show();
		var call_url = 'checkloc='+CPList[i].loc+'&type='+proto+'&host='+host+'&path='+path+'&port='+port;
		WMjsonp('cp_check.php', call_url, 'update_'+CPList[i].loc);
	}
	toutCheck = setTimeout('timeoutCheck()',20000);
};

var updateCPView = function(response, cp) {
	var cpName = cp;
	for (var i = 0; i < CPList.length; i++) 
		if(CPList[i].loc == cpName)
			CPList[i].response = 1;
	if(response.code == 0)
	{
		setNumbers(cpName, response.result.rtime ? response.result.rtime : 0
				, response.result.ctime ? response.result.ctime : 0
				, response.result.dtime ? response.result.dtime : 0
				, response.result.dsize ? response.result.dsize : 0
				, response.result.ip ? response.result.ip : ''
				, response.result.message ? response.result.message : '');
		setGraphBars(cpName, response.result.rtime ? response.result.rtime : 0
					,response.result.ctime ? response.result.ctime : 0
					,response.result.dtime ? response.result.dtime : 0);
		
		$('img#spinning_'+cpName).attr('class','trans95');
		$('span#status_'+cpName).html(response.result.message ? response.result.message : '');
		if(response.result.status == 0) {
			$('img#spinning_'+cpName).attr('src','/assets/img/icon-tick.gif');
		} else {
			$('img#spinning_'+cpName).attr('src', '/assets/img/icon-cross.gif');
		}
	}
	else
	{
		setNumbers(cpName, '0', '0', '0', '0', '', '0');
		setGraphBars(cpName,'0','0','0');
		$('img#spinning_'+cpName).attr('src', '/assets/img/icon-cross.gif');
		$('img#spinning_'+cpName).attr('class','trans95');
		$('span#status_'+cpName).html(response.error);
		hide_message(function callback() {
			show_message('error', response.info);
		});
		report_error('API Error: '+response.info+'(no. '+response.code+')');
	}
	
	var AllCPsFlag = true;
	for (var i = 0; i < CPList.length; i++)
		if(CPList[i].response == 0)
			AllCPsFlag = false;
	
	if(AllCPsFlag)
	{
		hide_message(function callback() {
			show_message('inform', ALL_DONE);
		});
		checkState = false;
		$('input#check_button').attr('value',checkButtonCheck);
		$('div#period_1').fadeIn(400);
		$('div#period_2').fadeIn(400);
		$('input#check_button').attr('disabled','');
		$('input#check_button').attr('class','formbtn-dark');
		clearTimeout(toutCheck);
		undisable_form();
	}
};

var timeoutCheck = function() {
	for (var i = 0; i < CPList.length; i++)
	{
		if(CPList[i].response==0)
		{
			cpName = CPList[i].loc;
			setNumbers(cpName, '0', '0', '0', '0', '', '0');
			setGraphBars(cpName,'0','0','0');
			$('img#spinning_'+cpName).attr('src','/assets/img/icon-cross.gif');
			$('img#spinning_'+cpName).attr('class','trans95');
			$('span#status_'+cpName).html(TIMEDOUT);
		}
	}
	hide_message(function callback() {
		show_message('warning', CHECK_NOT_IN_TIME);
	});
	checkState = false;
	$('input#check_button').attr('disabled','');
	$('input#check_button').attr('class','formbtn-dark');
	undisable_form();
};

var setNumbers = function(cpName, rtime, ctime, dtime, dsize, ip, message) {
	$('span#rtime_'+cpName).html(rtime);
	$('span#ctime_'+cpName).html(ctime);
	$('span#dtime_'+cpName).html(dtime);
	$('span#dsize_'+cpName).html(dsize);
	$('span#ip_'+cpName).html(ip);
	$('span#status_'+cpName).html(message);
};

var setGraphBars = function (cpName, rtime,ctime,dtime) {
	var multipl = 400/Math.log(5000);
	if(rtime != 0)
		var bar_rtime_width = Math.ceil(Math.log(rtime) * multipl);
	else
		var bar_rtime_width = 0;

	if(ctime != 0)
		var bar_ctime_width = Math.ceil(Math.log(ctime) * multipl);
	else
		var bar_ctime_width = 0;
			
	if(dtime != 0)
		var bar_dtime_width = Math.ceil(Math.log(dtime) * multipl);
	else
		var bar_dtime_width = 0;


	$('img#bar_rtime_'+cpName).animate({ 
    		width: bar_rtime_width+'px'   	
		}, 400);
	$('img#bar_ctime_'+cpName).animate({ 
    		width: bar_ctime_width+'px'    	
		}, 400);
	$('img#bar_dtime_'+cpName).animate({ 
    		width: bar_dtime_width+'px'    	
		}, 400);
		
	$('img#bar_rtime_'+cpName).attr('title',rtime+' ms');
	$('img#bar_ctime_'+cpName).attr('title',ctime+' ms');
	$('img#bar_dtime_'+cpName).attr('title',dtime+' ms');
	
};

function reportError(errMessage) {
    var errMesage_encoded = encodeURIComponent(errMessage);
    var url = 'checkit.php?vajaxerror=1&verrormessage='+errMesage_encoded;
	jQuery.ajax({
           url: url,
           dataType: 'text',
           method: 'POST',
           timeout: 2000,
           success: function (data){
           }
      });
}

var init_credit_check = function () {
	disable_form();
	WMjsonp("acct_credits.php","", "initCheck");
};


var initCheck = function (data) {
	
	if(data) {
		if(typeof data.code != 'undefined' && data.code==0) {
			var idx = 0;
			for (var i = 0; i < data.result.credits.length; i++) {
				if(data.result.credits[i].type=='check') {
					idx = i;
				}
			}
		}
		if(typeof data.result.credits[0].available != 'undefined' && data.result.credits[idx].available>=10) {
	
		} else {
			hide_message(function callback() {
				show_message('error', noMoreCreditsForToday);
				disable_form();
			});
			return false;
		}
	}
	
	if(form_validation()) {
		start_check();
		return true;
	} else {
		hide_message(function callback() {
			show_message('error', PROVIDE_VALID_ADDRESS);
		});
		undisable_form();
		reportError('Form validation error. URL:'+$('input#vhost').val());
		return false;
	}
};