
/****************************************************************************************************************************
 *
 * Onload initialisations
 *  
 * TODO: Should these be split to to the calling pages to speed load?
 *
 ****************************************************************************************************************************/


sella.init = function()
{
		sella.url_query.process();
		sella.rpc.execute_pending();

		
		$s("#show-more-links").one("click",showMoreLinks);

		sella.onclick("#close-feedback",			sella.hideAlert);
		sella.onclick('a.new-window',				new_window);
		sella.onclick(".sella-lightbox",			sella.lightbox);
		sella.onclick(".sella-carousel",			sella.carousel);
		sella.onclick(".watchlist_button_wrapper",	sella.watchlist.toggle);
		sella.onclick(".add-to-fav",				sella.watchlist.toggle);
		sella.onclick("#watching .button-delete",	sella.watchlist.stop_watching);
		sella.onclick("#remember_me",				showWarningIfChecked);
		
		sella.onclick(".img-main-link", function (e){
			e.preventDefault();
			var img = sella.get(e.target);
			if(img){
				var listing_id = img.parentNode.id.substr(14);//trim off ID prefix
				var src = img.src.split('/');//get img id off the end of the href
				var path = src.pop();
				var img_id = path.split('-');

			}
			sella.lightbox(listing_id, img_id[0]);

		});

		sella.onclick(".img-full-size-link", function (e){
			e.preventDefault();
			var a = sella.get(e.target);
			if(a){
				var listing_id = a.id.substr(10);//trim off ID prefix
				var href = a.href.split('/');//get img id off the end of the href
				href.pop();//lose the trailing '/''
				var img_id = href.pop();

			}
			sella.lightbox(listing_id, img_id);

		});
		sella.carousel("div#carousel");

		if ($s.cookie('accountbar') == 'hide') { // if the bar needs to be hidden
			$s("#account-box-toggle").one("click",sella.showAccountBar);
			$s("#account-box-toggle").addClass('open').removeClass('close');
		} else { //set the event handler
			$s("#account-box-toggle").one("click",sella.hideAccountBar);
		}
            
		$s("#browse-bar-toggle").click(function(e) {e.stopPropagation();e.preventDefault();sella.showBrowseBar();return false;});

		sella.address.initialise_address_autocomplete();
	
        sella.datepicker('#close_in_date', 5);
		sella.datepicker('#publish_date', 5);
		sella.datepicker('#auction_tender_close_date',3);
		sella.datepicker('.account #payment_date',3);

		//Hide the standard inputs if the basic uploader is disabled
		if ($s('#show_basic_uploader').val() === '1') {
			sella.show('ol#imagesOl');
			sella.hide('#multi_uploader');
		}

		if(typeof upload_data != 'undefined'){
			if(sella.image.uploader_ready()){
				sella.upload_images("#multi_uploader",upload_data);
			}else{
				sella.hide('#multi_uploader');
				sella.show('ol#imagesOl');//show the basic uploader instead
			}
		}

		if(sella.get('div.mc_register_form')){
			sella.onclick("div.mc_register_form input", sella.highlight_note);
			sella.onblur("div.mc_register_form input", sella.lowlight_note);
			sella.onblur("div.mc_register_form input#user_name", sella.register.check_username);
			sella.onblur("div.mc_register_form input#password", sella.register.check_password);
			sella.onblur("div.mc_register_form input#reenter_password", sella.register.check_password);
			
		}

//		if(sella.get('#basic_register')){
//			$s('#has_javascript').val('true');
//			sella.onclick("#basic_location_selector", sella.register.show_basic_location);
//		}

		sella.form.init_input_hints();
		
		if(sella.get('#edit_reserve_pricing')){
			sella.handle_checked('#reserve_price_off',function(){sella.disable('#reserve_price');});
			sella.handle_checked('#reserve_price_on',function(){sella.enable('#reserve_price');});
		}

		if(sella.get('#set_payment_instructions')){
			sella.handle_checked('#payment-other',function(){sella.checked_toggle('#payment-other','#payment_other_text');},'toggle');
		}
		

		$s('#select-wrapper select.search-category-dropdown').sSelect({ddMaxHeight: '300px'});

		if(sella.get('#login-form')){
			$s('#email').focus();
		}

		if(sella.get('#edit_email_options')){
			sella.handle_checked('#checkbox-watchlist',function(){
				sella.checked_toggle('#checkbox-watchlist','#watch_reminder_1h');
				sella.checked_toggle('#checkbox-watchlist','#watch_reminder_12h');
				sella.checked_toggle('#checkbox-watchlist','#watch_reminder_24h');
				sella.checked_toggle('#checkbox-watchlist','#watch_reminder_48h');
			},'toggle');
		}

		//if(sella.get('div#container.grabaseat')){
		//for airnz store background links
			//sella.onclick("div#container.grabaseat", function(e){

					//if(e.target.id && e.target.id == 'container'){
						//pageTracker._trackEvent('Banners', 'Clicks', 'Air New Zealand');
						//window.location.href='http://www.sella.co.nz/store/4m59l6/grabaseat-air-new-zealand/';
						//window.location.href='http://www.grabone.co.nz/';
					//}

			//});
		//}

		if(sella.get('div#content-main')){
			var trackers = sella.get_all('div#content-main .gallery div.tracker');
			var tracked_ids = new Array();
			for (var i = 0; i < trackers.length; i++) {
				tracked_ids[i] = trackers[i].id.substr(8);
			}
			sella.rpc({webservice:		'sella_stats_listing_search_viewed',
						params:			{listing_id: tracked_ids}});
		}

		sella.track('#tab_dollar_reserve','Dollar Reserve','Homepage Link');
		sella.track('#nav_dollar_reserve','Dollar Reserve','Nav Bar');
		sella.track('#view_dollar_reserve','Dollar Reserve','Filter Bar');
		
		// CHANGED TO ONCLICK TRACKING FOR THESE ADS - Leo
		
		//Car buyers checklist links
		//sella.track('#checklist_finance_now','Finance Now','Car Buyers Checklist');
		//sella.track('#checklist_tower_insurance','Tower Insurance','Car Buyers Checklist');
		//sella.track('#checklist_turners','Turners','Car Buyers Checklist');
		//sella.track('#checklist_cover_now','Cover Now','Car Buyers Checklist');
		
		//Start my listing for free link
		sella.track('#submit-save-listing','Enhancements','Start listing for free');
		
		$s(window).load(sella.load);
		};

sella.ready(sella.init);

/**
 * Called when the entire page (including images) has loaded.
 */
sella.load = function()
{
};

function initbid(){//TODO -replace - called by site-virtual/listing/index.html - expects values written to javascript via tal
	if(place_bid === 'place_bid'){
		if(bid_auto_bid === 'true'){
			bid_auto_bid = true;
		}
		else{
			bid_auto_bid = false;
		}
		sella.bid.validate (bid_listing_id, bid_price, bid_auto_bid);
	}
}

/****************************************************************************************************************************
 *
 * Watchlist
 *
 ****************************************************************************************************************************/
sella.watchlist = {};

	sella.watchlist.toggle = function (o) 
	{
		o.preventDefault();
		var listing_id = o.currentTarget.id.substring(17);
		if(o.target.name == 'add_watchlist') {
			sella.rpc({webservice:   'sella_watchlist_save_listing_for_current_user',
						params:       {listing_id: listing_id},
						pre_ajax:     'sella.watchlist.toggle.button_saving',
						on_success:   'sella.watchlist.toggle.button_watching'});
		}else if(o.target.name == 'watching'){
			window.location = "/my-sella/buy/";
		}
	};
	
	/**
	 * Update the button to say "Saving...."
	 */
	sella.watchlist.toggle.button_saving = function(options)
	{
		var element = $s('#watchlist_button_'+options.params.listing_id);
		
		if(element.hasClass('watchlist_button_wrapper')) {
			element.html('<div class="button-standard large-text"><input type="submit" value="Saving ..." name="saving_watchlist"><span></span></div>');
		} else {
			element.addClass('<input type="submit" name="add_watchlist" title="Start watching" value="Saving ..." />');
		}
	};
	
	/**
	 * Update the button to say "Watching".
	 */
	sella.watchlist.toggle.button_watching = function(response, options) 
	{
		var element = $s('#watchlist_button_'+options.params.listing_id);
		
		if(element.hasClass('watchlist_button_wrapper')) {
			element.html('<div class="button-standard large-text"><input type="submit" value="View Watchlist" name="watching"><span></span></div>');
			//element.html('<div class="button-blue large-text"><input type="button" class="button-watching example" alt="Watching" title="Watching" name="watching" value="Watching"><span></span></div>');
		} else {
			element.replaceWith('<a href="/my-sella/buy" class="go-watchlist watch-saved" title="Watching">Saved</a>');
		}
		
		// Increment the watching count in the account bar
		element = $s('#items-watching-count');
		element.text(1 + parseInt(element.text()));
	};

    sella.watchlist.stop_watching = function (o) {
		$s(this).addClass('button-saving-delete').removeClass('button-delete');
	};
	
	/**
	 * This is called from the http_fragment handler so we can 'add to watchlist' from emails.
	 */
	sella.watchlist.add = function()
	{
		sella.rpc({webservice:   'sella_watchlist_save_listing_for_current_user',
					params:       {listing_id: sella.get_listing_id()},
					on_success:   'sella.watchlist.add_success'});
	};
	
	sella.watchlist.add_success = function()
	{
		sella.feedback('This listing has been added to your watchlist.');
	};

/****************************************************************************************************************************
 *
 * Bidding
 *
 ****************************************************************************************************************************/

sella.bid = {};


	sella.bid.handle_placebid_clicked = function (o)
	{
		var ie6 = getIEVersionNumber(6);
		if(o && !ie6) {
			o.preventDefault();
			
			if (user_quarantined == "1") {
				window.location = '/user/quarantined/';
			}

			var form		= o.target.form;
			var listing_id	= form.listing_id.value;
			var price		= parseFloat(form.price.value.replace(/[^0-9\.]/gi, ''));

			var skip = true;
			if (buy_now_available == '1') {
				buy_now_price = parseFloat(buy_now_price);
				var formname = $s(form).attr('class');

				if (isNaN(price)) {
					price = -1;
				}
				if (isNaN(buy_now_price)) {
					buy_now_price = 0;
				}
				if (price >= buy_now_price) {
					skip = false;
					sella.widget({title:		'Your bid matches the buy-now',
								params:			{widget:		'bid_or_buynow_dialog_'+formname,
												method:			'sella_bid_or_buynow',
												listing_id:		listing_id}});
				}
			}
			if (skip) {
				sella.bid.handle_placebid_override_clicked(form);
			}
		}
	};


	sella.bid.handle_placebid_override_top_clicked = function(o)
	{
		var ie6 = getIEVersionNumber(6);
		if(o && !ie6) {
			o.preventDefault();
			var form = sella.get("form.place_bid_top");
			sella.bid.handle_placebid_override_clicked(form);
		}
	};


	sella.bid.handle_placebid_override_bottom_clicked = function(o)
	{
		var ie6 = getIEVersionNumber(6);
		if(o && !ie6) {
			o.preventDefault();
			var form = sella.get("form.place_bid_bottom");
			sella.bid.handle_placebid_override_clicked(form);
		}
	};


	sella.bid.handle_placebid_override_clicked = function (form)
	{
		var listing_id	= form.listing_id.value;
		var price		= form.price.value.replace(/[^0-9\.]/gi, '');
		var auto_bid	= form.auto_bid.checked;
		sella.widget({title:		'Please confirm your bid',
					params:         {widget:		'bid_dialog',
									method:			'sella_bid_validate',
									listing_id:		listing_id,
									price:			price,
									auto_bid:		auto_bid}});
	};

	
	sella.bid.initialize_buttons = function () 
	{
		sella.onclick(".button-place-bid", sella.bid.handle_placebid_clicked);
		sella.onclick(".button-place-bid-override-top", sella.bid.handle_placebid_override_top_clicked);
		sella.onclick(".button-place-bid-override-bottom", sella.bid.handle_placebid_override_bottom_clicked);
		sella.onclick(".button-buy-now", sella.purchase.handle_purchase_clicked);
		sella.onclick("#link-buy-now", sella.purchase.handle_purchase_clicked);
		sella.onclick("#link-enter-bid", sella.purchase.show_enter_bid_dialog);
		sella.onclick(".button-buy-classified", sella.purchase.handle_purchase_clicked);
	};

	sella.cancel_bid = function(selector){
		if(typeof selector === 'undefined') selector = '#bid_dialog';
		$s(selector).dialog("close");
		return false;
	};

	sella.place_bid = function() {
		$s('#button-place-bid-wrapper').addClass('button-disabled');
		$s('#button-place-bid-dialog').attr('disabled', 'disabled');
		$s("#bid-dialog-form").submit();
		return false;
	};
		
