var BlogViewer = function(options) {
	this.instanceName = false;
	this.is_alive = true;
	this.type = 'industry_standard';
	this.cat_id = 7;
	this.limit = 2;
	this.comment_length_limit = 140;
	this.at = 0;
	this.share = true;
	this.display_date = true;
	this.blog_selector_position = 'top';
	this.constrain_height = false;
	this.constrain_element = null;
	
	jQ.extend(true, this, options);
	
	this.limit = parseInt(this.limit);
	this.comment_length_limit = parseInt(this.comment_length_limit);
	this.constrain_height = (this.constrain_height) ? parseInt(this.constrain_height) : false;
	
	//check for string booleans from editor
	for (var i in this) {
		if (this[i] === 'true') {
			this[i] = true; 
		} else if (this[i] === 'false') {
			this[i] = false;
		} else {
			if (typeof(this[i]) == 'object') {
				for (var j in this[i]) {
					if (this[i][j] === 'true') {
						this[i][j] = true;
					} else if (this[i][j] === 'false') {
						this[i][j] = false;
					}
				}
			}
		}
	}
	
	/*
	var error = 'Product Viewer missing required parameters:\n';
	if (!this.instanceName) error += 'container\n';
	if (error != 'Product Viewer missing required parameters:\n') {
		alert(error);
		return;
	}
	*/
	
	this.container = jQ('#'+this.instanceName+'_container');

	if (!this.cat_id) {
		this.no_list_error();
		return;
	}
	
	this.get_markup();
}

BlogViewer.prototype.get_markup = function(post_data) {
	
	//check for specific post request
	var post_id = null;
	if (window.location.hash) {
		var slug = window.location.hash.replace('#','').split('~')[0];
		if (slug) post_data = { slug: slug };
	}
	
	var BV = this;
	
	var data = { module: 'blog', action: 'get_object', user_id: userId, cat_id: this.cat_id, 'max': this.limit, type: this.type, format: 'html', id: post_id, at: null, share: this.share, display_date: this.display_date, blogSelectorPosition: this.blog_selector_position };
	
	if (typeof(post_data) != 'undefined') jQ.extend(true, data, post_data);
	
	ONAPI.request({
		data: data,
		callback: function(data) {
			if (typeof(BV.container.get(0)) != 'undefined') {
				BV.container.get(0).blogViewer = BV;
				BV.container.html(data);
				BV.get_blogs_from_markup();
				BV.constrainHeight();
				window.scrollBy(0,0);
			}
		},
		error: function(data) {
			setTimeout(BV.load_error, 5000);
		}
	});
}

BlogViewer.prototype.load_error = function() {
	cb.console('load_error');
	this.container.html('<h1>Error Loading Blog</h1>');
}

BlogViewer.prototype.get_blogs_from_markup = function() {
	this.posts = {};
	var BV = this;
	
	var blog_posts = (this.container.find('#blog > ul > li').length) ? '#blog > ul > li' : '#blog .post_list_wrap .post_list li';
	this.container.find(blog_posts).each(function() {
		var id = this.id.split('_')[1];
		var slug = this.id.split('_')[2];
		jQ('#blogPostTitle_'+id).click(function() { BV.go_to_post(slug); });
		jQ('#blogPostCommentCount_'+id).add('#commentCountBottom_'+id).click(function() { BV.go_to_comments(slug); });
	});
	
	jQ('#showAllPosts').unbind('click').click(function() {
		window.location.hash = '#';
		BV.at = 0;
		BV.get_markup();
	});
	
	jQ('.show_older_posts').unbind('click').click(function() {
		BV.at += BV.limit;
		BV.get_markup({ at: BV.at });
	});
	
	jQ('.show_newer_posts').unbind('click').click(function() {
		if (BV.at >= 1) {
			BV.at -= BV.limit;
			BV.get_markup({ at: BV.at });
		}
	});
	
	jQ('#blog_yearSelector > li').unbind('click').click(function() {
		BV.get_markup({ year: this.innerHTML });
		jQ('html, body').animate({scrollTop:0}, 'slow');
	});

	jQ('#blog_yearSelector > .available_year').unbind('click').click(function() {
		BV.get_markup({ year: this.innerHTML });
		jQ('html, body').animate({scrollTop:0}, 'slow');
	});
	
	jQ('#blog_monthSelector > .available_month').unbind('click').click(function() {
		BV.get_markup({ month: this.innerHTML });
		jQ('html, body').animate({scrollTop:0}, 'slow');
	});
	
	jQ('.post_button').unbind('click').click(function() {
		var id = this.id.split('_')[1];
		BV.submit_comment(id);
	});
	
	jQ('.makeComment > textarea').unbind('keyup').keyup(function(e) {
		var charlimit = jQ(this).parent().find('.character_limit').text(BV.comment_length_limit - this.value.length);
		if (this.value.length > BV.comment_length_limit) {
			jQ(charlimit).addClass('comment_limit_exceeded');
		} else {
			jQ(charlimit).removeClass('comment_limit_exceeded');
		}
	});
	
	this.constrain_element_height = jQ(this.constrain_element).css('overflow','visible').height();
	jQ(this.constrain_element).css('overflow','hidden');
	
	if (window.location.hash.match('~comments')) {
		var pos = jQ('.blogPostComments:first').offset().top;
		window.scrollTo(0, pos);
	}
}

