var sixApart_atpComments_loaded = 0;
var isAdvanced = 0;
var commentPreview;

function prepareAtpComments(form){
    if(document.addEventListener){
        if( !isAdvanced && !registrationRequired ){
            form.author.addEventListener('focus',startLoader,false);
            if( form.email )
                form.email.addEventListener('focus',startLoader,false);
            if( form.url )
                form.url.addEventListener('focus',startLoader,false);
        }
        form.text.addEventListener('focus',startLoader,false);
    } else if(document.attachEvent){
        if( !isAdvanced && !registrationRequired ){
            form.author.attachEvent('onfocus',startLoader);
            if( form.email )
                form.email.attachEvent('onfocus',startLoader);
            if( form.url )
                form.url.attachEvent('onfocus',startLoader);
        }
        form.text.attachEvent('onfocus',startLoader);        
    }
    if(!isAdvanced) {
        if(document.addEventListener) {
            if( !isAdvanced && !registrationRequired ){
                form.author.addEventListener('focus', commentInputStyling,false);
                form.author.addEventListener('blur', commentInputStyling, false);
                if( form.email ){
                    form.email.addEventListener('focus', commentInputStyling,false);
                    form.email.addEventListener('blur', commentInputStyling, false);                    
                }
                if( form.url ){
                    form.url.addEventListener('focus', commentInputStyling,false);
                    form.url.addEventListener('blur', commentInputStyling, false);                    
                }
            }
            form.text.addEventListener('keyup', commentInputStyling,false);
        } else if(document.attachEvent) {
            if( !isAdvanced && !registrationRequired ){
                form.author.attachEvent('onfocus', commentInputStyling);
                form.author.attachEvent('onblur', commentInputStyling);
                if( form.email ){
                    form.email.attachEvent('onfocus', commentInputStyling);
                    form.email.attachEvent('onblur', commentInputStyling);                    
                }
                if( form.url ){
                    form.url.attachEvent('onfocus', commentInputStyling);
                    form.url.attachEvent('onblur', commentInputStyling);                    
                }
            }
            form.text.attachEvent('onkeyup', commentInputStyling);
        }
    }

    if( commentPreview = document.getElementById('comment-preview-confirmation') )
        if( getStyle(commentPreview,"display") != 'none' )
            addCommentStyles();
}

function addCommentStyles(){
    //advanced templates might not have these styles...
    var comment_style = document.createElement('link');
    comment_style.setAttribute('rel','stylesheet');
    comment_style.href = '/.shared/css/atp-comments.css';
    comment_style.type = 'text/css';
    comment_style.media = 'screen';
    document.getElementsByTagName('head')[0].appendChild(comment_style);    
}

function getStyle(el, property){
    if( el.currentStyle )
        var style = el.currentStyle[ property ];
    else if( window.getComputedStyle )
        var style = window.getComputedStyle( el,null ).getPropertyValue( property );
    return style;
}

