function showHide(parent, target) {
	var el = document.getElementById(target);
	if (el.style.display == 'block') {
		el.style.display = 'none';
		parent.innerHTML = 'Click pentru adaugare/editare detalii';
	}
	else if (el.style.display == 'none') {
		el.style.display = 'block';
		parent.innerHTML = 'Ascunde adaugare/editare detalii';
	}
	return false;
}

function addLink(ref) {
	
	var parent = document.getElementById(ref);
	var count  = parent.getElementsByTagName('input').length;
	var container = document.createElement('div');
	var input = document.createElement('input');
	var a = document.createElement('a');
	
	if (count == 13)//10 +3
		return false;

	a.href = '';
	a.innerHTML = 'x';
	a.style.textDecoration = 'none';
	a.style.verticalAlign = 'baseline';
	a.style.marginLeft = '3px';
	a.onmouseover = function(){a.style.fontWeight = 'bold'};
	a.onmouseout = function(){a.style.fontWeight = 'normal'};

	a.onclick = function(){
			parent.removeChild(this.parentNode);
			return false;
	};
	
	input.type = 'text';
	input.value = '';
	input.style.margin = '10px 2px 0 0';

	parent.appendChild(container);
	container.appendChild(input);
	container.appendChild(a);

	return false;
}

function doSubmit(id, ref) {
	
	var container = document.getElementById(ref);
	var inputs = container.getElementsByTagName('input');
	var cat_sel = document.getElementsByTagName('select')[0];
	var anchor = inputs[0];
	var email = inputs[1];
	var partnership = inputs[2];
	var desc = container.getElementsByTagName('textarea')[0];
	var img = document.createElement('img');
	var switchOnOff = container.previousSibling.previousSibling;
	//var submit = container.nextSibling.nextSibling;
	//var status = switchOnOff.previousSibling.previousSibling;
	var submit = document.getElementById('edit_submit');
	var status =  document.getElementById('submit_status');
	var fieldsToDisplay = new Array(switchOnOff, container, submit);

	var ajaxObj = new sack();
	
	img.src = '/images/ajax-loader.gif';

	ajaxObj.requestFile = '/domain_edit.php';
	ajaxObj.method = 'POST';
	
	for(i=3; i<inputs.length; i++) {
		if (inputs[i].value !== '')
			ajaxObj.setVar('links['+i+']', inputs[i].value);
	}
	ajaxObj.setVar('desc', desc.value);
	ajaxObj.setVar('email', email.value);
	ajaxObj.setVar('id_cat', cat_sel.value);
	ajaxObj.setVar('anchor', anchor.value);
	if (partnership.checked)
		ajaxObj.setVar('partnership', partnership.value);
	ajaxObj.setVar('id', id);
	
	ajaxObj.onLoading = function() {
		submit.style.display = 'none';
		switchOnOff.style.display = 'none';
		container.style.display = 'none';

		status.innerHTML = '.';
		status.style.fontSize='15px';
		status.style.display = 'block';
		displayProgress(status);
	}


	ajaxObj.onCompletion = function() {
		//alert(ajaxObj.response);return;
		status.removeAttribute('style');
		if (ajaxObj.response === '1') {
				status.innerHTML = 'A fost trimis un email care contine un link de activare pentru schimbarile efectuate.<br />Perioada de valabilitate a link-ului este de 10 minute<br />Va multumim<br /><br />';
				setTimeout(function(){window.location.reload()},10000);
				return true;
		}
		else if (ajaxObj.response === '2') {
				status.innerHTML = 'Va rugam completati campurile \'Descriere\', \'Email\' apoi selectati o \'Categorie\'<br /><br />';
				setTimeout(function(){displayFields(fieldsToDisplay)},2000);
				return false;
		}
		else if (ajaxObj.response === '3') {
				status.innerHTML = 'Adresa de email incorecta.<br /><br />';
				setTimeout(function(){displayFields(fieldsToDisplay)},2000);
				return false;
		}
		else if (ajaxObj.response === '4') {
				status.innerHTML = 'Unul dintre linkurile introduse nu este formatat corect.<br /><br />';
				setTimeout(function(){displayFields(fieldsToDisplay)},2000);
				return false;
		}
		else if (ajaxObj.response === '0') {
			status.innerHTML = 'Cererea dvs nu a putut fi procesata in acest moment, va rugam reincercati in cateva minute.<br />Va multumim pentru intelegere<br /><br />';
			setTimeout(function(){window.location.reload()},10000);
		}
	}
	ajaxObj.runAJAX();
}

function displayProgress(container) {
	re = /^\./;
	if (! re.test(container.innerHTML))
		return;

	container.innerHTML += ' .';
	setTimeout(function(){displayProgress(container)}, 200);
}

function displayFields(obj) {
	for (i=0; i<obj.length; i++) {
		//alert(obj[i]);
		obj[i].style.display = 'block';
	}
}

function removeLink(node) {
	var parent = node.parentNode;
	var granParent = parent.parentNode;
	granParent.removeChild(parent);
	return false;
}

