/**
* Document loaded
*/
$(function(){
	$("#ivr_message").hide();
	$("#no_javascript").hide();
});

/**
* Checks if IVR code is called at
*/
var ivr_pincode;
var ivr_country;
var ivr_line;

/**
* Set pincode to be checked
*/
function setIvrPincode(pincode)
{
	ivr_pincode = pincode;
	
	checkIvrSetup();
}

/**
* Set country of caller
*/
function setIvrCountry(country)
{
	ivr_country = country;
	
	checkIvrSetup();
}

/**
* Set line of caller
*/
function setIvrLine(line)
{
	ivr_line = line;
	
	checkIvrSetup();
}

/**
* Check if everything is setup to check
*/
function checkIvrSetup()
{
	if(ivr_pincode != '' && ivr_pincode != undefined && ivr_country != '' && ivr_country != undefined && ivr_line != '' && ivr_line != undefined)
	{
		//getIvrStatus();
		// Eerste 20 seconden niet checken
		setTimeout("getIvrStatus()", 20000);
	}
}

/**
* Get IVR status through Xajax
*/
function getIvrStatus()
{
	$.ajax({
	    type        : "POST",
	    cache       : false,
	    url         : "/checkIvr.php",
	    data        : {code:ivr_pincode, line:ivr_line, co:ivr_country},
	    error: function(XMLHttpRequest, textStatus, errorThrown) {
	    	// error
	    	$("#no_javascript").show();
	    },
	    success: function(data) {
	    
	    	if(data.indexOf("json") == -1)
	    	{
	    		// error
	    		$("#no_javascript").show();
	    	}
	    	else
	    	{
		    	var data2 = json_parse(data);
		    	
		    	if(data2.loggedIn != undefined && data2.loggedIn == false)
		    	{
		    		// error
		    		$("#no_javascript").show();
		    	}
		    	else if(data2.succes == true)
		    	{
		    		$("#ivr_message").show();
		    		$("#ivr_message").effect("highlight", {}, 25000);
		    		$("#ivr_pincode_txt").effect("highlight", {}, 25000);
		    		$("#ivr_pincode_txt").html(data2.newPincode);
		    		
		    		//setIvrPincode(data2.newPincode);
		    		ivr_pincode = data2.newPincode;
		    		
		    		setTimeout("removeIvrMessage()", 5000);
		    		
		    		showFancyPage('opwaarderen-succes');
		    		setTimeout("getIvrStatus()", 1000);
		    	}
		    	else if(data2.loggedIn == undefined && data2.succes == undefined)
		    	{
		    		// error
		    		$("#no_javascript").show();
		    	}
		    	else if(data2.stop != undefined && data2.stop == true)
		    	{
		    		// Stop met checken na 5 minuten
		    		$("#no_javascript").show();
		    	}
		    	else {
		    		if(data2.delay != undefined && data2.delay == true)
		    		{
		    			// Na 2 minuten elke 5 seconden checken
		    			setTimeout("getIvrStatus()", 5000);
		    		}
		    		else {
			       		setTimeout("getIvrStatus()", 1000);
			       	}
		    	}
		    }
	
	   		}
	   });
}

/**
* Hide IVR message
*/
function removeIvrMessage()
{
	$("#ivr_message").hide();
}
