var VERSION = parseInt(navigator.appVersion);
var SOLD_BY;


// PDF editing section

var CURRENT_PAGE = 1;
var SELECTED_OBJECT;
var OBJECT;
var RESET;

function showHideGrid()
{
	$('#gridContainer').css('display', ($('#showGrid').attr('checked') ? '' : 'none'));
}

function setGrid(x_y)
{
	$('#gridContainer div.grid_' + x_y).each
	(
		function()
		{
			$(this).remove();
		}
	);

	var value = parseInt($('#grid_' + x_y).val()) - 1;
	var c = (x_y == 'x' ? $('#gridContainer').innerWidth() : $('#gridContainer').innerHeight()) / (value + 1) / 2;

	for(i = 0, v = 0; i < c; i++, v += (value * 2) + 2)
	{
		if(x_y == 'x')
			$('#gridContainer').append('<div class="grid_x" style="position:absolute; left:' + v + 'px; top:1px; border-left:1px solid #eee; border-right:1px solid #eee; width:' + value + 'px; height:' + $('#gridContainer').innerHeight() + 'px;"></div>');
			
		
		else
			$('#gridContainer').append('<div class="grid_y" style="position:absolute; left:1px; top:' + v + 'px; border-top:1px solid #eee; border-bottom:1px solid #eee; width:' + $('#gridContainer').innerWidth() + 'px; height:' + value + 'px;"></div>');
	}
}

function a(query)
{
	if(query)
	{
		var test = getQueryString(query);
		var type;

		for(i = 0; i < test['page'].length; i++)
		{
			setSelectedImage(test['page'][i]);

			if(test['image'][i])
				type = 'image';

			else if(test['text'][i].search('jqResize') >= 0)
				type = 'rectangle';

			else
				type = 'textbox';
				
			addTextBox(type, '', test['width'][i], test['height'][i], test['left'][i], test['top'][i], test['text'][i]);

			setFontAlign(test['align'][i]);
			setBorderWidth(test['borderWidth'][i]);

			SELECTED_OBJECT.css('border-color', test['border'][i]);
			SELECTED_OBJECT.css('font-family', test['family'][i]);
			SELECTED_OBJECT.css('font-size', test['size'][i]);
			SELECTED_OBJECT.css('font-style', test['italic'][i]);
			SELECTED_OBJECT.css('font-weight', test['bold'][i]);
			SELECTED_OBJECT.css('text-decoration', test['underline'][i]);
			SELECTED_OBJECT.css('color', test['color'][i]);
			SELECTED_OBJECT.css('background-color', test['background'][i]);
			SELECTED_OBJECT.css('opacity', test['opacity'][i]);
		}
	}
}

function getQueryString(queryString)
{
    var assoc = new Array();
    var keyValues = queryString.split('&');
    var newVal;
    var values;
    var key;
    var value;

    for(var i in keyValues)
    { 
        values = keyValues[i].split('=');
        key = values[0];
        value = values[1];
        
        if(key.substr(key.length - 2, 2) == '[]')
        {
        	newVal = key.substr(0, key.length - 2);
        	
        	if(!assoc[newVal])
        		assoc[newVal] = new Array();
        	
        	assoc[newVal][assoc[newVal].length] = unescape(value);
        }
        else
        	assoc[key] = unescape(value); 
    } 

    return assoc; 
}

function setBoldIcon()
{
	if(SELECTED_OBJECT)
	{
		var selected = (SELECTED_OBJECT.css('font-weight') == '700' || SELECTED_OBJECT.css('font-weight') == 'bold');
		
		setClass('bold', selected);
	}
}

function setBoldFont()
{
	if(SELECTED_OBJECT)
	{
		var value = (SELECTED_OBJECT.css('font-weight') == '700' || SELECTED_OBJECT.css('font-weight') == 'bold' ? 'normal' : 'bold');
	
		SELECTED_OBJECT.css('font-weight', value);
	}
}

