/*****
**
** CSS HELPERS
**
****/

function standardize_box_heights(dom_query, count_children, line_size) {
	
	var count_children = count_children ? count_children : 'li';
	var line_size = line_size ? line_size : '1.5';
	
	var rows = new Array({elements: []});
	var row = 0;
	var offset = 0;
	
	$$(dom_query).each(function(el) {
		
		// if the offset has changed (i.e. we are on the next row), reset biggest
		if (el.offsetTop > offset) {
			
			// see if we've used the first index yet
			if (rows.length) {
				++row;
			}
			
			offset = el.offsetTop;
			
			rows[row] = {biggest: 0, elements: []}
		}
		
		// store the element in the rows array
		rows[row].elements.push(el);
		
		num_elements = el.getElementsBySelector(count_children).length;
		
		// if the number of elements is greater than the last, update biggest
		if (num_elements > rows[row].biggest) {
			rows[row].biggest = num_elements;
		}
		
	});
	
	rows.each(function(obj) {
		
		obj.elements.each(function(el) {
			
			el.style.height = 4 + (obj.biggest * line_size) + 'em';
			
		});
		
	});
	
}

/*****
**
** FORM HELPERS
**
****/

function showHint(id, hint) {
	
	var el = $(id);
	
	if (el.value == '') {
	
		el.value = hint;
		el.className = 'blur';
		
	}
	
	el.onfocus = function() {
		
		if (el.value == hint) {
			
			el.value = '';
			el.className = '';
			
		}
	
	}
	
	el.onblur = function() {
		
		if (el.value == '') {
			
			el.value = hint;
			el.className = 'blur';
			
		}
		
	}
}

function checkKey(evt) {
	
	var key;
	
	if ("which" in evt) { // ns/ff/op
		
		key = evt.which;
		
	}
	
	else if ("keyCode" in evt) { // sf/ie4
		
		key = evt.keyCode;
		
	}
	
	else if ("keyCode" in window.event) { // ie4+
		
		key = window.event.keyCode;
		
	}
	
	else if ("which" in window.event) {
		
		key = evt.which;
		
	}
	
	return key;
	
}

function populateForm(data) {
	
	data.each(function(obj) {
		
		switch (obj['type']) {
			case 'select':
				
				if (typeof obj['value'] == 'object' && obj['value']) {
					populateSelect(obj['field'], obj['value']);
				}
				else if (obj['value']) {
					
					$$('#' + obj['field'] + ' option').each(function(el) {
						el.selected = (obj['value'] == el.value) ? true : false;
					});
					
				}
				
				break;
			default:
				break;
		}
		
	});
	
}

function populateSelect(elementId, data, key, value, selected_key, key_is_index) {
	
	key   = key   ? key   : 'id';
	value = value ? value : 'name';
	
	var select = $(elementId);
	
	// reset this to just the first (blank) option
	select.length = 1;
	
	data.each(function(row) {
		
		var opt = new Option(row[value], row[key]);
		
		if (!key_is_index && selected_key == row[key]) {
			
			opt.selected = 'selected';
			
		}
		
		if (key_is_index && selected_key == select.length) {
			
			opt.selected = 'selected';
			
		}
		
		select.options[select.length] = opt;
		
	});
	
}

function toggleDisable(elementId, toggleMessage, forceEnable) {
	
	var el = $(elementId);
	
	if (toggleMessage) {
		
		if (forceEnable == false) {
			
			el.selectedIndex = 0;
			
		}
		
		el.options[0].text = toggleMessage;
		
	}
	
	el.disabled = el.disabled || forceEnable ? false : true;
	
	return true;
	
}

function clearSelect(selectId) {
	
	var el = $$('select');
	
	el.each(function(el) {
		
		if (el.id == selectId) {
			
			el.options[0].selected = true;
			
		}
		
	});
	
	return true;
	
}