sella.purchase = {};

	sella.purchase.handle_purchase_clicked = function (o) {

		o.preventDefault();

		var is_buy_now = (o.target.name === 'buy_now');

		var listing_id = null;
		var is_account = null;

		if (o.target.id == 'link-buy-now') {
			listing_id = sella.get_listing_id();
			is_account = false;
			is_buy_now = true;
		}
		else if (o.target.form.object_model) {
			listing_id = sella.get_listing_id();
			is_account = false;
		} 
		else if (o.target.form.watching) {
			listing_id = o.target.id;
			is_account = true;
		}

		if (listing_id) {
			
			sella.widget({title:  'Please confirm your purchase',
						  params: {widget:		'buy_now_dialog', 
									method:		'sella_bid_buynow_validate', 
									listing_id: listing_id, 
									is_buy_now: is_buy_now,
									is_account: is_account,
									type:		'buy_now'}});
		}
	};
	
	sella.purchase.show_enter_bid_dialog = function()
	{
		sella.widget({title:  'Please enter your bid',
			  params: {widget:		'enter_bid_dialog', 
						method:		'sella_bid_buynow_validate', 
						listing_id: sella.get_listing_id(),
						random:		Math.round(Math.random() * 100000) + 1000}});
		return false;
	};
	
	sella.place_buy_now = function(selector){
		if(typeof selector === 'undefined') selector = '#buy_now_dialog';
		$s("#buy-now-dialog-form").submit();
		return false;
	};

	sella.cancel_buy_now = function(selector){
		if(typeof selector === 'undefined') selector = '#buy_now_dialog';
		$s(selector).dialog("close");
		return false;
	};


/****************************************************************************************************************************
 * 
 * Registration
 * 
 ****************************************************************************************************************************/
sella.location = {};

	sella.location.update = function(el){
		
		//called when drop down is manually changed

		//split name on '-' eg: 'area-level-1' = area, level, 1
		//0 = namespace eg: area
		//1 = 'level' (always)
		//2 = level count eg 1, 2 or 3
		element_fragments = el.name.split("-");

		if(element_fragments[0] != 'area'){  //weird condition to maintain backwards compatibilty (orginally namespacing was not implemented beyond select elements)
			var namespace = element_fragments[0]+'-';
		} else {
			var namespace = '';
		}

		var select_id = el.id;
		var level = parseInt(element_fragments[2]) + 1;
		var selected_location = el.value;
		var area = $s('#' + element_fragments[0] + '-level-' + level);

		if(area.length > 0){
			if(selected_location !== ''){
				var opts = sella.location.fetch_options(selected_location, level);
				area.html(opts).attr("disabled",false);
				$s('#' + namespace + 'suburb_id').val(selected_location);
				area.focus();
			} else {
				area.attr("disabled","disabled").html('<option>Please select...</option>');
			}

			var nextlevel= level + 1;
			var next_area = $s('#' + element_fragments[0] + '-level-' + nextlevel);
			if(next_area.length > 0){
				next_area.attr("disabled","disabled").html('<option>Please select...</option>');
			}

			if(selected_location == ''){//selected Please select...
				$s('#' + namespace + 'suburb_id').val(selected_location);
				return false;
			}

		} else {
			$s('#' + namespace + 'suburb_id').val(selected_location);
			$s('#' + namespace + 'next_button').attr('disabled',false);//consider this approach for the register button
		}
		return false;

	};

	sella.location.set = function(location, namespace){

		namespace = typeof(namespace) != 'undefined' ? namespace : 'area-';

		if(namespace == 'area-'){
			//sort things out for legacy fors where namespace is not correctly implemented
			var namespace_mod = '';
		} else {
			var namespace_mod = namespace;
		}

		if($s('#' + namespace_mod + 'normal_locator').hasClass('progressive-to-show') == true){
			$s('#' + namespace_mod + 'suburb_id').val(location.suburb_id);
			$s('#' + namespace + 'level-3').html(sella.location.fetch_options(location.city_id, 3, location.suburb_id));
			$s('#' + namespace + 'level-2').html(sella.location.fetch_options(location.region_id, 2, location.city_id));
			$s('#' + namespace + 'level-1').html(sella.location.fetch_options(0, 1, location.region_id));
			$s('#' + namespace + 'level-2, #' + namespace + 'level-3').attr("disabled",false);
			$s('#' + namespace_mod + 'postcode').focus();
		}else{
			$s('#' + namespace_mod + 'suburb_select').val(location.suburb_id);
			$s('#' + namespace_mod + 'postcode').focus();
		}
		return false;
	};

	sella.location.lookup = function(namespace)
	{
		if(namespace == 'area-'){
			namespace_mod = ''
		} else {
			namespace_mod = namespace;
		}

		var suburb_field = sella.get_by_id(namespace_mod + 'suburb');
		var district_field = sella.get_by_id(namespace_mod + 'district');

		if (suburb_field.value && district_field.value) {
			
			sella.rpc({webservice:   'area_lookup',
						params:       [suburb_field.value, district_field.value],
						on_success:   function (response) {if (response.suburb_id) {sella.location.set(response,namespace);}}});
		}
	};


	sella.location.fetch_options = function(root, level, selected){
		//get correct start point in array
		levelobj = sella.eval_json(levels);
		var prev = level-1;
		if(root == 0){
			var options = levelobj[0];
		}else{
			var options = levelobj[prev][root];
		}
		var opts = '<option value="">Please select...</option>';
		for (var i = 0; i < options.length; i++) {
			var sel = '';
			if(typeof selected != 'undefined' && options[i]['id'] == selected){
				sel = 'selected ="selected"';//need to set selected
			}
			opts += '<option value="'+options[i]['id']+'" '+sel+' >'+options[i]['name']+'</option>';
		}
		return opts;
	};

	
	sella.register = {};

	sella.register.check_username = function(e)
	{
		var user_name = e.target.value;

		if(user_name != '') {
			var first_name = $s('div.mc_register_form #first_name').val();
			var last_name = $s('div.mc_register_form #last_name').val();
			$s('#user-name-message').removeClass().addClass('note-active two-line');

			sella.rpc({webservice:   'register_check_username',
						params:       [user_name, first_name, last_name],
						on_success:   sella.register.show_suggestions});
		}
	};

	sella.register.show_suggestions = function(response, options) 
	{
		if(response.condition == "suggested") {
			var html = response.message;
			html += ' Suggested usernames:<br />';
			for(var i =0;i < response.suggested.length; i++) {
				html += '<strong>&nbsp;&nbsp;'+response.suggested[i]+'<br /></strong>';
			}
			$s('#user-name-message').addClass(response.condition).html(html);
		} else {
			$s('#user-name-message').addClass(response.condition).html(response.message);
		}
	};

	sella.register.check_password = function(e){
		if(e.target.value !=''){
			var pw1 = '';
			var pw2 = '';
			var mg1 = 'Passwords must be at least 6 characters long.';
			var mg2 = '';

			var password1 = $s('div.mc_register_form #password').val();
			var password2 = $s('div.mc_register_form #reenter_password').val();
			if(password1.length < 6){
				pw1 = 'invalid';
			}else{
				pw1 = 'valid';
				mg1 = 'Valid Password.';
			}
			if(e.target.id == 'reenter_password'){
				if(pw1 == 'valid' && password1 !== password2){
					pw2 = 'invalid';
					mg2 = 'Invalid - does not match previous entry.';
				}else if(pw1 == 'valid' && password1 === password2){
					pw2 = 'valid';
					mg2 = 'Valid match to Password ';
				}else{
					pw2 = 'invalid';
					mg2 = 'Invalid  - does not match previous entry.';
				}
			}
			$s('#password-message').removeClass('valid invalid').addClass(pw1).html(mg1);
			$s('#reenter-password-message').removeClass('valid invalid').addClass(pw2).html(mg2);
		}
	};

	sella.register.show_basic_location = function(e){
		$s('#normal_locator').removeClass('progressive-to-show').addClass('progressive-to-hide');
		$s('#basic_locator').removeClass('progressive-to-hide').addClass('progressive-to-show');
		$s('#basic_register').val(true);

		return false;
	};

	/* Address autocompletion*/
	sella.address = {};

	sella.address.initialise_address_autocomplete = function(namespace)
	{
		namespace = typeof(namespace) != 'undefined' ? namespace : 'area-';
		if(namespace == 'area-'){
			//sort things out for legacy fors where namespace is not correctly implemented
			var namespace_mod = '';
		} else {
			var namespace_mod = namespace;
		}

		if($s('#' + namespace_mod + 'autocomplete_address input#' + namespace_mod + 'address_1').length > 0) {
			var ac = sella.autocomplete('#' + namespace_mod + 'address_1', "/services/address_proxy.php", sella.address.parse_json);
			ac.result(sella.address.populate_address_fields);

			sella.onchange('#' + namespace_mod + 'suburb', function(e) {
				sella.location.lookup(namespace);
			});
		}
		
		if($s('#listing-form input#area_id').length > 0){
			sella.listing_areas();  // what does this do?
		}
	};
	
	sella.address.populate_address_fields = function(event, data, formatted) 
	{
		var element_fragments = event.target.id.split("-");
		if(element_fragments.length != 1){  //weird condition to maintain backwards compatibilty (orginally namespacing was not implemented beyond select elements)
			var namespace = element_fragments[0]+'-';
		} else {
			var namespace = '';
		}

		$s('#' + namespace + 'address_1').val(data.number+' '+data.name);
		$s('#' + namespace + 'suburb').val(data.suburb);
		$s('#' + namespace + 'district').val(data.district);
		var url = '/services/rpc/address_find_postcode?'+escape(data.number) + '&' + escape(data.name) + '&' + escape(data.suburb);
		
		//sella.ajax.get(url, postcodesSelected);

		sella.rpc({rpc_url: 	url,
					namespace:	namespace,
					on_success:	postcodesSelected});

		sella.trigger('#' + namespace + 'suburb','change');
	};
	
	/**
	 * Custom JSON parser to parse to the output from web_address_find_postcode
	 * 
	 * e.g {"results":[ {'id':1234, "nice":"foo","number":"bar","name":"baz","suburb":"foo","district":"bar","region":"baz","x":47659,"y":6423745} ]}
	 */
	sella.address.parse_json = function(raw)
	{
		var parsed = [];
		var data = raw.results;
		for (var i = 0; i < data.length; i++) {
			parsed[parsed.length] = {
				data: data[i],
				value: data[i].nice,
				result: data[i].nice
			};
		}
		return parsed;
	};

/****************************************************************************************************************************
 * 
 * URL Query Processing
 * 
 ****************************************************************************************************************************/
