/**
 * This file contains all the main JavaScript functionality needed for the editor formatting buttons.
 * 
 * @author orangethemes
 * http://orangethemes.com
 */

/**
 * Define all the formatting buttons with the HTML code they set.
 */
var orangethemesButtons=[
		{
			id:'orangethemesbutton',
			image:'btn-button.png',
			title:'Button',
			allowSelection:false,
			fields:[{id:'text', name:'Text'},{id:'href', name:'Link URL'},{id:'bg_color', color:'E5E5E5', name:'Background Color', colorpalette:true},{id:'txt_color', color:'434343', name:'Text Color', colorpalette:true},{id:'align', name:'Align', values:['Left', 'Right']},{id:'size', name:'Size', values:['Small', 'Big']},{id:'target', name:'Target', values:['Self', 'Blank']}],
			generateHtml:function(obj){
				
				var buttonAlign=obj.align==='Left'?'left':'right';
				var buttonSize=obj.size==='Small'?'1':'2';
				var buttonTarget=obj.target==='Self'?'':'_blank';
				
				return '<a class="btn-'+buttonSize+' btn-'+buttonSize+'-align-'+buttonAlign+'" href="'+obj.href+'" target="'+buttonTarget+'" style="background-color: #'+obj.bg_color+';"><span style="color: #'+obj.txt_color+';">'+obj.text+'</span></a><br/><br/>';

			}
		},
		{
			id:'orangethemesspacer',
			image:'btn-spacer.png',
			title:'Spacer',
			allowSelection:false,
			fields:[{id:'style', name:'Style', values:['Title Spacer', 'Dotted Spacer', 'Solid Spacer', 'Star Spacer']},{id:'color', color:'49BCD7', name:'Spacer Color', colorpalette:true}],
			generateHtml:function(obj){
			
				switch(obj.style)
				{
					case 'Title Spacer':
					  var spacerStyle='title'
					  break;
					case 'Dotted Spacer':
					  var spacerStyle='dotted'
					  break;
					case 'Solid Spacer':
					  var spacerStyle='solid'
					  break;
					case 'Star Spacer':
					  var spacerStyle='star'
					  break;
					default:
					  var spacerStyle='title'
				}

				return '<div class="spacer-'+spacerStyle+'" style="background-color: #'+obj.color+'">&nbsp;</div><br/><br/>';

			}
		},

		{
			id:'orangethemesquote',
			image:'btn-quotes.png',
			title:'Quote',
			allowSelection:false,
			fields:[{id:'style', name:'Style', values:['Default', 'Dotted', 'Stars']},{id:'quotetext', name:'Quote text', textarea:true}],
			generateHtml:function(obj){
			
				switch(obj.style)
				{
					case 'Default':
					  return '<div class="blockquote-quote-marks"><blockquote>'+obj.quotetext+'</blockquote></div><br/><br/>';
					  break;
					case 'Dotted':
					   return '<blockquote class="blockquote-dotted-box">'+obj.quotetext+'</blockquote><br/><br/>';
					  break;
					case 'Stars':
					  return '<div class="blockquote-stars"><blockquote>'+obj.quotetext+'</blockquote></div><br/><br/>';
					  break;
					default:
					  return '<div class="blockquote-quote-marks"><blockquote>'+obj.quotetext+'</blockquote></div><br/><br/>';
				}

			}
		},
		{
			id:'orangethemeslist_1',
			image:'cpanel-btn-list-3.png',
			title:'Dotted List Style',
			allowSelection:false,
			list:"list-dotted"
		},
		{
			id:'orangethemeslist_2',
			image:'cpanel-btn-list-1.png',
			title:'Circle List Style',
			allowSelection:false,
			list:"list-circle"
		},
		{
			id:'orangethemeslist_3',
			image:'cpanel-btn-list-4.png',
			title:'Checkmark List Style',
			allowSelection:false,
			list:"list-checkmark"
		},
		{
			id:'orangethemeslist_4',
			image:'cpanel-btn-list-5.png',
			title:'Cross List Style',
			allowSelection:false,
			list:"list-cross"
		},
		{
			id:'orangethemescolumns',
			image:'btn-columns-2.png',
			title:'Two Columns Layout',
			allowSelection:false,
			fields:[{id:'columnone', name:'Column One Content', textarea:true}, {id:'columntwo', name:'Column Two Content', textarea:true}],
			generateHtml:function(obj){
				return '<div class="half-column-left">'+obj.columnone+'</div><div class="half-column-right">'+obj.columntwo+'</div><div class="clear"></div><br/><br/>';
			}
		},
		{
			id:'orangethemesthreecolumns',
			image:'btn-columns-3.png',
			title:'Three Columns Layout',
			allowSelection:false,
			fields:[{id:'columnone', name:'Column One Content', textarea:true}, {id:'columntwo', name:'Column Two Content', textarea:true}, {id:'columnthree', name:'Column Three Content', textarea:true}],
			generateHtml:function(obj){
				return '<div class="one-third-column-1">'+obj.columnone+'</div><div class="one-third-column-2">'+obj.columntwo+'</div><div class="one-third-column-3">'+obj.columnthree+'</div><div class="clear"></div><br/><br/>';
			}
		},
		{
			id:'orangethemesfourcolumns',
			image:'btn-columns-4.png',
			title:'Four Columns Layout',
			allowSelection:false,
			fields:[{id:'columnone', name:'Column One Content', textarea:true}, {id:'columntwo', name:'Column Two Content', textarea:true}, {id:'columnthree', name:'Column Three Content', textarea:true}, {id:'columnfour', name:'Column Four Content', textarea:true}],
			generateHtml:function(obj){
				return '<div class="one-fourth-column-1">'+obj.columnone+'</div><div class="one-fourth-column-2">'+obj.columntwo+'</div><div class="one-fourth-column-3">'+obj.columnthree+'</div><div class="one-fourth-column-4">'+obj.columnfour+'</div><div class="clear"></div><br/><br/>';
			}
		},		
		{
			id:'orangethemesgallery',
			image:'btn-gallery.png',
			title:'Insert Gallery Preview',
			allowSelection:false,
			fields:[{id:'links', name:'Gallery Link' }],
			generateHtml:function(obj){
				return '[gallery url="'+obj.links+'"]';
			}
		},
		{
			id:'orangethemescaption',
			image:'btn-image.png',
			title:'Image Caption',
			allowSelection:false,
			fields:[{id:'caption_title', name:'Title'},{id:'link', name:'Image URL'}],
			generateHtml:function(obj){
				return '[caption title="'+obj.caption_title+'" url="'+obj.link+'"]';
			}
		},
		{
			id:'orangethemesbreak',
			image:'cpanel-btn-break.png',
			title:'Insert Breake',
			allowSelection:false,
			generateHtml:function(){
				return '<br class="clear" />';
			}
		}
		
];

