var RubyMail = new Object();

var Widgets = new Object();
Widgets.OnChange = new Object();

DHTML.createListener( window, 'load' );

var arrowDir = "down";

function swap( img, isrc )
{
  if( !document.images ) return;
  document.images[img].src = isrc;
} // swap()

function toggleLoginBox()
{
    var isSafari = navigator.userAgent.indexOf( 'Safari' ) >= 0 ? true : false;

    dir = document.getElementById( "login-header-dir" );
    box = document.getElementById( "login-header-box" );
    
    if( dir && box )
    {
	// toggle the login box display status
	if( !isSafari )
	    new Effect.toggle( "login-header-box", "blind" );
	
	// swap the image
	if( arrowDir == "up" )
	{
	    dir.src = "/images/login_down.gif";
	    arrowDir = "down";
	    
	    if( isSafari )
		box.style.display = "none";
	}
	else
	{
	    dir.src = "/images/login_up.gif";
	    arrowDir = "up";

	    if( isSafari )
		box.style.display = "block";
	}
    }
} // toggleLoginBox()

function signupForNewsletter( newsletterForm )
{
    var formName = newsletterForm.name;
    var emailId  = formName + '-email';
    var imgId    = formName + '-img';
    var errorsId = formName + '-errors';

    DHTML.hide( errorsId );
    DHTML.changeInnerHTML( errorsId, '' );    

    var img = DHTML.getElement( imgId );
    if( img ) {
	img.src = '/images/ruby_loading_small.gif';
    }
    
    new Ajax.Request( '/ajax/newsletter.xml',
    { 
	parameters : 'email=' + escape( DHTML.getFormValue( emailId, formName ) )
		      + '&action=' + escape( DHTML.getFormValue( 'action', formName ) ),
	    onSuccess : function (req) { processSignupResults( formName, req ) },
	    onFailure : function () { handleSignupError( formName ) }
    }
		      );
        
    return false;	
} // signupForNewsletter()

function processSignupResults( formName, req )
{
    //alert( req.responseText );
    var xml     = req.responseXML;
    var xmlRoot = xml.getElementsByTagName( 'ruby' )[0];
    var success = xmlRoot.getAttribute( 'success' );
    var email   = xmlRoot.getAttribute( 'email' );
    var error   = xmlRoot.getAttribute( 'error' );
    
    var errorsId  = formName + '-errors';
    var formDivId = formName + '-formdiv';
    var formResultsId = formName + '-results';
    var imgId     = formName + '-img';
    
    if( success == 1 ) {
	DHTML.changeInnerHTML(  
			      formResultsId,
			      '<div style="line-height: 12px; color: #fff">'
			      + 'This address has been added:'
	                      + '<div style="font-weight: bold; text-align: center;">'
			      + email + '</div></div>'
			      );
	Element.hide( formDivId );
	Element.show( formResultsId );
    }
    else {
	var img = DHTML.getElement( imgId );
	if( img ) {
	    img.src = '/images/btn_arrow.gif';
	}
	
	DHTML.changeInnerHTML( 
			      errorsId,
			      error
			      );
	DHTML.show( errorsId );
    }
} // processSignupResults

function handleSignupError( formName, req )
{
    //alert( req.responseText );

    var imgId     = formName + '-img';
    var img = DHTML.getElement( imgId );
    if( img ) {
	img.src = '/images/btn_arrow.gif';
    }

    var errorsId  = formName + '-errors';
    DHTML.changeInnerHTML( errorsId, 'please try again in 5 minutes' );
    DHTML.show( errorsId );

} // handleSignupError

function cancelAddComment( formId )
{
    new Effect.BlindUp( 
		       'comment_form_div',
                       { afterFinish : 
			   function() {
			   
			      // Clear any previous error messages
			      var errTags = $A( document.getElementsByClassName( 'error', formId ) );
			      errTags.each( function( err ) { Element.hide( err ); err.innerHTML = '' } );

			      // Clear any data in form
			      Form.reset( 'comment_form' );
		           } // afterFinish
		       }
		      );

    return false;
} // cancelAddComment

function addComment( form_obj, projid, acctid )
{
    // Clear any previous error messages
    var errTags = $A( document.getElementsByClassName( 'error', form_obj ) );
    errTags.each( function( err ) { Element.hide( err ); err.innerHTML = '' } );

    // Get form data
    var params = Form.serialize( form_obj );
    params += '&pid=' + escape( projid ) + '&aid=' + escape( acctid );

    // Formulate a function that gets called when ajax returns
    var successFunc = function(req) { processAddComment( req ); }

    // Submit to ajax
    new Ajax.Request( '/ajax/dms/add_project_comment.xml',
                       {
			   parameters : params,
			   onSuccess  : successFunc
	  	       }
		    );	

    // Don't submit the form
    return false;
} // addComment

function processAddComment( req )
{
    var respXML = req.responseXML;
    //alert( req.responseText );

    var status = respXML.getElementsByTagName( 'ruby' )[0].getAttribute( 'status' );
    //alert( status );

    if( status == 'errors' ) {
	showErrors( respXML, '__', '_err' );
    }
    else if( status == 'success' ) {
	showComment( respXML );
    }
} // processAddComment

