var bRegError 			= false;
var debug 				= ""; 
var detected_product 	= "";
var xmlDoc;

//Public web "return" link
var pubweb_link			= "dtree";
var bridge_url			= "ocs_bridge.jsp?";
var selected_nav		= 0;

function isVista()
{
	var bVista = false;
	var browser_detect = navigator.userAgent.toLowerCase();

	if(debug.indexOf("on") > -1) alert("Register() -- Browser is: " + browser_detect + "\nIs Vista: " + browser_detect.indexOf("windows nt 6"));

	//set flag to true if vista is installed
	if (browser_detect.indexOf("windows nt 6") != -1)
		bVista = true;

	return bVista;
}

function check_ocs_bridge(){
	debug = get_url_param("debug");
	//build link back to public web support experience
	selected_nav = get_url_param("selected_nav");
	var referrer_url  = document.location.href;
	if(referrer_url.indexOf("id=error_messages") > -1){
		pubweb_link = "error_messages";	
	}else{
		pubweb_link = "tech_issues";	
	}
	
	if(debug.indexOf("on") > -1) alert("referrer = "+ pubweb_link + ", cookies = " + document.cookie);

	//Check if OCS installed. Parameter 'false' indicates that controls not ready (assumption). 
	if(debug.indexOf("stop") == -1){
		is_ocs_installed(false);
	}
}

function is_ocs_installed(readyForCheck) {

	var cookieVal = getCookieVal("SYM_OCSBridge"); 	// COOKIE CHECK

	if(cookieVal != null && cookieVal != ""){		
		if(cookieVal.indexOf("true") > -1){	
			// user previously launched OCS from catapult experience => display ocs_bridge page
			cookieVal = cookieVal.substring(cookieVal.indexOf("_")+1);
			if(debug.indexOf("on") > -1) alert("TRUE cookie found => direct to ocs_bridge " + cookieVal);
			document.location.href = bridge_url + "pvid="+ cookieVal +"&id=" + pubweb_link + "&selected_nav=" + selected_nav;

		}else{
			// user previously declined using OCS => display pub-web consumer support experience
			if(debug.indexOf("on") > -1) alert("FALSE cookie found => direct to pub-web support");

			document.getElementById("please_wait").className= "hidden";
			document.getElementById("pvselector").className= "shown";
			document.getElementById("backlink").className= "shown";
		}

	} else {  //no SYM_OCSBridge cookie info found => check if OCS eligible product is installed

		try{  
			//Check if OCS controls are registered  
			if (!readyForCheck) {
				if(debug.indexOf("on") > -1) alert("calling Registr()");
				//Try registering OCS controls
				Register("ocs","2.5","PROD");  //Call register
				//if(debug.indexOf("on") > -1) alert("returned from Registr()");

			} else { //OCS Controls registered or not found. Continue collecting product information.
				if(debug.indexOf("on") > -1) alert("call getProductInfo()");
				
				getProductInfo();  // PRODUCT DETECTION  (sets detected_product variable)
				
				if(debug.indexOf("on") > -1) alert("returned from getProductInfo()");
				
				if(detected_product != ""){   

					//check if PVID is listed in ocs_bridge_config.xml (do not offer user option to use catapult if PVID is not found in list)
					if(check_pvid_config(detected_product)){

						// OCS eligible product is installed => display ocs_bridge page
						if(debug.indexOf("on") > -1) alert("NO cookie found - OCS eligible product detected");
						document.location.href = bridge_url + "pvid="+ detected_product +"&id=" + pubweb_link + "&selected_nav=" + selected_nav;

						return true;
					}else{
						// OCS eligible product is installed but PVID is not found in ocs_bridge_config.xml file
						if(debug.indexOf("on") > -1) alert("NO cookie found - OCS eligible product detected but product not in config XML file");

						//set cookie for future detections 
						document.cookie   = "SYM_OCSBridge=false;path=/";

						//display PV-selector
						document.getElementById("please_wait").className= "hidden";
						document.getElementById("pvselector").className= "shown";
						document.getElementById("backlink").className= "shown";						
					}
					
				}else{
					// no OCS eligible product is installed => display pub-web consumer support experience
					if(debug.indexOf("on") > -1) alert("NO cookie found - no OCS eligible product installed");

					//set cookie for future detections 
					document.cookie   = "SYM_OCSBridge=false;path=/";

					//display PV-selector
					document.getElementById("please_wait").className= "hidden";
					document.getElementById("pvselector").className= "shown";
					document.getElementById("backlink").className= "shown";
				}
			}
		}catch(e) {
			if(debug.indexOf("on") > -1) alert("Error caught during detection/is_ocs_installed function => display pv-selector");			
			document.getElementById("please_wait").className= "hidden";
			document.getElementById("pvselector").className= "shown";
			document.getElementById("backlink").className= "shown";
		}
	}
}

