function array(){
	return Array.prototype.slice.call(arguments);
}

var eagle = {
	lang : {
		current : 'nb',
		
		en : {
			uploadedSuccessfully : ['Uploading completed', 'Your files have been uploaded successfully!'],
			reachedMaxLimit : ['Max limit reached', 'You can upload max 5 files simultaneously!'],
			duplicateFilesExist : ['Duplicate files','You are trying to upload a file that already exists on the uploader!'],
			uploadButton : 'Start uploading...',
			uploadIsEmpty : ['None files selected','You have to select at least one file before trying to upload!'],
			yes_delete : 'Yes, delete',
			cancel : 'Cancel',
			save : 'Save',
			send : 'Send'
		},
		nb : {
			uploadedSuccessfully : ['Opplasting var vellyket', 'Dine filer har blitt lastet opp!'],
			reachedMaxLimit : ['Maks opplastede filer', 'Du kan kun laste opp 5 filer samtidig!'],
			duplicateFilesExist : ['Duplikat filer eksisterer','Du prøver å laste opp filer som allerede finnes på opplasting kontainereren!'],
			uploadButton : 'Start opplasting...',
			uploadIsEmpty : ['Ingen filer valgt','Du må velge minst en fil før du kan begynne å laste opp!'],
			yes_delete : 'Ja, slett',
			cancel : 'Avbrytt',
			save : 'Lagre',
			send : 'Send'
		}
	},
	
	request : {
		sender : {
			load : function(o){
				$(o.target).data(':postdata', o.postdata);
				$.post(
					o.url, o.postdata,
					function(r){
						$(o.target).html(r);
						oxo.dialog.open({
							id : o.target, 
							opt : {
								width : 420,
								title : o.title,
								
								buttons : [{
									text : oxo.lang.translate('send'),
									click : function() {
										eagle.request.sender.send(o);	
								    }},{
								    	text : oxo.lang.translate('cancel'),
										click : function() {
											oxo.form.reset('#frm-send');
											$(this).dialog("close");
										}
								}]
							}	
						});
					}
				);
			},
			send : function(o){
				var selected 	= oxo.grid.init('#grid').getSelectedRows();
				var customdata 	= {'files' : selected};
				
				
				oxo.form.submit(
					'#frm-send', 
					customdata,
					function(_o){
						$(o.target).dialog("option", "position", 'center');
						
						if(_o.type == 'success'){
							oxo.form.reset('#frm-send');
						}
					}
				);
			}
		},
		file : {
			edit : function(o){
				$(o.target).data(':postdata', o.postdata);
				$.post(
					o.url, o.postdata,
					function(r){
						
						oxo.dialog.open({id : o.target, opt : {width : 420, title : o.title	}});
						
						if(typeof(r) == "string"){
							$(o.target).html(r);
							
							oxo.dialog.setButtons([{
								text : oxo.lang.translate('save'),
								click : function() {eagle.request.file.save(o);}
							},{
								text : oxo.lang.translate('cancel'),
								click : function() {
									oxo.form.reset('#frm-file');
									$(this).dialog("close");
								}}]);
						}else{

							var notice = oxo.notice.create(null, r.content, r.type, true);
							$(o.target).html(notice);
							oxo.notice.refresh();
							
							oxo.dialog.setButtons([{
								text : oxo.lang.translate('cancel'),
								click : function() {
									oxo.form.reset('#frm-file');
									$(this).dialog("close");
								}}]);
						}
						
						
						
						
					}
				);
			},
			
			save : function(o){
				var id 	= oxo.grid.init('#grid').getSelectedRow();

				oxo.form.submit(
					'#frm-file', 
					{'id' : id},
					function(_o){
						$(o.target).dialog("option", "position", 'center');
						
						if(_o.type == 'success'){
							oxo.grid.refresh();
							oxo.grid.setSelectedRow(id);
						}
					}
				);
			},
			
			remove : function(o){
				$(o.target).html('<div class="msg-container margin-t-15"></div>' + o.content + '<br />');
				oxo.dialog.open({
					id : o.target,
					opt : {
						width : 420,
						title : o.title,
						buttons : [
						     {
								text : oxo.lang.translate('yes_delete'),
								click : function() {
									$.post(o.url, o.postdata, function(r){
										var notice = oxo.notice.create(null, r.content, r.type, true);
										
										$(o.target).closest('div')
											   .find('.msg-container')
											   .html(notice);
										
										if(r.type == 'success'){
											oxo.grid.init('#grid').refresh();
											
											$(o.target).dialog('close');
										}
										
									});
								}
						    },{
						    	text : oxo.lang.translate('cancel'),
								click : function() {
									$(this).dialog("close");
								}
							}]
					}	
				});
				
				$('.ui-dialog-buttonpane :button').each(function(){
			        if($(this).text() == oxo.lang.translate('yes_delete')){
			            $(this).addClass('btn-color btn-color-red no-padding');
					}
				});
			}
		}
		
	},
	
	method : {
		send : {
			load : function(o){
				
				
			},
			
			remove : function(o){
				
			},
			
			reset : function(){
				
			},
			
			send : function(o){
				
			}
		}
	},
	
	upload : {
		uploader : null,
		applet : null,
		interval : null,
		formelm : null,
		
		start : function(){
			var count = this.uploader.getFileCount();
			if(count > 0){
				$('#msgcontainer').html('');
				this.uploader.startUpload();
			}else{
				var msg = eagle.upload.templates.messages(null, oxo.lang.translate('uploadIsEmpty'));
				
				$('#msgcontainer').html(msg);
				$('.closeable').notifyclose({animation: 'fade&slide', speed: 400});
			}
			
			return false;
		},
		
		send : function(form){
			var selected 	= oxo.grid.init('#grid').getSelectedRows();
			var customdata 	= {'files' : selected};
			oxo.form.submit(form, customdata);
		},
		
		reset : function(){
			this.uploader.destroy();
		},
		
		stop : function(){
			this.uploader.stopUpload();
		},
		
		callbacks: {
			uploaderFileRemoved : function(file, uploader){
				$('#' + file.getId()).toggle('highlight',function(){
					$(this).remove();
				});
			},
			
			uploaderFileStatusChanged : function(file, uploader){
				if(file.getStatus() == eagle.upload.file.STATUS_UPLOADING){
					eagle.upload.file.progressTimerId = 
						setTimeout(function(){eagle.upload.file.progress(file);},1000);
				}
				
				if(file.getStatus() == eagle.upload.file.STATUS_FINISHED){
					clearTimeout(eagle.upload.file.progressTimerId);
				}
			},
			
			uploaderStatusChanged : function(uploader){
				var isUploading = uploader.isUploading();
				
				if(!isUploading){
					
					var msg = eagle.upload.templates.messages(null, oxo.lang.translate('uploadedSuccessfully'), 'success');
					$('#msgcontainer').html(msg);
					$('.closeable').notifyclose({animation: 'fade&slide', speed: 400});
					
					
					oxo.grid.init('#grid').refresh();
				}
			},
			
			fileAdded : function(uploader, file){
				var rules = $('#notice-rules');
				var howto = $('#notice-howto-upload');
				
				if(rules.is(":visible") && howto.is(":visible")){
					rules.fadeTo(300, 0, function(){$(this).slideUp(300);});
					howto.fadeTo(300, 0, function(){$(this).slideUp(300);});
				}
	
				eagle.upload.file.queue.add(file);
			},
			
			messages : function(uploader, type, message, msgcontainer){
				
				var msg = eagle.upload.templates.messages(null, message);
				
				$('#' + msgcontainer).html(msg);
				$('.closeable').notifyclose({animation: 'fade&slide', speed: 400});
				
			}
		},
		
		progress : function(){
			
			
//			var files = eagle.upload.file.queue.files;
//			$each(function(id, file){
//				var progressbar = $('progressbar-' + id);
//			});
//			
//			
//			for(i = 0; i < files.length; i++){
//				var file 	= files[i];
//				var id 	= file.getId();
//				var pb 		= $('#progressbar-' + id);
//				
//				if(file.isUploading()){
//					var transfer = file.getTransferProgress();
//					pb.progressbar('value', transfer.getCompletionPercent());		
//					setTimeout("eagle.upload.progress()", 100);
//				}else if(file.isFinished()){
//					pb.attr("background-image", "jquery/images/loaded.gif");
//					pb.progressbar('value', 100);
//					
//					var li = pb.closest('li');
//					li.toggle('highlight',function(){
//						$(this).remove();
//					});
//				}
//			}
		},
		
		customattr : function(key, value){
			var setter 	= this.uploader.getAttributeSet();
			var attr	= setter.createStringAttribute(key, value);
			
			attr.setSendToServer(true);
		},
		
		file : {
			
			STATUS_READY : 0,
			STATUS_UPLOADING : 1,
			STATUS_FINISHED : 2,
			STATUS_FAILED : 3,
			STATUS_PREPROCESSING : 4,
			STATUS_DOWNLOADING : 5,
			STATUS_EDITING : 6,
			
			transferTimerId : null,
			
			progress : function(file){
				
				var pb  = $('#progressbar-' + file.getId());
				var transfer = file.getTransferProgress();
				pb.progressbar('value', transfer.getCompletionPercent());		
				
				eagle.upload.file.progressTimerId = 
					setTimeout(function(){eagle.upload.file.progress(file);}, 100);
			},
			
			browse : function(){
				return eagle.upload.applet.getMainView().getUploadView().showOpenDialog();
			},
			mime : {
				getType : function(mime){
					var type = mime.split("/");
					return type[1];
				}
			},
			
			
			queue : {
				indexes : 0,
				domId : 'eagle-queue',
				files : array(),
				add : function(file){
					var id = file.getId();
					var name = file.getName();
					var size = file.getLength();
					var type = eagle.upload.file.mime.getType(file.getMimeType());
					this.files[id] = file;
					this.create(id, name, size, type, true, 0);
				},
				
				remove : function(id){
					var file = this.files[id];
					eagle.upload.uploader.removeFileAt(file.getIndex());
					
					$('#' + id).remove();
					
					return true;
				},
				
				create : function(id, name, size, type, remove, percent){
					var tpl = this.tpl(id, name, size, type, remove);
					
					$('#' + this.domId + ' #eagle-files').append(tpl);
					$('#progressbar-' + id).progressbar({value: percent});
				},
				
				tpl : function(id, name, size, type, remove){
		
					var tpl = '';
					
					tpl += '<li class="round-5" id="' + id +'">';
					if(name.length > 38){
						name = name.substr(0,35) + ' ...';
					}
					
					// tpl += '<div class="span-2">';
					// tpl += '<div class="padding-10">';
					// tpl += '<div class="icon icon-file-queue icon-file-'+type+'"></div>';
					// tpl += '</div>';
					// tpl += '</div>';
					tpl += '<div class="span-7 last">';
					tpl += '<div class="fileinfo float-l padding-10">';
					tpl += '<div class="filename">'+name+'</div>';
					tpl += '<a onclick="eagle.upload.file.queue.remove('+id+')" class="remove" href="#"></a>';
					tpl += '<div class="clear"></div>';
					tpl += '<div class="progressbar" id="progressbar-'+id+'"></div>';
					tpl += '</div>';
					
					tpl += '</div>';
					tpl += '<div class="clear"></div>';

					tpl += '</li>';
		
					return tpl;
				}
			}
		},
		
		templates : {
			messages : function(id, message, type){
				var output = '';
				var msg = '';
				var isArray = false;
				
				if(!type) type = 'warning';
				
				output += '<div class="notification '+type+' closeable">';
				
				if(message.split){
					msg = [message];
				}else{
					msg = message;
					isArray = true
				}
				
				
				output += '<p><strong>'+msg[0]+'</strong>';
				
				if(isArray){
					output += '<br />' + msg[1];
				}
				
				output += '</p>';
				output += '</div>';
				
				return output;
			},
			
			uploadBtn : function(id){
				
				var output = '';
				
				output += '<a id="'+id+'" href="#" class="btn-color btn-color-green display-block" onclick="eagle.upload.start(); return false;">';
				output += this.i18n.uploadBtn;
				output += '</a>';
				
				return output;
			
			}
		}
		
	}
};

