window.addEvent('domready', function() {
	// General settings, especially for displaying and uploading photos
	Clientcide.setAssetLocation(base + 'files/clientcide');
	new Lightbox({
		relString: 'bradebox',
		onHide: function() {
			$$('select').fade('show');
		}
	});
	// Status messages at top of website
	$$('.message').each(function(msg) {
		if (typeof(clearmsg) != 'undefined') {
			msg.slide('hide');
		} else {
			msg.highlight('#ff0');
		}
		var closebtn = new Element('span');
		closebtn.set('text', 'Hide Message').inject(msg, 'top').addEvent('click', function() {
			msg.slide('out');
		});
	});
	// External links
	$$('a.external').each(function(elink) {
		elink.addEvent('click', function() {
			window.open(this.href);
			return false;
		});
	});
	// Star for required fields
	$$('.content-column div.required label').each(function(lel) {
		lel.set('html', '<span style="color:#f90">*</span> ' + lel.get('html'));
	});
	// Accordion for FAQ
	var myAccordion = new Fx.Accordion($$('#freqs h4'), $$('#freqs p'), {
		alwaysHide: true,
		display: -1
	});
	// Tool tips for user contact info
	var usertips = new Tips('.userinfo', {
		className: 'tipcontainer',
		text: function(tip) {
			return tip.getNext('.tipdata').get('html');
		}
	});
	// Report form slider
	$$('#AuctionReportForm').slide('hide');
	$$('#viewreportform').addEvent('click', function() {
		$$('#AuctionReportForm').removeClass('setoffhide').slide('toggle');
	});
	// Invoices box slider
	$$('.setoffhide').slide('hide');
	$$('#viewinvoices').addEvent('click', function() {
		$$('.setoff').removeClass('setoffhide').slide('toggle');
	});
	// User view slider
	$$('.setoffhide').slide('hide');
	$$('#viewinfo').addEvent('click', function() {
		$$('.setoffnorm').removeClass('setoffhide').slide('toggle');
	});
	// Login form popup
	$$('#popuplogin').fade('hide');
	$$('.login-btn').addEvent('click', function() {
		$('popuplogin').fade('toggle');
		$('UserUsername').fade('show').focus();
		return false;
	});
	// Lame workaround for CakePHP paginator to preserve query string
	$$('.sorters a').each(function(slink) {
		slink.setProperty('href', slink.getProperty('href') + qstr);
	});
	// "Print Salvage" button
	$$('a.printing').addEvent('click', function() {
		window.print();
		return false;
	});
	// Code highlighting when creating or editing standard pages
	$$('#PageContent').each(function() {
		editAreaLoader.init({
			id: 'PageContent',
			syntax: 'html',
			start_highlight: true,
			allow_toggle: false,
			font_family: 'monaco,monospace',
			word_wrap: true
		});
	});
	// Verbage for address field when registering
	$$('#UserRegisterForm #UserGroupId').each(function(el) {
		if (el.get('value') != '2') {
			$$('#alertz, .addfac').slide('hide');
		}
	});
	$$('#UserRegisterForm #UserGroupId').addEvent('change', function() {
		var addrtext = '<span style="color: rgb(255, 153, 0);">*</span> Address';
		if (this.get('value') == '2' || this.get('value') == '4') {
			addrtext = '<span style="color: rgb(255, 153, 0);">*</span> Billing Address';
		} else if (this.get('value') == '3') {
			addrtext = '<span style="color: rgb(255, 153, 0);">*</span> Mailing Address';
		}
		$$('#UserRegisterForm #UserAddress').getPrevious('label').set('html', addrtext);
		var emailtext = '<span style="color: rgb(255, 153, 0);">*</span> Billing Email';
		if (this.get('value') == '2' || this.get('value') == '4') {
			emailtext = '<span style="color: rgb(255, 153, 0);">*</span> Billing Email';
		} else if (this.get('value') == '3') {
			emailtext = '<span style="color: rgb(255, 153, 0);">*</span> Email';
		}
		$$('#UserRegisterForm #UserEmail').getPrevious('label').set('html', emailtext);
		if (this.get('value') == '2') {
			$$('#alertz, .addfac').slide('in');
		} else {
			$$('#alertz, .addfac').slide('out');
		}
	});
	// Choose existing category on resource add and edit form
	$$('#rcats li').addEvent('click', function() {
		$('ResourceCategory').set('value', this.get('text'));
	});
	// Patience on admin color key filter links
	$$('.colorkey a').addEvent('click', function() {
		scroll(0,0);
		$(document.body).setStyle('overflow', 'hidden');
		$$('html').setStyle('overflow', 'hidden');
		new Element('iframe', {
			id: 'surrounderie6',
			styles: {'opacity': .1}
		}).inject(
		new Element('iframe', {
			id: 'surroundie6'
		}).inject(
		new Element('div', {
			id: 'surroundmsg',
			html: '<h3>Filtering Salvage...</h3><p>Please wait while the list updates...</p>'
		}).inject(
		new Element('div', {
			id: 'surrounder',
			styles: {'opacity': .5}
		}).inject($(document.body), 'top'), 'after'), 'after'), 'after');
		location.hash = 'a';
		location.hash = 'b';
		location.hash = 'c';
		location.hash = 'd';
	});
	// Disable submit button on salvage add and edit forms
	$$('form.careful').addEvent('submit', function() {
		scroll(0,0);
		$(document.body).setStyle('overflow', 'hidden');
		$$('html').setStyle('overflow', 'hidden');
		$$('form.careful input[type=submit]').set('disabled', 'disabled');
		new Element('iframe', {
			id: 'surrounderie6',
			styles: {'opacity': .1}
		}).inject(
		new Element('iframe', {
			id: 'surroundie6'
		}).inject(
		new Element('div', {
			id: 'surroundmsg',
			html: '<h3>Saving your information...</h3><p>Please wait while this process completes.</p>'
		}).inject(
		new Element('div', {
			id: 'surrounder',
			styles: {'opacity': .5}
		}).inject($(document.body), 'top'), 'after'), 'after'), 'after');
		location.hash = 'a';
		location.hash = 'b';
		location.hash = 'c';
		location.hash = 'd';
	});
	// More subtly disable submit on bid and email forms to prevent double click
	$$('form.popform').addEvent('submit', function() {
		$$('form.popform input[type=submit]').set('disabled', 'disabled');
	});
	// Warn users to save before leaving salvage edit form
	if ($('AuctionEditForm')) {
		var alreadychanged = false;
		$$('#AuctionEditForm input, #AuctionEditForm select, #AuctionEditForm textarea').addEvent('change', function() {
			if (!alreadychanged) {
				window.onbeforeunload = function() {
					return "Changes to this salvage have not been saved.";
				}
			}
			alreadychanged = true;
		});
		$('AuctionEditForm').addEvent('submit', function() {
			window.onbeforeunload = function() {
				// allow form to submit
			}
		});
	// Show and hide fields based on category when editing salvage
		switchFields();
		$('AuctionCategoryId').addEvent('change', switchFields);
	}
	function switchFields() {
		switch ($('AuctionCategoryId').getElement('option:selected').get('text')) {
			case '--Select--':
			case 'Trucks':
				$$('.only_trailers').addClass('hide');
				$$('.only_other').addClass('hide');
				$$('.only_trucks').removeClass('hide');
				break;
			case 'Trailers':
				$$('.only_trucks').addClass('hide');
				$$('.only_other').addClass('hide');
				$$('.only_trailers').removeClass('hide');
				break;
			default:
				$$('.only_trucks').addClass('hide');
				$$('.only_trailers').addClass('hide');
				$$('.only_other').removeClass('hide');
		}
	}
	// Tire diagrams
	$$('.diabox').addEvent('click', function() {
		if ($(this).get('checked')) {
			$$('.diagramz .' + $(this).get('name').replace('_damaged]', '').replace('data[Auction][', '')).addClass('damaged');
		} else {
			$$('.diagramz .' + $(this).get('name').replace('_damaged]', '').replace('data[Auction][', '')).removeClass('damaged');
		}
	});
	// Multi-photo uploader when editing salvage - uses FancyUpload
	if ($('AuctionUploadForm')) {
		var up = new FancyUpload2($('asset-status'), $('asset-list'), {
			url: $('AuctionUploadForm').action,
			path: base + 'js/fancyupload/Swiff.Uploader.swf',
			typeFilter: {
				'Allowed Files (*.jpg, *.jpeg, *.gif, *.png, *.doc, *.xls, *.pdf)': '*.jpg; *.jpeg; *.gif; *.png; *.doc; *.xls; *.pdf'
			},
			target: 'asset-browse',
			appendCookieData: true,
			instantStart: true,
			onLoad: function(){
				this.target.addEvents({
					click: function(){
						return false;
					},
					mouseenter: function(){
						this.addClass('hover');
					},
					mouseleave: function(){
						this.removeClass('hover');
						this.blur();
					},
					mousedown: function(){
						this.focus();
					}
				});
			},
			onSelectFail: function(files){
				files.each(function(file){
					new Element('li', {
						'class': 'validation-error',
						html: file.validationErrorMessage || file.validationError,
						title: MooTools.lang.get('FancyUpload', 'removeTitle'),
						events: {
							click: function(){
								this.destroy();
							}
						}
					}).inject(this.list, 'top');
				}, this);
			},
			onFileSuccess: function(file, response){
				if (response.contains('"ui-success"')) {
					file.element.addClass('file-success');
					file.element.set('html', response);
				} else {
					file.element.addClass('file-failed');
					file.info.set('html', '<strong>Error:</strong> ' + response);
				}
			},
			onComplete: function() {
				new Lightbox({relString: 'bradebox'});
				$$('.ui-success .file-size a').addEvent('click', function(e) {
					mainPhoto(e, this);
				});
				$$('.ui-success a.file-remove').addEvent('click', function(e) {
					deletePhoto(e, this);
				});
				$$('.current-text').set('html', '<strong>All Uploads Complete</strong>');
			},
			onFail: function(error){
				switch (error) {
					case 'hidden':
						alert('To enable the embedded uploader, unblock it in your browser and refresh (see Adblock).');
						break;
					case 'blocked':
						alert('To enable the embedded uploader, enable the blocked Flash movie (see Flashblock).');
						break;
					case 'empty':
						//alert('A required file was not found. Please contact us if the error persists.');
						break;
					case 'flash':
						alert('To enable the embedded uploader, install the latest Adobe Flash plugin.')
				}
			}
		});
	}
	// Deleting photos from a salvage
	$$('li.prev-photo a.file-remove').addEvent('click', function(e) {
		deletePhoto(e, this);
	});
	function deletePhoto(event, link) {
		event.stop();
		var dlink = link;
		dlink.getNext('span.file-info').addClass('mini-alert').set('text', 'Deleting photo...');
		var htmlreq = new Request.HTML({
			onSuccess: function(rtree, relems, rhtml, rjs) {
				if (rhtml == 'yes') {
					dlink.getParent('li.file').setStyle('margin', 0).slide('out');
				} else {
					dlink.getNext('span.file-info').set('text', ' ').removeClass('mini-alert');
					alert('The photo could not be deleted.')
				}
			}
		}).get(link.href);
		return false;
	}
	// Set the main photo for a salvage
	$$('li.prev-photo span.file-size a').addEvent('click', function(e) {
		mainPhoto(e, this);
	});
	function mainPhoto(event, link) {
		event.stop();
		var mlink = link.getParent('span');
		mlink.getNext('span.file-info').addClass('mini-update').set('text', 'Setting main photo...');
		var htmlreq = new Request.HTML({
			onSuccess: function(rtree, relems, rhtml, rjs) {
				if (rhtml == 'yes') {
					$$('li.prev-photo, .ui-success').each(function(item) {
						item.getElement('span.file-info').set('text', ' ').removeClass('mini-update');
					});
					mlink.getNext('span.file-info').addClass('mini-update').set('text', 'Main Photo');
				} else {
					mlink.getNext('span.file-info').set('text', ' ').removeClass('mini-update');
					alert('The main photo could not be set.')
				}
			}
		}).get(link.href);
		return false;
	}
	// Save an ACV value on reports page
	var acvchanged = false;
	$$('form.acvformy input').addEvent('change', function(e) {
		if (!acvchanged) {
			window.onbeforeunload = function() {
				return "Not all ACV values have been saved.";
			}
		}
		acvchanged = true;
		$(this).setStyle('background', '#ff0');
	});
	$$('form.acvformy a').addEvent('click', function(e) {
		window.onbeforeunload = function() {
			// allow form to submit
		}
		acvchanged = false;
		saveacv(e, this);
	});
	var updated = false;
	function saveacv(event, link) {
		event.stop();
		var htmlreq = new Request.HTML({
			url: link.getParent('form').get('action'),
			onSuccess: function(rtree, relems, rhtml, rjs) {
				if (rhtml != 'Error') {
					if (!updated) {
						$$('.primarycol .hide').removeClass('hide').fade('in');
					}
					updated = true;
					link.getParent('td').getElement('input.minitdbox').setStyle('background', '#fff').highlight('#0f0');
					var vals = rhtml.split(';');
					link.getParent('td').getNext('td').set('text', vals[0]);
					//link.getParent('td').getNext('td').getNext('td').set('text', vals[1]);
				} else {
					link.getParent('td').getElement('input.minitdbox').set('value', '');
					alert('Error: Could not save ACV');
				}
			}
		}).post($(link.getParent('form').get('id')));
	}
	// Warn if not ACV form data not saved
	if ($('AuctionEditForm')) {
		var alreadychanged = false;
		$$('#AuctionEditForm input, #AuctionEditForm select, #AuctionEditForm textarea').addEvent('change', function() {
			if (!alreadychanged) {
				window.onbeforeunload = function() {
					return "Changes to this salvage have not been saved.";
				}
			}
			alreadychanged = true;
		});
		$('AuctionEditForm').addEvent('submit', function() {
			window.onbeforeunload = function() {
				// allow form to submit
			}
		});
	}
	// Sortable ACV table
	new HtmlTable($('acvtable'), {sortable: true});
	// Smooth tabs on salvage view and edit pages
	heavyTabs = new TabSwapper({
		tabs: $$('ul.tabz li'),
		clickers: $$('ul.tabz li a'),
		sections: $$('div.tabzpanel'),
		smooth: true
	});
	$$('.mainimg img').addEvent('click', function() {
		heavyTabs.show($$('div.tabzpanel').length - 1);
	});
	$$('p.nextpage').each(function(elem, i) {
		elem.addEvent('click', function() {
			heavyTabs.show(i + 1);
			window.scrollTo(0,0);
		});
	});
	$$('p.nextpage, ul.tabz li a').addEvent('click', function() {
		if (this.hasClass('showphotoz')) {
			$$('.extrabox').removeClass('hide').fade('in');
		} else {
			$$('.extrabox').addClass('hide').fade('hide');
		}
		$$('select').fade('show');
	});
	// Home page tabs
	var homepanels = $$('#hometabs div');
	$$('ul#link-wrapper li a').each(function(elem, i) {
		elem.addEvent('mouseenter', function() {
			for (var x = 0; x < homepanels.length; x++) {
				(x == i + 1) ? $('hometabs').addClass('img' + x) : $('hometabs').removeClass('img' + x);
			}
		});
	});
	$$('ul#link-wrapper').addEvent('mouseleave', function() {
		for (var x = 0; x < homepanels.length; x++) {
			(x == 0) ? $('hometabs').addClass('img' + x) : $('hometabs').removeClass('img' + x);
		}
	});
	// Facilities map
	if (typeof(show_facilities_map) != 'undefined') {
		var latlng = new google.maps.LatLng(36.0770048, -87.3877899);
		var myOptions = {
			zoom: 8,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		var geocoder = new google.maps.Geocoder();
		var infowin = new google.maps.InfoWindow();
		$('mapfind').addEvent('click', function() {
			findlocations();
		});
		$('mapzip').addEvent('keypress', function(e) {
			if (e.key == 'enter') {
				findlocations();
			}
		});
	}
	function findlocations() {
		var address = document.getElementById("mapzip").value;
		if (geocoder) {
			geocoder.geocode( { 'address': address}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					map.setCenter(results[0].geometry.location);
				} else {
					alert("Geocode was not successful for the following reason: " + status);
				}
			});
			var jsonreq = new Request.JSON({
				url: base + 'facilities/nearby/' + address,
				onSuccess: function(jsonlocs, jsonstr) {
					var summary = "<ul>\n";
					var foundone = false;
					for (var i = 0; i < jsonlocs.length; i++) {
						var loclatlng = new google.maps.LatLng(
							jsonlocs[i]['Facility']['latitude'],
							jsonlocs[i]['Facility']['longitude']
						);
						var marker = new google.maps.Marker({
							map: map, 
							position: loclatlng
						});
						var content = "<div><strong>" + jsonlocs[i]['Facility']['name'] + "</strong></div>\n"
							+ "<div>" + jsonlocs[i]['Facility']['address'] + "</div>\n"
							+ "<div>" + jsonlocs[i]['Facility']['city'] + ", "
							+ jsonlocs[i]['Facility']['state'] + " "
							+ jsonlocs[i]['Facility']['zip'] + "</div>\n"
							+ (jsonlocs[i]['Facility']['email'] ? "<div>" + jsonlocs[i]['Facility']['email'] + "</div>\n" : '')
							+ "<div>Phone: " + jsonlocs[i]['Facility']['phone'] + "</div>\n"
							+ (jsonlocs[i]['Facility']['fax'] ? "<div>Fax: " + jsonlocs[i]['Facility']['fax'] + "</div>\n" : '')
							+ "<div>Fee: " + jsonlocs[i]['Facility']['fee'] + "</div>\n";
						bindmapwindow(marker, map, infowin, "<div class='loccaption'>\n" + content + "</div>\n");
						if (jsonlocs[i]['Facility']['nearby']) {
							foundone = true;
							summary += "<li>" + content + "<div><em>Distance: "
								+ jsonlocs[i]['Facility']['distance'] + " miles</em></div></li>\n";
						}
					}
					summary += "</ul>\n";
					$('nearby_info').set('html', foundone ? summary : '<p>No facilities were found near this zip code.</p>');
				}
			}).send();
		} else {
			alert('Geocode error');
		}
	}
	function bindmapwindow(marker, map, infowin, content) {
		google.maps.event.addListener(marker, 'click', function() {
			infowin.setContent(content);
			infowin.open(map, marker);
		});
	}
	// Compute lat/long on facilities add/edit forms
	$$('.locationform').addEvent('submit', function(e) {
		e.stop();
		var geocoder = new google.maps.Geocoder();
		var locform = $(this);
		var address = $('locaddress').value + ', ' + $('loccity').value + ' ' + $('locstate').value + ' ' + $('loczip').value;
		if (geocoder) {
			geocoder.geocode( { 'address': address}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					$('loclatitude').set('value', results[0].geometry.location.lat());
					$('loclongitude').set('value', results[0].geometry.location.lng());
				}
				locform.submit();
			});
		} else {
			alert('Geocode error');
		}
	});
});