function setItalicIcon()
{
	if(SELECTED_OBJECT)
	{
		var selected = (SELECTED_OBJECT.css('font-style') == 'italic');
		
		setClass('italic', selected);
	}
}

function setItalicFont()
{
	if(SELECTED_OBJECT)
	{
		var value = (SELECTED_OBJECT.css('font-style') == 'italic' ? 'normal' : 'italic');
	
		SELECTED_OBJECT.css('font-style', value);
	}
}

function setUnderlineIcon()
{
	if(SELECTED_OBJECT)
	{
		var selected = (SELECTED_OBJECT.css('text-decoration') == 'underline');
		
		setClass('underline', selected);
	}
}

function setUnderlineFont()
{
	if(SELECTED_OBJECT)
	{
		var value = (SELECTED_OBJECT.css('text-decoration') == 'underline' ? 'none' : 'underline');
	
		SELECTED_OBJECT.css('text-decoration', value);
	}
}

function setAlignIcons()
{
	setLeftIcon();
	setRightIcon();
	setCenterIcon();
	setJustifyIcon();
}

function setLeftIcon()
{
	if(SELECTED_OBJECT)
	{
		var selected = (SELECTED_OBJECT.css('text-align') == 'left');
		
		setClass('leftAlign', selected);
	}
}

function setRightIcon()
{
	if(SELECTED_OBJECT)
	{
		var selected = (SELECTED_OBJECT.css('text-align') == 'right');
		
		setClass('rightAlign', selected);
	}
}

function setCenterIcon()
{
	if(SELECTED_OBJECT)
	{
		var selected = (SELECTED_OBJECT.css('text-align') == 'center');
		
		setClass('centerAlign', selected);
	}
}

function setJustifyIcon()
{
	if(SELECTED_OBJECT)
	{
		var selected = (SELECTED_OBJECT.css('text-align') == 'justify');
		
		setClass('justifyAlign', selected);
	}
}

function setFontAlign(value)
{
	if(SELECTED_OBJECT)
		SELECTED_OBJECT.css('text-align', value);
}

function setButtonFamily()
{
	if(SELECTED_OBJECT)
		$('#family').val(SELECTED_OBJECT.css('font-family'));
}

function setButtonSize()
{
	if(SELECTED_OBJECT)
		$('#size').val(SELECTED_OBJECT.css('font-size'));
}

function setButtonColor()
{
	if(SELECTED_OBJECT)
	{
		$('#fontColor').css('backgroundColor', SELECTED_OBJECT.css('color'));
		$('#backgroundColor').css('background-color', SELECTED_OBJECT.css('background-color'));
		$('#backgroundColor').css('background-image', $('#backgroundColor').css('background-color') == 'transparent' ? 'url("/members/images/colorpicker_transparent.png")' : 'none');
		$('#borderColor').css('background-color', SELECTED_OBJECT.css('border-color'));
	}
}

function setOpacityField()
{
	if(SELECTED_OBJECT)
		$('#opacity').val(SELECTED_OBJECT.css('opacity') * 100);
}

function setHorizontalGuide()
{
	if(SELECTED_OBJECT)
	{
		$('#horizontal_guide').css('left', SELECTED_OBJECT.parent().css('left'));
		$('#horizontal_guide').css('width', SELECTED_OBJECT.parent().innerWidth());
		$('#horizontal_guide').css('display', '');
	}
}

function setVerticalGuide()
{
	if(SELECTED_OBJECT)
	{
		$('#vertical_guide').css('top', SELECTED_OBJECT.parent().css('top'));
		$('#vertical_guide').css('height', SELECTED_OBJECT.parent().innerHeight());
		$('#vertical_guide').css('display', '');
	}
}

function setBWidth()
{
	if(SELECTED_OBJECT)
		$('#borderWidth').val(SELECTED_OBJECT.css('border-width'));
}

function alignBox(align)
{
	if(SELECTED_OBJECT)
		SELECTED_OBJECT.parent().alignBox(align);
}

