modtypeSearch = null; // setup global variables for modtype livesearch
initialModtypeTerm = null;
var currentCountry; // setup global variable current country
sfHover = function() {
	var sfEls = document.getElementById("navibar").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		};
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		};
	}
};
if (window.attachEvent) window.attachEvent("onload", sfHover); //Simulates hover action so suckerfish menu works in IE

function findWikiLink () {
	$('modtype_wikilink').value=('http://en.wikipedia.org/wiki/' + ($('modtype_fullname') ? $F('modtype_fullname') : (parentypeName() + ' ' + $F('modtype_name')).strip()).replace(/\(.+\)/g,'').split(' ').join('_')); $('wikilink_search').replace("<a class='external' target='_blank' id='wikilink_check' href='" + $F('modtype_wikilink') + "'>show this wikipedia page</a>");	
													}
function getResourceForm (selekt)
{
	var idNo = selekt.id.match(/scraped_item_select_(-?\d+)/)[1];
	var dummyLink = document.createElement("a");
	dummyLink.href = "/resources/new?resourceable_type=" +  selekt.value + "&modtype_id=" + $$('#main_content h1 a').find(function(s) {return s.href.match(/modtypes\/(\d+)/);}).href.match(/modtypes\/(\d+)/)[1] + "&resource[title]=" + $F('scraped_item_title_' + idNo) + "&resource[url]=" + $F('scraped_item_url_' + idNo).escapeHTML();
	var m = new Control.Modal(dummyLink,{ requestOptions:{method: 'get'}});
	m.open();
	$('scraped_resource_' + idNo).hide();
}
// adds extra photo fieldsets to existing photo submit forms
function addExtraPhoto(link) {
	var mostRecentForm = $$('fieldset.photo_fields').last();
	var formNumber = mostRecentForm.id.replace('photo_fields_','');
	var noExistingPhotos = (/n_\d/).test(formNumber);
	var newFormNumber = noExistingPhotos ? Number(formNumber.replace('n_','')) + 1 : 0 ;
	var newForm = $(mostRecentForm.cloneNode(true));
	newForm.id = 'photo_fields_n_' + newFormNumber;
	var newFormLegend = newForm.select('legend').first();
	var existingLegendNumber = Number(newFormLegend.innerHTML.match(/\d$/)[0]);
	newFormLegend.update("Photo " + (existingLegendNumber + 1));
	if(!noExistingPhotos)
		newForm.select('label[for="uploaded_data"]').first().innerHTML = "Upload additional photo";
		newForm.select('textarea', 'input[type="file"]', 'input[type="text"]').each(function(s) {
					s.id = s.id.replace('photo_' + formNumber, 'photo_n_' + newFormNumber); 
					s.setAttribute("name", s.name.replace('photo[' + formNumber, 'photo[n_' + newFormNumber));
					s.clear();});
	currentPhoto = newForm.select("div.current_photo").first();
	if(currentPhoto){currentPhoto.remove();};
	link.parentNode.parentNode.insertBefore(newForm, link.parentNode);
	if(existingLegendNumber > 3)
		link.parentNode.remove();
	else
		link.href = link.href.replace("new_photos=" + Number(newFormNumber + 1), "new_photos=" + Number(newFormNumber + 2));
}
// toggles div specified in show_item_link
function toggleFromLink(link)
{
	$(link.id.replace("show_","")).toggle();
	link.className = link.className.replace(/(show|hide)/, function(word) {
		return( word == "show" ? "hide" : "show");
		});	
	link.innerHTML = link.innerHTML.replace(/(show|hide)/i, function(word) {
		var rt = (word.toLowerCase() == "show" ? "hide" : "show");
		return( word.charAt(0).match(/(H|S)/) ? rt.capitalize() : rt ); 
		});	
}
function newLiveModelSearch(element, value)
{
	if (value.length > 1) {
		
		if (modtypeSearch && value.match(initialModtypeTerm) ) { // don't make Ajax call if we have a search array AND the term used to find that array is a match for the current search value -- in which case the array is still value i.e. am is good for amaz but not mot
					var termRegexp = RegExp(value, "i");
					var subSetResults = modtypeSearch.findAll(function(n) {return n.title.match(termRegexp);});
					var htmlResults = resultsToLinks(subSetResults,termRegexp);
					$('live_search_results').update(htmlResults);
			}
		else {
			new Ajax.Request('/search/live_search', {asynchronous:true, evalScripts:true, parameters:'term=' + encodeURIComponent(value),
				onFailure: function(transport) {
					$('live_search_results').update('<p class="highlight">"' + 
						value + '" not found! Why not <a href="/modtypes/new?subtype=Model">add it to our list of models</a></p>');
				},
				onSuccess: function(transport) {
				modtypeSearch = eval(transport.responseText); // fill the global modtypeSearch array with results
				initialModtypeTerm = value;  // and also the term that was used to find them
				var termRegexp = RegExp(value, "i");
				var htmlResults = resultsToLinks(modtypeSearch,termRegexp);
				$('live_search_results').update(htmlResults);
				}
			});
		}
	}
}
function resultsToLinks(resultsArray,rExp) {
	var resultString = '<h4>"' + rExp.source + '" found in: </h4>\n<ul>' + 
		resultsArray.collect(function(s) {return resultToLink(s,rExp);}).join("\n") + "</ul>";
	return resultString;
}
function resultToLink(r,term){
	var l='<li><a href="/modtypes/' + r.id + '" class="modtype_link">' + r.title.sub(term, '<em>#{0}</em>') + '</a></li>'; return l;
};

