var lastId		=	'';
var tweetajax   =	true;
var tweets 		=	[];
var tweetbank	=	[];
var target		=	'';
CKEDITOR.dialog.add( 'embedtweet', function( editor ) {
	var addloader 	=	function(loader){
		$('#tweets').append('<div class="tload"><div class="tweetsearch tweetcenter">Please wait while searching for tweets...</div><div><div class="tweetcenter"><img src="'+loader+'"></div><div>')
	};
	var addTweets 	=	function(method, searchText, loader){
		addloader(loader);
		tweets 	=	getTweets(method, searchText);
		if (tweets.length>0){
			listTweets(tweets);
			twttr.widgets.load();
			$('.tweetblock').removeClass('tweethide');
			$('.tmore').click(function(){
				$('.tmore').remove();
				$('.tload').remove();
				tweets 	=	addTweets(method, searchText, loader);
			});
			$('.tweetinsert').click(function(){
				$('.tweetblock').removeClass('tweetselected');
				$(this).parent('.tweetblock').addClass('tweetselected');
				insertTweet(this.id);
			});
		}
	};
	var insertTweet = function(tweetId){
		$(tweetbank).each(function(index,value){
			if (value.postId==tweetId)
			{	target	=	value.oembed;	}
		});
	};
	var getTweets 	=	function(method, searchText, loader){
		var data	=	'';
		if (tweetajax){
			$.ajax({
				url: method,
				async: false,
				type: 'POST',
				dataType: 'json',
				data: "searchText=" + searchText+'&lastId='+lastId,
				beforeSend: function(){
					tweetajax 	=	false;
				},
				success: function(response, statusText, xhr, $form) {
					if(response.status)
					{	
						lastId	=	response.lastId;
						data 	= 	response.tweets;
						tweetbank	=	$.merge(data, tweetbank);
					}
				},
				error: function(){ tweetajax 	=	true; },
				complete: function(){ 
					tweetajax 	=	true;
					$('.tload').remove();
				}
			});
		}
		return data;
	};
	var listTweets	=	function(tweets){
		var html 		=	'';
		var removeText 	=	'<script charset="utf-8" src="//platform.twitter.com/widgets.js" async=""></script>';
		$(tweets).each(function(index, value){
			html 	+=	'	<div class="tweetblock tweethide" style="height: initial !important;">'+value.oembed+'<div id="'+value.postId+'" class="tweetinsert"></div></div>';
		});
		
		html	+=	'<div class="tmore">Show More</div>';
		$('#tweets #tweetlist').append(html);
	};
	var trim	=	function(inputString) {
		if (typeof inputString != "string") { return inputString; }
		var retValue = inputString;
		var ch = retValue.substring(0, 1);
		while (ch == " ") {
			retValue = retValue.substring(1, retValue.length);
			ch = retValue.substring(0, 1);
		}
		ch = retValue.substring(retValue.length-1, retValue.length);
		while (ch == " ") {
			retValue = retValue.substring(0, retValue.length-1);
			ch = retValue.substring(retValue.length-1, retValue.length);
		}
		while (retValue.indexOf("  ") != -1) { 
			retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length);
		}
		return retValue;
	};
	
    return {
        title: 'Embed Tweet',
        minWidth: 600,
        minHeight: 400,
        onOk: function() { 
        	if (target==''){
        		alert('Please search and select tweet to embed');
        		return false;
        	}
        	return true;
        },
        contents: [
            {
                id: 'info',
                elements: [
                    {
                        id: 'search',
                        type: 'text',
                        label: 'Search',
                    	required : true,
                    },
                    {
                        id: 'go',
                        type: 'button',
                        label: 'Search',
                        className: 'cke_dialog_ui_button',
                        onClick: function()
                        {
                        	lastId		=	'';
                        	var _Call 	=	editor.config.customValues.name;
                    		var dialog = this.getDialog();
                        	var searchText 	=	dialog.getValueOf( 'info', 'search' );
                        	if ((trim(searchText)==''))
                        	{	$('#tweets .tmessage').show();	}
                        	else {
                        		var loader 	=	CKEDITOR.plugins.getPath('embedtweet')+'icons/loading.gif';
                        		$('#tweets .tmessage').hide();
                        		$('.tload').remove();
                        		$('#tweetlist').remove();
                        		$('#tweets').append('<div id="tweetlist"></div>');
                        		addTweets(_Call, searchText, loader);
                        	}
                        },
                        setup: function(widget) {
                        	this.setValue( widget.data.blockqoute);
                        },
                        commit: function(widget) {
                        	widget.setData( 'blockqoute', target);
                        }
                    },
                    {
                        id: 'tweets',
                        type: 'html',
                    	html : '<div id="tweets"><div class="tmessage">Please enter the search keyword or hashtag & click on search button</br>Use comma (,) in order to search for multiple keywords or hashtags</div></div>' 
                    }
                    
                ]
            }
        ],
        buttons: [  	CKEDITOR.dialog.okButton, 
                    	CKEDITOR.dialog.cancelButton],
    };
} );