function loadimg(_id, loc, fileSize) {
	var img = new Image();
	var div_status = document.getElementById("speedtest_status");
	var div_output= document.getElementById("speedtest_output");
	var ajaxObject = new Array();

	img.onload = function() {
		end = (new Date()).getTime();
		diff = end - start;
		
		//alert('loaded. timediff: ' + (end - start) + ' ms');
		connectSpeed = (Math.floor((((fileSize * 8) / (diff / 1000)) / 1024) * 10) / 10);//kbs

		//set display timeout to at least 10s
		to = ( (diff  >= 10000) ? 0 : (10000-diff)) ;

		audio_size = 5 * 8 * 1024;//Kb
		video_size = 700 * 8 * 1024;//Kb
		audio_seconds = audio_size / connectSpeed;
		video_seconds = video_size / connectSpeed;

		//ajax: get avgspeeds
		ajaxObject[0] = new sack();
		ajaxObject[0].requestFile = '/runBwGetAvgSpeedData.php';
		ajaxObject[0].onCompletion = function() {
			var data = eval(ajaxObject[0].response);
			var p_name = data.provider;
			var c_name = data.country;
			var c_avgs = data.c_avgspeed;
			var p_avgs = data.p_avgspeed;
			
			//compute %
			var c_percentage = (connectSpeed * 100) / c_avgs;
			c_percentage -= 100;
			c_percentage = Math.floor(c_percentage * 10) / 10;
			var p_percentage = (connectSpeed * 100) / p_avgs;
			p_percentage -= 100;
			p_percentage = Math.floor(p_percentage * 10) / 10;
			
			//compute % output text
			if (c_percentage == c_avgs)
				c_percentage_text = 'egala cu';
			else if (c_percentage < 0)
				c_percentage_text = 'cu <c_percentage>% mai mica decat';
			else if(c_percentage > 0)
				c_percentage_text = 'cu <c_percentage>% mai mare decat';
			
			if (p_percentage == p_avgs)
				p_percentage_text = 'egala cu';
			else if (p_percentage < 0)
				p_percentage_text = 'cu <p_percentage>% mai mica decat';
			else if(p_percentage > 0)
				p_percentage_text = 'cu <p_percentage>% mai mare decat';
			
			//compute output colors based on %
			c_color = 'red';
			if ( c_percentage > 5 )
				c_color = 'green';
			else if (  (c_percentage >= -5) && (c_percentage <= 5) )
				c_color = 'blue';

			p_color = 'red';
			if ( p_percentage > 5 )
				p_color = 'green';
			else if (  (p_percentage >= -5) && (p_percentage <= 5) )
				p_color = 'blue';
			
			//build up output
			var line1 = '<b>Viteza ta: <u>' + connectSpeed + '</u> Kbps</b>' ;
			if (connectSpeed > 512)
				line1 += '<br /><b>Viteza ta de conectare la internet iti permite sa urmaresti <a href="http://www-online.tv/watch-tv-online/' + c_name + '">TV online</a>, click <a target="_blank" href="http://www-online.tv/watch-tv-online/' + c_name + '">aici</a> pentru un test.</b>';
			var line2 = '<span style="font-weight:bold; color:' + c_color + '">Viteza medie download pe ' + c_name + ' (Vezi <a target="_blank" href="http://www.download-speed.org/speed-test/' + escape(c_name) + '">Viteza ' + c_name + '</a>): <u>' + c_avgs + '</u> Kbps <br>(viteza ta este ' + c_percentage_text + ' viteza medie pe tara)</span>';
			var line3 = '<span style="font-weight:bold; color:' + p_color + '">Viteza medie a providerului este: <u>' + p_avgs + '</u> Kbps <br>(viteza ta este ' + p_percentage_text + ' viteza medie a providerului tau <u>(' + p_name + ')</u></span>';
			var line4 = '<b>Poti downloada, in mod teoretic, o melodie (5MB) in  <audio_seconds> secunde</b>';
			var line5 = '<b>sau un film (700MB) in <video_minutes> minute.<br><u>Pentru rezultate cat mai concludente te rugam sa refaci testul de mai multe ori.</u></b>';
		
			line2 = line2.replace(/<c_percentage>/, Math.abs(c_percentage));
			line3 = line3.replace(/<p_percentage>/, Math.abs(p_percentage));
			line4 = line4.replace(/<audio_seconds>/, Math.floor(audio_seconds * 10) / 10);
			line5 = line5.replace(/<video_minutes>/, Math.floor((video_seconds / 60) * 10) / 10);
			
			var output = '<br />' + line1 + '<br />' + line2 + '<br />' + line3 + '<br />' + line4 + '<br />' + line5 + '<br /><br />';
			
			//display output with timeout and update href with server id
			setTimeout(function(){
				updateSrv(_id);
				div_status.innerHTML = output; 
				div_status.removeAttribute('style');
				div_output.style.display = 'block'}, to);
		}
		ajaxObject[0].runAJAX();

		//ajax: update db
		ajaxObject[1] = new sack();
		ajaxObject[1].requestFile = '/runBwClientDbUpdate.php';
		ajaxObject[1].method = 'GET';
		ajaxObject[1].setVar('id', _id);
		ajaxObject[1].setVar('speed', connectSpeed);
		ajaxObject[1].onCompletion = function() {
			//alert(ajaxObject[1].response);
		}
		ajaxObject[1].runAJAX();
	}
	if (loc == '')
		div.innerHTML = 'Invalid server';
	else {
		start = (new Date()).getTime();
		div_output.style.display = 'none';
		div_status.style.fontSize='15px';
		div_status.style.display = 'block';
		displayProgress(div_status);
		img.src = loc + fileSize + '.gif?t=' + escape(start);
	}
}


function updateSrv(_id) {
	var a = document.getElementById('speedtest_start');
	var pattern = /([^0-9]+).*/;
	a.href = a.href.replace(pattern, "$1" + _id);
}