BlogViewer.prototype.go_to_post = function(slug) {
	window.location.hash = slug;
	this.get_markup({ slug: slug });
}

BlogViewer.prototype.go_to_comments = function(slug) {
	window.location.hash = slug+'~comments';
	this.get_markup();
}

BlogViewer.prototype.submit_comment = function(id) {
	var title = jQ('#title_'+id).val();
	var comment = jQ('#text_'+id).val();
	comment = comment.substr(0, this.comment_length_limit);
	var BV = this;
	ONAPI.request({
		data: { module: 'blog', action: 'add_comment', user_id: userId, id: id, title : title, text: comment },
		callback: function(data) {
			jQ('#blogPostMakeComment_'+id).html('Thank you for your comment. It will be displayed based on comment configuration.');
		},
		error: function(data) {
			jQ('#blogPostMakeComment_'+id).prepend('There was a problem submitting your message.');
		}
	});
}

BlogViewer.prototype.constrainHeight = function() {
	if (!this.constrain_height) return;

	var parent = jQ(this.constrain_element).css({'overflow':'hidden'}).parent();
	parent.prepend('<div class="blog_scroll blog_scrolltop">top</div><div class="blog_scroll blog_scrollup">up</div><div class="blog_scroll blog_scrolldown">down</div><div class="blog_scroll blog_scrollbottom">bottom</div>');
	var BV = this;
	
	if (!parent.children('.blog_scrolltop:visible').length && !parent.children('.blog_scrollbottom:visible').length && !parent.children('.blog_scrollup:visible').length && !parent.children('.blog_scrolldown:visible').length) {
		jQ(this.constrain_element).css({'overflow':'auto'});
	}
	
	parent.children('.blog_scrolltop').mousedown(function() {
		this.keep_scrolling = true;
		BV.scrollup('.blog_scrolltop', 100);
	}).mouseup(function() { this.keep_scrolling = false; });
	
	parent.children('.blog_scrollup').mousedown(function() {
		this.keep_scrolling = true;
		BV.scrollup('.blog_scrollup', 50);
	}).mouseup(function() { this.keep_scrolling = false; });
	
	if (!jQ.browser.msie) {
		parent.children('.blog_scrolltop').add('.blog_scrollup').css('opacity', '0.7').hover(function() {
			/*if (jQ(BV.constrain_element).scrollTop() > 0)*/ jQ(this).css('opacity','1');
		}, function() {
			jQ(this).css('opacity','0.7');
		});
	}
	
	parent.children('.blog_scrolldown').mousedown(function() {
		this.keep_scrolling = true;
		BV.scrolldown('.blog_scrolldown', 50);
	}).mouseup(function() { this.keep_scrolling = false; });
	
	parent.children('.blog_scrollbottom').mousedown(function() {
		this.keep_scrolling = true;
		BV.scrolldown('.blog_scrollbottom', 100);
	}).mouseup(function() { this.keep_scrolling = false; });
	
	if (!jQ.browser.msie) {
		parent.children('.blog_scrollbottom').add('.blog_scrolldown').css('opacity', '0.7').hover(function() {
			/*if (jQ(BV.constrain_element).scrollTop() < BV.constrain_element_height)*/ jQ(this).css('opacity','1');
		}, function() {
			jQ(this).css('opacity','0.7');
		});
	}
}

BlogViewer.prototype.scrollup = function(o, distance) {
	if (jQ(this.constrain_element).siblings(o).get(0).keep_scrolling) {
		var BV = this;
		jQ(this.constrain_element).animate({scrollTop: (jQ(this.constrain_element).scrollTop()-distance)}, 50, 'linear', function() {
			BV.scrollup(o, distance);
		});
	}
}
BlogViewer.prototype.scrolldown = function(o, distance) {
	if (jQ(this.constrain_element).siblings(o).get(0).keep_scrolling) {
		var BV = this;
		jQ(this.constrain_element).animate({scrollTop: (jQ(this.constrain_element).scrollTop()+distance)}, 50, 'linear', function() {
			BV.scrolldown(o, distance);
		});
	}
}

BlogViewer.prototype.no_list_error = function() {
	this.container.html('<h1>No Blog has been chosen to show here.</h1>');
}