sella.url_query = {};

/**
 * Process any query parameters 
 */
sella.url_query.process = function()
{
	if(document.location.search == '?watch') {
		sella.watchlist.add();
	}
	else if(document.location.search == '?bid') {
		//sella.purchase.show_enter_bid_dialog();

		var e = jQuery.Event("click");
		e.target = $s('#button-place-bid')[0];
		sella.bid.handle_placebid_clicked(e);
	}
	else if(document.location.search == '?buynow') {
		// Emulate a click on the "Buy Now" button.
		var e = jQuery.Event("click");
		e.target = $s('#button-buy-now')[0];
		sella.purchase.handle_purchase_clicked(e);
	}
};

/****************************************************************************************************************************
 * 
 * Generic form helpers
 * 
 ****************************************************************************************************************************/
sella.form = {};

/**
 * Set the example text of all text inputs from their title attribute if a class of example is set.
 */
sella.form.init_input_hints = function() 
{
	$s('input.example, textarea.example').each(function(){
        $s(this).example(this.title);
    });
};
	
/****************************************************************************************************************************/

//categories.js

/****************************************************************************************************************************/
/* this is actually only used by areas in the listing process - it needs to die */

sella.category = function (options) {

	var that = this;
	this.options = options;
	var custom_event = options.class_prefix+'Selected';

	//create a custom event using the name options.class_prefix+'Selected' So = CategorySelected
	//var change_event = new Y.util.CustomEvent(options.class_prefix+'Selected', options);


	if (options.change_handler) {
		//if there is a change handler set in options subscribe it (bind it)
		//change_event.subscribe(options.change_handler);
		$s(options.field).bind(custom_event,function(){options.change_handler();});
	}
	//fire the custom event once
	//change_event.fire ();
	$s(options.field).trigger(custom_event);

	//create set_field which also fires the custom event
	var set_field = function (value) {
		options.field.value = value;
		//change_event.fire ();
		$s(options.field).trigger(custom_event);

	};

	var build_level = function (parent_id, categories, level, child_id) {

		var invalidate = function (level) {

			var obsolete_children = sella.get_all('select.'+options.class_prefix+'-level-'+level);

			for (var i = 0; i < obsolete_children.length; i++) {
				var child = obsolete_children[i];
				child.parentNode.removeChild(child);
			}

		};

		var build_select = function (categories, level, child_id) {

			var handle_changed = function (event,level) {
				// Determine the chosen parent category id, and subcategory level
				var child_level = level + 1;
				var parent_id = event.target.options[event.target.selectedIndex].value;

				// Delete all select elements for subcategories, as they are no longer applicable to the new parent category
				invalidate (child_level);

				set_field ('');//fire the event

				// AJAX request the new select
				that.request_level (parent_id, child_level);

			};

			var select = document.createElement('select');
			select.setAttribute('size', options.size);
			select.setAttribute('id', options.class_prefix+'-level-'+level);

			// Add classes for this and all parent levels, to make it easy to delete
			for (var i = 1; i <= level; i++) {
				sella.add_class(select, options.class_prefix+'-level-'+i);
			}

			// Add listener for category change
			sella.onchange(select, function (e){handle_changed(e,level);});//TODO - right syntax - seems so?

			var start = 0;

			if (options.size === 1) {

				var option = document.createElement('option');
				option.setAttribute('value', '');
				option.appendChild(document.createTextNode('Please Select'));
				select.appendChild(option);

				if (!child_id) {
					select.selectedIndex = 0;
				}

				start = 1;

			}

			// Add subcategories
			for (var j = 0; j < categories.length; j++) {

				var category = categories[j];

				var option = document.createElement('option');
				option.setAttribute('value', category.id);
				option.appendChild(document.createTextNode(category.has_children ? category.name+'  >>' : category.name));
				select.appendChild(option);

				if (child_id === category.id) {
					select.selectedIndex = start + j;
				}

			}

			return select;

		};

		
		if (categories.length === 0) {// No more subcategories means final category chosen
			set_field (parent_id);//fire the event
		} else {// We still need to choose a subcategory
			var select = build_select (categories, level, child_id);
			invalidate (level);
			options.container.appendChild(select);
		}
	};

	this.request_level = function (parent_id, level) {

		if (!parent_id) {
			return;
		}

		var level_response = function (response) {

			// Attempt to parse the response as JSON
			try {
				var categories = sella.eval_json(response.responseText);
			} catch (exception) {
				alert ("Internal server error");
				return false;
			}

			build_level (response.argument.parent_id, categories, response.argument.level, false);
		};

		var transaction = sella.ajax.get(this.options.rpc_url (parent_id), level_response, {level: level, parent_id: parent_id});
	};

	this.request_chain = function (parent_id, child_id) {

		var chain_response = function (response) {
			try {
				var levels = sella.eval_json(response.responseText);
			} catch (exception) {
				alert ("Internal server error");
				return false;
			}

			for (var i = 0; i < levels.length; i++) {
				var child_id = levels[i+1] ? levels[i+1].id : null;
				build_level (levels[i].id, levels[i].children, i+1, child_id);
			}

		};

		var transaction = sella.ajax.get(this.options.chain_rpc_url (parent_id, child_id), chain_response, {parent_id: parent_id, child_id: child_id});
		set_field (child_id);//fire the event
	};
};



/****************************************************************************************************************************/

//listing-helpers.js

/****************************************************************************************************************************/

sella.listing = {};

	sella.listing.update_categories = function(el){

		var select_id = el.id;
		var selected_category = el.value;
		var original_li = $s(el).parent().parent().attr('id');
		var next_siblings = $s('#'+original_li).nextAll();

		if(next_siblings[0]){
			var parent_li = next_siblings[0].id;
			var select = $s('#'+parent_li+' select');
			select.html('Loading...');
			
			sella.rpc({webservice:	'sella_category_options',
						params:		[selected_category],
						on_success:	function (cats, options) {
										var children = cats.children;
										var finish = cats.finish;
										var next = cats.next;
										$s('fieldset.mc-listing-categories label').removeClass('selected-category').addClass('greyed-category');
						
										if(finish == false){
											var opts = '';
											for (var i = 0; i < children.length; i++) {
												opts += '<option value="'+children[i]['id']+'">'+children[i]['name']+'</option>';
											}
											select.html(opts);
											select.attr('disabled',false);
											//$s('#next_button').attr('disabled',true) ;
											sella.disable_button('#next_button');
											var start = 1;
											
											$s('#'+parent_li+' label').removeClass('greyed-category').addClass('selected-category');
						
										}
										else if(finish != false) {
											//$s('#next_button').attr('disabled',false);
											sella.enable_button('#next_button');
											var start = 0;
											$s('#'+original_li+' label').removeClass('greyed-category').addClass('selected-category');
										}
						
										for (var i = start; i < next_siblings.length; i++) {
											var next_li = next_siblings[i].id;
											var next_select = $s('#'+next_li+' select');
											var single = '<option value="'+next['id']+'">'+next['name']+'</option>';
											next_select.html(single);
											next_select.attr('disabled',true);
										}
										
										$s('#category_id').val(selected_category);
										$s('#'+select_id).focus();
									}});
		} else {
			$s('#category_id').val(selected_category);
			//$s('#next_button').attr('disabled',false);
			sella.enable_button('#next_button');

		}
		return false;

	};
	
	sella.listing.initialise_details = function (){
		$s('#edit-listing-form ol li div.sidenote').each( function(e){
			var id = this.id;
			var field = id.substring(0, id.length - 9);
			sella.tooltip('#a_'+field,'#p_'+field);
			}
		);

		$s('#autosend_standard_instructions_container a').tooltip({
				tip: '#payment_instructions_text',
				// place tooltip on the right edge
				position: ['top', 'center'],
				// a little tweaking of the position
				offset: [-10, 15],
				// use a simple show/hide effect
				effect: 'toggle',

				relative: true,
				// custom opacity setting
				opacity: 0.9
		   });

		if($s('#registration').val() == '') sella.disable('#display_registration');
		sella.onclick('#registration', function(){sella.enable('#display_registration');});


		if(typeof(template_macros) !='undefined' && template_macros['about']) sella.listing.init_about();
		//if(template_macros['flatmate']) sella.listing.init_flatmate();
		if(typeof(template_macros) !='undefined' && template_macros['price']) sella.listing.init_price();
		if(typeof(template_macros) !='undefined' && template_macros['property_price']) sella.listing.init_property_price();
		//if(template_macros['rental_price']) sella.listing.init_rental_price();
		if(typeof(template_macros) !='undefined' && template_macros['payment']) sella.listing.init_payment();
		if(typeof(template_macros) !='undefined'&& template_macros['contact']) sella.listing.init_contact();
		//initialise any sidenotes
		
	};

	sella.listing.init_about = function (){

		sella.handle_checked('#subtitle',function(){sella.disable('#subcaption');});
		sella.handle_checked('#subtitle1',function(){sella.enable('#subcaption');});
        sella.listing.init_open_home_times();
    };

    sella.listing.init_open_home_times = function (){
        var hidden = [false, false, false, false];

        // Hide time ranges that have no date selected by default

        // But always show the first one.
        for (var i = 1; i < 4; i++) {
            var index_id = i + 1;
            if ($s('#how_to_view-date-'+index_id).val() == 0) {
                sella.hide('#how_to_view'+index_id);
                hidden[i] = true;
            } else {
                sella.show('#how_to_view'+index_id);
                hidden[i] = false;
            }
        }

        count_time_ranges = function() {
            var count = 0;
            for (var i = 0; i < 4; i++) {
                if (!hidden[i])
                    count++;
            }
            return count;
        };

        // Disable remove button by default if there is only one range.

        if (count_time_ranges() == 1)
            $s('#remove1').attr('disabled', true).removeClass('time_range_remove').addClass('time_range_remove_disabled');

        // Handle addition of new open home time

        sella.onclick('#a_add_time', function(){
            // Find next hidden time slot and reveal it.

            for (var i = 0; i < 4; i++) {
                if (hidden[i]) {
                    var id_index = i + 1;
                    hidden[i] = false;
                    
                    // Reveal time slot.

                    sella.show('#how_to_view'+id_index);

                    // If this is the last slot then disable the add button

                    if (i == 3)
                        sella.disable('#a_add_time');

                    // Ensure remove buttons are enabled

                    for (r = 1; r <= 4; r++)
                        $s('#remove'+r).attr('disabled', false).removeClass('time_range_remove_disabled').addClass('time_range_remove');

                    break;
                }
            }
        });

        remove_time_range = function(index) {
            //  Reset selection boxes

            var index_id = index + 1;
            $s("#how_to_view-date-"+index_id+" option[selected]").removeAttr('selected');
            sella.set_attr("#how_to_view-date-"+index_id+" option[value='0']", 'selected', 'selected');
            $s("#how_to_view-from-"+index_id+" option[selected]").removeAttr('selected');
            sella.set_attr("#how_to_view-from-"+index_id+" option[value='']", 'selected', 'selected');
            $s("#how_to_view-to-"+index_id+" option[selected]").removeAttr('selected');
            sella.set_attr("#how_to_view-to-"+index_id+" option[value='']", 'selected', 'selected');

            // UI control changes

            sella.hide('#how_to_view'+index_id);
            hidden[index] = true;
            sella.enable('#a_add_time');

            // Move to end of list

            $s('#how_to_view'+index_id).appendTo($s('#how_to_view_times'));

            // Disable remove button if there is only one range left.

            if (count_time_ranges() == 1) {
                last_remove_button = jQuery.inArray(false, hidden) + 1;
                if (last_remove_button != 0)
                    $s('#remove'+last_remove_button).attr('disabled', true).removeClass('time_range_remove').addClass('time_range_remove_disabled');
            }
        };

        // Handle removal of open home time

        sella.onclick('#remove1', function(){if(count_time_ranges() > 1) remove_time_range(0);});
        sella.onclick('#remove2', function(){if(count_time_ranges() > 1) remove_time_range(1);});
        sella.onclick('#remove3', function(){if(count_time_ranges() > 1) remove_time_range(2);});
        sella.onclick('#remove4', function(){if(count_time_ranges() > 1) remove_time_range(3);});
	};

	sella.listing.init_price = function ()
	{
		sella.handle_checked('#auction-has_reserve',function(){sella.disable('#auction-reserve_price');});
		sella.handle_checked('#auction-has_reserve1',function(){sella.enable('#auction-reserve_price');});

		sella.handle_checked('#multiple_relist',function () {sella.checked_toggle('#multiple_relist', '#multiple_quantity');},'toggle');

		multiple_quantity_value = $s('#multiple_quantity').val();
		$s('#multiple_quantity').change(function () {
			multiple_quantity_value = $s(this).val();
		});

		$s('#multiple_relist').click(function() {
			if (!$s(this).attr('checked')) {
				$s('#multiple_quantity').val(0);
			} else {
				$s('#multiple_quantity').val(multiple_quantity_value);
			}
		});

		sella.handle_checked('#close_in_0',function(){
			sella.enable('#close_in_duration_container select');
			sella.disable('#close_in_date_container select');
		});

		sella.handle_checked('#close_in_1',function(){
			sella.disable('#close_in_duration_container select');
			sella.enable('#close_in_date_container select');
		});

		sella.handle_checked('#publish_option_I',function(){
			sella.disable('#publish_date_days');
			sella.disable('#publish_date_hours');
		});

		sella.handle_checked('#publish_option_S',function(){
			sella.enable('#publish_date_days');
			sella.enable('#publish_date_hours');
		});
	};

	sella.listing.init_property_price = function (){
		sella.handle_checked('#price_option_asking_price',function(){
			sella.enable('#asking_price');
			sella.disable('#enquiries, #auction_container select, #tender_container select');
		});
		sella.handle_checked('#price_option_enquiries',function(){
			sella.enable('#enquiries');
			sella.disable('#asking_price, #auction_container select, #tender_container select');
		});
		sella.handle_checked('#price_option_auction',function(){
			sella.enable('#auction_container select');
			sella.disable('#asking_price, #enquiries, #tender_container select');
		});
		sella.handle_checked('#price_option_tender',function(){
			sella.enable('#tender_container select');
			sella.disable('#asking_price, #enquiries, #auction_container select');
		});
		sella.handle_checked('#price_option_negotiation',function(){
			sella.disable('#asking_price, #enquiries, #auction_container select, #tender_container select, #lease_container select, #lease_container input');
		});
		sella.handle_checked('#price_option_lease',function(){
			sella.enable('#lease_container select, #lease_container input');
		});
		//for business for sale whihc is also auction
		sella.handle_checked('#auction-has_reserve',function(){sella.disable('#auction-reserve_price');});
		sella.handle_checked('#auction-has_reserve1',function(){sella.enable('#auction-reserve_price');});

	};


	sella.listing.init_payment = function (){

		sella.handle_checked('#shipping, #shipping1',function(){sella.disable('#shipping_custom_container input');});
		sella.handle_checked('#shipping2',function(){sella.enable('#shipping_custom_container input');});
		sella.handle_checked('#payment-other',function(){sella.checked_toggle('#payment-other','#payment_other');},'toggle');


		sella.handle_change('#pickup',function(){
			if($s('#pickup').val() == 'must'){
				sella.disable('#shipping_container input');
				sella.disable('#shipping_custom_container input');
			}else{
				sella.enable('#shipping_container input');
				if($s('#shipping2').attr('checked') == true){
					sella.enable('#shipping_custom_container input');
				}else{
					sella.disable('#shipping_custom_container input');
				}
			}

		});


		sella.onchange('#shipping_custom_container', function(){sella.add_custom_shipping_fields('#shipping_custom_container');});
		sella.onclick('#shipping_custom_container', function(){sella.add_custom_shipping_fields('#shipping_custom_container');});
		sella.onkeyup('#shipping_custom_container', function(){sella.add_custom_shipping_fields('#shipping_custom_container');});

	};

	sella.listing.init_contact = function (){

		if($s('#contact_choice').length >0) {
			sella.handle_checked('#contact_choice',function(){ 
				sella.disable('#agent_details input, #agent_details select');
				sella.enable('#seller_details input, #seller_details select');
				sella.handle_checked('#agent_seller',function(){sella.disable('#agent_seller_name_row input');});
				sella.handle_checked('#agent_seller1',function(){sella.enable('#agent_seller_name_row input');});
				sella.handle_checked('#display_contact_phone',function(){sella.checked_toggle('#display_contact_phone','#contact_phone_prefix, #contact_phone_local');},'toggle');
				sella.handle_checked('#display_contact_mobile',function(){sella.checked_toggle('#display_contact_mobile','#contact_mobile_prefix, #contact_mobile_local');},'toggle');
			});
			sella.handle_checked('#contact_choice1',function(){
				sella.enable('#agent_details input, #agent_details select');
				sella.disable('#seller_details input, #seller_details select');
			});
		}else{
			sella.handle_checked('#display_contact_phone',function(){sella.checked_toggle('#display_contact_phone','#contact_phone_prefix, #contact_phone_local');},'toggle');
			sella.handle_checked('#display_contact_mobile',function(){sella.checked_toggle('#display_contact_mobile','#contact_mobile_prefix, #contact_mobile_local');},'toggle');
		}
	};

	sella.listing.initialise_publish = function (){

		sella.handle_checked('#publish_option_I',function(){sella.disable('#publish_date_days_container select');});
		sella.handle_checked('#publish_option_S',function(){sella.enable('#publish_date_days_container select');});

	};

