// from CE
var CommunityEngine = {	
	resize_image: function(img, options ) {
		this.options = options || {};

		var img_width = img.offsetWidth;
		var img_height = img.offsetHeight;
		var img_aspect_ratio = Math.round((img_width / img_height) * 100) / 100;

		var max_width = this.options['max_width'] || 120;
		var max_height = this.options['max_height'] || 90;
		var max_aspect_ratio = Math.round((max_width / max_height) * 100) / 100;

	//	alert("orig image size is " + img_width + "x" + img_height + "\n" + "aspect ratio is " + img_aspect_ratio + "\n\n" + "max image size is " + max_width + "x" + max_height + "\n" + "max aspect ratio is " + max_aspect_ratio);

		var new_img_width = 0;
		var new_img_height = 0;
		var new_aspect_ratio = 0;

		// if no resize needed
    if (img_width < 120 && img_height < 90) {
            new_img_width = img_width;
            new_img_height = img_height; 

		// if wider
		} else if (img_aspect_ratio > max_aspect_ratio) {
			new_img_width = max_width;
			new_img_height = Math.round(new_img_width / img_aspect_ratio);

		// if taller
		} else if (img_aspect_ratio < max_aspect_ratio) {
			new_img_height = max_height;
			new_img_width = Math.round(new_img_height * img_aspect_ratio);

		// equal
		} else {
			new_img_width = max_width;
			new_img_height = max_height;
		}

		img.style.width = new_img_width + "px";
		img.style.height = new_img_height + "px";
		new_aspect_ratio = Math.round((new_img_width / new_img_height) * 100) / 100;
	}	
}

var Cookie = {
	set: function(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	},

	get: function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	},

	destroy: function(name) {
		createCookie(name,"",-1);
	}	
}

CommunityEngine.ToggleInput = Class.create();
Object.extend(Object.extend(CommunityEngine.ToggleInput.prototype, Abstract.prototype), {
	initialize: function(element, text){
		this.element = $(element);
		this.text = text;
		Event.observe(this.element, 'focus', this.toggleInput.bindAsEventListener(this) );
		Event.observe(this.element, 'blur', this.toggleInput.bindAsEventListener(this) );						
	},
	
	toggleInput: function(event){
		if (event.type == 'focus'){
			this.element.value = (this.element.value == this.text) ? '' : this.element.value;
		} else if (event.type == 'blur'){
			this.element.value = (this.element.value == '') ? this.text : this.element.value;								
		}
	}
	
});

CommunityEngine.FeatureRotator = Class.create();
Object.extend(Object.extend(CommunityEngine.FeatureRotator.prototype, Abstract.prototype), {
	initialize: function(element, features, options){
		this.timer = null;
	    this.element = $(element);
	    this.options = Object.extend({
	    	frequency: 8,
			transition: true
		}, options || {});
		
		this.counter = 0;
		this.features = features;
		this.id = "#" + this.element.id;
		
		if (this.options.debug){
			console.log("this.element %d", this.element)
			console.log("this.id: %d", this.id)
			console.log("this.features %d",this.features)
		}
		
		this.start();
	},
	
	stop: function()
	{
		clearTimeout(this.timer);
	},
	
	start: function()
	{
		this.periodicallyUpdate();
	},
	
	periodicallyUpdate: function()
	{ 
		
		this.update();	
		if (this.features.length == 1)
		{
			return;
		}
		if (this.timer != null)
		{
			clearTimeout(this.timer);		
		}
		this.timer = setTimeout(this.periodicallyUpdate.bind(this), this.options.frequency*1000);		
	},

	currentFeature: function()
	{
	    return this.features[ Math.abs(this.counter) % this.features.length ];
	},	

	fadeInImage: function(){
		Element.removeClassName(this.new_feature, 'hidden')
		Element.addClassName(this.new_feature, 'showing')	
		Element.removeClassName(this.current_feature, 'showing')
		Element.addClassName(this.current_feature, 'hidden')		
		new Effect.Opacity(this.current_feature, {duration:0.1, from:0, to:1 });		
	},
	
	transitionImage: function(){
		new Effect.Opacity(this.current_feature, {duration:0.9, from:1.0, to:0.01, afterFinish: this.fadeInImage.bind(this) });
	},

	update: function()
	{
		current = $$('.homepage_features .showing')[0]
		this.current_feature = current;

		currentlyAt = this.currentFeature();	
		new_current = $('feature_'+currentlyAt[0])
		this.new_feature = new_current;
		this.new_feature_bg_src = currentlyAt[1];
		
		if (currentlyAt && (this.counter != 0) ) {
			if (this.options.transition) {
				this.transitionImage()
			} else {
					if (this.current_feature){
						Element.removeClassName(this.current_feature, 'showing')
						Element.addClassName(this.current_feature, 'hidden')
					}
					Element.removeClassName(this.new_feature, 'hidden')
					Element.addClassName(this.new_feature, 'showing')	
			}
		
			if (this.options.debug) {
				console.log("currently at: %d", currentlyAt );	
			}
		} else {
			if (this.options.debug) {
				console.log("Debug: current_feature is nil");	
			}			
		}
    ++this.counter;				
	}	
});


