/**
 * This is the selector javscript.
 * 1. Capable of handling multiple selectors.
 * 2. Lazy loads necessary Assets such as Jquery plugins, core library.
 * 
 * Notes: The Portlet's placement Id is used as a namespace for 
 * storing variables based on its state. Variables are the style class names,
 * Dom component Ids are all namescpaced with its portlet's placement id.
 * 
 * Hope this works out :)
 * 
 * @author Jerry Emmanuel
 * @version 1.0
 * @contact Cognizant - Jerry Emmanuel, 3M - Gerianne Freiberger
 * @revision 15-Jun-2011; Created
 */
//Cannot do var selectorLoad. Multiple selectors.. This should happen only once. 
if (typeof selectorLoad === "undefined") {
	
	selectorLoad = function() {
		// just in case if EWCD theme loads jquery already 
		if (typeof $ === "undefined") {
			//document.getElementById('info').innerHTML 
				//= document.getElementById('info').innerHTML + '<BR/>Loading Jquery 1.5.5...';	
			selectorLoad.getScript(selectorLoad.getCsAssetImageUrl('jquery'));
			selectorLoad.tryReady(0); // We will write this function later. It's responsible for waiting until jQuery loads before using it.
		} else {
			// from here some version of jquery is available
			//loading Selector Scripts
			var scriptsToLoad = [];
			
			if ($.prop) {
				//document.getElementById('info').innerHTML 
					//= document.getElementById('info').innerHTML + '<BR/>Jquery 1.5.5 is already loaded';
				scriptsToLoad = ['blockUI'];
			} else {
				//document.getElementById('info').innerHTML 
					//= document.getElementById('info').innerHTML + '<BR/>Updating to Jquery 1.5.5...';
				scriptsToLoad = ['blockUI', 'jquery'];
			}
			// wait for Html to be loaded fully as configurations can exist in embedded scripts in each of the selectors.
			$(document).ready( function() {
				// load from last index
				selectorLoad.loadDepandantScripts(selectorLoad.appendSelectorsToLoad(scriptsToLoad));					
			});			
		}
	};

	// The set of assets to lazy load.
	selectorLoad['assetsToLoad'] = {
		'jquery' : '1180613536257', // latest jquery corporate Asset
		//'gsdbSelector' : '1310732158505', //GSDB Selector multiple support
		'gsdbSelector' : '1273690288309', //GSDB Selector multiple support
		//'spreadSheetSelector' : '1313475784047', //SpreadSheet Selector multiple support
		//'spreadSheetSelector' : '1319237924827', //SpreadSheet Selector multiple support
		'spreadSheetSelector' : '1319243460136', //SpreadSheet Selector multiple support - by Sunit
		'blockUI' : '1273679990633', // blockUI, for both GSDB and SpreadSheet
		'tooltip' : '1273672112201' // tooltip for SpreadSheet
	};
	
	selectorLoad['instantiated'] = {
		'gsdb' : false,
		'spreadSheet' : false
	};
	
	//Create a Content Server Asset Image Url
	selectorLoad.getCsAssetImageUrl = function(assetName) {
		return "/3MContentRetrievalAPI/BlobServlet?assetType=MMM_Image&blobAttribute=ImageFile&assetId=" 
			+ selectorLoad['assetsToLoad'][assetName]; 
	};		

	// dynamically load any javascript file.
	selectorLoad.getScript = function(filename) {
	  	var script = document.createElement('script');
	  	script.setAttribute("type","text/javascript");
	  	script.setAttribute("src", filename);
	  
	  	if (script) {
			document.getElementsByTagName("head")[0].appendChild(script);
		}
	};

	selectorLoad.tryReady = function(time_elapsed) {
	 	// Continually polls to see if jQuery is loaded.
	 	if (typeof $ === "undefined") { // if jQuery isn't loaded yet...
	    	if (time_elapsed <= 5000) { // and we havn't given up trying...
	      		setTimeout("selectorLoad.tryReady(" + (time_elapsed + 200) + ")", 200); // set a timer to check again in 200 ms.
	    	} else {
	    		//console.log("Timed out while loading jQuery.");
	    	}
	  	} else {
	  		//console.log("Jquery is loaded.");
			//document.getElementById('info').innerHTML 
				//= document.getElementById('info').innerHTML + '<BR/>Jquery is loaded';
			
			// wait for html to be fully loaded
			$(document).ready( function() {
				// load from last index
				selectorLoad.loadDepandantScripts(selectorLoad.appendSelectorsToLoad(['blockUI']));
			});
	  	}
	};
	
	selectorLoad.appendSelectorsToLoad = function(assetsToLoad) {
		// if gsdb configurations are present, append gsdb selector script to be loaded.
		if (typeof selectorConfig !== "undefined" && selectorConfig) {
			assetsToLoad.splice(0,0,'gsdbSelector');
		}
		
		// if spreadSheet configurations are present, append spreadSheet selector script to be loaded.		
		if (typeof spreadSheetConfig !== "undefined" && spreadSheetConfig) {
			assetsToLoad.splice(0,0, 'spreadSheetSelector', 'tooltip');
		}
		return assetsToLoad;
	};
	
	selectorLoad.instantiateGsdb = function(time_elapsed) {
	 	// Continually polls to see if selector is loaded.
	 	if (typeof selector === "undefined") { // if selector isn't loaded yet...
	    	if (time_elapsed <= 5000) { // and we havn't given up trying...
	      		setTimeout("selectorLoad.instantiateGsdb(" + (time_elapsed + 200) + ")", 200); // set a timer to check again in 200 ms.
	    	} else {
	    		//"Timed out while loading Gsdb selector.");
	    	}
	  	} else {
	  		if (selector && typeof selector.init !== "undefined") {
		  		//document.getElementById('info').innerHTML 
		  			//= document.getElementById('info').innerHTML + '<BR>GSDB Sel: Should be printed only once.';
	  			
		  		selector.init();
		  		selectorLoad['instantiated']['gsdb'] = true;
	  		} else {
	  			if (time_elapsed <= 10000) {
	  				setTimeout("selectorLoad.instantiateGsdb(" + (time_elapsed + 200) + ")", 200); // set a timer to check again in 200 ms.
	  			}
	  		}
	  	}
	}
	
	selectorLoad.instantiateSpread = function(time_elapsed) {
	 	// Continually polls to see if selector is loaded.
	 	if (typeof spreadSel === "undefined") { // if selector isn't loaded yet...
	    	if (time_elapsed <= 5000) { // and we havn't given up trying...
	      		setTimeout("selectorLoad.instantiateSpread(" + (time_elapsed + 200) + ")", 200); // set a timer to check again in 200 ms.
	    	} else {
	    		//"Timed out while loading SpreadSheet selector.;
	    	}
	  	} else {
	  		if (spreadSel && typeof spreadSel.init !== "undefined") {
		  		//document.getElementById('info').innerHTML 
		  			//= document.getElementById('info').innerHTML + '<BR>SpreadSheet Sel: Should be printed only once.';
	  			
		  		spreadSel.init();
		  		selectorLoad['instantiated']['spreadSheet'] = true;
	  		} else {
	  			if (time_elapsed <= 10000) {
	  				setTimeout("selectorLoad.instantiateSpread(" + (time_elapsed + 200) + ")", 200); // set a timer to check again in 200 ms.
	  			}
	  		}
	  	}
	}	

	selectorLoad.loadDepandantScripts = function(assetsToLoad) {
		
		if (selectorLoad['assetsToLoad']['gsdbSelector_loaded'] && !selectorLoad['instantiated']['gsdb']) {
			selectorLoad.instantiateGsdb(0);       				
		}
		
		if (selectorLoad['assetsToLoad']['spreadSheetSelector_loaded'] && !selectorLoad['instantiated']['spreadSheet']) {
			selectorLoad.instantiateSpread(0);       				
		}
		
		if (!assetsToLoad || !assetsToLoad.length) {
			//document.getElementById('info').innerHTML 
				//= document.getElementById('info').innerHTML + '<BR/>All are loaded.';
			return false;
		}
		
		var assetToLoad = assetsToLoad.splice(assetsToLoad.length - 1, 1);
		if (assetToLoad.length && assetToLoad[0]) {
			assetToLoad = assetToLoad[0]; 
		}
		
		//document.getElementById('info').innerHTML 
			//= document.getElementById('info').innerHTML + '<BR/>Loading depandant script ' + assetToLoad;

		selectorLoad['assetsToLoad'][assetToLoad + '_loaded'] = false;

		$.ajax({
			url: selectorLoad.getCsAssetImageUrl(assetToLoad),
			dataType: 'script',
			success: function() {
				selectorLoad.loadNext(assetToLoad, assetsToLoad);
			},
			cache: false,
			statusCode : {
				304: function() {
					selectorLoad.loadNext(assetToLoad, assetsToLoad);
				},
				200: function() {
					selectorLoad.loadNext(assetToLoad, assetsToLoad);
				}
			}				
		});	
	};
	
	selectorLoad.loadNext = function(assetToLoad, remainingAssets) {		
		if (!selectorLoad['assetsToLoad'][assetToLoad + '_loaded']) {
			selectorLoad['assetsToLoad'][assetToLoad + '_loaded'] = true;
			selectorLoad.loadDepandantScripts(remainingAssets);
		}
	};
	
	
	// load jquery and then the other assets
	selectorLoad();
} else {
	// Assets are already loaded and that will take care of instantiating selector
	// Instantiation happens in selector Js Itself	
}