function toggleSellFieldset(elementId) {
	
	$$('form.edit div.sellStepNav a').each(function(el) {
		
		if (el.id == elementId + 'Link') {
			el.addClassName('active');
		}
		else {
			el.removeClassName('active');
		}
		
	});
	
	
	return toggleFieldset(elementId);
	
}

function toggleAccountType(existing) {
	
	if (existing == 1) {
		
		$('accountNew').hide();
		$('accountExisting').show();
		$('accountExistingLink').addClassName('active');
		$('accountNewLink').removeClassName('active');
		
	}
	else {
		
		$('accountNew').show();
		$('accountExisting').hide();
		$('accountExistingLink').removeClassName('active');
		$('accountNewLink').addClassName('active');
		
	}
	
}

function checkActiveFieldset(urlAnchor) {
	
	var fieldset = $$(urlAnchor);
	
	fieldset = (fieldset.length) ? fieldset[0].id : 'vehicle';
	
	if ($(fieldset + 'Link').className != 'active') {
		toggleSellFieldset(fieldset);
	}
	
	return true;
	
}

function toggleFieldset(elementId) {
	
	$$('fieldset').each(function(el) {
		
		if (elementId != el.id && el.visible()) {
			el.hide();
		}
		
	});
	
	$(elementId).show();
	
}

function toggleHelp(elementId, event) {
	
	$$('div.notice.help').each(function(el) {
		if (el.id == elementId && !el.visible()) {
			new Effect.Appear(el);
		}
		else if (el.visible()) {
			new Effect.Fade(el);
		}
	});
	
}

var button_to_disable;

function disableButton(button) {
	
	button = button ? button : button_to_disable;
	button.disabled = true;
	
}

function disableSubmit(el) {
	
	el.className = el.className + ' disabled'; 
	el.innerHTML = 'Please wait...';
	
	button_to_disable = el;
	
	window.setTimeout('disableButton();', 10);
	
	return true;
	
}

function enableSubmit(button, text) {
	
	button = $(button);
	
	button.disabled = false;
	button.removeAttribute('disabled');
	button.removeClassName('disabled');
	button.innerHTML = text;
	
}

function toggleActivateLabel(id) {
	
	$(id).parentNode.className = $(id).parentNode.className == 'active' ? '' : 'active';
	
	return true;
	
}

function highlightError(field) {
	
	var el = $(field);
	var label = $$('label[for=' + field + ']')[0];
	
	if (field.substring(0,5) == 'phone') {
		
		var num = field.substring(6,7);
		
		if (parseInt(num) == $$('p.phoneGroup').length) {
			
			el = $('phone_input');
			label = $$('p#contactPhone1 label')[0];
			
		}
		else {
			
			el = $$('p.phoneGroup span')[parseInt(num)];
			label = $$('p.phoneGroup label')[parseInt(num)];
			
		}
		
	}
	
	var fieldset_id = el ? el.up('div.page').id : false;
	var link = $(fieldset_id + 'Link');
	
	if (el) {
		
		el.addClassName('error');
		
	}
	
	if (label) {
		
		label.addClassName('error');
		
	}
	
	if (link) {
		
		link.addClassName('error');
		
	}
	
	if (!selectedFieldset && fieldset_id) {

		fieldset_id = fieldset_id.replace('Content', '');

		selectedFieldset = fieldset_id;
		activateTab(fieldset_id);
		
	}
	
}

