/**
 * JavaScript file
 *
 * @package     NoNumber! Extension Manager
 * @version     1.4.0
 *
 * @author      Peter van Westen <peter@nonumber.nl>
 * @link        http://www.nonumber.nl
 * @copyright   Copyright (C) 2010 NoNumber! All Rights Reserved
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 */
window.addEvent( 'domready', function() {
	nnManager = new nnManager();
});

var nnManager = new Class({

	initialize: function()
	{
		this.urls = {
			'selected': new Array(),
			'install': new Array(),
			'update': new Array()
		};
		this.counters = {
			'install': 0,
			'update': 0
		};
		this.timers = {
			'install': 0,
			'update': 0
		};
	},
	
	load_extensions: function()
	{
		var self = this;

		$each( $$('.result'), function( el ) {
			el.setStyle( 'display', 'none' );
		});
		$each( $$('.loading'), function( el ) {
			el.setStyle( 'display', 'block' );
		});
		$each( $$('.license_result'), function( el ) {
			el.setStyle( 'display', 'none' );
		});
		$each( $$('.license_loading'), function( el ) {
			el.setStyle( 'display', 'block' );
		});
		
		var delay = 1;
		$each( nn_extensions, function( extension ) {
			( function(){ self.load_extension( extension.id, extension.alias, 1 ); }).delay( delay*250 );
			delay++;
		});

		this.load_license( 'all' );
	},


	load_extension: function( id, alias, first )
	{
		var self = this;

		( function(){ self.load_installed( id, alias ); } ).delay( 0 );
		( function(){ self.load_info( id, alias ); } ).delay( 100 );
		( function(){ self.load_changelog( id, alias ); } ).delay( 200 );

		if ( !first ) {
			( function(){ self.load_license( id ); } ).delay( 300 );
		}
	},

	// INSTALLED
	load_installed: function( id, alias )
	{
		if ( id == 'all' ) {
			return;
		}
		$each( $$('.result_'+id), function( el ) {
			el.setStyle( 'display', 'none' );
		});
		$each( $$('.loading_'+id), function( el ) {
			el.setStyle( 'display', 'block' );
		});

		var url = 'index.php?nn_qp=1&folder=administrator.components.com_nonumbermanager&file=details.inc.php&ext='+alias;
		nnScripts.loadajax( url, 'nnManager.set_installed( \''+id+'\', \''+alias+'\', data.trim() )', 'nnManager.set_installed( \''+id+'\', \''+alias+'\', 0 )' );
	},

	set_installed: function( id, alias, data )
	{
		var self = this;
		
		$('installed_'+id+'_loading').setStyle( 'display', 'none' );
		$('version_'+id+'_loading').setStyle( 'display', 'none' );

		if ( data === 0 ) {
			$('installed_'+id+'_failed').setStyle( 'display', 'block' );
		} else if ( data == '' ) {
			$('installed_'+id+'_notinstalled').setStyle( 'display', 'block' );
		} else {
			$('installed_'+id+'_installed').setStyle( 'display', 'block' );
			$('version_'+id+'_version').setText( 'v'+data ).setStyle( 'display', 'block' );
		}
		
		( function(){ self.load_version( id, alias, data ); } ).delay( 200 );
	},


	// CHANGELOG
	load_info: function( id, alias )
	{
		var url = 'http://www.nonumber.nl/scripts/description.php?ext='+id;
		nnScripts.loadajax( url, 'nnManager.set_info( \''+id+'\', data.trim() )', 'nnManager.set_changelog( \''+id+'\', 0 )' );
	},

	set_info: function( id, data )
	{
		$('info_'+id+'_loading').setStyle( 'display', 'none' );

		if ( data != 0 && data != '' ) {
			$$('#info_'+id+'_icon span').setProperty( 'title', NN_DESCRIPTION+'::'+data );
			JTooltips = new Tips( $$('#info_'+id+'_icon span'), { fixed: 1, className: 'tool' } );
			$('info_'+id+'_icon').setStyle( 'display', 'block' );
		} else {
			$('info_'+id+'_failed').setStyle( 'display', 'block' );
		}
	},

	// CHANGELOG
	load_changelog: function( id, alias )
	{
		var url = 'http://www.nonumber.nl/scripts/changelog.php?ext='+alias;
		nnScripts.loadajax( url, 'nnManager.set_changelog( \''+id+'\', data.trim() )', 'nnManager.set_changelog( \''+id+'\', 0 )' );
	},

	set_changelog: function( id, data )
	{
		$('changelog_'+id+'_loading').setStyle( 'display', 'none' );

		if ( data != 0 && data != '' ) {
			$$('#changelog_'+id+'_icon span').setProperty( 'title', NN_CHANGELOG+'::'+data );
			JTooltips = new Tips( $$('#changelog_'+id+'_icon span'), { fixed: 1, className: 'changlog-tip tool' } );
			$('changelog_'+id+'_icon').setStyle( 'display', 'block' );
		} else {
			$('changelog_'+id+'_failed').setStyle( 'display', 'block' );
		}
	},

	// VERSIONS
	load_version: function( id, alias, version )
	{
		var self = this;
		
		var url = 'http://www.nonumber.nl/scripts/version.php?ext='+id+'&version='+version;
		nnScripts.loadajax( url, 'nnManager.set_versionstate( \''+id+'\', data.trim() )', 'nnManager.set_versionstate( \''+id+'\', 0 )' );
	},

	set_versionstate: function( id, data )
	{
		var self = this;

		$('check_'+id+'_loading').setStyle( 'display', 'none' );
		$('version_state_'+id+'_loading').setStyle( 'display', 'none' );
		$('version_button_'+id+'_loading').setStyle( 'display', 'none' );
		if ( data && data.length > 2 ) {
			data = data.toString().split( '|' );
		}		
		if ( !data || data.length < 4 || data.length > 4 ) {
			$('version_state_'+id+'_failed').setStyle( 'display', 'block' );
		} else {
			var current_version = data[0];
			var new_version = data[1];
			var hasnew = data[2];
			var link = data[3];


			var state = 'failed';

			if ( new_version && link ) {
				if ( !current_version ) {
					state = 'install';
				} else if ( hasnew == 1 ) {
					state = 'update';
				} else if ( hasnew == 2 ) {
					state = 'downgrade';
				} else {
					state = 'uptodate';
				}
			}

			if ( link != '' ) {
				$each( $$('#row_'+id+' .new_version_number'), function( el ) {
						el.setText( 'v'+new_version );
				});
				$('version_button_'+id+'_'+state)
					.setStyle( 'display', 'block' )
					.addEvent( 'click', function() { self.install_extension( link, state ); } );
				if ( state == 'install' || state == 'update' ) {
					this.add_url( link, state );
				}
				$each( $$('#check_'+id+'_check input'), function( el ) {
						el.value = link;
				});
				if ( state != 'uptodate' && state != 'downgrade' ) {
					$('check_'+id+'_check' ).setStyle( 'display', 'block' );
					$('link_installselected' ).setStyle( 'display', 'block' );
				}
			}
			$('version_state_'+id+'_'+state ).setStyle( 'display', 'block' );
		}
	},

	// INSTALL
	install_extension: function( url, state )
	{
		var self = this;

		var text = '';
		switch ( state ) {
			case 'uptodate':
				text = NN_UPTODATE;
				break;
			case 'downgrade':
				text = NN_DOWNGRADE;
				break;
			default:
				text = NN_AREYOUSURE;
				break;
		}

		if( !confirm( text ) ) {
			return;
		}

		text = '';
		switch ( state ) {
			case 'update':
				text = NN_UPDATING;
				break;
			case 'uptodate':
				text = NN_REINSTALLING;
				break;
			case 'downgrade':
				text = NN_DOWNGRADING;
				break;
			default:
				text = NN_INSTALLING;
				break;
		}

		nnScripts.overlay.open( 0.7, text );
		url = 'index.php?option=com_installer&task=doInstall&installtype=url&tmpl=component&install_url='
			+escape( url );

		nnScripts.loadajax( url, 'nnManager.redirect( data )', 'nnManager.redirect( 0 )', NN_TOKEN+'=1' );
	},

	add_url: function( url, task )
	{
		var self = this;

		this.counters[task] = 0;
		$clear( this.timers[task] );
		this.timers[task] = ( function(){ self.counters[task]++; } ).periodical( 500 );

		this.urls[task][this.urls[task].length] = url;

		this.show_allbutton( task );
	},

	show_allbutton: function( task )
	{
		var self = this;

		$( 'link_'+task+'all' ).setStyle( 'display', 'block' );
		if ( this.timers[task] ) {
			if ( this.counters[task] < 3 ) {
				( function(){ self.show_allbutton( task ); } ).delay( 500 );
			} else {
				this.counters[task] = 0;
				$clear( this.timers[task] );
				this.timers[task] = 0;

				$( 'link_'+task+'all_loading' ).setStyle( 'display', 'none' );
				$( 'link_'+task+'all_ready' ).setStyle( 'display', 'block' );
			}
		}
	},

	install_selected: function()
	{
		var self = this;

		this.urls['selected'] = new Array();
		$each( $$('input.check_checkbox'), function( el ){
			if ( el.checked && el.value ) {
				self.urls['selected'][self.urls['selected'].length] = el.value;
			}
			el.checked = false;
		});
		$('check_toggle').checked = false;
		
		if ( this.urls['selected'].length ) {
			this.install_extensions( 'selected' );
		} else {
			alert( NN_NONESELECTED );
		}
	},
	
	install_extensions: function( task )
	{
		var self = this;

		if( !confirm( NN_AREYOUSURE ) ) {
			return;
		}

		var text = NN_INSTALLING;
		if ( task == 'update' ) {
			text = NN_UPDATING;
		}
		nnScripts.overlay.open( 0.7, text, '('+NN_MAYTAKEAWHILE+')' );

		this.urls[task] = this.array_unique( this.urls[task] );
		this.install_walk( task, this.urls[task], NN_TOKEN );
	},

	install_walk: function( task, urls, token )
	{
		var self = this;

		if ( urls != '' && typeof urls !== 'object' ) {
			urls = urls.toString().split( ',' );
		}

		if ( urls == '' || !urls.length ) {
			var msgs = ''
			if ( task == 'update' ) {
				msgs = '<dd class="message"><ul><li>'+NN_EXTENSIONSUPDATED+'</li></ul></dd>';
			} else {
				msgs = '<dd class="message"><ul><li>'+NN_EXTENSIONSINSTALLED+'</li></ul></dd>';
			}
			msgs = msgs+'<dd class="notice"><ul><li>'+NN_CLEANCACHE+'</li></ul></dd>';
			
			msgs = '<dl id="system-message">'+msgs+'</dl>'
			this.redirect(msgs);
			return;
		}

		url = urls.shift();

		var url = 'index.php?option=com_installer&task=doInstall&installtype=url&tmpl=component&install_url='
			+escape( url );

		nnScripts.loadajax( url, 'nnManager.install_walk(  \''+task+'\', \''+urls+'\',\''+token+'\' )', 'nnManager.install_walk(  \''+task+'\', \''+urls+'\', \''+token+'\' )', token+'=1' );
	},

	redirect: function( data )
	{
		if ( !data ) {
			data = '<dl id="system-message"><dd class="error"><ul><li>'+NN_INSTALLATIONFAILED+'</li></ul></dd></dl>';
		} else {
			if ( data.indexOf( '<dl id="system' ) === -1 ) {
				data = '';
			} else {
				data = data.replace( /[ \s\n]+/g, ' ' ).replace( /^.*(<dl id="system.*<\/dl>).*$/gi, '\$1' ).trim();
			}
		}
		var form = document.adminForm;

		var myInput = document.createElement( 'input' ) ;
		myInput.setAttribute( 'type' , 'hidden' ) ;
		myInput.setAttribute( 'name' , 'msgs' ) ;
		myInput.setAttribute( 'value', data.replace(/\"/g, '\\$&') );
		form.appendChild( myInput ) ;

		submitform();
	},


	// LICENSES
	save_license: function( id )
	{
		var self = this;

		$each( $$('#license_field_'+id+' .license_result'), function( el ) {
			el.setStyle( 'display', 'none' );
		});
		$each( $$('#license_state_'+id+' .license_result'), function( el ) {
			el.setStyle( 'display', 'none' );
		});
		$('license_field_'+id+'_loading').setStyle( 'display', 'block' );
		$('license_state_'+id+'_loading').setStyle( 'display', 'block' );
		
		var field = $( 'license_code_'+id );

		var url = 'index.php?option=com_nonumbermanager&task=save&extension='+id+'&code='+field.value;
		nnScripts.loadajax( url, 'nnManager.load_license( \''+id+'\', data.trim() )', '' );
	},

	load_license: function( id )
	{
		var self = this;

		$each( $$('#license_field_'+id+' .license_result'), function( el ) {
			el.setStyle( 'display', 'none' );
		});
		$each( $$('#license_state_'+id+' .license_result'), function( el ) {
			el.setStyle( 'display', 'none' );
		});
		$('license_field_'+id+'_loading').setStyle( 'display', 'block' );
		$('license_state_'+id+'_loading').setStyle( 'display', 'block' );

		if ( !$('license_state_'+id+'_valid') ) {
			this.set_licensestate( id, 'local' );
			return;
		}

		var field = $( 'license_code_'+id );
		if ( field.value ) {
			var host = $( 'license_host' );
			var url = 'http://www.nonumber.nl/scripts/license.php?host='+host.value+'&code='+field.value+'&ext='+id;
			nnScripts.loadajax( url, 'nnManager.set_licensestate( \''+id+'\', data.trim() )', 'nnManager.set_licensestate( \''+id+'\', \'failed\' )' );
		} else {
			this.set_licensestate( id, '' );
		}
	},

	load_licenses: function( valid )
	{
		var self = this;

		$each( nn_extensions, function( extension ) {
			if ( extension.id != 'nonumbermanager' ) {
				if ( valid ) {
					self.set_licensestate( extension.id, 'allvalid' );
				} else {
					self.load_license( extension.id );
				}
			}
		});
	},

	set_licensestate: function( id, state )
	{
		var self = this;

		$('license_field_'+id+'_loading').setStyle( 'display', 'none' );
		$('license_state_'+id+'_loading').setStyle( 'display', 'none' );
		$each( $$('#license_field_'+id+' .license_result'), function( el ) {
			el.setStyle( 'display', 'none' );
		});
		$each( $$('#license_state_'+id+' .license_result'), function( el ) {
			el.setStyle( 'display', 'none' );
		});

		if ( state == 'allvalid' ) {
			$('license_code_'+id+'_allvalid').value = $('license_code_all').value;
			$('license_field_'+id+'_allvalid').setStyle( 'display', 'block' );
		} else {
			$('license_field_'+id+'_field').setStyle( 'display', 'block' );
		}

		if ( state != '' ) {
			var color = '#999999';
			switch( state) {
				case 'allvalid':
				case 'valid':
					color = '#006600';
					break;
				case 'invalid':
					color = '#990000';
					break;
				case 'local':
					color = '#999999';
					break;
				default:
					color = '#999999';
					state = 'failed';
					break;
			}
			$('license_code_'+id).setStyle( 'color', color );
			$('license_state_'+id+'_'+state).setStyle( 'display', 'block' );
		}

		if ( id == 'all' ) {
			this.load_licenses( ( state == 'valid' ) );
		}

	},

	// CUSTOM FUNCTIONS
	array_unique: function( a )
	{
	   var r = new Array();
	   o:for(var i = 0, n = a.length; i < n; i++) {
		  for(var x = i + 1 ; x < n; x++)
		  {
			 if(a[x]==a[i]) continue o;
		  }
		  r[r.length] = a[i];
	   }
	   return r;
	}
});