var SimpleSlide = new Class({
initialize: function(container,options) {
this.container = container;
this.options = options;
//  Is it on autorun or manual?
if(this.options.auto == "loop" || this.options.auto == "once") {
var automated;
this.automated = this.slider.periodical(this.options.time,this,$(this.container));
} else {
this.slider($(this.container))
}
},
slider: function(container) {
var direction;
if(this.options) direction = this.options.direction;
else direction = "forward";
var child;
if(this.options.goTo) {
var goTo = this.options.goTo.toInt();
goTo -= 1;
}
// Get all child nodes to scroll between.
var children = container.getChildren().getChildren()[0];
// Run through all child nodes to see if there is a tagged one.
children.each(function(e) {
// If there is, make it current child.
if(e.id == "currentChild") {
child = e;
}
});
if(goTo || goTo == 0) {
if(container.getChildren()[0].getChildren()[goTo]) child = container.getChildren()[0].getChildren()[goTo];
else alert("Slide "+goTo+" does not exist");
} else {
if(!child) {
// If there isn't, make the first one current child.
if(direction == "forward") {
child = children[0].getNext();
}
else if(direction == "back") {
child = container.getChildren()[0].getLast();
}
} else {
// Are we going to the next or previous node?
if(direction == "forward") {
var lastElement = container.getChildren()[0].getLast();
// Stops the loop at the last element.
if(lastElement == child.getNext() && this.options.auto == "once") $clear(this.automated);
// Is the current child the last node? Then set the first node as child, otherwise set the next node as child.
if(lastElement == child) child = children[0];
else child = child.getNext();
}
else if(direction == "back") {
var firstElement = container.getChildren()[0].getFirst();
// Stops the loop at the last element.
if(firstElement == child.getPrevious() && this.options.auto == "once") $clear(this.automated);
// Is the current child the last node? Then set the first node as child, otherwise set the next node as child.
if(firstElement == child) child = container.getChildren()[0].getLast();
else child = child.getPrevious();
}

}
}
// Is the child defined?
if(child) {
// Which type of slider is defined?
if(this.options.type == "scroll") this.scroll(container,children,child);
else if(this.options.type == "fade") this.fade(container,children,child);
else if(this.options.type == "scrollfade") this.scrollfade(container,children,child);
}
},
scroll: function(container,children,child) {
// Make it a scroll slide.
var scroll = new Fx.Scroll(container,{duration: this.options.duration, onComplete: function() {
// Remove tags from all child nodes.
children.each(function(e) {
e.id = "";
});
// Tag this child as current
child.id = "currentChild";
}}).toElement(child);

},
fade: function(container,children,child) {
// Make it a fade slide
var fade = new Fx.Style(container,'opacity',{duration: this.options.duration, onComplete: function() {
new Fx.Scroll(container,{duration: 1,onComplete: function() {
// Remove tags from all child nodes.
children.each(function(e) {
e.id = "";
});
// Tag this child as current
child.id = "currentChild";
new Fx.Style(container,'opacity').start(0.01,1);
}}).toElement(child);
}})
fade.start(1,0.01);
},
scrollfade: function(container,children,child) {
// In case you input the miliseconds as a string instead of integer.
var durationInt = this.options.duration.toInt();
// Make it a scrollfade slide
var fade = new Fx.Style(container,'opacity',{duration: (durationInt/2)})
fade.start(1,0.01).chain(function() {
fade.start(0.01,1);
});
new Fx.Scroll(container,{duration: durationInt, onComplete: function() {
// Remove tags from all child nodes.
children.each(function(e) {
e.id = "";
});
// Tag this child as current
child.id = "currentChild";
}}).toElement(child);
}
});
function adjustPictureTitleSize() {
	if(title_wrapper = document.getElementById('picture_title')) {
		max_length = 0;
		title = document.getElementById('picture_title').innerHTML;
		words = title.split(' ');
		for (var i = 0; i < words.length; i++) {
			if (words[i].length > max_length) {
				max_length = words[i].length;
			}
		}
		if(max_length < 7) {
			return;
		}
		else if (max_length < 9) {
			title_wrapper.style.fontSize = '27px'
		}
		else if (max_length < 11) {
            title_wrapper.style.fontSize = '23px'
        }
		else if (max_length < 16) {
            title_wrapper.style.fontSize = '19px'
        }
		else {
			title_wrapper.style.fontSize = '14px'
		}
	}
};
function toggleSearch() {
	if(e = $('search')) {
    var message = 'search something..';
		if(e.className == 'hide') {
			e.className = '';
			search_field = $('input_search')
			search_field.value = message
			return false;
		}
		else {
			if(search_field.value == message || search_field.value == '') {
				return false;
			}
			else {
				return true;
			}
		}
	}

};
function showRelated() {
    allElements = document.getElementById('fast_navigation').getElementsByTagName("LI")
    for (var i = 0; i < allElements.length; i++) {
        current = allElements[i];
        current.style.display = "none";
    }
    for( var i = 0; i < arguments.length; i++ ) {
        current = document.getElementById("category_" + arguments[i])
        current.style.display = "block";
    }
};