/*
 * Copyright (c) 2006 Jonathan Weiss <jw@innerewut.de>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
if (typeof Class != 'undefined') {
	var Tooltip = Class.create();
	Tooltip.prototype = {
	  initialize: function(element, tool_tip) {
	    var options = Object.extend({
	      default_css: false,
	      margin: "0px",
		  padding: "5px",
		  backgroundColor: "#d6d6fc",
		  delta_x: 5,
		  delta_y: 5,
	      zindex: 1000
	    }, arguments[1] || {});
	
	    this.element      = $(element);
	    this.tool_tip     = $(tool_tip);
	
	    this.options      = options;
	
	    // hide the tool-tip by default
	    this.tool_tip.hide();
	
	    this.eventMouseOver = this.showTooltip.bindAsEventListener(this);
	    this.eventMouseOut   = this.hideTooltip.bindAsEventListener(this);
	
	    this.registerEvents();
	  },
	
	  destroy: function() {
	    Event.stopObserving(this.element, "mouseover", this.eventMouseOver);
	    Event.stopObserving(this.element, "mouseout", this.eventMouseOut);
	  },
	
	  registerEvents: function() {
	    Event.observe(this.element, "mouseover", this.eventMouseOver);
	    Event.observe(this.element, "mouseout", this.eventMouseOut);
	  },
	
	  showTooltip: function(event){
		Event.stop(event);
		// get Mouse position
	    var mouse_x = Event.pointerX(event);
		var mouse_y = Event.pointerY(event);
		
		
		// decide if wee need to switch sides for the tooltip
		var dimensions = Element.getDimensions( this.tool_tip );
		var element_width = dimensions.width;
		var element_height = dimensions.height;
		
		if ( (element_width + mouse_x) >= ( this.getWindowWidth() - this.options.delta_x) ){ // too big for X
			mouse_x = mouse_x - element_width;
			// apply delta to make sure that the mouse is not on the tool-tip
			mouse_x = mouse_x - this.options.delta_x;
		} else {
			mouse_x = mouse_x + this.options.delta_x;
		}
		
		if ( (element_height + mouse_y) >= ( this.getWindowHeight() - this.options.delta_y) ){ // too big for Y
			mouse_y = mouse_y - element_height;
		    // apply delta to make sure that the mouse is not on the tool-tip
			mouse_y = mouse_y - this.options.delta_y;
		} else {
			mouse_y = mouse_y + this.options.delta_y;
		} 
		
		// now set the right styles
		this.setStyles(mouse_x, mouse_y);
		
			
		// finally show the Tooltip
		//new Effect.Appear(this.tool_tip);
		new Element.show(this.tool_tip);
	
	  },
	  
	  setStyles: function(x, y){
	    // set the right styles to position the tool tip
		Element.setStyle(this.tool_tip, { position:'absolute',
		 								  top:y + "px",
		 								  left:x + "px",
										  zindex:this.options.zindex
		 								});
		
		// apply default theme if wanted
		if (this.options.default_css){
		  	Element.setStyle(this.tool_tip, { margin:this.options.margin,
			 								  padding:this.options.padding,
			                                  backgroundColor:this.options.backgroundColor,
											  zindex:this.options.zindex
			 								});	
		}	
	  },
	
	  hideTooltip: function(event){
		//new Effect.Fade(this.tool_tip);
		new Element.hide(this.tool_tip);
	  },
	
	  getWindowHeight: function(){
	    var innerHeight;
		if (navigator.appVersion.indexOf('MSIE')>0) {
			innerHeight = document.body.clientHeight;
	    } else {
			innerHeight = window.innerHeight;
	    }
	    return innerHeight;	
	  },
	 
	  getWindowWidth: function(){
	    var innerWidth;
		if (navigator.appVersion.indexOf('MSIE')>0) {
			innerWidth = document.body.clientWidth;
	    } else {
			innerWidth = window.innerWidth;
	    }
	    return innerWidth;	
	  }
	
	}
}

/*****
**
** MODALBOX HELPERS
**
****/

function showCalcModal(anchor) {
	
	Modalbox.show(anchor.href, {title: anchor.title, overlayOpacity: 0.3 });
	
}

function showGalleryModal(anchor) {
	
	Modalbox.show($('galleryContainer'), {width: 745, overlayOpacity: 0.3, title: anchor.title});
	
	window.setTimeout('Modalbox.resizeToContent()', 5000);
	
}