function startLoader() {
    if (!sixApart_atpComments_loaded) {
        var loader = new YAHOO.util.YUILoader();
        loader.addModule({
            name: "atpcomments",
            type: "js",
            fullpath: atpCommentsPath
        });
        loader.addModule({
            name: "jsonrpc",
            type: "js",
            fullpath: "/.shared/js/jsonrpc-client.js"       
        });
        loader.require("yahoo-dom-event", "connection", "json", "jsonrpc", "atpcomments");      
        loader.insert({
            onSuccess: function() {
                findCommentFormNum();
                // If advanced template there is injecting/etc to do...
                if(isAdvanced) {
                    // Set the xid for later...
                    xid = getEventXid(commentFormNum); 
                    
                    var newDiv = document.createElement('div');
                    var commentForm = document.forms[commentFormNum];
                    newDiv.innerHTML = injectCode; 
                    YAHOO.util.Dom.insertBefore(newDiv, commentForm);
            
                    commentFormNum = commentFormNum + 2;
                    // Rewrite form to do the new right thing
                    // Hijack preview/submit buttons
                    YAHOO.util.Event.addListener(commentForm, 'submit', function(e){ YAHOO.util.Event.stopEvent( e )} );
                    if( commentForm.preview ){
                        commentForm.preview.setAttribute('onclick','');
                        
                        YAHOO.util.Event.addListener(commentForm.preview, 'click', function(){ atpComments.previewOnly( commentFormNum, 1 ) });
                    }else{
                        YAHOO.util.Dom.getElementsBy( function( el ){
                            if( el.name == 'preview' && el.type == 'image' ){
                                el.type = 'submit';
                                el.disabled = false;
                            }
                        }, 'input', commentForm );                        

                        if( commentForm.preview )
                            YAHOO.util.Event.addListener(commentForm.preview, 'click', function(){ atpComments.previewOnly( commentFormNum, 1 ) });
                    }
                    
                    if( !commentForm.post ){
                        // "image" inputs can't accept event handlers,
                        // so convert them to submit buttons.
                        YAHOO.util.Dom.getElementsBy( function( el ){
                            if( el.name == 'post' && el.type == 'image' ){
                                el.type = 'submit';
                                el.disabled = false;
                            }
                        }, 'input', commentForm );                        

                        // If we still haven't found a "post" button, look
                        // for all of the inputs in the form. If there's only
                        // one input, then assume it's a "post" button.
                        if( !commentForm.post ){
                            var inputs = YAHOO.util.Dom.getElementsBy( function( el ) {
                                return el.type == 'submit' ? true : false;
                            }, 'input', commentForm );
                            if ( inputs.length == 1 )
                                commentForm.post = inputs[ 0 ]; 
                        }
                    }

                    commentForm.post.setAttribute('onclick','');
                    YAHOO.util.Event.addListener(commentForm.post, 'click', function(){ atpComments.interceptPost( commentFormNum ) });

                    // Change form action
                    commentForm.setAttribute('action', '');
                } else {
                    xid = getEventXid(commentFormNum);
                    YAHOO.util.Event.addListener("comment-text", "keyup", atpComments.toggleButtons);
                    YAHOO.util.Event.addListener("comment-author", "keyup", atpComments.toggleButtons);
                    YAHOO.util.Event.addListener("comment-email", "keyup", atpComments.toggleButtons);
                }
                if( commentPreview = document.getElementById('comment-preview-confirmation') )
                    if( getStyle(commentPreview,"display") != 'none' )
                        addCommentStyles();
            }
        });
        sixApart_atpComments_loaded = 1;
    }
}

function commentInputStyling(e) {
    if( !e ) var e = window.event;
    var el;
    if( e.target )
        el = e.target;
    else if( e.srcElement )
        el = e.srcElement;
    var cInput = document.getElementById(el.id);
    if(e.type == 'focus') {
        cInput.className = '';
    } else if((e.type == 'blur') && (el.value == el.getAttribute('at:default'))) {
        cInput.className = 'grayText';
    }       
}

function setCookie (name, value, expires) {
    document.cookie = name + '=' + escape(value) + '; expires=' + expires.toGMTString() + '; domain=' + hostName + '; path=/';
}

function getCookie (name) {
    var key = name + '=';
    var c = document.cookie;
    var i = c.indexOf(key);
    if (i < 0) return '';
    var j = c.indexOf(';', i + key.length);
    if (j < 0) j = c.length;
    return unescape(c.substring(i + key.length, j));
}

function deleteCookie (name) {
    if (getCookie(name))
        setCookie(name, '', new Date(70, 0, 1, 0, 0, 1));
}

function checkLocal()
{
    // See if its already set
    if( typeof commenterName != "undefined" && commenterName )
        return;

    // Look for it in the query string
    var q = window.location.search.substring(1);
    var parms = q.split('&');
    for (var i=0; i<parms.length; i++) {
        var pos = parms[i].indexOf('=');
        if (pos > 0) {
            var key = parms[i].substring(0,pos);

            if (key != "commenter")
                continue;

            commenterName = unescape(parms[i].substring(pos+1));

            if( typeof commenterName == "undefined" || !commenterName ) {
                deleteCookie("commenter");
            } else {
                var now = new Date();
                now.setTime(now.getTime() + 60 * 60 * 1000);
                setCookie("commenter", commenterName, now);
            }
            return;
        }
    }

    // Look for a cookie if its still not set
    commenterName = getCookie("commenter");
}

/* comment registration */	
var showHideElements =
{
	"comments-open-login" : "none",
	"comments-open-logout" : "block",
	"comments-open-data" : "none",
	"comments-open-text" : "block",
	"comments-open-footer" : "block"
};

var showHideRegOptionalElements = {
	"comments-open-login" : "block",
	"comments-open-logout" : "none",
	"comments-open-data" : "block",
	"comments-open-text" : "block",
	"comments-open-footer" : "block"
};

var showHideTkElements =
{
	"comments-open-login" : "block",
	"comments-open-logout" : "none",
	"comments-open-data" : "none",
	"comments-open-text" : "none",
	"comments-open-footer" : "none"
};