function showComment( xml )
{
    // Get new comment data
    var commentData = new Object();
    $A( xml.getElementsByTagName( 'data' ) ).each( 
		   function(node) { commentData[node.getAttribute('key')] = node.getAttribute('value' ) } 
    );
    //alert( commentData );
    
    // Create new comment HTML
    var commentId      = 'comment_' + commentData.id;
    var newCommentHTML = '<div id="' + commentId + '" class="comment user" style="display: none">'
	               +   '<h3>' + commentData.title   + '</h3>'
	               +   '<div>'
	               +     'Posted by '
	               +     '<a href="mailto:' + commentData.posted_by_email + '" class="mailto">' + commentData.posted_by + '</a>'
                       +     ' on ' + commentData.posted_date
                       +   '</div>'
                       +   '<p>'  + commentData.comment + '</p>'
                       + '</div>';

    // Hide an "no commments" text
    var noComments = $( 'no_comments' );
    if( noComments ) {
	Element.hide( noComments );
    }

    // Transition-hide the add comment form
    new Effect.BlindUp(   
		        'comment_form_div',
                        { afterFinish : 

			    // When the transition is complete:
			    function() { 
			     
			      // Reset the form
			      Form.reset( 'comment_form' );

			      // Add the new comment to the list
			      var comments = $( 'comments' );
			      comments.innerHTML = newCommentHTML + comments.innerHTML;
			    
			      // Transition-show the new comment
			      new Effect.BlindDown( commentId,
			                            { afterFinish : 
							function() {
						          // Highlight the new comment
						          new Effect.Highlight( commentId );
						        } 
						    } 
						  );
			     } // after finish func
			 } 
		      ); // BlindUp

    return;
} // showComment

function showErrors( xml, prefix, suffix )
{
    var showErrFunc = function( err ) {
	var params = arguments.callee.params;
	var prefix = params.prefix;
	var suffix = params.suffix;

	var errKey = err.getAttribute( 'key' );
	var error  = err.getAttribute( 'msg' );
	
	var errTag = $( prefix + errKey + suffix );
	if( errTag ) {
	    errTag.innerHTML = error;
	    Element.show( errTag );
	}
    }; // showErrFunc
    showErrFunc.params = { 'prefix' : prefix, 'suffix' : suffix };

    $A( xml.getElementsByTagName( 'error' ) ).each( showErrFunc );
} // showErrors

function showTerms( url )
{
    var wndTerms = window.open( url, 'wndTerms', 'width=850,height=450,location=no,menubar=no,scrollbars=yes,resizable=no,toolbar=no' );
    wndTerms.focus();	
} // showTerms

function sendTestEmail( form_obj, projid )
{
    // Clear any previous error messages
    var errTags = $A( document.getElementsByClassName( 'error', form_obj ) );
    errTags.each( function( err ) { Element.hide( err );err.innerHTML = '' } );

    // Clear any previous results
    var resultsDIV = $( 'previewer-preview-results' );
    Element.hide( resultsDIV );
    resultsDIV.innerHTML = '';

    // Get form data
    var params = Form.serialize( form_obj );
    params += '&pid=' + escape( projid );

    // Formulate a function that gets called when ajax returns
    var successFunc = function(req) { processSendTestEmail( req ); }

    // Submit to ajax
    new Ajax.Request( '/ajax/mail/send_test_email.xml',
                       {
			   parameters : params,
			   onSuccess  : successFunc
	  	       }
		    );	

    // Don't submit the form
    return false;
} // sendTestEmail

function processSendTestEmail( req )
{
    var respXML = req.responseXML;
    //alert( req.responseText );

    var status = respXML.getElementsByTagName( 'ruby' )[0].getAttribute( 'status' );
    //alert( status );

    if( status == 'errors' ) {
	showErrors( respXML, '__', '_err' );
    }
    else if( status == 'success' ) {
	showTestEmailResults( respXML );
    }
} // processAddComment

function showTestEmailResults( xml )
{
    // Clear form
    Form.reset( 'send_test_form' );

    // Get results data
    var resultsData = new Object();
    $A( xml.getElementsByTagName( 'data' ) ).each( 
	       function(node) { resultsData[node.getAttribute('key')] = node.getAttribute('value' ) } 
    );

    var resultsDIV = $( 'previewer-preview-results' );
    resultsDIV.innerHTML = resultsData['msg'];
    
    Element.show( resultsDIV );
    
    return;
} // showTestEmailResults