/******************************************************************
 * Begin listing form date and time prevalidation/option munging
 ******************************************************************/
sella.listing.lpad = function (string, length, character) {
	string += '';
	while (string.length < length) {
		string = character + string;
	}
	return string;
};

sella.listing.iso_8601_to_date = function (string) {
	var parts = string.match(/([0-9]{4}).([0-9]{2}).([0-9]{2})/);
	if (parts == null) {
		return false;
	}

	var date = new Date();
	date.setFullYear(
		parseInt(parts[1], 10),
		parseInt(parts[2], 10) - 1,
		parseInt(parts[3], 10)
	);
	return date;
}

sella.listing.date_to_iso_8601 = function (date) {
	var string = date.getFullYear() + "-";
	string += sella.listing.lpad(date.getMonth() + 1, 2, '0') + '-';
	string += sella.listing.lpad(date.getDate(), 2, '0');
	return string;
};

sella.listing.get_date_options = function (start_date, number) {
	var date = sella.listing.iso_8601_to_date(start_date);
	var shortdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
	var shortmonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
	var options = [];

	for (var i = 0; i < number; i++) {
		var option = document.createElement('option');
		option.setAttribute('value', sella.listing.date_to_iso_8601(date));
		option.appendChild(document.createTextNode(shortdays[date.getDay()] + ' '
													+ date.getDate() + ' '
													+ shortmonths[date.getMonth()]));
		options.push(option);

		date.setDate(date.getDate() + 1);
	}

	return options;
};

sella.listing.get_time_options = function (date) {
	var options = [];

	for (var hour = 0; hour < 24; hour++) {
		if (date && (date.getHours() > hour)) {
			continue;
		}

		$.each([0, 15, 30, 45], function () {
			if (date && date.getHours() == hour && date.getMinutes() > this) {
				return;
			}

			var h = ((hour == 0) ? 12 : ((hour > 12) ? hour - 12 : hour));
			var a = (hour >= 12 ? 'pm' : 'am');

			var option = document.createElement('option');
			option.setAttribute('value', sella.listing.lpad(hour, 2, '0') + ':'
										+ sella.listing.lpad(this, 2, '0') + ':00');
			option.appendChild(document.createTextNode(h + ':' + sella.listing.lpad(this, 2, '0') + ' ' + a));
			options.push(option);
		})
	}
	
	return options;
}

sella.listing.select_fields_to_date = function (day_select, time_select) {
	var date = sella.listing.iso_8601_to_date($(day_select).val());

	if (time_select) {
		parts = time_select.val().match(/([0-9]{2}).([0-9]{2}).([0-9]{2})/);
		if (parts == null) {
			return date;
		}
		date.setHours(
			parseInt(parts[1], 10),
			parseInt(parts[2], 10),
			parseInt(parts[3], 10)
		);
	}

	return date;
};

sella.listing.update_close_in_date = function () {
	var date;
	if ($('#publish_option_I').attr('checked')) {
		date = sella.listing.date_to_iso_8601(new Date());
	} else {
		date = $('#publish_date_days').val();
	}

	var options = sella.listing.get_date_options(date, 14);
	if (options) {
		var original = $('#close_in_date').val();
		$('#close_in_date').empty().append(options);
		$('#close_in_date').val(original);
		$('#close_in_date').change();
	}
};

sella.listing.update_close_in_time = function () {
	var close_date = $('#close_in_date');
	var publish_date = $('#publish_date_days');

	var options;
	if ($('#publish_option_I').attr('checked') && close_date.val() == sella.listing.date_to_iso_8601(new Date())) {
		var date = new Date();
		date.setHours(date.getHours() + 1);
		options = sella.listing.get_time_options(date);
	} else if ($('#publish_option_S').attr('checked') && publish_date.val() == close_date.val()) {
		var date = sella.listing.select_fields_to_date($('#publish_date_days'), $('#publish_date_hours'));
		date.setHours(date.getHours() + 1);
		options = sella.listing.get_time_options(date);
	} else {
		options = sella.listing.get_time_options();
	}

	if (options && options.length != $('#close_in_time').children().size()) {
		var original = $('#close_in_time').val();
		$('#close_in_time').empty().append(options);
		$('#close_in_time').val(original);
		$('#close_in_time').change();
	}
}

sella.listing.update_publish_time = function () {
	var options;
	if ($('#publish_date_days').val() == sella.listing.date_to_iso_8601(new Date())) {
		options = sella.listing.get_time_options(new Date());
	} else {
		options = sella.listing.get_time_options();
	}

	if (options && options.length != $('#publish_date_hours').children().size()) {
		var original = $('#publish_date_hours').val();
		$('#publish_date_hours').empty().append(options);
		$('#publish_date_hours').val(original);
		$('#publish_date_hours').change();
	}
}

jQuery(function ($) {
	if ($('#publish_date_days') && $('#close_in_date')) {
		$('#publish_date_days').change(function () {
			sella.listing.update_close_in_date();
			sella.listing.update_publish_time();
		});
		$('#publish_date_hours').change(function () {
			sella.listing.update_close_in_time();
		});
		$('#close_in_date').change(function () {
			sella.listing.update_close_in_time();
		});
		$('#publish_option_I').click(function () {
			sella.listing.update_close_in_date();
		});
		$('#publish_option_S').click(function () {
			sella.listing.update_close_in_date();
		});

		// Trigger initially
		$('#publish_date_days').change();
	}
});

/****************************************************************************************************************************/

//stats.js

/****************************************************************************************************************************/

