var gBajax = createRequest();

function createRequest() {
	var obj;
	var browser = navigator.appName;
	if(browser == "Microsoft Internet Explorer"){
        obj = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        obj = new XMLHttpRequest();
    }
    return obj;
}

function clearField( field_name )
{
	document.getElementById( field_name ).value = '';
	document.getElementById( field_name ).style.backgroundColor = '';
}

function highlightFields( field_str )
{
	var fields = field_str.split(',');
	
	for( var i=0; i<fields.length; i++ )
	{
		highlightField( fields[i], '#F6F5CF' ); 
	}
	
}


function highlightField( field_name, field_color )
{
	document.getElementById( field_name ).style.backgroundColor = field_color;
}


function formatCurrency(num) 
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') +  num + '.' + cents);
}	//end function

function validate_required_fields(frmName, strTextBoxes)
{
	var oForm = document.getElementById(frmName);
	
	//turn the comma separated list into an array
	var arrBoxes = strTextBoxes.split(",");
	
	error = 0;
	
	//loop thru each box and determine if the text value is empty
	for( var intCount = 0; intCount < arrBoxes.length; intCount++ )
	{
		arrBoxes[intCount] = arrBoxes[intCount].trim_spaces();
		
		//alert( "inCount: " + intCount + " - text box: -->" + arrBoxes[intCount] + "<--" );
		
		var strText = document.getElementById(arrBoxes[intCount]).value;
		
		if( strText.length == 0 )
		{
			error++;
			
		}	//end if
		
	}	//end for loop
	
	//if any errors, then user did not enter all the required fields
	if( error > 0 )
	{
		alert( "Please enter all the required fields." );
		
		valid = false;
		
	}	//end if
	
	else
	{
		valid = true;
		
	}	//end else
	
	return valid;
	
}	//end function

function pop_templates()
{
	window.open('pop_templates.php','admin_pop','width=600,height=400,scrollbars=yes,resizable=yes');	
}

//removes all spaces in a string
function removespaces() 
{
	return this.replace(/.*\S/,'');
	
}	//end function

//trims leading and trailing spaces
function trim_spaces() 
{
	return this.replace(/^\s+/,'').replace(/\s+$/,'');
	
}	//end function

function clear_image( field_id )
{
	document.getElementById( 'pg-' + field_id ).src = 'images/spacer.gif';
	document.getElementById( field_id ).value = '';
	document.getElementById( field_id + '_filename' ).value = '';
}

function clear_link( field_id )
{
	document.getElementById( field_id ).value = '';
	document.getElementById( field_id + '_text' ).innerHTML = '';
	document.getElementById( field_id + '_text' ).style.backgroundColor = '';
}


function isNumeric(sText) {
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;
	for (i = 0; i < sText.length && IsNumber == true; i++) {
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) {
			IsNumber = false;
		}
	}
	return IsNumber;
}




//assigns a new function to string types
String.prototype.removespaces = removespaces;
String.prototype.trim_spaces = trim_spaces;

/**
 * Sets a cookie using the specified parameters.
 *
 * @param name a name for the cookie
 * @param value the value to store in the cookie
 * @param expires the cookie's lifetime
 * @param path the path in which to store the cookie
 * @param domain the domain for which the cookie is being saved
 * @param secure whether or not the cookie data should be secure
 */
function setCookie(name, value, expires, path, domain, secure) {

    // Setup
    var today = new Date();
    var expireDate = null;
    var cookieString = "";

    // Set Details
    today.setTime(today.getTime());

    if(expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }

    expireDate = new Date(today.getTime() + expires);

    // Build Cookie String
    cookieString = name + "=" + escape(value);

    if(expires) {
        cookieString += ";expires=" + expireDate.toGMTString();
    }

    if(path) {
        cookieString += ";path=" + path;
    }

    if(domain) {
        cookieString += ";domain=" + domain;
    }

    if(secure) {
        cookieString += ";secure";
    }

    // Set the Cookie
    document.cookie = cookieString;
}

/**
 * Attempts to retrieve a cookie with the specified name.
 *
 * @param name the name of the cookie to retrieve
 * @return the value of the requested cookie, or null if no cookie was found
 */
function getCookie(name) {
    // Setup
    var allCookies = document.cookie.split(";");
    var tempCookie = "";
    var cookieName = "";
    var cookieValue = "";
    var cookieFound = false;

    // Parse Cookie
    for(i = 0; i< allCookies.length; i++) {
        tempCookie = allCookies[i].split("=");
        cookieName = tempCookie[0].replace(/^\s+|\s+$/g, "");

        if(cookieName == name) {
            cookieFound = true;

            if(tempCookie.length > 1) {
                cookieValue = unescape(tempCookie[1].replace(/^\s+|\s+$/g, ""));
            }

            break;
        }

        tempCookie = null;
        cookieName = "";
    }

    if(!cookieFound) {
        cookieValue = null;
    }

    return cookieValue;
}

/**
 * Attempts to delete a cookie with the specified name/path/domain. Note that
 * the cookie will not actually be deleted, but will be set to be expired,
 * signalling the browser it is no longer needed and should be removed.
 *
 * @param name the name of the cookie to delete
 * @param path the path within which to look for the cookie
 * @param domain the domain for which the cookie was set
 */
