var formObj = null;
var gameTyp = "";
var secNum = -1;
var request=null;
var opType = -1;
var inpSearchCont = 0;
var numUpd = 0;


function sendUpdateInfo(obj){
    if (obj == null ) { return; }
    var url = "";
    var nme = "";

    formObj=obj;
    nme = obj.name;
    var sub = nme.substring(0,nme.indexOf("_"));
    gameTyp=sub;

    opType = 2; //type update

    url = "/voteme/getting.php?sec="+gameTyp+
	  "&op="+opType;

    httpRequest("GET",url,true);

}

window.onload=function(){
    var nme = null;
    var allInputs = document.getElementsByTagName("input");
    if(allInputs != null){
        for(var i = 0; i < allInputs.length;i++) {
            if(allInputs[i].type == "checkbox" && allInputs[i].name != "iremember"){
		if(nme == null)
			nme = allInputs[i];
                allInputs[i].onchange=function(){
                    sendVoteInfo(this)
		};
            }
        }
    }

    sendUpdateInfo(nme);
}


function sendVoteInfo(obj){
    if (obj == null ) { return; }
    var url = "";
    var nme = "";
    var val = 0;

    formObj=obj;
    nme = obj.name;
    var sub = nme.substring(0,nme.indexOf("_"));
    gameTyp=sub;

    opType = 1; //type update

    if(obj.checked == true)
	val = 1;

    url = "/voteme/getting.php?sec="+gameTyp+
          "&choices="+obj.value+
          "&r="+val+
	  "&op="+opType;
    httpRequest("GET",url,true);

    changeStyle(obj);
}

function changeStyle(obj){
    if (obj == null ) { return; }

    if(obj.checked) 
	document.getElementById('tr_' + obj.value).className = 'selected';  
    else
    	document.getElementById('tr_' + obj.value).className = '';  
 
}

function changeChk(obj, val){
    obj.checked = val;
    changeStyle(obj);
 
}

function updateForm(rName, val){
    var allInputs = document.getElementsByTagName("input");
    if(allInputs != null){
        for(; inpSearchCont < allInputs.length; inpSearchCont++) {
            if(allInputs[inpSearchCont].type == "checkbox"){
		if(allInputs[inpSearchCont].value == rName){
			changeChk(allInputs[inpSearchCont], val);
			return;
		}	
	    }
	}
    }

}


//event handler for XMLHttpRequest
function handleResponse(){
    try{
        if(request.readyState == 4){
            if(request.status == 200){
                var resp =  request.responseText;
                if(resp != null){
                    //return value is a JSON object
                    var func = new Function("return "+resp);
                    displayPollResults(func());
                }
            } else {
                //request.status is 503  if the application isn't available;
                //500 if the application has a bug
                alert(
                        "A problem occurred with communicating between"+
                        " the XMLHttpRequest object and the server program.");
            }
        }//end outer if
    } catch (err)   {
        alert("It does not appear that the server "+
              "is available for this application. Please"+
              " try again very soon. \nError: "+err.message + " S: "+request.responseText);

    }
}

function displayPollResults(obj){
    var str ="<br />";

    if(opType == 2) {
        numUpd = 0;
	inpSearchCont = 0;
	//var val = obj['choices'].length;
	for(var prop in obj['choices']) {
		str += prop + " : "+obj['choices'][prop]+"<br />"; 
		if(obj['choices'][prop]!=''){
			updateForm(obj['choices'][prop], true);
			numUpd++;
		}
	}

        var spanleft = document.getElementById("gselect");
        spanleft.innerHTML = numUpd;                 //SELECTS

    }else if(opType == 1) {
	if(obj['result'] != 1){
		//alert("valor no enviado!");
		updateForm(obj['vote'], false);
	}else{
            var spanleft = document.getElementById("gleft");
            spanleft.innerHTML = obj['left'];

	    if(obj['value'] == 1)
		numUpd ++;
	    else
		numUpd --;
            spanleft = document.getElementById("gselect");
            spanleft.innerHTML = numUpd;                 //SELECTS
	}
    }

    
/*
    var div = document.getElementById(gameTyp+"_poll");
    var spans = div.getElementsByTagName("span");
    for(var i = 0; i < spans.length; i++){
        if(spans[i].id.indexOf("title") != -1){
            spans[i].innerHTML = "<strong>Your poll of "+gameTyp+
                                 " games</strong>"
        }   else {
            //use the object and its properties
            str +="<br />";
            for(var prop in obj) { str += prop + " : "+obj[prop]+"<br />";}
            spans[i].innerHTML = str;
       }
    }
    div.style.visibility="visible";
*/

}

/* Initialize a Request object that is already constructed */
function initReq(reqType,url,bool){
    try{
        /* Specify the function that will handle the HTTP response */
        request.onreadystatechange=handleResponse;
        request.open(reqType,url,bool);
        request.send(null);
    } catch (errv) {
        alert(
                "The application cannot contact "+
                "the server at the moment. "+
                "Please try again in a few seconds." );
    }
}

/* Wrapper function for constructing a Request object.
 Parameters:
  reqType: The HTTP request type such as GET or POST.
  url: The URL of the server program.
  asynch: Whether to send the request asynchronously or not. */
function httpRequest(reqType,url,asynch){
    //Mozilla-based browsers
    if(window.XMLHttpRequest){
        request = new XMLHttpRequest();
    } else if (window.ActiveXObject){
        request=new ActiveXObject("Msxml2.XMLHTTP");
        if (! request){
            request=new ActiveXObject("Microsoft.XMLHTTP");
        }
     }
    //the request could still be null if neither ActiveXObject
    //initializations succeeded
    if(request){
       initReq(reqType,url,asynch);
    }  else {
        alert("Your browser does not permit the use of all "+
        "of this application's features!");}
}