function showUcdaModal(anchor) {
	
	showActionModal(anchor);
	
}

function showActionModal(anchor, options) {

	if (!options) {

		options = {};

	}

	options.title = anchor.title;
	
	showContentModal(anchor.href, options);
	
}

function showContentModal(content, options) {

	if (!options) {

		options = {};

	}
	
	var props = $H({width: 800, overlayOpacity: 0.3 });
	props.update(options);
	
	Modalbox.show(content, props.toObject());
	
}

function showSendFriendModal(anchor) {
	
	Modalbox.show(anchor.href, {title: 'Send article to friend: ' + anchor.title, width: 500, overlayOpacity: 0.3 });
	
}

/*****
**
** SEARCH HELPERS
**
****/

function showHint(id, hint) {
	
	if (!document.getElementById || !document.getElementById(id)) {
		
		return false;
		
	}
	
	var el = $(id);
	
	if (el.value == '') {
	
		el.value = hint;
		el.className = 'blur';
		
	}
	
	el.onfocus = function() {
		
		if (el.value == hint) {
			
			el.value = '';
			el.className = 'test';
			
		}
	
	}
	
	el.onblur = function() {
		
		if (el.value == '') {
			
			el.value = hint;
			el.className = 'blur';
			
		}
		
	}
}

var postalCodeTmp = '';

function changeSearchBy(name) {
	
	var link = $(name + 'Link');
	var altLink = $((name == 'byPostalCode' ? 'byRegionLink' : 'byPostalCodeLink'));
	
	var block = $(name);
	var altBlock = $((name == 'byPostalCode' ? 'byRegion' : 'byPostalCode'));
	
	var postalCode = $('postalCode');
	
	if (name == 'byRegion') {
		
		postalCodeTmp = postalCode.value;
		postalCode.value = '';
		
	}
	else if (postalCodeTmp) {
		
		postalCode.value = postalCodeTmp;
		
	}
	
	block.style.display = 'block';
	altBlock.style.display = 'none';
	
	if (link) {
		
		link.addClassName('activeTab');
		altLink.removeClassName('activeTab');
		
	}
	
}

function changeSearchByRadio(name) {
	
	switch (name) {
		
		case 'region':
			
			if ($('postalCode').value) {
				
				postalCodeTmp = $('postalCode').value;
				$('postalCode').value = '';
				
			}
			
			break;
			
		case 'postal':
			
			// put the postalcode back if there's not one already
			if (!$('postalCode').value) {
				$('postalCode').value = postalCodeTmp;
			}
			
			break;
		
	}
	
	if (!$('searchBy_' + name).checked) {
		
		$('searchBy_' + name).checked = true;
		
	}
	
	return;
	
	var link = $(name + 'Link');
	var altLink = $((name == 'byPostalCode' ? 'byRegionLink' : 'byPostalCodeLink'));
	
	var block = $(name);
	var altBlock = $((name == 'byPostalCode' ? 'byRegion' : 'byPostalCode'));
	
	var postalCode = $('postalCode');
	
	if (name == 'byRegion') {
		
		postalCodeTmp = postalCode.value;
		postalCode.value = '';
		
	}
	else if (postalCodeTmp) {
		
		postalCode.value = postalCodeTmp;
		
	}
	
	block.style.display = 'block';
	altBlock.style.display = 'none';
	
	if (link) {
		
		link.addClassName('activeTab');
		altLink.removeClassName('activeTab');
		
	}
	
}

function submitSearch() {
	
	var el = $('byRegion');
	
	if (el.style.display == 'block') {
		$('postalCode').value = '';
	}
	
	return true;
	
}

function submitForm() {
	
	submitSearch();
	return $('quickForm').submit();
	
}

var submitTimeout;

function timedSubmit(form) {
	
	if (submitTimeout) {
		window.clearTimeout(submitTimeout);
	}
	
	submitTimeout = setTimeout(submitForm, 4000);
	
}

