// ===================================================================
// Author: Jason Huselton <jhuselton@omnovia.com>
// WWW: 
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download. 
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================

/**
 * Add DESC HERE LATER. 
 *	TODO: 
 		- Add XML Handling to replace Delimiter for data
		- Replace with better way to create elements
		
 */
 

//These vars are used for the admin and should be removed.
var n_2_selectedTopicId = -1;  // no is the nb of rows of topics
var n_2no = 0;

var currentTopicID  = -1;  // Current Topic selected from the list.  main function calls and sets this to 0 upon page load.
var currentTopicLevel = -1; // We are currently at this level.  main() function calls and sets this to 0 upon page load.
var nbShownTopics = 0;  // this is the total of shown topics.
var department = "";
var firstFocusOnMessage = true;


/*	
	//LOAD XML IMPLEMENTATION
	var xmlDoc;
	
		// code for IE
	if (window.ActiveXObject)
	{
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	}
	// code for Mozilla, Firefox, Opera, etc.
	else if (document.implementation.createDocument)
	{
		xmlDoc=document.implementation.createDocument("","",null);
	}
	else
	{
		alert('Your browser cannot handle this script');
	}

*/

/*
*	getTopics - Main Function that starts the process.  Gets the Topics from PHP, and returns results
		returns True if it returns data, false if an error occurs.
*/
function getTopics(topicId, level) 
{

	// Add this exception b/c if not, Choosing Please Select.. for the first select box removes all drop downs
	if((topicId == -1) && (level == 1))
	{
		topicId = 0;
		level = 0;
	}

	// Used for Admin Operation
	n_2_selectedTopicId = currentTopicID;
	n_2no = currentTopicLevel;

	// Set the current Global topicID and Level for what was chosen
	currentTopicID = topicId;
	currentTopicLevel = level;

	//Remove all Topics after the Current Selected Level
	removeTopicsAfter(level);
	
	if (topicId != -1)
	{
		AjaxRequest.post(
		{
			'url':'support_topic.php',
			'action':'getTopics',
			'topicID':topicId,
			'inXML':0,
			'onSuccess':function(req) 
			{
				showTopics(req.responseText);
				//ajaxDoneLoading();
				return true;
			},
//			'onLoading':ajaxLoading("Loading..."),
			'onError':function(req) {
				//ajaxDoneLoading();
				alert("Error loading.  Please Refresh the Page\n\n" + req.responseText);
			}
		});
	}
	return false;
}
	
	
function removeTopicsAfter(currentTopicLevel)
{
	var no = currentTopicLevel;
	
	for (var i = no + 1; i <= nbShownTopics; i++)
	{
		try
		{
			var topicDiv = document.getElementById('topics')
			var elementToRemove = document.getElementById("divChoice" + i);
			topicDiv.removeChild(elementToRemove);
		}
		catch(err)
		{
			alert(err);	
		}
	}
	nbShownTopics = no;
}

	
/*  function showTopics
*	Function will get and show the next availabe topics for the drop down box.
*	Will call and set the Departemnt on the first level
*
*/

function showTopics(topicsInfo)
{

    showCrisisArea();
	if(currentTopicLevel == 1)
	{
		department = document.getElementById("choice1");
		if(department.selectedIndex > 0)
		{
			
			setDepartment(department.options[department.selectedIndex].value);
			
		}
	}

	var tArray = topicsInfo.split("!~");

	topicsListText = tArray[0];
	formFielsText = tArray[1];
	KBsListText = tArray[2];
		
	if (topicsListText != "")
	{
		nbShownTopics++;
		topicsList = topicsListText.split("~-");

		var sel_div = document.createElement("div");
		sel_div.id = "divChoice" + nbShownTopics;

		
		if(currentTopicLevel == 0)
		{
			var selText="<SELECT id ='choice" + nbShownTopics+"' onChange='getTopics(this.value," + nbShownTopics+")'><Option value='-1'>Please Select Department ...</Option>";
		}
		else
		{
			var selText="<SELECT id ='choice" + nbShownTopics+"' onChange='getTopics(this.value," + nbShownTopics+")'><Option value='-1'>Please Select...</Option>";				
		}
		
	
		for (var i=0; i < topicsList.length; i++)
		{
			parts = topicsList[i].split("~@");
			selText+= "<Option value='" + parts[0] + "'>" + parts[1] + "</Option>";
		}
		selText+= "</Select>";
	
		document.getElementById('topics').appendChild(sel_div);

		sel_div.innerHTML = selText;
		// we have more topics so don't show the list.
		toggleForm(false);
	}
	else
	{
		// no further topics.  Must show the forms always.
		toggleForm(true);
	}
	
	showKBs(KBsListText);
	
}