function deleteCookie(name, path, domain) {
    // Setup
    cookieString = "";

    // Attempt to Get Cookie
    if(getCookie(name)) {
        cookieString = name + "=";

        if(path) {
            cookieString += ";path=" + path;
        }

        if(domain) {
            cookieString += ";domain=" + domain;
        }

        cookieString += ";expires=Thu, 01-Jan-1970 00:00:01 GMT";

        // Set the Cookie
        document.cookie = cookieString;
    }
}

/**
 * Sets a cookie with a serialized array.
 *
 * @param name a name for the cookie
 * @param value the value to store in the cookie
 * @param expires the cookie's lifetime
 * @param path the path in which to store the cookie
 * @param domain the domain for which the cookie is being saved
 * @param secure whether or not the cookie data should be secure
 */
function setArrayCookie(name, array, expires, path, domain, secure) {
    // Setup
    var delimiter = ",";
    var arrayString = "";

    // Serialize Array
    arrayString = array.join(delimiter);

    // Set the Cookie
    setCookie(name, arrayString, expires, path, domain, secure);
}

/**
 * Gets a cookie with a serialized array.
 *
 * @param name the name of the cookie to retrieve
 * @return the value of the requested cookie, or null if no cookie was found
 */
function getArrayCookie(name) {
    // Setup
    var array = null;
    var arrayString = new String("");

    // Retrieve Cookie
    arrayString = new String(getCookie(name));

    // Unserialize Array
    if(arrayString) {
        array = arrayString.split(",");
    }

    return array;
}


function processSurvey()
{
	var objElement = document.getElementById("hfNumItem");

	if(objElement != null)
	{
		var count = objElement.value;
		var survey_id = 0;
		var item_id = 0;
		var answer_type = "";
		var selected_option_id = 0;
		var input_text = "";
		var full_name = "";
		var result_group_no = 0;

		//Get Survey Id
		objElement = document.getElementById("hfSurveyId");

		if(objElement != null) survey_id = objElement.value;

		//Get Name
		objElement = document.getElementById("full_name");

		if(objElement != null) full_name = objElement.value;
		else full_name = "Anonymous";

		//Get Result Group No
		objElement = document.getElementById("hfResultGroupNo");

		if(objElement != null) result_group_no = objElement.value;
		else result_group_no = 1;

		for(var i=1; i <= count; i++)
		{

			selected_option_id = 0;
			item_id = 0;
			answer_type = "";
			input_text = "";

			//Get Item Id
			objElement = document.getElementById("hfItemId" + i);

			if(objElement != null)
			{
				item_id = objElement.value;
			}
			else
			{
				item_id = 0;
			}

			//Get Item Type
			objElement = document.getElementById("hfAnswerType" + i);

			if(objElement != null)
			{
				answer_type = objElement.value;
			}
			else
			{
				answer_type = "";
			}
			
			//Get Item Id
			objElement = document.getElementById("hfItemId" + i);
			if(objElement != null)	item_id = objElement.value;

			//Process Survey
			if(answer_type == "True/False")
			{
				//Find out which option was selected
				objElement = document.getElementById("rbList" + i + "_Yes");

				if(objElement != null)
				{
					if(objElement.checked) input_text = "True";
					else input_text = "False";
				}
				else
				{
					input_text = "False";
				}

			}
			else if(answer_type == "Multiple Choice")
			{
				//Find out how many choice does this survey item have
				objElement = document.getElementById("hfNumOption" + i);

				if(objElement != null)
				{
					var	mc_count = objElement.value;
					for(var x=1; x <= mc_count; x++)
					{
						objElement = document.getElementById("rbList" + i + "_" + x);

						if(objElement != null)
						{
							if(objElement.checked)
							{
								selected_option_id = objElement.value;
								break;
							}
						}
					}
				}
			}
			else //Short Answer
			{
				objElement = document.getElementById("txtItemText" + i);
				if(objElement != null)	input_text = objElement.value;
			}

			
			gBajax = createRequest()
			gBajax.open('get', root+'process_survey.php?survey_id=' + survey_id + '&answer_type=' + answer_type + '&item_id=' + item_id + '&input_text=' + input_text + '&selected_option_id=' + selected_option_id + '&full_name=' + full_name + '&result_group_no=' + result_group_no);
			gBajax.onreadystatechange = processSurveyResponse;
			gBajax.send(null);
		}
	}

	return false;
}

function processSurveyResponse() {

	if(gBajax.readyState == 4){
		// this is the content of the called page
        var response = gBajax.responseText;
       	//process the response
       	if( response == "success")
       	{
			var obj = document.getElementById("divSurvey");

			if(obj != null)
			{
				obj.style.display = "none";
			}

			obj = document.getElementById("divThankYou");

			if(obj != null)
			{
				obj.style.display = "";
			}
       	}
       	else
       	{
       		alert("Failed to submit survey result.\r\n" +
       			  "Please contact web team regarding this message.");
       	}
    }

}
