var personalizationWidget = new Object();
personalizationWidget.build = function( ){
    this.nodes = Builder.node('span');
    this.engineHolder = Builder.node('div', { className: 'hidden-widget'} );

    this.nodes.appendChild( this.engineHolder );

    this.codeHolder = Builder.node('div',{className: 'copy-paste'},'%%%%');
    this.defaultInput = Builder.node('input',{type: 'text',
					      className: 'text-field text-input',
					      autocomplete: 'off',
					      onFocus: 'personalizationWidget.clearDefault();',
					      onKeyUp: 'personalizationWidget.updateCode();'});
}

personalizationWidget.getNodes = function( insertFunction ){
    if( this.fieldList == undefined ){
	getRemoteValue('account','personalization','',
		       function( retObj ) { personalizationWidget.fieldList = retObj.response.value; },
		       false
		       );
    }

    this.insertFunction =  (typeof insertFunction == 'function' ) ? insertFunction : false;

    if( this.nodes == undefined )
	this.build();

    return this.nodes;
}

personalizationWidget.toggle = function(){
    if( personalizationWidget.engineHolder.style.display != 'block' ){
	if( personalizationWidget.fieldList == undefined )
	    return alert('ERROR: Personalization Fields have not been provided.');
	personalizationWidget.engineHolder.style.display = 'block';
	personalizationWidget.start();
    } else {
	personalizationWidget.engineHolder.style.display = 'none';
    }
}
personalizationWidget.start = function(){
    removeAllChildNodes( personalizationWidget.engineHolder );
    if( personalizationWidget.selectList == undefined ){
	personalizationWidget.selectList = Builder.node('select', 
							{ className: 'select',onChange: 'personalizationWidget.select();' },
					     [Builder.node('option',{value: 'select'},'Select a Field')] );
	for( var i in personalizationWidget.fieldList ){
	    if( typeof personalizationWidget.fieldList[i] == 'string' ){
		personalizationWidget.selectList.appendChild( Builder.node('option',{value: i}, personalizationWidget.fieldList[i]) );
	    }
	}
    }
    personalizationWidget.selectList.value='select';
    personalizationWidget.engineHolder.appendChild( personalizationWidget.selectList );
}
personalizationWidget.select = function(){
    if( personalizationWidget.selectList.value == 'select' )
	return;
    removeAllChildNodes( personalizationWidget.engineHolder );

    personalizationWidget.engineHolder.appendChild( personalizationWidget.codeHolder );

    personalizationWidget.defaultCleared = false;
    var middleDiv = Builder.node('div');

    if( personalizationWidget.selectList.value != 'EMAIL' ){
	personalizationWidget.defaultInput.value = 'Provide substitute for empty fields';
	middleDiv.appendChild( personalizationWidget.defaultInput );
    }
    middleDiv.appendChild(Builder.node('br') );

    if( personalizationWidget.insertFunction ){
	middleDiv.appendChild(Builder.node('input',{type: 'button', className: 'confirm-button',onClick: 'personalizationWidget.askForCursor(this);',value: 'Insert Code'} ) );
	middleDiv.appendChild(Builder.node('br') );
    }
    
    personalizationWidget.engineHolder.appendChild( middleDiv );

    personalizationWidget.engineHolder.appendChild(Builder.node('a',{href: '#', style: 'font-size: .9em', onClick: 'personalizationWidget.start();return false;'},
					      'Start Over') );

    personalizationWidget.updateCode();
}
personalizationWidget.clearDefault = function(){
    if( personalizationWidget.defaultCleared )
	return;
    personalizationWidget.defaultCleared = true;
    personalizationWidget.defaultInput.value = '';
}
personalizationWidget.askForCursor = function(buttonClicked){
    var middleDiv = buttonClicked.parentNode;
    removeAllChildNodes( middleDiv );

    middleDiv.appendChild( Builder.node('div','Place your cursor in the desired location, then click "OK"' ) );
    middleDiv.appendChild(Builder.node('input',{type: 'button', className: 'confirm-button',onClick: 'personalizationWidget.runInsert();',value: ' OK '} ) );
    middleDiv.appendChild(Builder.node('br') );
}
personalizationWidget.runInsert = function(){
    personalizationWidget.insertFunction( personalizationWidget.currentCode() );
    personalizationWidget.toggle();
}
personalizationWidget.updateCode = function(){
    personalizationWidget.codeHolder.replaceChild( _cTxt( personalizationWidget.currentCode() ), personalizationWidget.codeHolder.firstChild);
}
personalizationWidget.currentCode = function (){
    var code = '';
    if( personalizationWidget.defaultCleared ) {
	personalizationWidget.defaultInput.value = personalizationWidget.defaultInput.value.replace(/[<>%]/g, '');
	if( personalizationWidget.defaultInput.value )
	    code += ':' + personalizationWidget.defaultInput.value;
    }
    return '%%' + personalizationWidget.selectList.value + code + '%%';
}


