/**
 * @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.
 */


ejax = {
	http:		false, //HTTP Object
	format: 	'text',
	callback:	function(data){},
	error:		false,
	btnArray: 	new Array(),
	getHTTPObject : function() {
		var http = false;

		//Use IE's ActiveX items to load the file.
		if ( typeof ActiveXObject != 'undefined' ) {
			try {
				http = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch (e) {
				try {
					http = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch (E) {
					http = false;
				}
			}
		//If ActiveX is not available, use the XMLHttpRequest of Firefox/Mozilla etc. to load the document.
		} 
		else if ( XMLHttpRequest ) {
			try {http = new XMLHttpRequest();}
			catch (e) {http = false;}
		}
		this.http	= http;
	},
	
	/**
	 * Ajax function
	 */	 	
	load : function ( view, method )
	{
		// This will be the site we are trying to connect to.
		url	 = eblog_site + '/index.php?option=com_easyblog&tmpl=component&no_html=1&format=ejax&' + eblog_auth + '=1';
		
		//Kill the Cache problem in IE.
		url	+= "&uid=" + new Date().getTime();
		
		var parameters	= '&view=' + view + '&layout=' + method;
		
		// If there is more than 1 arguments, we want to accept it as parameters.
		if ( arguments.length > 2 )
		{
				
			for ( var i = 2; i < arguments.length; i++ )
			{
				var myArgument	= arguments[ i ];
				
				if(ej.isArray(myArgument))
				{
					for(var j = 0; j < myArgument.length; j++)
					{
					    var argument    = myArgument[j];

						if ( typeof( argument ) == 'string' )
						{
							// Regular expression to check if the argument have () or not
							var expr = /^\w+\(*\)$/;
							// check the argument
							var match = expr.exec( argument );

							var arg = argument;

							if ( !match ) {
								arg = escape( arg );
							}

							// Encode value to proper html entities.
							parameters	+= '&value' + ( i - 2 ) + '[]=' + encodeURIComponent( arg );
						}
					}
				}
				else
				{
				    var argument    = myArgument;
					if ( typeof( argument ) == 'string' )
					{
						// Regular expression to check if the argument have () or not
						var expr = /^\w+\(*\)$/;
						// check the argument
						var match = expr.exec( argument );

						var arg = argument;

						if ( !match ) {
							arg = escape( arg );
						}

						// Encode value to proper html entities.
						parameters	+= '&value' + ( i - 2 ) + '=' + encodeURIComponent( arg );
					}
				}
				
				
				
				
			}
		}

		this.getHTTPObject(); //The XMLHttpRequest object is recreated at every call - to defeat Cache problem in IE
		
		if ( !this.http || !view || !method ) return;
		
// 		if ( this.http.overrideMimeType )
// 			this.http.overrideMimeType( 'text/xml' );

		var ths = this;//Closure

		this.http.open( 'POST' , url , true );

		// Required because we are doing a post
		this.http.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
		this.http.setRequestHeader( "Content-length", parameters.length );
		this.http.setRequestHeader( "Connection", "close" );

		this.http.onreadystatechange = function(){
			//Call a function when the state changes.
			if(!ths)
				return;

			var http = ths.http;

			if (http.readyState == 4)
			{
				//Ready State will be 4 when the document is loaded.
				if(http.status == 200)
				{
					var result = "";
					
					if(http.responseText)
					{
						result = http.responseText;
					}
					
					// Evaluate the result before processing the JSON text. New lines in JSON string, 
					// when evaluated will create errors in IE.
					result	= result.replace(/[\n\r]/g,"");
					
					//alert(result);
					
					result	= eval( result );

					//Give the data to the callback function.
					ths.process( result );
				}
				else
				{
					//An error occured
					if(ths.error) ths.error(http.status);
				}
			}
		}
		this.http.send( parameters );
	},
	
	/**
	 * Method to get translated string from server
	 *
	 * @param	string
	 */
	string: function( str ) {
		var url	 = eblog_site + '/index.php?option=com_easyblog&tmpl=component&no_html=1&controller=easyblog&task=ajaxGetSystemString';
		//url  	 = url + "&uid=" + new Date().getTime();
		
		var r1 = ej.ajax({
		    type: "POST",
			url: url,
			data: "data=" + str,
			async: false,
			cache: true
		}).responseText;
		
		return r1;
	},
	
	/**
	 * Get form values
	 * 
	 * @param	string	Form ID	 	 
	 */	 	
	getFormVal : function( element ) {

	    var inputs  = [];
	    var val		= null;
		
		ej( ':input', ej( element ) ).each( function() {
			val = this.value.replace(/"/g, "&quot;");
			val = encodeURIComponent(val);
			
			if(ej(this).is(':checkbox') || ej(this).is(':radio'))
		    {
				if(ej(this).attr('checked'))
				    inputs.push( this.name + '=' + escape( val ) );
		    }
		    else
		    {
				inputs.push( this.name + '=' + escape( val ) );
			}
		});
		//var finalData = inputs.join('&&');
		//return finalData;
		return inputs;
	},
	
	process : function ( result ){
		// Process response according to the key
		for(var i=0; i < result.length;i++)
		{
			var action	= result[ i ][ 0 ];
			
			switch( action )
			{
				case 'script':
					var data	= result[ i ][ 1 ];
					eval( data );
					break;
					
				case 'after':
					var id		= result[ i ][ 1 ];
					var value	= result[ i ][ 2 ];
					ej( '#' + id ).after( value );					
					break;					
					
				case 'append':
					var id		= result[ i ][ 1 ];
					var value	= result[ i ][ 2 ];
					ej( '#' + id ).append( value );					
					break;
					
				case 'assign':
					var id		= result[ i ][ 1 ];
					var value	= result[ i ][ 2 ];
					
					ej( '#' + id ).html( value );
					break;
				
				case 'value':
					var id		= result[ i ][ 1 ];
					var value	= result[ i ][ 2 ];
					
					ej( '#' + id ).val( value );
					break;
					
				case 'prepend':
					var id		= result[ i ][ 1 ];
					var value	= result[ i ][ 2 ];
					ej( '#' + id ).prepend( value );
					break;
					
				case 'destroy':
					var id		= result[ i ][ 1 ];
					ej( '#' + id ).remove();
					break;
					
				case 'dialog':
					ejax.dialog( result[ i ][ 1 ], result[ i ][ 2 ], result[ i ][ 3 ] , result[i][4],result[i][5]);
					break;
					
				case 'alert':
					ejax.alert( result[ i ][ 1 ], result[ i ][ 2 ], result[ i ][ 3 ] );
					break;
					
				case 'addSubmitButton':
					ejax.addSubmitButton( result[ i ][ 1 ], result[ i ][ 2 ]);
					break;
					
				case 'addCancelButton':
					ejax.addCancelButton( result[ i ][ 1 ]);
					break;
					
				case 'addButton':
					ejax.addButton( result[ i ][ 1 ], result[ i ][ 2 ]);
					break;
					
				case 'create':
					break;
			}
		}
		delete result;
	},
	
	/**
	 * Dialog
	 */	 	
	dialog: function( content, callback, title, width, height ) {
		ejax._showPopup( 'dialog', content, callback, title, width, height );
	},
	
	/**
	 * Alert
	 */
	alert: function( content, title, width, height ) {
		ejax._showPopup( 'alert', content, '', title, width, height );
	},
	
	// Close dialog box
	closedlg: function() {
	    ej('.dialog').fadeOut('fast', function() {
			ej('#eblog-dialog').remove();
		});
	},
	

	addSubmitButton: function ( label, callback ) {
	    var okLBL       = ejax.string('COM_EASYBLOG_OK');
	
	    var btnLabel    = (label) ? label : okLBL;
		ejax.addButton(btnLabel, callback, 'submit');
	},
	
	addCancelButton: function ( label ) {
	    var cancelLBL       = ejax.string('COM_EASYBLOG_CANCEL');
	
	    var btnLabel    = (label) ? label : cancelLBL;
		ejax.addButton(btnLabel, '', 'cancel');
	},
	
	addButton: function (label, callback, prefix) {
	    var buttonAttr  = {
	                        prefix:null,
							lbl:null,
						    callback:null
	                      };

		buttonAttr.lbl  		= label;
		buttonAttr.callback  	= (callback) ? callback : '';
		buttonAttr.prefix  		= (prefix) ? prefix : 'custom';
	                      
	    this.btnArray.push(buttonAttr);
	},
	
	_generateButton: function( type, callback ) {
		//alert(this.btnArray.length);
	
	    if(this.btnArray.length <= 0)
	    {
	        if((type == 'dialog') && (callback))
	        {
	            ejax.addSubmitButton('', callback);
	        }
	        else if (((type == 'dialog') && (! callback)) || (type == 'alert'))
	        {
				var defaultLbl  = '';
				if(type == 'alert')
	                defaultLbl  = ejax.string('COM_EASYBLOG_OK');
	            else
	                defaultLbl  = ejax.string('COM_EASYBLOG_CLOSE');
	                
	            ejax.addCancelButton(defaultLbl);
	        }
	    }
	    
	    var myBtn   = '';

		ej.each(this.btnArray, function( i, btn) {
		    var nBtn    = (btn.prefix == 'custom') ? 'edialog-custom' + i : 'edialog-' + btn.prefix;
		    var cBtn    = '<span class="dialog-bottom-actions-' +btn.prefix+ '"><span class="inner"><input type="button" name="' + nBtn + '" id="' + nBtn + '" class="button" value="' +btn.lbl+ '" /></span></span>';
		    
		    //ej('#eblog-dialog .dialog-bottom .dialog-bottom-actions').append(cBtn);
		    myBtn   += cBtn;

		    if(btn.prefix == 'cancel')
		    {
				ej('#edialog-cancel').live('click', function() {
				    ej('#edialog-cancel').die();
				 	ejax.closedlg();
				});
		    }
		    else if(btn.prefix == 'submit')
		    {
				// bind callback to OK button
				ej('#edialog-submit').live('click', function() {
				    ej('#edialog-submit').die();
				    ejax.closedlg();
				    if(btn.callback)
				    {
		            	eval( btn.callback );
		            }
				});
		    }
		    else
		    {
				// bind custom button to it call back
				ej('#'+ nBtn).live('click', function() {
				    ej('#'+ nBtn).die();
				    ejax.closedlg();
				    if(btn.callback)
				    {
						// eval the callback
	            		eval( btn.callback );
				    }
				});
			}
		});
		
		//remove generated button
		this.btnArray = new Array();
		
		return myBtn;
	},
	
	/**
	 * Private function
	 * 
	 * Generate dialog and popup dialog
	 */	 	 	 	
	_showPopup: function( type, content, callback, title, width, height ) {

		//var eWidth = width == null ? '500' : width;
		var eWidth = (width) ? width : '500';
		
		//clear if previous dialog shown
		if(ej('#eblog-dialog').length > 0 )
		{
		    ej('#eblog-dialog').remove();
		}
		
		if ( ej('#eblog-dialog').length <= 0 )
		{
			ej('body').append('<div id="eblog-dialog"></div>');
			
			var _dlg = '';

			_dlg += '		<div class="dialog" style="width: ' + eWidth + 'px;">';
			_dlg += '			<div class="dialog-top clearfix">';
			_dlg += '				<span class="dialog-top-left"></span>';
			_dlg += '				<span class="dialog-top-right"></span>';
			_dlg += '				<div class="dialog-top-title">';
			_dlg += '					<h3>' + unescape( title ) + '</h3>';
			_dlg += '					<a href="javascript:void(0);" onclick="ejax.closedlg();" class="closeme">Close</a>';
			_dlg += '				</div>';
			_dlg += '			</div>';
			_dlg += '			<div class="dialog-middle clearfix">';
			_dlg += '				<div class="dialog-middle-left"></div>';
			_dlg += '				<div class="dialog-middle-right"></div>';
			_dlg += '				<div class="dialog-middle-content">';
			_dlg += '				</div>';
			_dlg += '			</div>';
			_dlg += '			<div class="dialog-bottom clearfix">';
			_dlg += '				<span class="dialog-bottom-left"></span>';
			_dlg += '				<span class="dialog-bottom-right"></span>';
			_dlg += '				<div class="dialog-bottom-actions">';
			
			_dlg +=  ejax._generateButton(type, callback);
			
			// Used in dialog only
// 			if ( type == 'dialog' ) {
// 			_dlg += '					<span class="dialog-bottom-actions-cancel"><span class="inner"><input type="button" name="edialog-cancel" id="edialog-cancel" class="button" value="Cancel" /></span></span>';
// 			}
			_dlg += '				</div>';
			_dlg += '			</div>';
			_dlg += '		</div>';

			ej("#eblog-dialog").html(_dlg);

		}
		// add hover effect to dialog button
		ej('.dialog :input').hover( function() {
			ej(this).parent().parent().addClass('button-hover');
		}, function() {
			ej(this).parent().parent().removeClass('button-hover');
		});

		
		
		// clean up string
		content = content.replace(/[\n\r]/g, "");
		
		// Regular expression to check if the argument is a string, function call,
		// ej call or ejax call
		// as long as it is a function call, we will evaluate it
		var expr = /^\w+\(.*\)|ej\(.*\)|ejax\.\w+\(.*\)$/i;
		
		// check the argument
		var match = expr.exec( unescape( content ) );
		
		// if we can detect () in the string then eval it
		if ( match )
		{
			ej('.dialog-middle-content').html( '<div class="dialog-middle-content-inner">' + eval( unescape( content ) ) + '</div>' );
		}
		else
		{
			ej('.dialog-middle-content').html( '<div class="dialog-middle-content-inner">' + unescape( content ) + '</div>' );
		}

		if (!height || height == 'auto')
		{
			height	= ej('.dialog-middle-content').height();
		}
		
		ej("#eblog-dialog").show('fast', function() {
			ej('.dialog-middle-left, .dialog-middle-right, .dialog-middle-content').height(  height + 'px' );
			//ej('.dialog').fadeIn('fast');
			ej('.dialog').fadeIn(500);
		});

		//Center window based on the current browser.		
		var topMargin	= ej(document).scrollTop() + ( document.documentElement["clientHeight"] - height ) / 2;
		var leftMargin	= ( ej(window).width() - eWidth ) / 2;

		ej('.dialog').css( 'margin-top' , topMargin + 'px');
		
		if ( lang_direction == 'ltr' )
		{
			ej('.dialog').css('margin-left' , leftMargin + 'px' );
		}
		else 
		{
			ej('.dialog').css('margin-right' , leftMargin + 'px' );
		}
		 
		ej('#eblog-dialog').bind( 'keypress', function(e) {
			var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
			if ( key === 13 ) {
				ej(this).click();
			}
		});
	}
}

