var CommentsLoader = {
    entry_id: 0,
	comment_div: 0,
	load_link_div: 0,
	isBranch: 0,
	isSubtree: 0,
	isWholePage: 0,
	load: function(entry_id, page, reverse, display, parent_comment_id, per_page) {
		if (!this.completed) return;
		this.completed = false;

        this.entry_id = entry_id;
		this.comment_div = (parent_comment_id ? $('comment_children_' + parent_comment_id) : $('comments_' + entry_id));
		this.load_link_div = (parent_comment_id ? $('load_childrens_link_' + parent_comment_id) : 0);
		this.isBranch = 0;
		this.isSubtree = (page < 0);
		this.isWholePage = (parent_comment_id == 0);
		this.showSpinner();
		var co = YAHOO.util.Connect.asyncRequest('GET', '/commentsv3/show_comments.php?entry_id=' + entry_id + '&page=' + page + '&display=' + display + '&reverse=' + reverse + '&comment_id=' + parent_comment_id + '&per_page=' + per_page, this);

		if (CommentPollerV3 && (page == 1)) { // hide new_comment_alert on 1st page refresh
		    CommentPollerV3.hideAlert();
		}
	},
	loadBranch: function(entry_id, page, reverse, display, parent_comment_id) {
		if (!this.completed) return;
		this.completed = false;

		this.comment_div = $('comment_children_' + parent_comment_id);
		this.load_link_div = $('load_branch_link_' + parent_comment_id);
        this.isBranch = 1;
        this.isSubtree = 0;
        this.isWholePage = 0;
		this.showSpinner();
		var co = YAHOO.util.Connect.asyncRequest('GET', '/commentsv3/show_comments.php?entry_id=' + entry_id + '&page=' + page + '&display=' + display + '&reverse=' + reverse + '&comment_id=' + parent_comment_id, this);
	},
	showSpinner: function() {
		spinner = $('comment_spinner_pager');
		target_div = ((this.isBranch || this.isSubtree) ? this.load_link_div : this.comment_div); 
		if ( spinner && target_div ) {
			target_div.innerHTML = spinner.innerHTML;
			return true;
		}
		return false;
	},
	success: function(o) {
		if (this.load_link_div) this.load_link_div.innerHTML = '';
		this.completed = true;

        if (this.isBranch) {
            if (this.load_link_div) this.load_link_div.style.display = 'none';
            if (this.comment_div) this.comment_div.innerHTML += o.responseText;
		}
		else {
            if (this.comment_div) this.comment_div.innerHTML = o.responseText;
	        if (this.isWholePage) setTimeout('window.scrollTo(0,D.getY(\'comments-header\'));', 2000);
		}
		HuffPoUtil.ImageLoader.foldCheck("comments_inner_" + this.entry_id);
	},
	failure: function(o) {
		if (this.comment_div) this.comment_div.innerHTML = "Sorry, we couldn't load comments for some reason. Try reloading the page.";
		this.completed = true;
	},
	completed: true
};

var CommentPollerV3 = {
	check: function(entry_id, first_time)
	{
 		if (urchinTracker)
			urchinTracker('/devy/v3_poll');

//	    if ((last_comment_id > 0)&&(last_comment_id > this.lastCommentId)) { // remember the max comment_id for the entry
//	        this.lastCommentId = last_comment_id;
//	    }

	    if (CommentsLoader.completed) { // try to avoid conflict state
    		if (first_time || !this.openFlag) {
    			var conn = YAHOO.util.Connect.asyncRequest('GET', '/commentsv3/checkNewComments.php?entry_id=' + entry_id, this);
    		}
	    }
		// if the user is logged in, check for new comments every 3 minutes
		if (HuffCookies.getUserName())
		    setTimeout("CommentPollerV3.check(" + entry_id + ", false);", 180000);

	},

	success: function(o)
	{
		// responseText holds the number of new comments and new last comment_id
        var nca = $('new_comment_alert');
        var nca_cnt = $('new_comment_alert_cnt');

		var newCommentCnt = parseInt(o.responseText);

		if (!isNaN(newCommentCnt) && (newCommentCnt > this.lastCommentCnt)) {
		    if (!this.lastCommentCnt) {
		        this.lastCommentCnt = newCommentCnt;
		    }
			else if (!this.openFlag)	{
				nca_cnt.innerHTML = newCommentCnt - this.lastCommentCnt;

				nca.style.bottom = 0;
				nca.style.left = 0;
				HuffPoUtil.show(nca);
				this.openFlag = true;

    			// update the this.lastCommentCnt
    			this.lastCommentCnt = newCommentCnt;
			}
		}
		else {
			this.hideAlert();
		}
	},

	failure: function(o)
	{
		//alert("failure: " + o.responseText);
	},

	hideAlert: function() {
        if (this.openFlag) {
			this.openFlag = false;
            var nca = $('new_comment_alert');
			HuffPoUtil.hide(nca);
        }
	},

	openFlag: false,
	lastCommentCnt: 0
};