function toggleModelCategory() {
	
	var model = $('model_name');
	var cat = $('category_id');
	
	if (model.value != 0) {
		cat.disabled = true;
	}
	else if (cat.value != 0) {
		model.disabled = true;
	}
	else {
		cat.disabled = false;
		model.disabled = false;
	}
	
	return true;
	
}

function create_table_row_links() {
	
	var rows = $$('table.searchListView tbody tr');
	
	rows.each(function(item) {
		
		Element.extend(item);
		var anchor = item.getElementsBySelector('td a');
		anchor = anchor[0];
		
		item.onclick = new Function("document.location = '" + anchor.href + "';");
		item.onmouseover = new Function('this.style.cursor = "pointer"; this.style.cursor = "hand";');
		
	});
	
}


function selectVehicleType(categoryId, calledBySelect) {
	
	var icons = $$('img.typeIcon');
	var onSrc = '/images/icon/vehicle/category_' + categoryId + '_on.png';
	
	// turn off all the icons; turn on the icon matching categoryId, unless it was already on, then we turn it off
	icons.each(function(el) {
		
		el.src = (el.id == 'category_' + categoryId && el.src.indexOf("_on.png") == -1) ? onSrc : '/images/icon/vehicle/' + el.id + '.png';
		
	});
	
	var icon = $('category_' + categoryId);
	
	// only change the dropdown value if it wasn't the select that called this function
	if (!calledBySelect) {
		
		$$('#category_id option').each(function(el) {
			el.selected = (el.value == categoryId && (!icon || (icon && icon.src.indexOf("_on.png") != -1))) ? true : false;
		});
		
	}
	
	new Effect.Highlight('category_id', {startcolor: '#99ff99', endcolor: '#ffffff'});
	
	return true;
	
}


/*****
**
** SLIDER HELPERS
**
****/

function check_slider_range(v, evt) {
	
	//prevent overlap
	left_handle_value = parseInt(v[0]);
	right_handle_value = parseInt(v[1]);
	
	
	if (evt.activeHandleIdx == 0 && left_handle_value > right_handle_value) {
		
		evt.setValue(right_handle_value, 0);
		
	}
	
	if (evt.activeHandleIdx == 1 && left_handle_value > right_handle_value) {
		
		evt.setValue(left_handle_value, 1);
		
	}
	
};

var update_slider_label = function(v, evt) {
	
	var label;
	var inputvalue = v;
	var multivalue = false;
	
	var labelPrefix = evt.options.labelText ? evt.options.labelText : '';
	var labelSuffix = evt.options.labelTextSuffix ? evt.options.labelTextSuffix : '';
	
	var minhitLabel = evt.options.minhitLabel ? evt.options.minhitLabel : 'under ';
	var maxhitLabel = evt.options.maxhitLabel ? evt.options.maxhitLabel : 'over ';
	
	
	// if it's an array, do the slider range check
	if (v.constructor.toString().indexOf('Array') > 0) {
		
		multivalue = true;
		check_slider_range(v, evt);
		
	}
	
	label = multivalue ? v[0] + '-' + v[1] : v;
	
	var maxhit = (v == evt.options.range.end || (multivalue && v[1] == evt.options.range.end)) && evt.options.unlimitedMaxValue;
	var minhit = (v == evt.options.range.start || (multivalue && v[0] == evt.options.range.start)) && evt.options.zeroMinValue;
	
	// if the slider is at the very end, we show a special label value (i.e. "over xxx")
	if (maxhit) {
		
		label = multivalue ? v[0] : evt.options.labelMaxvalue;
		labelPrefix = multivalue ? maxhitLabel + labelPrefix : labelPrefix;
		
		inputvalue = multivalue ? [v[0], evt.options.inputMaxvalue] : evt.options.inputMaxvalue;
		
	}
	
	// if the slider is at the very beginning, we show a special value (i.e. "under xxx")
	else if (minhit) {
		
		label = multivalue ? v[1] : evt.options.labelMinvalue;
		labelPrefix = multivalue ? minhitLabel + labelPrefix : labelPrefix;
		
		inputvalue = multivalue ? [0, v[1]] : 0;
		
	}
	
	
	
	label = labelPrefix + label + labelSuffix;
	
	if (multivalue && v[0] == evt.options.range.start && v[1] == evt.options.range.end && evt.options.minMaxLabel) {
		
		label = evt.options.minMaxLabel;
		inputvalue = multivalue ? [0, 0] : 0;
		
	}
	
	$(evt.options.labelId).innerHTML = label;
	
	if (evt.options.inputName) {
		
		if (multivalue) {
			
			$(evt.options.inputName + '_start').value = inputvalue[0];
			$(evt.options.inputName + '_end').value = inputvalue[1];
			
		}
		else {
			
			$(evt.options.inputName).value = inputvalue;
			
		}
		
	}
	
}