//determine if detected PVID is eligible 
function check_pvid_config(pvid){
	var file = "";
	if(document.domain.indexOf("uat.ges") > -1 || document.domain.indexOf("preview.ges") > -1){
		if(debug.indexOf("on") > -1) alert("loading: http://www-uat.ges.symantec.com/content/en/us/home_homeoffice/pagecopy/support/ocs_bridge_config.xml");		
		file = "http://www-uat.ges.symantec.com/content/en/us/home_homeoffice/pagecopy/support/ocs_bridge_config.xml";
	}else{
		if(debug.indexOf("on") > -1) alert("loading: http://www.symantec.com/content/en/us/home_homeoffice/pagecopy/support/ocs_bridge_config.xml");		
		file = "http://www.symantec.com/content/en/us/home_homeoffice/pagecopy/support/ocs_bridge_config.xml";
	}
	
	xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	loadXML(file);

	var objNodeList 	= xmlDoc.getElementsByTagName("value");
	var allowed_pvids 	= objNodeList.item(0).xml;
 		
	if(allowed_pvids.indexOf(pvid) > -1){
		return true;
	}else{
		return false;
	}
}

function loadXML(xmlFile) {
	xmlDoc.async="false";
	xmlDoc.onreadystatechange=verify_xmlLoad;
	xmlDoc.load(xmlFile);
}

function verify_xmlLoad() { 
	if(xmlDoc.readyState!=4)
		return false; 
}
 

function getProductInfo () {
	var sr = document.getElementById("srCtl");

	if(debug.indexOf("on") > -1) alert("sr control: " + sr);

	if(sr == null){
		if(debug.indexOf("on") > -1) alert("SR Control is NULL.");
		sr = addControl(document.getElementById("divControls"), "srCtl", "clsid:44990301-3c9d-426d-81df-aab636fa4345");
	}
																		        
	if(debug.indexOf("on") > -1) alert("sr control now: " + sr);
	
	try{ //detect if OCS eligible product is installed on the user's machine

		//SupportAction link for execution.
		var saCab = "";
		if(document.domain.indexOf("support.ges") > -1)
			saCab = "http://support.ges.symantec.com/techsupp/asa/ss/sa/sa_cabs/catapult.cab";
		else if (document.domain.indexOf("uat.ges") > -1 || document.domain.indexOf("preview.ges") > -1)
			saCab = "http://www-uat.ges.symantec.com/techsupp/asa/ss/sa/sa_cabs/catapult.cab";
		else
			saCab = "https://www-secure.symantec.com/techsupp/asa/ss/sa/sa_cabs/catapult.cab";

		var saReturn = runSupportAction(sr,saCab);
		
		if(debug.indexOf("on") > -1) alert("SupportAction Result: " + saReturn);

		switch (parseInt(saReturn))
		{
			case 1:  detected_product = "n360_3.0"; 
					 break;
			case 2:  detected_product = "nis_2009"; 
					 break;
			case 3:  detected_product = "nav_2009"; 
					 break;
			case 4:  detected_product = "nis_2008"; 
					 break;
			case 5:  detected_product = "nav_2008"; 
					 break;
			case 6:  detected_product = "n360_2.0"; 
					 break;
			case 7:  detected_product = "n360"; 
					 break;
		}
		
		if(debug.indexOf("on") > -1) alert("getProductInfo() - Detected Product: " + detected_product);

	}catch(e) {
		if(debug.indexOf("on") > -1) alert("Error caught in getProductInfo() method");		
		detected_product = "";
	}
}


