var sortMode = 'Attending';
var currentDetailsElement;
var currentDetailsKey;
var rowHighlightColor = '#D7D7D7';
var rowRolloverColor = '#F1EFA3';
var bestTripElement=null;
var foundBestElement = "false";
var urlLink = 'www.expedia.com';


function listTrips() {
	var table = document.getElementById('resultTable');
	// remove existing rows
	var rows = table.getElementsByTagName('tr');
	for (var i = rows.length-1; i > 0; i--) {
		table.deleteRow(i);
	}

	var caption = document.getElementsByTagName('caption');
	caption[0].innerHTML = 'Sorted <b>by ' +sortMode+'</b>';
	var listRows = 0;
	var firstTripKey = 0;
	var firstTripElement = 0;
	var bestTripKey = 0;
	var reqForm = document.requirementsForm;
	var tbody = table.getElementsByTagName('tbody')[0];
	var currentTripOrder = tripOrder[sortMode];
	for (var i = 0; i < currentTripOrder.length; i++) {
		var skip = false;
		var currentTripKey = currentTripOrder[i];

		var currentTrip = tripData[currentTripKey];

		var tr = document.createElement('tr');
		if (i == 0) {
			firstTripKey = currentTripKey;
			firstTripElement = tr;
		}
		addEventHandlers(tr, currentTripKey);
		if (currentDetailsKey == currentTripKey) {
			tr.style.backgroundColor = rowHighlightColor;
			currentDetailsElement = tr;
		}

		var destinationCell = document.createElement('td');
		destinationCell.innerHTML = currentTrip['destination'];

		var departureCell = document.createElement('td');
		departureCell.innerHTML = currentTrip['departureDate'];

		var returnCell = document.createElement('td');
		returnCell.innerHTML = currentTrip['returnDate'];
		
		highlightBestTripRow(tr, currentTrip['destination'], new Array (currentTrip['departureDate'], currentTrip['returnDate']));
		if (bestTripElement && foundBestElement == "true") {
			bestTripKey = currentTripKey;
			foundBestElement = "false";
		}
		
		var attendingCell = document.createElement('td');
		var userCount = 0;
		for (var userId in currentTrip['tripUser']) {
			// remove trips that don't have the required users
			if (reqForm && reqForm.requiredUser) {
				for (var j = 0; j < reqForm.requiredUser.length; j++) {
					if (reqForm.requiredUser[j].checked && reqForm.requiredUser[j].value == userId && currentTrip['unavailableUsers'][userId]) {
						skip = true;
					}
				}
			}
			if (!currentTrip['unavailableUsers'][userId]) {
				userCount++;
			}
		}
		attendingCell.align = 'middle';
		attendingCell.innerHTML = '' +userCount;

		var avgStarCell = document.createElement('td');
		avgStarCell.innerHTML = showStars(currentTrip['averageStars'], true);

		// remove trips that don't meet the minimum star criteria
		if (reqForm && currentTrip['averageStars'] < getSelectedValue(document.requirementsForm.minimumAverageStars)) {
			skip = true;
		}

		var groupFareCell = document.createElement('td');
		groupFareCell.innerHTML = "$" + currentTrip['groupFare'].toFixed(0);

		var myFareCell = document.createElement('td');
		myFareCell.align = 'middle';
		var fares = currentTrip['myFare'];
		if (!fares) {
			if (userHomeTownId != currentTrip['tripUserDestination']) {
				fares = 'No Airline Fare Found';
			} else {
				fares = 'FREE! You\'re already there';
			}
		}
		if (!isNaN(fares)) {
			fares = "$" + fares.toFixed(0);
		}
		myFareCell.innerHTML = fares;

		// remove trips with maximum individual price
		if (reqForm && document.requirementsForm.highestMaxFare.value && !isNaN(document.requirementsForm.highestMaxFare.value) && currentTrip['maxFare'] > document.requirementsForm.highestMaxFare.value) {
			skip = true;
		}

		// remove trips with average price greater
		if (reqForm && document.requirementsForm.highestAverageFare.value && !isNaN(document.requirementsForm.highestAverageFare.value) && currentTrip['averageFare'] > document.requirementsForm.highestAverageFare.value) {
			skip = true;
		}

		if (!skip) {
			tr.appendChild(destinationCell);
			tr.appendChild(departureCell);
			tr.appendChild(returnCell);
			tr.appendChild(attendingCell);
			tr.appendChild(avgStarCell);
			tr.appendChild(groupFareCell);
			tr.appendChild(myFareCell);
			
			tbody.appendChild(tr);
			listRows++;
		} else {
			if (currentDetailsKey == currentTrip['tripKey']) {
				removeDetails();
			}
		}
	}

	// If there are no rows, add an empty one
	if (listRows == 0) {
		tr = document.createElement('tr');
		td = document.createElement('td');
		td.innerHTML = 'There are no trips that match the criteria.';
		td.colSpan = 8;

		tr.appendChild(td);
		tbody.appendChild(tr);
	} else {
		if(firstTripElement && firstTripKey){
			if(bestTripDestination == '' || bestTripDate[0] == '' || bestTripDate[1] == ''){
				showDetails(firstTripElement,firstTripKey);
			}else if(bestTripElement && bestTripKey!=0 ){
				showDetails(bestTripElement,bestTripKey);
			}
  		}
  	}
  table=null;
  rows=null;
  caption=null;
  listRows=null;
  firstTripKey=null;
  firstTripElement=null;
  bestTripKey=null;
  reqForm=null;
  tbody=null;
  currentTripOrder=null;
}


