/*
 * @author Erik Anders aka --=GT-O=--Hellfire
 */

// reference local blank imageExt.BLANK_IMAGE_URL = 'images/spacer.gif';
 
// create namespace
Ext.namespace('gto');
 
// create application
var swfu;

gto.album = function() {
	var base_url = 'http://www.gtoclan.de/';
	var hisTok = ':';
	
	BeforeUpdateHandler = function(a, b)
	{
		console.log(a,b);
		return true;
	}
	
	fileDialogStartHandler = function()
	{
		
		var s = gto.album.swfu;
		
		var i = 0;
		var f = s.getFile(i++);
		while (f)
		{
			if (f.filestatus === SWFUpload.FILE_STATUS.QUEUED)
			{
				s.cancelUpload(f.id);
			}
			f = s.getFile(i++);
		}
		
	}
	
	fileQueuedHandler = function(file)
	{
		
	}
	
	fileDialogCompleteHandler = function(s, q)
	{
		var s = gto.album.swfu;
		var i = 0;
		var f = s.getFile(i++);
		
		while (f)
		{
			if (f.filestatus === SWFUpload.FILE_STATUS.QUEUED)
			{
				Ext.getCmp('filebox').setText(f.name);
				break;
			}
			f = s.getFile(i++);
		}
		
		if (gto.album.swfu.getStats().files_queued == 1 && validateUploadForm() === true)
		{
			Ext.getCmp('start-upload-btn').enable();
		}
		else
		{
			Ext.getCmp('start-upload-btn').disable();
		}
		return true;
	}
	
	// The uploadStart event handler. This function variable is assigned to upload_start_handler in the settings object 
	uploadStartHandler = function (file) 
	{ 
		var continue_with_upload = true; 
		
		Ext.getCmp('upload-progress').show();
		Ext.getCmp('upload-progress').updateProgress(0, 'Starte Upload...');
		return continue_with_upload; 
	}; 
	
	// The uploadSuccess event handler. This function variable is assigned to upload_success_handler in the settings object 
	uploadSuccessEventHandler = function (file, data) 
	{
		Ext.getCmp('upload-progress').updateProgress(1, 'Upload erfolgreich');
		
		data = Ext.decode(data);
		
		gto.album.picEditForm.form.submit({
			url: 'content.php',
			params:
			{
				load: 'ajax-album_main',
				mode: 'savepic',
				pic_url: data.pic_url.replace(data.path, ''),
				thumb_url: data.thumb_url.replace(data.path+'thumb/', '')
			},
		    waitMsg: "Speichern...",
		    success:function(form, action) {
		        /*Ext.Msg.show({
		            title:"Information",
		            msg: "Speichern erfolgreich",
		            buttons: Ext.Msg.OK,
		            icon: Ext.MessageBox.INFO
		        });*/
				gto.album.cancelPicEdit();
				Ext.History.add('p'+hisTok+action.result.pic_id); 
		    },
		    failure:function(form, e) {
		        gto.album.cancelPicEdit();
				Ext.Msg.show({
		            title:"Information",
		            msg: "Speichern fehlgeschlagen",
		            buttons: Ext.Msg.OK,
		            icon: Ext.MessageBox.ERROR
		        });
				
				//Ext.History.fireEvent('change'); 
		    }
		});
	}; 
	
	uploadProgressHandler = function (file, uploaded, total)
	{
		Ext.getCmp('upload-progress').updateProgress(uploaded/total, Ext.util.Format.fileSize(uploaded)+'/'+Ext.util.Format.fileSize(total)+' '+parseInt(uploaded/total*100)+'%');
	};
	
	validateUploadForm = function()
	{
		
		var e = Ext.get('pic_title').dom.textLength > 0 && Ext.get('pic_desc').dom.textLength > 0;
		
		if (e === true)
		{
			Ext.getCmp('filebox').enable();
			if (gto.album.swfu.getStats().files_queued == 1)
			{
				Ext.getCmp('start-upload-btn').enable();
			}
		}
		else
		{
			Ext.getCmp('filebox').disable();
			Ext.getCmp('start-upload-btn').disable();
		}
		return e;
	}
	
	return {
		init: function()
		{   
			
			Ext.QuickTips.init();
			Ext.History.init();
			Shadowbox.init();
			
			this.spot =  new Ext.Spotlight
			(
				{
					easing: 'easeOut',
					duration: .3
				}
			);
			
			this.swfu = new SWFUpload({
				upload_url: base_url+"content.php",
				post_params: {load: 'ajax-album_main', mode: 'upload'},
				flash_url: base_url+"flash/swfupload.swf",
				file_types : "*.jpg", 
				file_size_limit : "1024",
				button_placeholder_id: 'filebox-tmp',
				//file_queue_limit: 1,
				file_queued_handler : fileQueuedHandler,
				file_dialog_start_handler: fileDialogStartHandler,
				file_dialog_complete_handler: fileDialogCompleteHandler,
				upload_start_handler: uploadStartHandler,
				upload_progress_handler: uploadProgressHandler,
				upload_success_handler: uploadSuccessEventHandler
			}); 
			
			Ext.History.on('change', function(token){
				var h = window.location.hash;
				if (!token && (h.indexOf(hisTok) != -1))
				{
					token = h.substr(1);
				}
				
				if(token){
		            var parts = token.split(hisTok);
		            switch(parts[0])
					{
						case 'm':
							this.loadMain(parts[1]);
							break;
						case 'c':
							this.loadCat(parts[1]);
							break;
						case 'p':
							this.loadPic(parts[1]);
							break;
						default:
							this.loadMain(1);
							break;
					}
		        }
		    }, this);
			
			if (window.location.hash == '')
			{
				Ext.History.add('m'+ hisTok + 1);
			}
			else
			{
				Ext.History.fireEvent('change');
			}
			
			
		},
		
		loadMain: function(b)
		{			
			Ext.get('album-content').load({
				url: 'content.php',
				params: 'load=ajax-album_main&mode=main',
				text: 'Loading...',
				callback: function()
				{
					Ext.select('span[id^="edit_"]').addListener('click', gto.album.editCat, gto.album);
					Ext.select('span[id^="delete_"]').setStyle({textDecoration: 'line-through'});
				}
			});
		},
		
		loadCat: function(c)
		{
			c = c.split(';');
			Ext.get('album-content').load({
				url: 'content.php',
				params: 'load=ajax-album_main&mode=cat&cat='+parseInt(c[0])+'&p='+(parseInt(c[1]) || 0)+'&i='+(parseInt(c[2]) || 10),
				text: 'Loading...',
				scope: this,
				callback: function()
				{
					Shadowbox.init();
					Shadowbox.setup();
					
					var a = Ext.get('picsperpage').dom.innerHTML;
					Ext.get('picsperpage').dom.innerHTML = '';
					new Ext.form.NumberField(
					{
						id: 'ppp',
						name: 'ppp',
						autoCreate: {tag: "input", type: "text", size: "2", autocomplete: "off"},
						value: a,
						maxValue: 100,
						renderTo: 'picsperpage'
					});
			
					var b = Ext.get('currentpage').dom.innerHTML;
					Ext.get('currentpage').dom.innerHTML = '';
					new Ext.form.NumberField(
					{
						id: 'cp',
						name: 'cp',
						autoCreate: {tag: "input", type: "text", size: "2", autocomplete: "off"},
						value: b,
						minValue: 1,
						maxValue: Ext.get('totalpages').dom.innerHTML,
						renderTo: 'currentpage'
					});
					
					this.gobtn = new Ext.Button(
					{
						id: 'cg',
						name: 'cg',
						text: 'Los',
						renderTo: 'change-go',
						handler: function()
						{
							Ext.History.add('c'+hisTok+c[0]+';'+Ext.getCmp('cp').value+';'+Ext.getCmp('ppp').value);
						},
						scope: this
					});
					
					Ext.get('upload-btn').on('click', gto.album.editPic, gto.album);
					Ext.select('span[id^="del_"]').on('click', gto.album.delPic, gto.album);
				}
			});
		},
		
		loadPic: function(p)
		{
			Ext.get('album-content').load({
				url: 'content.php',
				params: 'load=ajax-album_main&mode=pic&pic='+p,
				text: 'Loading...',
				callback: function()
				{
					Shadowbox.init();
					Shadowbox.setup();
				}
			});
		},
		
		editCat: function(e, t, o)
		{
			var id = t.id.substr(5);
			var renderCT = 'cat-edit-ct';
			if (id != 0)
			{
				var cat_type = Ext.get('cattype_'+id).dom.innerHTML;
			}
			else
			{
				var cat_type = 1;
			}
			
			this.catEditForm = new Ext.FormPanel({
				id: 'cat-editor',
				formId: 'cat-editor-form',
		        labelAlign: 'top',
		        frame:true,
		        title: (id != 0) ? '"'+Ext.get('catname_'+id).dom.innerHTML+'" bearbeiten' : 'Kategorie erstellen',
		        bodyStyle: 'padding:5px 5px 0;',
		        width: 600,
		        items: [
				{
					xtype:'textfield',
					fieldLabel: 'Kategoriename',
					id: 'cat_title',
					width: 200,
					value: (id != 0) ? Ext.get('catname_'+id).dom.innerHTML : '',
					allowBlank: false,
					blankText: "Das Feld darf nicht leer sein"
				},
				{
		            xtype: 'textarea',
		            fieldLabel:'Beschreibung',
					id: 'cat_desc',
					value: (id != 0) ? Ext.get('catdesc_'+id).dom.innerHTML : '',
		            height:200,
		            anchor:'98%',
					allowBlank: false,
					blankText: "Das Feld darf nicht leer sein"
		        },
				{
					xtype: 'radiogroup',
					fieldLabel: 'Art der Kategorie',
					columns: [65, 100, 100],
					items:
					[
						{
							name: 'cat_type',
							boxLabel: 'Offen',
							inputValue: 1,
							checked: (cat_type == 1) ? true : false
						},
						{
							name: 'cat_type',
							boxLabel: 'Geschlossen',
							inputValue: 2,
							checked: (cat_type == 2) ? true : false
						},
						{
							name: 'cat_type',
							boxLabel: 'Versteckt',
							inputValue: 3,
							checked: (cat_type == 3) ? true : false
						}
					]
				},
				{
		            xtype: 'hidden',
					id: 'cat_id',
					value: id
		        }],

		        buttons: [{
		            text: 'Speichern',
					type: 'submit',
					scope: this,
					handler: function (btn, e)
					{
						this.catEditForm.form.submit({
							url: 'content.php',
							params: 'load=ajax-album_main&mode=savecat',
				            waitMsg: "Speichern...",
				            success:function(form, e) {
				                Ext.Msg.show({
				                    title:"Information",
				                    msg: "Speichern erfolgreich",
				                    buttons: Ext.Msg.OK,
				                    icon: Ext.MessageBox.INFO
				                });
								gto.album.spot.hide();
								Ext.get('cat-editor').remove();
								Ext.History.fireEvent('change'); 
				            },
				            failure:function(form, e) {
				                Ext.Msg.show({
				                    title:"Information",
				                    msg: "Speichern fehlgeschlagen",
				                    buttons: Ext.Msg.OK,
				                    icon: Ext.MessageBox.ERROR
				                });
				            }
				        });
					}
		        },{
		            text: 'Abbrechen',
					handler: this.cancelCatEdit
		        }]
		    });

		    this.catEditForm.render(renderCT);
			gto.album.spot.show('cat-editor');
	
			return false;
		},
		
		cancelCatEdit : function (btn, e)
		{
			gto.album.spot.hide();
			Ext.get('cat-editor').remove();
		},
		
		editPic: function(e, t, o)
		{
			Ext.get('sliced-05').mask();
			
			var renderCT = 'content_container';
			
			this.picEditForm = new Ext.FormPanel({
				id: 'pic-editor',
				formId: 'pic-editor-form',
		        labelAlign: 'top',
		        frame:true,
		        title: 'Bild hochladen',
		        bodyStyle: 'padding:5px 5px 0;',
		        width: 600,
		        items: [
				{
					xtype:'textfield',
					fieldLabel: 'Name des Bildes',
					id: 'pic_title',
					width: 200,
					value: '',
					allowBlank: false,
					blankText: "Das Feld darf nicht leer sein"
				},
				{
		            xtype: 'textarea',
		            fieldLabel:'Beschreibung',
					id: 'pic_desc',
					value: '',
		            height:200,
		            anchor:'98%',
					allowBlank: false,
					blankText: "Das Feld darf nicht leer sein"
		        },
				{
					xtype: 'radiogroup',
					fieldLabel: 'Art des Bildes',
					columns: [65, 100],
					items:
					[
						{
							name: 'pic_type',
							boxLabel: 'Sichtbar',
							inputValue: 1,
							checked: true
						},
						{
							name: 'pic_type',
							boxLabel: 'Versteckt',
							inputValue: 3,
							checked: false
						}
					]
				},
				{
		            xtype: 'button',
					text: 'Datei zum Hochladen ausw&auml;hlen (*.jpg)',
					id: 'filebox',
					scope: this,
					disabled: true,
					handler: function()
					{
						this.swfu.selectFile();
					}
		        },
				new Ext.ProgressBar(
				{
					id: 'upload-progress',
					width: 570,
					hidden: true,
					style:
					{
						marginTop: '10px',
						width: '100%'
					}
				}),	
				{
		            xtype: 'hidden',
					id: 'cat_id',
					value: parseInt(Ext.get('span-cat-id').dom.innerHTML)
		        }
				],

		        buttons: [{
		            text: 'Speichern',
					type: 'submit',
					id: 'start-upload-btn',
					disabled: true,
					scope: this,
					handler: function (btn, e)
					{
						this.swfu.startUpload();
					}
		        },{
		            text: 'Abbrechen',
					handler: this.cancelPicEdit
		        }]
		    });

			this.picEditForm.render(renderCT);
			
			Ext.get('pic_title').on(
			{
				'keyup': validateUploadForm,
				scope: this,
				delay: 400
			});		
			
			Ext.get('pic_desc').on(
			{
				'keyup': validateUploadForm,
				scope: this,
				delay: 400
			});
			
			Ext.get('pic-editor').setStyle(
			{
				left: '240px',
				top: '10px',
				position: 'absolute',
				zIndex: 99999
			});
		},
		
		cancelPicEdit: function()
		{
			Ext.get('sliced-05').unmask();
			Ext.get('pic-editor').remove();
		},
		
		delPic: function(e, t, o)
		{
			var id = t.id.substr(4);
			Ext.Msg.confirm('Best&auml;tigung', 'Willst du das Bild wirklich l&ouml;schen?', function(b)
			{
				if (b = 'yes')
				{
					Ext.Ajax.request({
						url: 'content.php',
						params: 'load=ajax-album_main&mode=delpic&pic_id='+id,
						callback: function()
						{
							Ext.History.fireEvent('change');
						}
					});
				}
			}, this);
		}
	}
}();
