dojo.require("dojo.widget.*");
dojo.require("dojo.widget.SlideShow");
dojo.require("dojo.widget.ContentPane");
dojo.require("dojo.widget.LayoutContainer");
dojo.require("dojo.io.*");
dojo.hostenv.writeIncludes();

dojo.addOnLoad(init);

var pdata = new Object();
var markers = new Array;
var activeListItem = null;
var map = null;
var pictureIndex = 0;

// from http://groups.google.com/group/Google-Maps-API/browse_thread/thread/60707f79305efc96/
GMap2.prototype.centerAndZoomOnBounds = function(bounds) {
   var center_lat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2.0;
   var center_lng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2.0;
   var center = new GLatLng(center_lat,center_lng)
   map.setCenter(center, map.getBoundsZoomLevel(bounds));

}

function init() {
	map = new GMap2(document.getElementById("MapPane"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(41, -96), 4);

	var publisher_id = "pub-0675193288092248";
	var bottomLeft = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(10,10));

	var adsManagerOptions = {
		maxAdsOnMap: 1,
		style: 'adunit',
		channel: '0065134861',
		position: bottomLeft 
	};
	
	adsManager = new GAdsManager(map, publisher_id, adsManagerOptions);
	adsManager.enable();

	if (typeof(input) == 'object') {
		search(input);
	}
}

function loading() {
	var results = document.getElementById("ResultsPane");
	results.innerHTML = '<p>&nbsp;</p><p align="center"><img src="/img/loading_animation.gif"></p>';
}

function unloading() {
	var results = document.getElementById("ResultsPane");
	results.innerHTML = '';
}


function search(input) {
	// clear any potential error highlighting
	document.getElementById('make').className = 'header';
	document.getElementById('model').className = 'header';
	document.getElementById('zipcode').className = 'header';

	// throw up animated loading gif
	loading();

	var args = {
         url: "/server.html",
	     mimetype: "text/javascript",
         load: function(type, evaldObj) {
				   pdata.search = evaldObj;
				   // assume we return error code on error
				   // or an array otherwise
				   // i don't think this could be called a best practice
				   // should probably change HTTP response code
				   if (typeof(pdata.search) == 'number') {
					   // error handling
					   displayError(pdata.search);
				   } else {
					   displayItems(pdata.search);
				   }
				} 

    };

	if (input instanceof HTMLFormElement) {
         args['formNode'] = input;
	} else {
         args['content'] = input;
         args['content']['action'] = 'search';
	}

    dojo.io.bind(args);
}

function displayError(code) {
	// kill loading image
	unloading();

	// these are the eBay API error codes
	// except for 0, which I made up
	switch(code) {
	case 0:
	  // no results
	  document.getElementById('ResultsPane').innerHTML = 'Sorry, that car is not for sale within that area. Try widening your search by increasing the number of miles you\'re looking within.';
	  break;
	case 447:
	  // picked a make, but no model in category with available models
	  document.getElementById('model').className += ' error';
	  break;
	case 17415:
	  // bad zip code
	  document.getElementById('zipcode').className += ' error';
	  break;
	default:
	  document.getElementById('ResultsPane').innerHTML = 'Something bad happened on my side, but I\'m not sure exactly what. Sorry.';
	  break;
	  // everything else for now
	}
}