Ajax.Responders.register({ 
 onCreate: function() { 
   if (Ajax.activeRequestCount > 0) 
     Element.show('wait-spinner'); 
 }, 
 onComplete: function() { 
   if (Ajax.activeRequestCount == 0) 
     Element.hide('wait-spinner'); 
 } 
 }); 
function parentypeName()
{
	var pN = $$('#main_content h1 a').first(); return (pN ? pN.innerHTML : ($('parenttype') ? $('parenttype').options[$('parenttype').selectedIndex].innerHTML : ''));
}
function showEbayCategory(link){
	var cDiv = link.up("div"); // find the current category div selected
	var cBody = cDiv.down("div.body");
	var aBody = $$("div#ebay_box div.active div.body").first(); // find the body of the active category div
	// unless we're already in the active category, hide the active category, make it inactive, and make current category active
	if(aBody != cBody){aBody.hide(); aBody.up("div").removeClassName('active').addClassName('inactive'); cDiv.removeClassName('inactive').addClassName('active'); cBody.show();}; 	
	if(!cBody.innerHTML.match(/Loading/g)){return false;}; //skip Ajax request if data is already there
	new Ajax.Request((link.href+'&max_entries=4'), {method:'get', asynchronous:true,
		onSuccess: function(transport) {
			cBody.hide();
			cBody.replace(transport.responseText);
			cBody.show();
		}});	
};
function showAdjacentThumb(link, pId, className){ // pass in id of new photo
	className = className || "thumbnail";
	var newThumb = $(className+'_'+pId);
	var thumbs = newThumb.up('div.photo_group').select('div.'+className);
	var cCaption = $(link.parentNode.previousSibling);
	var cImage = cCaption.previousSibling;
	var currPos = thumbs.indexOf(newThumb);
	cImage.src = newThumb.down('img').src.replace(/(small|thumb|medium)\./,"large.");
	cCaption.update(newThumb.down('a').title + linkToPhotoDetails(newThumb.down('a')));
	$("adjacent_image_links").replace(nextImageLinks(thumbs, currPos)); // pass number of thumbnails, and also the index of the NEW image
};
function nextImageLinks(thumbs, index){
	var result = '<p id="adjacent_image_links">';
	var tSize = thumbs.size();
	if(tSize > 1){
		if(index > 0 ){result+='<a href="#" class="previous" onclick="showAdjacentThumb(this,' + thumbs[index-1].id.match(/(\d+)/)[0] + ', \'' + thumbs[index].className +'\');return false;"><< Previous Photo</a>';};
		if(index < tSize-1 ){result+='<a href="#" class="next" onclick="showAdjacentThumb(this,' + thumbs[index+1].id.match(/(\d+)/)[0] + ', \'' + thumbs[index].className + '\');return false;">Next Photo >></a>';};
		result += '<br />' + tSize + ' in group&nbsp;';
	};
	result +='<a href="#" onclick="Control.Modal.close(); return false;" class="close-modal">close</a></p>';
	return result;
};
function linkToPhotoDetails(photoLink) { return ' (<a href="' + photoLink.href + '">See photo details</a>)';}

