/*
    * TicketSwitch 2009 Copyright (c) - Finder Functions
    * Author: Ben Campbell
    * JQuery 1.2.1+ Dependent
*/

$(window).bind("load",function(){
    $("#easeOfUseSlider").slider({ steps: 10,  value: 50, animate:true  });
    $("#functionalitySlider").slider({ steps: 10, value: 50, animate:true  });
    $("#choiceOfTicketsSlider").slider({ steps: 10, value: 50, animate:true  });
});
$(document).ready(function() {
	correctLoader = "<img class='processLoader' src='/shared/images/"+userID+"buyLoaderFinder.gif' alt='Loading...' />";
	xmlCore = "/tickets/xml_core.exe"
	setCoreCookie = "/tickets/xml_persist_dict_set.exe/"+userID+"?";
	noDiscounts = 0;
	allowSelfPrint = "<self_print_mode>html</self_print_mode>";

	function stageTwo() {
		if (noDiscounts == 0) {
		$(".nextStage2").html("This may take a few seconds..."+correctLoader);
		} else {
		$(".nextStage").html("This may take a few seconds..."+correctLoader);
		}
		$("#discountTokenHide").html("");
		for (var i=1;i <= discountTicketNo;i++) {
			discountContainer = $("<discount_token />");
			discounts = ($(".discount"+i+"").val());
			discountContainer.append(discounts);
			$("#discountTokenHide").append(discountContainer)
		}
		discountTokens = $("#discountTokenHide").html();
		var xmlCreateOrder = jQuery.createXMLDocument("<create_order>"+allowSelfPrint+"<user_id>"+userID+"</user_id><crypto_block>"+discountOptionCrypt+"</crypto_block>"+discountTokens+"</create_order>");
		$.ajax({
			type: "POST",
			contentType: "text/xml",
			data: xmlCreateOrder,
			processData: false,
			url:"/tickets/xml_core.exe",
			success: function(orderData) {		
				//var newBlockB = $(orderData).find('create_order_result').text().replace('/</g','&lt;').replace('/>/g','&gt;');
				//var xmlStringTwo = (new XMLSerializer()).serializeToString(orderData);
				//alert(xmlStringTwo);
				finalBlock = $(orderData).find('crypto_block').text();
				orderToken = $(orderData).find('order_token').text();
				var trolleyAdd = jQuery.createXMLDocument("<trolley_add_order>"+allowSelfPrint+"<user_id>"+userID+"</user_id><crypto_block>"+finalBlock+"</crypto_block><order_token>"+orderToken+"</order_token></trolley_add_order>");
				$.ajax({
					type: "POST",
					contentType: "text/xml",
					data: trolleyAdd,
					processData: false,
					url:"/tickets/xml_core.exe",
					success: function(resultData) {		
						//var newBlockB = $(resultData).find('trolley_add_order_result').text().replace('/</g','&lt;').replace('/>/g','&gt;');
						//var xmlStringTwo = (new XMLSerializer()).serializeToString(resultData);
						//alert(xmlStringTwo);
						addPossible = $(resultData).find('add_possible').text();
						trolleyBlock = $(resultData).find('crypto_block').text();
						trolleyToken = $(resultData).find('trolley_token').text();
						if (addPossible == 'yes') {
							if (eventProcess == 1) {
								if (noDiscounts == 0) {
								$(".processLoader").remove();
								}
								$('.dispatchSelectRadio').attr('disabled','disabled');
								$('.availSelect').attr('disabled','disabled');
								$('.selectDiscount').attr('disabled','disabled');
								$('#dateList').attr('disabled','disabled');
								$('#timeList').attr('disabled','disabled');
								$('.nextStage2').hide();
								;
								$("#trolleyButtons").show().append("<div class='itemAdded'>Item added successfully!</div><div class='payNow'>Pay for this now</div><div class='proceedToTrolley'>Proceed to Trolley</div><div class='contShopping'>Continue Shopping</div>")
									$(".proceedToTrolley").click(function() {
										$.cookie('trolleyBlock',trolleyBlock,{ expires: 2 });
										$.cookie('trolleyToken',trolleyToken,{ expires: 2 })
										window.location.replace("http://www.ticketswitch.com");
									});
									
									$(".payNow").click(function() {
											var trolleyQuery = jQuery.createXMLDocument("<get_reservation_link>"+allowSelfPrint+"<user_id>"+userID+"</user_id><crypto_block>"+trolleyBlock+"</crypto_block><trolley_token>"+trolleyToken+"</trolley_token></get_reservation_link>");
											$.ajax({
												type: "POST",
												contentType: "text/xml",
												data: trolleyQuery,
												processData: false,
												url:"/tickets/xml_core.exe",
												success: function(trolleyData) {
													//var newBlockB = $(trolleyData).find('trolley_describe_result').text().replace('/</g','&lt;').replace('/>/g','&gt;');
													//var xmlStringTwo = (new XMLSerializer()).serializeToString(trolleyData);
													//alert(xmlStringTwo);
													resLink = $(trolleyData).find('reservation_link').text();
													window.location.replace(resLink);
													
												
												}
										   });
									 });
							
							} else {
								var trolleyQuery = jQuery.createXMLDocument("<get_reservation_link>"+allowSelfPrint+"<user_id>"+userID+"</user_id><crypto_block>"+trolleyBlock+"</crypto_block><trolley_token>"+trolleyToken+"</trolley_token></get_reservation_link>");
								$.ajax({
									type: "POST",
									contentType: "text/xml",
									data: trolleyQuery,
									processData: false,
									url:"/tickets/xml_core.exe",
									success: function(trolleyData) {
										//var newBlockB = $(trolleyData).find('trolley_describe_result').text().replace('/</g','&lt;').replace('/>/g','&gt;');
										//var xmlStringTwo = (new XMLSerializer()).serializeToString(trolleyData);
										//alert(xmlStringTwo);
										resLink = $(trolleyData).find('reservation_link').text();
										window.location.replace(resLink);
										
									
									}
							   });
							}
							
						} else {
							$(".processLoader").remove();
							$("#trolleyButtons").show().append("this item could not be added to your basket at this time.")	
						}
					}
				});
			}
		});
	};
	
	function buyProcess() {
	fullBlock = fullXmlBlock.replace('crypto_block=','');
	ticketNo = $(this).val();
	thisDateList = $("<select id='dateList' class='ajaxDropdown' />");	
	thisDepList	 = $("<select id='depDate'  class='ajaxDropdown' />")
	thisTimeList = $("<select id='timeList'  class='ajaxDropdown' />");
	depDateDiv = $("<div class='departureDate' />");
	ticketTypeTable = $("<table id='ticketTable' />");	
	dispatchMethodTable = $("<table id='dispatchTable' />");
	depDateCollectList = $("<ul class='depCollectText' />")
	startedProcess = 0;
	dispatchChosen = 0;
	ticketTypeChosen = 0;
	$("#timeBox,#fixedTime,#typeAndNumber,#dispatchOptions,#discountOptions,ul.collectText,.noAvailability").hide();
	$("#calendarBox,#timeBox").html("");
		$("ul.collectText,.nextStage").hide().remove();
		$(".processLoader").remove();
		if (startedProcess == 0) {
			var xmlDoc = jQuery.createXMLDocument("<date_time_options>"+allowSelfPrint+"<user_id>"+userID+"</user_id><crypto_block>"+fullBlock+"</crypto_block><event_token>"+eventToken+"</event_token></date_time_options>")
			choiceNumber = 0;
			$.ajax({
				type: "POST",
				contentType: "text/xml",
				data: xmlDoc,
				processData: false,
				url:"/tickets/xml_core.exe",
				success: function(data) {
					startedProcess = 1;
					$("#dispatchTable,#ticketTable,#discountOptions,#discountTokenHide").html("");
					$("ul.collectText,.nextStage").hide().remove();
					$("#calendarBox").show();
					collectDepartTextTest = $(data).find('collect_text').length;
					thisDateList.append("<option class='noChoice' value=''> Please select a date</option>")
					//var newBlockA = $(data).find('performance').text().replace('/</g','&lt;').replace('/>/g','&gt;');
					//var xmlString = (new XMLSerializer()).serializeToString(data);
					//alert(xmlString);
					needDepDate	= $(data).find('need_departure_date').text();
						$(data).find('performance').each(function(){
							hasDateDesc = 0;
							choiceNumber += 1;
							checkNumber = choiceNumber-1;
							var listItemDateText 	= $(this).find('date_desc').text();									  
							var listItemDateVar 	= $("<option class='dateOption' id='itemNo"+choiceNumber+"'/>");
							var listItemDateValue 	= $(this).find('date_yyyymmdd').text();
							var limitedAvail 		= $(this).find('is_limited').text();
							if ($(this).find('date_desc').length > 0) {
								hasDateDesc = 1;
								var listItemPerfName	= $(this).find('perf_name').text();
							}
							if ($(this).find('date_yyyymmdd').text() != $(this).next().find('date_yyyymmdd').text()) {
								if (limitedAvail=="no") {listItemDateVar.text(listItemDateText);} else {listItemDateVar.text(listItemDateText +  "   Limited Availability!");	}
								listItemDateVar.attr('value',listItemDateValue)
								if (hasDateDesc == 1 && currentDateLingo == 1) {
									listItemDateVar.text(listItemPerfName);	
								}
								thisDateList.append(listItemDateVar);
							}
							dateTimeBlock = $(data).find('crypto_block').text();
						});
					if (needDepDate == "no") {
						$("#calendarBox").append("<div class='titleNode'>Date:</div>")
						$("#calendarBox").append(thisDateList)
						if (collectDepartTextTest > 0) {
							$(data).find('collect_text').each(function() {
								depCollectListItem = $("<li />")
								depCollectText = $(this).text();
								depCollectListItem.append(depCollectText);
								$(depDateCollectList).append(depCollectListItem)
							});
							$("#calendarBox").append(depDateCollectList)
						}	
					} else {
						$("#calendarBox").append("<div class='titleNode titleNodeDep'>Usage Date:</div>")
						$("#calendarBox").append(thisDateList)
					}
					$("select#dateList").change(function() {
						$("#timeBox").html("")
						$(".departureDate,select#depDate,ul.depCollectText").empty();
						$(".processLoader").remove();
						if ($(this).select("option").val()=='') {
							$("#timeBox,#fixedTime,#typeAndNumber,#typeAndNumber,#dispatchOptions,#discountOptions").hide();	
							$("#ticketTable,#dispatchTable,#discountOptions,#discountTokenHide").html("");
							$("ul.collectText, .nextStage").hide().remove();
							$(".processLoader").remove();
						} else {
							chosenDate = $(this).val();	
							$("#calendarBox").append(correctLoader);
							if ($(data).find('date_yyyymmdd:contains("'+chosenDate+'")').parent('performance').length > 1) { 
								if ($('performance').find('date_yyyymmdd').text() == $('performance').next().find('date_yyyymmdd').text()) {
									depDateCollectList.remove();
									thisTimeList.empty()
									$("#timeBox,#typeAndNumber").show();
									thisTimeList.append("<option class='noChoice' value=''>Please select a time</option>")
								}
								$(data).find('date_yyyymmdd:contains("'+chosenDate+'")').parent('performance').each(function(){
									listItemTimeText = $(this).find('time_desc').text();
									listItemTimeVal = $(this).find('time_hhmmss').text();	
									var listItemTimeVar = $("<option class='timeOption' />");
									listItemTimeVar.text(listItemTimeText);
									listItemTimeVar.attr('value',listItemTimeVal);
									thisTimeList.append(listItemTimeVar);
								});
								$("#fixedTime").hide();
								$("#typeAndNumber").hide();
								$("#timeBox").append("<div class='titleNode'>Time:</div>");
								$("#timeBox").append(thisTimeList);
								$("#ticketTable").html("");
								$("#dispatchTable").html("")
								$("#discountOptions").html("");
								$("#discountTokenHide").html("");
								$("ul.collectText").remove();
								$(".nextStage").remove();
								$(".processLoader").remove();
								$(".noAvailability").hide();
								if (collectDepartTextTest > 0) {
									$("#timeBox").append(depDateCollectList)
								}
							} else {
								if (needDepDate == "yes") {
									$(depDateCollectList).remove();
									$(".processLoader").remove();
									thisDepList.append("<option class='noOption' value=''>Please select a date</option> ")
									$(data).find('performance').each(function(){
										var listItemDepText 	= $(this).find('date_desc').text();									  
										var listItemDepVar 	= $("<option class='depOption' />");
										var listItemDepValue 	= $(this).find('date_yyyymmdd').text();
										if (listItemDepValue != $("select#dateList").select('option').val()) {
											listItemDepVar.text(listItemDepText);
											listItemDepVar.attr('value',listItemDepValue)
											thisDepList.append(listItemDepVar);
										} else {
										return false;
										}
									
									});
									depDateDiv.append("<div class='titleNode titleNodeDep'>Departure Date:</div>")
									depDateDiv.append(thisDepList);
									if (collectDepartTextTest > 0) {
										$(data).find('collect_depart_text collect_text').each(function() {
											depCollectListItem = $("<li />")
											depCollectText = $(this).text();
											depCollectListItem.append(depCollectText);
											$(depDateCollectList).append(depCollectListItem)
										});
										depDateDiv.append(depDateCollectList)
									}
									$("#calendarBox").append(depDateDiv);

								} else {
									$(".noAvailability").hide();
									$(".fixedTimeSpan").html("")
									$("#timeBox").hide();	
									$("#fixedTime").show();
									$("#typeAndNumber").show();
									$("#ticketTable").html("");
									$("#dispatchTable").html("")
									$("#discountOptions").html("")
									$("#discountTokenHide").html("");
									$("ul.collectText").remove();
									$(".nextStage").remove();
									$(data).find('date_yyyymmdd:contains("'+chosenDate+'")').parent('performance').each(function(){		
										listItemTimeText = $(this).find('time_desc').text();
										listItemTimeVal	 = $(this).find('time_hhmmss').text();
										$(".fixedTimeSpan").append(listItemTimeText);
										timeAndDateChosen();
									});
								}
							}
							
						}
						$("select#depDate").change(function() {
							if (!$(this).select('option').val()=='') {
								depDateValue = $(this).select('option').val();
								$("#calendarBox").append(correctLoader);
								timeAndDateChosen();
							} else {
								$(".noAvailability").hide();
								$("#typeAndNumber").hide();
								$("#dispatchOptions").hide();
								$("ul.collectText").remove();
								$(".nextStage").remove();
							}
						});								
															
						$("select#timeList").change(function() {					
							if (!$(this).select('option').val()=='') {
								$(".processLoader").remove();
								listItemTimeVal = $(this).select('option').val();
								$("#timeBox").append(correctLoader);
								timeAndDateChosen();
							} else {
								$("#typeAndNumber").hide();
								$("#dispatchOptions").hide();
								$("ul.collectText").remove();
								$(".nextStage").remove();
							}
						});
					});
					function timeAndDateChosen () {
						//alert(chosenDate+listItemTimeVal+dateTimeBlock)
						$(".noAvailability").hide();
						$("#ticketTable").html("");
						$("#typeAndNumber").hide();
						$("#dispatchTable").html("");
						$("#discountOptions").hide().html("");
						$("#discountTokenHide").html("");
						$("ul.collectText").remove();
						$(".nextStage").remove();
						$(data).find('date_yyyymmdd:contains("'+chosenDate+'")').parent('performance').each(function() {
							if ($(this).find('time_hhmmss').length < 1) {
								chosenPerfToken = $(this).find('perf_token').text();
								$("#fixedTime").hide();
									findTicketNumbers();
							} else {
								if ($(this).find('time_hhmmss').text()==listItemTimeVal) {																						 
									chosenPerfToken = $(this).find('time_hhmmss:contains("'+listItemTimeVal+'")').parent().find('perf_token').text();
									findTicketNumbers();
								}
							}
						});
						
					}
					function findTicketNumbers() {
						$("#dispatchTable").html("")
						$("#ticketTable").html("");
						$("#discountOptions").html("")
						$("#discountTokenHide").html("");
						$("ul.collectText").remove();
						$(".nextStage").remove();
						//alert(dateTimeBlock+" "+chosenPerfToken)
						if (needDepDate == "yes") {
							var xmlFindTickets = jQuery.createXMLDocument("<availability_options>"+allowSelfPrint+"<user_id>"+userID+"</user_id><crypto_block>"+dateTimeBlock+"</crypto_block><perf_token>"+chosenPerfToken+"</perf_token><departure_date>"+depDateValue+"</departure_date></availability_options>")
						} else {
							var xmlFindTickets = jQuery.createXMLDocument("<availability_options>"+allowSelfPrint+"<user_id>"+userID+"</user_id><crypto_block>"+dateTimeBlock+"</crypto_block><perf_token>"+chosenPerfToken+"</perf_token></availability_options>")
						}
						$.ajax({
							type: "POST",
							contentType: "text/xml",
							data: xmlFindTickets,
							processData: false,
							url:"/tickets/xml_core.exe",
							success: function(ticketData) {
								isAvailable = $(ticketData).find('ticket_type').length;
								$(".processLoader").remove();
								$("#dispatchTable").html("");
								$("#discountOptions").html("")
								$("#discountTokenHide").html("");
								$("#ticketTable").html("");
								$("ul.collectText").remove();
								$(".nextStage").remove();
								if (isAvailable < 1) {
									$(".noAvailability").slideDown();
								} else {
									$(".noAvailability").hide();
									ticketTypeTable.prepend("<tr><th class='ticketTypeCell'>Ticket Type</th><th class='ticketPriceCell'>Price</th><th class='ticketChargeCell'>Processing Fee</th><th class='ticketTotalCell'>Total</th><th class='ticketNumberAvail'>How many?</th></tr>")
									dispatchMethodTable.prepend("<tr><th class='dispatchTypeCell headDisabled dispatchHead'>Dispatch Method</th><th class='dispatchPriceCell headDisabled dispatchHead'>Cost</th><th class='dispatchSelectCell headDisabled dispatchHead'>Select</th></tr>")
	
									$("#typeAndNumber").show();
									$("#dispatchOptions").show();
									$("#discountOptions").show();
									//var newBlockB = $(ticketData).find('performance').text().replace('/</g','&lt;').replace('/>/g','&gt;');
									//var xmlStringTwo = (new XMLSerializer()).serializeToString(ticketData);
									//alert(xmlStringTwo);
									ticketTypeCurrency	= $(ticketData).find('currency_pre_symbol').text();
									ticketTypeCrypto	= $(ticketData).find('crypto_block').text();
									$(ticketData).find('ticket_price').each(function() {
										ticketTypeRow 		 = $("<tr class='ticketTypeRow' />")
										ticketTypeDesc		 = $(this).parent().parent().find('ticket_type_desc').text();
										ticketTypePrice		 = parseInt($(this).parent().find('ticket_price').text()*100)/100;
										ticketTypeSurcharge  = parseInt($(this).parent().find('surcharge').text()*100)/100;
										ticketTypeAvail		 = parseInt($(this).parent().find('number_available').text());
										ticketTypeBandToken	 = $(this).parent().find('band_token').text();
										ticketTypeDescCell	 = $("<td class='ticketTypeCell' />");
										ticketTypePriceCell	 = $("<td class='ticketPriceCell' />");
										ticketTypeChargeCell = $("<td class='ticketChargeCell' />");
										ticketTypeTotalCell	 = $("<td class='ticketTotalCell' />");
										ticketTypeAvailCell	 = $("<td class='ticketNumberAvail' />");
										ticketTypeAvailSelect = $("<select class='availSelect' />");						
										ticketTypeBandInput	 = $("<input type='hidden' class='bandTokenClass' name='bandToken' />")
										ticketTypePriceFormat = ticketTypePrice.toFixed(2);
										ticketTypeSurchargeFormat = ticketTypeSurcharge.toFixed(2);
										ticketTypeTotalFormat = (ticketTypePrice+ticketTypeSurcharge).toFixed(2);
										ticketTypeBandInput.attr('value',ticketTypeBandToken);
										ticketTypeDescCell.append(ticketTypeDesc);
										ticketTypePriceCell.append(ticketTypeCurrency);
										ticketTypePriceCell.append(ticketTypePriceFormat);
										ticketTypeChargeCell.append(ticketTypeCurrency);
										ticketTypeChargeCell.append(ticketTypeSurchargeFormat);
										ticketTypeTotalCell.append(ticketTypeCurrency);
										ticketTypeTotalCell.append(ticketTypeTotalFormat);
										for (var i=0;i <= ticketTypeAvail;i++) {
											ticketTypeAvailSelect.append("<option value="+i+">"+i+"</option>")
										}
										ticketTypeAvailCell.append(ticketTypeAvailSelect);
										ticketTypeAvailCell.append(ticketTypeBandInput);
										ticketTypeRow.append(ticketTypeDescCell);
										ticketTypeRow.append(ticketTypePriceCell);
										ticketTypeRow.append(ticketTypeChargeCell);
										ticketTypeRow.append(ticketTypeTotalCell)
										ticketTypeRow.append(ticketTypeAvailCell)
										ticketTypeTable.append(ticketTypeRow);
									});
									
									$(ticketData).find('despatch_method').each(function(){
										dispatchTypeRow 		 = $("<tr class='dispatchTypeRow' />")
										dispatchTypeDesc		 = $(this).find('despatch_desc').text();
										dispatchTypePrice		 = parseInt($(this).find('despatch_cost').text()*100)/100;
										dispatchTypeBlock		 = $(this).find('despatch_token').text();
										dispatchTypeSelect		 = $("<input type='radio' class='dispatchSelectRadio' name='dispatchOptionsRadio' />");
										dispatchPriceFormat		 = dispatchTypePrice.toFixed(2);
										dispatchTypeDescCell	 = $("<td class='dispatchTypeCell dispatchCell dispatchTypeDisabled' />");
										dispatchTypePriceCell	 = $("<td class='dispatchPriceCell dispatchCell dispatchTypeDisabled' />");
										dispatchTypeSelectCell	 = $("<td class='dispatchSelectCell dispatchCell dispatchTypeDisabled' />");
										dispatchTypeDescCell.append(dispatchTypeDesc);
										dispatchTypePriceCell.append(ticketTypeCurrency);
										dispatchTypePriceCell.append(dispatchPriceFormat);
										dispatchTypeSelect.attr('value', dispatchTypeBlock);
										dispatchTypeSelect.attr('disabled','disabled');
										dispatchTypeSelectCell.append(dispatchTypeSelect);
										dispatchTypeRow.append(dispatchTypeDescCell);
										dispatchTypeRow.append(dispatchTypePriceCell);
										dispatchTypeRow.append(dispatchTypeSelectCell);
										dispatchMethodTable.append(dispatchTypeRow);
									});
									ticketCollectTextList = $("<ul class='collectText' />");
									$(ticketData).find('collect_seats_text collect_text').each(function() {
										collectTextListItem = $("<li class='collectItem' />");
										collectTextListText = $(this).text();
										collectTextListItem.append(collectTextListText);
										ticketCollectTextList.append(collectTextListItem);
									 });
									$(".collectTextInfo").append(ticketCollectTextList).show();
	
									$("#typeAndNumber").append(ticketTypeTable);
									$("#dispatchOptions").append(dispatchMethodTable);
									$(".nextStage").remove();
									$("#dispatchOptions").append("<div class='nextStage nextStageDisabled'>Next</div>");
									$(".nextStage").show();
									
									
									
									$(".availSelect:last").parent().parent().addClass("lastRow")
									$(".availSelect:last").parent().addClass("lastOption")
									$(".dispatchSelectRadio:last").parent().parent().addClass("lastRow")
									$(".dispatchSelectRadio:last").parent().addClass("lastOption")
									
									$(".availSelect").change(function() {
										if ($(this).find("option:selected").val()!=0) {
									
											$(this).addClass("chosenSelect");
												noOfTickets = $(".chosenSelect").val();
												chosenBandToken = $(".chosenSelect").parent().find("input.bandTokenClass").val();
										
											$(".availSelect").parent().addClass("disabledSelect");
											$(".chosenSelect").parent().removeClass("disabledSelect");
											$(".disabledSelect").find('select').attr("disabled","disabled")
											$(".dispatchCell").removeClass("dispatchTypeDisabled");
											$(".dispatchHead").removeClass("headDisabled");
											//$(".ticketTypeWarning").show();			
											$('.dispatchSelectRadio').removeAttr('disabled');
											ticketTypeChosen = 1;
											$("#discountOptions").html("")
											$("#discountTokenHide").html("");
											$(".nextStage").show();
											if (dispatchChosen == 1) {
												$(".nextStage").removeClass('nextStageDisabled')
											}
										} else {
											$(".availSelect").removeAttr('disabled').removeClass("chosenSelect").parent().removeClass("disabledSelect");
											//$(".ticketTypeWarning").hide();
											$(".dispatchCell").addClass("dispatchTypeDisabled");
											$(".dispatchSelectRadio").attr('disabled','disabled');
											$(".dispatchHead").addClass("headDisabled")
											$(".nextStage").addClass('nextStageDisabled')
											ticketTypeChosen = 0;
											$("#discountOptions").html("");
											$("#discountTokenHide").html("");
											$(".nextStage").show();
										}
									  });
									
									
									
									$(".dispatchSelectRadio").click(function() {
										if(this.checked && ticketTypeChosen == 1){
											dispatchToken = $(this).val();
											dispatchChosen = 1;
											$(".nextStage").removeClass('nextStageDisabled')
										}
									}); 
									$("input[name='dispatchOptionsRadio']").change(function() {
										$("#discountOptions").html("");
										$("#discountTokenHide").html("");
										$(".nextStage").show();
									})
									
									$(".nextStage").click(function() {
										if (ticketTypeChosen==1 && dispatchChosen==1)	{
											$(".nextStage").append(correctLoader);
											var xmlFindDisc = jQuery.createXMLDocument("<discount_options>"+allowSelfPrint+"<user_id>"+userID+"</user_id><crypto_block>"+ticketTypeCrypto+"</crypto_block><band_token>"+chosenBandToken+"</band_token><no_of_tickets>"+noOfTickets+"</no_of_tickets><despatch_token>"+dispatchToken+"</despatch_token></discount_options>")
											$("#discountOptions").html("")
											$("#discountTokenHide").html("");
											$.ajax({
												type: "POST",
												contentType: "text/xml",
												data: xmlFindDisc,
												processData: false,
												url:"/tickets/xml_core.exe",
												success: function(discountData) {
													$(".processLoader").remove();
													//var newBlockB = $(discountData).find('discount_options_result').text().replace('/</g','&lt;').replace('/>/g','&gt;');
													//var xmlStringTwo = (new XMLSerializer()).serializeToString(discountData);
													//alert(xmlStringTwo);
													discountOptionCrypt		= $(discountData).find('crypto_block').text();
													discountTicketNo		= 0;
													discountChoices = $(discountData).find('has_discount_choices').text();
													if (discountChoices == 'yes') {
														$(discountData).find('discounts').each(function() {
															discountTicketNo ++;
															discountSelect		= $("<select class='selectDiscount discount"+discountTicketNo+"' />");
															$(this).find('discount').each(function() {
																discountOption		= $("<option class='discountOption' />")
																discountDesc		= $(this).find('discount_desc').text();
																discountValue		= $(this).find('discount_token').text();
																discountPrice		= parseInt($(this).find('ticket_price').text()*100)/100;
																discountCharge		= parseInt($(this).find('surcharge').text()*100)/100;
																discountPriceFormat = discountPrice.toFixed(2);
																discountChargeFormat= discountCharge.toFixed(2);
																discountOption.attr('value',discountValue);
																discountOption.append(discountDesc+" ("+ticketTypeCurrency+discountPriceFormat+" + "+ticketTypeCurrency+discountChargeFormat+")");
																discountSelect.append(discountOption);
															});
															$("#discountOptions").append("<div class='ticketNumberHead'>Ticket "+discountTicketNo+":</div>")
															$("#discountOptions").append(discountSelect)
														});
														$("#discountOptions").prepend("<div class='popupProcessHeading'>Discount options</div>");
														$(".nextStage").hide();
														$("#discountOptions").append("<div class='nextStage2'>Buy Now!</div>");
														$(".nextStage2").click(function() {
															stageTwo();								
														})
													} else {
														$(discountData).find('discounts').each(function() {
															discountTicketNo ++;
															discountSelect		= $("<select class='selectDiscount discount"+discountTicketNo+"' />");
															noDiscounts = 1;
															$(this).find('discount').each(function() {
																discountOption		= $("<option class='discountOption' />")
																discountDesc		= $(this).find('discount_desc').text();
																discountValue		= $(this).find('discount_token').text();
																discountPrice		= parseInt($(this).find('ticket_price').text()*100)/100;
																discountCharge		= parseInt($(this).find('surcharge').text()*100)/100;
																discountPriceFormat = discountPrice.toFixed(2);
																discountChargeFormat= discountCharge.toFixed(2);
																discountOption.attr('value',discountValue);
																discountOption.append(discountDesc+" ("+ticketTypeCurrency+discountPriceFormat+" + "+ticketTypeCurrency+discountChargeFormat+")");
																discountSelect.append(discountOption);
															});
															$("#discountOptions").hide().append(discountSelect)
														});
														stageTwo();
													}
												}
											});
										}					   
									});
								}
							}
						});
					}
				}
			});
		}	
	}
	if (eventProcess == 1) {
		buyProcess();		
	}
	emailSent = 0;
	$("#miniTrolley").hide();
	$('#sendToFriendName').val("");
	$('#sendToFriendEmail').val("");
	$('#sendToFriendName2').val("");
	enteringEmail = 0;
		if (!trolleyCount == 0) {
			$(".hoverBasket").hover(function() {
				clearTimeout($(this).data('timeout'));
				if (trolleyCount == 0) {} else {
					$("#miniTrolley").slideDown('normal');
					$("#search-panel").css({"background-image":"none"})
				}
			},function() {
				if (enteringEmail == 1 && emailSent == 0) {} else {
					var timeOutConfig = setTimeout(function() {
						$("#miniTrolley").slideUp('normal');
						$("#search-panel").css({"background-image":"url(/shared/images/user_id/globaltickets/search-panelCurve.png)"});
						$(".confirmDelete").slideUp("normal");
						$(".sendToFriend").slideUp("normal");
						$('*').removeClass('deleting').removeClass("emailing");
						$('img.blankCover').hide();
						$('.confirmEmpty').slideUp("normal");
						$('#sendToFriendName').val("").removeClass('right').removeClass('wrong').addClass('yellowClass');
						$('#sendToFriendEmail').val("").removeClass('right').removeClass('wrong').addClass('yellowClass');
						$('#sendToFriendName2').val("").removeClass('right').removeClass('wrong').addClass('yellowClass');
	
					}, 1000);
					$(this).data('timeout', timeOutConfig);
				}
			   });
		}
	
	$('.confirmEmptyNo').click(function() {
		$('.confirmEmpty').slideUp("normal");
		$('*').removeClass('deleting').removeClass("emailing");
		$('img.blankCover').hide();
	});
	
	$(".hoverTrolleyItemSpace").css({"margin-bottom":"10px"});
	$(".hoverTrolleyItemSpace:last").css({"margin-bottom":"0px"})							   
	
	
	$(".miniRemove").click(function() {
		$(this).parent().parent().addClass('deleting');
		$('.deleting').find('img.blankCover').show();
		$('.deleting').find(".confirmDelete").slideDown("normal");
		$(".sendToFriend").slideUp("normal");
		$('*').removeClass("emailing");
		
	});
	
	$(".removeTrolleyAll").click(function() {
		$(".hoverTrolleyItem").addClass('deleting');
		$('img.blankCover').show();
		$('.confirmEmpty').slideDown("normal");
	
		$(".sendToFriend").slideUp("normal");
		
	});
	$(".cancelSendToFriend").click(function() {
		$(".sendToFriend").slideUp("normal");
		$('#sendToFriendName').val("").removeClass('right').removeClass('wrong').addClass('yellowClass');
		$('#sendToFriendEmail').val("").removeClass('right').removeClass('wrong').addClass('yellowClass');
		$('#sendToFriendName2').val("").removeClass('right').removeClass('wrong').addClass('yellowClass');
		$('.nameOneError').hide();
		$('.nameTwoError').hide();
		$('.errorTable').html("");
		enteringEmail = 0;

	});
	
	$(".mailTrolley").click(function() {
		$(".hoverTrolleyItem").removeClass('deleting');
		$('img.blankCover').hide();
		$('.confirmEmpty').slideUp("normal");
		$(".sendToFriend").slideDown("normal");
		enteringEmail = 1;

	});
	
	$(".confirmDeleteNo").hover(function() {$(this).css({"color":"#cc3300"})},function(){$(this).css({"color":"#e75b2b"});});						
	$(".confirmDeleteYes").hover(function() {$(this).css({"color":"#92af0a"})},function(){$(this).css({"color":"#acc33b"});});				
	$(".confirmEmptyNo").hover(function() {$(this).css({"color":"#cc3300"})},function(){$(this).css({"color":"#e75b2b"});});						
	$(".confirmEmptyYes").hover(function() {$(this).css({"color":"#92af0a"})},function(){$(this).css({"color":"#acc33b"});});	
	$(".hoverTrolleyItemSpace").hover(function() {
		$(this).css({"background":"#d1e3ef url(/shared/images/user_id/globaltickets/hoverTrolleyItemTopB.gif) top right no-repeat"})
		$(this).find(".hoverTrolleyItemBox").css({"background":"#fff url(/shared/images/user_id/globaltickets/hoverTrolleyItemBottomB.gif) bottom right no-repeat"})
		$(this).find(".miniRemove img").css({"background-position":"bottom left"})
		$(this).find(".confirmDeleteYes img").css({"background-position":"left"})
		$(this).find(".confirmDeleteNo img").css({"background-position":"left"})
	}, function() {
		$(this).css({"background":"#d1e3ef url(/shared/images/user_id/globaltickets/hoverTrolleyItemTopB.gif) top left no-repeat"})
		$(this).find(".hoverTrolleyItemBox").css({"background":"#f0f0f0 url(/shared/images/user_id/globaltickets/hoverTrolleyItemBottomB.gif) bottom left no-repeat"})	
		$(this).find(".miniRemove img").css({"background-position":"top left"})
		$(this).find(".confirmDeleteYes img").css({"background-position":"right"})
		$(this).find(".confirmDeleteNo img").css({"background-position":"right"})
	})
	
	$(".miniRemove").hover(function() {
		$(this).find('img').css({"background-position":"bottom right"});								
	}, function() {
		$(this).find('img').css({"background-position":"bottom left"});
	});
	
	
	$(".trolleyToolbar").hover(function() {
		$(this).css({"background-position":"right bottom"})
		$(".miniTrolleyIcon").css({"background-position":"left bottom"})
		},function(){
		$(this).css({"background-position":" right top"})
		$(".toolHintIndicate").hide();
		$(".miniTrolleyIcon").css({"background-position":"left top"})
    	$(".miniTrolleyHint").slideUp("fast");

	})
	
	whoTo = 0;
	$(".sendOutNote").click(function() {$(this).hide();$(".sendOut").slideDown("normal");$(".sendOutNote2").show();$(".sendingToFriend").show();$("#sendToFriendName2").val("");$("#sendToFriendName2").val("").removeClass('wrong').removeClass('right').addClass('yellowClass');whoTo = 1;});
	$(".sendOutNote2").click(function() {$(this).hide();$(".sendOut").slideUp("normal");$(".sendOutNote").show();$(".sendingToFriend").hide();$("#sendToFriendName2").val("");whoTo = 0;})
	
	$("#sendToFriendName").focus(function() {
		$(this).addClass('yellowClass');
	});
	
	$("#sendToFriendName").blur(function() {
		if (!$(this).val()=='') {
			if ($(this).val().length<=2) {
				$(this).removeClass('yellowClass').addClass('wrong').removeClass('right')
			} else {
				$(this).addClass('right').removeClass('yellowClass').removeClass('wrong')
				$(".nameOneError").hide();
			}
		}
	})
	
		$("#sendToFriendName2").focus(function() {
			if (whoTo == 1) {
				$(this).addClass('yellowClass');
			}
		});
		$("#sendToFriendName2").blur(function() {
			if (whoTo == 1) {
				if (!$(this).val()=='') {
					if ($(this).val().length<=2) {
						$(this).removeClass('yellowClass').addClass('wrong').removeClass('right')
					} else {
						$(this).addClass('right').removeClass('yellowClass').removeClass('wrong')
						$(".nameTwoError").hide();
					}
				}
			}
		})
	
    var feedbackCookie = $.cookie('feedback');
    var name = $("#feedbackArea");
    var menuYloc = null;
    var nameForm = $("#feedbackFormArea");
    var isOpen = 0;

    $(".feedback").hover(function() {$(this).css({"color":"#333333"})},function() {$(this).css({"color":"#666666"})});
    $(".feedback").click(function() {

        $.cookie("feedback", null);
        $(document).ready(function(){
            menuYloc = parseInt(name.css("top").substring(0,name.css("top").indexOf("px")))
            $(window).scroll(function () {
                offset = $(document).scrollTop()+"px";
                name.animate({top:offset},{duration:500,queue:false});
            });
        });
        $(document).ready(function(){
            menuYloc = parseInt(nameForm.css("top").substring(0,nameForm.css("top").indexOf("px")))
            $(window).scroll(function () {
                offset = $(document).scrollTop()+"px";
                nameForm.animate({top:offset},{duration:500,queue:false});
            });
        });
        $("#feedbackMessageGood").val("");
        $("#feedbackMessageBad").val("");
        $("#easeOfUseSlider").slider('option', 'value',  50);
        $("#functionalitySlider").slider('option', 'value',  50);
        $("#choiceOfTicketsSlider").slider('option', 'value',  50);
        $("#feedbackFormArea").css({"display":"block"}).animate({width: "250px"}, {queue:false, duration: 1700, easing: 'easeOutBounce'});
        $("#feedbackArea").css({'width':'26px', 'display':'block'}).animate({right:"250" + "px"},{queue:false, duration:1700, easing: 'easeOutBounce'});
        isOpen = 1;
        $("#feedbackClose").click(function () {
            if (isOpen == 1) {
                    $("#feedbackFormArea").animate({width: "0px"}, {queue:false, duration: 1700, easing: 'easeOutBounce'});
                    $("#feedbackArea").animate({right:"0" + "px"},{queue:false, duration:1700, easing: 'easeOutBounce'});
                    isOpen = 0;
            } else {
                    $("#feedbackArea").animate({width:"0" + "px"},"slow").queue(function() {$("#feedbackArea").css({"display":"none"})});
                    $.cookie('feedback', 'off');
            }
        });

    return false;
    });

   $('.resizeMostRecent').css({"background" : "url(/shared/images/user_id/globaltickets/miniImageBorder.png) top no-repeat"});
   $('.resizeMostRecent img').attr('src',"/shared/images/user_id/globaltickets/selectedLastTransImageCover.png");
   $(".finderLastTrans a").hover(function(){
            currentTitle 		= $(this).find(".selectItemName").val();
            currentVenue 		= $(this).find(".selectItemVenue").val();
            currentPrice 		= $(this).find(".selectItemPrice").val();
            currentLink 		= $(this).find(".selectItemLink").val();
            currentBook 		= $(this).find(".selectItemBook").val();
            currentEventId 		= $(this).find(".selectItemId").val();
			currentDateLingo	= $(this).find(".lastTransLoopIndex").val();
            imgHref 			= $(this).attr('href');
            featuredPosition 	= $(this).offset();
            featuredWidth 		= "220";
            
		    $(".finderLastTrans a").removeClass("selectedTrans");
            $(".finderLastTrans a").addClass("nonSelectedTrans");
            $(this).addClass("selectedTrans");
            $(this).removeClass("nonSelectedTrans")
            $('.selectedTrans img').attr('src',"/shared/images/user_id/globaltickets/selectedLastTransImageCover.png");
            $('.nonSelectedTrans img').attr('src',"/shared/images/user_id/globaltickets/lastTransImageCover.png");
            $('.finderLastTrans').css({"background" : "transparent"});
            $(this).parent('.finderLastTrans').css({"background" : "url(/shared/images/user_id/globaltickets/miniImageBorder.png) top no-repeat"});
            $("#popupFeaturedItem").show().css({"left":featuredPosition.left - featuredWidth, "top":featuredPosition.top + "px"})
            $(".popupFeaturedLoader").html("<img src='/shared/images/loader-grey.gif' />").css({"margin-top":"20px","margin-left":"15px","display":"block"});
            $(".big").css({"display": "none"});
            $.ajax({
                type: "GET",
                url: '/tickets/xml_feed.buy/'+userID+'?'+lastTransFeed+'&use_cities=yes&event_ids='+currentEventId,
                dataType: "xml",
                success: function(xml) {
                    $(xml).find('event_list').each(function(){
                        $(".popupFeaturedLoader").html("").css({"margin-top":"0px","margin-left":"0px","display":"none"});;
                        $(".big").attr('src',imgHref);
                        $(".big").show();
                        $(".popupFeaturedTitle").html($(this).find('event_desc').text());
                        $(".popupFeaturedVenue").html($(this).find('venue_desc').text());
//                        $(".popupFeaturedVenue").append(", " + $(this).find('area_desc').text());                         // AREA DESCRIPTION
                        $(".popupFeaturedVenue").append(", " + $(this).find('city_desc').text());                           // CITY DESCRIPTION
                        $(".popupFeaturedPrice").html(currentPrice);
                    });
                }
            });
        });

        $('.lastTransThumbs').hover (function() {},function() {
            $(".hoverImage").attr('src','#')
            $("#popupFeaturedItem").animate({opacity: "hide"}, "normal");
            $(".popupFeaturedTitle").html("");
            $(".popupFeaturedVenue").html("");
            $(".popupFeaturedCity").html("");
            $(".popupFeaturedPrice").html("");
        });

    $(".buttonEventInfoPopup").click(function(){
        $("#popupSummary").html("");
        eventToken =  currentEventId;
	    $.ajax({
         type: "GET",
         url: '/tickets/xml_feed.buy/'+userID+'?'+lastTransFeed+'&event_ids='+currentEventId+'&mime_text_type=html',
         dataType: "xml",
         success: function(xml) {
             $(xml).find('event_info').each(function(){
                    var eventInformation = $(this).text();
                    $('<div id="popupEventInformation"></div>').html(eventInformation).appendTo('#popupSummary');
					
			   });
			   buyProcess();
               $(".quickBuyButton").click(function() {
					$("#popupEventInfo .NumberOfTicketsContainer").slideDown();
					$("#popupEventInfo #popupButtons").slideUp();
					$("#popupEventInformation").animate({height:"100px"},500);
					
											 
			 });
			}
         });
        $("#popupTitle").html(currentTitle);
        $("#popupVenue").html(currentVenue);
        $("#popupPrice").html(currentPrice);
        $("a.selectedLink").attr('href',currentLink);
        $("a.bookLink").attr('href',currentBook);
    });
    if (feedbackCookie == 'off') {
        $("#feedbackArea").css({'display': 'none'});
    } else {
        $("#feedbackFormArea").css('width', '0px');
            $(document).ready(function(){
                menuYloc = parseInt(name.css("top").substring(0,name.css("top").indexOf("px")))
                $(window).scroll(function () {
                    offset = menuYloc+$(document).scrollTop()+"px";
                    name.animate({top:offset},{duration:500,queue:false});
                });
            });
            $(document).ready(function(){
                menuYloc = parseInt(nameForm.css("top").substring(0,nameForm.css("top").indexOf("px")))
                $(window).scroll(function () {
                    offset = menuYloc+$(document).scrollTop()+"px";
                    nameForm.animate({top:offset},{duration:500,queue:false});
                });
            });
            $("#feedbackOpen").toggle(function () {
                $("#feedbackMessageGood").val("");
                $("#feedbackMessageBad").val("");
                $("#easeOfUseSlider").slider('option', 'value',  50);
                $("#functionalitySlider").slider('option', 'value',  50);
                $("#choiceOfTicketsSlider").slider('option', 'value',  50);
                $("#feedbackFormArea").css({"display":"block"}).animate({width: "250px"}, {queue:false, duration: 1700, easing: 'easeOutBounce'});
                $("#feedbackArea").animate({right:"250" + "px"},{queue:false, duration:1700, easing: 'easeOutBounce'});
                isOpen = 1;
            },
            function () {
                $("#feedbackFormArea").animate({width: "0px"}, {queue:false, duration: 1700, easing: 'easeOutBounce'});
                $("#feedbackArea").animate({right:"0" + "px"},{queue:false, duration:1700, easing: 'easeOutBounce'});
                isOpen = 0;
            });
            $("#feedbackClose").click(function () {
                if (isOpen == 1) {
                        $("#feedbackFormArea").animate({width: "0px"}, {queue:false, duration: 1700, easing: 'easeOutBounce'});
                        $("#feedbackArea").animate({right:"0" + "px"},{queue:false, duration:1700, easing: 'easeOutBounce'});
                        isOpen = 0;
                } else {
                        $("#feedbackArea").animate({width:"0" + "px"},"slow").queue(function() {$("#feedbackArea").css({"display":"none"})});
                        $.cookie('feedback', 'off');
                }
            });
        }
    if ($(".fine").val()=='') {
        $(".fine").removeClass("yellowClass")
    } else {
        $(".fine").addClass("yellowClass")
    }
    $("#feedbackMessageGood").focus(function() {
        $("#feedbackMessageGood").addClass("right") ;
        $(".capitalRight").addClass("capitalRightFocused")
    });
    $("#feedbackMessageGood").blur(function() {
        $(".capitalRight").removeClass("capitalRightFocused")
        if ($("#feedbackMessageGood").val()=='') {
            $(this).removeClass("right")
        }
    });

    $("#feedbackMessageBad").focus(function() {
        $("#feedbackMessageBad").addClass("wrong")  ;
        $(".capitalWrong").addClass("capitalWrongFocused")

    });
    $("#feedbackMessageBad").blur(function() {
        $(".capitalWrong").removeClass("capitalWrongFocused")

        if ($("#feedbackMessageBad").val()=='') {
            $(this).removeClass("wrong")
        }
    });
    $(".fine").focus(function() {
        $(this).addClass("yellowClass") ;
    });
    $(".fine").blur(function() {
        if ($(this).val()=='') {
            $(this).removeClass("yellowClass")
        }
    });



    $(".feedbackSubmit").click(function () {
		feedbackName = $("#feedbackName").val();
		email = $("#feedbackEmail").val();
		message_one = $("#feedbackMessageGood").val();
		message_two = $("#feedbackMessageBad").val();
		dest_email_addr = $("#toField").val();
		script_name = $("#feedback_script_name").val();
		event_desc = $("#feedback_event_desc").val();
		part_query = $("#feedback_part_query").val();
		feedbackSubject = $("#feedbackSubject").val();
		dataString = '&first_name=' + feedbackName + '&dest_email_addr=' + dest_email_addr + '&email_address=' + email + '&message_one=' + message_one + '&feedbackScriptName=' + script_name + '&feedbackEventDesc=' + event_desc + '&feedbackPartQuery=' + part_query + '&subject=' + feedbackSubject + '&message_two=' + message_two ;
		ease =          $("#easeOfUseSlider").slider('option', 'value');
		functionality = $("#functionalitySlider").slider('option', 'value');
		choice =        $("#choiceOfTicketsSlider").slider('option', 'value');
  		$.ajax({
            type: "POST",
            url: feedbackPath+"?"+feedbackQuery,
            data: dataString + '&feedbackEase=' + ease + '&feedbackFunctionality=' + functionality + '&feedbackChoice=' + choice,
            success: function() {
				$('#feedbackFormArea').html("<div id='feedbackSuccessMessage'></div>");
                $('#feedbackSuccessMessage').html("<h2>Your feedback form is being submitted.</h2>")
                $('#feedbackSuccessMessage').append("<img id='feedbackLoader' src='/shared/images/user_id/globaltickets/loaderOrange.gif' />")
                .hide()
                 .fadeIn(1500, function() {
                    $('#feedbackSuccessMessage').html("<img id='feedbackLoader' src='/shared/images/user_id/globaltickets/feedbackSentThanks.png' />")
                    $('#feedbackSuccessMessage').append("<img id='feedbackSent' src='/shared/images/user_id/globaltickets/feedbackSent.jpg' />").queue(function() {
                    $("#feedbackFormArea").animate({width: "0px"}, {queue:false, duration: 2500, easing: 'easeOutBounce'});
                    $("#feedbackArea").animate({right:"0" + "px"},{queue:false, duration:2500, easing: 'easeOutBounce'});
                    });

                });
            },
			error: function () {
				alert("Sorry, your message could not be sent at this time.  Please try later, or contact us at: \n \n feedback@ticketswitch.com")
			}
        });
		return false;
     });


            var newsList = $("<ul id='feedNews' />");
            var speed = 0;
            var pause = 7000;
            var pagePlace=5;
            testVar = xmlFeed+userID+"?"+newsBlock+"&page_len=" + newsLength;
            testVarTwo = xmlFeed+userID+"?"+newsBlock+"&item_limit=1";
            $.ajax({
                type: "GET",
                url: testVar,
                dataType: "xml",
                success: function(xml) {
                    if (newsBlock == "undefined" || newsBlock == null) {
                        newsBlock = "testBlock1";
                    }
                    $(xml).find('event').each(function(){
                        var link =                  $("<a class='recentProduct' />");
                        var newsRssNewsTitle =      $(this).find('event_desc').text();
                        var newsRssNewsText =       $(this).find('event_info').text();
                        var newsRssNewsLink =       $(this).find('event_info_button_url').text();
                        var newsRssNewsElement =    $("<li class='rightColumnListItem' />").hover(function() {$(this).css({"background-position":"2px 1px"})},function() {$(this).css({"background-position":"2px -73px"})});
                        var separator =             $("<div class='rightColumnSeparator' />");
                        link.attr("href",newsRssNewsLink);
                        link.text(newsRssNewsTitle);
                        newsRssNewsElement.prepend(link);
                        newsList.append(newsRssNewsElement);

                    });
                 }
             });
             $("#newsFeedArea").empty().prepend(newsList);
            function feedTickerNews()   {
                $.ajax({
                    type: "GET",
                    url: testVarTwo+"&use_info_button_urls=yes&page_no=" + pagePlace,
                    dataType: "xml",
                    success: function(xml) {
                        if (newsBlock == "undefined" || newsBlock == null) {
                            newsBlock = "testBlock1";
                        }
                        $(xml).find('event').each(function(addtoNews){
                            var link =                  $("<a class='recentProduct' />");
                            var newsRssNewsTitle2 =      $(this).find('event_desc').text();
                            var newsRssNewsText2 =       $(this).find('event_info').text();
                            //var newsRssNewsLink2 =     $(this).find('buy_button_url').text();             // THIS LINKS AS A BUY BUTTON
                            var newsRssNewsLink2 =       $(this).find('event_info_button_url').text();      // THIS LINKS TO THE EVENT INFORMATION PAGE
                            var newsRssNewsElement2 =    $("<li class='rightColumnListItem' />").hover(function() {$(this).css({"background-position":"2px 1px"})},function() {$(this).css({"background-position":"2px -73px"})});
                            var separator2 =             $("<div class='rightColumnSeparator'><img src='/shared/images/spacer.gif' width='159' height='1' alt='' /></div>");
                            link.attr("href",newsRssNewsLink2);
                            link.text(newsRssNewsTitle2);
                            newsRssNewsElement2.prepend(link);
                            newsList.prepend(newsRssNewsElement2);
                        });

                    }
                });
                $('ul#feedNews li:last').hide().remove();
                if (pagePlace<25) {
                    pagePlace++;
                } else {
                    pagePlace=1;
                }
                $('.newFeedItem').removeClass("newFeedItem")

            }

        interval = setInterval(feedTickerNews, pause);





    $(".column").sortable({
        handle: 'h2',
        placeholder: 'placeholder',
        forcePlaceholderSize: true,
        opacity: 0.4,
        connectWith : '.column',
        update  : function(event, ui){
            var cookieString = '';
            $(".column").each(function(i){
                cookieString += (i===0) ? '' : '|';
                $('.dragbox',this).each(function(i){
                    cookieString += (i===0) ? '' : ';';
                    cookieString += $(this).attr('id') + ',';
                });
            });
            $.cookie('sortable-positions',cookieString,{
                expires: 30
            });
        }

    });

    if (!$.cookie('sortable-positions')) return;
    var cookiePositions = $.cookie('sortable-positions');
    if (cookiePositions.length > 0)
    {

     $('.column').each(function(i){
            var thisColumn = $(this),
                widgetData = cookiePositions.split('|')[i].split(';');

            $(widgetData).each(function(){
                if(!this.length) {return;}
                var thisWidgetData = this.split(','),
                    clonedWidget = $('#' + thisWidgetData[0]);

                if(thisWidgetData[1]==='collapsed') {
                    $(clonedWidget).find('.portlet-content').css('display','none');
                }

                $('#' + thisWidgetData[0]).remove();
                $(thisColumn).append(clonedWidget);
            });
        });
    }




});
$(document).ready(function() {
     var recentPanel = $.cookie('recents');
	 var catPanel = $.cookie('cats');
     var emailPanel = $.cookie('newsletter');
	
//	if (recentPanel == 'hide') {$("#item-1").hide();}
//	if (recentPanel == 'show'){$("#item-1").show();}
	
//	if (catPanel == 'hide'){$("#item-4").hide();}
//	if (catPanel == 'show'){$("#item-4").show();}
	
//	if (emailPanel == 'hide'){$("#item-5").hide();}
//	if (emailPanel == 'show'){$("#item-5").show();}
//	if (emailPanel == 'done'){$("#item-5").remove();}
	
	
	if (!$.cookie('recents')) {$("#item-1").hide();}
	if (recentPanel == 'hide') {$("#item-1").hide();}
	if (recentPanel == 'show') {$("#item-1").show();}
//	emailPanel = if (!emailPanel == 'done')
//	{emailPanel = 'hide'}

    $(".closePanelCategories").click(function() {
        $("#item-4").fadeOut("slow");
        $.cookie('cats','hide');
        if (emailPanel == 'hide' || emailPanel == null) {
            $("#item-5").css({"display":"block"});
            $.cookie('newsletter', 'show');
        }
        $("#showOriginal").css({"display":"block"})
     });

    $(".closePanelRecentlyViewed").click(function() {
        $("#item-1").fadeOut("slow");
        $.cookie('recents', 'hide');
        if (emailPanel == 'hide' || emailPanel == null || emailPanel !='done') {
            $("#item-5").css({"display":"block"});
            $.cookie('newsletter', 'show');
        }
        $("#showOriginal").css({"display":"block"})
     });

    $(".closePanelnewsLetter").click(function() {
        $("#item-5").fadeOut("slow");
        $.cookie('newsletter', 'hide');
    });

    $("#showOriginal").click(function() {
        $("#item-4").show();
        $.cookie('cats',null);
        recentPanel = 'hide';
        if (emailPanel != 'done') {
		emailPanel = null;
		}
        $("#item-5").css({"display":"none"});
        $("#showOriginal").css({"display":"none"})
    });

	
    if (catPanel == 'hide') {$("#item-4").hide();}
    
	if (catPanel == 'hide' || recentPanel == 'hide') {$("#showOriginal").css({"display":"block"})}

    $(".RSSfeeds li").hover(function() {$(this).css({"background-position":"2px 5px"})},function() {$(this).css({"background-position":"2px -69px"})    });
    $("#history li").hover(function() {$(this).css({"background-position":"2px 1px"})},function() {$(this).css({"background-position":"2px -73px"})});
    $("#showOriginal").hover(function() {$(this).css({"color":"#1768BF"})},function() {$(this).css({"color":"#3788df"})});


// SEARCH FORM PARAMETERS
	hasClassList = 0;
	hasCountryList = 0;
	$(".classSelect").focus(function() {
		if (hasClassList == 0) {
			$.ajax({
				type: "GET",
				url: '/tickets/xml_feed.buy/'+userID+'?class_list=yes',
				dataType: "xml",
				success: function(xml) {
					$(xml).find('class').each(function() {
						mainClassDesc = $(this).find('description:first').text();
						mainClassCode = $(this).find('code:first').text();
						classOption = $("<option class='classChoice' />");
						classOption.append(mainClassDesc);
						classOption.attr('value',mainClassCode);
						$(".classSelect").append(classOption);
					});
				}
			});
		hasClassList=1;
		}
	});
	$(".classSelect").change(function() {
		$(".subClassChoice").remove();
		if (!$('.classSelect').val()=="") {
			chosenClass = $('.classSelect').val();
			$.ajax({
				type: "GET",
				url: "/tickets/xml_feed.buy/"+userID+"?class_list=yes",
				dataType: "xml",
				success: function(xml) {
					$('.subClassSelect').removeAttr('disabled')
					$(xml).find('class').each(function() {
						
						if ($(this).find('code:first').text() == chosenClass) {
							$(this).find('subclass').each(function() {					
								subClassDesc = $(this).find('description').text();
								subClassCode = $(this).find('code').text();
								subClassOption = $("<option class='subClassChoice' />")
								subClassOption.append(subClassDesc);
								subClassOption.attr('value',chosenClass+'/'+subClassCode);
								$('.subClassSelect').append(subClassOption);
						   });
						}
					});
				}
		    });
		} else {
			$('.subClassSelect').attr('disabled','disabled')
		}
	});
	
	// DATE OPTIONS
	hasStartDays=0;hasStartMonth=0;hasStartYear=0;hasEndDays=0;hasEndMonth=0;hasEndYear=0;
	function buildDate() {
		dateSelect = $("<option class='"+dateName+"Option' value='"+dateNumber+"'  />");
		if (dateNumber <= totalDate) {
			if (dateNumber < 10) {
				dateSelect.append("0"+dateNumber)
			} else {
				dateSelect.append(dateNumber)
			}
			buildDateHere.append(dateSelect)
			dateNumber++;
			buildDate();
		}
	}
	
	function fEndDay() {if (hasEndDays==0) {buildDateHere= $("#selectDayEnd");dateNumber =1;totalDate=31;	hasEndDays=1;dateName="day";buildDate();};};
	function fEndMonth() {if (hasEndMonth==0) {buildDateHere= $("#selectMonthEnd");dateNumber =1;	totalDate=12;hasEndMonth=1;dateName="month";buildDate();};};
	function fEndYear() {if (hasEndYear==0) {buildDateHere= $("#selectYearEnd");dateNumber =thisYear;totalDate=thisYear+2;hasEndYear=1;dateName="year";	buildDate();};};
	function fStartDay() {if (hasStartDays==0) {buildDateHere= $("#selectDay");dateNumber =1;totalDate=31;hasStartDays=1;dateName="day";	buildDate();};};
	function fStartMonth() {if (hasStartMonth==0) {	buildDateHere= $("#selectMonth");dateNumber =1;totalDate=12;hasStartMonth=1;dateName="month";buildDate();};};
	function fStartYear() {if (hasStartYear==0) {buildDateHere= $("#selectYear");dateNumber =thisYear;	totalDate=thisYear+2;hasStartYear=1;dateName="year";buildDate();};};
	
	$("#selectDayEnd").focus(function() {fEndDay();});
	$("#selectMonthEnd").focus(function() {fEndMonth();});
	$("#selectYearEnd").focus(function() {fEndYear();});
	$("#selectDay").focus(function() {fStartDay();});
	$("#selectMonth").focus(function() {fStartMonth();});
	$("#selectYear").focus(function() {fStartYear();});
	
	$("#start-date").find('.datepick-trigger').click(function() {fStartDay();fStartMonth();fStartYear();});
	$("#end-date").find('.datepick-trigger').click(function() {fEndDay();fEndMonth();fEndYear();});

	
	$(".countrySelect").focus(function() {
		if (hasCountryList == 0) {
			$.ajax({
				type: "GET",
				url: '/tickets/xml_feed.buy/'+userID+'?country_list=yes',
				dataType: "xml",
				success: function(xml) {
					$(xml).find('country').each(function(){
						countryName = $(this).find('country_desc').text();
						countryCode = $(this).find('country_code').text();
						countryOption = $("<option class='countryChoice' />")
						countryOption.append(countryName);
						countryOption.attr('value',countryCode);
						$('.countrySelect').append(countryOption);
					});
				}
			});
			hasCountryList=1;
		}
	});
	$(".countrySelect").change(function() {
		$(".cityChoice").remove();
		if (!$('.countryChoice').val()=='') {
			currentCountry = $('.countrySelect').val();
			$.ajax({
				type: "GET",
				url: '/tickets/xml_feed.buy/'+userID+'?&city_list=yes',
				dataType: "xml",
				success: function(xml) {
					$(xml).find('city').each(function(){
						cityCountry = $(this).find('country_code').text();	
						cityName = $(this).find('city_desc').text();
						cityCode = $(this).find('city_code').text();
						cityLong = $(this).find('longitude').text();
						cityLat = $(this).find('latitude').text();
						cityRadius = $(this).find('radius_km').text();
						hasProduct = $(this).find('has_product').text();
	
						if (currentCountry == cityCountry && hasProduct == 'yes') {
							
							cityOption = $("<option class='cityChoice "+hasProduct+"' />")
							cityOption.append(cityName);
							cityOption.attr('value','s_geo='+cityLat+':'+cityLong+':'+cityRadius+'&cpy.city_name='+cityName);
							$('.citySelect').append(cityOption)
						}
					});
				}
			});								
		}
	});
	$(".classSelect").change(function() {
		$('.classSelect').attr('name','s_class');
		$('.subClassSelect').attr('name','degraded')
    });
	$('.subClassSelect').change(function() {
		if (!$(this).val()=="") {
			$('.classSelect').attr('name','degraded')
			$('.subClassSelect').attr('name','s_class')
		}
	});
	willSubmit = 0;
	function searchName () {
		willSubmit = 1;
		if (!searchValue.length==0) {
			if (searchValue.length<3) {
				if (confirm("Your search for '"+searchValue+"' likely to return a huge number of results. \n\n  Would you like to continue? \n")) {
					$.post(setCoreCookie+searchTerms, function() { $(".gtSearch").submit();});
				} else {
					return false;
				}
			} else {
				$.post(setCoreCookie+searchTerms, function() { $(".gtSearch").submit();});
			}
		} else {
			if (confirm("You have not entered a search term. If you continue your results will contain every event currently on sale.  This may take some time. \n\n  Would you like to continue? \n")) {
				$.post(setCoreCookie+searchTerms, function() { $(".gtSearch").submit();});
			} else {
				return false;
			}
		}
	}
	$("#searchSubmit").click(function() {
	   if (willSubmit == 0) {
			searchValue = $(".searchField").val();
			searchTerms = "name=search_term&value="+searchValue;
			searchName();
			return false;
		}
	});

				



// SEARCH FILTERS ***BETA***				
	$(".refineButton").click(function() {
		refineTo = $('input.refineByWordText').val();
		if (refineTo.length > 3) {
			$(".eventLink").hide();
			$(".searchResultEventName a:contains("+refineTo+")").each(function() {
					$(this).parent().parent().parent().parent().show();												   
		   });
		} else {
			alert("Please be more specific")
			$('input.refineByWordText').val('');
			$(".eventLink").show();
		}
		
	  });
			


// NEWSLETTER

    $("#newsLetterName").focus(function() {
        if ($(this).val().length<=2) {
            $(this).removeClass("right");
            $(this).removeClass("yellowClass");
            $(this).addClass("wrong");
        } else {
            $(this).removeClass("wrong");
            $(this).removeClass("yellowClass");
            $(this).addClass("right");
        }
            if ($(this).val()=="") {
        $(this).addClass("yellowClass");
        }
    });
    $("#newsLetterName").blur(function() {
        if ($(this).val()=="") {
            $(this).removeClass("yellowClass");
            $(this).removeClass("wrong");
            $(this).removeClass("right");
          return;
      }
        if ($(this).val().length<=2) {
            $(this).removeClass("yellowClass");
            $(this).addClass("wrong");
        } else {
            $(this).removeClass("wrong");
            $(this).removeClass("yellowClass");
            $(this).addClass("right");
        }
        if ($(".newsLetterBody .right").length==2) {
            $("#submitNewsLetter").css({"background-position":"top","cursor":"pointer"})
            $("#submitNewsLetter").attr('onclick','')
        } else {
            $("#submitNewsLetter").css({"background-position":"bottom","cursor":"auto"})
            $("#submitNewsLetter").attr('onclick','return false')
        }

   });
    function isValidEmailAddress(emailAddress) {
        pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        return pattern.test(emailAddress);
    }

    $("#newsLetterEmail").focus(function() {
        if ($(this).val()=="") {
            $(this).addClass("yellowClass");
        }
    });

    $("#newsLetterEmail").keyup(function() {
        var email = $("#newsLetterEmail").val();
        if(email != 0) {
            if (isValidEmailAddress(email)) {
                $("#newsLetterEmail").removeClass("yellowClass")
                $("#newsLetterEmail").removeClass("wrong")
                $("#newsLetterEmail").addClass("right")
            } else {
                $("#newsLetterEmail").removeClass("wrong")
                $("#newsLetterEmail").removeClass("right")
                $("#newsLetterEmail").addClass("yellowClass")
            }
            if ($(".newsLetterBody .right").length==2) {
                $("#submitNewsLetter").css({"background-position":"top","cursor":"pointer"})
                $("#submitNewsLetter").attr('onclick','')
            } else {
                $("#submitNewsLetter").css({"background-position":"bottom","cursor":"auto"})
                $("#submitNewsLetter").attr('onclick','return false')
            }
        }
     });
    $("#newsLetterEmail").blur(function() {
        var email = $("#newsLetterEmail").val();
        if(email != 0) {
            if (isValidEmailAddress(email)) {
                $("#newsLetterEmail").removeClass("yellowClass")
                $("#newsLetterEmail").removeClass("wrong")
                $("#newsLetterEmail").addClass("right")
            } else {
                $("#newsLetterEmail").removeClass("yellowClass")
                $("#newsLetterEmail").removeClass("right")
                $("#newsLetterEmail").addClass("wrong")
            }
        }
     });
    $("#newsLetterEmail").blur(function() {
        if ($(this).val()=="") {
            $(this).removeClass("yellowClass");
            $(this).removeClass("wrong");
            $(this).removeClass("right");
        }
    });

        $("#submitNewsLetter").click(function () {
            if ($(".newsLetterBody .right").length==2) {
                $("#submitNewsLetter").attr('onclick','')
                newsletterName =        $("#newsLetterName").val();
                newsletterEmail =       $("#newsLetterEmail").val();
                newsletter_email_addr = $("#newsLettertoField").val();
                newsletterSubject =         $("#newsLetterSubject").val();
                newsletterdataString = 'first_name=' + newsletterName + '&dest_email_addr=' + newsletter_email_addr + '&email_address=' + newsletterEmail + '&subject=' + newsletterSubject ;
                $.ajax({
                    type: "POST",
                    url: feedbackPath+'?crypto_block=' + newsletter_crypt,
                    data: newsletterdataString,
                    success: function() {
                        $('.newsLetterBody').html("<div id='newsLetterSent'><img id='feedbackLoader' src='/shared/images/user_id/globaltickets/xmlLoader.gif' alt='' /></div>");
                        $('#newsLetterSent').append("")
                        .hide()
                        .fadeIn(1500, function() {
                            $('#newsLetterSent').html("<img id='feedbackLoader' src='/shared/images/user_id/globaltickets/feedbackSentThanks.png' />").queue(
                                function() {
                                    $("#item-5").fadeOut(1500);
                                });
                        $.cookie('newsletter','done');
                        });
                    }
                });
            return false;
        } else {
            return false;
        }
    });


    /* CLASS LIST */
    var categoryList = $("<ul id='categoryList' />");
    var subCatList = $("<ul class='subCategoryList' />")

    function categoryFeed () {
        $.ajax({
            type: "GET",
            url: xmlFeed+userID+'?'+genericBlock+'&class_list=yes'+limitCountry,
            dataType: "xml",
            success: function(xml) {
                $(xml).find('class').each(function() {
                    var tierOneCat =    $(this).find('description:first').text();
                    var tierOneCatLink = $(this).find('description:first').text().toLowerCase().replace(/ /g,"-");
                    var tierOneCode =   $(this).find('code:first').text();
                    var catItem     =   $("<li class='categoryListItem' />");
                    var catLink     =   $("<a class='categoryLink' />");
                    var catSpan     =   $("<span class='catSpan' />")
					var tierOneHref = searchPath+'?'+genericBlock+'&s_class='+tierOneCode+'&s_coco='+countryCode;
					expandCats =    $("<span class='showMoreCats'><span class='plusSign'>+</span></span><div class='subList'></div>");
                    catLink.attr('href',tierOneHref);
                    catLink.text(tierOneCat)
                    catSpan.html(catLink)
                    catItem.prepend(catSpan);
                    if ($(this).find('subclass').length>1) {
                        catItem.append(expandCats);
                    }
                    categoryList.append(catItem);
                    $(".showMoreCats").append("<input type='hidden' value='"+tierOneCode+"' class='moreCatsInput' />")

                });
                $(".showMoreCats").click(function() {
					$("a.categoryLink").removeClass("openTierOne");
					$(this).parent('li.categoryListItem').find('a.categoryLink').addClass("openTierOne")		
					$(".subCategoryList").slideUp("fast");
					if ($(this).find(".currentOpenClass").length >=1)	{
						$('.plusSign').html("+").removeClass("currentOpenClass");
						$(".subList").removeClass("showTheseCats");
						$(this).parent('li.categoryListItem').find('a.categoryLink').removeClass("openTierOne")	
						return false
					} else {
						$('.plusSign').html("+").removeClass("currentOpenClass");
						$(this).find('.plusSign').html("<img src='/shared/images/xmlLoader.gif' width='15' height='15' alt='' />").addClass("currentOpenClass");
						$(".subList").removeClass("showTheseCats");
						$(this).next($(".subList")).toggle().addClass("showTheseCats");
						var subCatLists = $(this).find('.moreCatsInput').val();
						$.ajax({
							type: "GET",
							url: xmlFeed+userID+'?'+genericBlock+'&class_list=yes'+limitCountry+"&s_class="+subCatLists,
							dataType: "xml",
							success: function(xml) {
								$(".currentOpenClass").html("<img src='/shared/images/spacer.gif' alt='' width='10' height='10' class='ndash' />");
								$(".subCategoryList").html("");
								$(xml).find('class').each(function() {
									if ($(this).find('code:first').text() == subCatLists) {
										$(this).find('subclass').each(function() {
											var tierTwoCat = $(this).find('description').text();
											var tierTwoLink = $(this).find('code').text();
											var tierTwoItem = $("<li class='subCatItem' />");
											var tierTwoHref = searchPath+'?'+genericBlock+'&s_coco='+countryCode+'&s_class='+subCatLists+'/'+tierTwoLink;
											var catLinkSec     =   $("<a class='categoryLinkSec' />");
											catLinkSec.attr('href',tierTwoHref);
											catLinkSec.text(tierTwoCat)
											tierTwoItem.append(catLinkSec);
											subCatList.append(tierTwoItem);
											$(".showTheseCats").append(subCatList);

										});
									}
								});
								$(".subCategoryList").slideDown("fast");
							}
						});
					}
           		});
            }
        });
    $(".categoriesList .box").empty().prepend(categoryList);
    }
	
    categoryFeed();
    $(".box").append("<div class='clear'></div>")



});