var oxo = {
		obj : {
			caller : function(objName){
				return eval(objName);
			}
		},
		
		lang : {
			translate : function(name){
				return oxo.obj.caller('eagle.lang.' + eagle.lang.current +'.' + name);
			}
		},
		
		
		
		grid : {
			gridElm : null,
			gridElmId : null,
			
			/**
			 * @return oxo.grid
			 */
			init  : function(id){
				if(this.gridElmId != id){
					this.gridElmId = id;
					this.gridElm = jQuery(id);
				}
				
				return this;
			},
			
			button : {
				attach : function(){
					
					var prefix 	= 'grid-btn-';
					var btns	= $('a[class^="'+prefix+'"]');
					var rows 	= oxo.grid.init('#grid').getSelectedRows();
					

					$.each(btns,function(k, btn){
						$(this).button({disabled: true});
						
						var rel = $(this).attr('rel');
						var active = rel.split(':')[1];
						
						if(rows.length == 1 && active == 'singel'){
							$(this).button({disabled: false});
						}
						
						if(rows.length > 0 && active == 'multi'){
							$(this).button({disabled: false});
						}
					});
					
					
					return;
				}
			},
			
			getSelectedRows : function(){
				return this.gridElm.getGridParam('selarrrow');
			},
			
			getSelectedRow : function(){
				return this.gridElm.getGridParam('selrow');
			},
			
			getSelectedRowData : function(id){
				if(id == null){
					id = this.getSelectedRow();
				}
				
				return this.gridElm.jqGrid('getRowData', id);
			},
			
			refresh : function(){
				this.gridElm.trigger('reloadGrid');
				
				this.button.attach();
			},
			
			setSelectedRow : function(id){
				return this.gridElm.jqGrid('setSelection', id, true);
			},
			
			formatter : {
				action : function(cell, option, row){
					return 	'<div class="float-r">' +
							'<div class="margin-r-5 icon icon-close"></div>' +
							'</div>';
				},
				
				_null : function(cell, option, row){
					if(cell == null) return 0;

					return cell;
				},
				
				substr : function(cell, option, row){
					if(cell.length > 30){
						return cell.substr(0,30) + ' ...';
					}else{
						return cell;
					}
				},
				
				fixed : function(cell, option, row){
					return 'kr ' + parseFloat(cell).toFixed(2);
				},
				
				whenWillBeDeleted : function(cell, option, row){

					var d = new Date((cell*1000));
					
					return d.toLocaleDateString();
					
				}
			},
			
			search : function(options){
				var defaults = {
					elmSearchId : '#grid-search',
					elmGridId : '#grid',
					opt : {
						gridModel : false,
						gridName : true,
						filterModel: [{label: '', name : 'term'}],
						formclass : 'frm-grid-search',
						tableclass : 'tbl-grid-search no-padding no-margin',
						buttonclass : 'btn-default btn-plus'
					}
				};
				
				$.extend(defaults, options);
				
				jQuery(defaults.elmSearchId).jqGrid(
						'filterGrid',
						defaults.elmGridId, 
						defaults.opt
				); 
				
				var gs = jQuery('.' + defaults.opt.tableclass.split(' ')[0]);
				gs.find('label').parent().remove();
				gs.find('input').addClass('full input-icon input-icon-search');
			}
		},
		
		form : {
			element : {
				input : function(options){
					var defaultOptions = {
						'type' : 'text'
					};
					
					$.extend(defaultOptions, options);
					
					var attr = '';
					$.each(defaultOptions, function(i, v){
						attr += i + '="' + v + '" ';
					});
		
					return '<input '+ attr +' />';
				},
				
				textarea : function(options){
					var defaultOptions = {
						'type' : 'text'
					};
					
					$.extend(defaultOptions, options);
					
					var attr = '';
					var value = '';
					$.each(defaultOptions, function(i, v){
						if(i == 'value'){
							value = v;
						}else
							attr += i + '="' + v + '" ';
					});
		
					return '<textarea '+ attr +'>' + value + '</textarea>';
				},
				
				button : function(options){
					var defaultOptions = {
						'href' : '#'
					};
					
					$.extend(defaultOptions, options);
						
					var attr = '';
					var value = '';
					$.each(defaultOptions, function(i, v){
						if(i == 'value'){
							value = v;
						}else
							attr += i + '="' + v + '" ';
					});

					return '<a '+attr+'>'+value+'</a>';
				},
				
				txt : function(options){
					var defaultOptions = {};
					
					$.extend(defaultOptions, options);
						
					var attr = '';
					var value = '';
					$.each(defaultOptions, function(i, v){
						if(i == 'value'){
							value = v;
						}else
							attr += i + '="' + v + '" ';
					});

					return '<div '+attr+'>'+value+'</div>';
				},
				
				select : function(options){
					var attr 	= '';
					var values	= null;
					var selected= null;
					$.each(options, function(k,v){
						if(k == 'values')
							values = v;
						else if(k == 'value')
							selected = v;
						else
							attr += k + '="' + v + '" ';
					});
					
					var option = '';
					if(values !== null){
						$.each(values, function(k, v){
							if(selected == k)
								option += '<option value="' + k + '" selected>' + v + '</option>';
							else
								option += '<option value="' + k + '">' + v + '</option>';
						});
					}
					
					return '<select ' + attr + '>' + option + '</select>';
				}
			},
			
			reset : function(form){
				$(':input', form)
				 .not(':button, :submit, :reset, :hidden')
				 .val('')
				 .removeAttr('checked')
				 .removeAttr('selected');
			},
			
			submit : function(id, customdata, func){
				var form, formvalues, postvalues = '';
			
				form 		= $(id);
				formvalues 	= form.serialize();
				
				$(form).closest('div')
				   	   .find('.msg-container').html('');
				
				if(customdata){
					postvalues = formvalues + '&' + $.param(customdata);
				}else{
					postvalues = formvalues;
				}
				
				$.post(
					form.attr('action'),
					postvalues,
					function(r){
						if(r.type == 'success'){
							oxo.form.onSuccess(form, r, func);
						}else if(r.type == 'error'){
							oxo.form.onError(form, r, func);
						}else if(r.type == 'warning'){
							oxo.form.onWarning(form, r, func);
						}
					}
				);
				
				return;
			}, 
			
			onSuccess : function(form, r, func){
				var notice = oxo.notice.create(null, r.content, r.type, true);
				
				$(form).closest('div')
					   .find('.msg-container')
					   .html(notice);
				
				oxo.notice.refresh();
				func({'type' : 'success'});
			},
			
			onError : function(form, r, func){
				var notice = oxo.notice.create(null, r.content, r.type, true);
				
				$(form).closest('div')
					   .find('.msg-container')
					   .html(notice);
				
				oxo.notice.refresh();
				func({'type' : 'error'});
			},
			
			onWarning : function(form, r, func){
				var notice = oxo.notice.create(null, r.content, r.type, true);
				
				$(form).closest('div')
					   .find('.msg-container')
					   .html(notice);
				
				oxo.notice.refresh();
				func({'type' : 'warning'});
			}
		},
		
		dialog : {
			current : null,
			bind : function(handlerElement, dialog){
				$(handlerElement).bind('click', function(){
					oxo.dialog.open(dialog);
				});
			},
			
			get : function(id){
				if(id == null){
					id = this.current;
				}
				
				return $(id);
			},
			
			/**
			 * @return oxo.dialog
			 */
			open : function(options){
				var defaults = {
					id : '#dialog',
					opt : {
						modal : true,
						width : 650
					}
				};

				$.extend(true, defaults, options);
				
				var page = $(defaults.id);
				page.dialog(defaults.opt);
				
				this.current = defaults.id;
				
				page.bind("dialogclose", function(event, ui) {
					page.find('.msg-container').html('');
					//page.find('form')[0].reset();
				});
				
				return this;
			},
			
			setButtons : function(options){
				oxo.dialog.get().dialog("option", "buttons", options);
					
				return;	
			},

			close : function(id){
				if(id == null){
					page = $('#' + this.current);
				}else{
					page = $('#' + id);
				}
				
				page.dialog('close');
			},
			
			closeAndReset : function(id){
				if(id == null){
					page = $('#' + this.current);
				}else{
					page = $('#' + id);
				}
				
				page.find('form')[0].reset();
				page.dialog('close');
			}
		},
		
		notice : {
			
			create : function(id, content, type, closeable){
			
				var title, body;
				
				if(!type) type = 'warning';
				
				if(!closeable) closeable = '';
				else closeable = 'closeable';
				
				if(content instanceof Array){
					title = content[0];
					body = content[1];
				}else{
					title = content;
					body = false;
				}
				
				var output = '';
				output += '<div class="notification '+type+' closeable">';
				output += '<p><strong>'+title+'</strong>';
				if(body) output += '<br>' + body;
				output += '</p>';
				output += '</div>';
				
				return output;
		
			},
			
			refresh : function(){
				$('.closeable').notifyclose({animation: 'fade&slide', speed: 400});
				$('.remember').notifyremember({});
			},
			
			submit : function(form){
				var error, notice = false;
				var values 		= $(form).serializeArray();
				var msgcontiner = $(form).closest('div').find('.msg-container');
				
				if(form.title.value == ''){
					notice 	= this.create(null, ['Tittelfeltet mangler!','Vennligst fyll ut tittelfeltet og prøv på nytt!'], 'error', true);
					error = true;
				}else if(form.body.value == ''){
					notice 	= this.create(null, ['Meldingsfeltet mangler!','Vennligst fyll ut meldingsfeltet og prøv på nytt!'], 'error', true);
					error = true;
				}else{
					$.post(
						form.action,
						values,
						function(r){
							var notice = oxo.notice.create(null, r.content, r.type, true);
							msgcontiner.html(notice);
							oxo.notice.refresh();
							form.reset();
							oxo.grid.init('#grid').refresh();
						}
					);
				}
				
				if(error){
					error = false;
					msgcontiner.html(notice);
					this.refresh();
				}
			}
		}

};