function getCountry() {
		if(!currentCountry){
		currentCountry = google.loader.ClientLocation.address.country_code;
		createCookie('current_country', currentCountry, 7);
		updateCurrentCountryFlag();
	};
}
function updateCurrentCountryFlag()
{
	var img = new Element('img', { 'class': 'icon', src: '/images/flags/' + currentCountry.toLowerCase() + '.gif' });
	// var link = new Element('a', {'id': 'choose_country_link', 'href':'#'}).update(img);
	$('user_country_flag').update(img);
	// Event.addBehavior({"a#choose_country_link": chooseCountryLink}); // this works in IE, but clicking on flags a second time doesn't . All OK in FF, Safari
}
// with thanks to http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}

function loadRTE()
{
	var tScript = new Element('script', { 'type': 'text/javascript', src: "http://yui.yahooapis.com/2.4.1/build/yuiloader/yuiloader-beta-min.js" });
	var h = $$('head').first();
	h.insert(tScript);
	$$('body').first().addClassName("yui-skin-sam");
	
	var rte_timer = setInterval(function () {
	      loaded = false;
	      try { 
	        loaded = (typeof YAHOO != 'undefined');
	      } catch (e) {}	
	      if (loaded) {
	        clearInterval(rte_timer);
					var loader = new YAHOO.util.YUILoader({
						// base:"/javascripts/build/",
						// filter:"DEBUG",
						require: ["editor"],
						onProgress: function(){Element.show('wait-spinner');},
						onSuccess: function() {
							Element.hide('wait-spinner'); 
						  var myEditor = new YAHOO.widget.Editor('rich_text_editor_field', { 
								 handleSubmit: true,
							   height: '300px', 
							   width: '500px',
								 toolbar: {
								        buttons: [
								            { group: 'textstyle', label: 'Text Style',
								                buttons: [
								                    { type: 'push', label: 'Bold', value: 'bold' },
								                    { type: 'push', label: 'Italic', value: 'italic' },
								                    { type: 'push', label: 'Underline', value: 'underline' },

													          { type: 'separator' },
																		{ type: 'push', label: 'HTML Link CTRL + SHIFT + L', value: 'createlink', disabled: true },
																		{ type: 'separator' },
																		{ type: 'color', label: 'Font Color', value: 'forecolor', disabled: true },
								                    { type: 'color', label: 'Background Color', value: 'backcolor', disabled: true },
												            { type: 'separator' },
																		{ type: 'push', label: 'Remove Formatting', value: 'removeformat', disabled: true }
								                ]
								            },
								
														{ type: 'separator' },
												    { group: 'parastyle', label: 'Paragraph Style',
												        buttons: [
												        { type: 'select', label: 'Normal', value: 'heading', disabled: true,
												            menu: [
												                { text: 'Normal', value: 'none', checked: true },
												                // { text: 'Header 1', value: 'h1' },
												                { text: 'Header 2', value: 'h2' },
												                { text: 'Header 3', value: 'h3' },
												                { text: 'Header 4', value: 'h4' },
												                { text: 'Header 5', value: 'h5' },
												                { text: 'Header 6', value: 'h6' }
												            ]
												        }
												        ]
												    },
												    { type: 'separator' },
												    { group: 'alignment', label: 'Alignment',
												        buttons: [
																		{ type: 'push', label: 'Align Left CTRL + SHIFT + [', value: 'justifyleft' },
												            { type: 'push', label: 'Align Center CTRL + SHIFT + |', value: 'justifycenter' },
												            { type: 'push', label: 'Align Right CTRL + SHIFT + ]', value: 'justifyright' },
												            { type: 'push', label: 'Justify', value: 'justifyfull' }
												        ]
												    },
												    { type: 'separator' },
												    { group: 'indentlist', label: 'Indenting and Lists',
												        buttons: [
																		{ type: 'push', label: 'Indent', value: 'indent', disabled: true }, 
																		{ type: 'push', label: 'Outdent', value: 'outdent', disabled: true },
																		{ type: 'push', label: 'Create an Ordered List', value: 'insertorderedlist' },
												            { type: 'push', label: 'Create an Unordered List', value: 'insertunorderedlist' }
												        ]
												    }
								        ]	   
								}
							});
							myEditor.on('afterOpenWindow', function() { //set z-index on link editing overlay
								myEditor.get('panel').cfg.setProperty('zIndex', 1999);
							});
					    //Override these methods on the current instance with copies from the SimpleEditor's prototype
					    // myEditor._handleCreateLinkClick = YAHOO.widget.SimpleEditor.prototype._handleCreateLinkClick;
					    // myEditor._handleCreateLinkWindowClose = YAHOO.widget.SimpleEditor.prototype._handleCreateLinkWindowClose;	
					    myEditor.render();
						}
					});
					loader.insert(); 
				}
			}, 10);
}
function showMap(resources, template)
{	
	var center;
	var zoom;
	var points;
	var template = template ? new Template(template) : new Template("<h4>#{title}</h4><p class='address'>#{full_address}</p><p class='read_more'><a href='#{url}'>more info</a></p>");
	var mapSize = new GSize(600, 500);
  var map = new google.maps.Map2(document.getElementById("map_canvas"), {size: mapSize});
	if(Object.isArray(resources)){
		var mapInfo = mapInfoFromPoints(resources);
		center = mapInfo[0];
		var bounds = mapInfo[1];
		zoom = map.getBoundsZoomLevel(bounds, mapSize);
		map.setMapType(G_HYBRID_MAP);
	} else {
		center = new GLatLng(resources.lat,resources.lng);
		zoom = 12;
		resources = $A([resources]);
	};
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());
  map.setCenter(center, zoom);

	function createMarker(res, message) {
		var point = new GLatLng(res.lat,res.lng);
	  var marker = new GMarker(point);
	  GEvent.addListener(marker, "click", function() {
	    map.openInfoWindowHtml(point, message, {maxWidth:200});
	  });
	  return marker;
	}
	var resource = resources.first();
	resources.each(function(resource,i){
		var caption = template.evaluate(resource);
		map.addOverlay(createMarker(resource, caption));
	});
}
function mapInfoFromPoints (points)
{	
	var lats = points.pluck('lat');
	var lngs = points.pluck('lng');
	var maxLat = Math.max.apply(null,lats);
	var minLat = Math.min.apply(null,lats);
	var maxLng = Math.max.apply(null,lngs);
	var minLng = Math.min.apply(null,lngs);
	var center = new GLatLng((minLat+(maxLat-minLat)/2),(minLng+(maxLng-minLng)/2));
	var bounds = new GLatLngBounds(
			new GLatLng(minLat, minLng),
			new GLatLng(maxLat, maxLng)
		);
	return [center, bounds];
}
// Behaviours
var ShowLargeImage = Behavior.create({
onclick : function() { 
	var pLink = this.element;
	var pBlock = pLink.up('div.photo_group');
	var thumbs = pBlock ? pBlock.select('div.thumbnail', 'div.small_photo') : [];
	var pDiv = pLink.up().match('div.caption') ? pLink.up('div', 1) : pLink.up('div');
	var curPos = thumbs.indexOf(pDiv);
	Control.Modal.open(false, {opacity: 0.75, waitForImageToLoad:true, contents: '<img src=\"' + $(pDiv.down('img')).src.replace
	(/(small|thumb|medium)\./,"large.") + '" id="modal_image" /><p class="caption">' + pLink.title + linkToPhotoDetails(pLink) + '</p>' + nextImageLinks(thumbs, curPos)}); return false;} 
});