function showKBs(KBsListText)
{
		ulText = "";

		

		KBsList = KBsListText.split("~-");

		//identify the div the kbs will go in. alredy created
		var kbDiv = document.getElementById('KBs');
		

		//Reset the KB list
		kbDiv.innerHTML = ulText;

		if (KBsListText != "")
		{	
			

			ulText = "<h2>Knowledgebase Articles</h2>"
			//ulText += createSearchForm();

			KBsList = KBsListText.split("~-");
			ulText += "<ul class=orange>";

			for (var i=0; i < KBsList.length; i++)
			{
				parts = KBsList[i].split("~@");
				ulText += "<li> <a href='http://support.omnovia.com/kb/" + parts[0] + "'> " + parts[1] + "</a></li>";
				
			}
			ulText += "</ul>";

		}

		document.getElementById('KBs').innerHTML = ulText;
		
}

	
	
	function ajaxLoading(msg)
	{
		//alert($msg);
	
	}
	


//UTILITY FUNCTION
function toggleForm(setDisplay)
{
		var support_form = document.getElementById('supportForm');
		
		if (setDisplay)
		{
			populatePath(nbShownTopics);
			support_form.style.visibility = 'visible';
			addSpacer();
		}
		else
		{
			support_form.style.visibility = 'hidden';
		}

}


function addSpacer()
{
	
	var text = "<br /><br /><br /><br /><br /><br /><br /><br />";
	document.getElementById('spaceghost').innerHTML = text;
	document.getElementById('footer').style.marginBottom = "-60px";
}


function populatePath(CurrentNumberTopics)
{

	var topicPath = "";
	for (var i = 1; i <= CurrentNumberTopics; i++)
	{
		var currentTopic = getTopicPath(i);
		topicPath += currentTopic + " | ";

	}
	setHiddenTopicField(topicPath);
}


function getTopicPath(currentTopicNumber)
{
	var currentPathForm = document.getElementById("choice" + currentTopicNumber);
	return currentPathForm.options[currentPathForm.selectedIndex].text;
}


function setHiddenTopicField(topicPath)
{
	hiddenField = document.getElementById("supportPath");
	hiddenField.value = topicPath;
	
	//alert(hiddenField.value);
}

//ADMININSTRATIVE FUNCTIONS
function addTopic()
{

	AjaxRequest.post(
		{
			'url':'support_topic.php',
			'action':'addTopic',
			'topicText':document.getElementById('addTopicText').value,
			'topicOrder':document.getElementById('addTopicOrder').value,
			'topicKbs':document.getElementById('addListKB').value,
			'parentTopicId':currentTopicID,
			'inXML':0,
			'onSuccess':function(req) 
			{
				getTopics(currentTopicID, currentTopicLevel);
				//alert(req.responseText);
				//ajaxDoneLoading();
			},
//			'onLoading':ajaxLoading("Loading..."),
			'onError':function(req) {
				//ajaxDoneLoading();
				alert("Error loading.\n\n" + req.responseText);
			}
		});

	

}
	
	
function deleteTopic()
{

	AjaxRequest.post(
		{
			'url':'support_topic.php',
			'action':'deleteTopic',
			'topicID':currentTopicID,
			'inXML':0,
			'onSuccess':function(req) 
			{
				getTopics(n_2_selectedTopicId, n_2no);
				//ajaxDoneLoading();
			},
//			'onLoading':ajaxLoading("Loading..."),
			'onError':function(req) {
				//ajaxDoneLoading();
				alert("Error loading.\n\n" + req.responseText);
			}
		});
	
}

	
	


//FUNCTIONS TAKEN FROM PREVIOUS OMNOVIA SUPPORT PAGES
function addchangeevent()
{
	var id = document.getElementsByName('5303ec7aa6');
	if (id[0] != null)
	{
		id = id[0];
		id.onchange=function()
		{
			if (id.options[id.selectedIndex].value == 'Urgent')
				document.getElementById('modLogin').style.display = '';
			else
				document.getElementById('modLogin').style.display = 'none';

		}
	}
}

function onFormSubmit()
{
	clearInitialMessage();
	if(!validateFields())
		return;
		
	document.submitticket.submit();
//	var myPath = document.getElementById("supportPath");
//	myPath.value = "";
//	alert(myPath.value);

}

function validateFields()
{
	var fullName = document.getElementById('fullname');
	if(!validateTextField(fullName.value, "fullname"))
		return false;

	var emailField = document.getElementById('email');
	if(!validateEmail(emailField.value, "email"))
		return false;

	var phoneNumber = document.getElementById('48e0cb7f2b');
	if(!validatePhone(phoneNumber.value, "48e0cb7f2b"))
		return false;

	var fullName = document.getElementById('subject');
	if(!validateTextField(fullName.value, "subject"))
		return false;

	var fullName = document.getElementById('message');
	if(!validateTextField(fullName.value, "message"))
		return false;



	return true;
	
}