jQuery.createXMLDocument = function( s ) {
    var browserName = navigator.appName;
    var xmlDoc;
    if ( browserName == "Microsoft Internet Explorer" ) {
        xmlDoc = new ActiveXObject( "Microsoft.XMLDOM" );
        xmlDoc.async = "false";
        xmlDoc.loadXML( s );
    } else {
        xmlDoc = ( new DOMParser() ).parseFromString( s, "text/xml" );
    }
    return xmlDoc;
}

	
		
$(document).ready(function() {		
		
	 function isValidEmailAddress(emailAddress) {
        pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        return pattern.test(emailAddress);
    }
	
	$("#sendToFriendEmail").focus(function() {
		$(this).addClass('yellowClass');
	});
	
	$("#sendToFriendEmail").blur(function() {
        var verEmail = $("#sendToFriendEmail").val();
        if(verEmail != 0) {
			if (isValidEmailAddress(verEmail)) {
				$("#sendToFriendEmail").addClass("yellowClass")
			} else {
			$("#sendToFriendEmail").removeClass('yellowClass').addClass("wrong")
			}
		}
	});		
		
	$("#submitSendToFriend").click(function() {
		var errorTable = $("<ul class='errorTable' />");
		recipientEmail = $("#sendToFriendEmail").val();
		senderName =	$("#sendToFriendName").val();
		recipientName = $("#sendToFriendName2").val();
		var emailErrors = 0;
			$.ajax({
					type: "POST",
					data:"",
					url: "/tickets/xml_email_addr_check.exe/globaltickets_aff?dest_email_addr="+recipientEmail,
					success: function(emailData) {
						$(".emailErrors").html("");
						$(emailData).find('error_desc').each(function() {
							errorList = $("<li class='errorClass' />");
							emailIssue = $(this).text();
							errorList.append(emailIssue);
							errorTable.append(errorList);
					  	});
						$(".emailErrors").append(errorTable);
						isValid = $(emailData).find('is_valid').text();
						if (isValid == "yes") {
							$("#sendToFriendEmail").removeClass('yellowClass').removeClass('wrong').addClass("right")	
							correctEmail = true;
							enteringEmail = 0;
						} else {
							$("#sendToFriendEmail").removeClass('yellowClass').removeClass('right').addClass("wrong")	
							correctEmail = false;
						}
						
						if ($("#sendToFriendName").val().length<=2) 
						{
							$("#sendToFriendName").removeClass('yellowClass').addClass('wrong')
							$(".nameOneError").show();
							correctName1 = false;
						} else {
							$("#sendToFriendName").removeClass('yellowClass').addClass('right')
							correctName1 = true;
						}
						if (whoTo == 1) {
							if ($("#sendToFriendName2").val().length<=2) {
								$("#sendToFriendName2").removeClass('yellowClass').addClass('wrong')
								$(".nameTwoError").show();
								correctName2 = false;
							} else {
								$("#sendToFriendName").removeClass('yellowClass').addClass('right')
								correctName2 = true;
							}
							if (correctEmail == true && correctName1 == true && correctName2 == true)
							{
								$(".sendToFriendBox").html("<span style='float:left; margin-left:5px;color:#666;'>Sending Itinerary...</span> <img src='/shared/images/xmlLoader' style='float:right;margin-top:0px;margin-right:5px;' width='15' height='15' alt='' /><div class='clear'></div>");
								sendToFriendString2 = '&sender_name=' +senderName+ '&recipient_name='+recipientName+'&dest_email_addr=' + recipientEmail;
								$.ajax({
									type: "POST",
									url: feedbackPath+'?'+sendToFriend_crypt,
									data: sendToFriendString2,
									success: function() {
										var timeOutMail = setTimeout(function() {
											$(".sendToFriend").slideUp("normal").remove();
										}, 700);
										$(this).data('timeout', timeOutMail);	
										emailSent = 1;
									}
								});
							}
						} else {
							if (correctEmail == true && correctName1 == true) {
								$(".sendToFriendBox").html("<span style='float:left; margin-left:5px;color:#666;'>Sending Itinerary...</span> <img src='/shared/images/xmlLoader' style='float:right;margin-top:0px;margin-right:5px;' width='15' height='15' alt='' /><div class='clear'></div>");
								sendToFriendString = '&sender_name='+senderName+ '&dest_email_addr=' + recipientEmail;
								$.ajax({
									type: "POST",
									url: feedbackPath+'?'+sendToFriend_crypt,
									data: sendToFriendString,
									success: function() {
										var timeOutMail = setTimeout(function() {
											$(".sendToFriend").slideUp("normal").remove();
										}, 700);
										$(this).data('timeout', timeOutMail);	
										emailSent = 1;
									}
								});
							}
						}
					
					}
				});

	})

	offerLoopNo = 5;packageLoopNo =5;
	hotelPointPos= 20;
	timeoutTime = 5000;
	itemNumber = 0;
	hotelIsHovered = 0;
	packageLoopLimit = packageLoopNo-1;
	$(".package a").removeClass('selected')
	$(".item"+itemNumber).find("a").addClass('selected')
	setTimeout ( function() {
		function hotelPos() {
			if (itemNumber >= packageLoopLimit) {
				hotelPointPos= 0;
				itemNumber =0;
				$(".hotelDealsPoint").animate({marginTop: hotelPointPos+"px"}, { duration: 800, easing: 'easeOutBounce'});
				$(".package a").removeClass('selected')
				$(".item"+itemNumber).find("a").addClass('selected')
				setTimeout(function() {
					hotelPointPos= hotelPointPos+20;
					hotelPos();
				},timeoutTime);	
			} else {
				$(".hotelDealsPoint").animate({marginTop: hotelPointPos+"px"}, { duration: 400, easing: 'easeOutBounce'});
				itemNumber++;
				$(".package a").removeClass('selected')
				$(".item"+itemNumber).find("a").addClass('selected')
				setTimeout(function() {
					hotelPointPos= hotelPointPos+20;
					hotelPos();
				},timeoutTime);
			}
		}
		setTimeout( function() {
				hotelPos();
		},timeoutTime);
	},2500);
	$(".item0 a").hover(function() {
		hotelIsHovered = 1;
		hotelPointPos= 0;
		itemNumber = 0;
		$(".hotelDealsPoint").dequeue();
		$(".package a").removeClass('selected')
		$(".item0").find("a").addClass('selected')
		$(".hotelDealsPoint").animate({marginTop: hotelPointPos+"px"}, { duration: 800, easing: 'easeOutBounce'});
	});
	$(".item1 a").hover(function() {
		hotelIsHovered = 1;
		hotelPointPos= 20;
		itemNumber = 1;
		$(".hotelDealsPoint").dequeue();
		$(".package a").removeClass('selected')
		$(".item1").find("a").addClass('selected')
		$(".hotelDealsPoint").animate({marginTop: hotelPointPos+"px"}, { duration: 800, easing: 'easeOutBounce'});
	});
	$(".item2 a").hover(function() {
		hotelIsHovered = 1;
		hotelPointPos= 40;
		itemNumber = 2;
		$(".hotelDealsPoint").dequeue();
		$(".package a").removeClass('selected')
		$(".item2").find("a").addClass('selected')
		$(".hotelDealsPoint").animate({marginTop: hotelPointPos+"px"}, { duration: 800, easing: 'easeOutBounce'});
	});
	$(".item3 a").hover(function() {
		hotelIsHovered = 1;
		hotelPointPos= 60;
		itemNumber = 3;
		$(".hotelDealsPoint").dequeue();
		$(".package a").removeClass('selected')
		$(".item3").find("a").addClass('selected')
		$(".hotelDealsPoint").animate({marginTop: hotelPointPos+"px"}, { duration: 800, easing: 'easeOutBounce'});
	});
	$(".item4 a").hover(function() {
		hotelIsHovered = 1;
		hotelPointPos= 80;
		itemNumber = 4;
		$(".hotelDealsPoint").dequeue();
		$(".package a").removeClass('selected')
		$(".item4").find("a").addClass('selected')
		$(".hotelDealsPoint").animate({marginTop: hotelPointPos+"px"}, { duration: 800, easing: 'easeOutBounce'});
	});
	
	specialPointPos= 20;
	specialNumber = 0;
	specialLoopLimit = offerLoopNo-1;
	$(".special a").removeClass('selected')
	$(".itemS"+specialNumber).find("a").addClass('selected')

	function specialPos() {
		if (specialNumber >= specialLoopLimit) {
			specialPointPos= 0;
			specialNumber =0;
			$(".specialDealsPoint").animate({marginTop: specialPointPos+"px"}, { duration: 800, easing: 'easeOutBounce'});
			$(".special a").removeClass('selected')
			$(".itemS"+specialNumber).find("a").addClass('selected')
			setTimeout(function() {
				specialPointPos= specialPointPos+20;
				specialPos();
			},timeoutTime);	
		} else {
			$(".specialDealsPoint").animate({marginTop: specialPointPos+"px"}, { duration: 400, easing: 'easeOutBounce'});
			specialNumber++;
			$(".special a").removeClass('selected')
			$(".itemS"+specialNumber).find("a").addClass('selected')
			setTimeout(function() {
				specialPointPos= specialPointPos+20;
				specialPos();
			},timeoutTime);
		}
	}
	
	setTimeout( function() {
		specialPos();
	},timeoutTime);
	
	$(".itemS0 a").hover(function() {
		specialPointPos= 0;
		specialNumber = 0;
		$(".specialDealsPoint").dequeue();
		$(".special a").removeClass('selected')
		$(".itemS0").find("a").addClass('selected')
		$(".specialDealsPoint").animate({marginTop: specialPointPos+"px"}, { duration: 800, easing: 'easeOutBounce'});
	});
	$(".itemS1 a").hover(function() {
		specialPointPos= 20;
		specialNumber = 1;
		$(".specialDealsPoint").dequeue();
		$(".special a").removeClass('selected')
		$(".itemS1").find("a").addClass('selected')
		$(".specialDealsPoint").animate({marginTop: specialPointPos+"px"}, { duration: 800, easing: 'easeOutBounce'});
	});
	$(".itemS2 a").hover(function() {
		specialPointPos= 40;
		specialNumber = 2;
		$(".specialDealsPoint").dequeue();
		$(".special a").removeClass('selected')
		$(".itemS2").find("a").addClass('selected')
		$(".specialDealsPoint").animate({marginTop: specialPointPos+"px"}, { duration: 800, easing: 'easeOutBounce'});
	});
	$(".itemS3 a").hover(function() {
		specialPointPos= 60;
		specialNumber = 3;
		$(".specialDealsPoint").dequeue();
		$(".special a").removeClass('selected')
		$(".itemS3").find("a").addClass('selected')
		$(".specialDealsPoint").animate({marginTop: specialPointPos+"px"}, { duration: 800, easing: 'easeOutBounce'});
	});
	$(".itemS4 a").hover(function() {
		specialPointPos= 80;
		specialNumber = 4;
		$(".specialDealsPoint").dequeue();
		$(".special a").removeClass('selected')
		$(".itemS4").find("a").addClass('selected')
		$(".specialDealsPoint").animate({marginTop: specialPointPos+"px"}, { duration: 800, easing: 'easeOutBounce'});
	});
	
		
});



