/**
 * @package		EasyBlog
 * @copyright	Copyright (C) 2010 Stack Ideas Private Limited. All rights reserved.
 * @license		GNU/GPL, see LICENSE.php
 *  
 * EasyBlog is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 * See COPYRIGHT.php for copyright notices and details.
 */

// some global vars
var isSave = false;


var eblog = {
	
	/**
	 * Dashboard
	 */
	dashboard: {
		
		// for dashboard submenu
		submenu: {
			
			init: function() {			
				// dashboard submenu
				ej('.toolbar-dashboard').hoverIntent( function() {
					ej('.submenu').slideDown(200);
					ej('.toolbar-dashboard a:first-child').addClass('hover');
				}, function() {
					setTimeout( function() {
						ej('.submenu').slideUp(200);
						ej('.toolbar-dashboard a:first-child').removeClass('hover');
					}, 500);
				});			
			}
		}
	
	},
	
	
	/**
	 * Editor
	 */	 	
	editor: {
	
	    checkPublishStatus: function() {
	        var status  		= ej('#published').val();
	        var unpublishdate   = ej('#publish_down').val();
	        
	        if(unpublishdate == '' || unpublishdate == '0000-00-00 00:00:00')
	        {
	            eblog.editor.postSubmit();
	            return true;
	        }
	        
	        ejax.load( 'dashboard' , 'checkPublishStatus' , status,  unpublishdate);
	        return true;
	    },
	    
	    cancelSubmit: function() {
			isSave = false;
			ej("#save_post").attr('disabled', '');
			return false;
	    },
	    
	    postSubmit: function () {
	        //do submitting
			ej(window).unbind('beforeunload');
			ej('#blogForm').submit();
	    },
		
		// save the post
		save: function() {
			
			// this flag is used to prevent onbeforeunload event get triggered
			// on dashboard.write.php
// 			isSave = true;

			// toggle up TinyMCE editor
			if ( typeof( tinyMCE ) == 'object' ) {
				if ( ej('#write_content').is(":visible") ) {
					tinyMCE.execCommand('mceToggleEditor', false, 'write_content');
				}
			}

			ej("#save_post").attr('disabled', 'disabled');
			
			if(eblog.editor.validate())
			{
			    eblog.editor.checkPublishStatus();
			}
			else
			{
				isSave = false;
				ej("#save_post").attr('disabled', '');
				return false;
			}
		},
		
		validate: function() {
			
			// not really fix the issue
			if ( typeof( tinyMCE ) == 'object' ) {
				if ( ej('#write_content').is(":visible") ) {
					tinyMCE.execCommand('mceToggleEditor', false, 'write_content');
					tinyMCE.execCommand('mceToggleEditor', false, 'write_content');
				}
				else {
					tinyMCE.execCommand('mceToggleEditor', false, 'write_content');
				}
			}
			
			if( ej("#title").val() == "" || ej("#title").val() == emptyText )
			{
				eblog.system.alert('COM_EASYBLOG_EMPTY_BLOG_TITLE' , 'COM_EASYBLOG_WARNING');
				return false;
			}
			
			if(ej("#write_content").val() == "")
			{
				eblog.system.alert('COM_EASYBLOG_EMPTY_BLOG_CONTENT' , 'COM_EASYBLOG_WARNING');
				return false;
			}

			return true;
		},
		
		/**
		 * Generate date time picker like Wordpress
		 */		 		
		datetimepicker: {
			
			element: function(id, reset) {
			
				// reference: http://www.quackit.com/javascript/javascript_date_and_time_functions.cfm
				
				var day, month, year, hour, minute, ampm;
				
				eblog.editor.datetimepicker.hideEditLink(id);

				var day, month, year, hour, minute, ampm;
				
				eblog.editor.datetimepicker.hideEditLink(id);
				
				if ( ej('#' + id).val() != '' ) {
					var strValue = ej('#' + id).val();
					var strTemp = strValue.split(' ');
					var strTime = strTemp[1].split(':');
					var strDate = strTemp[0].split('-');
	
					day 	= strDate[2];
					month 	= strDate[1];
					year 	= strDate[0];
					hour	= strTime[0];
					minute	= strTime[1];
				}
				else {
					today = new Date();
					
					day 	= today.getDate();
					month 	= today.getMonth() + 1;  //in js, month start from 0, not 1
					year 	= today.getFullYear();
					hour	= today.getHours();
					minute	= today.getMinutes();
				}
				
				minute = parseInt(minute);
				
// 				alert(minute);
				
				if (minute < 10) {
					minute = '0' + minute;
				}
				
				if ( hour > 11 ) {
					ampm = 'pm';
				}
				else {
					ampm = 'am';
				}
				
				if ( hour > 12 ) {
					hour -= 12;
				}
				
				var html = '';
				html += '<div class="dtpicker-wrap" id="dtpicker_'+id+'" style="display: none;">';
				html += '	<select tabindex="4" name="dt_month" id="dt_month_'+id+'">';
				html += '		<option value="01" '+ (month == '01' ? 'selected="selected"' : "" )  +'>'+ sJan +'</option>';
				html += '		<option value="02" '+ (month == '02' ? 'selected="selected"' : "" )  +'>'+ sFeb +'</option>';
				html += '		<option value="03" '+ (month == '03' ? 'selected="selected"' : "" )  +'>'+ sMar +'</option>';
				html += '		<option value="04" '+ (month == '04' ? 'selected="selected"' : "" )  +'>'+ sApr +'</option>';
				html += '		<option value="05" '+ (month == '05' ? 'selected="selected"' : "" )  +'>'+ sMay +'</option>';
				html += '		<option value="06" '+ (month == '06' ? 'selected="selected"' : "" )  +'>'+ sJun +'</option>';
				html += '		<option value="07" '+ (month == '07' ? 'selected="selected"' : "" )  +'>'+ sJul +'</option>';
				html += '		<option value="08" '+ (month == '08' ? 'selected="selected"' : "" )  +'>'+ sAug +'</option>';
				html += '		<option value="09" '+ (month == '09' ? 'selected="selected"' : "" )  +'>'+ sSep +'</option>';
				html += '		<option value="10" '+ (month == '10' ? 'selected="selected"' : "" )  +'>'+ sOct +'</option>';
				html += '		<option value="11" '+ (month == '11' ? 'selected="selected"' : "" )  +'>'+ sNov +'</option>';
				html += '		<option value="12" '+ (month == '12' ? 'selected="selected"' : "" )  +'>'+ sDec +'</option>';
				html += '	</select>';
				html += '	<input type="text" autocomplete="off" tabindex="4" maxlength="2" size="2" value="' + day + '" name="dt_day" id="dt_day_'+id+'">, ';
				html += '	<input type="text" autocomplete="off" tabindex="4" maxlength="4" size="4" value="' + year + '" name="dt_year" id="dt_year_'+id+'"> @ ';
				html += '	<input type="text" autocomplete="off" tabindex="4" maxlength="2" size="2" value="' + hour + '" name="dt_hour" id="dt_hour_'+id+'"> : ';
				html += '	<input type="text" autocomplete="off" tabindex="4" maxlength="2" size="2" value="' + minute + '" name="dt_min" id="dt_min_'+id+'">';
				html += '	<select tabindex="4" name="dt_ampm" id="dt_ampm_'+id+'">';
				html += '		<option value="am" ' + (ampm == "am" ? 'selected="selected"' : '') + '>'+ sAm +'</option>';
				html += '		<option value="pm" ' + (ampm == "pm" ? 'selected="selected"' : '') + '>'+ sPm +'</option>';
				html += '	</select>';
				html += '	<div class="dtpicker-action" id="dtpicker_action_'+id+'">';
				html += '		<a class="dtpicker-save" href="javascript:void(0);" onclick="eblog.editor.datetimepicker.save(\''+id+'\')">'+btnOK+'</a>';
				
				if ( reset ) {
				html += '		<a class="dtpicker-reset" href="javascript:void(0);" onclick="eblog.editor.datetimepicker.reset(\''+id+'\')">'+btnReset+'</a>';
				}
				
				html += '		<a class="dtpicker-cancel" href="javascript:void(0);" onclick="eblog.editor.datetimepicker.cancel(\''+id+'\')">'+btnCancel+'</a>';
				html += '	</div>';
				html += '</div>';				
				
				ej(html).insertAfter('#datetime_' + id);
				ej('#dtpicker_' + id).slideDown('fast');
			},
			
			reset: function(id) {
				ej('#dtpicker_' + id).slideUp('fast');
				ej('#' + id).val('');
				ej('#datetime_' + id + ' .datetime_caption').html(sNever);
				eblog.editor.datetimepicker.showEditLink(id);
			},
			
			cancel: function(id) {
				ej('#dtpicker_' + id).slideUp('fast');
				
				eblog.editor.datetimepicker.showEditLink(id);
			},
			
			save: function(id) {
				ej('#dtpicker_' + id).slideUp('fast');
				
				// construct date time
				var day, month, year, hour, minute, ampm;
				
				//today = new Date();
				day 	= ej('#dtpicker_' + id + ' #dt_day_' + id).val();
				month 	= ej('#dtpicker_' + id + ' #dt_month_' + id).val();
				
				month = parseInt(month, 10);
				if ( month < 10 ) {
					month = '0' + month;
				}

				year 	= ej('#dtpicker_' + id + ' #dt_year_' + id).val();
				hour	= ej('#dtpicker_' + id + ' #dt_hour_' + id).val();
				
				ampm	= ej('#dtpicker_' + id + ' #dt_ampm_' + id).val();
				if ( ampm == 'pm' ) {
					
					switch ( hour ) {
						case 12:
							//hour = '00';
							break;
							
						default:
							hour = parseInt(hour) + 12;
							break;		
					}
				}
				else {
					switch ( hour ) {
						case 12:
							hour = '00';
							break;
							
						default:
// 							hour += 12;
							break;		
					}
				}
				
				minute	= ej('#dtpicker_' + id + ' #dt_min_' + id).val();
				minute  = parseInt(minute);
				if (minute < 10) {
					minute = '0' + minute;
				}
				
				
				var setTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':00';
				ej('#' + id).val(setTime);
				ej('#datetime_' + id + ' .datetime_caption').html(setTime);
	
				eblog.editor.datetimepicker.showEditLink(id);
				ej('.dtpicker-wrap').remove();
			},
			
			showEditLink: function(id) {
				ej('#datetime_' + id + ' .edit_link').fadeIn('fast');
			},
			
			hideEditLink: function(id) {
				ej('#datetime_' + id + ' .edit_link').fadeOut('fast');
			}
		},
		
		
		
		
		
		// get permalink from controller
		permalink: function() {
			//We don't want to load empty permalinks
			if( ej('#title').val() != '' )
			{
				ejax.load( 'dashboard' , 'getPermalink' , ej('#title').val() );
			}		
		},
		
		// show hide editor tabs
		tab: {
		
			show: function( id ) {
				if ( id == 'write-editor' ) {
					ej('#tab_content').hide();
				}
				else {
					ej('#tab_content').show();
				}

				ej(".container").each( function() {
					if ( ej(this).attr("id") != "write-editor" && ej(this).attr("id") != id && ej(this).attr("id") != "") {
						ej(this).hide();
						ej("#" + id).show();
					}
				});
				ej(".tab-button").each( function() {
					if ( ej(this).hasClass("current") ) {
						ej(this).removeClass("current");
					}
				});
				ej("#" + id + "-button").addClass("current");
			
				return false;
			}
		},
		
		// all about tags in editor
		tag: {
			
			add: {
			
				newtag: function() {
					var tags		= ej('#tag-value').val();
					
					if(tags == "")
					{
						eblog.system.alert('COM_EASYBLOG_INVALID_EMPTY_TAG', 'COM_EASYBLOG_WARNING');
						return false;
					}
					
					var tagsArray	= tags.split( ',' );
					
					if( tagsArray.length > 0 )
					{
						ej( tagsArray ).each( function( key , value ) {
							
							value	= ej.trim(value);
							idValue	= value.replace( / /g, '-' );
				
							if( ej('#tag-' + idValue ).html() == null )
							{
								if(idValue != '')
								{
									var strItem = '<li class="tag-list-item" id="tag-' + idValue + '">';
									strItem += '	<a href="javascript:void(0);" onclick="eblog.editor.tag.remove(\'' + idValue + '\');" class="remove-tag"><span>X</span></a>';
									strItem += '	<span class="tag-caption">' + value + '</span>';
									strItem += '	<input type="hidden" name="tags[]" value="' + value + '" />';
									strItem += '</li>';
									ej( '#tag-list' ).append( strItem );
								}
							}
							else
							{
								eblog.system.alert('COM_EASYBLOG_TAG_EXISTS', 'COM_EASYBLOG_WARNING');
							}
						});
					}
					ej( '#tag-value' ).val('');			
				},
				
				existing: function(value) {
				
					if( value.length > 0 )
					{
						value	= ej.trim(value);
						idValue	= value.replace( / /g, '-' );
						
						if( ej('#tag-' + idValue ).html() == null )
						{
							var strItem = '<li class="tag-list-item" id="tag-' + idValue + '">';
							strItem += '	<a href="javascript:void(0);" onclick="eblog.editor.tag.remove(\'' + idValue + '\');" class="remove-tag"><span>X</span></a>';
							strItem += '	<span class="tag-caption">' + value + '</span>';
							strItem += '	<input type="hidden" name="tags[]" value="' + value + '" />';
							strItem += '</li>';		
							ej( '#tag-list' ).append( strItem );
						}
						else
						{
       						eblog.system.alert('COM_EASYBLOG_TAG_EXISTS', 'COM_EASYBLOG_WARNING');
						}
					}	
								
				}
			},
			
			remove: function(key) {
				ej('#tag-' + key ).remove();
			}
		}
	},
		
	loader:{
		item: null,
		loading: function( elementId ) {
			eblog.loader.item = elementId;
			ej( '#' + elementId ).addClass( 'eblog_loader' );
		},
		doneLoading: function(){
			if( eblog.loader.item != null )
			{
				ej( '#' + eblog.loader.item ).removeClass( 'eblog_loader');
			}
		}
	},
	/**
	 * All comment operations
	 */
	comment: {
	    /**
	     * Comment like or dislike
	     */
	    likes: function(contentId, status, likeId) {
	    	eblog.loader.loading( 'likes-' + contentId );
	        ejax.load('Entry', 'likesComment', contentId, status, likeId);
	    },
	
		
		/**
		 * Save comment
		 */
		save: function() {
			//clear err-msg
			ej('#err-msg').removeClass('info error');
			ej('#err-msg').html('');

			eblog.loader.loading( 'comment_form_title' );			

			finalData	= ejax.getFormVal('#frmComment');
			ejax.load('Entry', 'commentSave', finalData);
			
			if ( ej('#empty-comment-notice').length > 0 ) {
				ej('#empty-comment-notice').fadeOut('100');
			}
		},
		
		/**
		 * Reply to comment
		 */		 		
		reply: function(id, commentDepth, autoTitle) {
			// hide all reply container
			ej('.cancel_container').hide();
			// show all reply container
			ej('.reply_container').show();
			
			//prepare the comment input form	
			ej('#comment-reply-form-' + id).show();
			var commentForm = ej('#eblog-wrapper #comment-form').clone();
			ej('#eblog-wrapper #comment-form').remove();
			//ej('#eblog-wrapper #comment-form').hide();
			
			ej('#comment-reply-form-' + id).addClass('comment-form-inline').append(commentForm);
			ej('#parent_id').val(id);
			ej('#comment_depth').val(commentDepth);
			
			if(autoTitle)
			{
				//auto insert title
				var title   = ej('#comment-title-' + id).text();
				var reTitle = (title != '') ? 'RE:' + title : '';
				ej('#title.inputbox').val(reTitle);
			}
			
			//toggle toolbar button
			ej('#toolbar-reply-' + id).hide();
			ej('#toolbar-cancel-' + id).show();

			//need to check if bbcode enabled
			if(ej('.markItUpContainer').length > 0)
			{
				ej("#comment").markItUpRemove();
				ej("#comment").markItUp(EasyBlogBBCodeSettings);
			}

		},
		
		/**
		 * Cancel comment reply
		 */		 		
		cancel: function(id) {
			//revert the comment input form	
			var commentForm = ej('#eblog-wrapper #comment-reply-form-' + id + ' #comment-form').clone();
			ej('#eblog-wrapper #comment-reply-form-' + id + ' #comment-form').remove();	
			ej('#eblog-wrapper #comment-separator').after(commentForm);
			ej('#parent_id').val('');
			ej('#comment_depth').val('0');
			ej('#comment-reply-form-' + id).hide();
			
			ej('#title.inputbox').val('');
			
			//toggle toolbar button
			ej('#toolbar-cancel-' + id).hide();
			ej('#toolbar-reply-' + id).show();

			//need to check if bbcode enabled
			if(ej('.markItUpContainer').length > 0)
			{
				ej("#comment").markItUpRemove();
				ej("#comment").markItUp(EasyBlogBBCodeSettings);
			}
		},
		
		/**
		 * Save edit comment
		 */
		edit: function() {
			//clear err-msg
			ej('#err-msg').removeClass('info error');
			ej('#err-msg').html('');
			//toggleSpinner(true);
		
			finalData	= ejax.getFormVal('#frmComment');
			ejax.load('dashboard', 'updateComment', finalData);			
		},
		
		
		/**
		 * Actions
		 */
		action: function(param, url) {
			var count	= 0;
			var cids    = "";
			var actionStr   = ej("#"+param).val();
			
			if(actionStr == '')
			{
				eblog.system.alert('COM_EASYBLOG_PLEASE_SELECT_ACTION_TO_PERFORM', 'COM_EASYBLOG_WARNING');
				return;
			}
			
		    ej("#adminForm INPUT[name='cid[]']").each( function() {
		        if ( ej(this).attr('checked') ) {
		            if(cids.length == 0)
		            {
		                cids    = ej(this).val();
		            }
		            else
		            {
		                cids    = cids + ',' + ej(this).val();
		            }
		            count++;
				}
			});
			
			if(count <= 0)
			{
				eblog.system.alert('COM_EASYBLOG_PLEASE_SELECT_ONE_ITEM_TO_CONTINUE', 'COM_EASYBLOG_WARNING');
				return;
			}
			
			if(actionStr == 'unpublishComment')
			{
				ejax.load('dashboard', 'publishComment', cids, '0', 'comment');
			}
			else if(actionStr == 'publishComment')
			{
			    ejax.load('dashboard', 'publishComment', cids, '1', 'comment');
			}
			else if(actionStr == 'removeComment')
			{
				eblog.comment.confirm(url, cids, '');
			}		
		},
		
		confirm: function(url, commentId, lbl)
		{
			var targetUrl   = url + '&task=removeComment&commentId=' + commentId;
			var callback    = 'window.location = "' + targetUrl + '";';
		
			ejax.addCancelButton();
			ejax.addSubmitButton('', callback);
			eblog.system.dialog('COM_EASYBLOG_ARE_YOU_SURE_YOU_WANT_TO_REMOVE_COMMENT', '', 'CONFIRMATION');
		    return;
		},
		
		displayInlineMsg: function (msgType, msg)
		{
		    //ej('#err-msg').show();
		    ej('#err-msg').removeClass('info error');
		    ej('#err-msg').html(msg);
		    ej('#err-msg').addClass(msgType);
		    
		    if(msgType == 'info')
		    {
				setTimeout( function() {
					ej('#err-msg').removeClass('info error');
					ej('#err-msg').html('');
				}, 6000);
			}
		}
		
	},
	
	/**
	 * Featured
	 */

	featured: {
	    add: function(type, cid)
	    {
			ejax.load('Latest', 'makeFeatured', type, cid);
	    },

	    remove: function(type, cid)
		{
		    ejax.load('Latest', 'removeFeatured', type, cid);
		}

	},
	
	
	/**
	 * Spinner
	 */
	spinner: {
	
		// toggle btw the spinner and save button
		show: function() {
			ej('#blogSubmitBtn').hide();
			ej('#blogSubmitWait').show();		
		},
		
		// toggle btw the spinner and save button
		hide: function() {
			ej('#blogSubmitWait').hide();
			ej('#blogSubmitBtn').show();			
		},
		
		// for publish operation
		publish: function(id, show) {
			if(show == 1)
			{
				ej("#"+id+"Spinner").html("<img src=\""+spinnerPath+"\" alt=\"Loading\">");
			}
			else
			{
				ej("#"+id+"Spinner").html("");
			}		
		}
		
	},
	
	
	/**
	 * Elements
	 */	 	
	element: {
		
		focus: function(element) {
			ele	= '#' + element;
			ej(ele).focus();
			ejax.closedlg();			
		}
	},

	
	/**
	 * Blog
	 */
	blog: {
		
		/**
		 * HTTP POST
		 */		 		
		publish: function(url, id, status) {
			var targetUrl   = url + '&task=toggleBlogStatus&status=' + status + '&blogId=' + id;
			window.location = targetUrl;
		},
		
		remove: function(id, actionSrc) {
			var id_str = "";
			var src     = (actionSrc) ? actionSrc : 'Dashboard';
			
			ej.each(id, function() {		
				eblog.spinner.publish(id, 1);	
				if(id_str!="")
				{
					id_str += ",";
				}
				id_str += this;	
		    });
			
			ejax.load('Dashboard', 'deleteBlog', id_str, src);		
		},
		
		confirm: function(url, blogId, lbl) {
			var targetUrl   = url + '&task=deleteBlog&blogId=' + blogId;
			var callback    = 'window.location = "' + targetUrl + '";';
		    //ejax.load('dashboard','viewComment', id, mode);
			
// 			if( lbl == '' )
// 			{
// 				lbl	= 'COM_EASYBLOG_ARE_YOU_SURE_YOU_WANT_TO_REMOVE_BLOG';
// 			}

			ejax.addCancelButton();
			ejax.addSubmitButton('', callback);
		    eblog.system.dialog( 'COM_EASYBLOG_ARE_YOU_SURE_YOU_WANT_TO_REMOVE_BLOG' , '', 'CONFIRMATION');
		    return;		
		},
		
		approve: function(url, blogId, lbl) {
			var targetUrl   = url + '&task=approveBlog&blogId=' + blogId;
			var callback    = 'window.location = "' + targetUrl + '";';
		    //ejax.load('dashboard','viewComment', id, mode);
		
			ejax.addCancelButton();
			ejax.addSubmitButton('', callback);
		    eblog.system.dialog('COM_EASYBLOG_ARE_YOU_SURE_YOU_WANT_TO_APPROVE_BLOG', '', 'CONFIRMATION');
		    return;			
		},
		
		ajaxpublish: function(id, status, actionSrc) {
			var id_str  = "";
			var src     = (actionSrc) ? actionSrc : 'Dashboard';
			
			ej.each(id, function() {
				eblog.spinner.publish(id, 1);
				if(id_str!="")
				{
					id_str += ",";
				}
				id_str += this;	
		    });
			ejax.load('Dashboard', 'togglePublishStatus', id_str, status, src);			
		},
		
		// show subscription
		subscription: {

			show: function(id) {
				ejax.load('Entry', 'showSubscription', id );
			},
			
			submit: function() {
			
				eblog.system.loader(true);

				finalData	= ejax.getFormVal('#frmSubscribe');
				ejax.load('Entry', 'addSubscription', finalData);
			}
		},
		
		
		action: function(param, url) {
			var count		= 0;
			var cids    	= "";
			var actionStr   = ej("#"+param).val();
		
			if(actionStr == '')
			{
				eblog.system.alert('COM_EASYBLOG_PLEASE_SELECT_ACTION_TO_PERFORM', 'COM_EASYBLOG_WARNING');
				return;
			}
		
		    ej("#adminForm INPUT[name='cid[]']").each( function() {
		        if ( ej(this).attr('checked') ) {
		            if(cids.length == 0)
		            {
		                cids    = ej(this).val();
		            }
		            else
		            {
		                cids    = cids + ',' + ej(this).val();
		            }
		            count++;
				}
			});
		
			if(count <= 0)
			{
				eblog.system.alert('COM_EASYBLOG_PLEASE_SELECT_ONE_ITEM_TO_CONTINUE', 'COM_EASYBLOG_WARNING');
				return;
			}
		
			if(actionStr == 'unpublishBlog')
			{
				ejax.load('Dashboard', 'togglePublishStatus', cids, '0');
			}
			else if(actionStr == 'publishBlog')
			{
			    ejax.load('Dashboard', 'togglePublishStatus', cids, '1');
			}
			else if(actionStr == 'deleteBlog')
			{
			    //showConfirmBlogDelete(url, cids, '')
			    eblog.blog.confirm(url, cids, '');
			}		
		},
		
		
		/**
		 * Tab section in blog.read.php
		 */
		tab: {
			
			init: function() {
				// set default to comment button
				//ej('.tab_button .comments').addClass('item-active');
				
				// hide all containers
				ej('.tab_container').hide();
				
				// show 1st item			
				//ej('.tab_container:first').show();
				
				if ( ej('#section-comments').length > 0 ) {
					ej('#section-comments').show();
				}
				else if ( ej('#section-trackbacks').length > 0 ) {
					ej('#section-trackbacks').show();
				}
				else if ( ej('#section-author').length > 0 ) {
					ej('#section-author').show();
				}
				
				ej('.tab_item:first').addClass('item-active');
				
				// bind click function
				ej('.tab_button .tab_item').click( function() {
					if ( ej(this).hasClass('item-active') ) {
						return false;
					}
					else {
						ej('.tab_button .tab_item').each( function() {
							if ( ej(this).hasClass('item-active') ) {
								ej(this).removeClass('item-active');
							}
						});
						
						ej(this).addClass('item-active');
						
						// hide all other container
						ej('.tab_container').slideUp(100).fadeOut(100);
						
						// get id from element
						var _id = ej(this).attr('id');
						var _x = _id.split('-');
						var id = _x[1];
						
						ej('#section-' + id).fadeIn('fast').slideDown('fast');
					}
					
					return false;
				});		
			}
			
		}		
		
	},
	
	
	/**
	 * Blogger
	 */
	blogger: {
		
		subscription: {
		
			show: function(id)
			{
				ejax.load('Blogger', 'showSubscription', id);
			},
			
			submit: function()
			{
			    eblog.system.loader(true);
			
				finalData	= ejax.getFormVal('#frmSubscribe');
				ejax.load('Blogger', 'addSubscription', finalData);
			}
		}
	},
	 
	 
	/**
	 * Categories
	 */
	category: {
	
	    subscription: {
			show: function(id)
			{
				ejax.load('Categories', 'showSubscription', id);
			},

			submit: function()
			{
			    eblog.system.loader(true);
			
				finalData	= ejax.getFormVal('#frmSubscribe');
				ejax.load('Categories', 'addSubscription', finalData);
			}
	    },
		
		remove: function(url, catId, lbl) {
			var targetUrl   = url + '&task=deleteCategory&categoryId=' + catId;
			var callback    = 'window.location = "' + targetUrl + '";';
		
			ejax.addCancelButton();
			ejax.addSubmitButton('', callback);
		    eblog.system.dialog('COM_EASYBLOG_ARE_YOU_SURE_YOU_WANT_TO_REMOVE_CATEGORY', '', 'CONFIRMATION');
		    return;			
		},
		
		edit: function(id) {
			ejax.load('Dashboard', 'editCategoryDialog', id);		
		},
		
		save: function() {
		    //get form elements for later ajax submit
			finalData	= ejax.getFormVal('#frmEditCategory');
			
			//do the form post submit for avatar into hidden iframe.
			ej('#frmEditCategory').submit();
			
			//now submit the ajax.
			ejax.load('Dashboard', 'saveCategory', finalData);
			return;
		}
	},
	
	
	/**
	 * Tags
	 */
	tag: {
		
		remove: function(url, tagId, lbl) {
			var targetUrl   = url + '&task=deleteTag&tagId=' + tagId;
			var callback    = 'window.location = "' + targetUrl + '";';
		
			ejax.addCancelButton();
			ejax.addSubmitButton('', callback);
		    eblog.system.dialog('COM_EASYBLOG_ARE_YOU_SURE_YOU_WANT_TO_REMOVE_TAG', '', 'CONFIRMATION');

		    return;		
		},
		
		edit: function(id) {
			ejax.load('Dashboard', 'editTagDialog', id);
		},
		
		/**
		 * Actions
		 */
		action: function(param, url) {
			var count	= 0;
			var cids    = "";
			var actionStr   = ej("#"+param).val();

			if(actionStr == '')
			{
				eblog.system.alert('COM_EASYBLOG_PLEASE_SELECT_ACTION_TO_PERFORM', 'COM_EASYBLOG_WARNING');
				return;
			}

		    ej("#adminForm INPUT[name='cid[]']").each( function() {
		        if ( ej(this).attr('checked') ) {
		            if(cids.length == 0)
		            {
		                cids    = ej(this).val();
		            }
		            else
		            {
		                cids    = cids + ',' + ej(this).val();
		            }
		            count++;
				}
			});

			if(count <= 0)
			{
				eblog.system.alert('COM_EASYBLOG_PLEASE_SELECT_ONE_ITEM_TO_CONTINUE', 'COM_EASYBLOG_WARNING');
				return;
			}

			if(actionStr == 'deleteTag')
			{
				eblog.tag.confirm(url, cids, '');
			}
		},
		
		confirm: function(url, tagId, lbl)
		{
			var targetUrl   = url + '&task=deleteTag&tagId=' + tagId;
			var callback    = 'window.location = "' + targetUrl + '";';

			ejax.addCancelButton();
			ejax.addSubmitButton('', callback);
			eblog.system.dialog('COM_EASYBLOG_ARE_YOU_SURE_YOU_WANT_TO_REMOVE_TAGS', '', 'CONFIRMATION');
		    return;
		},
		
		save: function() {
			finalData	= ejax.getFormVal('#frmEditTag');
			ejax.load('Dashboard', 'saveTag', finalData);		
		}
		
	},
	
	/**
	 * Twitter
	 */
	twitter: {
		
		update: function(id) {	
			if ( id != "" )
			{
				eblog.spinner.publish(id, 1);
				ejax.load('Dashboard', 'ajaxUpdateTwitter', id);
			}		
		}
		
	},
	
	
	/**
	 * Forms
	 */
	form: {
		
		checkbox: {
			
			checkall: function() {
				ej("#adminForm INPUT[type='checkbox']").each( function() {
				    if ( ej('#toggle').attr('checked') )
						ej(this).attr('checked', true);
			  		else
			  		    ej(this).attr('checked', false);
				});
				return false;				
			}
		}
		
	},
	
	
	/**
	 * Trackbacks
	 */
	trackback: {
		
		url: {
			
			copy: function() {
				ej( '#trackback-url' ).focus().select();
			}
			
		}
		
	},
	
	
	/**
	 * Adminpanel for blog posts
	 */
	adminpanel: {
		
		show: function(element) {
			ej('#' + element + ' .adminpanel').fadeIn(100);
		},
		
		hide: function(element) {
			ej('#' + element + ' .adminpanel').fadeOut('fast');
		},
		
		hideall: function() {
			if ( ej('.adminpanel').length > 0 ) {
				ej('.adminpanel').hide();
			}
		}
		
	},
	
	
	/**
	 * Admin_menu for blog posts
	 * 
	 * substitute for the problematic adminpanel	 	 
	 */
	adminmenu: {
		
		show: function(element) {
			ej('#' + element + ' ul').show();
			
			// this is fix for IE zIndex issue
			ej('#' + element + ' ul').parent().css({ zIndex: '4000' });
		},
		
		hide: function(element) {
			ej('#' + element + ' ul').hide();
			
			// this is fix for IE zIndex issue
			ej('#' + element + ' ul').parent().css({ zIndex: '1' });
		},
		
		hideall: function() {
			if ( ej('.admin_menu').length > 0 ) {
				ej('.admin_menu ul').hide();
			}
		},
		
		toggle: function(e) {
			if ( ej('#' + e).hasClass('menu_open') ) {
				eblog.adminmenu.hide(e);
				ej('#' + e).removeClass('menu_open');
			}
			else {
				eblog.adminmenu.show(e);
				ej('#' + e).addClass('menu_open');
			}
// 			console.log(e);			
		}
		
	},
	
	

	/**
	 *  Common method for EasyBlog
	 */

	system: {
	    alert: function ( text, title ) {
	    
	    	var _text  = escape(ejax.string(text));
	    	var _title = escape(ejax.string(title));
	    	ejax.alert(_text, _title, '450', 'auto');

			//ejax.load('Latest', 'ajaxShowAlertDialog', _text, _title);
	    },
	    
	    dialog: function (text, callback, title) {
	    
	    	var _text  = escape(ejax.string(text));
	    	var _title = escape(ejax.string(title));
	        ejax.dialog( _text, callback,  _title , '450', 'auto');
	        //ejax.load('Latest', 'ajaxShowDialog', text, callback, title);
	    },
	    
	    getString: function ( text ) {
			var str = ejax.string( text );
			return str;
	    },
	    
	    loader: function (show) {
	    
	        if(show)
	        {
	            if(jQuery('img#easyblog-loader').length > 0)
	            {
	                jQuery('img#easyblog-loader').remove();
	            }
	        
	            var img  = new Image;
	            img.src  = '/components/com_easyblog/assets/icons/wait.gif';
	            img.name = 'easyblog-loader';
	            img.id 	 = 'easyblog-loader';
	            
	            
	            var divBody     = jQuery('div#eblog-wrapper');
	            var divWidth	= divBody.width();
	            
	            //divHeight   	= window.innerHeight || self.innerHeight || (de&&de.clientHeight) || window.parent.document.body.clientHeight;
	            divHeight   	= window.innerHeight || self.innerHeight || window.parent.document.body.clientHeight;
	            
	            divBody.prepend(img);
	            jQuery('img#easyblog-loader').css('marginTop', (divHeight / 2));
	            jQuery('img#easyblog-loader').css('marginLeft', (divWidth / 2));
	            jQuery('img#easyblog-loader').css('position', 'absolute');
	            jQuery('img#easyblog-loader').css('z-index', 10);
	        }
	        else
	        {
	            if(jQuery('img#easyblog-loader').length > 0)
	            {
	                jQuery('img#easyblog-loader').remove();
	            }
	        }
		}
	}
}





