
function Burriteria( id, latlng, name, address, city, state, directory ) {
	this.id = id;
	this.latlng = latlng;
	this.name = name;
	this.address = address;
	this.city = city;
	this.state = state;
	this.directory = directory;

	this.div = null;
	this.marker = null;

	this.comments = new BurriteriaComments(this);
	this.images = new BurriteriaImages(this);
	this.menu = new BurriteriaMenu(this);	

	Burriteria.prototype.getInfoWindow = function() {
		var div = DOMElement('div','burriteriainfowindow');
		
		div.appendChild(this.getTitleDiv());
		div.appendChild(this.getRatingsDiv());
		//div.appendChild(this.getDirectionsDiv());
		div.appendChild(this.getTabs());

		return div;
	};

	Burriteria.prototype.getTitleDiv = function() {
		var div = DOMElement('div','burriteriatitlediv');
		div.style.paddingBottom = '10px';
		div.style.paddingRight = '15px';
		var span = DOMElement('span');

		span.style.fontWeight = 'bold';
		span.appendChild(document.createTextNode(this.name));
		div.appendChild(span);
		div.appendChild(DOMElement('br'));
		div.appendChild(document.createTextNode(this.address));
		div.appendChild(DOMElement('br'));
		div.appendChild(document.createTextNode(this.city+', '+this.state));

		div.appendChild(this.getDirectionsDiv());
		
		return div;
	};

	Burriteria.prototype.getRatingsDiv = function() {
		var div = DOMElement('div');
		div.style.float = 'right';
		div.style.paddingBottom = '10px';

		for ( var i = 0; i < this.rating_elements.length; ++i ) {
			div.appendChild(this.rating_elements[i].getDiv());
			/*div.appendChild(document.createTextNode('Average Rating: '));
			var avg = this.avgRatings[i];
			if (avg < 0)
				div.appendChild(document.createTextNode('N/A'));
			else
				div.appendChild(document.createTextNode(this.avgRatings[i]));*/
		}

		//
		// Add the legend
		//
		var legend = document.createElement('div');
		var imgs = [{o:32,k:'me'},{o:16,k:'all'},{o:0,k:'both'}];
		for ( var i = 0; i < imgs.length; ++i )
		{
			var image = document.createElement('div');
			image.style.backgroundImage = 'url(/media/_.final.png)';
			image.style.backgroundPosition = '-' + imgs[i].o + 'px 0px';
			image.style.backgroundRepeat = 'no-repeat';
			image.style.height = '16px';
			image.style.width = '16px';
			if ( !document.all )
				image.style.display = 'table-cell';
			else
				image.style.display = 'inline';

			legend.appendChild(image);

			var span = document.createElement('span');
			span.style.paddingLeft = '0.5em';
			span.style.paddingRight = '1em';
			span.appendChild(document.createTextNode(imgs[i].k));
			if ( !document.all )
				span.style.display = 'table-cell';
			else
				span.style.display = 'inline';

			legend.appendChild(span);
		}
		legend.style.marginTop = '5px';
		div.appendChild(legend);

		return div;
	};
	
	Burriteria.prototype.getDirectionsDiv = function()
	{
		var div = DOMElement('div');
		var link = document.createElement('a');
		link.setAttribute('href','#');
		link.onclick = function( evt )
		{
			getDirections(this.id,this.address,this.city,this.state);
		};
		link.appendChild(document.createTextNode('get directions'));
		div.appendChild(link);
		return div;
	};

	Burriteria.prototype.getMarker = function() {
		var f_this = this;
		this.marker = new GMarker(this.latlng);
		GEvent.addListener(this.marker,'click',function() {
			f_this.marker.openInfoWindow(f_this.getInfoWindow());
		});

		return this.marker;
	};

	Burriteria.prototype.setRatingFn = function( r_ ) {
		var this_ = this;
		return function( r ) {
			var r_e = this_.rating_elements[r_];
			r_e.setRating(r);
			setRating(this_,r_e.default_rating,r_);
		};
	};

	Burriteria.prototype.getWordImageArray = function( s, r, sf ) {
		var wia = new Array();
		for ( var i = 0; i < s.length; ++i ) {
			wia.push(r+s.charAt(i)+sf);
		}
		return wia;
	};

	Burriteria.prototype.getTabs = function() {
		var div = DOMElement('div');
		var div_ = DOMElement('div','tabbar');
		var content = DOMElement('div','burriteriainfowindowcontent');

		var at = new Array('comments','images','menu');
		var aa = new Array(this.comments,this.images,this.menu);
		for ( var i = 0; i < at.length; ++i ) {
			var a = DOMElement('a');
			a.setAttribute('href','javascript:;');
			a.appendChild(document.createTextNode(at[i]));
			a.onclick = aa[i].makeDisplayFn(content);
			div_.appendChild(a);
		}
		
		div.style.clear = 'both';
		div.appendChild(div_);
		div.appendChild(content);
		
		this.comments.setInDiv(content);

		return div;
	};

	Burriteria.prototype.setAvgRatings = function(avgRating, ratingType) {
		this.avgRatings[ratingType-1] = avgRating;
	};
	
	Burriteria.prototype.setAverageRating = function(ratingType, avg) {
		this.rating_elements[ratingType-1].setAverageRating(avg);
	};
	
	// this defines the parameters for the RatingElement... 5 stars max, default 0, etc.
	this.rating_elements = new Array(new RatingElement(5,0,this.getWordImageArray('DOSMANOS','/media/','.final.png'),48,32,16,64,0,80,this.setRatingFn(0),16,16,0),
																		new RatingElement(5,0,this.getWordImageArray('CALIENTE','/media/','.final.png'),48,32,16,64,0,80,this.setRatingFn(1),16,16,0),
																		/*new RatingElement(5,0,this.getWordImageArray('REGALADO','/media/rate.','.2.png'),16,0,this.setRatingFn(2),16,16,0),*/
																		new RatingElement(5,0,this.getWordImageArray('CUALIDAD','/media/','.final.png'),48,32,16,64,0,80,this.setRatingFn(2),16,16,0));
																		
	this.avgRatings = new Array();
	for (var i = 0; i < this.rating_elements.length; i++) {
		this.avgRatings[i] = -1;
	}																	
}