function setButtonDisabled(textbox)
{
	var status = (textbox === undefined);
	var t = (status || !textbox);

	$('#family').attr('disabled', t);
	$('#size').attr('disabled', t);
	
	$('#opacity').attr('disabled', status);
	$('#upArrow').attr('disabled', status);
	$('#downArrow').attr('disabled', status);
	$('#borderWidth').attr('disabled', status);
	
	$('.formatButtons').css('opacity', (t ? 0.5 : 1));
	$('.formatAllButtons').css('opacity', (!status ? 1 : 0.5));
	
	if(status == true)
		setDefaults();
}

function setDefaults()
{
	$('#family').val('Arial');
	$('#size').val('12');
	$('#fontColor').css('background-color', '#000000');
	$('#backgroundColor').css('background-color', 'transparent');
	$('#backgroundColor').css('background-image', 'url("/members/images/colorpicker_transparent.png")');
	$('#borderColor').css('background-color', '#000000');
	$('#borderWidth').val('0');
	$('#opacity').val('100');
	
	setClass('bold', false);
	setClass('italic', false);
	setClass('underline', false);
	setClass('leftAlign', false);
	setClass('rightAlign', false);
	setClass('centerAlign', false);
	setClass('justifyAlign', false);
}

function setClass(id, selected)
{
	$('#' + id).removeClass();
	$('#' + id).addClass((selected ? 'selectedButton' : 'normalButton'));	
}

function cloneObject()
{
	if(SELECTED_OBJECT)
	{
		var newObject = SELECTED_OBJECT.parent().clone(true);
		
		newObject.css('left', '0');
		newObject.css('top', '0');
	
		$('#bodyDiv_' + CURRENT_PAGE).append(newObject);
		
		
		// Change focus to the newly cloned object
		
		SELECTED_OBJECT.delayDisable();
		
		SELECTED_OBJECT = jQuery('.draggable', newObject);
		SELECTED_OBJECT.focus();
	}
}

function setBorderWidth(value)
{
	if(SELECTED_OBJECT)
	{
		SELECTED_OBJECT.css('border-width', value);
		
		if(jQuery('div', SELECTED_OBJECT).size() > 0)
		{
			SELECTED_OBJECT.css('width', SELECTED_OBJECT.width() + 'px');
			SELECTED_OBJECT.css('height', SELECTED_OBJECT.height() + 'px');
			SELECTED_OBJECT.parent().css('width', (SELECTED_OBJECT.outerWidth()) + 'px');
			SELECTED_OBJECT.parent().css('height', (SELECTED_OBJECT.outerHeight()) + 'px');
			SELECTED_OBJECT.parent().css('min-width', (parseInt(value) * 2 + 15) + 'px');
			SELECTED_OBJECT.parent().css('min-height', (parseInt(value) * 2 + 15) + 'px');
		}
	}
}