var Comments = {
	topicName: '',
	topicDir: '',

    bFacebookConnected: false,
	added_comment_id: 0,
	
	maxWords: 250,

	collapseComment: function(id) {
		$('cmt_txt_wrap_expand_'+id).style.display   = 'inline';
		$('cmt_txt_wrap_collapse_'+id).style.display = 'none';
		$('cmt_txt_wrap_'+id).style.display			 = 'none';
		$('comment_children_'+id).style.display		 = 'none';
	},

	expandComment: function(id) {
		$('cmt_txt_wrap_expand_'+id).style.display   = 'none';
		$('cmt_txt_wrap_collapse_'+id).style.display = 'inline';
		$('cmt_txt_wrap_'+id).style.display			 = 'block';
		$('comment_children_'+id).style.display		 = 'block';
	},

	// returns 0 for okay length or n, where n is the number of words too long
	lengthOkay: function(el) {
		over = 0;
		trimmed = el.value;

		if ( trimmed.match(/\S/) ) {
			trimmed = trimmed.replace(/^[\s._\-*+&?\/\\]+/, '');
			trimmed = trimmed.replace(/[\s._\-*+&?\/\\]$/, '');
		}

		chunkedText = trimmed.split(/[\s._\-*+&?\/\\]+/);

		if (chunkedText.length > this.maxWords)
			return (chunkedText.length - this.maxWords);

		else if (trimmed == '' || !el.value || el.value == '')
			// no text
			return -1;
		else
			// okay
			return 0;
	},

	alertEmpty: function() {
		alert("Your comment is empty. Please type a comment, then click POST again.");
	},

	alertTooLong: function(over) {
		alert("Your comment is too long by " + over + " " + (over == 1 ? 'word' : 'words') + ". The maximum length is " + this.maxWords + " words. Please edit your comment and click POST again.");
	},

	addComment: function(parent_id) {
		if (!this.is_post_completed) return;

	    parent_id_txt = (parent_id ? '_' + parent_id : '_root');

	    txt_el = $('comment_text' + parent_id_txt);
	    if (txt_el.value == txt_el.defaultValue) txt_el.value = '';

		var over = this.lengthOkay(txt_el);
		if (over == 0) {
			this.is_post_completed = false;

		    //$('post_button' + parent_id_txt).disabled = true;
			HuffPoUtil.hide('post_button' + parent_id_txt);
	        D.setStyle('post_spinner' + parent_id_txt, 'display', 'inline');
			YAHOO.util.Connect.setForm('comments_form' + parent_id_txt);
			var co = YAHOO.util.Connect.asyncRequest('POST', '/commentsv3/postComment.php', this);

		} else if (over > 0) {
			this.alertTooLong(over);
		} else if (over < 0)
			this.alertEmpty();
	},

	scrollToComment: function(id) {
		scrollToAnchor('comment_' + id);
	},

	scrollToParent: function(id) {
		this.scrollToComment(id);
		Fat.fade_element('comment_' + id, 30, 1000);
	},

	// callbacks
	success: function(o) {
		splits   = o.responseText.split(':::');
		new_html = splits[0];
		cmt_parent_id = parseInt(splits[1]);
		cmt_id   = parseInt(splits[2]);
		cmt_entry_id = splits[3];
		this.added_comment_id = cmt_id; 
		
		if (cmt_parent_id) {
			// comment is in reply to a parent comment
			var el = $('comment_children_' + cmt_parent_id);
			if ((el==null) || (typeof el == "undefined")) return;

			//if($('post_button_' + cmt_parent_id)) $('post_button_' + cmt_parent_id).disabled = false;
			if($('comment_text_' + cmt_parent_id)) $('comment_text_' + cmt_parent_id).value = '';

			HuffPoUtil.show('post_button_' + cmt_parent_id);
			
	        D.setStyle('post_spinner_' + cmt_parent_id, 'display', 'none');

			HuffPoUtil.hide('reply_' + cmt_parent_id);
			HuffPoUtil.hide('comment_preview_' + cmt_parent_id);
			if ($('reply_ajax_for_' + cmt_parent_id)) $('reply_ajax_for_' + cmt_parent_id).innerHTML = '';

			if (cmt_id) {
    			//Fat.fade_element('comment_children_' + cmt_parent_id);
    			Fat.fade_element('comment_' + cmt_id);

    			el.innerHTML = el.innerHTML + new_html;
			}

			// close preview
			HuffPoUtil.hide('comment_preview_' + cmt_parent_id);

			if (typeof LOTCC != 'undefined') LOTCC.bcpw("act","reply");
		} else {
			// comment is a new root-level comment
			var el = $('comments_inner_' + cmt_entry_id);
			//if($('post_button_root')) $('post_button_root').disabled = false;
			if($('comment_text_root')) $('comment_text_root').value  = '';
			HuffPoUtil.show('post_button_root');
			if($('post_spinner_root')) D.setStyle('post_spinner_root', 'display', 'none');

			if (cmt_id) {
    			Fat.fade_element('comment_' + cmt_id);
    			el.innerHTML = new_html+el.innerHTML;
			}

			// close preview
			HuffPoUtil.hide('comment_preview_root');

			if (typeof LOTCC != 'undefined') LOTCC.bcpw("act","comment");
		}

		this.is_post_completed = true;
		
		var doFacebookPublish = (splits.length > 6);
		if (doFacebookPublish) {
			FbFeedBundleId = splits[6];
			FbFeedTokens = {"entry_title": splits[7], "comment": splits[8], "entry_link": splits[9]};
		    FB.ensureInit(function() {
		    	FB.Connect.showFeedDialog(FbFeedBundleId, FbFeedTokens, null, null, null, FB.RequireConnect.require, function () {if (Comments.added_comment_id) Comments.scrollToComment(Comments.added_comment_id)});
		    });
		}

		if (cmt_id && !doFacebookPublish) this.scrollToComment(cmt_id);
        HuffPoUtil.ImageLoader.foldCheck("comments_inner_" + cmt_entry_id);
		if (!cmt_id) alert(new_html);
	},

	failure: function(o)
	{
		this.is_post_completed = true;
	},

	displayReplyBox: function(comment_id, entry_id, page) {
		comment_id_txt = (comment_id ? comment_id : 'root');
		el = $('reply_ajax_for_' + comment_id_txt);
		el.innerHTML = '<br /><p><img src="/images/v/spinner.gif" alt="loading" /> Loading...</p>';
		var co = YAHOO.util.Connect.asyncRequest('POST', '/commentsv3/commentForm.php', ReplyBoxCallbacks,'entry_id='+entry_id+'&comment_id='+comment_id+'&page='+page+'&topic_name='+this.topicName+'&topic_dir='+this.topicDir);
		return false;
	},

	previewComment: function(comment_id) {
		comment_id_txt = (comment_id ? comment_id : 'root');
		comment_body = $('comment_preview_inner_' + comment_id_txt);
		body_text = $('comment_text_' + comment_id_txt).value;
		re= /<\S[^>]*>/g;
		body_text = body_text.replace(re,"");
		comment_body.innerHTML = body_text.replace( /\r|\n/g, '<br \/>' );

		HuffPoUtil.show('comment_preview_' + comment_id_txt);
	},
    
    onFacebookConnect: function(fb_container_id) {
        if (this.is_facebook_id_saved) return;
        
        var newHTML = 
            '<table border="0"><tr>'
            +'<td>Facebook account: </td>'
            +'<td><fb:name uid="loggedinuser" useyou="false"/></td>'
            +'<td><fb:profile-pic uid="loggedinuser" facebook-logo="true" size="thumb" ></fb:profile-pic></td>'
            +'</tr></table>'
        ;
        fb_container_el = $(fb_container_id);
        if (fb_container_el) fb_container_el.innerHTML = newHTML;
        fb_root_container_el = $('facebook_data_root');
        if (fb_root_container_el) fb_root_container_el.innerHTML = newHTML;

	    FB.ensureInit(function() {
	        FB.XFBML.Host.parseDomTree();
	        
	        // save FacebookId
	        nFaceBookId = FB.Connect.get_loggedInUser();
	        if (nFaceBookId) {
	            YAHOO.util.Connect.asyncRequest('POST', '/commentsv3/_saveFacebookId.php', {
	                success: function(){
	                    Comments.is_facebook_id_saved = true;
	                }
	            }, 'facebook_id=' + nFaceBookId);
	        }
	    });
    },
    
    onFacebookPledge: function(pledgeId, feedBundleId, pledgeText, pledgeLink) {
    	if (!this.is_post_completed) return;
    	this.is_post_completed = false;

		feedTokens = {'pledge': pledgeText, 'pledge_link': pledgeLink};
	    FB.ensureInit(function() {
			FB.Connect.showFeedDialog(feedBundleId, feedTokens, null, null, null, FB.RequireConnect.promptConnect);
	        YAHOO.util.Connect.asyncRequest('GET', '/commentsv3/fb_pledge_gateway.html?user_joined=1&id=' + pledgeId, {
	        	success: function(o){
		        	Comments.is_post_completed = true;
		        },
	            failure: function(o){
	                Comments.is_post_completed = true;
	            }
	        });
	    });
    },

    onFacebookVote: function(feedBundleId, voteText, permalink, title, callback, img_obj, preview_html) {
    	if (!this.is_post_completed) return;
    	this.is_post_completed = false;
		if(typeof(preview_html) != 'undefined'){
            feedTokens = {
                'images'   : img_obj,
                'vote_text': voteText,
                'vote_link': '<a href="' + permalink + '" target="_blank">' + title + '</a>',
                'vote_preview': preview_html
            };
		}
		else{
            feedTokens = {
                'vote_text': voteText,
                'vote_link': '<a href="' + permalink + '" target="_blank">' + title + '</a>'
            };
		}
	    FB.ensureInit(function() {
			FB.Connect.showFeedDialog(feedBundleId, feedTokens, null, null, null, FB.RequireConnect.promptConnect, function(){
		        	   Comments.is_post_completed = true;
		        	   callback();
		           });
	    });
    },

	is_post_completed: true,
    is_facebook_id_saved: false,
    is_facebook_checked: true
};

