(function(){var startTag=/^<([-A-Za-z0-9_]+)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/,endTag=/^<\/([-A-Za-z0-9_]+)[^>]*>/,attr=/([-A-Za-z0-9_]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g;var empty=makeMap("area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed");var block=makeMap("address,applet,blockquote,button,center,dd,del,dir,div,dl,dt,fieldset,form,frameset,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul");var inline=makeMap("a,abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var");var closeSelf=makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");var fillAttrs=makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");var special=makeMap("script,style");var HTMLParser=this.HTMLParser=function(html,handler){var index,chars,match,stack=[],last=html;stack.last=function(){return this[this.length-1]};while(html){chars=true;if(!stack.last()||!special[stack.last()]){if(html.indexOf("<!--")==0){index=html.indexOf("-->");if(index>=0){if(handler.comment)handler.comment(html.substring(4,index));html=html.substring(index+3);chars=false}}else if(html.indexOf("</")==0){match=html.match(endTag);if(match){html=html.substring(match[0].length);match[0].replace(endTag,parseEndTag);chars=false}}else if(html.indexOf("<")==0){match=html.match(startTag);if(match){html=html.substring(match[0].length);match[0].replace(startTag,parseStartTag);chars=false}}if(chars){index=html.indexOf("<");var text=index<0?html:html.substring(0,index);html=index<0?"":html.substring(index);if(handler.chars)handler.chars(text)}}else{html=html.replace(new RegExp("(.*)<\/"+stack.last()+"[^>]*>"),function(all,text){text=text.replace(/<!--(.*?)-->/g,"$1").replace(/<!\[CDATA\[(.*?)]]>/g,"$1");if(handler.chars)handler.chars(text);return""});parseEndTag("",stack.last())}if(html==last)throw"Parse Error: "+html;last=html}parseEndTag();function parseStartTag(tag,tagName,rest,unary){if(block[tagName]){while(stack.last()&&inline[stack.last()]){parseEndTag("",stack.last())}}if(closeSelf[tagName]&&stack.last()==tagName){parseEndTag("",tagName)}unary=empty[tagName]||!!unary;if(!unary)stack.push(tagName);if(handler.start){var attrs=[];rest.replace(attr,function(match,name){var value=arguments[2]?arguments[2]:arguments[3]?arguments[3]:arguments[4]?arguments[4]:fillAttrs[name]?name:"";attrs.push({name:name,value:value,escaped:value.replace(/(^|[^\\])"/g,'$1\\\"')})});if(handler.start)handler.start(tagName,attrs,unary)}}function parseEndTag(tag,tagName){if(!tagName)var pos=0;else for(var pos=stack.length-1;pos>=0;pos--)if(stack[pos]==tagName)break;if(pos>=0){for(var i=stack.length-1;i>=pos;i--)if(handler.end)handler.end(stack[i]);stack.length=pos}}};this.HTMLtoXML=function(html){var results="";HTMLParser(html,{start:function(tag,attrs,unary){results+="<"+tag;for(var i=0;i<attrs.length;i++)results+=" "+attrs[i].name+'="'+attrs[i].escaped+'"';results+=(unary?"/":"")+">"},end:function(tag){results+="</"+tag+">"},chars:function(text){results+=text},comment:function(text){results+="<!--"+text+"-->"}});return results};this.HTMLtoDOM=function(html,doc){var one=makeMap("html,head,body,title");var structure={link:"head",base:"head"};if(!doc){if(typeof DOMDocument!="undefined")doc=new DOMDocument();else if(typeof document!="undefined"&&document.implementation&&document.implementation.createDocument)doc=document.implementation.createDocument("","",null);else if(typeof ActiveX!="undefined")doc=new ActiveXObject("Msxml.DOMDocument")}else doc=doc.ownerDocument||doc.getOwnerDocument&&doc.getOwnerDocument()||doc;var elems=[],documentElement=doc.documentElement||doc.getDocumentElement&&doc.getDocumentElement();if(!documentElement&&doc.createElement)(function(){var html=doc.createElement("html");var head=doc.createElement("head");head.appendChild(doc.createElement("title"));html.appendChild(head);html.appendChild(doc.createElement("body"));doc.appendChild(html)})();if(doc.getElementsByTagName)for(var i in one)one[i]=doc.getElementsByTagName(i)[0];var curParentNode=one.body;HTMLParser(html,{start:function(tagName,attrs,unary){if(one[tagName]){curParentNode=one[tagName];return}var elem=doc.createElement(tagName);for(var attr in attrs)elem.setAttribute(attrs[attr].name,attrs[attr].value);if(structure[tagName]&&typeof one[structure[tagName]]!="boolean")one[structure[tagName]].appendChild(elem);else if(curParentNode&&curParentNode.appendChild)curParentNode.appendChild(elem);if(!unary){elems.push(elem);curParentNode=elem}},end:function(tag){elems.length-=1;curParentNode=elems[elems.length-1]},chars:function(text){curParentNode.appendChild(doc.createTextNode(text))},comment:function(text){}});return doc};function makeMap(str){var obj={},items=str.split(",");for(var i=0;i<items.length;i++)obj[items[i]]=true;return obj}})();

function clear_form(form_id){
    $(':input','#'+form_id)
        .not(':button, :submit, :reset, :hidden')
        .val('')
        .removeAttr('checked')
        .removeAttr('selected');
}
 
function limitText(limitField, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
        alert("You have reached the character limit (400) for this field.")
	}
}

function update_count(count_id, inc){
    var count_str = $("#count_"+count_id).html();
    var count_arr = count_str.split(" ");
    var count = parseInt(count_arr[0]);
    count = count + inc;
    var c = count==1 ? " Comment" : " Comments";
    $("#count_"+count_id).html(count+c);
    return count;
}


 
 
 BTRAV.BTComments = {
    allCommentsObj: [],
	totalCommentsCount: 0,
    editorsList: 'jessholl,laura.buckley,LauraMichonski,Sean',    
	showCommentCount: 20,
	curCommentCount: 0,
	curTopLevel: 0,
    curSubLevel: 0,
    replyMargin : 45,
    commentId : "test401",
    defaultText : 'Comment: (you may use HTML tags for style)'
 }
 

 
  
 BTRAV.BTComments.commentInfoPopUp = function() {         
            $("#postcommentinfo").CreateBubblePopup({
            position : 'right',
            align	 : 'center',
            innerHtml: '<div id="postcommenttext"><div class="comment-info">We encourage users to analyze, comment on, and even challenge the articles, blogs, reviews, and multimedia features of BudgetTravel.com.<p></p>User reviews and comments that include profanity or personal attacks or other inappropriate comments or material will be removed from the site. Additionally, entries that are unsigned or contain "signatures" by someone other than the actual author will be removed. Finally, we will take steps to block users who violate any of our posting standards, terms of use or privacy policies or any other policies governing this site. Please review the full rules governing commentaries and discussions.</div></div>',
            themeName: 'none', 
            themePath: 'http://www.budgettravel.com/site_media/img/jquerybubblepopup-theme', 
            selectable: true,
            alwaysVisible: false,
            openingSpeed: 100,
            closingSpeed: 100
     
            });
    } 
    
 BTRAV.BTComments.validateForm = function($thisForm) {        
        var $this_form = $thisForm;         
        var username = '';
        var useremail = '';
        if (typeof(BTRAV.user) != "undefined" && BTRAV.user.username != "") {
            username = BTRAV.user.username;
            useremail = "dummy@dummy.com"; /** will auto replace by user email **/
        } else {
            username = $(".user_full_name",$this_form).val(); 
            useremail = $(".user_email",$this_form).val();
            if (username.trim() == '' || username.trim() == 'Name') { 
                alert("Please enter your name");  $(".user_full_name",$this_form).focus(); return false;
            }
            
            if (useremail.length < 5 || BTRAV.validEmail(useremail) == false) { 
                alert("Please enter a valid e-mail"); $(".user_email",$this_form).focus();  return false; 
            }
        }        
        var commentText = $(".commentText",$this_form).val();  
        if (commentText.trim().length < 3 || commentText.trim() == BTRAV.BTComments.defaultText) { 
            if (commentText.trim().length > 400) {
                alert("Please limit your comment to 400 characters"); $(".commentText",$this_form).focus(); return false;
            } else {
                alert("Please enter your comment"); $(".commentText",$this_form).focus(); return false;
            }
        }
        return true;
}
 
BTRAV.BTComments.initForm = function() {
    $(".user_full_name,.user_email","#new-comments").live("click",function() { $(this).val('');})
    $(".commentText").live("focus", function(){  if ( $(this).val().trim() == BTRAV.BTComments.defaultText ) {  $(this).val('');} });   
    $("#blogstyle").live('click',function(e) { e.preventDefault(); $(".comment-container","#new-comments").toggleClass("blogstyle");  } );
	$(".loadmorecomments","#new-comments").live('click',function(e) {  
		e.preventDefault(); 
		$(this).remove();  			
		BTRAV.BTComments.loadMoreComments(); 
		
	});
	
    $(".comment-form-submit","#new-comments").live("click",function(e) {
        e.preventDefault();    
            var $thisForm = $(this).parent().parent().parent();
            if ( BTRAV.BTComments.validateForm($thisForm)) {
                $thisForm.css("visibility","hidden");
                $postcommentAjax = $(".post-comment-ajax",$thisForm.parent());
                $postcommentAjax.find(".comments-ajax-load-text").text("Posting your comment.").end().show();                                 
                $thisForm.find("textarea").val(HTMLtoXML($thisForm.find("textarea").val().replace(/<script/gi,"").replace(/\n\r?/g, '<br />')));
                var form_data = $thisForm.serialize();
                var inreplyTo = $thisForm.find(".in_reply_to").val();
                $.ajax({
                    type: 'POST',
                    url: "/comments/post/" +  BTRAV.BTComments.commentId + "/",
                    data: form_data,
                    success: function(result){
                    if (result.indexOf("success") >= 0){
                        var resultId = "";                   
                        if (result.split(" - ").length > 0) {
                            resultId = parseInt(result.split(" - ")[1]);
                        }
                        
                        if (inreplyTo == "") {
                            inreplyTo = resultId;
                        }                        
                        var username = '';
                        var btUserName = '';
                        try{ username = BTRAV.user.username; btUserName = BTRAV.user.username; }                        
                        catch(err){ username = $(".user_full_name",$thisForm).val();  btUserName = ''; }
                        var $replyBox = $thisForm.parent().parent();
                        if ($replyBox.hasClass("replyBox")) {             
                            var replyBoxMargin = 2; //only 1 level down for now.
                            var commentObj = BTRAV.BTComments.createCommentObj(resultId,username,$(".commentText",$thisForm).val(),'Just Now',replyBoxMargin,inreplyTo,btUserName)
                            var comment = BTRAV.BTComments.displayComment(commentObj);           
                                $replyBox.replaceWith(comment);      
                            
                        } else {
                            var commentObj = BTRAV.BTComments.createCommentObj(resultId,username,$(".commentText",$thisForm).val(),'Just Now',1,inreplyTo,btUserName)
                            var comment = BTRAV.BTComments.displayComment(commentObj);                          
                            $("#comments-container>.headline").after(comment); 
                        }                                         
						 BTRAV.BTComments.updateCommentsCount(1);
                        $postcommentAjax.find(".comments-ajax-load-text").text("Your comment have been posted succesfully. Thank You").end().fadeOut(1500,function() {
                            $thisForm.css("visibility","visible");
                            $(".replyBox","#new-comments").remove();
                            document.commentForm.reset();              
                        });
                    }
                    else{
                        alert(result);
                    }
                }
                });
            } else {
                $(".post-comment-ajax",$thisForm.parent()).hide();
                $thisForm.css("visibility","visible");               
            }
        });
}
 
BTRAV.BTComments.init = function() {
    $(document).ready(function() {
        //BTRAV.BTComments.commentInfoPopUp();
        if ( location.href.indexOf('qa.') >= 0 || location.href.indexOf('qaadmin.') >= 0) {
            BTRAV.BTComments.commentId += '-test';
        }
        
        var postHTML = BTRAV.BTComments.displayCommentBox("","Post a comment");        
        $("#new-comments").html(postHTML);
        BTRAV.BTComments.initForm();
        $("#comments-container").html('<div class="comments-ajax-load-text">Loading comments...</div>');
        BTRAV.BTComments.getComments(BTRAV.BTComments.commentId,"#comments-container");
    });
}

BTRAV.BTComments.displayCommentBox = function(replyId,postHeader) {
    var commentBox = "";
    commentBox += '<div class="headline postcomments" id="postcommentheadline">' +  postHeader + '</div>';    
    commentBox += '<div class="comment-form clearfix">';
    if (typeof(BTRAV.user) != "undefined" &&  BTRAV.user.username != "") {    
        commentBox += '<form action="" class="comment-form loggedIn" name="commentForm">';    
    } else {
        commentBox += '<form action="" class="comment-form" name="commentForm">';    
    }
    commentBox += '<div class="comment-form-left">';    
    commentBox += '<input type="text" name="user_full_name" value="Name" class="text user_full_name" />';    
    commentBox += '<input type="text" name="user_email" value="E-Mail"  class="text user_email" />'; 
    commentBox += '<input type="hidden" name="in_reply_to" value="' + replyId +'" class="in_reply_to" class="text" />';   
    commentBox += '</div>';    
    commentBox += '<div class="comment-form-right">';    
    commentBox += '<textarea name="comment" class="commenttextarea commentText" onKeyDown="limitText(this.form.comment, 400);">Comment: (you may use HTML tags for style)</textarea>';
    commentBox += '<div class="comment-form-actions">';    
    commentBox += '<a href="#" class="button comment-form-submit">Submit Comment</a>';    
    commentBox += '</div> ';     
    commentBox += '</div>';    
    commentBox += '</form>'; 
    commentBox += '<div class="comments-ajax-load post-comment-ajax">'; 
    commentBox += '<div class="comments-ajax-load-text"> Posting your comment.</div>'; 
    commentBox += '</div>'; 
    commentBox += '</div>'; 
    commentBox += '<div id="comments-container"></div>';    
    return commentBox;
    }


BTRAV.BTComments.replyTo = function(replyId,replyUsername,depthPx,replyToId) {
    $(".replyBox","#new-comments").remove();
    var replyBox = '<div id="replyBox" class="replyBox depth' + depthPx + '">';
    replyBox += BTRAV.BTComments.displayCommentBox(replyId, "Replying to " + replyUsername );
    replyBox += '</div>';
    $replyContainerId = $("#comment-" + replyId);
    $replyContainerId.after(replyBox); 
    $("textarea","#replyBox").focus();
}

BTRAV.BTComments.createCommentObj = function(commentId,commentUser,commentText,commentDate,commentDepth,replyToId,btUserName) {
    if (commentDepth > 2) {
        commentDepth = 2;
    }
    
    var editor = "";
    
    if ( btUserName != "" &&  BTRAV.BTComments.editorsList.toLowerCase().indexOf(btUserName.toLowerCase()) >=0 ) {
        editor = "editor";
    }
    
    var commentObj = {
        "commentId": commentId,
        "commentUser" : commentUser,
        "commentText": commentText,
        "commentDate": commentDate,
        "commentDepth": commentDepth,
        "replyToId": replyToId,
        "editor": editor
    }    
    return commentObj;
}

BTRAV.BTComments.displayComment = function(commentObj) {    
    var commentBox = "";
    commentBox += '<div class="comment-container depth' + commentObj.commentDepth + '" id="comment-' + commentObj.commentId + '">';
    commentBox += '<div class="comment-box clearfix">';
    commentBox += '<div class="comment-quote"></div>';
    commentBox += '<div class="comment-text">' + HTMLtoXML(commentObj.commentText) + '</div>';
    commentBox += '<div class="comment-author"><em>by</em> ';
    commentBox += '<span><strong class="' + commentObj.editor + '">' + commentObj.commentUser + '</strong> on ' + commentObj.commentDate +'</span>';    
    commentBox += '<a href="javascript:BTRAV.BTComments.replyTo(' + commentObj.commentId + ',\'' + commentObj.commentUser + '\',' + commentObj.commentDepth + ',' +  commentObj.replyToId + ');" class="replyTo">Reply</a>';
    commentBox += '</div></div></div>';
    return commentBox;
}

 BTRAV.BTComments.getComments = function(contentId,commentContainerId) {
    var $commentsContainer = $(commentContainerId);
	BTRAV.BTComments.container = $commentsContainer;
   
    $.ajax({
            type: 'GET',
            dataType: 'json',
            url: '/comments/get/'+contentId+'/',
            success: function(results){
			    BTRAV.BTComments.totalCommentsCount = results.length;
				if ( BTRAV.BTComments.totalCommentsCount < BTRAV.BTComments.showCommentCount ) {
					BTRAV.BTComments.showCommentCount = BTRAV.BTComments.totalCommentsCount;
				}                
                var commentsHTML = "";
				commentsHTML += '<div class="headline" id="count_' + contentId +'"></div>';
				
                for (var i=0; i<results.length; i++) {
                    var cDateTime = new Date(results[i].fields.create_date.replace(/-/g," "));
                    var commentObj = BTRAV.BTComments.createCommentObj(results[i].pk,results[i].fields.user_full_name,results[i].fields.comment,cDateTime.toString("MMMM dd, yyyy, h:mm tt"),results[i].fields.depth,results[i].fields.path[0],results[i].fields.bt_user);
                    
                    if (results[i].fields.depth == 1) {
                        var curCommentObj = {};                                          
                        curCommentObj.topLevel = commentObj;
                        curCommentObj.subLevel = [];
                        BTRAV.BTComments.allCommentsObj.push(curCommentObj);                          
                    } else {
                        BTRAV.BTComments.allCommentsObj[BTRAV.BTComments.allCommentsObj.length - 1].subLevel.push(commentObj);
                    }
                }
                
                
                BTRAV.BTComments.allCommentsObj = BTRAV.BTComments.allCommentsObj.reverse();				
				commentsHTML += BTRAV.BTComments.loadComments();                
                $commentsContainer.html(commentsHTML);    
				BTRAV.BTComments.updateCommentsCount(0);					   
            }    
        });
}

 BTRAV.BTComments.updateCommentsCount = function(n) {
	var $countsId = $("#count_"+ BTRAV.BTComments.commentId);
	BTRAV.BTComments.totalCommentsCount += n;
	BTRAV.BTComments.curCommentCount += n;
	var c = (BTRAV.BTComments.totalCommentsCount == 1) ? " Comment" : " Comments";
	if (BTRAV.BTComments.totalCommentsCount > BTRAV.BTComments.showCommentCount ) {
		 c = "Showing " + BTRAV.BTComments.curCommentCount + " of " + BTRAV.BTComments.totalCommentsCount + c;
		 $countsId.html(c);
	} else {	
		$countsId.html(BTRAV.BTComments.totalCommentsCount + c);
	}
    
	$("#commentsbar").html('<a href="#new-comments">comments (' + BTRAV.BTComments.totalCommentsCount + ')</a>');
							
 }
 
 

BTRAV.BTComments.loadComments = function() {
	var commentsHTML = "";
	var i = BTRAV.BTComments.curTopLevel;
	var endedComment = 0;
	var commentCount = 0;
	while (commentCount < BTRAV.BTComments.showCommentCount && i < BTRAV.BTComments.allCommentsObj.length) {
		if (BTRAV.BTComments.curSubLevel == 0) {
            commentsHTML +=  BTRAV.BTComments.displayComment(BTRAV.BTComments.allCommentsObj[i].topLevel);                
            commentCount++;
        }
		var subLevelObj = BTRAV.BTComments.allCommentsObj[i].subLevel;        
        if (commentCount >= BTRAV.BTComments.showCommentCount && subLevelObj.length > 0 ){ 
            BTRAV.BTComments.curSubLevel = -1;
        } else {    
            var n = BTRAV.BTComments.curSubLevel;
            if (n < 0) {n = 0;}            
            while (n < subLevelObj.length) {
                commentsHTML +=  BTRAV.BTComments.displayComment(subLevelObj[n]);
                commentCount++;
                if (commentCount >= BTRAV.BTComments.showCommentCount) {
                    BTRAV.BTComments.curSubLevel = n + 1;
                    n = subLevelObj.length;                      
                } else {
                    BTRAV.BTComments.curSubLevel = 0;
                }
                n++;
            } 
        }        
        if (commentCount < BTRAV.BTComments.showCommentCount || BTRAV.BTComments.curSubLevel == 0) {
            i++;
            BTRAV.BTComments.curSubLevel = 0;
        }
	}	

	BTRAV.BTComments.curTopLevel = i;
	BTRAV.BTComments.curCommentCount += commentCount;
	if (BTRAV.BTComments.curCommentCount < BTRAV.BTComments.totalCommentsCount) {
		commentsHTML += '<div class="showmorecomments"><a href="#" class="button loadmorecomments">Load more comments</a></div>';
	} else {
        BTRAV.BTComments.curCommentCount = BTRAV.BTComments.totalCommentsCount;
    }
		
    return commentsHTML;
  
}

 BTRAV.BTComments.loadMoreComments = function() {
	var commentsHTML = BTRAV.BTComments.loadComments();
	$(".showmorecomments", "#new-comments").remove();	
	BTRAV.BTComments.container.append(commentsHTML);
	BTRAV.BTComments.updateCommentsCount(0);
 }
 

