var Seatmap = Class.create( { 
	
	/**
	 * Constructor
	 * @param eventInfo Event information object
	 */
    initialize: function(eventInfo, options) {
		this.options = options;
		/** State of the seatmap object, to decide if the widget is updating or not */
		this.isUpdatingWidget = false;
		/** Content of the last seat_selection response */
		this.seat_selection_response;
		/** Variables to handle availability updates */
		this.refreshInProgress = 0;
		/** Number of refreshes that has been made */
		this.refreshCounter = 0;
		/** Indicates if a single seat is left */
		this.leaveSingleSeat = false;
		this.active = false;
		this.displayMapError = false;
		this.inited = false;
		
		this.eventInfo = eventInfo;
		this.cart = new Cart(eventInfo.config.ticketLimit);
		this.cartView = new Cartview();
		this.svlDynamic = new SvlDynamic(eventInfo);
		this.updateSingleSeatMessage();
		this.initPopups();
		
		this.addEventListeners();
		if($('edp_isc_display').visible() && startUpErrorMessage > 0) {
			this.displayStartupErrorMessage(startUpErrorMessage);
		}
		
		// TODO: remove this when feature pages are in use
		this.takeatourURL = '/staticPage.php?page=takeatour';

	},
	
	reInitialize: function(eventInfo) {
		this.eventInfo = eventInfo;
		this.emptyCart();
		this.cart.setMaxTicketLimit(this.eventInfo.config.ticketLimit);
		this.svlDynamic = new SvlDynamic(this.eventInfo);
		
		this.options.imgURL = eventInfo.imgURL;
		this.generatePriceCategoryFilter();
		this.mapInit();
	},

	setTakeATourURL: function(url) {
		this.takeatourURL = url;
	},
	
	setDebugMode: function(debug) {
		this.svlDynamic.setDebugMode(debug);
	},
	
	startRefreshAvailability: function() {
		if (this.eventInfo.config.availabilityRefreshRate == 0) {
			this.eventInfo.config.availabilityRefreshRate = 60000;
		}
		this.interval = setInterval(this.refreshAvailability.bind(this), this.eventInfo.config.availabilityRefreshRate);
	},
	
	stopRefreshAvailability: function() {
		clearInterval(this.interval);
		this.popups['refreshPopup'].hide();
		this.refreshInProgress = 0;
	},

	refreshAvailability: function() {
		if ($('edp_isc_display').visible() && !$('no-flash-message-container') && !this.refreshInProgress && !this.displayMapError && !$('pricetype_popup').visible() && this.refreshCounter < 20) {
			this.popups['refreshPopup'].show();
			this.refreshInProgress = 1;
			this.refreshCounter++;
			this.widget_call("refreshAvailability", Object.toJSON({availabilityURL : this.eventInfo.availabilityURL}));
		}
	},	

	// Function to send requests to the widget
	widget_call: function(methodName, params) {
		//log(methodName);
		//log(params);
		try {
			var result = $('map-area').mapFunction(methodName, params);	
			//log(result);
		}
		catch(e)
		{
			//log("ERROR on call to isc widget method:" + methodName);
		}
	},
	
	trackEvent: function(code) {
		// TODO: insert correct webtrends code
//	    dcsMultiTrack('DCS.dcsuri', code,'WT.ti', code);        
	},
	
	// Events from the widget
	widget_callback: function(response) {

		this.active = true;

		switch (response.event_name) {
			case "seat_selection":
				this.seatSelectionHandler(response);
				break;

			case "polygon_selection":
				this.polygonSelection(response);
				break;

			case "map_init":
				this.mapInit();
				break;

			case "nav_button_clicked":
				sendMultiTrack('ISM_Widget_NavTool', 'DCSext.ISM_Widget');
				break;

			// If select seats has been sent to widget this respons always comes last after all "seat_selection" responses
			case "show_seats_complete":
				this.isUpdatingWidget = false;
				this.unavailableSeatsHandler(response);
				this.seatSelectionHandler(this.seat_selection_response);
				break;

			case "shade_complete":
				this.shadeComplete();
				break;

			case "display_map_complete":
				this.active = false;
				if(this.inited){
					this.updateSelectedSeatsInWidget();
				}
				this.inited = true;
				break;

			case "show_seats_error":
				break;

			case "highlight_sections_complete":
				break;

			case "highlight_sections_error":
				break;

			case "reset_map_complete":
				break;

			case "refresh_availability_complete":
				this.popups['refreshPopup'].hide();
				this.updateSelectedSeatsInWidget();
				this.refreshInProgress = 0;
				break;

			case "refresh_availability_error":
				this.popups['refreshPopup'].hide();
				this.refreshInProgress = 0;
				this.displayMapError = true;
				this.displayError();
				this.trackEvent('widget_error');
				break;

			case "nav_drag_completed":
				break;

			case "add_svl_scripts_or_data_complete":
				this.popups['filterPopup'].hide();
				break;

			case "display_map_error":
				this.displayMapError = true;
				this.displayError();
				this.trackEvent('widget_error');
				break;

			case "svl_script_error":
				break;

			case "json_param_error":
				break;

			default:
				log("unhandled event: "+response.event_name);
				break;
		}
	},

	displayError: function() {
		var loadingDiv = $('loadingISM');

		if (loadingDiv.visible()) {
			loadingDiv.hide();
		}
		var widgetMessagePopup = this.popups['widgetMessagePopup'];

		widgetMessagePopup.setTitle('<span class="errorTitle">' + TU("SORRY") + '</span>');

		var content = TU("CONNECTION_FAILED");
		content += '<div class="text-center messageButtons" style="margin-top: 15px; margin-bottom: 5px;"><input id="widget_message_close_sec" type="button" class="button" onclick="sendMultiTrack(\'ISM_Error_BestAvail\', \'DCSext.ISM_Errors\');" value="'+ TU("BEST_AVAILABLE") +'"/></div>';

		widgetMessagePopup.setContent('<span class="widgetMessageContent">' + content +'</span>');
		widgetMessagePopup.show();
		$('FlashOpaquePopupLayer').show();
		$('FlashOpaquePopupLayer').addClassName("full-white");
		
		Event.observe($('widget_message_close'), 'click', function() { 
			widgetMessagePopup.hide(); 
			$('FlashOpaquePopupLayer').hide();
			toggleMode(); 
			return false;
		});
		Event.observe($('widget_message_close_sec'), 'click', function() { 
			widgetMessagePopup.hide(); 
			$('FlashOpaquePopupLayer').hide();
			toggleMode(); 
			return false;
		});
	},
	
	displayLeaveSingleSeatError: function() {
		var leaveSingleSeatPopup = this.popups['leaveSingleSeatPopup'];
		var title = '<span class="errorTitle">' + TU('LEAVE_SINGLE_SEAT_TITLE') + '</span>';
		var content = '<span class="widgetMessageContent">' + TU('LEAVE_SINGLE_SEAT_MESSAGE') + '<div class="text-center messageButtons" style="margin-top: 15px; margin-bottom: 5px;"><input id="single_seat_popup_close_button" type="button" class="button" value="'+ TU('OK') +'"/></div></span>';
		leaveSingleSeatPopup.setTitle(title);
		leaveSingleSeatPopup.setContent(content);
		leaveSingleSeatPopup.show();
		Form.Element.enable($('cart_checkout_button')); // Must be here otherwise the button will be disabled
		Event.observe($('single_seat_popup_close'), 'click', function() { leaveSingleSeatPopup.hide(); return false; });
		Event.observe($('single_seat_popup_close_button'), 'click', function() { leaveSingleSeatPopup.hide(); return false; });
	},

	displaySeatRemovedMessage: function(removedSeats) {
		var seatRemovedPopup = this.popups['seatRemovedPopup'];
		var title = '<span class="errorTitle">' + TU('SEAT_REMOVED_TITLE') + '</span>';
		var content = '<span class="widgetMessageContent" style="width:400px"><b>' +TU('SEAT_REMOVED_MESSAGE') +'</b><br><br>';
		content += '<table class="shoppingCartTable">';
		content += '<thead><tr><th class="level-col dotted-underline">';
		content += TU('LEVEL');
		content += '</th><th class="section-col dotted-underline">';
		content += TU('SECTION');
		content += '</th><th class="row-col dotted-underline">';
		content += TU('ROW');
		content += '</th><th class="seat-col dotted-underline">';
		content += TU('SEAT');
		content += '</th></tr></thead>';
		removedSeats.each((function(seat){
			content += '<tr><td width="50px">' + this.getLevelName(seat.getLevel()) + '</td><td width="50px">' + this.getSectionName(seat.getSection()) + '</td><td width="50px">' + seat.getRow() + '</td><td width="50px">' + seat.getSeat() + '</td></tr>';  
		}).bind(this));
		content += '</table>';
		content +='</span><div class="text-center messageButtons" style="margin-top: 15px; margin-bottom: 5px;"><input id="seat_removed_popup_close_button" type="button" class="button" value="'+ TU('OK') +'"/></div>';
		seatRemovedPopup.setTitle(title);
		seatRemovedPopup.setContent(content);
		seatRemovedPopup.show();
		Event.observe($('seat_removed_popup_close'), 'click', function() {
			sendMultiTrack('ISM_Error_SeatsLost_Cancel', 'DCSext.ISM_Errors');
			seatRemovedPopup.hide();
			return false;
		});
		Event.observe($('seat_removed_popup_close_button'), 'click', function() {
			sendMultiTrack('ISM_Error_SeatsLost_OK', 'DCSext.ISM_Errors');
			seatRemovedPopup.hide();
			return false;
		});
	},

	seatSelectionHandler: function(response) {
		if(response != null) {
			this.seat_selection_response = response;
		}

		if(this.isUpdatingWidget) {
			return;
		}

		if(response.intermediate_seat_selection == null && response.last_touched_seat_position == null) {
			this.leaveSingleSeat = false;
			this.updateSingleSeatMessage();
			return;
		}

		if(this.tempCart) {
			this.prevCart = Object.clone(this.tempCart);
		} else {
			this.prevCart = new Cart(this.eventInfo.config.ticketLimit+1);
		}
		//capcacity in tempcart is max+1, this way we know when an add has been attempted so even when the real cart is full
		// check handling of fullcart
		this.tempCart = new Cart(this.eventInfo.config.ticketLimit+1);  

		var intermediate = response.intermediate_seat_selection;
		this.leaveSingleSeat = false;
		if(intermediate) {
			this.parseSeatSelection(intermediate);

			if(intermediate.more_selections) {
				intermediate.more_selections.each((function(moreselection) {
					this.parseSeatSelection(moreselection);
				}).bind(this));
			}
		}
		this.updateSingleSeatMessage();

		var seat;

		// A seat is removed (for the case when deselected seat from widget)
		if(this.tempCart.singleSeatCount < this.cart.singleSeatCount) {
			this.cart.seats.each((function(s) {
				if(Object.isArray(s.value)) { // GA
					// Only support removing of single seats
				} else if(!this.tempCart.contains(s.value)) {
					seat = s.value;
				}
				
			}).bind(this));
			this.removeSeatFromCart(seat.getSeatId(), null,false);

		}
		// A seat is added from the seatmap
		else if(this.tempCart.singleSeatCount > this.cart.singleSeatCount || this.tempCart.gaSeatCount>0 )
		{
			var selection = intermediate.more_selections ? intermediate.more_selections.last() : intermediate;
			if(selection == undefined) {
				selection = intermediate;
			}

			if(this.cart.isFull()) {
				//log("CART IS FULL");
				this.updateSelectedSeatsInWidget();
				this.displayPopup('MAX_TICKETS');
				return;
			}
			else {
				this.tempCart.seats.each((function(s) {
					if(Object.isArray(s.value)) { // GA
						var numOfGA = this.prevCart.contains(s.value.first());
						if(numOfGA < s.value.length) {
							seat = s.value.last();
						}
					} else if(!this.prevCart.contains(s.value)) {
						seat = s.value;
					}
				}).bind(this));
				if(seat) {
					this.seatSelection(seat);
				} else {
					return;
				}
			}
		}
	},

	parseSeatSelection: function(seatObj) {
		if(seatObj.is_ga) {
			var seat = new Seat();
			seat.setPriceCategories(seatObj.price_levels);
			seat.setLevelSections(seatObj.section_names);
			seat.setGA(true);
			this.tempCart.addSeat(seat);
		} else {
			seatObj.seat_names.each((function(seatname) {
				var seat = new Seat();
				seat.setPriceCategory(seatObj.price_level)
				seat.addPriceCategory(seatObj.price_level)
				seat.setLevelSection(seatObj.section)
				seat.setRow(seatObj.row)
				seat.setSeat(seatname)
				this.tempCart.addSeat(seat);
				if(!this.leaveSingleSeat && seatObj.leaves_a_single && this.eventInfo.avoidSingleSeats) {
					this.leaveSingleSeat = true;
				}
			}).bind(this));
		}
	},

	unavailableSeatsHandler: function(response) {
		if(response.seats_not_selectable.length > 0) {
			var seat;
			var removedSeats = [];
			response.seats_not_selectable.each((function(s) {
				seat = new Seat();
				seat.setLevelSection(s.section_name);
				seat.setRow(s.row_name);
				seat.setSeat(s.seat_name);
				if(this.cart.contains(seat)) {
					this.removeSeatFromCart(seat.getSeatId(), null,false);
					removedSeats.push(seat);
				}	
			}).bind(this));
			this.displaySeatRemovedMessage(removedSeats);
		}
	},

	updateSingleSeatMessage: function() {
		if (this.eventInfo.avoidSingleSeats){
			if(this.leaveSingleSeat) {
				$('isc_single_seat_icon').show();
				$('isc_single_seat_msg').show();
				$('isc_single_seat_msg').setStyle({color: '#EF6307', fontWeight: 'bold'});
			} else {
				$('isc_single_seat_icon').hide();
				$('isc_single_seat_msg').show();
				$('isc_single_seat_msg').setStyle({color: '#000000', fontWeight: 'normal'});
			}
		}	
		else {
			$('isc_single_seat_msg').hide();
		}
	},

	shadeComplete: function() {
		
		var loadingDiv = $('loadingISM');
	
		// Check if its the first shadeComplete
		if (loadingDiv.visible()) {
			loadingDiv.hide();
			if (welcomeISM) {
				// Display Welcome Message
				var wp = this.popups['welcomePopup'];
				var title = '<span style="font-size:18px; padding-top: 5px;">' +TU("WELCOME_LAYER_TITLE") +'</span>';

				var content = '<ul class="number-module">';
				content += '<li><span class="number-box highlight-bg">1</span><br/><strong>' +TU("WELCOME_LAYER_ONE") +'</strong></li>';
				content += '<li><span class="number-box highlight-bg">2</span><br/><strong>' +TU("WELCOME_LAYER_TWO") +'</strong></li>';
				content += '<li><span class="number-box highlight-bg">3</span><br/><strong>' +TU("WELCOME_LAYER_THREE") +'</strong></li>';
				content += '</ul>';
				content += '<div class="text-center">';
				content += '<input id="isc_welcome_close_sec" class="button-secondary" type="button" value="'+ TU("WELCOME_LAYER_BUTTON_ONE") +'"/>';
				content += '<span class="gap20"> </span>';
				content += '<input id="isc_welcome_take_tour_button" class="button" onclick="window.open(\''+this.takeatourURL+'\',\'form\')" type="button" value="'+ TU("WELCOME_LAYER_BUTTON_TWO") +'"/>';
				content += '</div>';

				wp.setTitle(title);
				wp.setContent(content);
				wp.show();

				// Event listner for the Use Map button
				Event.observe($('isc_welcome_close_sec'), 'click', function(){
					$('welcome_popup').hide();
				});
			}
			// Show Legend
			var anchor = $('map-area').cumulativeOffset();
			//var legend = $('cart-legend');

			//legend.style.left = -1 + anchor[0] +'px';
			//legend.style.top = 390 + anchor[1] +'px';
			//$('cart-legend').show();
		}

		this.stopRefreshAvailability();
		this.startRefreshAvailability();
	},

	seatSelection: function(seat) {
		// See if we want to add it to the cart instead of displaying popup
		log(seat);
		var prices = this.eventInfo.prices; 
		var priceTypNum = 0;

		prices.price.each(function(s){	
			if(s.priceCategory == seat.priceCategory) {
				priceTypNum++;
			}
			prices.priceType.each(function(d) {
				if (d.number == s.priceType) {
					isPasswordProtected = d.isPasswordProtected;
				}
			});
		});

		if (!seat.isGA() && priceTypNum == 1 && !isPasswordProtected) {
			this.addSeatToCartDirect(seat);	
		}
		else {
			this.showPriceTypeSelection(seat, this.eventInfo);
		}	
	},

	polygonSelection: function(response) {
		sendMultiTrack('ISM_Widget_Polygon', 'DCSext.ISM_Widget');
	},

	/**
	 * Show the seatmap in the widget
	 */
	mapInit: function() {
		var svlInput= {
			eventID: this.eventInfo.eventID,
			availabilityURL: this.eventInfo.availabilityURL,
			mapsellURL: this.eventInfo.mapsellURL,
			langID: this.options.langID,
			overrideJSON: "",
			svlScriptJSON : this.svlDynamic.getSvlScriptFilter(new Array()),
			svlDataJSON : this.svlDynamic.getSvlData(getSelectedFilters())
		};
		this.widget_call("widgetSettings", Object.toJSON(this.options));
		this.widget_call("displayMap", Object.toJSON(svlInput));
	},

	/**
	 * Add seat to the Cart and the CartView
	 * @param seat Seat
	 */
	addSeatToCart: function(seat) {
		this.cart.addSeat(seat);
		this.cartView.addSeat(seat, this.eventInfo);
		if(this.cart.getSize() == 1) {
			Form.Element.enable($('cart_checkout_button'));  //will enable every time but it does not break anything
		}
	},

	removeSeatFromCart: function(seatId, gaId, doWidgetSelection) {
		this.cart.removeSeat(seatId, gaId);
		this.cartView.removeSeat(seatId, gaId);
		//check if the cart is empty, disable the button
		if(this.cart.getSize() == 0) {
			Form.Element.disable($('cart_checkout_button'));
			this.resetCart();
		}
		if(doWidgetSelection) {
			this.updateSelectedSeatsInWidget();
		}
	},

	/**
	 * Empty all seats from Cart and CartView
	 */
	emptyCart: function() {
		this.cart.empty();
		this.cartView.empty();
		//check if the cart is empty, disable the button
		if(this.cart.getSize() == 0) {
			Form.Element.disable($('cart_checkout_button'));
			this.resetCart();
		}
		this.updateSelectedSeatsInWidget();
		this.leaveSingleSeat = false;
		this.updateSingleSeatMessage();
	},

	/**
	 * Reset the temporary carts in Seatmap
	 */
	resetCart: function() {
		this.tempCart = new Cart();
		this.prevCart = new Cart();
	},

	getSeatsFromCart: function() {
		return this.cart.getSeats();
	},

	updateSelectedSeatsInWidget: function()
	{
		var seatArray = this.cart.toWidgetJson();

		if(seatArray.length > 0) {
			var jsonString = Object.toJSON({seats:seatArray});
			this.isUpdatingWidget = true;
			this.widget_call('showSeats',jsonString);
		} else {
			var jsonString = Object.toJSON({seats:[]});
			this.widget_call('showSeats',jsonString);
		}
	},

	priceCatFilter : function(arg) {
		// what priceCats to filter for
		var selectedFilters = arg;
		
		var input = {svlScriptJSON : this.svlDynamic.getSvlScriptFilter(selectedFilters)
					,svlDataJSON : this.svlDynamic.getSvlData(getSelectedFilters())
		};
		this.popups['filterPopup'].show();

		// Adding the widget call in a timeout, or the popup will never be displayed
		setTimeout((function() {
				this.widget_call('addSVLScriptsOrData', Object.toJSON(input));
				this.updateSelectedSeatsInWidget();}).bind(this)
			,200);
		
		// TODO: insert correct webtrends code
//		var code = 'filter_'+(selectedFilters.length > 0) ? selectedFilters[0] : 'none';
//		dcsMultiTrack('DCS.dcsuri', code,'WT.ti', code);        

		return true;
	},


	getPriceInfo: function(priceCategory, priceType) {
		var returnPrice;
		this.eventInfo.prices.price.each(function(price){
			if(priceType != null){
				if((price.priceCategory.toString() == priceCategory.toString()) && (price.priceType.toString() == priceType.toString())) {
					returnPrice = price;
				}
			}
		});
		
		return returnPrice;
	},

	getPriceTypeInfo: function(priceTypeNumber) {
		var priceType;
		this.eventInfo.prices.priceType.each(function(pt) {
			if(pt.number == priceTypeNumber) {
				priceType = pt;
			}
		});
		return priceType;
	},

	getRegularPrices: function(priceCategoryNumber) {
		var regularPrices = new Hash();
		this.eventInfo.prices.price.each(function(p){
			if(p.isRegular) {
				regularPrices.set(p.priceCategory, p);
			}
		});
		return regularPrices;
	},

	getPriceCategoryById: function(priceCategoryId) {
		var priceCategory;
		this.eventInfo.prices.priceCategory.each(function(pc){
			if(pc.number == priceCategoryId) {
				priceCategory = pc;
			}
		});
		return priceCategory;
	},

	getPriceTypesForSeat: function(seat) {
		var priceTypes = new Array();
		
		var tempPriceTypes = new Hash();
		var priceType;
		this.eventInfo.prices.price.each((function(p){
			if((seat.hasPriceCategory(p.priceCategory))) {
				priceType = this.getPriceTypeInfo(p.priceType);
				if (priceType.blockingCodes.length == 0) {
					tempPriceTypes.set(priceType.number, priceType);
				}	
			}
		}).bind(this));
		
		tempPriceTypes.each(function(p) {
			if(p.isRegular)
				priceTypes.push(p.value);
		});
		tempPriceTypes.each(function(p) {
			if(!p.isRegular)
				priceTypes.push(p.value);
		});

		return priceTypes;
	},
	
	

	getLevelName: function(code) {
		if(!code || this.eventInfo.seats.level[code] == undefined)
			return code;

		var name = this.eventInfo.seats.level[code].name;
		if(name != undefined) {
			return name;
		} else {
			return code;
		}
	},

	getSectionName: function(code) {
		if(!code || this.eventInfo.seats.section[code] == undefined)
			return code;

		var name = this.eventInfo.seats.section[code].name;
		if(name != undefined) {
			return name;
		} else {
			return code;
		}
	},
	
	addSeatToCartDirect: function(seat) {
		var prices = this.eventInfo.prices;
		prices.price.each(function(s){
			if(s.priceCategory==seat.priceCategory) {
				var name;
				var number;
				var code;
				prices.priceType.each(function(d) {
					if (d.number == s.priceType) {
						number = d.number;
						code = d.code;
					}
				});
				seat.setPriceTypeNumber(number);
				seat.setPriceTypeCode(code);	
			}
		});
		this.addSeatToCart(seat);
	},

	showLoadingMessage: function() {
		var ism = $('loadingISM');
		var anchor = $('map-area-position').positionedOffset();
		ism.show();
	},

	show: function() {
		if(this.displayMapError){
			this.showLoadingMessage();
			this.displayMapError = false;
			this.mapInit();
		} else if(!this.inited){
			flashVersion = swfobject.getFlashPlayerVersion();
			if (flashVersion.major == 0) {
				// flash is not available
				$('no-flash-message-container').show();	
				$('opaque-layer-full').show();
			}
			else {
				this.showLoadingMessage();
			}
		}
		offset = calculate_offset('map-area-position', 'map-area-locator');
		$('map-area-anchor').style.left = offset[0] + 'px';
		$('map-area-anchor').style.top = offset[1] + 'px'; 
	},

	hide: function() {
		$('map-area-anchor').style.left = '-1200px';
		$('map-area-anchor').style.top = '-1200px'; 
	},
	
	generatePriceCategoryFilter: function() {
		var htmlString = '';
		var regularPrices = this.getRegularPrices();
		regularPrices.each((function(rp) {
			var pc = this.getPriceCategoryById(rp.value.priceCategory);
			htmlString += '<li id="priceCategory_' + pc.number + '">' + pc.code + ' - ' + regularPrices.get(pc.number).priceFormatted + '</li>' +
			'<div class="priceCatExtend" id="priceCategoryExtend_' + pc.number + '" style="display:none;"><span class="highlight">' + pc.code + '</span>' +
			'<span class="highlight"><br/></span><span class="message">' + TU('FILTER_DESCRIPTION') + '</span></div>\n';
		}).bind(this));
		$('price-filter').innerHTML = htmlString;
	},
	
	showPriceTypeSelection: function(seat, eventInfo) {
		log("seat: "); log(seat);

		var popup = this.popups['pricetypePopup'];		
		
		var tablerows = "";
		var passwordProtectedPriceTypes = new Array();
		if(seat.isGA()) {
			log("seat.isGA()");
			log(seat);

			var priceTypes = this.getPriceTypesForSeat(seat);
			var priceCategories = seat.getPriceCategories();
			
			for(var pc = 0; pc < priceCategories.length; pc++) {
				var priceCategory = this.getPriceCategoryById(priceCategories[pc]);

				// If this category is not sold on the web
				if (!priceCategory) {
					continue;
				}
				
				tablerows += '<tr class="divider">' +
				'<td colspan="3"><span>' + priceCategory.code + '</span></td>' +
				'</tr>';
				
				
				for(var i = 0 ; i < priceTypes.length;i++){
					var priceType = priceTypes[i];
					var price = this.getPriceInfo(priceCategory.number, priceType.number)

					if (price) {
						var priceCategoryNumber = priceCategory.number;
						var pricetypeLimitation;
						var name = priceType.name;		
						var priceTypeNumber = priceType.number;
						var priceTypeCode = priceType.code;
						var isPasswordProtected = priceType.isPasswordProtected;
						var hasQuantityLimit = priceType.hasQuantityLimit;
						var hasMandatoryUpsell = priceType.hasMandatoryUpsell;
						var hasOptionalUpsell = priceType.hasOptionalUpsell;
						var hasAdditionalInfo = !!priceType.additionalInfo;
 						
						passwordContent = '<td id ="password_container_' + priceCategoryNumber + '_' + priceTypeCode + '" ></td>';	
						if (isPasswordProtected){
							passwordProtectedPriceTypes.push(priceCategoryNumber + '_' + priceTypeCode);
						}
						var dropdownLimit = eventInfo.config.ticketLimit - this.cart.getSize();
						var dropdown = Popup.createDropDownHTML(dropdownLimit, priceTypeNumber, priceTypeCode, priceCategoryNumber);
						
						if(hasAdditionalInfo || hasMandatoryUpsell || hasOptionalUpsell || hasQuantityLimit) {
							pricetypeLimitation  = '<span class="pricetype-icon-box" id="'+eventInfo.eventID+name+priceTypeNumber+priceTypeCode+'"  onmouseover="TicketForm.showTooltip($(\''+eventInfo.eventID+name+priceTypeNumber+priceTypeCode+'\'), \'tooltip_'+eventInfo.eventID+name+priceTypeNumber+priceTypeCode+'\')" onmouseout="$(\'tooltip_'+eventInfo.eventID+name+priceTypeNumber+priceTypeCode+'\').hide()">?</span>';
							pricetypeLimitation += '<div class="pricetype-tooltip" id="tooltip_'+eventInfo.eventID+name+priceTypeNumber+priceTypeCode+'" style="display:none;"><strong>'+name+'</strong>';
							if (hasAdditionalInfo) {
								pricetypeLimitation += '<p>'+priceType.additionalInfo+'</p>';
							} else {
								if (hasQuantityLimit) {
									pricetypeLimitation += '<p>'+TU("PRICETYPE_HAS_QUANTITY_LIMIT")+'</p>';
								}
								if (hasMandatoryUpsell) {
									pricetypeLimitation += '<p>'+TU("PRICETYPE_HAS_MANDATORY_UPSELL")+'</p>';
								}
								if (hasOptionalUpsell) {
									pricetypeLimitation += '<p>'+TU("PRICETYPE_HAS_OPTIONAL_UPSELL")+'</p>';
								}
							}
							pricetypeLimitation += '</div>';	
							
						} else {
							pricetypeLimitation = '';
						}
						
						//generate a tablerow
						tablerows += '<tr>' +
						'<td class="left">'+dropdown+'</td>' +
						'<td><span class="ticket-type-desc">'+name+'</span>' + pricetypeLimitation + '<span class="ticket-type-price">'+price.priceFormatted+'</span></td>';
						tablerows +=passwordContent;					
						tablerows +='</tr>';
					}								
				}
			}
			
			// If multiple sections exist generate and show the dropdown
			if(seat.getLevelSections().length > 1) {
				var levelSectionDropdown = '<select id="levelSection"><option value="'+seat.getLevelSections().join(';')+'">' + TU('BEST_AVAILABLE') + '</option>';
				seat.getLevelSections().each((function(ls) {
					var lsArray = ls.split("-");
					levelSectionDropdown += '<option value="' + ls + '">' + this.getLevelName(lsArray[0]) + ' - ' + this.getSectionName(lsArray[1]) + '</option>';
				}).bind(this));
				levelSectionDropdown += '</select>';
				tablerows += '<tr class="divider">' +
				'<td colspan="3"><span>' + TU('SECTION') + '</span></td>' +
				'</tr>';
				tablerows += '<tr><td colspan="3">' + levelSectionDropdown + '</td></tr>';
			}
			else {
				if(tablerows == "")
					tablerows = TU("NOT_AVAILABLE_ON_WEB");
			
				tablerows += '<input type="hidden" id="levelSection" value="' + seat.getLevelSections().first() + '" />';
			}

			//Set title
			var title = '<span class="seat-type-title">' + TU("SECTION") + ' ' + seat.levelSection + '</span>';
			if(seat.levelSection){
				popup.setTitle(title);
			}
			
			//Set underTitle
			if(eventInfo.mksVal==1){
				var underTitle = '<strong class="generalAdmission"></strong><span class="gaDesc"></span>';
			} else {
				var underTitle = '<strong class="generalAdmission">'+ TU("GENERAL_ADMISSION_ONLY") +'</strong><span class="gaDesc">'+ TU("GENERAL_ADMISSION_DLB_DESC") +'</span>';
			}
			popup.setUnderTitle(underTitle);
		
			var table = '<div class="scrollable" id="scrollable"><table class="ticketType-table" id="ticketType-table" cellspacing="0">'+tablerows+
						'</table></div><br/>'+
						'<div class="ticketType-span" id="ticketType-span" style="text-align:center;"><input class="button" type="button" disabled="" value="'+ TU("ADD_BUTTON")+'"/></div>';
			var eventListener = '<script>$$(".scrollable .ticketType-table .gaPriceTypeSelect").each(function(selection){selection.observe("change", function(){Popup.gaDisableButton();});});</script>';
						 
			popup.setContent(table +eventListener);
			
						
			//add observer on form
			var elem = $$(".ticketType-table .button");
			var test = '';
			$$(".ticketType-span .button")[0].observe('click',(function(){
				$$(".ticketType-span .button")[0].disable();
				
				$$(".ticketType-table .gaPriceTypeSelect").each((function(selection){
					var priceTypeNumber = selection.getAttribute("ptNumber");
					var priceTypeCode = selection.getAttribute("ptCode");
					var priceCategoryNumber = selection.getAttribute("pcNumber");
					var amount = selection.value;
								
					if(amount>0)
					{
						seat.setPriceTypeNumber(priceTypeNumber);
						seat.setPriceTypeCode(priceTypeCode);
						seat.setPriceCategory(priceCategoryNumber);
						for(var i = 0;i<amount;i++)
						{			
							if(this.cart.isFull())
							{
								this.updateSelectedSeatsInWidget();
								this.displayPopup('MAX_TICKETS');
								break;
							}							
							var newSeat = Object.clone(seat);
							newSeat.setLevelSection($('levelSection').getValue());
							this.addSeatToCart(newSeat);
						}
					}
					//Stop observing				
				}).bind(this));
				$$(".ticketType-span .button")[0].stopObserving();
				this.popups['pricetypePopup'].hide();
			}).bind(this));
		} else {
			//Set title
			var title = '<span class="seat-type-title">' + TU("SECTION") + ' ' + seat.section + ', ' + TU("ROW") + ' ' + seat.row + ', ' + TU("SEAT") + ' ' + seat.seat +'</span>';
			popup.setTitle(title);
			
			//Set underTitle
			var underTitle = '<strong class="singleSeat">'+ TU("PLEASE_SELECT_ONE") +'</strong>';
			popup.setUnderTitle(underTitle);
			
			//Price Type table 
			var content ='<div id="scrollable"><table border="0" cellpadding="0" cellspacing="0" class="ticketType-table" id="ticketType-table">';
			
			this.getPriceTypesForSeat(seat).each(function(priceType) {
				var name = priceType.name;
				var number = priceType.number;
				var code = priceType.code;
				var hasQuantityLimit = priceType.hasQuantityLimit;
				var hasMandatoryUpsell = priceType.hasMandatoryUpsell;
				var hasOptionalUpsell = priceType.hasOptionalUpsell;
				var hasAdditionalInfo = !!priceType.additionalInfo;
				
				priceFormatted = this.getPriceInfo(seat.getPriceCategory(), priceType.number).priceFormatted;
				
				passwordContent = '<td id ="password_container_' + code + '" ></td>';
				if (priceType.isPasswordProtected){
					passwordProtectedPriceTypes.push(code);
				}
				if(hasAdditionalInfo || hasMandatoryUpsell || hasOptionalUpsell || hasQuantityLimit) {
					pricetypeLimitation  = '<span class="pricetype-icon-box" id="'+eventInfo.eventID+name+number+code+'"  onmouseover="TicketForm.showTooltip($(\''+eventInfo.eventID+name+number+code+'\'), \'tooltip_'+eventInfo.eventID+name+number+code+'\')" onmouseout="$(\'tooltip_'+eventInfo.eventID+name+number+code+'\').hide()">?</span>';
					pricetypeLimitation += '<div class="pricetype-tooltip" id="tooltip_'+eventInfo.eventID+name+number+code+'" style="display:none;"><strong>'+name+'</strong>';
					if (hasAdditionalInfo) {
						pricetypeLimitation += '<p>'+priceType.additionalInfo+'</p>';
					} else {
						if (hasQuantityLimit) {
							pricetypeLimitation += '<p>'+TU("PRICETYPE_HAS_QUANTITY_LIMIT")+'</p>';
						}
						if (hasMandatoryUpsell) {
							pricetypeLimitation += '<p>'+TU("PRICETYPE_HAS_MANDATORY_UPSELL")+'</p>';
						}
						if (hasOptionalUpsell) {
							pricetypeLimitation += '<p>'+TU("PRICETYPE_HAS_OPTIONAL_UPSELL")+'</p>';
						}
					}
					pricetypeLimitation += '</div>';	
					
				} else {
					pricetypeLimitation = '';
				}
					
				content += '<tr><td class="left"><input id="price_type_button_' + code + '" type="button" class="button" ptCode="' + code +'" ptNumber="'+ number +'" value="'+ TU("SELECT_BUTTON") + '"/></td><td><span class="ticket-type-desc">' + name + '</span>' +  pricetypeLimitation + '<span class="ticket-type-price">' + priceFormatted + '</span></td>' + passwordContent + '</tr>';
				
			}, this);
			
			content +='</table></div>';
			
			//add the table to the popup
			popup.setContent(content);
			
		}
		if(passwordProtectedPriceTypes)
			popup.settings.width=400;
			
		if(seat.isGA() && seat.hasMultiplePriceCategories()){
			passwordProtectedPriceTypes.each(function(catAndType) {
				var priceCategoryNumber = catAndType.split('_')[0];
				var priceTypecode = catAndType.split('_')[1];
				var password = priceTypePasswords.get(priceTypecode);
				password.createPasswordClone($('password_container_' + catAndType));
				if(!password.validated)
					$('ticketType-table').select('[ptCode="' + priceTypecode + '"][pcNumber="' + priceCategoryNumber + '"]').first().disabled=true;
		
			});
		}
		else {		
			passwordProtectedPriceTypes.each(function(code) {
				var password = priceTypePasswords.get(code);
				password.createPasswordClone($('password_container_' + code));
				if(!password.validated)
						if(seat.isGA())
							$('ticketType-table').select('[ptCode="' + code + '"]').first().disabled=true;
						else	
							$('price_type_button_' + code).disabled=true;
			});
		}	
		//add observer on close button
		var closeButton = $('pricetype_close');
		closeButton.observe('click',(function(){
			this.resetCart();
			this.updateSelectedSeatsInWidget();
			//closeButton.stopObserving();
		}).bind(this));
		
		popup.show();
		popup.addPriceTypeListeners(seat);
		
	},
	

	addEventListeners: function () {
		
		//Popups
		Event.observe($('ticket_limits_link'), 'click', (function(){this.popups['ticketLimitsPopup'].show(); sendMultiTrack('ISM_TicketLimit', 'DCSext.ISM_OtherLinks');}).bind(this));
		Event.observe($('map_disclaimer_link'), 'click', (function(){this.popups['mapDisclaimerPopup'].show();}).bind(this));
		
		//Mouse legends tooltips
		Event.observe($('legend-not-available'), 'mouseover', function(){
			var tooltip = $('not-available-legend-tooltip');
			var anchor = $(this).cumulativeOffset();
			tooltip.style.left = -10 + anchor[0] +'px';
			tooltip.style.top = -47 + anchor[1] +'px';
			tooltip.show();
		});
		
		Event.observe($('legend-available'), 'mouseover', function(){
			var tooltip = $('available-legend-tooltip');
			var anchor = $(this).cumulativeOffset();
			tooltip.style.left = -10 + anchor[0] +'px';
			tooltip.style.top = -60 + anchor[1] +'px';
			tooltip.show();
		});
		
		Event.observe($('legend-also-available'), 'mouseover', function(){
			var tooltip = $('also-available-legend-tooltip');
			var anchor = $(this).cumulativeOffset();
			tooltip.style.left = -10 + anchor[0] +'px';
			tooltip.style.top = -60 + anchor[1] +'px';
			tooltip.show();
		});

		Event.observe($('legend-available'), 'mouseleave', function(){$('available-legend-tooltip').hide();});
		Event.observe($('legend-not-available'), 'mouseleave', function(){$('not-available-legend-tooltip').hide();});
		Event.observe($('legend-also-available'), 'mouseleave', function(){$('also-available-legend-tooltip').hide();});

		
		//Cart
		Event.observe($('show_cart_details'), 'click', this.cartView.showDetailsSmooth);
		Event.observe($('hide_cart_details'), 'click', this.cartView.hideDetailsSmooth);
		
		//If window is resize, reposition the legend
		Event.observe(document.onresize ? document : window, "resize", function() {Seatmap.showLegend();});
		
	},
	
	displayPopup: function (type) {
		var content ="";
		
		switch(type)
		{
		case 'MAX_TICKETS':
			
			var wmp = seatmap.popups['widgetMessagePopup'];
			var title = '<span style="font-size:18px; text-align:center;">' +TU("ERROR_MESSAGE_TITLE_OOPS") +'</span>';
			var ok = TU("OK");
			var button ='<div class="text-center messageButtons"><input class="button-secondary" type="button" value="'+ok+'" id="okButton"/></div><script> Event.observe($("okButton"), "click", function(){seatmap.popups["widgetMessagePopup"].hide();});</script>';
			
			content = sprintf(TU("CART_FULL_MESSAGE"), seatmap.cart.capacity);
			
			wmp.setTitle('<span class="errorTitle">' +title +'</span>');
			wmp.setContent('<span class="widgetMessageContent">' + content +'</span>' + button);
			wmp.show();
					
			break;
		default:
			return;
		}
	},
	
	//Display errormessage based on variable from stage 2
	displayStartupErrorMessage: function (errorCode, message) {
		
		var content ="";
		var bestAvailable = TU("BEST_AVAILABLE");
		var newSeatSelection = TU("NEW_SEAT_SELECTION");
		
		var buttons ='<div class="text-center messageButtons"><input class="button-secondary" style="font-size: 11px;" type="button" value="'+bestAvailable+'" id="bestAvail"/><input class="button" type="button" value="'+newSeatSelection+'" id="newSeatSelection"/></div>';

		var title = TU("SORRY");
		switch(errorCode) {
			case 1:
			case 2:
			case 3:
			case 4:
			case 5:
			case 6:
			case 7:
				content = TU("UNABLE_TO_RESERVE_SEATS");
				break;
			case 9:
				content = textunits.PRICETYPES_HAS_QUANTITY_LIMIT_ERROR_PART1;
				content += '<p>';
				
				if (message !== undefined) {
					priceTypeErrorsMessage =message.split(",");
				}
				
				
				priceTypeErrorsMessage.each(function(m) {
					content += m + '<br/>';
				});
				
				content += '</p>';				
				content += textunits.PRICETYPES_HAS_QUANTITY_LIMIT_ERROR_PART2;
				buttons = '<div class="text-center messageButtons"><input class="button-secondary" type="button" value="'+TU("OK")+'" id="newSeatSelection"/></div>';
				break;
			case 30:
				content = passwordError;
				break;	
			case 100:
			default:
				content = TU("ERROR_GENERIC");
				break;
		}
	
		var wmp = this.popups['widgetMessagePopup'];
		
		wmp.setTitle('<span class="errorTitle">' +title +'</span>');
		wmp.setContent('<span class="widgetMessageContent">' + content + '</span>'+buttons);
		
		if($("bestAvail")) {
			Event.observe($("bestAvail"), "click",  (function(){this.popups['widgetMessagePopup'].hide();toggleMode();}).bind(this));
		}
		
		if($("newSeatSelection")) {
			Event.observe($("newSeatSelection"), "click", (function(){this.popups['widgetMessagePopup'].hide();}).bind(this));
		}
		wmp.show();		
	},	
	
	
	initPopups: function() {
		this.popups = [];
		

		this.popups['welcomePopup'] = new Popup(
				{
					popup_id: "welcome_popup",
					close_id: "welcome_close",
					anchor_id: "map-area-position",
					width: 330,
					offset: { x: 150, y: 80 },
					widgetDisable: false,
					pageDisable: false
				});
		

		this.popups['pricetypePopup'] = new Popup(
				{
					popup_id: "pricetype_popup",
					close_id: "pricetype_close",
					anchor_id: "map-area-position",
					width: 330,
					height: 300,
					offset: { x: 180, y: 40 },
					widgetDisable: true,
					pageDisable: false
				});		
		
		this.popups['filterPopup'] = new Popup(
				{
					popup_id: "filter_popup",
					close_id: "welcome_close",
					anchor_id: "map-area-position",
					width: 200,
					offset: { x: 10, y: 10 },
					widgetDisable: false,
					pageDisable: false
				});
		
		this.popups['refreshPopup'] = new Popup(
				{
					popup_id: "refresh_popup",
					close_id: "welcome_close",
					anchor_id: "map-area-position",
					width: 200,
					offset: { x: 10, y: 10 },
					widgetDisable: true,
					pageDisable: false
				});


		this.popups['leaveSingleSeatPopup'] = new Popup(
				{
					popup_id: "leave_single_seat_popup",
					close_id: "single_seat_popup_close",
					anchor_id: "map-area-position",
					width: 450,
					offset: { x: 130, y: 100 },
					widgetDisable: true,
					pageDisable: false
				});
		

		this.popups['widgetMessagePopup'] = new Popup(
			{
				popup_id: "widget_message_popup",
				close_id: "widget_message_close",
				anchor_id: "map-area-position",
				width: 280,
				offset: { x: 195, y: 80 },
				widgetDisable: false,
				pageDisable: true
			});
		
		this.popups['ticketLimitsPopup'] = new Popup(
				{
					popup_id: "ticket_limits_popup",
					close_id: "ticket_limits_close",
					anchor_id: "map-area-position",
					width: 300,
					offset: { x: 250, y: -205 },
					widgetDisable: false,
					pageDisable: false
				});

		this.popups['mapDisclaimerPopup'] = new Popup(
			{
				popup_id: "map_disclaimer_popup",
				close_id: "map_disclaimer_close",
				anchor_id: "map-area-position",
				width: 300,
				offset: { x: 360, y: 10 },
				widgetDisable: false,
				pageDisable: false
			});
		

		this.popups['languagePopup'] = new Popup(
				{
					popup_id: "language_popup",
					close_id: "language_popup_close",
					anchor_id: "languages_module",
					width: 400,
					offset: { x: -419, y: 28 },
					widgetDisable: true,
					pageDisable: true
				});					
		

		
		this.popups['seatRemovedPopup'] = new Popup(
				{
					popup_id: "seat_removed_popup",
					close_id: "seat_removed_popup_close",
					anchor_id: "map-area-position",
					width: 400,
					offset: { x: 130, y: 100 },
					widgetDisable: true,
					pageDisable: false
				});	

			
	}
});


//Show and position the html-legend in the page
Seatmap.showLegend = function() {
	var anchor = $('map-area').cumulativeOffset();
	//var legend = $('cart-legend');
	
	//legend.style.left = -1 + anchor[0] +'px';
	//legend.style.top = 390 + anchor[1] +'px';
	//$('cart-legend').show();
	return true;
}