function fetchAndSlideCategories() {
	// fetch categories
    var categories_partial_url = "/categories_sidebar";
    $('categories_sidebar').innerHTML = 'prefetching ...'
    new Ajax(categories_partial_url, {
        method: 'get',
        update: $('categories_sidebar')
    }).request();

    // slide categories
    var slideCategoriesIntoView = new Fx.Slide('categories_sidebar');
    $('categories_menu').addEvent('click', function(e){
        e = new Event(e);
				$('categories_sidebar').style.marginTop == "0px" ? slideCategoriesIntoView.slideOut() : slideCategoriesIntoView.slideIn()
        e.stop();
    });
    //slideCategoriesIntoView.hide();
		$('categories_sidebar').style.marginTop = "-197px";
		$('categories_sidebar').style.display = 'block';
};
function isEmpty(element) {
	if ((element.value.length == 0) || (element.value == null) || element.value.match(/^[\s]+$/)) {
	   return true;
	}
	else {
	   return false;
   }
}

function validateCommentFields() {
	if (!$('comment_form')) {
		return;
	}
	$('comment_form').addEvent('submit', function(e) {
	    if(errorField = $('errors')) {
	        errorField.parentNode.removeChild(errorField);
	    }
	    errorListParent = document.createElement('ul');
	    errorListParent.setAttribute('id', 'errors');
		var currentElement = $('comment_fields')
	    var errorListElements = [];
	    var alpha = /^[a-zA-Z{1,} ?]+$/;
		var email=/([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4})/gi;
	    // validate
	    comment_user_name = $('comment_user_name');
		comment_content = $('comment_content');
		comment_email = $('comment_email');
	    errorListElements.push(document.createTextNode('Your comment could not be posted due to the following errors:'))
		if (!isEmpty(comment_user_name)) {
			if (!comment_user_name.value.match(alpha)) {
				errorListElements.push(document.createTextNode('Name must contain letters only. (Leave blank if you want to post as anonymous)'))
			}
		}
		if(!isEmpty(comment_email)) {
		    if(!comment_email.value.match(email)) {
                errorListElements.push(document.createTextNode('Email is not valid.'))
            }
		}
	    if(isEmpty(comment_content)) {
	        errorListElements.push(document.createTextNode('Content can\'t be blank.'))
	    }
	    for (var i = 0; i < errorListElements.length; i++) {
	        errorList = document.createElement('li');
	        if (i == 0) {
	            errorList.className = "error_description";
	        }
	        errorList.appendChild(errorListElements[i]);
	        errorListParent.appendChild(errorList);
	    }
	    parentElement = currentElement.parentNode;
	    if(errorListElements.length > 1) {
	        parentElement.insertBefore(errorListParent, currentElement);
	    }
	    else {
			$('comment_form').style.display = 'none';
			var ajaxLoader = $('comment_loading').addClass('loader');
			this.send({
                update: ajaxLoader,
                onComplete: function() {
					   ajaxLoader.removeClass('loader');
					   var showCommentSlide = new Fx.Slide('latest_comment');
					   showCommentSlide.hide();
					   $('latest_comment').style.display = 'block';
					   showCommentSlide.slideIn();
                }
            });

	    }
		new Event(e).stop();
	});
};

function check(e) {
    var target = (e && e.target) || (event && event.srcElement);
    var searchObj = document.getElementById('search');
    checkParent(target, searchObj) ? searchObj.className = 'hide' : null;
// 		var fastMenuObj = document.getElementById('categories_sidebar');
// 		if (checkParent(target, fastMenuObj)) {
// 			if(fastMenuObj.style.marginTop == "0px" && e.target != "http://" + location.host + "/categories") {
// 				$('categories_sidebar').style.marginTop = "-197px";
// 			}
// 		}
};

function checkParent(t, parentObj){
    while(t.parentNode){
        if(t == parentObj){
            return false
        }
        t = t.parentNode
    }
    return true
};
window.addEvent('domready', function() {
	adjustPictureTitleSize();
	fetchAndSlideCategories();
	validateCommentFields();
	document.addEvent("mousedown", check);
});