function createMarker(point, i) {
	var marker = new GMarker(point); 
	GEvent.addListener(marker, "click", function() { 
		var infoTabs = [];
		var description = '';
		var url = 'http://rover.ebay.com/rover/1/711-53200-19255-0/1?type=4&campid=5336037842&toolid=10001&customid=2&mpre=' + escape(i[12]);

		description += '<div id="dialog"><div class="dialogdropshadow"><div class="dialogcontent"><span class="itemtitle">' + i[3] + '<\/span><br />';
		description += '<span class="itemcost">$' + i[9] + '</span> <span class="itemtime">Time Left: <strong>' + i[10] + '</strong></span><br />';
		description += '<div class="itemdescription"><img src="/img/icon_newwindow.gif" width="11" height="10" alt="" />&nbsp;<a href="' + url + '" target="_blank">View Description</a></div></div></div>';
  		infoTabs.push(new GInfoWindowTab("Description", description));

		dojo.io.bind({
			url: "/server.html",
			content: {action: 'GetReviews', ItemID: i[0]},
			mimetype: "text/javascript",
			load: function(type, evaldObj) {
			  var data = evaldObj;
			  var reviews = '<div id="dialog"><div class="dialogdropshadow"><div class="dialogcontent"><span class="itemtitle">Reviews</span><br />';
			  if (data.length) {
				  for (var j = 0; j < data.length; j++) {
					var url = 'http://rover.ebay.com/rover/1/711-53200-19255-0/1?type=4&campid=5336037842&toolid=10001&customid=2&mpre=' + escape(data[j]['URL']);
					reviews += '<div class="itemdescription">' + data[j]['Title'] + ' (' + data[j]['Rating'] + ' Stars) ';
					reviews += '<img src="/img/icon_newwindow.gif" width="11" height="10" alt="" />&nbsp;<a href="' + url + '" target="_blank">View Review</a></div>';
				  }
			  } else {
			  	reviews += '<p>No reviews available for this car.</p>';
			  }
			  reviews += '</div></div></div>';
			  infoTabs.push(new GInfoWindowTab("Reviews", reviews));
			  marker.openInfoWindowTabsHtml(infoTabs); 
			}
		});

/*
		infoTabs.push(new GInfoWindowTab("Reviews", ""));
		marker.openInfoWindowTabsHtml(infoTabs); 
		setTimeout(function() {
			nodes = map.getInfoWindow().getContentContainers();
			dojo.io.bind({
				url: "server.html",
				content: {action: 'GetReviews', ItemID: i[0]},
				mimetype: "text/javascript",
				load: function(type, evaldObj) {
				  var data = evaldObj;
				  var reviews = '<div id="dialog"><div class="dialogdropshadow"><div class="dialogcontent"><span class="itemtitle">Reviews</span><br />';
				  for (var j = 0; j < data.length; j++) {
					reviews += '<p>' + data[j]['Title'] + ' (' + data[j]['Rating'] + ' Stars)</p>';
				  }
				  reviews += '</div></div></div>';
				  nodes[1].innerHTML = reviews;
				}
		 	});
			}, 1
		); 
*/
		if (activeListItem) { 
			activeListItem.parentNode.className = '';
			hidePictures();
			pictureIndex = 0;
		}

		activeListItem = document.getElementById("list" + i[0]);
		// need to pop up to parent, since we're tabling tds instead of trs to work around Safari bug
		// see http://bugzilla.opendarwin.org/show_bug.cgi?id=4944
		activeListItem.parentNode.className = 'listactive';
		var	listresults = dojo.widget.byId('listresults').domNode; 
		if (activeListItem.offsetTop < listresults.scrollTop || activeListItem.offsetTop > listresults.scrollTop + listresults.clientHeight) {
			listresults.scrollTop = activeListItem.offsetTop;
		}

	    dojo.io.bind({
			url: "/server.html",
			content: {action: 'GetImageURLs', ItemID: i[0] },
			mimetype: "text/javascript",
			load: function(type, evaldObj) {
					  pdata.getitem = evaldObj;
		  
					  // assume we return error code on error
					  // or an array otherwise
					  // i don't think this could be called a best practice
					  // should probably change HTTP response code
					  if (typeof(pdata.search) == 'number') {
						  // error handling
//							displayError(pdata.getitem);
					  } else {
						  displayPictures(pdata.getitem);
					  }
				   }
   
		 });
	}); 

	return marker; 

} 

function swapPicture(shift) {
	pictureIndex += shift;

	if (pictureIndex < 0 || pictureIndex > pdata.getitem.length - 1) { return true; }

	if (pictureIndex == 0) { document.getElementById('leftarrow').style.visibility = 'hidden'; }
	else if (pictureIndex == 1) { document.getElementById('leftarrow').style.visibility = 'visible'; }
	else if (pictureIndex == pdata.getitem.length - 2) { document.getElementById('rightarrow').style.visibility = 'visible'; }
	else if (pictureIndex == pdata.getitem.length - 1) { document.getElementById('rightarrow').style.visibility = 'hidden'; }

	document.getElementById('itemphoto').src = pdata.getitem[pictureIndex];
}