function addTextBox(type, file, width, height, left, top, text)
{
	setDefaults();
	
	if(type == 'rectangle' && (!width || !height))
	{
		width = 150;
		height = 100;
	}
	
	if(!left)
		left = 0;
		
	if(!top)
		top = 0;

	if(!text)
	{
		text = '';
	
		if(type == 'textbox')
			text = 'Double-click to Edit...';

		else
		{
			if(type == 'image')
				text += '<img src="' + file + '" />';

			text += '<div class="jqResize"></div>';
		}
	}
		
	$('#bodyDiv_' + CURRENT_PAGE).append('<div class="borderContainer"><div class="draggable ' + type + '" tabindex="-1">' + text + '</div></div>');
	
	if(type == 'textbox')
	{
		var newTextbox = $('#bodyDiv_' + CURRENT_PAGE + ' div:last');
		var newTextboxParent = newTextbox.parent();
		
		setBoldIcon();
		setItalicIcon();
		setClass('leftAlign', true);
		
		newTextboxParent.jqResize('.jqResize');
		newTextbox.attr('contentEditable', 'true');
	}
	else
	{
		var newTextbox = $('#bodyDiv_' + CURRENT_PAGE + ' div:last').parent();
		var newTextboxParent = newTextbox.parent();

		newTextboxParent.jqResize('.jqResize');
		newTextbox.attr('contentEditable', 'false');
	}
	
	if(width && height)
	{
		newTextboxParent.css('width', width + 'px');
		newTextboxParent.css('height', height + 'px');
	}

	
	// Remove current SELECTED_OBJECT

	if(SELECTED_OBJECT)
		SELECTED_OBJECT.delayDisable();

	newTextboxParent.jqDrag();
	

	// Set location coordinates for new object

	newTextboxParent.css('left', left + 'px');
	newTextboxParent.css('top', top + 'px');
	
	$('#location_x').val(left);
	$('#location_y').val(top);

	
	//newTextbox.disableTextSelect();
	
	newTextbox.mousehold
	(
		function()
		{
			if(OBJECT)
				clearTimeout(OBJECT);
		}
	);
	
	newTextbox.bind
	(
		'click',
		{ type:type },

		function(e)
		{
			RESET = false;	// Override reset flag if clicked on textbox / rectangle
			
			if(!SELECTED_OBJECT || !SELECTED_OBJECT.equals($(this)))
			{
				if(SELECTED_OBJECT)
					SELECTED_OBJECT.delayDisable();
					
				var selectedObjectParent = $(this).parent();
					
					
				// Set location coordinates for selected object

				$('#location_x').val(parseInt(selectedObjectParent.css('left')));
				$('#location_y').val(parseInt(selectedObjectParent.css('top')));
				
				selectedObjectParent.css('border', '1px solid red');
				
				SELECTED_OBJECT = $(this);

				if(e.data.type != 'textbox')
					setButtonDisabled(false);
				
				else
				{
					setButtonDisabled(true);
					setButtonSize();
					setButtonFamily();
					setBoldIcon();
					setItalicIcon();
					setUnderlineIcon();
					setAlignIcons();
				}

				setButtonColor();				
				setOpacityField();
				setBWidth();
				setHorizontalGuide();
				setVerticalGuide();
			}
			
			$(this).focus();				
		}
	);

	newTextbox.mouseover
	(
		function()
		{
			$(this).css('cursor', ($(this).attr('contentEditable') == 'true' || $(this).attr('contentEditable') == true ? 'text' : 'move'));
		}
	);
	
	if(type == 'textbox')
	{
		newTextbox.dblclick
		(
			function()
			{
				$(this).attr('contentEditable', 'true');
				$(this).css('cursor', 'text');
			}
		);
	}
	
	newTextbox.blur
	(
		function()
		{
			RESET = true;
			
			objCopy = $(this);
			
			OBJECT = setTimeout('objCopy.delayDisable()', 175);
		}
	);
	
	SELECTED_OBJECT = newTextbox;
	SELECTED_OBJECT.focus();
	
	setButtonDisabled((type == 'textbox'));
	setHorizontalGuide();
	setVerticalGuide();
}

function setSelectedImage(index)
{
	if(index != CURRENT_PAGE)
	{
		$('#thumb_' + CURRENT_PAGE).removeClass();
		$('#thumb_' + CURRENT_PAGE).addClass('normalImage');
		$('#bodyTag_' + CURRENT_PAGE).toggle();
		$('#bodyDiv_' + CURRENT_PAGE).toggle();

		CURRENT_PAGE = index;

		$('#thumb_' + CURRENT_PAGE).removeClass();
		$('#thumb_' + CURRENT_PAGE).addClass('selectedImage');
		$('#bodyTag_' + CURRENT_PAGE).toggle();
		$('#bodyDiv_' + CURRENT_PAGE).toggle();
	}
}

// End PDF editing section


function appendRow(table, row, element)
{
	if(!element)
		element = 'tr';
		
	if(!row)
		row = 0;	// Specify which row will be cloned
		
	$(table).append($(table + ' ' + element + ':eq(' + row + ')').clone());
	$(table + ' ' + element + ':last').css('display', '');
}