function BurriteriaComments( burriteria ) {
	this.burriteria = burriteria;
	this.last_update = null;
	this.comments = null;

	BurriteriaComments.prototype.makeDisplayFn = function( d ) {
		var this_ = this;
		return function() {
			this_.setInDiv(d);
		};
	};

	BurriteriaComments.prototype.setInDiv = function( d ) {
		while ( d.firstChild )
			d.removeChild(d.firstChild);

		if ( !this.last_update || !this.comments )
			this.updateCommentsAndContainer(d);
		else
			d.appendChild(this.getDiv(d));
	};

	BurriteriaComments.prototype.getDiv = function( d ) {
		var div = DOMElement('div');

		if ( this.comments.length < 1 ) {
			div.appendChild(document.createTextNode('no comments posted'));
		} else {
			for ( var i in this.comments )
				div.appendChild(this.comments[i].getDiv());
		}

		div.appendChild(this.getAddCommentDiv(d));
		
		return div;
	};

	BurriteriaComments.prototype.updateCommentsAndContainer = function( d ) {
		d.appendChild(document.createTextNode('loading comments...'));
		GDownloadUrl('workhorse.php?action=getcomments&burriteriaid='+this.burriteria.id,this.makeSuccessFn(d));
	};

	BurriteriaComments.prototype.makeSuccessFn = function( d ) {
		var this_ = this;
		return function( rd, rc ) {
			this_.successFn(rd,rc,d);
		};
	};

	BurriteriaComments.prototype.successFn = function( response_data, response_code, div ) {
		var xml = GXml.parse(response_data);
		this.comments = new Array();

		var x_comments = xml.getElementsByTagName('comment');
		for ( var i = 0; i < x_comments.length; ++i ) {
			var comment = new BurriteriaComment(x_comments[i].getAttribute('username'),x_comments[i].getAttribute('timestamp'),x_comments[i].firstChild.data);
			this.comments.push(comment);
		}
		
		this.last_update = new Date().getTime();
		this.setInDiv(div);
	};

	BurriteriaComments.prototype.getAddCommentDiv = function( d ) {
		var div = DOMElement('div','burriteriacommentadd');
		div.appendChild(document.createTextNode('add a comment'));
		div.appendChild(DOMElement('br'));

		var ta = DOMElement('textarea');
		div.appendChild(ta);
		div.appendChild(DOMElement('br'));

		var submit = DOMElement('input');
		submit.setAttribute('type','button');
		submit.setAttribute('value','post');
		div.appendChild(submit);

		var this_ = this;
		submit.onclick = function() {
			this_.submitComment(ta,d);
		};

		return div;
	};

	BurriteriaComments.prototype.submitComment = function( ta, d ) {
		var c = ta.value;
		var this_ = this;
		showAlert('Submitting comment. Please wait.');

		var ajax = GXmlHttp.create();
		ajax.open('POST','workhorse.php?action=addcomments',true);
		ajax.onreadystatechange = function() {
			if ( ajax.readyState != 4 )
				return;

			closeAlert();
			var stati = ajax.responseXML.documentElement.getElementsByTagName('status');
			if ( stati[0].getAttribute('status') == 'true' ) {
				this_.last_update = null;
				this_.setInDiv(d);
			} else {
				var error = stati[0].getAttribute('errormessage');
				if ( error == 'login' )
					requireLogin(function(){this_.submitComment(ta,d);});
				else
					showAlert('Unexpected error: "'+error+'".','mulligan!',closeAlert);
			}
		};
		ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		ajax.send('burriteriaid='+this.burriteria.id+'&comments='+escape(c));
		ajax.send(null);
	};
}