var Blogger = {
	select_el: 0,
	refresh_el: 0,
	is_completed: true,
	
	getBlogList: function(comment_parent_id, api) {
		if (!this.is_completed) return;

        parent_id_txt = (comment_parent_id ? '_' + comment_parent_id : '_root');
		
		// name and password must be not empty
		var name_el = $(api + '_name' + parent_id_txt);
        var pass_el = $(api + '_password' + parent_id_txt);
		if (!name_el || !name_el.value.length || !pass_el || !pass_el.value.length) {
			alert(api + ' username or password not set');
			return;
		}

        var host_el = $(api + '_host' + parent_id_txt);
		if (host_el && !host_el.value.length) {
            alert(api + ' hostname not set');
            return;
		}
		
        this.is_completed = false;
        this.select_el = $(api + '_titles' + parent_id_txt);

        this.refresh_el = $(api + '_refresh_link' + parent_id_txt);
		if (this.refresh_el) this.refresh_el.innerHTML = '<img border="0" src="/images/v/spinner.gif" alt="loading" />';

        YAHOO.util.Connect.setForm('comments_form' + parent_id_txt);
        var co = YAHOO.util.Connect.asyncRequest('POST', '/commentsv3/' + api + 'BlogList.php', this);
	},
	
    // callbacks
    success: function(o) {
        if (this.select_el) {
            var splits = o.responseText.split(':::');
			var isError = (splits[0] == 'error');
			if (isError) {
                if (this.refresh_el) this.refresh_el.innerHTML = 'refresh list';
				alert('Error: ' + splits[1]);
			} 
            else {
                this.select_el.innerHTML = this.select_el.innerHTML + o.responseText;
                if (this.refresh_el) D.setStyle(this.refresh_el, 'display', 'none');
			}
		}
        this.is_completed = true;
    },

    failure: function(o)
    {
        this.is_completed = true;
		if (this.refresh_el) this.refresh_el.innerHTML = 'refresh list';
    }
};