function indexAt(what, a)
{
	var foundIndex = -1;
	var i = 0;

	while(i < a.length && foundIndex < 0)
	{
		if(a[i].value == what)
			foundIndex = i;

		i++;
	}

	return foundIndex;
}

function calculateSub()
{
	var total = 0;
	var subTotal = 0;

	$("input[name='qty[]']").each
	(
		function(index)
		{
			subTotal = $(this).val() * $("input[name='ppi[]']")[index].value
			$("input[name='subTotal[]']")[index].value = subTotal;

			total += subTotal;

		}
	);

	$("#total").val(total);
}

function bindElements()
{
	$("select").each
	(
		function(index)
		{
			$(this).bind
			(
				'change',
				{ index: index },
				
				function(e)
				{
					if(!$(this).val())
					{
						$("input[name='ppi[]']")[e.data.index].value = 0;
						calculateSub();
					}
					else
					{
						var Params = {};
						Params.type = "GET";
						Params.url = "/members/getCost.php?rewardid=" + $(this).val();
						Params.dataType = "json";

						Params.success = function(data)
						{
							if(data)
							{
								$.each
								(
									data,

									function(ky, val)
									{
										$("input[name='ppi[]']")[e.data.index].value = val;
										
										calculateSub();										
									}
								);
							}		
						};

						//Params.error = function(x, y, z) { alert(x.responseText); };

						$.ajax(Params);
					}
				}
			);
		}
	);
}

function populatePolicyInfo(JSONObj)
{
	var index;
	var permissionIDs = document.form.elements['permissionIDs[]'];

	$("input[name='permissionIDs[]']").each
	(
		function(index)
		{
			$(this).removeAttr('disabled');
			$(this).removeAttr('checked');
			$('#companyAccess_' + $(this).val()).removeAttr('disabled');
			$('#companyAccessAdd_' + $(this).val()).removeAttr('disabled');
			$('#companyAccessRemove_' + $(this).val()).removeAttr('disabled');
			$('#permissionIDs_' + $(this).val()).removeAttr('disabled');
			$('#permissionIDsAdd_' + $(this).val()).removeAttr('disabled');
			$('#permissionIDsRemove_' + $(this).val()).removeAttr('disabled');
			$('#companyAccess_' + $(this).val()).length = 0;
			$('#permissionIDs_' + $(this).val()).length = 0;
			
			$('#companyAccess_' + $(this).val() + '_div input').each
			(
				function()
				{
					$(this).remove();
				}
			);
			
			$('#permissionIDs_' + $(this).val() + '_div input').each
			(
				function()
				{
					$(this).remove();
				}
			);
			
			showHideLayer('box' + $(this).val(), '', index);			
		}
	);
	
	
	// Repopulate form based on policy JSON object
	
	if(JSONObj)
	{
		$.each
		(
			JSONObj,

			function(ky, val)
			{
				for(i = 0; i < val.companyIDs.length; i++)
				{
					values = val.companyIDs[i].split('_');

					addOption('companyAccess_' + ky, values[1], values[0]);
				}

				for(i = 0; i < val.groupIDs.length; i++)
				{
					values = val.groupIDs[i].split('_');

					addOption('permissionIDs_' + ky, values[1], values[0]);
				}
				
				$('#companyAccess_' + ky).attr('disabled', (val.lockPermissions == 1));
				$('#companyAccessAdd_' + ky).attr('disabled', (val.lockPermissions == 1));
				$('#companyAccessRemove_' + ky).attr('disabled', (val.lockPermissions == 1));
				$('#permissionIDs_' + ky).attr('disabled', (val.lockPermissions == 1));
				$('#permissionIDsAdd_' + ky).attr('disabled', (val.lockPermissions == 1));
				$('#permissionIDsRemove_' + ky).attr('disabled', (val.lockPermissions == 1));
				
				index = indexAt(ky, permissionIDs);
				
				if(index >= 0)
				{
					//$('#permissionIDs')[index].disabled = (val.lockPermissions == 1);
					//$('#permissionIDs')[index].checked = (val.checked == 1);
					permissionIDs[index].disabled = (val.lockPermissions == 1);
					permissionIDs[index].checked = (val.checked == 1);
					
					showHideLayer('box' + ky, '', index);
				}
			}
		);
	}
}