function BurriteriaComment( u, t, c ) {
	this.user = u;
	this.timestamp = t;
	this.comment = c.replace(/^\s+|\s+$/,'');

	BurriteriaComment.prototype.getDiv = function() {
		var div = DOMElement('div');
		div.appendChild(document.createTextNode(this.user+' says... '+this.comment));
		return div;
	};
}

function BurriteriaImages( burriteria ) {
	this.burriteria = burriteria;
	this.last_update = null;
	this.images = null;

	BurriteriaImages.prototype.makeDisplayFn = function( d ) {
		var this_ = this;
		return function() {
			this_.setInDiv(d);
		};
	};

	BurriteriaImages.prototype.setInDiv = function( d ) {
		while ( d.firstChild )
			d.removeChild(d.firstChild);

		if ( !this.last_update || !this.images )
			this.updateImagesAndContainer(d);
		else
			d.appendChild(this.getDiv(d));
	};

	BurriteriaImages.prototype.getDiv = function( d ) {
		var div = DOMElement('div');

		if ( this.images.length < 1 ) {
			div.appendChild(document.createTextNode('no images posted'));
		} else {
			for ( var i = 0; i < this.images.length; ++i ) {
				var img = DOMElement('img');
				//img.setAttribute('src','/media/userimages/'+this.images[i]+'.thumb.jpg');
				img.setAttribute('src',this.images[i]);
				div.appendChild(img);
				div.appendChild(DOMElement('br'));
			}
		}
		
		div.appendChild(this.getAddImageDiv(d));
		
		return div;
	};

	BurriteriaImages.prototype.updateImagesAndContainer = function( d ) {
		d.appendChild(document.createTextNode('loading images...'));
		GDownloadUrl('workhorse.php?action=getimages&burriteriaid='+this.burriteria.id,this.makeSuccessFn(d));
	};

	BurriteriaImages.prototype.makeSuccessFn = function( d ) {
		var this_ = this;
		return function( rd, rc ) {
			this_.successFn(rd,rc,d);
		};
	};

	BurriteriaImages.prototype.successFn = function( response_data, response_code, div ) {
		this.images = new Array();
		var xml = GXml.parse(response_data);

		var x_images = xml.getElementsByTagName('image');
		for ( var i = 0; i < x_images.length; ++i ) {
			this.images.push(x_images[i].getAttribute('filename'));
		}

		this.last_update = new Date().getTime();
		this.setInDiv(div);
	};

	BurriteriaImages.prototype.getAddImageDiv = function( d ) {
		var div = DOMElement('div');
		var form = DOMElement('form');
		form.setAttribute('method','post');
		form.setAttribute('action','workhorse.php?action=addimages&burriteriaid='+this.burriteria.id+'&'+Math.random());
// perform login validation pre-upload to save bandwidth, at some point
//		form.onsubmit = function() {
//			return true;
//		};
		form.setAttribute('enctype','multipart/form-data');
		// daahhhhhh ie...
		form.encoding = 'multipart/form-data';
		var this_ = this;
		form.onsubmit = function() {
			return new AjaxFormUploader(this).submit(function(){
				this_.forceRefresh(d);
			});
		};
		
		// doesn\'t really do much, but it\'ll keep non-malicious users from bugging out.
		//
		// ... n/m php lies!
		var mfs = DOMElement('input');
		mfs.setAttribute('type','hidden');
		mfs.setAttribute('name','MAX_FILE_SIZE');
		mfs.setAttribute('value',Math.pow(2,20));
		form.appendChild(mfs);
		
		var file = DOMElement('input');
		file.setAttribute('type','file');
		file.setAttribute('name','file');
		file.setAttribute('maxlength',Math.pow(2,20));
		form.appendChild(file);
		
		var add = DOMElement('input');
		add.setAttribute('type','submit');
		add.setAttribute('value','upload');
		form.appendChild(add);

		div.appendChild(form);
		div.style.paddingTop = '10px';
		return div;
	};

	BurriteriaImages.prototype.forceRefresh = function( d ) {
		this.last_update = null;
		this.setInDiv(d);
	};
}