function removeDetails() {
	currentDetailsElement = null;
	currentDetailsKey = null;
	var table = document.getElementById('tripIdeaDetailsTable');
	var rows = table.rows;
	for (var i = rows.length - 1; i > 0; i--) {
		table.deleteRow(i);
	}
	var tbody = table.getElementsByTagName('tbody')[0];
	var tr = document.createElement('tr');
	var td = document.createElement('td');
	td.innerHTML = 'Click on Any of the Trips Ideas on the above to see Prices and Book your Trip';
	td.colSpan = 6;
	tr.appendChild(td);
	tbody.appendChild(tr);
}

function addEventHandlers(element, key) {
	element.onclick = function () {
		showDetails(element, key);
		return false;
	};
	element.onmouseover = function () {
		element.style.cursor = 'pointer';
		element.style.backgroundColor = rowRolloverColor;
	}
	element.onmouseout = function () {
		if (element == currentDetailsElement) {
			element.style.backgroundColor = rowHighlightColor;
		} else {
			element.style.backgroundColor = '';
		}
	}
}

function showDetails(element, tripKey) {
	//reset existing highlight
	if (currentDetailsElement) {
		currentDetailsElement.style.backgroundColor = '';
	}
	currentDetailsKey = tripKey;
	currentDetailsElement = element;
	// add a new highlight
	element.style.backgroundColor = rowHighlightColor;
	var table = document.getElementById('tripIdeaDetailsTable');
	var tbody = table.getElementsByTagName('tbody')[0];
	var rows = table.rows;
	for (var i = rows.length - 1; i > 0; i--) {
		table.deleteRow(i);
	}
	var currentTrip = tripData[tripKey];
	var counter = 0;
	for (var userId in currentTrip['tripUser']) {
			var tr = document.createElement('tr');
			if (currentTrip['unavailableUsers'][userId]) {
				tr.style.color = '#808080';
			}
			var commentTr = document.createElement('tr');
			commentTr.colSpan = 5;
	
			var _currentTripUserOrigin = currentTrip['tripUserOrigin'][userId];
			var fare = null;
			var airLineLink = null;
			if (_currentTripUserOrigin  && _currentTripUserOrigin != "") {
				fare = currentTrip['javascriptFares'][_currentTripUserOrigin];
				airLineLink = currentTrip['javascriptURL'][_currentTripUserOrigin];
			}
	
			var userOrigin = currentTrip['tripUserOrigin'][userId];
			if (!fare) {
				if (userOrigin != currentTrip['tripUserDestination']) {
					fare = 'No Airline Fare Found';
				} else {
					fare = 'FREE! You\'re already there';
				}
			} else {
			    fare = fare[0].split(";")[0];
			}
			var photoTd = document.createElement('td');
			photoTd.rowSpan = 2;
			if (userId > 0)
				photoTd.innerHTML = '<a href="/user/view/' +userId + '"><img  alt="userImage30" class="userImage30" src="' +tripUserImages[userId] + '"/></a>';
			else
				photoTd.innerHTML = '<img alt="userImage" class="userImage30" src="' +tripUserImages[userId] + '"/>';
			tr.appendChild(photoTd);
			var userTd = document.createElement('td');
			if (userId > 0)
				userTd.innerHTML = '<a href="/user/view/' +userId + '" ' + (currentTrip['unavailableUsers'][userId] ? 'style="color: #808080;"' : '') + ' >' +currentTrip['tripUser'][userId] + '</a>';
			else
				userTd.innerHTML = currentTrip['tripUser'][userId];
			tr.appendChild(userTd);
			var cityTd = document.createElement('td');
			cityTd.appendChild(document.createTextNode(currentTrip['tripUserOriginCity'][userId]));
			tr.appendChild(cityTd);
	
			var destinationPrefTd = document.createElement('td');
			destinationPrefTd.innerHTML = showStars(currentTrip['destinationPreference'][userId], true);
			tr.appendChild(destinationPrefTd);
	
			var datePrefTd = document.createElement('td');
			datePrefTd.innerHTML = showStars(currentTrip['datePreference'][userId], true);
			tr.appendChild(datePrefTd);
	
			var fareTd = document.createElement('td');
			var whichOption = 'exp';
	
			if ((fare != 'No Airline Fare Found') && (fare != 'FREE! You\'re already there')) {
				var cityHR = document.createElement('span');
				cityHR.setAttribute('color', '#FF0000');
				cityHR.setAttribute('font-size', '15px');
				if (airLineLink == 'NA') {
					cityHR.innerHTML = '<span style="color: #FF0000;" font-size:30px; class ="bestHilightLink" >' +fare + ' </span>';
				} else {
					cityHR.innerHTML = '<a href=# onClick=showPopup("' +airLineLink + '"' + ') >' +fare + ' </a>';
				}
			} 
			var depDate = currentTrip['departureDate'];
			var departureDate = new Date(depDate);
	
	    	if (depDate.length != 10) {
		  	  var subSt = depDate.substring(6, 8);
			    var finalDepDate = depDate.substring(0, 6) + 20 + subSt;
			    departureDate = new Date(finalDepDate);
		    }
		    
			var myDate = new Date;
		    if (cityHR)
				fareTd.appendChild(cityHR);
			if (departureDate >= myDate) {
				var newform = document.createElement('form');
				var newselect = document.createElement('select');
				newselect.id = ('selectProvider' +userId).replace('-', '_');
				var newopt = document.createElement('option');
				newopt.value = 'exp';
				newopt.appendChild(document.createTextNode('Expedia'));
				newselect.appendChild(newopt);
				var newopt1 = document.createElement('option');
				newopt1.value = 'hot';
				newopt1.appendChild(document.createTextNode('HotWire'));
				newselect.appendChild(newopt1);
				var kay = document.createElement('option');
				kay.value = 'kayak';
				kay.appendChild(document.createTextNode('Kayak'));
				newselect.appendChild(kay);
				var orb = document.createElement('option');
				orb.value = 'orb';
				orb.appendChild(document.createTextNode('Orbitz'));
				newselect.appendChild(orb);
				var newopt2 = document.createElement('option');
				newopt2.value = 'trav';
				newopt2.appendChild(document.createTextNode('Travelocity'));
				newselect.appendChild(newopt2);
				var priceLine = document.createElement('option');
				priceLine.value = 'pline';
				priceLine.appendChild(document.createTextNode('PriceLine'));
				newselect.appendChild(priceLine);
				newform.appendChild(newselect);
				var srcButton = document.createElement('span');
				srcButton.innerHTML = '<input  type="image" name="book" src="/i/btn_go.gif"  onClick="return openBookingPage(' +userId + ');" class ="mouseOver" />';
				newform.appendChild(srcButton);
				fareTd.appendChild(newform);
				
				srcButton=null;
				newform=null;
				newselect=null;
				newopt=null;
				newopt1=null;
				kay=null;
				orb=null;
				newopt2=null;
				priceLine=null;
			}
			
			if ((fare == 'No Airline Fare Found') || (fare == 'FREE! You\'re already there')) {
				fareTd.appendChild(document.createTextNode(fare));
			}
			tr.appendChild(fareTd);
	
			var commentTd = document.createElement('td');
			commentTd.colSpan = 5;
			 if (tripUserComments[userId]){
				 commentTd.innerHTML = '<span style="font-size: 80%; color: #666;">' +tripUserComments[userId] + '</span>';
			}
			 commentTr.appendChild(commentTd);
	
			 tbody.appendChild(tr);
			 tbody.appendChild(commentTr);
	
			 counter++;
			 tr=null;
			 commentTr=null;
			 _currentTripUserOrigin=null;
			 commentTd=null;
			 fareTd=null;
			 datePrefTd=null;
			 fare=null;
			 airLineLink=null;
			 userOrigin=null;
			 photoTd=null;
			 userTd=null;
			 userTd=null;
			 cityTd=null;
			 datePrefTd=null;
			 destinationPrefTd=null;
			 myDate=null;
	}
	table=null;
	rows=null;
	currentTrip=null;
}