function setProjectOptions()
{
	var value = document.form.status.value;
	var reasonSection = document.getElementById('reasonSection');
	var completionSection = document.getElementById('completionSection');
	
	if(reasonSection && completionSection)
	{
		reasonSection.style.display = (value == '4' ? '' : 'none');
		completionSection.style.display = (value == '3' ? '' : 'none');
	
		document.form.targetStartDate.disabled = (value == '5');
		document.form.targetEndDate.disabled = (value == '5');
		document.form.bidDate.disabled = (value == '5');
		document.form.hour.disabled = (value == '5');
		document.form.minute.disabled = (value == '5');
		document.form.ampm.disabled = (value == '5');
		document.form.projectEstimator.disabled = (value == '5');
		document.form.noDisplayCalendar.disabled = (value == '5');
		document.form.invitational.disabled = (value == '5');
	}
}

function printit()
{
	if(window.print)
		window.print();

	else
	{
		var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
		
		document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
		WebBrowser1.ExecWB(6, 2);
	}
}

function addTime()
{
	var date = document.getElementById('startDate').value;
	var startHour = document.getElementById('startHour').value;
	var startMinute = document.getElementById('startMinute').value;
	var startAmPm = document.getElementById('startAmPm').value;
	var endHour = document.getElementById('endHour').value;
	var endMinute = document.getElementById('endMinute').value;
	var endAmPm = document.getElementById('endAmPm').value;

	var value = date + " @ " + startHour + ":" + startMinute + " " + startAmPm + " - " + endHour + ":" + endMinute + " " + endAmPm;
	
	if(opener.addOption('times', value, value))
		alert('Time successfully added!');
}

function setAllChecked(elements)
{
	for(i = 0; i < elements.length; i++)
	{
		$('#' + elements[i] + ' option').each
		(
			function()
			{
				$(this).attr('selected', 'selected');
			}
		);
	}
}

function optionValueIndexOf(options, value)
{
	var index = -1;
	
	for(var i = 0; i < options.length && index == -1; i++)
	{
		if(options[i].value == value)
			index = i;
	}

	return index;
}

function selectOptions(element, field)
{
	var checks = document.getElementsByName(element);
	var values;
	var objOption;
	var sortedArray = new Array();
	var added = false;

	for(i = 0; i < checks.length; i++)
	{
		if(checks[i].checked)
		{
			values = checks[i].value.split('_');

			if(opener.addOption(field, values[1], values[0]))
				added = true;

			checks[i].checked = false;
		}
	}

	if(added)
		alert('Selections add successfuully!');

	//window.close();
}

function populateForm(companyID)
{
	$.getJSON
	(
		"/members/getCompanyInfo.php?company=" + companyID,
		
		function(data)
		{
			populateCompanyInfo(data);
			
			$.unblockUI();
		}
	);
	
	$.blockUI
	(
		{
			message: '<img src="/members/images/busy.gif" /> Please wait...',
			css: { padding:10 }
		}
	);
	
	document.form.email.value = "";
	

	// Assign phone & fax info to constants as default values

	PHONE = document.form.phone.value;
	FAX = document.form.fax.value;
}

function populateCompanyInfo(JSONObj)
{
	var users = document.getElementById('users');
	
	
	// Remove all options except for "Select User"
	
	users.length = 1;
	
	$.each
	(
		JSONObj,
		
		function(ky, val)
		{
			users.options[users.options.length] = new Option(val, ky);
		}
	);
}

function populateUserInfo(JSONObj)
{
	var phone = (JSONObj.phone ? JSONObj.phone : PHONE);
	var fax = (JSONObj.fax ? JSONObj.fax : FAX);
	
	$("#email").val(JSONObj.email);
	$("#phone").val(phone);
	$("#fax").val(fax);
}