//-----------------------------------------------------------------------------------------------------------------------------------------
//Launch OCS
function launch_ocs(choice) {

	debug = get_url_param("debug");

	if(choice.indexOf("true") > -1){  //LINK TO OCS SUPPORT
		
		//hide 'continue' button & display progress bar
		document.getElementById("button_div").className 		= "hidden";
		document.getElementById("button_div_2").className 		= "hidden";
		document.getElementById("weblink").className 			= "hidden";		
		document.getElementById("help_text").className 			= "hidden";
		document.getElementById("please_wait").className 		= "shown";
		
		//set cookie for future detections
		var cookie_var = "SYM_OCSBridge=true_" + get_url_param("pvid") + ";path=/";
		document.cookie = cookie_var;
		if(debug.indexOf("on") > -1) alert("cookie write: " + cookie_var);

		var sr = document.getElementById("srCtl");
		
		if(sr == null)
			sr = addControl(document.getElementById("divControls"), "srCtl", "clsid:44990301-3c9d-426d-81df-aab636fa4345");

		//LAUNCH OCS	
		var sa_result = -1;
		if(document.domain.indexOf("uat.ges") > -1 || document.domain.indexOf("preview.ges") > -1){
			if(debug.indexOf("on") > -1) alert("Launching OCS: http://www-uat.ges.symantec.com/techsupp/asa/ss/sa/sa_cabs/run_ese.cab");
			sa_result = runSupportAction(sr, "http://www-uat.ges.symantec.com/techsupp/asa/ss/sa/sa_cabs/run_ese.cab"); 
		}else{
			if(debug.indexOf("on") > -1) alert("Launching OCS: http://www.symantec.com/techsupp/asa/ss/sa/sa_cabs/run_ese.cab");
			sa_result = runSupportAction(sr, "http://www.symantec.com/techsupp/asa/ss/sa/sa_cabs/run_ese.cab"); 
		}
		
		if(sa_result != 0){
			if(debug.indexOf("on") > -1) alert("ERROR SA result = " + sa_result);
			//set cookie for future detections
			document.cookie   = "SYM_OCSBridge=false;path=/";

			//display error message w/ link to pub-web
			document.getElementById("please_wait").className 		= "hidden";
			document.getElementById("weblink").className 			= "hidden";
			document.location.href = "ocs_bridge_error.jsp?id=" + get_url_param("id") + "&pvid=" + get_url_param("pvid") + "&selected_nav="+selected_nav;

		}else{
		    setTimeout(function(){
				document.getElementById("please_wait").className 	= "hidden";
				document.getElementById("button_div_2").className 	= "shown";
				document.getElementById("weblink").className 		= "shown";
				document.getElementById("help_text").className 		= "shown";
				}, 10000);
		}

	}else{	//LINK TO PUB-WEB SUPPORT

		//set cookie for future detections
		document.cookie   = "SYM_OCSBridge=false;path=/";

		var web_link	  = "index.jsp";
		var nav_param 	  = get_url_param("selected_nav");
		var bucket_param  = get_url_param("id");
		var pvid_param	  = get_url_param("pvid");
		
		if(choice.indexOf("dtree_ts") > -1){  //dtree_ts & allow user to select another PVID
			web_link 	  = "dtree_ts.jsp?id=" + bucket_param + "&selected_nav=" + nav_param;
		}else{ //user opted out of catapult => display static hot topics
			web_link	  = "top_ts_issues.jsp?id=" + bucket_param + "&selected_nav=" + nav_param + "&pvid=" + pvid_param;
		}

		if(debug.indexOf("on") > -1) alert("web_link = "+ web_link+", cookie write:  SYM_OCSBridge=false;path=/");
		document.location.href = web_link;
	}
}

//Function to run SupportAction
function runSupportAction(script_runner, path_to_cab) {

	if(debug.indexOf("on") > -1) alert("runSupportAction() --- script runner: " + script_runner);

	if(path_to_cab.indexOf("run_ese") > -1){
		var entry_source = "web_bridge_" + get_url_param("id");
		script_runner.SetParameter("entry_source", entry_source);
		if(debug.indexOf("on") > -1) alert("entry_source = " + entry_source);	
	}
	
	try {
		var ver = new String(script_runner.ModuleVersion).substr(0,3);
		var mainResult;
		if (ver < 6.8) {
			script_runner.SetAuthOption(false);
			script_runner.SetAuthOptionEx(2);
			
			mainResult = script_runner.Evaluate(path_to_cab);
		} else {
            script_runner.SetUserInputWait(true) 
			script_runner.SetAuthOption(false);
			script_runner.SetAuthOptionEx(2);          
			
			mainResult = script_runner.EvaluateTestAndRun(path_to_cab);
		}
		return mainResult;

	}catch(e){
		if(debug.indexOf("on") > -1) alert("Error in SA execution = " + e.description);
		mainResult = -1;
		return mainResult;
	}
}

