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)));
				enable_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 enable_form = function (){
	$('#maincolumn input', document).attr('disabled', '');
	$('#maincolumn input[type=submit]').removeClass('formbtn-disabled');
	$('input#vhost').blur();
};

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_breakdown = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((\[.*\])|([^:\/?#]*))(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(host);
	
	if(host.indexOf('[')>-1)
	{
		// is a proper ipv6 url
		var improper_ipv6_url_check = null;
	}
	else
	{
		// not a proper ipv6 url
		var improper_ipv6_url_check = /([^:\/?#.]+)\:\/\/(.+?)(\/.*)?$/.exec(host);
	}	
	
	var ipv4_check_match = /(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|255[0-5])\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])/.exec(host);
	
	if(improper_ipv6_url_check!=null && improper_ipv6_url_check[2] && improper_ipv6_url_check[2].match(/\:/g) && improper_ipv6_url_check[2].match(/\:/g).length>1)
	{
		// improper url with ipv6 provided
		proto = improper_ipv6_url_check[1];
		host = improper_ipv6_url_check[2];
		if(improper_ipv6_url_check[3])
			path = improper_ipv6_url_check[3];
		else
			path = '';
		port = 80;
	}
	else if(url_breakdown[1] == 'http' || url_breakdown[1] == 'https')
	{
		// proper url provided
		proto = url_breakdown[1];
		host = url_breakdown[6];
		host = host.replace('[', '');
		host = host.replace(']', '');
		if(url_breakdown[9])
		{
			port = url_breakdown[9];
		}
		else
		{
			if(proto=='http')
				port = 80;
			else if(proto=='https')
				port = 443;
		}
		path = url_breakdown[10];
	}
	else if(ipv4_check_match!=null)
	{
		// just an ip provided
		proto = "http";
		port = 80;
		// ip already given	
	}
		
	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;
		if(port!=80) call_url += '&port='+port;
		jsonp(CHECKAPIURL, 'cp_check', call_url, 'update_'+CPList[i].loc);
	}
	toutCheck = setTimeout('timeoutCheck()',20000);
};

var jsonp = function (base, url, params, callback) {
	  var script = this.document.createElement("script");
	  if(LOGGEDIN) {
		  params = "call="+url+"&"+params
		  url = '';
	  }
	  url += "?"+params;
	  url += (url.indexOf('?') > -1)? '&': '?';
	  url += "callback="+callback+"&_="+Math.floor(Math.random()*999999);
	  url = base+url;
	  script.setAttribute("src", url);
	  script.setAttribute("type", "text/javascript");
	  try{
		  this.document.body.appendChild(script);
	  } catch(err) {
		  console.log('error json call');
	  }
	  
};

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);
		enable_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');
	enable_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();
	jsonp(CHECKAPIURL, "acct_credits", "", "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);
		});
		enable_form();
		reportError('Form validation error. URL:'+$('input#vhost').val());
		return false;
	}
};