/*****
**
** VEHICLE HELPERS
**
****/

function processUpload(imageUploader) {
	
	var obj = getImageUploader(imageUploader);
	
	// if the image uploader exists, use it to submit BOTH forms
	if (obj) {
		obj.Send();
	}
	
	// otherwise just use the regular form (return true to onSubmit)
	else {
		return true;
	}
	
	return false;
	
}

function format_float(value) {
	
	value = parseFloat(format_number(value));
	
	if (isNaN(value)) {
		return 0;
	}
	
	return value;
	
}

function format_integer(value) {
	
	value = parseInt(format_number(value));
	
	if (isNaN(value)) {
		return 0;
	}
	
	return value;
	
}

function format_number(value) {
	
	value = value.replace(/,/g, "");
	value = value.replace(/[kK]+/, 'k');
	value = value.replace(/[kK]/, "000");
	
	return value;
	
}

function updateProvinceCode(code, field_prefix, force_update) {
	
	if (!code && !force_update) {
		
		return false;
		
	}
	
//	field_prefix = field_prefix ? field_prefix + '_' : '';
	
	select_name = field_prefix + 'province_code';
	region_name = field_prefix + 'region_id';
	
	select = $(select_name);

	for (i=0; i<select.options.length; i++) {
		
		if (select.options[i].value == code) {
			
			select.selectedIndex = i;
			
			new Ajax.Request('/geography/regionLookup', {asynchronous:true, evalScripts:false, onComplete:function(request, json){populateSelect(region_name, json); toggleDisable(region_name);}, onLoading:function(request, json){toggleDisable(region_name);}, parameters:'province_code=' + $(select_name).options[$(select_name).selectedIndex].value + '&fieldname=' + select_name});				
			
		}
		
	}
	
}

function updatePostalCode(json) {
	
	var city = (json['city'] && json['province_code']) ? json['city'] + ', ' + json['province_code'] : '';
	var recheck_link = ' (<a href="#" class="alwayson">Re-check Postal Code</a>)';
	
	$('city').innerHTML = city ? city + recheck_link : '<strong style="color: #990000;">Can\'t find postal code! Try entering a nearby postal code.' + recheck_link + '</strong>';
	$('postal_code').value = json['postal_code'];
	
	return city ? true : false;

}

function removeCustomFeature(idx) {
	
	return $("custom_feature_" + idx).parentNode.remove()
	
}

var custom_feature_index = 0;

function addCustomFeature(value) {
	
	// see if they are just passing a value or if they've entered one
	if (!value || !value.trim()) {
		var newEl = $('new_custom_feature');
		
		value = newEl.value;
		
		if (!value.trim()) {
			
			return false;
			
		}
		
		newEl.value = '';
		
	}
	
	// increment the index so items don't start clobbering each other
	++custom_feature_index;
	
	t = new Template('<li><input type="checkbox" checked="checked" value="#{value}" name="custom_feature[#{id}]" id="custom_feature_#{id}" />&nbsp;<label for="custom_feature_#{id}">#{value}</label></li>');
	
	new Insertion.Before('otherFeaturesInput', t.evaluate({id: custom_feature_index, value: value}));
	
	var newLi = $('custom_feature_' + custom_feature_index).parentNode;
	
	new Effect.Appear(newLi);
	
}