var attachmentWidget = new Object();

attachmentWidget.getNodes = function( linkType, insertFunction ){
    this.linkType = (linkType == 'html')? 'html':'text';

    if( this.fileList == undefined ){
	getRemoteValue('account','attachments','',
		       function( retObj ) { attachmentWidget.fileList = retObj.response.value; },
		       false
		       );
    }

    this.insertFunction =  (typeof insertFunction == 'function' ) ? insertFunction : false;

    if( this.nodes == undefined )
	this.nodes = Builder.node('div', { className: 'hidden-widget'} );

    return this.nodes;
}
attachmentWidget.toggle = function(){
    if( attachmentWidget.nodes.style.display != 'block' ){
	if( attachmentWidget.fileList == undefined )
	    return alert('ERROR: Attachment List has not been provided.');
	attachmentWidget.nodes.style.display = 'block';
	attachmentWidget.start();
    } else {
	attachmentWidget.nodes.style.display = 'none';
    }
}
attachmentWidget.start = function(){
    removeAllChildNodes( attachmentWidget.nodes );
    if( attachmentWidget.selectList == undefined ){
	attachmentWidget.selectList = Builder.node('select', 
						   [Builder.node('option',{value: 'select'},'Select a File')] );
	for( var i in attachmentWidget.fileList ){
	    if( typeof attachmentWidget.fileList[i] == 'string' ){
		attachmentWidget.selectList.appendChild( Builder.node('option',{value: i},attachmentWidget.fileList[i] ) );
	    }
	}
    }
    attachmentWidget.selectList.value='select';
    attachmentWidget.nodes.appendChild( attachmentWidget.selectList );


    if( attachmentWidget.linkText == undefined )
	attachmentWidget.linkText = Builder.node('input',{type: 'text',
							  className: 'text-field text-input',
							  autocomplete: 'off',
							  onFocus: 'attachmentWidget.clearDefault();'});

    attachmentWidget.defaultCleared = false;
    attachmentWidget.linkText.value='Click Here';
    var actionDiv = Builder.node('div');

    if( attachmentWidget.linkType == 'html' ){
	actionDiv.appendChild( attachmentWidget.linkText );
    }

    actionDiv.appendChild(Builder.node('br') );
    actionDiv.appendChild(Builder.node('input',{type: 'button', className: 'confirm-button', onClick: 'attachmentWidget.askForCursor(this);', value: 'Insert Code'} ) );
    attachmentWidget.nodes.appendChild( actionDiv );
}

attachmentWidget.clearDefault = function(){
    if( attachmentWidget.defaultCleared )
	return;
    attachmentWidget.defaultCleared = true;
    attachmentWidget.linkText.value = '';
}
attachmentWidget.currentCode = function(){
    return '%%FILE_LINK:' + attachmentWidget.selectList.value + '%%';
}
attachmentWidget.askForCursor = function(buttonClicked){
    if( attachmentWidget.selectList.value == 'select' )
	return;
    if( attachmentWidget.linkType == 'html' ){
	attachmentWidget.linkText.value = attachmentWidget.linkText.value.replace(/[%<>]/g, '');
	if( ! attachmentWidget.linkText.value )
	    return;
    }

    var actionDiv = buttonClicked.parentNode;
    removeAllChildNodes( actionDiv );
    actionDiv.appendChild( Builder.node('div','Place your cursor in the desired location, then click "OK"' ) );
    actionDiv.appendChild(Builder.node('input',{type: 'button', className: 'confirm-button',onClick: 'attachmentWidget.runInsert();',value: ' OK '} ) );

}
attachmentWidget.runInsert = function(){
    if( attachmentWidget.linkType == 'html' )
	attachmentWidget.insertFunction( attachmentWidget.currentCode(), 
					 attachmentWidget.linkText.value );
    else 
	attachmentWidget.insertFunction( attachmentWidget.currentCode() );
    
    attachmentWidget.toggle();
}
///////////////////
var imagesWidget = new Object();