function showStars(selected, avgMode) {
	var quarterStar = 0;
	var halfStar = 0;
	var threeQuarterStar = 0;

	var output = '';
	var prefix = '';

	if (avgMode) {
		if (selected == 'R') {
			return '<img alt="reject" width="13" height="13" src="/i/reject-on.gif"/>';
		}

		prefix = 'static_';
		if (Math.floor(selected) != selected) {
			var remainder = selected - Math.floor(selected);
			if (remainder < .25) {
				selected = Math.floor(selected);
			} else if (remainder >= .25 && remainder < .50) {
				quarterStar = Math.ceil(selected);
				selected = Math.floor(selected);
			} else if (remainder >= .50 && remainder < .75) {
				halfStar = Math.ceil(selected);
				selected = Math.floor(selected);
			} else if (remainder >= .75) {
				threeQuarterStar = Math.ceil(selected);
				selected = Math.floor(selected);
			}
		}
	} else {
		output = '<img alt="reject" width="13" height="13" src="/i/reject.gif"/>';
		if (selected == 'R') {
			selected = 0;
			output = '<img alt="reject" width="13" height="13" src="/i/reject-on.gif"/>';
		}
	}

	for (var i = 1; i <= 5; i++) {
		var src = prefix + 'star_empty.gif';
		if (i <= selected) {
			src = prefix + 'star_full.gif';
		} else if (i == quarterStar) {
			src = prefix + 'star_one_quarter.gif';
		} else if (i == halfStar) {
			src = prefix + 'star_half.gif';
		} else if (i == threeQuarterStar) {
			src = prefix + 'star_three_quarter.gif';
		}
		output += '<img  alt="star" width="13" height="13" src="/i/' +src + '"/>';
	}
	return output;
}