// NEWS AND RSS
 $(document).ready(function() {
	var newsOrRss = 0;
	$(".newsHeader").css({ "color": "#fff", "background":"url(/shared/images/user_id/globaltickets/newsRssLeftActive.png) left top no-repeat", "cursor":"auto"});
	$(".rssHeader").css({"color": "#3788df","background":"url(/shared/images/user_id/globaltickets/newsRssRightDead.png) left top no-repeat", "cursor":"pointer"});
	function loadRss(){
		if(newsOrRss==0){
			$(".newsSection").css({"display": "block"});
			$(".rssSection").css({"display": "none"});
			$(".feedsSection").css({"min-height":"240px","height":"240px"})
			newsOrRss = 1;
		}
	}
	function loadNews(){
		if(newsOrRss==1){
			$(".newsSection").css({"display": "none"});
			$(".rssSection").css({"display": "block"});
			$(".feedsSection").css({"min-height":"120px","height":"120px"})
			newsOrRss = 0;
		}
	}
	$(".newsHeader").click(function(){
		$(".newsHeader").css({"color": "#fff","background":"url(/shared/images/user_id/globaltickets/newsRssLeftActive.png) left top no-repeat", "cursor":"auto"});
		$(".rssHeader").css({"color": "#3788df","background":"url(/shared/images/user_id/globaltickets/newsRssRightDead.png) left top no-repeat", "cursor":"pointer"});

		loadRss();
	});
	$(".rssHeader").click(function(){
		$(".newsHeader").css({"color": "#3788df","background":"url(/shared/images/user_id/globaltickets/newsRssLeftDead.png) left top no-repeat", "cursor":"pointer"});
		$(".rssHeader").css({"color": "#fff", "background":"url(/shared/images/user_id/globaltickets/newsRssRightActive.png) left top no-repeat", "cursor":"auto"});

		loadNews();
	});
	loadRss();
		
		
		
});






			//var newBlockA = $(data).find('performance').text().replace('/</g','&lt;').replace('/>/g','&gt;');
				//	var xmlString = (new XMLSerializer()).serializeToString(data);
					//alert(xmlString);
					