function clearInitialMessage()
{
	
	if (firstFocusOnMessage)
	{
		document.getElementById("message").value = "";
		firstFocusOnMessage = false;
		//startIRSTimer();
	}

}

function removeUrgentOption()
{
	  var prioritySelect = document.getElementById('5303ec7aa6');
	  if (prioritySelect.length = 3)
	  {
			prioritySelect.remove(prioritySelect.length - 1);
	  }
}

function addUrgentOption()
{
	
	var prioritySelect = document.getElementById('5303ec7aa6');

	if (prioritySelect.length = 2)
	{
		var urgentOption = document.createElement('option');
		urgentOption.text = "Urgent";
		urgentOption.value = "Urgent";
		
		try
		{
			prioritySelect.add(urgentOption, null)
		}
		catch(ex)
		{
			prioritySelect.add(urgentOption);
		}
	}

}

/* BRUCE PROJECT Message comes from client_index.php.  Shows message if any system wide issues occur */
function showCrisisArea()
{
	crisisArea = document.getElementById('crisis_area');
	if(!crisisArea.innerHTML == "")
	{
		crisisArea.style.display = 'block';
	}
		
	
}

//NO LONGER BEING USED.  REPLACED BY SIMPLY ADDING TO DIFF LOCATION
function createSearchForm()
{

	
	var formText;
	
	formText = "<div>";
	formText += "<form method='POST' action='http://support.omnovia-dev.com/index.php' name='search'><input type='text' class='searchtext' name='searchquery'/><input type='submit' class='yellowbutton' value='Search' name='Submit'/><input type='hidden' value='core' name='_m'/><input type='hidden' value='searchclient' name='_a'/><input type='hidden' value='knowledgebase' name='searchtype'/></form>";
	formText += "</div>";
	
	return formText;	
}


/*  setDepartment
*		Sets the hidden vield value of departmentid to the correct Departmetn for ticket submission
*		It is important the value being passed stay in the DB otherwise, the department will default to Web Conference Support
*
*/

function setDepartment(departmentValue)
{
		departmentField = document.getElementById("departmentid");
		switch(departmentValue)
		{
			case "1":  //Web Conference Support
				departmentField.value = 1;
				addUrgentOption()
				break;
			
			case "2": //omNovia Sales
				departmentField.value = 4;
				removeUrgentOption()
				break;

			case "3": //Secure Viewer
				departmentField.value = 2;
				removeUrgentOption()
				break;

			case "4": //Billing
				departmentField.value = 5;
				removeUrgentOption()
				break;
				
			default:  //Default case is to omNovia Web Conference Support...consider removing the first case.
				departmentField.value = 1;
				break;
			
			
		}


}

//Hidden Fields Functions

function populateHiddenFields()
{
/*   NO LONGER BEING USED -- NEED REMOVE
	var usernameCookie = getCookie("un");
	
	var username_textbox = document.getElementById("conference_username");
	
	if(usernameCookie != null && username_textbox != null )
		username_textbox.value = usernameCookie;
*/
  

	document.getElementById("lastRoomID").value = getCookie("lastRoomID");
	document.getElementById("SCLanguage").value = getCookie("SCLanguage");
	document.getElementById("omnovia_ssl").value = getCookie("omnovia_ssl");
	document.getElementById("presenter").value = getCookie("presenter");
	document.getElementById("twowindows").value = getCookie("twowindows");
	document.getElementById("sc_ticket_room_name").value = getCookie("omnovia_origin");
	
//populate isTrial Field

   
}


function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);

	if(begin == -1) {
		begin = dc.indexOf(prefix);
		if(begin != 0)
			return null;
	} else
		begin += 2;

	var end = document.cookie.indexOf(";", begin);

	if(end == -1)
		end = dc.length;

	var theValue = unescape(dc.substring(begin + prefix.length, end));

	return (theValue == undefined || theValue == "" ? null : theValue);
}


/* After losing focus with the Presenter Password field, this function is called.  A handler function is called on success
*/
function validateModPassword()
{
	var email =  document.getElementById('email').value;
	var password = document.getElementById('opt_password').value;

	AjaxRequest.post(
	{
		'url':'/scripts/checkMod.php',
		'passwd':password,
		'email':email,
		'onSuccess':function(req) 
		{
			handleModResponse(req.responseText);

			return true;
		},
		'onError':function(req) {
			alert("Error loading.  Please Refresh the Page\n\n" + req.responseText);
		}
	});
}

/* Handler function called when the validateModPassword function returns success */
function handleModResponse(text)
{
	//alert(text);	
	var priorityField = document.getElementById('5303ec7aa6');
	if(text != "1")
	{
		alert("Your email address and/or password do not match an authorized Presenter or Moderator Account.  Please submit your ticket as High or modify your information to submit an Urgent Ticket.");
		priorityField.selectedIndex = 1;
		document.getElementById('modLogin').style.display = 'none';
		exit;
	}
	
}