function commentSignIn()
{
	if( typeof commenterName == "undefined" || !commenterName || !getCookie("VID")){
	    var cForm = document.forms[commentFormNum];
        if(!cForm)
            return false;
    	var val = getCookie("typepadauthor");
        if( cForm.author && val){
        	cForm.author.value = val;
        	cForm.author.className = '';
        }
        val = getCookie("typepademail");
        if( cForm.email && val){        
        	cForm.email.value = val;
        	cForm.email.className = '';
        }
        val = getCookie("typepadurl");
        if( cForm.url && val){
        	cForm.url.value = val;
        	cForm.url.className = '';
        }
        
        if( registrationRequired ){
        	for( var i in showHideTkElements )
        	{
        		e = document.getElementById( i );
        		if( e )
        			e.style.display = showHideTkElements[ i ];
        	}            
        } else if( registrationOptional ) {
            // If logged out but registration is optional, don't show
            // the logout link, but re-enable the name/email/uri fields
            // for advanced template users who may have the old comments.js.
        	for ( var i in showHideRegOptionalElements ) {
        		e = document.getElementById( i );
        		if( e )
        			e.style.display = showHideRegOptionalElements[ i ];
        	}            
        }
		return;
	}
	
	// insert name
	var e = document.getElementById( "commenter-name" );
	var e2 = document.getElementById( "comment-preview-author" );
	if( e && e2 && getCookie("VID") ) {
		e.innerHTML = commenterName;
		e2.innerHTML = commenterName;
	}
	
	// hide/show various elements
	for( var i in showHideElements )
	{
		e = document.getElementById( i );
		if( e )
			e.style.display = showHideElements[ i ];
	}
}

function findCommentFormNum() {
	for (commentFormNum=0;commentFormNum<document.forms.length;commentFormNum++) {
	    if( document.forms[commentFormNum].id && (document.forms[commentFormNum].id == 'comment-form') ){
	        return commentFormNum;
	        break;
	    }else if( document.forms[commentFormNum].getAttributeNode('action') && document.forms[commentFormNum].getAttributeNode('action').value.match("\/t\/comments$") ){
	        return commentFormNum;
	        break;
	    }
	}
	return -1;
}

function getEventXid(commentFormNum) {
    // Send either xid or id depending on what the form has in it.
    if(document.forms[commentFormNum].entry_xid)
        xid = document.forms[commentFormNum].entry_xid.value;
    else {
        var typePadID = document.forms[commentFormNum].entry_id.value;
        var jsonClient = new TC.JSONRPCClient( jsonURL );
        var method = isPage ? 'Page.LookupByTypepadId' : 'Post.LookupByTypepadId';
        jsonClient.request( {
            method: method,
            params: {
            typepad_id: typePadID
            },
            callback: function( r ) {
                if ( r.error )
                    alert( r.error );
                else
                    xid = r.result;
            }
        } );

    }
    return xid;
}

if( registrationRequired || registrationOptional ){
    if( document.getElementById('comments-open-login') )
        document.getElementById('comments-open-login').style.display = 'block';
    // overriden if you're signed in at commentsignin
}

var commentFormNum;
findCommentFormNum();

checkLocal();
commentSignIn();

if( registrationRequired && (typeof( commenterName ) == "undefined" || !commenterName || !getCookie( 'VID' )) ){
    // we don't want to do anything if registration is required and there's no one logged in 
}else{
    if( document.getElementById('comments-open-text') )
        document.getElementById('comments-open-text').style.display = 'block';
    if( document.getElementById('comments-open-data') ){
        if( !registrationRequired && !registrationOptional ){ // no reg, always show
            document.getElementById('comments-open-data').style.display = 'block';
        }else if( registrationRequired ){
            // reg required, never show
        }else if( registrationOptional ){
            // reg optional, only show if not logged in
            if( (typeof( commenterName ) == "undefined") || !commenterName )
                document.getElementById('comments-open-data').style.display = 'block';
        }
    }
    if( document.getElementById('comments-open-footer') )
        document.getElementById('comments-open-footer').style.display = 'block';

    for (var i=0;i<document.forms.length;i++) {
        if( document.forms[i].getAttributeNode('action') && document.forms[i].getAttributeNode('action').value.match("\/t\/comments$") ) {
            isAdvanced = 1;
            prepareAtpComments(document.forms[i]);
            break;
        }
    }

    if(!isAdvanced && document.getElementById('comment-form') && document.getElementById('comment-form').tagName == 'FORM'){
        prepareAtpComments(document.getElementById('comment-form'));
    }
}