function highlightBestTripRow(element, destination, dates) {
	if (bestTripDestination == '' || bestTripDate[0] == '' || bestTripDate[1] == '') {
		return;
	} else {
		if (destination == bestTripDestination && bestTripDate[0] == dates[0] && bestTripDate[1] == dates[1]) {
			element.bgColor = '#A1DAA7';
			bestTripElement = element;
			foundBestElement = "true";
		}
	}
}

var MAX_STARS = 5;
function highlightToStar(element, mode) {
	var type = element.id.substring(0, element.id.indexOf('_'));
	var id = element.id.substring(element.id.indexOf('_') + 1, element.id.lastIndexOf('_'));
	var currentValue = document.getElementById(type + 'Preference[' +id + ']').value;

	var hoverValue = 0;
	if (mode == 'on') {
		hoverValue = element.id.substring(element.id.lastIndexOf('_') + 1);
	}

	if (hoverValue == 'R' || hoverValue == '0') {
		var reject = document.getElementById(type + '_' +id + '_R');

		var highlightAppend = '';
		if (hoverValue == 'R') {
			highlightAppend = '-highlight';
		}

		var valueAppend = '';
		if (currentValue == 'R') {
			valueAppend = '-on';
		}
		reject.src = '/i/reject' +valueAppend + highlightAppend + '.gif';
	}

	for (var i = 1; i <= MAX_STARS; i++) {
		var star = document.getElementById(type + '_' +id + '_' +i);

		var highlightAppend = '';
		if (i <= hoverValue) {
			highlightAppend = '-highlight';
		}

		var valueAppend = '';
		if (i <= currentValue) {
			valueAppend = '-on';
		}
		star.src = '/i/star' +valueAppend + highlightAppend + '.gif';
	}

}

function clickStar(element) {
	var type = element.id.substring(0, element.id.indexOf('_'));
	var id = element.id.substring(element.id.indexOf('_') + 1, element.id.lastIndexOf('_'));
	var hoverValue = element.id.substring(element.id.lastIndexOf('_') + 1);
	document.getElementById(type + 'Preference[' +id + ']').value = hoverValue;
	highlightToStar(element, 'on');
	updateVote(type, id, hoverValue);
}

function updateAveragePrice(frm) {
	var key = frm.bestTripOptions.options[frm.bestTripOptions.selectedIndex].value;
	frm.price.value = tripData[key]['averageFare'];
}