var LoadRteFromLink = Behavior.create({
	onclick : function() {
		// alert('about to load RTE');
		$('rich_text_editor_field').value = $('rich_text_editor_field').value.replace(/\\n/g, '<br />'); 
		loadRTE(); 
		this.element.remove(); 
		return false;
	}	
});

var chooseCountry = Behavior.create({
	onclick : function() {
		currentCountry = this.element.id.match(/chosen_country_(-?\w+)/)[1];
		createCookie('current_country', currentCountry, 7);
		updateCurrentCountryFlag();
		Control.Modal.close();
		return false;
	}
});
var chooseCountryLink = Behavior.create({
	onclick : function() {
		var c = $('alternative_countries').innerHTML + '<p class="close-modal"><a href="#" onclick="Control.Modal.close(); return false;">close</a></p>';
		Control.Modal.open(this.element, {position:'relative', offsetLeft: 200, offsetTop:26, closeOnClick:true, contents:c, overlayDisplay:false, afterOpen: function(){Event.addBehavior({ "a.chosen_country_link": chooseCountry }); }}); 
		return false;
		}
});

Event.addBehavior({
".show-for-js": function(event) {
Element.show(this);
},
".hide-for-js": function(event) {
Element.hide(this);
},
"a.external:click": function(event) {
window.open(this.href, "ext"); return false;
},
"form:submit": function(event) {
Element.show("wait-spinner"); this.getInputs("submit").each(function(submit) {submit.value = "Processing..."; submit.disable();});
},
"form.delete_button:click": function(event) {
return confirm('Are you sure?');
},
"a.modal_link": function(event) {
new Control.Modal(this, {overlayCloseOnClick: false, waitForImageToLoad:true, zIndex:99, requestOptions:{method: 'get'}}); return false;
},
"a.remote": Remote.Link,
"form.remote": Remote.Form,
"a.add_extra_photo:click": function(event) {
addExtraPhoto(this); return false;
},
".thumbnail a": ShowLargeImage,
".small_photo a": ShowLargeImage,
".main_photo a": function(event) {
var phDiv = this.up('div.main_photo');
if(phDiv.id == 'flickr_photo'){ return true;}; //follow link if it's a flickr image
var oldImg = phDiv.down('img'); new Control.Modal(this, {opacity: 0.75, waitForImageToLoad:true, contents: '<img src=\"' + oldImg.src.replace("medium", "large") + '" id="modal_image" /><p class="caption">' + oldImg.title + ' (<a href="' + this.href + '">See photo details</a>)</p><p class="close-modal"><a href="#" onclick="Control.Modal.close(); return false;">close</a></p>'}); return false;
},
"a.next_thumb_link:click": function(event) {
	showNextThumb(this); return false;
}, 
"a.modal_image": function(event) {
new Control.Modal(this); return false;
},
"a.modtype_link": function(event) {
new Control.Modal(this, {position: 'relative', offsetLeft: 25, offsetTop: 5, width: 200, hover: true, requestOptions:{method: 'get'}}); return false;
},
"a.toggle_item:click": function(event) {
toggleFromLink(this); return false;
},
"#modal_container form#new_message": Remote.Form,
"#wrapper a.amazon_book": function(event) {
new Control.Modal(this, {position: 'relative', offsetLeft: -100, offsetTop: -100}); return false;
},
"#modal_container a.amazon_book": function(event) {
new Control.Modal(this); return false;
},
"a.add_feed:click": function(event) {
new Ajax.Request('/feeds', {asynchronous:true, evalScripts:true, parameters:'feed_id=' + this.href});
return false;
},
"#header-livesearch-term": function(event) {
	new Form.Element.Observer('header-livesearch-term', 0.5, newLiveModelSearch );
	},
"a.abuse_link:click": function(event) {
	new Ajax.Request(this.href, {asynchronous:true, evalScripts:true, method:'get'}); return false;
	},
"a.search_amazon:click": function(event) {
		new Ajax.Updater('amazon_result', this.href, {asynchronous:true, evalScripts:true, onFailure:function(request){new Effect.Highlight('amazon_result', {duration: 3});}, parameters:'term=' + $F('resource_title')});	return false;
	},
"a.ratings_block_vote_link:click": function(event) {
	new Ajax.Request(this.href.replace('new',''), {asynchronous:true, evalScripts:true}); return false;
},
"div.show_as_alert": function(event) {
	var alertBox = this;
	this.remove();
	var m = new Control.Modal(false, {contents: ('<div id=\"modal_inner\">' + alertBox.innerHTML + '</div><div class=\"close-modal\"><a href=\"#\" onclick=\"Control.Modal.close(); return false;\">close</a></div>')});
	m.open();
	},
"input.todo_complete_box": function(event) {
	new Form.Element.EventObserver(this, function(element, value) {new Ajax.Request(('/todos/' + element.id.replace('todo_complete_box_','')), {asynchronous:true, evalScripts:true, method:'put', parameters:'todo[completed]=' + (element.checked ? 1 : 0) });});
	},
"a.add_friend_button:click": function(event) {
		new Ajax.Request('/friendships', {asynchronous:true, evalScripts:true, parameters:'friend_id=' + this.href});
		return false;
	},
"#user_messaging_block form.delete_button": Remote.Form,
"select.scraped_item_select:change": function(event) {
	getResourceForm(this);
	},
"a#wikilink_search:click": function(event) {
		findWikiLink(); return false;
	},	
"input#modtype_name": function(event) {
	new Form.Element.Observer(this, 0.2, function(element, value) {if($('fullname_value')) {$('fullname_value').update(parentypeName() + ' ' + $F('modtype_name')); }});
	},
"#edit_fullname:click": function(event) {
	$('fullname_area').update('<label for="modtype_fullname">Full name (including Marque)</label><br><input id="modtype_fullname" name="modtype[fullname]" size="30" value="'+ parentypeName() + ' ' + $F('modtype_name') + '" type="text">');
	},
"#parenttype:change": function(event) {
	if(oldParentValue !== undefined){var r=confirm('Are you sure you want to change this model\'s parent?'); if(!r){$('parenttype').value = oldParentValue;};};
	},
".read_more_container a.read_more:click": function(event) {
	var parent = this.up(".read_more_container");
	parent.down('div.show-for-js').hide();
	parent.down('div.hide-for-js').show();
	return false;
	},
"a.expander:click": function(event) {
	new Ajax.Request('/modtypes/' + $(this).id.replace('expander_', '') + '/expand', {asynchronous:true, evalScripts:true, method:'get'}); return false;
	},
"input#disposed_of": function(event) {
	this.observe('click', function(){$("disposed_of_picker").show(); $("disposed_of_trigger").hide();});
	},
"a#insert_template:click": function(event) {
	try{YAHOO.widget.EditorInfo.getEditorById('rich_text_editor_field').setEditorHTML(siteTemplate);}
	catch(e){ $('rich_text_editor_field').value = siteTemplate;}
		this.remove(); return false;
	},
"#rich_text_editor_field": function(event){
	if($$('.yui-editor-container').size > 0){alert('RTE Editor already exists'); return;};
	if(this.getValue().search(/<\/?[^>]+>/gi)>=0){ //load RTE if textarea contains any tags
		loadRTE(); 
		}
	else {	//insert link to add editor
		var rteLink = new Element('a', { 'class': 'add_rte' }).update("Add formatting");
		this.up().down('label').insert(rteLink);
		Event.addBehavior({"a.add_rte": LoadRteFromLink});
		}
	},
"a.ebay_category_link:click": function(event) {
	showEbayCategory(this);	return false;
	},
"a#ebay_models_link": function(event) {
	showEbayCategory(this);	return false;
	},
"a#choose_country_link": chooseCountryLink,
"a.uncheck_all_boxes:click": function(event) {
	this.up(".checkboxes").select("input.checkbox").each(function(s) {s.checked = 0;});	return false;
	},
"a.check_all_boxes:click": function(event) {
	this.up(".checkboxes").select("input.checkbox").each(function(s) {s.checked = 1;});	return false;
	}
});
Event.addBehavior.reassignAfterAjax = true;