function displayPictures(pictures) {
	var tr = document.createElement("TR");
	var td = document.createElement("TD");

	if (pictures.length > 1) { 
		td.innerHTML = '<img src="/img/icon_arrowleft.gif" width="7" height="12" class="listgalleryarrow" style="visibility:hidden" id="leftarrow" onClick="swapPicture(-1);">';
	} else {
		td.innerHTML = '&nbsp;';
	}
	td.className = 'listgallery';
	tr.appendChild(td);

	td = document.createElement("TD");
	colspan = document.createAttribute('colspan');
	colspan.value = 2;
	td.setAttributeNode(colspan);
	td.setAttribute('colspan', 2);

	td.innerHTML = '<img src="' + pictures[0] + '" width="150" height="112" align="left" class="itemphoto" id="itemphoto">';
	if (pictures.length > 1) { 
		td.innerHTML += '<img src="/img/icon_arrowright.gif" width="7" height="12" class="listgalleryarrow" id="rightarrow" border="0" onClick="swapPicture(1);">';
	}
	td.className = 'listgallery';
	tr.appendChild(td);

	// go up (to tr) and over (because we insertBefore)
	var index = activeListItem.parentNode.nextSibling;
	if (index) {
		index.parentNode.insertBefore(tr, index);
	} else {
		activeListItem.parentNode.parentNode.appendChild(tr);
	}
}

function hidePictures() {
	// go up (to tr) and over (because we insertedBefore the nextSibling)
	var index = activeListItem.parentNode.nextSibling;
	index.parentNode.removeChild(index);
}

// need to calculate zoom level
function mapItems(data) {
	var bounds = new GLatLngBounds();

	// clean up previous search (if any)
	map.clearOverlays();

	for (var i = 0; i < data.length; i++) {
	  var point = new GLatLng(data[i][2], data[i][1]);
	  var marker = createMarker(point, data[i]);

	  markers[data[i][0]] = marker;
	  map.addOverlay(marker);

	  bounds.extend(point);
	}
	
	// center and zoom on middle point of all markers
	map.centerAndZoomOnBounds(bounds);
}

function makeResultsRow(i) {
	var row  = '';
	/* <tr><th>Make - Model</th><th>Year</th> */
	/* <th>Mileage</th><th>Price</th><th>Bids</th><th>Distance</th></tr> */

	/* putting id on td to work around Safari bug */
	row += '<tr>';
	row += '<td id="list' + i[0] + '"><input type="checkbox" style="visibility:hidden" name="vehicles" value="' + i[0] + '"></td>';
	row += '<td><a href="javascript:void(0)" onClick="showWindow(' + i[0] + ');"><img src="' + i[11] + '" width="80" height="60" class="itemphoto"></a></td>';
	row += '<td><span class="itemtitle"><a href="javascript:void(0)" onClick="showWindow(' + i[0] + ');">' + i[3] + '</a></span><br />';
	row += '<span class="itemcost">$' + i[9] + '</span> <span class="itemtime">Time Left: <strong>' + i[10] + '</strong></span> <br />';
	row += 'Year: <strong>' + i[7] + '</strong> Mileage: <strong>' + i[6] + '</strong> <br />';
	row += 'Distance: <strong>' + i[5] + ' miles</strong></td></tr>';
	
	return row;
}

function showWindow(id) {
	GEvent.trigger(markers[id], "click");
}

function setCssText(node, cssText){
	// make opera sing
	if(dojo.lang.isUndefined(node.style.cssText)){
		node.setAttribute("style", cssText);
	}else{
		node.style.cssText= cssText;
	}
}

