
Blog = Class.create({
	initialize: function(obj){
	 	this.prefix = obj.prefix;
		this.filters = new Object();
		this.filters.search = "";
		this.filters.tagged = "";
		this.searchField = this.prefix + "-filter-search";
		this.tagField = this.prefix + "-filter-tag";
		this.earlierButton = this.prefix + '-advance-button';
		this.laterButton = this.prefix + '-retire-button';
		this.content = this.prefix + '-post-content';
		this.indexField = this.prefix + '-index';
		this.totalPostField = this.prefix + '-max-post-no';
		if(obj.comments)
			this.commentContainer = this.prefix + "-viewBox";
		else
			this.commentContainer = "";
		this.cursor = 0;
		this.posts = [];
		this.allTags= [];
		this.tagCount= new Object();
		this.sortedTags= [];
		this.tagCursor= 0;
		this.temporaryOffset= 0;
		this.tagsLoaded= false;
		this.totalPosts = [];
		this.commentDiv = this.prefix + "_comment_text";

	},
	
	
	initializeBlog: function(){
		this.cursor = 0;
		this.posts = [];
		this.totalPosts = [];
		this.getTumbleLog("");
		if(this.prefix == "blog"){
			this.commentPoster = new ajaxObject("AJAX/add_blog_comment.lasso");
			this.commentPoster.callback = function(responseText, responseStatus){
				eval(responseText);
			}.bind(this);
		}
	},
	
	getTumbleLog: function(query){
		if((query != "") && (query.charAt(0) != "&"))
			query = "&" + query;
	//	alert("start=" + blogController.temporaryOffset + query);
		new Ajax.Request("AJAX/fetch_main_tumblelog.lasso", {parameters: "which=" + this.prefix + "&start=" + this.temporaryOffset + query,
			onSuccess: function(data){
				if(data.responseText.indexOf("!DOCTYPE") != -1)
					this.getTumbleLog(query);
				eval("responseText = " + data.responseText);
				temporaryPostArray = responseText.posts;
				for(i=0; i< temporaryPostArray.length; i++){
					this.posts[this.posts.length] = Object.clone(temporaryPostArray[i]);
					if(!this.tagsLoaded){
						if("tags" in responseText.posts[i]){
							for(j=0; j < responseText.posts[i].tags.length; j++){
								this.allTags.push(responseText.posts[i].tags[j]);
							}
						}
					}
				}
	//			alert(blogController.posts.length + " " + responseText['posts-total'] + " " + temporaryPostArray.length);
				if((this.temporaryOffset + 50 < responseText['posts-total']) && (temporaryPostArray.length != 0)){
					this.temporaryOffset += 50;
	//				alert("there are more blog posts left to download");
					this.getTumbleLog(query);
				}
				else{  //we've reached an iteration of blog.update where all posts have been retrieved, and can move on
					this.loadPost(0);
					//blogController.updateBodyHeight();
					this.cursor = 0;
					this.temporaryOffset = 0;
					this.totalPosts = this.posts.length;
					$(this.totalPostField).innerHTML = this.posts.length;
					this.updateArrows();
					if(!this.tagsLoaded)
						this.finalizeTagList();
				}
			}.bind(this),
			
			onFailure: function(){ alert("Blog failed to load.");}
			
			});
	},
	
	loadPost: function(id){
		$(this.content).innerHTML = "<h2>" +this.posts[id]['regular-title']+"</h2><div class='blogcontent'>" + this.posts[id]['regular-body']+"</div>";
		$(this.indexField).value = (id + 1);
		
		if(this.prefix == "product"){
			var cropImages = $(this.content).select("IMG.crop");
			for(i=0; i<cropImages.length; i++){
				var src = $(cropImages[i]).src;
				var width = $(cropImages[i]).width;
				var height = $(cropImages[i]).height; 
				var offsetX = width / 4;
				var offsetY = height / 4;
				$(cropImages[i]).wrap('div', { 'class': 'crop', "style" : "background-image: url(" + src + "); background-position: center center;"});
				$(cropImages[i]).wrap('a', { 'class': 'lightview', 'rel': 'gallery[' + id + ']', 'href': src});
				$(cropImages[i]).src = "images/transparent.png";
				//$(cropImages[i]).style.left = "-" + offsetX + "px";
				//$(cropImages[i]).style.top = "-" + offsetY + "px";
			}
		}
		
		if(this.commentContainer != "")
			new Ajax.Updater(this.commentContainer, "AJAX/fetch_comments.lasso", {parameters: {"Post_ID" : this.posts[id].id}, evalScripts: true});
		
		if(onSmartphone)
			this.blogScroller = new TouchScroll($(this.prefix + '-post-content'), {elastic: true});

	},
/*	
	updateBodyHeight: function(){
		titleHeight = $('blog-post-title').getHeight();			// just added these
		var newHeight = 560 - titleHeight;				
		$('blog-post-content').style.height = newHeight+'px';	
	},
*/	
	setFilter: function(param){
		if(param == 'search'){
			this.filters.search = $(this.searchField).value;
		}
		if(param == 'tag'){
			//alert(this.tagField);
			this.filters.tagged = $(this.tagField).value;
		}
		this.updateListing();	
	},
	
	updateListing: function(){
		var query = "";
		if(this.filters.tagged != "")
			query += "tagged=" + this.filters.tagged;
		if(this.filters.search != ''){
			if(query != '')
				query += "&";
			query += "search=" + this.filters.search;
		}
		//alert(query);
	
		this.cursor = 0;
		this.posts = [];
		this.totalPosts = [];	
		this.getTumbleLog(query);
	},
	
	earlier: function(){
		if((this.cursor + 1) < this.totalPosts){
			if((this.cursor +1) < this.posts.length){
				this.loadPost(this.cursor + 1);
			}
			else{  // we need to download more posts from tumblr via ajax
			
			}
			this.cursor++;
			this.updateArrows();
		}
	},
	
	later: function(){
		if((this.cursor - 1) >= 0){
			this.loadPost(this.cursor - 1);
			this.cursor--;
			this.updateArrows();
		}
	},
	
	goToPost: function(index){
		if((index <= 0) || (index > this.totalPosts)){
			$('blog-index').value = "";
			return false;
		}
		if(index <= this.posts.length){
			this.cursor = index - 1;
			this.loadPost(this.cursor);
		}
		else{
			alert("we'll need to load this post via ajax");
		}	
		//two cases - either the page is already cached in the tumblelog posts array, or it needs to be downloaded.
		//in former case, easy enough
		//in latter case, need to download the actual blog post using the api. next and previous buttons work as usual, recursively calling gotopost
		this.updateArrows();
		return false;
	},
	
	updateArrows: function(){
		if((this.cursor == 0) && (this.totalPosts == 1)){
			$(this.earlierButton).writeAttribute({"class" : "slide_navigator_disabled"});
			$(this.laterButton).writeAttribute({"class" : "slide_navigator_disabled"});	
			return;	
		}
		if(this.cursor == 0){	//at most recent [index 0]
			$(this.earlierButton).writeAttribute({"class" : "slide_navigator_enabled"});
			$(this.laterButton).writeAttribute({"class" : "slide_navigator_disabled"});
		}
		else if(this.cursor == (this.posts.length - 1)){	// at earliest post [index n]
			$(this.earlierButton).writeAttribute({"class" : "slide_navigator_disabled"});
			$(this.laterButton).writeAttribute({"class" : "slide_navigator_enabled"});
		}
		else{	//anywhere else
			$(this.laterButton).writeAttribute({"class" : "slide_navigator_enabled"});
			$(this.earlierButton).writeAttribute({"class" : "slide_navigator_enabled"});
		}
	},
	
	finalizeTagList: function(){
		for(i=0; i<this.allTags.length; i++){
			this.tagCount[this.allTags[i]] = (this.tagCount[this.allTags[i]] ? this.tagCount[this.allTags[i]] + 1 : 1);
		}
		for(var n in this.tagCount){
			this.sortedTags[this.sortedTags.length] = new Object();
			this.sortedTags[this.sortedTags.length - 1][n] = this.tagCount[n];
		}
		this.sortedTags.sort(function(a,b){if((Object.values(a))[0] > (Object.values(b))[0]) return -1; else return 1;});
		$(this.prefix + '-filter-tag').update().insert("<option value=''>All categories</option>");
		for(i=0; (i<10) && (i<this.sortedTags.length); i++)
			$(this.prefix + '-filter-tag').insert("<option value=\"" + Object.keys(this.sortedTags[i])[0] + "\">" + Object.keys(this.sortedTags[i])[0] + "</option>");
		$(this.prefix + '-filter-tag').down(0).writeAttribute({"selected" : "selected"});
		this.tagsLoaded = true;
	},
	
	postBlogComment: function(){
		if($('blog_comment_email').value == ""){
			$('blog_comment_email').focus();
			return false;
		}
		if($('blog_comment_name').value == "")
			$('blog_comment_name').value = 'Anonymous';
		commentQuery = $('blog_comment').serialize();
		ID = this.posts[this.cursor].id;
		commentQuery += "&Post_ID=" + ID;
		this.commentPoster.update(commentQuery);
	
		//validation code here
	
		return false;
	}	

});


blogController = new Blog({prefix: "blog", comments: true});
productController = new Blog({prefix: "product", comments: false});