ej(document).ready( function() {

	// init submenu element
	eblog.dashboard.submenu.init();
	
	// init tab section in blog posts
	eblog.blog.tab.init();
	
	// init admin panel in al posts, if available
	eblog.adminpanel.hideall();
	
	// init admin panel in al posts, if available
	eblog.adminmenu.hideall();
	
// 	// bind the event
// 	eblog.adminmenu.bind();
	
	// only bind if the element exists
	if ( ej('#write-editor .write-title').length > 0 ) {
		// bind focus event to to editor title
		ej('#write-editor .write-title').bind('focus', function() {
			ej(this).parent().parent().addClass('focus');
		});
		
		// bind focus event to to editor title
		ej('#write-editor .write-title').bind('blur', function() {
			ej(this).parent().parent().removeClass('focus');
		});
	}
	
	ej('.featured_remove a').live('click', function() {
	    ej(this).parent().hide();
	    ej(this).parent().prev('.featured_add').show();
	    //ej('.featured_add').show();
 	});
 	
 	ej('.featured_add a').live('click', function() {
		ej(this).parent().hide();
	    //ej('.featured_remove').show();
	    ej(this).parent().next('.featured_remove').show();
 	});

	if ( ej('#title').length > 0 ) {
		ej('#title').bind('change', function() {
			eblog.editor.permalink();
		});
	}
	
});