sella.stats = {};

	sella.stats.initialize = function () {
		if(document.getElementById('stats-table')){
			var stats = document.getElementById('stats-table');

			var bodies = stats.getElementsByTagName('tbody');

			for (var i = 0; i < bodies.length; i++) {

				var ths = bodies[i].getElementsByTagName('th');

				for (var j = 0; j < ths.length; j++) {

					var th = ths[j];

					var a = document.createElement ('a');
					a.setAttribute('href', '#chart');

					while (th.hasChildNodes()) {
						a.appendChild(th.firstChild);
					}

					a.onclick = function () {
						sella.stats.buildChart (this.parentNode.parentNode.id);
					};

					th.appendChild(a);
				}

			}
		}
	};

	sella.stats.buildChart = function (id) {

		var stats = document.getElementById('stats-table');

		var months = stats.getElementsByClassName('months')[0].getElementsByTagName('th');

		var month_names = [];

		// skip first column
		for (var i = 1; i < months.length; i++) {
			month_names.push (months[i].innerHTML);
		}

		var tr = document.getElementById(id);

		var title = tr.getAttribute('title') + ' (Last 12 Months)';

		var tds = tr.getElementsByTagName('td');

		var max_value = 0;
		var month_values = [];

		for (i = 0; i < tds.length; i++) {

			var values = tds[i].getElementsByClassName('value');
			if (values.length == 1) {
				var value = parseFloat(values[0].innerHTML);

				if (value > max_value) {
					max_value = value;
				}

				month_values.push(value);
			} else {
				month_values.push(-1);
			}

		}

		var chart = document.getElementById('chart');
		while (chart.hasChildNodes()) {
			chart.removeChild(chart.firstChild);
		}

		var img = document.createElement('img');

		img.setAttribute('src',
			'http://chart.apis.google.com/chart?'
			+'cht=bvs'
			+'&chs=400x200'
			+'&chd=t:'+month_values.join(',')
			+'&chds=0,'+max_value
			+'&chxt=x,y'
			+'&chxr=1,0,'+max_value
			+'&chxl=0:|'+month_names.join('|')+'|'
			+'&chtt='+title
		);

		chart.appendChild(img);

	};




/****************************************************************************************************************************/

//listing_areas.js

/****************************************************************************************************************************/

sella.listing_areas = function () {
	var field = document.getElementById('area_id');
	if (field) {
		var container = document.createElement('div');
		field.parentNode.insertBefore(container, field);

		var areas = new sella.category({
				container: container,
				rpc_url: function (parent_id) {
					return sella.rpc_url ('area_get_children', parent_id);
						},
				chain_rpc_url: function (parent_id, child_id) {
					return sella.rpc_url ('area_get_chain_with_children', parent_id, child_id);
						},
				field: field,
				class_prefix: 'area',
				size: 1
		});

		var parent_id = 0;
		var child_id = listing.area_id;

		if (child_id && child_id !== parent_id) {
			areas.request_chain (parent_id, child_id);
		} else {
			areas.request_level (parent_id, 1);
		}
	}
};


/****************************************************************************************************************************/

//search.js

/****************************************************************************************************************************/

sella.product_search = function() {
	sella.onsubmit('search', function(e) {
		var elem = sella.get_by_id('product-search');
		var value = sella.trim(elem.value);
		if (value.length > 0 && value.length < 4) {
			e.preventDefault();
			//showAlert(e, elem);
		}
	});
	var search_fields = sella.get_all("input.search_keywords");
	for (var i in search_fields) {
		sella.onsubmit(search_fields[i].form, function(e) {
			var elem = sella.get_all(this+' > input.search_keywords');//TODO this is probably  wrong
			//showAlert(e, elem[0]);
		});
	}
};

/****************************************************************************************************************************/

//upload_images.js

/****************************************************************************************************************************/
sella.image = {};
	sella.image.uploader_ready = function(){
		if(sella.helpers.hasFlashVersion('9', '0', '0')) {
			$s.include('/javascript/jquery/jquery.uploadify.js', true);
			return true;
		} else {
			return false;
		}
	};
	sella.image.increment = function(){
		var numeric = parseInt($s('#img-count').html());
		numeric++;
		$s('#img-count').html(numeric);
	};

	sella.image.decrement = function(){
		var numeric = parseInt($s('#img-count').html());
		numeric--;
		$s('#img-count').html(numeric);
	};

	sella.image.feedback = function(response){
		$s("#upload_feedback").html(response);
	};

	sella.image.clear = function(selector){
		$s(selector).fadeOut(250, function() {$s(selector).remove();});
	};

	sella.image.clear_feedback = function(){
		$s("#upload_feedback").empty();
	};
	
	sella.image.disable_publish_button = function()
	{
		if($s('#submit-save-listing').parent().hasClass('button-disabled')) {
			return;
		}
		//sella.image.publish_button_css = $s('#submit-save-listing').attr('class');
		$s('#submit-save-listing').parent().addClass('button-disabled');
		$s('#submit-save-listing').attr('disabled', true);
	};
	
	sella.image.enable_publish_button = function()
	{
		$s('#submit-save-listing').parent().removeClass('button-disabled');
		$s('#submit-save-listing').attr('disabled', false);
	};
	
	sella.image.oncomplete = function(event, queueID, fileObj, response, queuedata, data, selector)
	{
		var responsearr = response.split(':');
		if(responsearr.length > 1 && responsearr[0] == 'done') {
			sella.image.load_thumbnail(selector+queueID,fileObj.name, data.id, responsearr[1]);
			sella.image.increment();
			if(parseInt(queuedata.fileCount) < 2) {
				sella.image.enable_publish_button();
			}
			return false;
		} else {
			sella.image.feedback(response);
			sella.image.enable_publish_button();
		}
	};
	
	sella.image.onselect = function()
	{ 
		sella.image.disable_publish_button();
		sella.image.clear_feedback();
	};
	
	sella.image.onerror = function(event, queueID, fileObj, errorObj)
	{
		var html = '<a class="del" onclick="sella.image.clear(\''+selector+queueID+'\')" href="javascript:void(0)">Delete</a>';
		$s('#cancel'+queueID).parent().html(html);
		sella.image.enable_publish_button();
	};
	
	sella.image.load_thumbnail = function(selector,name, listing_id, image_id){
		if(!$s(selector).length) return false;
		sella.ajax.get(sella.rpc_url ('sella_image_thumbnail_details', listing_id, image_id),
			function (o){
				var details = sella.eval_json(o.responseText);
				var checked = '';
				if(details.main =='1') var checked = 'checked="checked"';

				var html = '<a class="del" onclick="return sella.image.remove(this,\''+listing_id+'\',\''+image_id+'\')" href="javascript:void(0)">Delete</a>';
				html += '<input type="radio" class="radio-btn" name="main_image" id="radio-'+image_id+'" value="'+image_id+'" '+checked+' onclick="sella.image.promote(\''+listing_id+'\',\''+image_id+'\')"/>';
				html += '<img src="'+details.path+'" alt=""/>';
				html += '<div class="message">'+name+'</div>';
				html += '<input type="text" name="caption_'+image_id+'" class="caption example" title="Add image caption..." />';
				
				//need to know if this uploaded image is main and set as checked - defaults if only one, otherwise needs to be settable by remove and promote below
				$s(selector).html(html);
				$s(selector).removeClass('fileUploadQueueItem');
				$s(selector).addClass('uploadedImage');
				$s('.uploaded-image-box-title').removeClass('hide');//need to ensure title row is visible
				sella.form.init_input_hints();
			}
		);
	};

	sella.image.remove = function(obj, listingId, imageId)
	{
		sella.ajax.get(sella.rpc_url ('sella_listing_image_delete', listingId, imageId),
			function(o){
				var imageNode = obj.parentNode;
				if (imageNode) {
					imageNode.parentNode.removeChild(imageNode);
					sella.image.decrement();
				}
			}
		);
		return false;
	};

	sella.image.promote = function(listingId, imageId)
	{
		sella.ajax.get(sella.rpc_url ('sella_image_set_main_image', listingId, imageId),
			function(o){
				var radioNode = sella.get_by_id('radio-'+imageId);
				if (radioNode) {
					//var clone = $s('#radio-'+imageId).parent().clone();
					$s('.uploaded-image-box-title').after($s('#radio-'+imageId).parent());
					radioNode.checked = true;
				}
			}
		);
	};

/**
 * Display a Google map and optionally Google Streetview in the given DOM elements.
 *
 * @example sella.map.display({selector: '#map', address: '46 Riccarton Road Christchurch City, Canterbury NZ'});
 * @options
 *   selector:          CSS selector of the map enclosing DIV
 *   address:           The street address to centre the map on.
 *   disableStreetview: Set to true if you don't want to use the streetview
 *   width:				Width of map in pixels
 *   height:			Height of map in pixels
 */
sella.display_map = function(options)
{
	var enclosingDiv = $s(options.selector);
	var geocoder	 = new GClientGeocoder();
	var map;		

	if (options.width && options.height) {
		map = new GMap2($s('.mapview', enclosingDiv).get(0), {size: new GSize(options.width, options.height)});
	} else {
		map	= new GMap2($s('.mapview', enclosingDiv).get(0));
	}		


	map.disableScrollWheelZoom();
	map.addControl(new GLargeMapControl3D());
	map.addControl(new GMapTypeControl());

	var address = options.address + ', New Zealand'; // make sure it finds NZ

	geocoder.getLatLng(
			  address
			, function(point) {

				if (point) {
					map.setCenter(point, 15);
					var marker = new GMarker(point);
					map.addOverlay(marker);
					enclosingDiv.show();

					var panoClient = new GStreetviewClient();

					if(!options.disableStreetview) {
						$s('.streetview', enclosingDiv).hide();

						panoClient.getNearestPanorama(point, function(panoData) {
							if (panoData.code != 200) {
								$s('#streetviewLinkContainer').hide();
							} else {
								new GStreetviewPanorama($s('.streetview', enclosingDiv).get(0), {latlng:point});
							}
						});

						$s('.streetviewLink', enclosingDiv).bind('click', function (e) {
							$s('.streetview', enclosingDiv).show();
							$s('.mapview', enclosingDiv).hide();
							return false;
						});
						$s('.mapviewLink', enclosingDiv).bind('click', function (e) {
							$s('.mapview', enclosingDiv).show();
							$s('.streetview', enclosingDiv).hide();
							return false;
						});
					}										

				} else {
					// Failed to find the address - hide the map
					//enclosingDiv.hide();
				}
			});
};


/* If quickpay is selected as confirm payment, move the user to view payments */
function goToViewPayments( selectId, listingId ) {
    objSelect = document.getElementById( selectId );
    arrOptions = objSelect.getElementsByTagName('option');

    if (arrOptions.length > 0) {
        for(i=0;i<arrOptions.length;i++) {
            if (arrOptions[i].selected == true) {
                if (arrOptions[i].value == 'quickpay') {
                    window.location = '/my-sella/buy/view-payment-instructions/'+listingId+'/?quickpayme=true';
                }
            }
        }
    }
}

/* ATTENTION: DARON. new function to go to a URL */
function sellaGoToURL( $url ) {
    if ( $url.indexOf('http') == -1 ) {
        return false;
    }
    window.location = $url;
}

/****************************************************************************************************************************/

//From existing Messy JS files - refactor individual calls to pageready, global namespace pollution and general crap dom html code

/****************************************************************************************************************************/

//form.js

/****************************************************************************************************************************/

//TODO - refactor to jQuery

var validateForm = function(oEvent, options) {
	var valid = true;
	var formFields = sella.get_all('form .validate');
	for (var i=0; i<formFields.length; i++) {
		valid = valid && validateFormField(formFields[i]);
	}
	if (typeof options.submitButton == 'object') {
		options.submitButton.disabled = (!valid);
	}
	return valid;
};