/**
 * Contains the main formatting buttons functionality.
 */
orangethemesButtonManager={
	dialog:null,
	idprefix:'orangethemes-shortcode-',
	ie:false,
	opera:false,
		
	/**
	 * Init the formatting button functionality.
	 */
	init:function(){
			
		var length=orangethemesButtons.length;
		for(var i=0; i<length; i++){
		
			var btn = orangethemesButtons[i];
			orangethemesButtonManager.loadButton(btn);
			
		}
		
		if ( jQuery.browser.msie ) {
			orangethemesButtonManager.ie=true;
		}
		
		if (jQuery.browser.opera){
			orangethemesButtonManager.opera=true;
		}
		
	},
	
	/**
	 * Loads a button and sets the functionality that is executed when the button has been clicked.
	 */
	loadButton:function(btn){
	
		tinymce.create('tinymce.plugins.'+btn.id, {
	        init : function(ed, url) {
			        ed.addButton(btn.id, {
	                title : btn.title,
	                image : url+'/buttons/'+btn.image,
	                onclick : function() {
			        	
			           var selection = ed.selection.getContent();
	                   if(btn.allowSelection && selection){
	                	   //modification via selection is allowed for this button and some text has been selected
	                	   selection = btn.generateHtml(selection);
	                	   ed.selection.setContent(selection);
	                   }else if(btn.fields){
	                	   //there are inputs to fill in, show a dialog to fill the required data
	                	   orangethemesButtonManager.showDialog(btn, ed);
	                   }else if(btn.list){
	                	   ed.dom.remove('orangethemescaret');
		           		    ed.execCommand('mceInsertContent', false, '&nbsp;');	
	           			
	                	    //this is a list
	                	    var list, dom = ed.dom, sel = ed.selection;
	                	    
		               		// Check for existing list element
		               		list = dom.getParent(sel.getNode(), 'ul');
		               		
		               		// Switch/add list type if needed
		               		ed.execCommand('InsertUnorderedList');
		               		
		               		// Append styles to new list element
		               		list = dom.getParent(sel.getNode(), 'ul');
		               		
		               		if (list) {
		               			dom.addClass(list, btn.list);
		               		}
	                   }else{
	                	   //no data is required for this button, insert the generated HTML
	                	   ed.execCommand('mceInsertContent', true, btn.generateHtml());
	                   }
					   
					   addLoadEvent(jscolor.init);
	                }
	            });
	        }
	    });
		
	    tinymce.PluginManager.add(btn.id, tinymce.plugins[btn.id]);
	},
	
	/**
	 * Displays a dialog that contains fields for inserting the data needed for the button.
	 */
	showDialog:function(btn, ed){

		
		if(orangethemesButtonManager.ie){
			ed.dom.remove('orangethemescaret');
		    var caret = '<div id="orangethemescaret">&nbsp;</div>';
		    ed.execCommand('mceInsertContent', false, caret);	
			var selection = ed.selection;
		}
	    
		var html='<div>';
		for(var i=0, length=btn.fields.length; i<length; i++){
			var field=btn.fields[i], inputHtml='';
			if(btn.fields[i].colorpalette){
					//this field should be a text area
					inputHtml='<input type="text" class="color" value="'+btn.fields[i].color+'" id="'+orangethemesButtonManager.idprefix+btn.fields[i].id+'">';
			} else if(btn.fields[i].values){
				//this is a select list
				inputHtml='<select id="'+orangethemesButtonManager.idprefix+btn.fields[i].id+'">';
				jQuery.each(btn.fields[i].values, function(index, value){
					inputHtml+='<option value="'+value+'">'+value+'</option>';
				});
				inputHtml+='</select>';
			}else{
				if(btn.fields[i].textarea && !orangethemesButtonManager.opera){
					//this field should be a text area
					inputHtml='<textarea id="'+orangethemesButtonManager.idprefix+btn.fields[i].id+'" ></textarea>';
				}else{
					//this field should be a normal input
					inputHtml='<input type="text" id="'+orangethemesButtonManager.idprefix+btn.fields[i].id+'" />';
				}
			}
			html+='<div class="orangethemes-shortcode-field"><label>'+btn.fields[i].name+'</label>'+inputHtml+'</div>';
		}
		html+='<a href="" id="insertbtn" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button"><span class="ui-button-text">Insert</span></a></div>';
				
		var dialog = jQuery(html).dialog({
							 title:btn.title, 
							 modal:true,
							 close:function(event, ui){
								jQuery(this).html('').remove();
							 }
							 });
		
		orangethemesButtonManager.dialog=dialog;
		
		//set a click handler to the insert button
		dialog.find('#insertbtn').click(function(event){
			event.preventDefault();
			orangethemesButtonManager.executeCommand(ed,btn,selection);
		});
	},
	
	/**
	 * Executes a command when the insert button has been clicked.
	 */
	executeCommand:function(ed, btn, selection){

    		var values={}, html='';
    		
    		if(!btn.allowSelection){
    			//the button doesn't allow selection, generate the values as an object literal
	    		for(var i=0, length=btn.fields.length; i<length; i++){
	        		var id=btn.fields[i].id,
	        			value=jQuery('#'+orangethemesButtonManager.idprefix+id).val();
	        		
	    			values[id]=value;
	    		}
	    		html = btn.generateHtml(values);
    		}else{
    			//the button allows selection - only one value is needed for the formatting, so
    			//return this value only (not an object literal)
    			value = jQuery('#'+orangethemesButtonManager.idprefix+btn.fields[0].id).attr("value")
    			html = btn.generateHtml(value);
    		}
    		
    	orangethemesButtonManager.dialog.remove();

    	if(orangethemesButtonManager.ie){
	    	selection.select(ed.dom.select('div#orangethemescaret')[0], false);
	    	ed.dom.remove('orangethemescaret');
    	}

  		ed.execCommand('mceInsertContent', false, html);
    	
	}
};

/**
 * Init the formatting functionality.
 */
(function() {
	
	orangethemesButtonManager.init();
    
})();

