/**
 * This class helps to check if objects has been defined.
 *
 * Until the objects has been defined, we wait.
 */
function ObjectChecker() {
	var toCheck = [];
	var maxTime = 5000;
	var timeStart = -1;
	var interval = 100;
	var afterCheckCallback;
	// for external manual status check
	this.status = true;

	this.setMaxTime = function(value){
		maxTime = value;
	}
	
	this.checkDwrInterfaces = function(){
		var toCheck = [];
		toCheck.push('dwr');
		toCheck.push('DWREngine');
		toCheck.push('userContextSSL');
		toCheck.push('purchaseFlowServiceSSL');
		toCheck.push('phoneLocator');
		toCheck.push('translationBean');
		toCheck.push('userContext');
		toCheck.push('purchaseFlowService');
		toCheck.push('webShop');
		toCheck.push('mediaSearch');
		this.setArrayToCheck(toCheck);
		this.check();
	}

	this.setCallback = function(callback){
		if(typeof(callback) == "function"){
			afterCheckCallback = callback;
		}else{
			afterCheckCallback = function(){
				stateManager.init();
			}
		}
	}

	this.setArrayToCheck = function(args){
		if(!args)
			return;
		toCheck = [];	
		if(typeof(args)== "string")
			toCheck.push(args);
		else
			toCheck = args;	
	}
	
	this.check = function(){
		timeStart = new Date();
		startCheck();
	}
	
	var startCheck = function(){
		var actualTime = new Date();
		var timePassed = actualTime - timeStart;
		if (timePassed < maxTime) {
			if (internalCheck()) {
				timeStart = -1;
				debug("ObjectChecker --- everything was perfect. let's rock");
				afterCheckCallback();
			} else {
				setTimeout(function(){startCheck();}, interval);
				debug("ObjectChecker --- one more try");
			}
		} else {//if timeout
			this.status = false;
			debug("ObjectChecker --- something went wrong but trying any way");
			afterCheckCallback();
		}
	}
	
	function internalCheck(){
		var good = true;
		for(var i=0;i<toCheck.length;i++){
			//if(typeof(window[toCheck[i]]) != "object" ){
			if(typeof(window[toCheck[i]]) != "object" ){
				good = false;
				//debug("ObjectChecker.internalCheck() - the object " + toCheck[i] + " was not an object. It's a " + typeof(toCheck[i]));
				break;
			}
		}
		return good;
	}
}

///////////////////////////////////////////////////////////////////////////////////
// DO NOT remove the next newline and DO NOT add code after this comment.