var validateFormField = function(formField) {
	var valid = true;
	var eField = $s(formField);
	if (eField.hasClass('validate-number') && isNaN(formField.value) && formField.value.match(/[^\d]/)) {
		//Invalid number
		valid = false;
	} else if (eField.hasClass('validate-alpha') && !formField.value.match(/^[a-zA-Z]+$/)) {
		//Invalid alpha
		valid = false;
	} else if (eField.hasClass('validate-alphanum') && !formField.value.match(/\w/)) {
		//Invalid alphanumeric
		valid = false;
	} else if (eField.hasClass('validate-email') && !formField.value.match(/\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/)) {
		//Invalid email
		valid = false;
	} else if (eField.hasClass('validate-checked') && !formField.checked) {
		//Checkbox must be checked.
		valid = false;
	} else if (eField.hasClass('validate-selected') && formField.options[formField.selectedIndex].value.replace(/0/,'').length==0) {
		//Selected option must have a value
		valid = false;
	} else if (eField.hasClass('validate-radio')) {
		//Selected option must have a value
		//Get all radio buttons
		//var radioFields = Y.util.Selector.query('input', formField.parentNode.parentNode);
		var radioFields = $s('input', $s(formField.parentNode.parentNode)).get();

		valid = false;
		for (var i=0; i<radioFields.length; i++) {
			if (radioFields[i].name==formField.name && radioFields[i].checked) {
				valid = true;
				break;
			}
		}
	};
	return valid;
};

var autoValidateForm = function(options) {
	//var formFields = sella.get_all('form .validate');
	//Y.util.Event.addListener(formFields, 'change', validateForm, options);
	sella.onchange('form .validate',{options:options}, validateForm );
};

//TODO - refactor to jQuery


function checkAll(value, classname) {

	var boxes = sella.get_all('input.'+classname+'_box');
	for (var i = 0; i < boxes.length; i++) {
		boxes[i].checked = value;
	}
	$s('input.check_all').attr('checked',value);
}

function deleteCommentTab(user_id, blacklist_id, blacklist, href){
	if(!user_id){
		window.location.pathname="/login/";
	}
	else{
		url = sella.rpc_url (
			blacklist ? 'sella_user_blacklist_delete_comment' : 'sella_listing_comment_delete',
			user_id,
			blacklist_id
		);
		sella.ajax.get(url,afterDelete,{href:href, item:blacklist_id},function(){alert('Sorry - Failed to delete comment');});
	}

}

function afterDelete(o){//TODO - remove inline html
	sella.get_by_id('comments'+o.argument.item).innerHTML = '<a href="'+o.argument.href+'" class="add-comment">Add comment</a>';
	$s("#close-feedback").click();
}

function deleteBlacklist(user_id, blacklist_id, blacklist_name, feedback){
		if(!user_id){
				window.location.pathname="/login/";
		}
		else{
			sella.ajax.get(
				sella.rpc_url ('sella_user_blacklist_delete', user_id, blacklist_id),
				afterSaveBlacklist,
				{name:blacklist_name, item:blacklist_id, feedback:feedback}
			);
		}

}

function afterSaveBlacklist(o){//TODO - remove inline html
        $s('.blacklist'+o.argument.item).parent().remove();
        $s('.global-note').remove();
        $s('#content_feedback').html('<div class="global-note"><p>'+o.argument.name+' has been removed from your blacklist.</p></div>');
        if(o.argument.feedback){
            $s('.blacklistform'+o.argument.item).html('<form method="post"><input type="hidden" name="blacklist_id" value="'+o.argument.item+'" /><div class="button-neutral button-icon"><span class="icon-container blacklist-small" /><input type="submit" name="blacklist" value="Add to Blacklist" /><span></span></div></form>');
		}
}

function initialise_images() 
{
	sella.onclick('div#img-thumbs a', function(e) {
		e.preventDefault();
		setImg(e.target);
	});
}

function imgPath (id, size, modifier) {
    var mod = '';
    if(modifier !=''){
        mod = '-'+modifier;
    }
	return '/images/thumb/'+id.substr(-3,1)+'/'+id.substr(-2,1)+'/'+id.substr(-1,1)+'/'+id+'-'+size+mod+'.jpg';
}

function setImg (new_img, current) {
	var item = sella.get('.img-main-link');
	if (item) {
		item.setAttribute('href', 'display-images/'+new_img+'/');
	}
	item = sella.get('.img-full-size-link');
	if (item) {
		item.setAttribute('href', 'display-images/'+new_img+'/');
	}
	item = sella.get('#img-main');
	if (item) {
		item.setAttribute('src', imgPath(new_img.id.replace(/image-/, ''), '390x292','' ));
		item.setAttribute('title', new_img.title);
		item.setAttribute('alt', new_img.alt);
	}
	if(typeof current != 'undefined') $s('#st-current').html(current);
}

function addBlacklist(user_id, blacklist_id){
	if (!user_id) {
		window.location.pathname = "/login/";
	}
	else {
		sella.ajax.get(
			sella.rpc_url ('sella_user_blacklist_add', user_id, blacklist_id),
			afterAdd,
			{blacklist_id:blacklist_id}
		);
	}
	return false;
}

function afterAdd(o){
	var blacklist_id = o.argument.blacklist_id;
	uri = window.location.pathname;
	window.location.pathname = uri+'?blacklist_id='+blacklist_id+'&questions';
}

function ignoreQuestion(user_id, question_id, account){
	if (!user_id) {
		window.location.pathname = "/login/";
	}
	else {
		sella.ajax.get(sella.rpc_url ('sella_comment_moderate', question_id, 'deactivate'),afterIgnore,{question_id:question_id,account:account});
	}
}

function afterIgnore(o){
	var question_id = o.argument.question_id;
	var account = o.argument.account;
	if(account){
		sella.get_by_id('question_'+question_id).innerHTML = '';
		sella.css('question_'+question_id,'list-style-type','none');
	}
	else{
		sella.get_by_id('status_'+question_id).innerHTML = 'Ignore';
	}
}

function calculate(){
	var price_float = parseFloat(price);
	var ship;
	if(sella.get_by_id('final_shipping_info').value){
		ship = parseFloat(sella.get_by_id('final_shipping_info').value);
	}
	else{
		ship = 0;
	}
	ship += price_float;
	sella.get_by_id('total').innerHTML = ship.toFixed(2);
}

function show(id){//refactor - we have sella.show()
	if (sella.get_by_id(id).style.display == "none") {
		sella.get_by_id(id).style.display = "block";
	}
	else{
		sella.get_by_id(id).style.display = "none";
	}
}

function applyReady(){
	sella.onclick('#no_cv', function() {handleClick('show_cv', false);});
	sella.onclick('#cv_upload', function() {handleClick('show_cv', true);});
	sella.onclick('#no_cover_letter', function() {handleClick('cover_letter_input', false);handleClick('cover_letter_upload', false);});
	sella.onclick('#input_cover_letter', function() {handleClick('cover_letter_input', true);handleClick('cover_letter_upload', false);});
	sella.onclick('#upload_cover_letter', function() {handleClick('cover_letter_input', false);handleClick('cover_letter_upload', true);});
}

function handleClick(id, is_show){
	if(!is_show){
		sella.add_class('#'+id, 'hide');
	}
	else{
		sella.remove_class('#'+id, 'hide');
	}
}


/****************************************************************************************************************************/

//address.js

/****************************************************************************************************************************/


function postcodesSelected(o, options) {
	var el = sella.get_by_id(options.namespace + 'postcode');
	el.value = o ? o : '';
}

function updateSelector(region,district,suburb) {
	sella.ajax.get(sella.rpc_url ('area_lookup', suburb, district), changeSelector);
}

function changeSelector(o) {
	var ch = eval('(' + o.responseText + ')');

	if (ch) {
		sella.ajax.get(sella.rpc_url ('area_get_children', 0), getAllArea, {selector_no:1, selected_id:ch.region_id});
		sella.ajax.get(sella.rpc_url ('area_get_children', ch.region_id), getAllArea, {selector_no:2, selected_id:ch.city_id});
		sella.ajax.get(sella.rpc_url ('area_get_children', ch.city_id), getAllArea, {selector_no:3, selected_id:ch.suburb_id});
	}
}

function seriesOptionSelected(selector_no) {
	//able to tell if has-children? nicer to hide subsequent lists?
	var selector = document.getElementById('selector_' + selector_no);
	var option = selector.options[selector.selectedIndex];
	var next_selector = document.getElementById('selector_' + (selector_no+1) );

	if(next_selector) {
		for(i=1;i<3;i++) {
			var next = document.getElementById('selector_' + (selector_no+i) );
			if (next) {
				resetSelect(next);
			}
		}
		sella.ajax.get(sella.rpc_url ('area_get_children', option.value), getAllArea, {selector_no:selector_no, selected_id:0});
	}
}

/**
 * called after ajax call success
 */
function getAllArea(o){
	var ch = eval(o.responseText);
	var selected_id = o.argument.selected_id;
	var selector_no = o.argument.selector_no;

	if(selected_id == 0) {
		var selector = 'selector_' + (selector_no + 1);
	} else {
		var selector = 'selector_' + selector_no;
	}

	populateSelect(selector, ch, selected_id);
}


/**
 * given a result set, populates listbox
 */
function populateSelect(sel, ch, selected) {
	var i = 0;
	var item;
	var more;
	var newOption;
	var selector = sella.get_by_id(sel);

	for (i=0;i<ch.length;i++) {
		item = ch[i];
		more = (item.depth != 3) ? ' >' : '';
		newOption = new Option(item.name + more, item.id);
		newOption.label = item.name + more;
		newOption.title = item.name;
		newOption.selected = (item.id == selected) ? 'selected' : '';
		newOption.area = item;
		selector.options[i] = newOption;
	}
}

function resetSelect(s) {
	while (s.options.length > 0) {
		s.options[0] = null;
	}
	s.disabled = false;
}

function resetInput(s) {
	if(s == 1) {
		var inputName = 'physical_address_region';
	} else if(s ==2) {
		var inputName = 'physical_address_district';
	} else if(s ==3) {
		var inputName = 'physical_address_suburb';
	}

	var selectedInput = document.getElementById(inputName);
	selectedInput.value = '';
}


/****************************************************************************************************************************
 *
 * Advanced Search
 *
/****************************************************************************************************************************/

sella.advanced_search = function() 
{
	if (sella.get_by_id('property')) {
		new sella.area_drilldown('#form-sale');
		new sella.area_drilldown('#form-rent');

		sella.onclick('#type-sale', function(e) {
			e.preventDefault();
			sella.remove_class('#form-sale', 'hide');
			sella.add_class('#form-rent', 'hide');
			sella.remove_class('#property-type-group', 'right');
			sella.add_class('#property-type-group', 'left');
		});

		sella.onclick('#type-rent', function(e) {
			e.preventDefault();
			sella.remove_class('#form-rent', 'hide');
			sella.add_class('#form-sale', 'hide');
			sella.remove_class('#property-type-group', 'left');
			sella.add_class('#property-type-group', 'right');
		});
	}

/* disabled as area is no longer multiple dropdowns
	if (sella.get_by_id('motoring')) {
		new sella.area_drilldown('#motoring');
	}
*/

	if (sella.get_by_id('jobs')) {
		new sella.area_drilldown('#form-jobs');
		var jobs_occupations = new occupation_handler('occupation_id', 'occupation', 'sub-occupation', sub_occupation_id);
	}

	if (sella.get_by_id('flatmates')) {
		new sella.area_drilldown('#form-flatmates');
	}
};



function rpc() {
	this.rpc_url = null;
	this.process_response = function(response) {
		try { // Attempt to parse the response as JSON
			var categories = sella.eval_json(response.responseText);
			var field = sella.get_by_id(response.argument.field_id);
			field._populate(categories);
		} catch (exception) {
			return false;
		}
	};
	this.fetch = function(field, parent_cat_id) {
		if (!parent_cat_id) {
			return;
		}

		sella.ajax.get(
			sella.rpc_url(this.rpc_url, parent_cat_id),
			this.process_response,
			{field_id: field.id, parent_id: parent_cat_id}//scope?
		);
	};
}