// from townizen
function remove_parent_of_class(element, remove_object_class) {
	$(element).up(remove_object_class).remove();
}

function mark_for_destroy(element, remove_object_class) {
  $(element).next('.should_destroy').setValue(1);
  $(element).up(remove_object_class).hide();
}

function choose_image(image_id, trigger, default_text) {
	var container = $(trigger).up('.photo');
	var value_holder = $("selected_image");
	var trigger = $(trigger);
	var nv = "-1"
	
	if (container.hasClassName("selected")) {
		value_holder.value = nv;
		deselect_image_from(container, default_text);
		return;
	}
	
	var selected = container.up(".image-selection").down(".selected");
	if (selected)
		deselect_image_from(selected, default_text);	
	
	value_holder.value = image_id;
	container.addClassName("selected");
	trigger.innerHTML = "selected [cancel this selection]"
}

function deselect_image_from(container, default_text) {
	var container = $(container);
	container.down(".select-hint").innerHTML = default_text;
	container.removeClassName("selected");
}

function switch_tab(element) {
	$$('#tabs .active').each(function(e){e.removeClassName('active')});
	$(element).addClassName('active');
}

// forums
var TopicForm = {
  editNewTitle: function(txtField) {
    $('new_topic').innerHTML = (txtField.value.length > 5) ? txtField.value : 'New Topic';
  }
}

var LoginForm = {
  checkLogin: function(txt) {
    if(txt.value.match(/^https?:\/\//)) {
      $('password_fields').hide();
    } else {
      $('password_fields').show();
    }
  }
}

var EditForm = {
  // show the form
  init: function(postId) {
    $('edit-post-' + postId + '_spinner').show();
    this.clearReplyId();
  },

  // sets the current post id we're editing
  setReplyId: function(postId) {
    $('edit').setAttribute('post_id', postId.toString());
    $('posts-' + postId + '-row').addClassName('editing');
    if($('reply')) $('reply').hide();
  },
  
  // clears the current post id
  clearReplyId: function() {
    var currentId = this.currentReplyId()
    if(!currentId || currentId == '') return;

    var row = $('posts-' + currentId + '-row');
    if(row) row.removeClassName('editing');
    $('edit').setAttribute('post_id', '');
  },
  
  // gets the current post id we're editing
  currentReplyId: function() {
    return $('edit').getAttribute('post_id');
  },
  
  // checks whether we're editing this post already
  isEditing: function(postId) {
    if (this.currentReplyId() == postId.toString())
    {
      $('edit').show();
      $('edit_post_body').focus();
      return true;
    }
    return false;
  },

  // close reply, clear current reply id
  cancel: function() {
    this.clearReplyId();
    $('edit').hide()
  }
}

var ReplyForm = {
  // yes, i use setTimeout for a reason
  init: function() {
    EditForm.cancel();
    $('reply').toggle();
    $('post_body').focus();
    // for Safari which is sometime weird
//    setTimeout('$(\"post_body\").focus();',50);
  }
}

Event.addBehavior({
  '#search,#monitor_submit': function() { this.hide(); }
})


var makeRound = function(){var els = document.getElementsByTagName('div'); for(var i=0; el=els[i]; i++) if(el.className.indexOf('round')>-1 && el.firstChild && el.firstChild.className!='t') el.innerHTML = '<b class="t"><b class="r"></b></b><div class="c"><b class="br"></b>'+el.innerHTML+'<b class="br"></b></div><b class="b"><b class="r"><!----></b></b>';}

function check_search_field(field, form, default_value) {
	Event.observe(
		form,
		'submit',
		function(e) {
			if (field.value == "" || field.value == default_value) {
				var msg = "<span>You must input something in the search field.</span><small><a href='#' onclick='$(\'notification_box\').hide();return false;'>Close this message</a></small>";
				if ($('notification_box')) {
					$('notification_box').update(msg);
					Effect.Appear('notification_box', { duration: 0.1 });
				}
				else {
					var nbox = "<div class='warning flash_message notice' id='notification_box'>" + msg + "</div>";
					new Insertion.After($$('.search')[0], nbox);
				}

				Event.stop(e);
				show_error_message();
			}
		},
		false
	)
}

function box_slide_up() {
	if ($('notification_box'))
	{
		Effect.Fade( 'notification_box', { duration: 2.0 } );
	}
}

function show_error_message() {
	setTimeout('box_slide_up()', 4000);	
}

function nextSlider(i) {
	next_slider += i;
	if (next_slider < 0) next_slider = 0;
	if (next_slider >= slider_count) next_slider = slider_count - 1;
}

function prepareSliderArrows() {
	if (next_slider == 0) {
		$('news-slider-up').hide();
	}
	
	if (next_slider > 0) {
		$('news-slider-up').show();
	}
	
	if (next_slider == slider_count - 1 || slider_count == 0) {
		$('news-slider-down').hide();
	}
	else {
		$('news-slider-down').show();
	}
}