function loadUserInfo(webUserID)
{
	if(webUserID > 0)
	{
		$.getJSON
		(
			"/members/getUserInfo.php?userid=" + webUserID,
			
			function(data)
			{
				populateUserInfo(data);
			}
		);
	}	
	else
	{
		$('#phone').val(PHONE);
		$('#fax').val(FAX);
		$('#email').val('');
	}
}

function addOption(element, textValue, valueValue)
{
	var documentOptions = document.getElementById(element);
	var div = document.getElementById(element + "_div");
	var hiddenElement;
	var added = false;

	if(documentOptions)
	{
		if(optionValueIndexOf(documentOptions, valueValue) == -1)
		{
			documentOptions.options[documentOptions.options.length] = new Option(textValue, valueValue);

			hiddenElement = document.createElement("input");

			hiddenElement.setAttribute("type", "hidden");
			hiddenElement.setAttribute("name", element + "[]");
			hiddenElement.setAttribute("value", valueValue);
			hiddenElement.setAttribute("id", element + "_" + length);

			if(div.appendChild(hiddenElement))
				added = true;
		}
	}
	
	return added;
}

function removeOptions(option)
{

/*
	$('#' + option).each
	(
		function(index)
		{
			//alert('Yes ' + index);
			
			//if($(this).attr('selected'))
			//{
				$(this).remove();
				$('#' + option + '_' + index).remove();
			//}
		}
	);
	
*/
	
	var documentOptions = document.getElementById(option);
	var hiddenElement;
	var optionValue;
	
	var x = 0;
	
	for(i = 0, x = 0; i < documentOptions.options.length; i++, x++)
	{
		if(documentOptions.options[i].selected)
		{
			optionValue = documentOptions.value;
			documentOptions.remove(i);
			
			hiddenElement = document.getElementById(option + "_" + x);
			
			if(hiddenElement)
				hiddenElement.parentNode.removeChild(hiddenElement);
			
			i--;
		}
	}
}


// Event scheduling section

function setTimeSection()
{
	var eventType = document.getElementById('eventType');
	var value = eventType.value;
	
	var timeSection = document.getElementById('timeSection');
	var durationSection = document.getElementById('durationSection');

	timeSection.style.display = (value > 0 ? '' : 'none');
	durationSection.style.display = (value > 0 ? '' : 'none');
}

function setRecurringTimesSection(repeatOption)
{
	var value = $('#recurres').val();
	
	$('#weeklyOptions').css('display', (value == 2 ? '' : 'none'));
	$('#monthlyOptions').css('display', (value == 3 ? '' : 'none'));
	$('#specifiedOptions').css('display', (value == 5 ? '' : 'none'));
	$('#recurringEndsSection').css('display', (value > 0 && value < 5 ? '' : 'none'));
	$('#recurringTimesSection').css('display', (value == 2 || value == 3 || value == 5 ? '' : 'none'));
	$('#exceptionSection').css('display', (value > 0 ? '' : 'none'));

	printValidOptions(repeatOption);
	setRecurringEndsSection();
}

function setRecurringEndsSection()
{
	var recurringEnds = document.getElementById('recurringEnds');
	var recurringEndsSection = document.getElementById('recurringEndsSection');
	var endDateSection = document.getElementById('endDateSection');
	var repeatNumberSection = document.getElementById('repeatNumberSection');

	var value = recurringEnds.value;

	endDateSection.style.display = (recurringEndsSection.style.display == '' && value == 1 ? '' : 'none');
	repeatNumberSection.style.display = (recurringEndsSection.style.display == '' && value == 2 ? '' : 'none');
}