var ReplyBoxCallbacks = {
	success: function(o) {
		var splits   = o.responseText.split(':::');
		var new_html = splits[0];
		var comment_id = parseInt(splits[1]);

		comment_id_txt = (comment_id ? comment_id : 'root');
		var el = $('reply_ajax_for_' + comment_id_txt);
		el.innerHTML = new_html;
        
        // facebook tags render
	    FB.ensureInit(function() {
	    	FB.XFBML.Host.parseDomTree();
	    	nFacebookId = FB.Connect.get_loggedInUser();
	    	if (nFacebookId && Comments.is_facebook_checked) {
	    		checkBox = $('post_to_facebook_' + comment_id_txt);
	    		if (checkBox) checkBox.checked = true;
	    		fbDiv = $('facebook_data_' + comment_id_txt);
	    		if (fbDiv) fbDiv.style.display = 'block';
	    	}
	    });
	}
};

/*----------------------------------------------------------------------*/

// @name      The Fade Anything Technique
// @namespace http://www.axentric.com/aside/fat/
// @version   1.0-RC1
// @author    Adam Michela
// @name      The Fade Anything Technique
// @namespace http://www.axentric.com/aside/fat/
// @version   1.0-RC1
// @author    Adam Michela

var Fat = {
	make_hex : function (r,g,b) {
		r = r.toString(16); if (r.length == 1) r = '0' + r;
		g = g.toString(16); if (g.length == 1) g = '0' + g;
		b = b.toString(16); if (b.length == 1) b = '0' + b;
		return "#" + r + g + b;
	},
	fade_all : function () {
		var a = document.getElementsByTagName("*");
		for (var i = 0; i < a.length; i++) {
			var o = a[i];
			var r = /fade-?(\w{3,6})?/.exec(o.className);
			if (r) {
				if (!r[1]) r[1] = "";
				if (o.id) Fat.fade_element(o.id,null,null,"#"+r[1]);
			}
		}
	},
	fade_element : function (id, fps, duration, from, to) {
		if (!fps) fps = 30;
		if (!duration) duration = 3000;
		if (!from || from=="#") from = "#FFFF33";
		if (!to) to = this.get_bgcolor(id);

		var frames = Math.round(fps * (duration / 1000));
		var interval = duration / frames;
		var delay = interval;
		var frame = 0;

		if (from.length < 7) from += from.substr(1,3);
		if (to.length < 7) to += to.substr(1,3);

		var rf = parseInt(from.substr(1,2),16);
		var gf = parseInt(from.substr(3,2),16);
		var bf = parseInt(from.substr(5,2),16);
		var rt = parseInt(to.substr(1,2),16);
		var gt = parseInt(to.substr(3,2),16);
		var bt = parseInt(to.substr(5,2),16);

		var r,g,b,h;
		while (frame < frames) {
			r = Math.floor(rf * ((frames-frame)/frames) + rt * (frame/frames));
			g = Math.floor(gf * ((frames-frame)/frames) + gt * (frame/frames));
			b = Math.floor(bf * ((frames-frame)/frames) + bt * (frame/frames));
			h = this.make_hex(r,g,b);

			setTimeout("Fat.set_bgcolor('"+id+"','"+h+"')", delay);

			frame++;
			delay = interval * frame;
		}
		setTimeout("Fat.set_bgcolor('"+id+"','"+to+"')", delay);
	},
	set_bgcolor : function (id, c) {
		var o = document.getElementById(id);
		o.style.backgroundColor = c;
	},
	get_bgcolor : function (id) {
		var o = document.getElementById(id);
		while(o) {
			var c;
			if (window.getComputedStyle) c = window.getComputedStyle(o,null).getPropertyValue("background-color");
			if (o.currentStyle) c = o.currentStyle.backgroundColor;
			if ((c != "" && c != "transparent") || o.tagName == "BODY") { break; }
			o = o.parentNode;
		}
		if (c == undefined || c == "" || c == "transparent") c = "#FFFFFF";
		var rgb = c.match(/rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/);
		if (rgb) c = this.make_hex(parseInt(rgb[1]),parseInt(rgb[2]),parseInt(rgb[3]));
		return c;
	}
};