function showResults(data) {

	var html = '';
	var layout = dojo.widget.createWidget("LayoutContainer");
	var results = document.getElementById("ResultsPane");

	results.innerHTML = '';
	results.appendChild(layout.domNode);
	setCssText(layout.domNode, "width: 100%; height: 100%;");

	var content = dojo.widget.byId('listfilter');
	if (! content) {
		content = dojo.widget.createWidget("ContentPane", {layoutAlign: 'top', id: 'listfilter'});
		setCssText(content.domNode, "background-color: #b9cee2; border: solid 1px #7591ad; padding: 2px 5px 2px 5px; height: 20px;");
	
		html = '<form>Sort by: ';
		html += '<select onChange="return sortResults(this.options[this.selectedIndex].value);" name="select4">';
		html += '<option value="Distance">Distance</option>';
		html += '<option value="Mileage">Mileage</option>';
		html += '<option value="Price">Price</option>';
		html += '<option value="TimeRemaining">Time Remaining</option>';
		html += '<option value="Year">Year</option>';
		html += '</select></form>';
	
		content.setContent(html);
	}

	layout.addChild(content);

/*
	content = dojo.widget.byId('listactions');
	if (! content) {
		content = dojo.widget.createWidget("ContentPane", {layoutAlign: 'bottom', id: 'listactions'});
		setCssText(content.domNode, "background-color: #e0e8f0; border-top: solid 1px #7591ad; padding: 5px; height: 20px;");
	
		html = '<img src="img/icon_selectarrow.gif"> <span id="watchText"><a href="javascript:void(0);" onClick="watchList();">Add Selected to Watch List</a></span>';
		content.setContent(html);
	}
	layout.addChild(content);
*/

	content = dojo.widget.byId('listresults');
	if (! content) {
		content = dojo.widget.createWidget("ContentPane", {layoutAlign: 'client', id: 'listresults'});
	}

	html  = makeResultsTable(data);

	content.setContent(html);
	layout.addChild(content);

	layout.onResized();
}

function makeResultsTable(data) {
	var html = '<form id="results"><table border="0" cellspacing="0" cellpadding="0"><tbody>';
	for (var i = 0; i < data.length; i++) {
		html += makeResultsRow(data[i]);
	}
	html += '</tbody></table></form>';

	return html;
}

function displayItems(data) {
	mapItems(data);
	showResults(data);
}

function cmp(a, b) {
	if (a > b) return  1;
	if (a < b) return -1;
			   return  0;
}

function sortResults(order) {
	switch(order) {
	case 'Distance':
		pdata.search.sort(function (a,b) { return a[5].toString().replace(/[^0-9]/g,'') - b[5].toString().replace(/[^0-9]/g,''); });
		break;
	case 'Mileage':
		pdata.search.sort(function (a,b) { return a[6].toString().replace(/[^0-9]/g,'') - b[6].toString().replace(/[^0-9]/g,''); });
		break;
	case 'Price':
		pdata.search.sort(function (a,b) { return a[9].toString().replace(/[^0-9]/g,'') - b[9].toString().replace(/[^0-9]/g,''); });
		break;
	case 'TimeRemaining':
		pdata.search.sort(function (a,b) { 
			// break "1d 2h 3m" apart
			var a_parts = a[10].split(" ");
			var b_parts = b[10].split(" ");
		
			// if you have more parts, then you are bigger
			var parts = cmp(a_parts.length, b_parts.length);
			if (parts) return parts;
			
			// loop through each part and compare
			// parseInt removes the trailing "d, h, m" bits
			for (var i = 0; i < a_parts.length; i++) {
				var result = cmp(parseInt(a_parts[i]), parseInt(b_parts[i]));
				if (result) return result;
			}
		
			return 0;
		});
		break;
	case 'Year':
		// sorted desc
		pdata.search.sort(function (a,b) { return b[7].toString().replace(/[^0-9]/g,'') - a[7].toString().replace(/[^0-9]/g,''); });
		break;
	default:
		pdata.search.sort();
	}

	var html = makeResultsTable(pdata.search);
	var	listresults = dojo.widget.byId('listresults'); 
	listresults.setContent(html);
}