/**
 * Looks after the area select inputs (Region, District, Suburb) for the advanced
 * search forms.
 * 
 * @param container_select A CSS selector of a containing element
 */
sella.area_drilldown = function (container_select) 
{
	this.container			= $s(container_select);
	this.region_select		= $s('select[name="region_id"]',	this.container)[0];
	this.district_select	= $s('select[name="district_id"]',	this.container)[0];
	this.suburb_select		= $s('select[name="suburb_id"]',	this.container)[0];
	this.area_input			= $s('input#area_id',				this.container)[0];
	
	// Setup the event handlers
	sella.onchange(this.region_select,		this, this.region_change);
	sella.onchange(this.district_select,	this, this.district_change);
	sella.onchange(this.suburb_select,		this, this.suburb_change);
};

sella.area_drilldown.prototype.region_change = function (event)
{
	// Update the selected area_id
	event.data.area_input.value = event.currentTarget.value;
	
	event.data.clear_select(event.data.district_select, 'Districts');
	event.data.clear_select(event.data.suburb_select, 'Suburbs');
	
	event.data.populate_area_select(event.currentTarget.value, event.data.district_select);
};

sella.area_drilldown.prototype.district_change = function (event) 
{
	// Update the selected area_id
	event.data.clear_select(event.data.suburb_select, 'Suburbs');
	
	if(event.currentTarget.value == '0') {
		event.data.area_input.value = event.data.region_select.value;
		return
	}
	event.data.area_input.value = event.currentTarget.value;
	event.data.populate_area_select(event.currentTarget.value, event.data.suburb_select);
	
};

sella.area_drilldown.prototype.suburb_change = function (event)
{
	// Update the selected area_id
	if(event.currentTarget.value == '0') {
		event.data.area_input.value = event.data.district_select.value;
		return;
	}
	event.data.area_input.value = event.currentTarget.value;
};

/**
 * Send the RPC call to get child areas
 */
sella.area_drilldown.prototype.populate_area_select = function (area_id, element)
{
	if(area_id == '0') {
		return;
	}
	
	// Populate the other selects based on the currently selected area
	sella.rpc({webservice:   'area_get_children',
				params:       {area_id: area_id},
				on_success:   sella.area_drilldown.populate_onsuccess, 
				element:      element});
};

/**
 * Handle RPC response and populate area select.
 */
sella.area_drilldown.populate_onsuccess = function (response, options) 
{
	$(response).each(function (index, area) {
		$(options.element).append($s('<option />').val(area.id).html(area.name));
	});
	$(options.element).attr('disabled', '');
};

sella.area_drilldown.prototype.clear_select = function (select, title) 
{
	$(select).html($s('<option />').val('0').html('All '+title+'...'));
	$(select).attr('disabled', 'disabled');
};

var occupations_rpc;

function occupation_handler(occupation_id, occupation, sub_occupation, sub_occupation_ids) {
	occupations_rpc = new rpc();
	occupations_rpc.rpc_url = 'sella_category_children';

	occupation_id = sella.get_by_id(occupation_id); // load the areas if defined
	occupation = sella.get_by_id(occupation);
	sub_occupation = sella.get_by_id(sub_occupation);
	//Y.util.Event.addListener([occupation, sub_occupation], 'change', function(){this.handle_changed();});
	sella.onchange(occupation,function(){this.handle_changed();});
	sella.onchange(sub_occupation,function(){this.handle_changed();});

	occupation.handle_changed = function() {
		sub_occupation.reset();
		var option = this.options[this.selectedIndex];
		occupation_id.value = option.value;
		if (this.selectedIndex !== 0) { // an option is selected
			sub_occupation.populate(option.value);
		}
	};
	sub_occupation.handle_changed = function() {
		if (this.selectedIndex !== 0) { // at least one option selected
			var selected_ids = [];
			for (var i in this.options) {
				if (this.options[i] != null && this.options[i].selected) {
					selected_ids[selected_ids.length] = this.options[i].value;
				}
			}
			if (selected_ids.length > 0) {
				occupation_id.value = selected_ids.join(',');
			}
		} else { // get the selected parent id
			var option = occupation.options[occupation.selectedIndex];
			occupation_id.value = option.value;
		}
	};
	sub_occupation.reset = function() {
		//Y.util.Dom.addClass(this, 'hide');
		sella.add_class(this, 'hide');
		this.options.length = 0;
		this.options[this.options.length] = new Option('All Occupations', 0);
	};
	sub_occupation.populate = function(occupation_id) {
		occupations_rpc.fetch(this, occupation_id);
	};
	sub_occupation._populate = function(sub_occupations) {
		if (sub_occupations.length === 0) {
			return;
		}

		selectedOpt = false;
		for (var i in sub_occupations) {
			var option = new Option(sub_occupations[i].name, sub_occupations[i].id);
			if (sub_occupation_ids && sub_occupation_ids == option.value) {
				selectedOpt = this.options.length;
				option.selected = true;
			}
			this.options[this.options.length] = option;
		}
		sub_occupation_ids = null; // clear it if defined
		this.handle_changed();

		if ( selectedOpt !== false ) {
			opt = this.options[selectedOpt];
			opt.selected = true;
		}

		//Y.util.Dom.removeClass(this, 'hide');
		sella.remove_class(this, 'hide');

	};

	if (occupation_id && occupation_id.value > 0 && occupation_id.value !== '') {
		occupation.handle_changed();
	}
}



/****************************************************************************************************************************/

//date.js

/****************************************************************************************************************************/


function dayValidation(){
	var selMonth = sella.get_by_id("date_of_birth_month");
	var selDay = sella.get_by_id("date_of_birth_day");
	var selYear = sella.get_by_id("date_of_birth_year");
	var day = parseInt(selDay.options[selDay.selectedIndex].value);
	var month = parseInt(selMonth.options[selMonth.selectedIndex].value);//months in js are 0 indexed
	var year = parseInt(selYear.value);
	year = (isNaN(year) ? 0 : year);
	var lastday = new Date(year, month, 0);//month this is actually set to the month after, 0 gets the previous day
	var lastd = lastday.getDate();

	selDay.innerHTML = "";
	for(i=1; i<=lastd; i++){
		opt = document.createElement("option");
		opt_txt = document.createTextNode(i);
		opt.appendChild(opt_txt);
		opt.setAttribute("value", i);
		if (i == day) {
			opt.selected = true;
		}
		//console.log(i);
		selDay.appendChild(opt);
	}
	selDay.disabled = false;
}


function validateYear() {
	var year = parseInt(this.value);
	if (isNaN(year)) {
		year = '';
	} else {
		if (year < 100) {
			year += (year < 70 ? 2000 : 1900); // 2 digit year
		}
		var this_year = new Date().getFullYear();
		if (year > this_year) {
			year = year - 100;
		}
		var hundy = this_year - 100; // a hundred years ago
		if (year < hundy) {
			year = hundy; // too long ago
		}
	}
	this.value = (year == '' ? 'year' : year);
	dayValidation();
}

function dateReady(){
	sella.onfocus('#date_of_birth_year', function() {if (this.value=='year') this.value = '';});
	sella.onblur('#date_of_birth_year', validateYear);
	sella.onchange('#date_of_birth_month', function() {dayValidation();});
}



/****************************************************************************************************************************/

//display_images.js

/****************************************************************************************************************************/

function configureBackButton() {
	// hook back-to-listing buttons
	$s("h2.back-to-listing > a").click(handleBackLink);

	// sort out other links, use location.replace()
	var links = $s("content-main > a").get();
	for (var i=0; i< links.length; i++) {
		var link = links[i];
		if (link.href.substr(0,10) !== 'javascript') {
			sella.onclick(link, handleLink);//TODO do we need to pass id not object reference?
		}
	}
}


function handleBackLink(e) {
	if (window.history && window.history.length > 1) {
		event.stopEvent(e);
		window.history.go(-1);
	}
}
function handleLink(e) {
	if (this.href.length > 0) {
		event.stopEvent(e);
		window.location.replace(this.href);
	}
}





/****************************************************************************************************************************/

//listing.js

/****************************************************************************************************************************/

function listingReady () {

	var contain = sella.get_by_id("listing-flash-banner");
	var contain_wide = sella.get_by_id("listing-flash-banner-wide");

	if (contain || contain_wide) {
		if(contain){
            var flashBanner = new SWFObject(flashMovieURL, "flash-banner", "678", "83", "6", "#e5f7fc");
            flashBanner.addParam("wmode", "transparent");
            flashBanner.addParam("allowScriptAccess", "always");
            flashBanner.write("listing-flash-banner");
        }
		else if(contain_wide){
            var flashBanner = new SWFObject(flashMovieURL, "flash-banner", "960", "119", "6", "#e5f7fc");
            flashBanner.addParam("wmode", "transparent");
            flashBanner.addParam("allowScriptAccess", "always");
            flashBanner.write("listing-flash-banner-wide");
        }
	}
}

/****************************************************************************************************************************/

//login.js

/****************************************************************************************************************************/

function showWarningIfChecked(banana) {

	if (this.checked) {
		var message = "Selecting this will keep you logged in on this computer and could allow others who are using this computer to access your account.";
        if (!confirm (message)) {
        	this.checked = false;
        }
	}
}

/****************************************************************************************************************************/

//postsale.js

/****************************************************************************************************************************/

function instructions_tab(id){
	document.getElementById('instructions_'+id).className = 'show_block';
	document.getElementById('fulfillment_'+id).className = 'hide';
	document.getElementById('feedback_'+id).className = 'hide';
	document.getElementById('instructions_tab_'+id).className = 'on';
	document.getElementById('fulfillment_tab_'+id).className = 'off';
	document.getElementById('feedback_tab_'+id).className = 'off';
	return false;
}

function fulfillment_tab(id){
	document.getElementById('instructions_'+id).className = 'hide';
	document.getElementById('fulfillment_'+id).className = 'show_block';
	document.getElementById('feedback_'+id).className = 'hide';
	document.getElementById('instructions_tab_'+id).className = 'off';
	document.getElementById('fulfillment_tab_'+id).className = 'on';
	document.getElementById('feedback_tab_'+id).className = 'off';
	return false;
}

function feedback_tab(id){
	document.getElementById('instructions_'+id).className = 'hide';
	document.getElementById('fulfillment_'+id).className = 'hide';
	document.getElementById('feedback_'+id).className = 'show_block';
	document.getElementById('instructions_tab_'+id).className = 'off';
	document.getElementById('fulfillment_tab_'+id).className = 'off';
	document.getElementById('feedback_tab_'+id).className = 'on';
	return false;
}

/****************************************************************************************************************************
 *
 * Subscribe
 *
 ****************************************************************************************************************************/

function savesearch (element, user_id, uri, title, type) 
{
	if (!type) {
		type = 'search';
	}

	if(sella.get('#store_subscribe')){
		element = sella.get('#subscribe_store_link');
		$s('#store_subscribe span').remove();
		$s('#store_subscribe a.store_rss').remove();
		$s('#store_subscribe a').removeClass();
		$s('#store_subscribe').removeClass().addClass('store_subscribed');
	}

	
	var options = {webservice:      'sella_search_save',
			params:          {user_id: sella.get_user_id(), uri: uri, title: title, type: (type=='similar'?'search':type)},
			requires_login:  true,
			pre_ajax:		 'savesearch.pre_ajax',
			on_success:      'savesearch.on_success',
			type:            type}; 
	
	if(element.form) {
		element.form.setAttribute('action', '/my-sella/subscriptions/');
		element.setAttribute('id', 'button-saved');
		element.setAttribute('name', 'button-saved');
		element.setAttribute('title', 'Saved');
		element.setAttribute('value', 'Saved');
		element.onclick = null;
	} else {
		options.link_selector = '#'+element.id;
	}
	sella.rpc(options);
	
	return false;
}