var contact_phone_index = 0;

function addContactPhone(phoneNum, phoneType) {
	
	if ($$('p.phoneGroup').length >= 2) {
		
		alert('You may enter a maximum of 3 contact numbers!');
		return false;
		
	}
	
	var typeSelect = $('phone_type_select');
	var phoneInput = $('phone_input');
	
	var phone_value = phoneNum ? phoneNum : phoneInput.value;
	
	var phone_type_id = phoneType ? phoneType : typeSelect.options[typeSelect.selectedIndex].value;
	var phone_type_label = phoneType ? phoneType : typeSelect.options[typeSelect.selectedIndex].text;
	
	if (phoneType) {
		
		$$('select#phone_type_select option').each(function (el) {
			
			if (el.value == phoneType) {
				
				phone_type_label = el.text;
				
			}
			
		});
		
	}
	
	// stop here if the value is empty
	if (!phone_value.trim()) {
		return false;
	}
	
	++contact_phone_index;
	
	var phoneGroupTag = '<p class="labelFieldPair phoneGroup" id="phoneGroup#{index}">' +
							'<label for="phone_2">#{phone_type_label}: </label>' +
							'<span class="phone">#{phone_value}</span>' +
							'<a href="#" onclick="if (!confirm(\'Really delete contact number (#{phone_value})?\')) { return false; } delContactPhone(#{index}); return false;" title="Remove Contact Number"><img src="/images/icon/bin_closed.png" alt="Remove Contact Number" /></a>' +
							'<input type="hidden" name="phone_type[]" value="#{phone_type_id}" />' +
							'<input type="hidden" name="phone[]" value="#{phone_value}" />' +
						'</p>';
	
	var t = new Template(phoneGroupTag);
//	var t = new Template('<p><select name="phone_type_#{id}">#{options}</select> <input type="text" name="phone_#{id}" /></p>');
	
	new Insertion.Before('contactPhone1', t.evaluate({phone_type_label: phone_type_label, phone_type_id: phone_type_id, phone_value: phone_value, index: contact_phone_index}));
	
	// if the number didn't get passed in, it came from the input, so clear it here
	if(!phoneNum) {
		phoneInput.value = '';
	}
	
}

function delContactPhone(phoneId) {
	
	$('phoneGroup' + phoneId).remove();
	
	return true;
	
}

function showNextPhoto() {
	
	el = $('galleryLargephoto');
	
	nextId = galleryIndex + 1;
		
	if (!images[nextId]) {
		nextId = 0; 
	}
	
	el.src = images[nextId].src;
	galleryIndex = nextId;
	
	// make sure the new photo fits
	Modalbox.resizeToContent();
	
}

function showPrevPhoto() {
	
	el = $('galleryLargephoto');
	
	prevId = galleryIndex - 1;
	
	if (!images[prevId]) {
		
		prevId = images.length - 1;
		
	}
	
	el.src = images[prevId].src;
	galleryIndex = prevId;
	
	// make sure the new photo fits
	Modalbox.resizeToContent();
	
}


function linkToZoom(anchor) {
	
	var img = $(anchor).down('img');
	
	var src = img.src;
	
	var largePhoto = $('galleryLargephoto');
	largePhoto.src = src.replace(/\.sm\./, '.lg.');
	
	for (i in images) {
		
		if (images[i].src == largePhoto.src) {
			
			galleryIndex = parseInt(i);
			break;
			
		}
		
	}
	
	showGalleryModal(anchor);
	
	return true;
	
}