imagesWidget.getNodes = function( insertFunction, templateClick, apiNamespace ){
    imagesWidget.apiNamespace = apiNamespace ? apiNamespace : 'account';
    imagesWidget.templateClick = templateClick ? true : false;

    if( this.nodes == undefined )
	this.nodes = Builder.node('div');

    if( this.accountImagesHolder == undefined ){
	this.accountImagesHolder = Builder.node('div', 'Loading Images...');
	this.nodes.appendChild( this.accountImagesHolder );
	getRemoteValue(imagesWidget.apiNamespace,'accountImages','',
		       function( retObj ) { imagesWidget.configureImages(retObj.response.value, 'account'); },
		       false
		       );
    }

    if( this.freeImagesHolder == undefined ) {
	this.freeImagesHolder = Builder.node('div', 'Loading Images...');
	this.nodes.appendChild( this.freeImagesHolder );
	getRemoteValue(imagesWidget.apiNamespace,'freeImages','',
		       function( retObj ) { imagesWidget.configureImages(retObj.response.value, 'free'); },
		       false
		       );

    }

    this.insertFunction =  (typeof insertFunction == 'function' ) ? insertFunction : false;


    return this.nodes;
}
imagesWidget.configureImages = function(imageList, imageTypes){
    var holder;
    var title;
    if( imageTypes == 'account' ){
	holder = imagesWidget.accountImagesHolder;
	title = 'Your Images';
    } else {
	holder = imagesWidget.freeImagesHolder;
	title =  'Free Images';
    }

    removeAllChildNodes( holder );

    if( imageList.length ){
	holder.appendChild( Builder.node('h2', {className: 'standard'},title) );
	
	for ( var i=0; i < imageList.length; i++)
	    holder.appendChild( Builder.node( 'div',
					      {'className':'imagesWidget-image-frame'},
					      [Builder.node('img', {'src': '/thumbnail/'+imageList[i].id+'/',
							      'className': 'clickable',
							      'title': imageList[i].name,
							      'onClick': 'imagesWidget.imageClicked( this );'
							      }
						      )
						  ]));
	holder.appendChild( Builder.node('br', {className: 'clearing'} ) );
    }
}
imagesWidget.imageClicked = function( imageClicked ){
    if( imagesWidget.templateClick )
	eBuilderTemplate.setRange();


    if( ! imagesWidget.insertFunction ){
	alert('ERROR: No Insert Function was provided!');
	return;
    }
    var imageID = imageClicked.src.match(/[^\/]*\/thumbnail\/([0-9a-f]+)\//i)
    imageID = imageID[1];

    var posLeft = getOffsetLeft( imageClicked ) - 3;
    var posTop = getOffsetTop( imageClicked ) - 3;
    
    var dialog = Builder.node('div',{ className: 'imagesWidget-image-dialog',style:'top:'+posTop+'px;left:'+posLeft+'px;',
				      id: 'imagesWidget-image-dialog-id-' + imageID
	},
	[Builder.node('div','Should this image be a link?'),
	 Builder.node('input',{type: 'button', className: 'confirm-button', onClick: 'imagesWidget.getURL('+ imageID +');', value: 'Yes'}),
	 Builder.node('input',{type: 'button', className: 'confirm-button', onClick: 'imagesWidget.insertCode('+ imageID +');', value: 'No'})
	 ]);
    EB_addToPage( dialog );
}
imagesWidget.getURL = function( imageID ){
    var dialogDocID = 'imagesWidget-image-dialog-id-'+imageID;
    var overlayHolder = $( dialogDocID );
    removeAllChildNodes( overlayHolder );
    overlayHolder.appendChild( Builder.node('div','Enter a location:') );
    overlayHolder.appendChild( Builder.node('input',{type: 'text', className:'text-input',id: 'imagesWidget-url-'+imageID, value: 'http://'}) );
    overlayHolder.appendChild( Builder.node('div',
					    [ Builder.node('input',
							   {type: 'button',className: 'confirm-button', onClick: 'imagesWidget.insertCode('+ imageID + ',$(\'imagesWidget-url-'+imageID+'\').value);this.parentNode.parentNode.removeChild(this.parentNode);',value: 'OK'}),
					      Builder.node('a',
							   {href: '#', onClick: '$( \''+ dialogDocID +'\' ).parentNode.removeChild( $( \''+ dialogDocID +'\' ) );return false;'},'cancel') 
					      ] ) );
}
imagesWidget.insertCode = function( imageID, linkURL ){
    if( imagesWidget.insertFunction ) {
	var imageURL = 'http://' + getDomain() + '/image/'+imageID+'/?%%campaign_id%%';
	var htmlString = '<img src="'+ imageURL + '" ';
	
	if( linkURL )
	    htmlString += 'style="border: 0;" ';

	htmlString += '/>';

	if( linkURL ) {
	    linkURL = linkURL.replace(/[\'\"\s<>]/g, '');
	    htmlString = '<a href="' + linkURL + '">'+ htmlString + '</a>';
	}
	imagesWidget.insertFunction( htmlString );
    } else {
	alert( 'ERROR: Insert Function Not Specified!' );
    }
    var overlayHolder = $('imagesWidget-image-dialog-id-'+imageID);
    overlayHolder.parentNode.removeChild( overlayHolder );
}