savesearch.pre_ajax = function(options)
{
	if(options.link_selector) {
		sella.show_link_indicator(options.link_selector);
	}
};

savesearch.on_success = function (response, options) 
{
	if(sella.get('#store_subscribe')){//dupe code because this can get called by login - this needs refactoring
		$s('#store_subscribe span').remove();
		$s('#store_subscribe a.store_rss').remove();
		$s('#store_subscribe a').removeClass();
		$s('#store_subscribe').removeClass().addClass('store_subscribed');
	}

	var uri;
	var link_title = 'You have subscribed to this '+options.type;
	
	if(options.type == 'member') {
		uri = '/my-sella/subscriptions/members/';
	}
	else if(options.type == 'search') {
		uri = '/my-sella/subscriptions/';
	}
	else if(options.type == 'similar') {
		uri = '/my-sella/subscriptions/';
		link_title = 'You have subscribed to similar listings';
	}
	else if(options.type == 'category') {
		uri = '/my-sella/subscriptions/categories/';
	}

	if(options.link_selector) {
		$s(options.link_selector).replaceWith('<a class="receive-email-listings" id="email_seller_listings" href="'+uri+'">'+link_title+'</a>');
	}


	// Increment the subscriptions count in the account bar
	element = $s('#items-saved-count');
	element.text(1 + parseInt(element.text()));
};



/****************************************************************************************************************************/

//alert

/****************************************************************************************************************************/

sella.hide_alert = function(selector,user_id, alert_id, type) {
	//remove the element from the dom
	if(user_id && type == 'intro'){
		sella.rpc({webservice:   'sella_alert_user_hide',
					params:       {user_id: user_id, type:type, alert_id:alert_id}});
	}else{
		$s.cookie('viewed_'+type, alert_id, {path:'/',expires: 3650});//set the cookie in either case
	}
	$s(selector).hide();
	return false;
};



/******************************************************************************
 * 
 * Closing soon scrolling list
 * 
 ******************************************************************************/
sella.scroll_closing = {};

sella.scroll_closing.minimum_to_show = 16;

sella.scroll_closing.get_client_time = function () {
	return Math.round((new Date()).getTime() / 1000);
}

sella.scroll_closing.get_server_time = function () {
	return parseInt($('.scroll_closing #server_time').text());
}

sella.scroll_closing.process = function (list) {
	if (list.children('li').size() < 1) {
		return;
	}

	if (list.children('li').size() < sella.scroll_closing.minimum_to_show + 2) {
		jQuery.ajax({
			cache: false,
			dataType: 'html',
			data: {'ajax': 'true'},
			url: '/services/ajax/scroll/',
			success: function (data) {
				data = $(data).filter('li');
				var last_time = parseInt(list.children('li').eq(list.children('li').length - 1).find('.closes_at').text());
				while (data.length > 0 && last_time >= parseInt(data.eq(0).find('.closes_at').text())) {
					data = $(data).not(':first');
				}
				data.appendTo(list);
			}
		});
	}

	var first_item = list.children('li').eq(0);
	var first_item_closes = parseInt(first_item.find('.closes_at').text());

	if (this.get_client_time() >= first_item_closes) {
		first_item.animate({
				marginLeft: '-=60'
			}, 1000, function () {
				$(this).remove();
				sella.scroll_closing.process(list);
			}
		);
	} else {
		setTimeout("sella.scroll_closing.process($('#scroll_closing_list'))", (Math.abs(this.get_client_time() - first_item_closes) + 1) * 1000);
	}
};

jQuery(function ($) {
	if (!$('.scroll_closing') || !$('.scroll_closing #server_time')) {
		return;
	}

	if (Math.abs(sella.scroll_closing.get_client_time()
					- sella.scroll_closing.get_server_time()) < 2 * 60) {
		sella.scroll_closing.process($('#scroll_closing_list'));
	}
});

/*********************************************************************************************************************/

///REFACTOR OR KILL THESE

/*********************************************************************************************************************/

//From existing inline page code - //TODO: get all these out of the global namespace, check for dupes

/*********************************************************************************************************************/

/* mimic target="_blank" - just add class="new-window" */
function new_window(e) {
	window.open(this.href,'mywindow');
	e.preventDefault();
}

/* show/hide more links */
function showMoreLinks(e) {
	sella.show('#more-links');
	$s('#more-links').focus();
	sella.onmouseover("#more-links ul",showMoreLinks);
	sella.onmouseout("#more-links ul",hideMoreLinks);
	sella.onblur("#more-links ul",hideMoreLinks);
	e.preventDefault();

}

function hideMoreLinks(e) {
	sella.hide('#more-links');
	$s("#show-more-links").one("click",showMoreLinks);
	e.preventDefault();
}

/* context help */
function showContextHelp() {
	sella.show('#context-help-text');
}

function hideContextHelp() {
	sella.hide('#context-help-text');
}


//from site/my-sella/buy

function loadQuickChange() {
	var links = sella.get_all("a.reminder_link");
	for (var i = 0; i<links.length; i++) {
		sella.onclick(links[i], loadDropdown);
	}
}

function loadDropdown(e) {
	e.stopEvent();
	alert(this.href);
	var id_parts = this.id.split('_');
	var span = sella.get_by_id('reminder_'+id_parts[id_parts.length-1]);
	span.orig = span.innerHTML;
	span.innerHTML = 'text';
}

function clearPassword(){
	if(sella.get_by_id('password').value != null){
		sella.get_by_id('password').value = '';
	}
}

function open_panel(id){
	document.getElementById('open-'+id).className = 'hide';
	document.getElementById('close-'+id).className = 'show_block';
	document.getElementById(id).className = 'show_block';
	return false;
}
function close_panel(id){
	document.getElementById('open-'+id).className = 'show_block';
	document.getElementById('close-'+id).className = 'hide';
	document.getElementById(id).className = 'hide';
	return false;
}

function attachLimiter() {
		var spans = sella.get_all('div.text_counter');
		for (var i=0; i<spans.length; i++) {
			var textfield = document.getElementById(spans[i].id.replace(/-counter/,''));
			if (textfield) {
				sella.onkeyup(textfield, calculateRemaining);
				calculateRemaining.call(textfield); // figure out how many chars are remaining for this field.
			}
		}
	}

function calculateRemaining() {
	var max_length = parseInt(this.getAttribute('maxLength'));
	if (!isNaN(max_length) && max_length>0) {
		var id = this.id;
		var counter = sella.get_by_id(id+'-counter');
		if (counter) {
			var remaining = max_length - this.value.length;
			counter.innerHTML = remaining + ' characters left';
		}
	}
}


function loadFlashLogos(){

		var flash_logos = sella.get_all(".logo_flash");

		if (flash_logos) {
			for (var i = 0; i < flash_logos.length; i++) {
				var logo = flash_logos[i];
				var flash = logo.innerHTML;
				var len = flash.length;
				var logo_url = '/file/' + flash.substr(len-3, 1) + "/" + flash.substr(len-2, 1) + "/" + flash.substr(len-1, 1) + "/" + flash + '.swf';
				var flashLogo = new SWFObject(logo_url, "flash-logo", "100", "75", "6", "#e5f7fc");
				flashLogo.addParam("wmode", "transparent");
				flashLogo.write(logo.id);
			}
		}
	}


/**
 * Adserver statistics
 */
adserver_view_queue = [];

function adserver_view(id) {
	adserver_view_queue.push(id);
}

function adserver_click(id) {
	jQuery.ajax({
		url: sella.rpc_url('adserver_statistic_receive_click', id),
		type: 'GET'
	});
}

jQuery(function ($) {
	if (adserver_view_queue.length > 0) {
		$.ajax({
			url: sella.rpc_url('adserver_statistic_receive_views', adserver_view_queue),
			type: 'GET'
		});
	}
});

/**
 * Sella store statistics
 */
jQuery(function ($) {
	if (typeof sella_store_id != 'undefined') {

		$('.finda-business .name a').click(function () {
			$.get(sella.rpc_url('sella_stats_store_finda_clicked', [sella_store_id]));
		});
		$('.finda-business .url a').click(function () {
			$.get(sella.rpc_url('sella_stats_store_website_clicked', [sella_store_id]));
		});
	}
});

/**
 * New-style form widget javascript support
 */
sella.form_widget = {};

/**
 * Address selector
 *
 * This is a almost fully self-contained address selector, using drop-downs. Use the
 * form_widget/address_selector component to use this.
 *
 * Depends on sella.location.fetch_options
 */
sella.form_widget.address_selector = {};

sella.form_widget.address_selector.init = function(prefix) {
	$('#' + prefix + 'suburb').change(function (e) {
		if ($('#' + prefix + 'suburb').val() && $('#' + prefix + 'district').val()) {
			sella.rpc({
				webservice:   'area_lookup',
				params:       [$('#' + prefix + 'suburb').val(), $('#' + prefix + 'district').val()],
				on_success:   function (r) {
					if (r.suburb_id) {
						if ($('#' + prefix + 'normal_locator').hasClass('progressive-to-show') == true) {
							$('#' + prefix + 'suburb_id').val(r.suburb_id);
							$('#' + prefix + 'level_1').html(sella.location.fetch_options(0, 1, r.region_id));
							$('#' + prefix + 'level_2').html(sella.location.fetch_options(r.region_id, 2, r.city_id));
							$('#' + prefix + 'level_3').html(sella.location.fetch_options(r.city_id, 3, r.suburb_id));
							$('#' + prefix + 'level_2, #' + prefix + 'level_3').attr("disabled", false);
						} else {
							$('#' + prefix + 'suburb_select').val(r.suburb_id);
						}
						$('#' + prefix + 'postcode').focus();
						return false;
					}
				}
			});
		}
	});

	$('#' + prefix + 'address_1').autocomplete(
		'/services/address_proxy.php',
		{
			minChars: 2,
			max: 10,
			autoFill: true,
			width: 600,
			selectFirst: true,
			dataType: 'json',
			parse: function (data) {
				return $.map(data.results, function (item) {
					return {
						data: item,
						value: item.nice,
						result: item.nice
					};
				});
			},
			formatItem: function(item) {
				return item.nice;
			}
		}
	).result(function (e, r) {
		$('#' + prefix + 'address_1').val(r.number + ' ' + r.name);
		$('#' + prefix + 'suburb').val(r.suburb);
		$('#' + prefix + 'district').val(r.district);

		sella.rpc({
			rpc_url: '/services/rpc/address_find_postcode?' + escape(r.number) + '&' + escape(r.name) + '&' + escape(r.suburb),
			prefix: prefix,
			on_success: function (postcode, options) {
				$('#' + options.prefix + 'postcode').val(postcode ? postcode : '');
			}
		});

		$('#' + prefix + 'suburb').change();
	});

	$('#' + prefix + 'level_1, #' + prefix + 'level_2, #' + prefix + 'level_3').change(function () {
		var id = $(this).attr('id');
		var level = parseInt(id.charAt(id.length - 1));

		if (level < 3) {
			if ($(this).val() == "") {
				$('#' + id.substring(0, id.length - 1) + (level + 1))
					.attr('disabled', true)
					.html('<option>Please select...</option>');
			} else {
				$('#' + id.substring(0, id.length - 1) + (level + 1))
					.html(sella.location.fetch_options($(this).val(), level + 1))
					.attr('disabled', false)
					.focus();
			}
			$('#' + id.substring(0, id.length - 1) + (level + 2))
					.attr('disabled', true)
					.html('<option>Please select...</option>');
		} else if (level == 3) {
			$('#' + prefix + 'suburb_id').val($(this).val());
		}
	});
}