Opportunities = {
	activeRouteId: null,

	init: function()
	{
		Opportunities.uploadRoutes();
		Opportunities.tabCreator();
	},

	uploadRoutes: function () {
		if (Opportunities.uploadRoutesPresent()) {
			Opportunities.addClickEventToEditButtons();
			Opportunities.insertAddRouteButton();
		}
	},

		// uploadRoutes helpers

		uploadRoutesPresent: function()
		{
			return ($('uploadRoutes') && $('routeList'));
		},



		addClickEventToEditButtons: function()
		{
			$('routeList').getElements("a").addEvent("click", function(event){Opportunities.editRoute(event)});
		},

		insertAddRouteButton: function()
		{
			$('uploadRoutes').adopt(new Element("div", {id: 'addLink'}).adopt(new Element("a", {href: '#', text: MultiLingual.getString('js_addroute')}).addEvent("click", function(event){Opportunities.addRouteClickBehaviour(event)})));
		},

			// insertAddRouteButton helpers

			addRouteClickBehaviour: function(event)
			{
				event.stop();

				var airportId = $('airportid').value ;
				var routeType = $('routetype').value;

				if (airportId && routeType) {
					var rowCount = $('routeList').getElements("tr").length - 1;

					$('routeList').getElement('tbody').adopt(new Element("tr").adopt(
						new Element("td", {text: $('airportid').getElements('option')[$('airportid').selectedIndex].text}),
						new Element("td", {text: $('routetype').getElements('option')[$('routetype').selectedIndex].text}),

						new Element("td").adopt(
							new Element("a", {href: '#', text: 'Edit'}).addEvent("click", Opportunities.editRoute)
						),

						new Element("td").adopt(
							new Element("input", {type: 'hidden', name: 'airportid['+ rowCount + ']', value: airportId}),
							new Element("input", {type: 'hidden', name: 'routetype[' + rowCount + ']', value: routeType}),
							new Element("input", {type: 'checkbox', name: 'delete[' + rowCount + ']', value: 'true'})
						)
					));

					$('airportid').value = '';
					$('routetype').value = '';
				}
			},

			// end insertAddRouteButton helpers
		// end uploadRoutes helpers




	editRoute: function (event) {
		event.stop();
		Opportunities.storeActiveRoute(event);

		var hiddenDataElement = Opportunities.getHiddenDataElement(event);
		if (Opportunities.hasRouteData(hiddenDataElement)) {
			var route = Opportunities.populateRouteData(hiddenDataElement);
			Opportunities.displayRouteDialog(route);
		} else if (Opportunities.getActiveRouteId(event) > 0) {
			new Request.JSON({
				url: '/ajax/opportunity-data.php',
				onSuccess: function(data) {
					Opportunities.displayRouteDialog(data);
				}
			}).get({'routeid': Opportunities.getActiveRouteId(event), lang: MultiLingual.langCode});
		} else {
			Opportunities.displayRouteDialog();
		}
	},

	// editRoute helpers

		storeActiveRoute: function(event)
		{
			$('routeList').store('currentRoute', $(event.target).getParent());
		},

		getActiveRouteId: function(event)
		{
			var id = $(event.target).get('rel');
			Opportunities.activeRouteId = id;
			return id;
		},

		getHiddenDataElement: function(event)
		{
			return $(event.target).getParent().getNext();
		},

		hasRouteData: function(element)
		{
			return element.getElements('input[type=hidden]').length > 1;
		},

		populateRouteData: function(hiddenDataElement)
		{
			var route = Opportunities.addRouteData(hiddenDataElement);
			route = Opportunities.addAirlineIds(route, hiddenDataElement);
			route = Opportunities.addDeletedAirlineIds(route, hiddenDataElement);
			return route;
		},

		addRouteData: function(element)
		{
			var data = {};
			data['routeId'] = element.getElement('input[name^=routeId').value;
			data['airportid'] = element.getElement('input[name^=airportid]').value;
			data['routetype'] = element.getElement('input[name^=routetype]').value;
			data['description'] = element.getElement('input[name^=description]').value;

			return data;
		},

		addAirlineIds: function(route, data)
		{
			var airlineIds = Opportunities.getAirlineIds(data);
			if (airlineIds) {
				route['airlines'] = Opportunities.getAirlineIdDetails(airlineIds);
			}
			return route;
		},

		getAirlineIds: function(data)
		{
			return data.getElements('input[name^=airlineid]');
		},

		getAirlineIdDetails: function(airlineIds)
		{
			var details = new Array();
			index = 0;
			airlineIds.each(function (el) {
				details[index] = {};
				details[index]['id'] = el.value;
				details[index]['title'] = $('airlineidPopup').getElement('option[value=' + el.value + ']').text;
				index++;
			});

			return details;
		},

		addDeletedAirlineIds: function(route, data)
		{
			var deleteIds = Opportunities.getDeletedAirlineIds(data);
			if (deleteIds) {
				route['deletedairlines'] = Opportunities.getDeletedAirlineIdDetails(deleteIds);
			}
			return route;
		},

		getDeletedAirlineIds: function(data)
		{
			return data.getElements('input[name^=airlinedeleteid]');
		},

		getDeletedAirlineIdDetails: function(deleteIds)
		{
			var details = new Array();
			index = 0;
			deleteIds.each(function (el) {
				details[index] = {};
				details[index]['id'] = el.value;
				index++;
			});
			return details;
		},

		// end editRoute helpers



	displayRouteDialog: function(route) {
		if (!Opportunities.opportunityDialog) {
			new Request.HTML({
				url: '/ajax/opportunity-form.php',
				onSuccess: function(tree, elements, html) {
					var dialogHTML = new Element("div", {'id': 'opportunityDialog', 'class': 'popupDialog'}).adopt(tree);
					$(document.body).adopt(dialogHTML);

					Opportunities.tabCreator();

					tinyMCE.execCommand('mceAddControl', false, 'descriptionPopup');

					Opportunities.opportunityDialog = new PopupDialog(dialogHTML, {'actionSelector': 'div.submit input'});
					Opportunities.opportunityDialog.callback = Opportunities.saveRoute;

					var addLink = $(Opportunities.opportunityDialog.dialog).getElementById('tagAirlinesPopup').getElement('a');
					addLink.addEvent("click", function(e) {
						e.stop();

						var airlineId = $('airlineidPopup').value;

						if (airlineId) {
							var rowCount = $('airlineListPopup').getElements("tr").length - 1;

							$('airlineListPopup').adopt(new Element("tr").adopt(
								new Element("td", {
									text: $('airlineidPopup').getElements('option')[$('airlineidPopup').selectedIndex].text
								}),

								new Element("td").adopt(
									new Element("input", {
										type: 'hidden',
										name: 'airlineidPopup['+ rowCount + ']',
										value: airlineId
									}),

									new Element("input", {
										type: 'checkbox',
										name: 'deletePopup[' + rowCount + ']',
										value: airlineId
									})
									)
								));

							$('airlineidPopup').value = '';
						}
					});

					Opportunities.loadRoute(route);
				}
			}).get({lang: MultiLingual.langCode});
		} else {
			Opportunities.loadRoute(route);
		}
	},

	saveRoute: function() {
		var dialog = $(Opportunities.opportunityDialog.dialog);

		var description = (tinyMCE.activeEditor ? tinyMCE.activeEditor.getContent() : dialog.getElementById('descriptionPopup').value);
		var routeType = dialog.getElementById('routetypePopup').value;
		var airportId = dialog.getElementById('airportidPopup').value;

		var airlineidPopup = dialog.getElements('input[name^=airlineidPopup]');
		var deletePopup = dialog.getElements('input[name^=deletePopup][checked]');

		var currentRoute = $('routeList').retrieve('currentRoute').getParent();

		var rowData = currentRoute.getChildren();
		rowData[0].set('text', dialog.getElementById('airportidPopup').getElements('option')[dialog.getElementById('airportidPopup').selectedIndex].text);
		rowData[1].set('text', dialog.getElementById('routetypePopup').getElements('option')[dialog.getElementById('routetypePopup').selectedIndex].text);

		currentRoute.getLast().getElements('input[type=hidden]').destroy();

		currentRoute.getLast().adopt(
			new Element("input", {'type': 'hidden', 'name': 'airportid[' + (currentRoute.rowIndex-1) + ']', 'value' : airportId}),
			new Element("input", {'type': 'hidden', 'name': 'routetype[' + (currentRoute.rowIndex-1) + ']', 'value' : routeType}),
			new Element("input", {'type': 'hidden', 'name': 'description[' + (currentRoute.rowIndex-1) + ']', 'value' : description}),
			new Element("input", {'type': 'hidden', 'name': 'routeRowToDelete[' + (currentRoute.rowIndex-1) + ']', 'value' : currentRoute.rowIndex-1})
		);

		if (airlineidPopup) {
			airlineidPopup.each(function (el) {
				currentRoute.getLast().adopt(
					new Element('input', {
						'type': 'hidden',
						'name': 'airlineid[' + (currentRoute.rowIndex-1) + '][' + el.value + ']',
						'value': el.value
					})
				);
			});
		}

		if (deletePopup) {
			deletePopup.each(function (el) {
				currentRoute.getLast().adopt(
					new Element('input', {
						'type': 'hidden',
						'name': 'airlinedeleteid[' + (currentRoute.rowIndex-1) + '][' + el.value + ']',
						'value': el.value
					})
				);
			});
		}
	},


	loadRoute: function(route) {
		var dialog = $(Opportunities.opportunityDialog.dialog);

		if (dialog) {
			dialog.getElementById('routetypePopup').value = (route && route.routetype ? route.routetype : '');
			dialog.getElementById('airportidPopup').value = (route && route.airportid ? route.airportid : '');
			dialog.getElementById('descriptionPopup').value = (route && route.description ? route.description : '');

			// remove all selected airlines
			$('opportunityDialog').getElementById('airlineListPopup').getElements('tr:not(:first-child)').destroy();

			if (route && route.airlines) {
				for(i = 0; i < route.airlines.length; i++) {

					dialog.getElementById('airlineListPopup').adopt(
						new Element('tr').adopt(
							new Element('td', {
								'text': route.airlines[i].title
							}),
							new Element('td').adopt(
								new Element('input', {
									'type': 'hidden',
									'name': 'airlineidPopup[' + i + ']',
									'value': route.airlines[i].id
								}),

								new Element('input', {
									'type': 'checkbox',
									'name': 'deletePopup[' + i + ']',
									'id': 'deletePopup' + route.airlines[i].id,
									'value': route.airlines[i].id
								})
							)
						)
					)
				}
			}

			if (route && route.deletedairlines) {
				for(i = 0; i < route.deletedairlines.length; i++) {
					var deletedId = route.airlines[i].id;
					var deletedElement = $('deletePopup' + deletedId);
					if (deletedElement) {
						deletedElement.checked = true;
					}
				}
			}

			var editor = tinyMCE.getInstanceById('descriptionPopup');
			if ($defined(editor)) editor.setContent(route && route.description ? route.description : '');

			Opportunities.opportunityDialog.openDialog();
		}
	},



	tabCreator: function () {
		$$('.tabWrapper').each(function (el) {
			if (el.getChildren('.tabTitle').length) {
				el.store('tabs', new Tabr(el));
			}
		});
	}

}

window.addEvent('domready', Opportunities.init);