/*----------------------------------------------------------------------*/
/* scroll functions from and (c) brandspankingnew
http://www.brandspankingnew.net/archive/2005/09/animated_anchor.html */
/*----------------------------------------------------------------------*/

/*
SCROLL FUNCTIONS
*/

var scrollInt;
var scrTime, scrSt, scrDist, scrDur, scrInt;

function scrollPage() {
	scrTime += scrInt;
	if (scrTime < scrDur) {
		window.scrollTo( 0, easeInOut(scrTime,scrSt,scrDist,scrDur) );
	}else{
		window.scrollTo( 0, scrSt+scrDist );
		clearInterval(scrollInt);
	}
}

// modified from original; now looks for div#some_id
function scrollToAnchor(aname) {
	var anchors, i, ele;

	if (!document.getElementById)
		return;

	// get anchor
	anchors = document.getElementsByTagName("div");
	for (i=0;i<anchors.length;i++) {
		if (anchors[i].id == aname) {
			ele = anchors[i];
			i = anchors.length;
		}
	}

	// set scroll target
	if (window.scrollY)
		scrSt = window.scrollY;
	else if (document.documentElement.scrollTop)
		scrSt = document.documentElement.scrollTop;
	else
		scrSt = document.body.scrollTop;

	scrDist = ele.offsetTop - scrSt;
	scrDur = 100;
	scrTime = 0;
	scrInt = 10;

	// set interval
	clearInterval(scrollInt);
	scrollInt = setInterval( scrollPage, scrInt );
}

/*
EASING FUNCTIONS
*/

function easeInOut(t,b,c,d) {
	return c/2 * (1 - Math.cos(Math.PI*t/d)) + b;
}

