//global variables that can be used by ALL the function son this page.
var inputs;
var imgFalse = '../images/false.png';
var imgTrue = '../images/true.png';

//this function runs when the page is loaded, put all your other onload stuff in here too.
function init() {
	replaceChecks();
}

function replaceChecks() {
	
	//get all the input fields on the page
	inputs = document.getElementsByTagName('input');

	//cycle trough the input fields
	for(var i=0; i < inputs.length; i++) {

		//check if the input is a checkbox
		if(inputs[i].getAttribute('type') == 'checkbox') {
			//create a new image
			var img = document.createElement('img');
			
			//check if the checkbox is checked
			if(inputs[i].checked) {
				img.src = imgTrue;
			} else {
				img.src = imgFalse;
			}
			img.style.cursor = "pointer";
			
			var inputVal = inputs[i].value;
			
			//set image ID and onclick action
			img.id = "checkImage"+i;
			//set image 
			img.onclick = new Function('checkChange('+i+')');
			//place image in front of the checkbox
			inputs[i].parentNode.insertBefore(img, inputs[i]);
			
			//hide the checkbox
			inputs[i].style.display='none';
		}
	}
}

//change the checkbox status and the replacement image
function checkChange(i) {
	if(inputs[i].checked) {
		inputs[i].checked = false;
		document.getElementById('checkImage'+i).src=imgFalse;
	} else {
		inputs[i].checked = true;
		document.getElementById('checkImage'+i).src=imgTrue;
	}
}

// val true -> checkAll
// val false -> uncheckAll
function checkUncheckAll(val,table){

	var refString;
	var form;
	if(table == 'torrents'){
		refString = 'Check all torrents';
		form = document.torrents_form;
	}
	else if(table == 'softsubs'){
		refString = 'Check all softsubs';
		form = document.softsub_form;
	}
	else if(table == 'ed2k'){
		refString = 'Check all ed2k links';
		form = document.ed2k_form;
	}
	
	//get all the input fields on the page
	inputs = form.elements;

	//cycle trough the input fields
	for (var i = 0; i < inputs.length; i++) {
	
		//check if the input is a checkbox
		if (inputs[i].getAttribute('type') == 'checkbox') {
		
			//create a new image
			var img = document.createElement('img');
			//check if checkAll or uncheckAll
			if(val) {
				inputs[i].checked = 'checked';
				inputs[i].src=imgTrue;
				document.getElementById("checkImage"+i).src=imgTrue;
			} else {
				inputs[i].checked = '';
				inputs[i].src=imgFalse;
				document.getElementById("checkImage"+i).src=imgFalse;
			}
		}
	}
	
	var a = document.getElementsByTagName('a');
	for(var i = 0; i < a.length; i++){
		if(val) {
			if(a[i].title == refString){
				a[i].setAttribute("onclick", "checkUncheckAll(false,'"+table+"')");
				a[i].innerHTML = "Uncheck All";
			}
		}
		else if(!val) {
			if(a[i].title == refString){
				a[i].setAttribute("onclick", "checkUncheckAll(true,'"+table+"')");
				a[i].innerHTML = "Check All";
			}
		}
	}
}



window.onload = init;