(function($){
	$.fn.notifyclose = function(options){
		var defaults = {
			animation: 'slide',
			speed: 300
		};
		
		var options = $.extend({}, defaults, options);
		
		return this.each(function(){
			var elm = $(this);
			
			elm.css({cursor: 'pointer'})
			   .click(function(){
				  hide (elm);
			   });
			
			function hide(elm){
				switch(options.animation){
					case 'slide':
						elm.slideUp(options.speed);
						break;
					case 'fade':
						elm.fadeOut(options.speed);
						break;
					case 'fade&slide':
						elm.fadeTo(options.speed, 0, function(){elm.slideUp(options.speed);});
						break;
					default:
						elm.fadeTo(options.speed, 0, function(){elm.slideUp(options.speed);});
						break;
				}
			}	
		});
	}
})(jQuery);

(function($){
	$.fn.notifyremember = function(options){
		var defaults 	= {};
		var options 	= $.extend({}, defaults, options);
		
		return this.each(function(){
			var elm = $(this);
			
			var id = elm.attr('id');
			if(id != ''){
				//var id = 'notification_' + elm.length;
				
				elm.click(function(){
					$.cookie(id, 'hidden');
				});
				
				var cookie = $.cookie(id);
				if(cookie == 'hidden'){
					elm.hide();
				}else elm.show();
			}
		});
	}
})(jQuery);