function srCtl_OnEvent(context_in, event_in) {
	if (context_in == "ScriptError"){     // trap error events (push users to pubweb support)
		document.getElementById("please_wait").className 		= "hidden";
		document.getElementById("weblink").className 			= "hidden";
		doQuit();		
		document.location.href = "ocs_bridge_error.jsp?id=" + get_url_param("id") + "&pvid=" + get_url_param("pvid") + "&selected_nav=" + selected_nav;

	} else {}
}

function doQuit(){
	try {
		document.srCtl.Abort(999);
	} catch(e) {}
}

function addControl(divObj, objName, classID) {
	var objCtrl = document.createElement('object');
	divObj.appendChild(objCtrl);
	objCtrl.style.display='none';
	objCtrl.classid= classID;
	objCtrl.id=objName;
	return(objCtrl);
}

function checkBrowser() {
	var agent = navigator.userAgent.toLowerCase();
	if (agent.indexOf("msie")!=-1) {
		return(true);
	}else{
		return(false);
	}
}

function get_url_param(name){
	var start=location.search.indexOf("?"+name+"=");
	if (start<0) 
		start=location.search.indexOf("&"+name+"=");
	if (start<0) 
		return '';
	start += name.length+2;
	var end=location.search.indexOf("&",start)-1;
	if (end<0) 
		end=location.search.length;
	var result=location.search.substring(start,end);
	var result='';
	for(var i=start;i<=end;i++) {
		var c=location.search.charAt(i);
		result=result+(c=='+'?' ':c);
	}
	return unescape(result);
}


function getCookieVal(cookie_name) {
    var cookie_value 	= "";
    var cookies 		= document.cookie;
	if (cookies) {
		var startpos = cookies.indexOf(cookie_name);

		if (startpos > -1) {
            startpos += cookie_name.length;
            var endpos = cookies.indexOf(";", startpos);
            if (endpos < 0) 
                endpos = cookies.length;

            cookie_value = cookies.substring(startpos, endpos);    
            cookie_value = unescape(cookie_value);
            cookie_value = cookie_value.replace(/^=/, "");
            cookie_value = cookie_value.replace(/^&/, "");
        }
    }

    return cookie_value;
}

//Register OCS controls
function Register(prod,version,server){
	var berr = false;

	try{
		// Register controls. Event Handlers will take care of rest.
		var ocsct = document.getElementById("OCSCtrl");

		if(ocsct != null)
		{
			results = ocsct.Initialize(prod,version,server);
			if(debug.indexOf("on") > -1) alert("OCSCtrl.Initialize - results: " + results );
		}
		else berr = true;
	}catch(e){
		if(debug.indexOf("on") > -1) alert("Exception caught:  Register()");
		//OCS control not found (older product). Continue gathering info with no further control check.
		bRegError = true;
		berr = true;
	}

	if(berr) {
		//If os is not Vista then we need to add the srCtl control to the system
		if (isVista()){
			if(debug.indexOf("on") > -1) alert("Register() -- Vista - sending Omniture error request");
			sendOmnitureRequest();
		}

		if(debug.indexOf("on") > -1) alert("Register() -- adding srCtl");
		addControl(document.getElementById("divControls"), "srCtl", "clsid:44990301-3C9D-426D-81DF-AAB636FA4345");

		if(debug.indexOf("on") > -1) alert("Register() --- calling is_ocs_installed()");
		is_ocs_installed(true);
	}
}

//Unregister OCS controls
function Unreg(){
	try{
		//Unregister controls.	
		OCSCtrl.UnRegisterKeys();
	}catch(e){
	}
}


function sendOmnitureRequest(){
	try{
		s.pageName= lg+"/"+ct+": hho: support: ocs_bridge: error";					
		var s_code=s.t();
		if(s_code)
			document.write(s_code);
	} catch(err) {
		if(debug.indexOf("on") > -1) alert("Omniture error sending invisible page request: " + err.description);
	}	
}