function AjaxFormUploader( form ) {
	this.form = form;

	// for reference, a good chunk of this was ganked from
	// http://www.webtoolkit.info/ajax-file-upload.html
	// but then, a lot of it wasn\'t. all the crappy x_body stuff is all burratr.
	AjaxFormUploader.prototype.submit = function( fn ) {
		var div = DOMElement('div');
		var iframe_name = Math.random()+'';
		iframe_name = iframe_name.replace(/[^\d]/,'');

		// yeah. right.
		//
		// ie bugs the fuck out when you place an iframe in the DOM as a target; but
		// it\'s (apostrophe escape for vi syntax highlighting...) perfectly fine
		// if you just insert as straight html. hm.

		div.innerHTML = '<iframe style="display:none;" src="about:blank" id="'+iframe_name+'" name="'+iframe_name+'" onload="if(this.oncomplete){this.oncomplete();}"></iframe>';

		// and then burratr bugs out if you don\'t hide the div altogether.
		div.style.display = 'none';
		
		this.form.appendChild(div);
		this.form.setAttribute('target',iframe_name);
		//this.form.setAttribute('target','new');

		var iframe = document.getElementById(iframe_name);
		iframe.oncomplete = function() {
			var doc = this.contentDocument;
			if ( !doc ) doc = this.contentWindow.document;
			if ( !doc ) doc = window.frames[iframe.getAttribute('id')].document;

			// looks like ff recognizes Content-type and sets the js objects accordingly; ie, on the other hand,
			// just treats it as a regular html page. thus the use of GXml.parse, after properly formatting the input.
			if ( doc.body ) {
				var x_body = doc.body.innerHTML.replace(/\<.*?\>/g,'');
				x_body = x_body.replace(/\&lt\;/g,'<');
				x_body = x_body.replace(/\&gt\;/g,'>');
				//alert(x_body);
				x_body = x_body.replace(/[^>]+</g,'<');
				x_body = x_body.replace(/>[^<]+/g,'>');

				doc = GXml.parse(x_body);
			}

			if ( fn )
				fn();

			var errors = doc.getElementsByTagName('error');
			if ( errors.length > 0 ) {
				showAlert(errors[0].getAttribute('code'),' OK ',closeAlert);
				return;
			}
		};

		return true;
	};
}

function BurriteriaMenu( burriteria ) {
	this.burriteria = burriteria;
	this.last_update = null;
	this.menu = null;

	BurriteriaMenu.prototype.makeDisplayFn = function( d ) {
		var this_ = this;
		return function() {
			this_.setInDiv(d);
		};
	};

	BurriteriaMenu.prototype.setInDiv = function( d ) {
		while ( d.firstChild )
			d.removeChild(d.firstChild);

		d.appendChild(this.getDiv());
	};

	BurriteriaMenu.prototype.getDiv = function() {
		var div = DOMElement('div');
		div.appendChild(document.createTextNode('this feature is not yet enabled.'));
		return div;
	};
}