function previewerShow( tab_to_show )
{
    var tabHTML = document.getElementById( "previewer-nav-tab-html" );
    var tabText = document.getElementById( "previewer-nav-tab-text" );
    var tabSend = document.getElementById( "previewer-nav-tab-send" );
    
    if( tabHTML && tabText && tabSend )
    {
	if( tab_to_show == 'html' )
	{
	    tabHTML.className = 'current';
	    tabText.className = '';
	    tabSend.className = '';

	    DHTML.show( 'previewer-preview-html' );
	    DHTML.hide( 'previewer-preview-text' );
	    DHTML.hide( 'previewer-preview-send' );
	}
	else if( tab_to_show == 'text' )
	{
	    tabHTML.className = '';
	    tabText.className = 'current';
	    tabSend.className = '';

	    DHTML.hide( 'previewer-preview-html' );
	    DHTML.show( 'previewer-preview-text' );
	    DHTML.hide( 'previewer-preview-send' );
	}
	else // if( tab_to_show == 'send' )
	{
	    tabHTML.className = '';
	    tabText.className = '';
	    tabSend.className = 'current';

	    DHTML.hide( 'previewer-preview-html' );
	    DHTML.hide( 'previewer-preview-text' );
	    DHTML.show( 'previewer-preview-send' );
	}
    }
} // previewerShow()

// handle click
function handleClick( numBox )
{
    var o, anchor;
    var effectName, effectOptions;

    effectName = 'slide';

    // change the link label
    o = document.getElementById( 'report-box-' + numBox );
    if( o )
    {
	anchor = document.getElementById( 'report-box-' + numBox + '-expand' );
	if( anchor )
	{
	    if( anchor.innerHTML == "show" )
	    {
	
		o.innerHTML = "Showing...";
	    }
	    else
	    {
		o.innerHTML = "Hiding...";
	    }
	}
    }

    // do the effect toggle
    effectOptions = { afterFinish: expandFinished };
    new Effect.toggle( 'report-box-' + numBox + '-content', 
		       effectName,
		       effectOptions
		       ); 

} // handleClick()

function expandFinished( obj )
{
    var numBox;
    var box;
    var elementName = obj.element.id;
    var controlName;

    // get the box number from the element name
    var parts = elementName.split( /\-/ );
    if( parts )
    {
	numBox = parts[2];

	if( numBox )
	{
	    box = document.getElementById( 'report-box-' + numBox );
	    if( box )
	    {
		if( box.innerHTML == "Showing..." )
		{
		    controlName = "hide";
		}
		else // hiding
		{
		    controlName = "show";
		}
		
		box.innerHTML = '[<a href="javascript:handleClick( ' + numBox + ' );" id="report-box-' + numBox + '-expand" class="active">' + controlName + '</a>]';
	    }
	}
    }
} // expandFinished()

function modifyHTMLPreview( evt )
{
    if( !evt ) evt = event;
    var srcElem = evt.target || evt.srcElement;

    // Make all links popup in new window
    var links = $A( srcElem.getElementsByTagName( 'A' ) );
    links.each( function(atag) { atag.target = '_blank' } );
    
} // modifyHTMLPreview

function monitorImportProgress( acctId, projId, xnet )
{
    var monitor = new RubyMail.ImportMonitor( { 
	frequency  : 3,
	account_id : acctId,
        project_id : projId,
	xnet       : xnet
    } );

} //  monitorImportProgress

/* *******************************************************

  RubyMail.ImportMonitor Class

   ******************************************************* */
RubyMail.ImportMonitor = Class.create();
Object.extend( RubyMail.ImportMonitor.prototype, Ajax.PeriodicalUpdater.prototype );
Object.extend( RubyMail.ImportMonitor.prototype, {

    baseInitialize : RubyMail.ImportMonitor.prototype.initialize,
    
    initialize : function( options ) {
	
	var acctId = options.account_id;
	var projId = options.project_id;

	var xnetPath = options.xnet ? '/extranet' : '';

	this.pollURL     = '/account/' + acctId + '/campaign/' + projId + xnetPath + '/send/step2.xml';
	this.completeURL = '/account/' + acctId + '/campaign/' + projId + xnetPath + '/send/step3.html';
	this.errorURL    = '/account/' + acctId + '/campaign/' + projId + xnetPath + '/send/import_error.html';
	
	options.onSuccess = this.onSuccess.bind(this);
	options.onFailure = this.onFailure.bind(this);
	options.parameters = 'action=poll';

	this.baseInitialize( new Object(), this.pollURL, options );
	
	this.failureCount = 0;
    },

    onTimerEvent : function() {
	
	this.updater = new Ajax.Request( this.pollURL, this.options );
	
    },

    onSuccess : function(req) {

	var xml    = req.responseXML;
	var root   = xml.getElementsByTagName( 'ruby' )[0];
	var status = root ? root.getAttribute( 'status' ) : null;

	if( status && status == 'success' ) {
	    var completeElem = $A( root.getElementsByTagName( 'data' ) ).detect( 
				       function (elem) { return elem.getAttribute( 'key' ) == 'complete' } 
			       );
	    var isComplete = completeElem.getAttribute( 'value' );
	    if( isComplete == 1 ) {
		this.stop();
		
		DHTML.setLocation( this.completeURL );
	    }
	}
	else if( status && status == 'errors' ) {
	    this.failureCount = 3;
	    this.onFailure( req );
	}
	else {
	    this.onFailure( req );
	}
    },
	
    onFailure : function(req) {
	// Let it fail up to 3 times before doing something
	if( this.failureCount >= 3 ) {
	    this.stop();
	    DHTML.setLocation( this.errorURL );
	}
	else {
	    this.failureCount++;
	}
    }
} ); // ImportMonitor

