﻿
// DocumentFormatsList control is a mixed-style control, using the best practices of JScript programming
// combined to server-side completeness as well.

GlobalStatesList = []; // expected to be set on server-side
GlobalInsuranceTypesList = []; // expected to be set on server-side
GlobalWebSiteAddress = '/';
UnspecifiedId = 0; // const
SwitchDocumentFormatsParentPrefix = 'switchDocumentFormatsParent';

function DocumentFormatsList (viewStateFieldId, boxId) { 	
	registerVirtualObject(viewStateFieldId, this);
    
	this.viewStateField = document.getElementById(viewStateFieldId);
	this.box = document.getElementById(boxId);
    
	this.loadViewState();
	this.loadPresentation();
}

function DocumentFormatsList_Prototype() {

	this.loadViewState = function() {
		this.viewState = Sys.Serialization.JavaScriptSerializer.deserialize(this.viewStateField.value);
		this.SelectedDocumentFormats = this.viewState.SelectedDocumentFormats;
		this.SelectedDocumentFormatsChanged = new Event();
		this.SelectedDocumentFormatsSet = new Event();
		var _this = this;
		Sys.UI.DomEvent.addHandler(theForm, 'submit', function() {
			_this.saveViewState();
		});
	}

	this.saveViewState = function() {
		this.viewStateField.value = Sys.Serialization.JavaScriptSerializer.serialize(this.viewState);
	}

	this.loadPresentation = function() {
		this.createMainVisualBoxes();

		this.insuranceTypes = GlobalInsuranceTypesList;
//		this.viewState.InsuranceTypes = null; // not needed to serialize and send it back to server.
		this.insuranceTypeBoxes = new Object();
		this.documentCheckBoxes = new Object();
		for(var i = 0; i < this.insuranceTypes.length; i++) {
			var insuranceType = this.insuranceTypes[i];

			var insuranceTypeBox = this.createInsuranceTypeBox(insuranceType);
			if(insuranceType.Carriers.length > 0) {
				var carriersGroups = this.createCarriersGroups(insuranceTypeBox);
				var lengthToDetermineColumn = (insuranceType.Carriers.length > 9 ? insuranceType.Carriers.length : 9);
				for(var j = 0; j < insuranceType.Carriers.length; j++) {
					var carrier = insuranceType.Carriers[j];
					this.addCarrierBox(carriersGroups[Math.floor((j / lengthToDetermineColumn) * this.viewState.ColumnsNumber)], carrier);
				}
			}
			else {
				this.addNoDocumentsMessage(insuranceTypeBox);
			}
		}
		if(this.viewState.IsInsuranceTypeSelectorVisible) {
			this.createInsuranceTypeSelector();
		}
		if(this.viewState.EnableStateFilter) {
			this.createStateFilter();
			this.applyStateFilter();
		}
		if(typeof (this.insuranceTypeBoxes[this.viewState.SelectedInsuranceTypeId]) != 'undefined') {
			this.showInsuranceTypeBox(this.viewState.SelectedInsuranceTypeId);
		}
		else {
			for(var key in this.viewState.insuranceTypeBoxes) {
				this.showInsuranceTypeBox(key);
				break;
			}
		}
		if(typeof (this.onLoaded) == 'function') {
			this.onLoaded();
		}
	}

	this.createMainVisualBoxes = function() {
		this.box.className = 'documentFormatsList';
		this.boxControls = document.createElement('div');
		this.boxControls.className = 'boxControls';
		this.box.appendChild(this.boxControls);
	}

	this.createInsuranceTypeBox = function(insuranceType) {
		var insuranceTypeBox = document.createElement('div');
		if(this.viewState.IsInsuranceTypeSelectorVisible || this.viewState.ShowDocumentsListInSeparateBox) {
			insuranceTypeBox.className = 'insuranceTypeBox';
		}
		insuranceTypeBox.style.clear = 'both';
		insuranceTypeBox.style.display = 'none';
		insuranceTypeBox.style.marginTop = '4px';
		this.box.appendChild(insuranceTypeBox);

		this.insuranceTypeBoxes[insuranceType.Id] = insuranceTypeBox;
		return insuranceTypeBox;
	}

	this.createCarriersGroups = function(insuranceTypeBox) {
		var carriersGroups = new Array();
		for(var k = 0; k < this.viewState.ColumnsNumber; k++) {
			var carriersGroup = document.createElement('div');
			carriersGroup.className = 'carriers-column';
			insuranceTypeBox.appendChild(carriersGroup);
			carriersGroups[k] = carriersGroup;
		}
		return carriersGroups;
	}

	this.addCarrierBox = function(insuranceTypeBox, carrier) {

		var documentFormatsParentElement = insuranceTypeBox;

		if(carrier.IsOnline || carrier.DocumentFormats.length > 1) {
			if(typeof (this.createdCarrierIndex) == 'undefined') this.createdCarrierIndex = 0;
			this.createdCarrierIndex++;

			var carrierHeaderElement = document.createElement('div');
			var baseClassName = carrier.IsOnline ? 'onlineCarrierHeaderElement' : 'carrierHeaderElement';
			carrierHeaderElement.className = baseClassName;
			carrierHeaderElement.appendChild(document.createTextNode(carrier.Name));

			documentFormatsParentElement = document.createElement('div');
			documentFormatsParentElement.className = 'carrierBox';
			documentFormatsParentElement.style.display = 'none';
			documentFormatsParentElement.isCarrierDocumentsGroup = true;
			documentFormatsParentElement.carrierHeaderElement = carrierHeaderElement;
			documentFormatsParentElement.id = 'documentFormatsParentElement' + this.createdCarrierIndex;
			insuranceTypeBox.appendChild(carrierHeaderElement);
			insuranceTypeBox.appendChild(documentFormatsParentElement);

			var _this = this;
			carrierHeaderElement.onclick = function() {
				var shouldBeExpanded = (documentFormatsParentElement.style.display == 'none');
				documentFormatsParentElement.style.display = (shouldBeExpanded) ? '' : 'none';
				carrierHeaderElement.className = baseClassName + (shouldBeExpanded ? (' ' + baseClassName + '-expanded') : '');
				if(shouldBeExpanded == true) {
					Array.add(_this.viewState.ExpandedCarrierBoxes, carrier.Id);
				}
				else {
					Array.remove(_this.viewState.ExpandedCarrierBoxes, carrier.Id);
				}
			}
			this[SwitchDocumentFormatsParentPrefix + documentFormatsParentElement.id] = carrierHeaderElement.onclick;

			if(Array.contains(this.viewState.ExpandedCarrierBoxes, carrier.Id) ||
				this.insuranceTypes[0].Carriers.length == 1) {
				carrierHeaderElement.onclick();
			}
		}

		for(var i = 0; i < carrier.DocumentFormats.length; i++) {
			var documentFormat = carrier.DocumentFormats[i];
			this.addDocumentFormatCheckBox(documentFormatsParentElement, documentFormat);
		}
	}

	this.addDocumentFormatCheckBox = function(carrierBox, documentFormat) {
		var checkBox = new ManagedCheckBox(carrierBox, documentFormat.Name.replace(/\&/, '&amp;').replace(' - ', ' &ndash; '));
		checkBox.SetChecked(Array.contains(this.viewState.SelectedDocumentFormats, documentFormat.Id));
		checkBox.associatedDocumentFormat = documentFormat;
		var _this = this;
		checkBox.CheckedChanged.addHandler(function() {
			var currentListContainsItem = Array.contains(_this.viewState.SelectedDocumentFormats, documentFormat.Id);
			if(checkBox.Checked == true) {
				if(currentListContainsItem == false) {
					Array.add(_this.viewState.SelectedDocumentFormats, documentFormat.Id);
				}
				if(checkBox.parent.style.display == 'none') {
					_this[SwitchDocumentFormatsParentPrefix + checkBox.parent.id]();
				}
			}
			else {
				if(currentListContainsItem == true) {
					Array.remove(_this.viewState.SelectedDocumentFormats, documentFormat.Id);
				}
			}
			_this.SelectedDocumentFormatsChanged.invokeHandlers();
		});
		if(typeof (this.documentCheckBoxes[documentFormat.Id]) == 'undefined') {
			this.documentCheckBoxes[documentFormat.Id] = [];
		}
		Array.add(this.documentCheckBoxes[documentFormat.Id], checkBox);
	}

	this.addNoDocumentsMessage = function(insuranceTypeBox) {
		insuranceTypeBox.innerHTML = 'There are no document formats for this insurance line.';
	}

	this.getInsuranceTypeById = function(id) {
		for(var j = 0; j < this.insuranceTypes.length; j++) {
			var insuranceType = this.insuranceTypes[j];
			if(insuranceType.Id == id) {
				return insuranceType;
			}
		}
		alert('Could not find insurance type with specified id (' + id + ').');
	}

	this.createInsuranceTypeSelector = function() {

		var _this = this;
		var insuranceTypeOptions = new Array();
		for(var idx = 0; idx < this.insuranceTypes.length; idx++) {
			var insuranceType = this.insuranceTypes[idx];
			var option = new ManagedSelectOption(insuranceType.Name, insuranceType.Id);
			option.IsSelected = (insuranceType.Id == this.viewState.SelectedInsuranceTypeId);
			if(insuranceType.Carriers.length == 0) {
				option.CssClass = 'option-disabled';
			}
			option.Selected.addHandler(function(eventArgs) {
				_this.hideAllInsuranceTypeBoxes();
				_this.showInsuranceTypeBox(eventArgs.Option.Value);
				_this.viewState.SelectedInsuranceTypeId = eventArgs.Option.Value;
			});
			Array.add(insuranceTypeOptions, option);
		}

		this.insuranceTypeSelector = new ManagedSelect(this.boxControls, this.viewState.InsuranceTypeSelectorLabel, insuranceTypeOptions);
		this.viewState.InsuranceTypeSelectorLabel = null; // not needed to go to server again

		var linkToInsuranceTypes = document.createElement('a');
		linkToInsuranceTypes.href = GlobalWebSiteAddress + 'Accounting/InsuranceType/InsuranceTypes.aspx';
		linkToInsuranceTypes.innerHTML = 'Edit…';
		linkToInsuranceTypes.title = 'Edit insurance types list';
		linkToInsuranceTypes.style.position = 'relative';
		linkToInsuranceTypes.style.lineHeight = '24px';
		//linkToInsuranceTypes.style.bottom = '3px';
		linkToInsuranceTypes.style.marginLeft = '5px';
		linkToInsuranceTypes.style.marginRight = '32px';
		linkToInsuranceTypes.style.styleFloat = 'left'; //styleFloat only for IE
		linkToInsuranceTypes.style.cssFloat = 'left';
		this.boxControls.appendChild(linkToInsuranceTypes);

		this.insuranceTypeSelector.box.style.width = 'auto';
		this.insuranceTypeSelector.box.style.display = 'inline';
		this.insuranceTypeSelector.box.style.styleFloat = 'left'; //styleFloat only for IE
		this.insuranceTypeSelector.box.style.cssFloat = 'left';
		this.insuranceTypeSelector.box.style.clear = 'none';
	}

	this.createStateFilter = function() {
		var _this = this;
		var handlerForSelectedOption = function(eventArgs) {
			_this.viewState.SelectedStateId = eventArgs.Option.Value;
			_this.applyStateFilter();
		}

		var optionAll = new ManagedSelectOption('— All —', null);
		optionAll.Selected.addHandler(handlerForSelectedOption);

		var stateOptions = [optionAll];

		for(var i = 0; i < GlobalStatesList.length; i++) {
			var state = GlobalStatesList[i];
			var option = new ManagedSelectOption(state.Name, state.Id);
			option.Selected.addHandler(handlerForSelectedOption);
			stateOptions[stateOptions.length] = option;
		}
		this.stateFilterSelector = new ManagedSelect(this.boxControls, 'State filter:', stateOptions);

		this.stateFilterSelector.box.style.width = 'auto';
		this.stateFilterSelector.box.style.styleFloat = 'left';
		this.stateFilterSelector.box.style.clear = 'none';
	}

	this.hideAllInsuranceTypeBoxes = function() {
		for(var id in this.insuranceTypeBoxes) {
			this.insuranceTypeBoxes[id].style.display = 'none';
		}
	}

	this.showInsuranceTypeBox = function(insuranceTypeId) {
		this.insuranceTypeBoxes[insuranceTypeId].style.display = '';
	}

	this.SetSelectedDocumentFormats = function(newValue) {
		this.viewState.SelectedDocumentFormats = this.SelectedDocumentFormats = newValue;
		for(var documentFormatId in this.documentCheckBoxes) {
			var checkBoxesList = this.documentCheckBoxes[documentFormatId];
			var isChecked = Array.contains(this.SelectedDocumentFormats, documentFormatId);
			for(var i = 0; i < checkBoxesList.length; i++) {
				var checkBox = checkBoxesList[i];
				checkBox.SetChecked(isChecked);
			}
		}
		this.SelectedDocumentFormatsChanged.invokeHandlers();
		this.SelectedDocumentFormatsSet.invokeHandlers();
	}

	this.applyStateFilter = function() {
		// going through carrier header boxes like [+] DocName and setting atLeastOnevisible = false to all of them
		for(var key in this.insuranceTypeBoxes) {
			var box = this.insuranceTypeBoxes[key];
			for(var i = 0; i < box.childNodes.length; i++) {
				var documentsGroups = box.childNodes[i].childNodes;
				for(var j = 0; j < documentsGroups.length; j++) {
					var documentGroup = documentsGroups[j];
					if(documentGroup.childNodes.length > 0) {
						documentGroup.atLeastOneVisible = false;
					}
				}
			}
		}
		for(var key in this.documentCheckBoxes) {
			var list = this.documentCheckBoxes[key];
			for(var n = 0; n < list.length; n++) {
				var checkBox = list[n];
				var documentFormat = checkBox.associatedDocumentFormat;
				if(!checkBox.isFiltered &&
				   (this.viewState.SelectedStateId == null || Array.contains(documentFormat.StateIds, this.viewState.SelectedStateId))) {
					checkBox.box.style.display = '';
					var documentsGroupElement = checkBox.box.parentNode;
					if(documentsGroupElement.isCarrierDocumentsGroup) {
						if(!documentsGroupElement.atLeastOneVisible) {
							documentsGroupElement.carrierHeaderElement.style.display = '';
							documentsGroupElement.atLeastOneVisible = true;
						}
					}
				}
				else {
					var documentsGroupElement = checkBox.box.parentNode;
					if(documentsGroupElement.isCarrierDocumentsGroup) {
						if(!documentsGroupElement.atLeastOneVisible) {
							documentsGroupElement.carrierHeaderElement.style.display = 'none';
						}
					}
					checkBox.box.style.display = 'none';
				}
			}
		}
	}

	this.disableTemplateTypesFromBeingSelected = function(templateTypesToDisable) {
		for(var i = 0; i < templateTypesToDisable.length; i++) {
			var templateId = templateTypesToDisable[i];
			var list = this.documentCheckBoxes[templateId];
			if(typeof (list) != 'undefined') {
				for(var n = 0; n < list.length; n++) {
					var checkBox = list[n];
					if(checkBox != null) {
						checkBox.SetEnabled(false);
					}
				}
			}
		}
	}
}

DocumentFormatsList.prototype = new DocumentFormatsList_Prototype();

function getDocumentFormatsListById(documentFormatsObjectId) {
	return getVirtualObject(documentFormatsObjectId);
}