function printValidOptions(repeatOption)
{
	var possibleOptions = new Array('None', 'Days', 'Weeks', 'Months', 'Years');

	var recurres = document.getElementById('recurres');
	var repeatOptions = document.getElementById('repeatOptions');

	repeatOptions.length = 0;

	for(i = recurres.value; i <= 4; i++)
	{
		repeatOptions.options[repeatOptions.length] = new Option(possibleOptions[i], i);
		
		if(i == repeatOption)
			repeatOptions.options[repeatOptions.length - 1].selected = true;
	}
}

// End event scheduling


function showHideLayer(boxID, btnID, id)
{
	var box = document.getElementById(boxID);
	var checkid = document.getElementsByName('permissionIDs[]');
	
	if(checkid[id])
		var isChecked = checkid[id].checked;
		
	if(box)
	{
		if(btnID)
			var boxbtn = document.getElementById(btnID);

		if(!isChecked)
		{
			box.style.display = 'none';

			if(btnID)
			{
				boxbtn.src = '/members/images/expand.gif';
				boxbtn.setAttribute('alt', 'Expand');
			}
		}
		else
		{
			box.style.display = '';

			if(btnID)
			{
				boxbtn.src = '/members/images/collapse.gif';
				boxbtn.setAttribute('alt', 'Collapse');
			}
		}
	}
}

function openForm($link, $width, $height, $window)
{
	var x = window.open($link,  $window, 'width=' + $width + ', height=' + $height + ', scrollbars=1, resizable=1');

	if(x.opener == null)
		x.opener = self;
}

function confirmSubmit(message)
{
	if(!message)
		message = "This action can not be undone! Continue?";

	var agree = confirm(message);

	return(agree ? true : false);
}

function setRepresentative(name, id)
{
	var formInfo = self.opener.window.document.form;

	formInfo.rep.value = name;
	formInfo.representative.value = id;

	window.close();
}

function setSpecifier(id, business, name)
{
	var formInfo = self.opener.window.document.form;

	if(id)
	{
		eval("formInfo.businessList" + id + ".value = business");
		eval("formInfo.businessID" + id + ".value = name");
	}
	else
	{
		formInfo.soldBy.value = business;
		formInfo.company.value = name;
		formInfo.calculate.disabled = true;
		formInfo.soldAmount.disabled = false;
	}

	window.close();
}

function setAwarded(userid, companyName)
{
	var formInfo = self.opener.window.document.form;

	formInfo.userid.value = userid;

	if(companyName)
	{
		formInfo.companyName.value = companyName;
		formInfo.companyName2.value = companyName;

		if(formInfo.affiliateID.value != '' && formInfo.userid != '')
		{
			//formInfo.calculate.disabled = false;
			formInfo.soldAmount.disabled = false;
		}
	}

	window.close();
}

function movePDF(company, affiliateID, subOf, folder)
{
	var formInfo = self.opener.window.document.form;

	if(company)
		formInfo.company.value = company;

	if(affiliateID > 0)
		formInfo.affiliateID.value = affiliateID;

	if(subOf)
		formInfo.subOf.value = subOf;

	if(folder)
		formInfo.parentName.value = folder;

	if(formInfo.calculate)
	{
		if(affiliateID > 0 && formInfo.userid.value)
		{
			formInfo.soldAmount.disabled = false;
			formInfo.calculate.disabled = false;
		}
	}

	window.close();
}

function moveValues(fields, values)
{
	var formInfo = self.opener.window.document;
	var element;
	
	for(i = 0; i < fields.length; i++)
	{
		element = formInfo.getElementById(fields[i]);
		
		if(element)
			element.value = values[i];
	}

	window.close();
}

function validateReportForm()
{
	if($('input[name="option[]"]:checked').size() == 0)
	{
		alert('You must select at least 1 element to display!');
	
		return false;
	}
}

function test(jqueryObj)
{
	SOLD_BY = jqueryObj;
}

function test2(company, companyID)
{
	var soldBy = jQuery("input[name='soldBy[]']", SOLD_BY);
	var soldByName = jQuery("input[name='soldByName[]']", SOLD_BY);
	
	soldBy.val(companyID);
	soldByName.val(company);
}