$(function($){
	window.str_ajax_url = '/member/ajax.asp';
	window.legacy_ie = $.browser.msie ? (function(a){ return (a[0] < 8); })($.browser.version.split('.')) : false;
	var rnd = Math.random().toString();
	$(document).bind("ajaxSend", function(){
		fn_wait(rnd);
	})
	$(document).bind("ajaxComplete", function(){
		fn_wait(rnd,false);
	});
	Ext.QuickTips.init();
	if (window.barc_member) dom_replaceMemberLogin();
	
	if (location.hash) {
		var rex = /reset=([\da-f]+)$/i
			, arr_match = location.hash.match(rex)
		var str_code = (arr_match) ? arr_match[1] : '';
		if (str_code) {
			fn_doLogin({auth_code:str_code},{success:function(){ frm_memberProfile().show() },failure:$.noop});
		}
	}
	$('.member-login').live('submit',function() {
		fn_doLogin(this);
		return false;
	});
	$('.member-signup').live('click',function() {
		var fn = fn_wait();
		fn_close_dlg(function(){
			frm_memberSignup().show(null,fn);
		});
		return false;
	});
	$('.password-reset').live('click',function() {
		var fn = fn_wait();
		fn_close_dlg(function(){
			frm_passwordReset().show(null,fn);
		});
		return false;
	});
	$('.member-post').live('click',function() {
		fn_wait(function(fn){
			if (window.barc_member) {
				frm_newPost().show(null,fn);
			} else {
				frm_memberLogin(function(){ frm_newPost().show(); }).show(null,fn);
			}
		});
		return false;
	});
});

function fn_close_dlg(callback) {
	var arr_fn = [], callback = callback || Ext.emptyFn;
	$('body>.x-window').each(function(){
		var str_id = this.id
			, cmp = Ext.getCmp(str_id)
			, dlg = (cmp.getDialog) ? cmp.getDialog() : cmp;
		arr_fn.push(function(fn){ dlg.on('hide',fn_do_once(fn)); dlg.close();});
	});
	fn_async_do(arr_fn,callback);
}

function fn_async_do(arr_fn,fn_done) {
	var len = arr_fn.length , c = len;
	function fn_do() {
		if (--c == 0) fn_done();
	}
	if (len) {
		for(var i=0;i<len;i++) arr_fn[i](fn_do);
	} else {
		fn_done();
	}
}

function fn_async_seq(arr_fn,fn_done) {
	var i = 0;
	function fn_do() {
		if (i >= arr_fn.length) {
			fn_done();
		} else {
			arr_fn[(i++)](fn_do)
		}
	}
	if (arr_fn.length) {
		fn_do();
	} else {
		fn_done();
	}
}

function fn_do_once(fn) {
	var done = false;
	return function() {
		if (!done) {
			done = true;
			fn();
		}
	};
}

function fn_sync_seq(arr_fn,args) {
	return function(){
		var a = args || arguments;
		for (var i=0;i<arr_fn.length;i++) arr_fn[i].apply(this,a);
	};
}

function fn_wait(str_id,b) {
	var self = arguments.callee, args = Array.prototype.slice.call(arguments,0);
	var fn_do = (args[0] instanceof Function) ? args[0] : null;
	var o = self.vars ? self.vars : self.vars = {id:0,stack:{},el:new Ext.LoadMask(Ext.getBody(),{msg:'Loading. Please wait ...'})};
	var str_id = Ext.isPrimitive(str_id) ? String(str_id) : String(o.id++);
	var fn_done;
	(function(id){
		fn_done = function() {
			if (o.stack.hasOwnProperty(id)) delete o.stack[id];
			if (jQuery.isEmptyObject(o.stack)) {
				o.el.hide();
			}
		}
	})(str_id);
	if (b === false) {
		fn_done();
	} else
	if (fn_do) {
		if (jQuery.isEmptyObject(o.stack)) {
			o.stack[str_id] = fn_done;
			setTimeout(function(){ fn_do(fn_done) },500);
			o.el.show();
		} else {
			o.stack[str_id] = fn_done;
			fn_do(fn_done);
		}
	} else {
		if (jQuery.isEmptyObject(o.stack)) o.el.show();
		return o.stack[str_id] = fn_done;
	}
}

function fn_debugView(el) {
	var a = [];
	for (var n in el) if (el.hasOwnProperty(n)) a.push(n + ':"' + String(el[n]).replace(/([\\"])/ig,'\\$1') + '"');
	return '{' + a.join(',') + '}';
}

function fn_validate_file_ext(el,fname) {
	var valid = false, a = String(el.valid_ext).toLowerCase().split(','), ext = String(fname).split('.').reverse()[0];
	if (ext) $.each(a,function(i,s){ if (ext == s) valid = true; });
	if (!valid) {
		el.reset();
		Ext.Msg.alert('Invalid File Type','You have selected an invalid file type. Please try again.');
	}
	return valid;
}

function fn_ext_ajax_submit(frm,cfg) {
	if (Ext.isFunction(cfg)) cfg = {success:cfg};
	if (!cfg) cfg = {};
	if (!cfg.success) cfg.success = Ext.emptyFn;
	var fn_log = function(frm,act) {
		if (window.console && act.result && act.result.log) $.each(act.result.log.split('\n'),function(i,v){ console.log(v) });
	};
	var arr_success = [fn_log,cfg.success];
	var arr_failure = [fn_log,fn_ext_ajax_fail];
	var action = {
		success:function(){ fn_sync_seq(arr_success,arguments)(); },
		failure:function(){ fn_sync_seq(arr_failure,arguments)(); }
	};
	if (cfg.progress) {
		var dlg = Ext.Msg.progress('Processing ...','Please wait while your post is submitted. This can take some time if you have selected images or file attachments.');
		var req_id = fn_get_guid(), i = 0, task_id;
		action.url = Ext.urlAppend(frm.url,'uid=' + req_id);
		var fn_check
			, fn_sched = function(){ task_id = setTimeout(fn_check,800); }
			, fn_clear = function(){ clearTimeout(task_id); task_id = false; dlg.hide(); };
		fn_check = function(){
			i++;
			$.ajax({
				url:window.str_ajax_url,
				dataType:'json',
				global:false,
				data:{a:'get_progress',uid:req_id},
				success:function(d,s){
					var prog = (d.size) ? d.received / d.size : 0;
					dlg.updateProgress(prog,Math.round(prog * 100).toString() + '%');
					if (task_id !== false) fn_sched();
				}
			});
		};
		arr_success.unshift(fn_clear);
		arr_failure.unshift(fn_clear);
		fn_sched();
	}
	frm.submit(action);
}

function fn_ext_ajax_fail(form,action) {
	var str_err, xhr = action.response;
	if (action.result && action.result.error) {
		str_err = 'Error: ' + action.result.error;
	} else
	if (action.failureType == Ext.form.Action.CLIENT_INVALID || action.failureType == Ext.form.Action.SERVER_INVALID) {
		str_err = 'Incomplete or invalid information submitted. Please check the highlighted fields and try again.';
	} else
	if (action.failureType == Ext.form.Action.CONNECT_FAILURE) {
		str_err = 'Connection or Server Side Failure. Status Code: ' & xhr.status;
	} else
	if (action.failureType == Ext.form.Action.LOAD_FAILURE) {
		str_err = 'Response Load Failure. Please try again later.';
	} else {
		str_err = 'Unspecified Error. Please try again later.';
	}
	ext_err(str_err,'Error Submitting Form');
}
function fn_jquery_ajax_fail(evt,xhr,req,err) {
	if (xhr.status && xhr.status != 200) alert('Connection or Server Side Failure. Status Code: ' & xhr.status);
	else if (err) alert('Error: ' + err.name + '\n' + err.message);
	else alert('Unhandled XHR Failure.');
}

function dom_replaceMemberLogin() {
	var $login = $('#login').remove(), $parent = $('<div/>').attr({'id':'member'}), memb = window.barc_member;
	$parent.append($('<p/>').attr({'class':'left'}).html('Welcome to BARC. You are logged in as: <span class="full_name">' + memb.full_name + '</span> (<span class="email">' + memb.email + '</span>)'));
	var $act = $('<p/>').attr({'class':'right'});
	$act.append($('<a/>').attr({'href':'#'}).text('View My Profile').click(function(){ frm_memberProfile().show(); return false; }))
	$act.append($('<span/>').text('|'))
	$act.append($('<a/>').attr({'href':'#'}).text('Logout').click(function(){ fn_doLogout(function(){ $parent.replaceWith($login); }); return false; }))
	$parent.append($act);
	$('#header_inner').append($parent)
}
function dom_updateMemberLogin() {
	var memb = window.barc_member, $div = $('#member');
	$div.find('.full_name').text(memb.full_name);
	$div.find('.email').text(memb.email);
}

function fn_doLogin(frm,cfg) {
	var cfg = cfg || {};
	if (!cfg.success) cfg.success = $.noop;
	var data = (frm.getValues) ? frm.getValues() : (frm.tagName) ? $(frm).serialize() : $.param(frm);
	$.ajax({
		type:'POST',
		url:str_ajax_url + '?a=login',
		data:data,
		success:function(d,s,xhr){
			if (d.success) {
				window.barc_member = d.data;
				if (typeof frm.reset == 'function') frm.reset();
				dom_replaceMemberLogin();
				cfg.success();
			} else {
				if (cfg.failure) {
					cfg.failure();
				} else {
					ext_err('Login Failed. Check that you are using the correct email address and password and try again. <a class="password-reset" href="#">Forgot your password?</a>','Invalid Login');
				}
			}
		},
		error:fn_jquery_ajax_fail,
		dataType:'json'
	});
}

function fn_doLogout(fn) {
	$.ajax({
		type:'POST',
		url:str_ajax_url + '?a=logout',
		success:function(d,s,xhr){
			if (d.success) {
				window.barc_member = null;
				fn();
			} else {
				ext_err();
			}
		},
		error:fn_jquery_ajax_fail,
		dataType:'json'
	});
}

function fn_getSimpleStore(col) {
	var arr = [];
	$.each(col,function(n,v){ arr.push([n,v]); });
	return new Ext.data.SimpleStore({fields:['val','desc'],data:arr})
}

function frm_newPost() {
	var dlg = new Ext.Window({
		 id:'x-dlg-post'
		,title:'Create New Post'
		,modal:true
		,width:562
		,minWidth:400
		,height:400
		,minHeight:300
		,layout:'fit'
		// form
		,items:[{
			 xtype:'form'
			,id:'x-frm-post'
			,border:false
			,url:str_ajax_url + '?a=new_post'
			,fileUpload:true
			// tabpanel
			,items:[{
				 id:'x-panel-tabs'
				,xtype:'tabpanel'
				,activeItem:0
				,border:false
				,anchor:'100% 100%'
				,deferredRender:false
				// tabs
				,defaults:{
					 layout:'form'
					,labelWidth:120
					,width:400
					,defaultType:'textfield'
					,bodyStyle:'padding:5px'
					,hideMode:'offsets'
				}
				,listeners:{
					'tabchange':function(){
						var tp = this
							, i = tp.items.indexOf(tp.getActiveTab())
							, btn_reset = Ext.getCmp('x-btn-reset')
							, btn_next = Ext.getCmp('x-btn-next')
							, btn_submit = Ext.getCmp('x-btn-submit');
						if (i == 1) {
							btn_reset.show();
						} else {
							btn_reset.hide();
						}
						if (i == tp.items.length - 1) {
							btn_next.hide();
							btn_submit.show();
						} else {
							btn_next.show();
							btn_submit.hide();
						}
					}
				}
				,items:[{
					 title:'Post Description'
					,defaults:{anchor:'-20'}
					,autoScroll:true
					// fields
					,items:[{
						 xtype:'textfield'
						,fieldLabel:'Post Title'
						,name:'post_title'
						,allowBlank:false
					},{
						 xtype:'textarea'
						,fieldLabel:'Brief Description'
						,name:'post_text'
						,height:45
						,allowBlank:false
					},{
						 xtype:'htmleditor'
						,fieldLabel:'Full Description'
						,name:'post_html'
						,height:150
						,enableColors:false
						,enableFont:false
						,enableFontSize:false
						,allowBlank:false
					},{
						 xtype:'lovcombo'
						,fieldLabel:'Categories'
						,hideOnSelect:false
						,store:fn_getSimpleStore(barc_post_cats)
						,beforeBlur:Ext.emptyFn
						,name:'post_cats_desc'
						,hiddenName:'post_cats'
						,displayField:'desc'
						,valueField:'val'
						,editable:false
						,allowBlank:false
						,mode:'local'
						,triggerAction:'all'
//					},{
//						 xtype:'lovcombo'
//						,fieldLabel:'Search Keywords'
//						,hideOnSelect:false
//						,store:fn_getSimpleStore(barc_post_tags)
//						,beforeBlur:Ext.emptyFn
//						,name:'post_tags_desc'
//						,hiddenName:'post_tags'
//						,displayField:'desc'
//						,valueField:'val'
//						,editable:false
//						,mode:'local'
//						,triggerAction:'all'
					}]
				},{
					 title:'Images and Attachments'
					,items:[{
						 xtype:'fieldset'
						,title:'Add a Photo'
						,autoHeight:true
						,items:[{
							 xtype:'fileuploadfield'
							,id:'x-frm-post-img-upload'
							,fieldLabel:'Upload Your Own'
							,name:'photo_upl'
							,valid_ext:'BMP,GIF,JPG,JPEG,PNG,TIF,TIFF'
							,width:300
							,emptyText:'Select an image'
							,buttonText:'Select File'
							,listeners:{fileselected:fn_validate_file_ext}
						},{
							 xtype:'displayfield'
							,allowBlank:true
							,html:'(Please select a JPEG, PNG or GIF image; 2MB Max Filesize)'
						},{
							 xtype:'hidden'
							,id:'photo_url'
							,name:'photo_url'
						},{
							 border:false
							,id:'x-frm-post-el-thumb'
							,html:'<div class="x-thumbnail-pane"><img class="x-thumbnail" src="/img/imageNotFound.gif"/></div>'
						},{
							 xtype:'button'
							,fieldLabel:'Choose One of Ours'
							,width:80
							,text:'Select Photo'
							,handler:function(){
								var self = arguments.callee;
								if (!self.chooser)
								self.chooser = new ImageChooser({
									url:'/member/js_photos.asp',
									width:435,
									height:300
								});
								self.chooser.show(null,function(rec){
									Ext.getCmp('photo_url').setValue(rec.url);
									$('#x-frm-post-el-thumb').css('display','block').find('img').attr('src',rec.url);
								});
							}
						}]
					},{
						 xtype:'fieldset'
						,title:'Upload Attachment(s)'
						,autoHeight:true
						,items:[{
							 xtype:'fileuploadfield'
							,id:'x-frm-post-file-upload-01'
							,fieldLabel:'Attachment 1'
							,name:'file_1'
							,valid_ext:'JPG,JPEG,PNG,BMP,GIF,TXT,PDF'
							,width:300
							,emptyText:'Select a file'
							,buttonText:'Select File'
							,listeners:{fileselected:fn_validate_file_ext}
						},{
							 xtype:'fileuploadfield'
							,id:'x-frm-post-file-upload-02'
							,fieldLabel:'Attachment 2'
							,name:'file_2'
							,valid_ext:'JPG,JPEG,PNG,BMP,GIF,TXT,PDF'
							,width:300
							,emptyText:'Select a file'
							,buttonText:'Select File'
							,listeners:{fileselected:fn_validate_file_ext}
						},{
							 xtype:'displayfield'
							,allowBlank:true
							,html:'(Please select a PDF or JPG file; 2MB Max Filesize)'
						}]
					}]
				},{
					 title:'Calendar'
					,items:[{
						 xtype:'fieldset'
						,title:'Calendar of Events'
						,autoHeight:true
						,items:[{
							 xtype:'displayfield'
							,allowBlank:true
							,html:'<span>If you would like this post to appear on the calendar, please select the date below and select what category you would like it to belong to.</span>'
						},{
							 xtype:'datefield'
							,format:'d/m/Y'
							,fieldLabel:'Date'
							,name:'evt_start'
							,width:240
							,listeners:{
								focus:window.legacy_ie ? $.noop : function() {
									if(this.menu == null) this.menu = new Ext.menu.DateMenu();
									if(!this.menu.isVisible()) this.onTriggerClick();
								}
							}
						},{
							 xtype:'combo'
							,fieldLabel:'Event Category'
							,width:240
							,name:'evt_cat_desc'
							,hiddenName:'evt_cat'
							,displayField:'desc'
							,valueField:'val'
							,store:fn_getSimpleStore(barc_post_evt_cat)
							,editable:false
							,mode:'local'
							,triggerAction:'all'
						}]
					}]
				}]

			}]
			,buttons:[{
				 id:'x-btn-reset'
				,text:'Reset'
				,hidden:true
				,handler:function() {
					Ext.getCmp('x-frm-post-img-upload').reset();
					Ext.getCmp('x-frm-post-file-upload-01').reset();
					Ext.getCmp('x-frm-post-file-upload-02').reset();
				}
			},{
				 id:'x-btn-next'
				,text:'Next'
				,handler:function() {
					var tp = Ext.getCmp('x-panel-tabs')
						, items = tp.items
						, i = items.indexOf(tp.getActiveTab());
					if (i < tp.items.length - 1) tp.setActiveTab(i + 1);
				}
			},{
				 id:'x-btn-submit'
				,text:'Submit'
				,hidden:true
				,handler:function() {
					var frm = Ext.getCmp('x-frm-post').getForm();
					var fn_success = function(){
						dlg.close();
						Ext.Msg.alert('Thank You for Your Submission', 'Your post has been sent to the administrators of BARC and is awaiting approval.');
					}
					fn_ext_ajax_submit(frm,{success:fn_success,progress:true});
				}
			},{
				 text:'Cancel'
				,handler:function() {dlg.close()}
			}]
			
		}]
	});
	
	return dlg; 
}


function frm_memberSignup(fn_callback) {
	var dlg, fp;
	function fn_submit() {
		fn_ext_ajax_submit(fp.form,function(frm,act){
			dlg.close();
			window.barc_member = act.result.data;
			dom_replaceMemberLogin();
			if (fn_callback) {
				fn_callback();
			} else {
				Ext.Msg.alert('Thank You for Signing Up', 'You are now a member of BARC. Please feel free to contribute to BARC using the "Post an Item" button at the top of the right column.');
			}
		});
	}
	fp = new Ext.FormPanel({
		labelWidth:120,
		frame:true,
		defaults:{width:160},
		url:str_ajax_url + '?a=signup',
		items:[{
			xtype:'textfield',
			fieldLabel:'First Name',
			id:'x-frm-signup-el-fname',
			name:'fname',
			allowBlank:false
		},{
			xtype:'textfield',
			fieldLabel:'Last Name',
			name:'lname',
			allowBlank:false
		},{
			xtype:'textfield',
			fieldLabel:'Email address',
			name:'email',
			vtype:'email'
		},{
			xtype:'textfield',
			fieldLabel:'Choose Password',
			inputType:'password',
			name:'pwd1',
			allowBlank:false
		},{
			xtype:'textfield',
			fieldLabel:'Repeat Password',
			inputType:'password',
			name:'pwd2',
			allowBlank:false
		}],
		buttons:[{
			text:'Submit',
			handler:fn_submit
		},{
			text:'Cancel',
			handler:function() { dlg.close(); }
		}],
		keys:[{
			key:Ext.EventObject.ENTER,
			handler:fn_submit
		}]
	});
	dlg = new Ext.Window({
		id:'x-dlg-signup',
		width:320,
		height:220,
		closable:true,
		modal:true,
		title:'New Member Signup',
		layout:'fit',
		defaultButton:'x-frm-signup-el-fname',
		items:fp
	});
	return dlg;
}


function frm_passwordReset(fn_callback) {
	var dlg, fp;
	function fn_submit() {
		fn_ext_ajax_submit(fp.form,function(frm,act){
			dlg.close();
			Ext.Msg.alert('Password Reset', 'You have been emailed a link to reset your password.');
		});
	}
	fp = new Ext.FormPanel({
		labelWidth:120,
		frame:true,
		defaults:{width:160},
		url:str_ajax_url + '?a=reset',
		items:[{
			xtype:'textfield',
			fieldLabel:'Email address',
			id:'x-frm-reset-el-email',
			name:'email',
			vtype:'email'
		},{
			 xtype:'displayfield'
			,allowBlank:true
			,html:'You must enter the same email address you originally signed up with.'
		}],
		buttons:[{
			text:'Submit',
			handler:fn_submit
		},{
			text:'Cancel',
			handler:function() { dlg.close(); }
		}],
		keys:[{
			key:Ext.EventObject.ENTER,
			handler:fn_submit
		}]
	});
	dlg = new Ext.Window({
		id:'x-dlg-reset',
		width:320,
		height:190,
		closable:true,
		modal:true,
		title:'Password Reset Request',
		layout:'fit',
		defaultButton:'x-frm-reset-el-email',
		items:fp
	});
	return dlg;
}


function frm_memberProfile() {
	var dlg, fp, memb = window.barc_member;
	function fn_submit() {
		fn_ext_ajax_submit(fp.form,function(frm,act){
			dlg.close();
			window.barc_member = act.result.data;
			dom_updateMemberLogin();
			Ext.Msg.alert('Profile Updated', 'Your new details have been saved.');
		});
	}
	fp = new Ext.FormPanel({
		labelWidth:120,
		frame:true,
		defaults:{width:160},
		url:str_ajax_url + '?a=member_update',
		items:[{
			xtype:'textfield',
			fieldLabel:'First Name',
			name:'fname',
			value:memb.f_name,
			allowBlank:false
		},{
			xtype:'textfield',
			fieldLabel:'Last Name',
			name:'lname',
			value:memb.l_name,
			allowBlank:false
		},{
			xtype:'textfield',
			fieldLabel:'Email address',
			name:'email',
			value:memb.email,
			vtype:'email'
		},{
			xtype:'textfield',
			fieldLabel:'Change Password',
			inputType:'password',
			id:'x-frm-profile-el-pw1',
			name:'pwd1'
		},{
			xtype:'textfield',
			fieldLabel:'Repeat Password',
			inputType:'password',
			name:'pwd2'
		}],
		buttons:[{
			text:'Save',
			handler:fn_submit
		},{
			text:'Cancel',
			handler:function() { dlg.close(); }
		}],
		keys:[{
			key:Ext.EventObject.ENTER,
			handler:fn_submit
		}]
	});
	dlg = new Ext.Window({
		id:'x-dlg-profile',
		width:320,
		height:220,
		closable:true,
		modal:true,
		title:'Your Member Profile',
		layout:'fit',
		defaultButton:'x-frm-profile-el-pw1',
		items:fp
	});
	return dlg;
}


function frm_memberLogin(fn_callback) {
	var fp, dlg;
	function fn_submit() {
		var frm = dlg.getEl().select('form').first().dom;
		fn_doLogin(frm,{success:function(){ fn_callback(); dlg.close(); }});
	}
	dlg = new Ext.Window({
		 id:'x-dlg-login'
		,width:360
		,height:240
		,autoScroll:true
		,modal:true
		,title:'Member Login'
		,padding:8
		,items:[{
			 border:false
			,html:'<p>You must be a member to post to BARC.</p><p><b>Please login below:</b></p>'
		},{
			xtype:'form',
			border:false,
			labelWidth:120,
			defaults:{width:160},
			items:[{
				xtype:'textfield',
				fieldLabel:'Email address',
				id:'x-frm-login-el-email',
				name:'email',
				vtype:'email'
			},{
				xtype:'textfield',
				inputType:'password',
				fieldLabel:'Password',
				name:'passwd',
				allowBlank:false
			}],
			keys:[{
				key:Ext.EventObject.ENTER,
				handler:fn_submit
			}]
		},{
			 border:false
			,html:'<p>If you are not currently a member, <a class="member-signup" href="#">click here</a> to sign up.<br/>If you forgot your password, <a class="password-reset" href="#">click here</a> to reset it.</p>'
		}]
		,defaultButton:'x-frm-login-el-email'
		,buttons:[{
			text:'Login',
			handler:fn_submit
		},{
			text:'Cancel',
			handler:function() {dlg.close()}
		}]
	});
	return dlg;
}

function ext_err(msg,t,fn_callback) {
	var msg = Ext.Msg.show({
		title:t || 'Error Processing Request',
		width:480,
		msg:msg || 'An Unspecified Error has Occured. Please try again later.',
		buttons:Ext.Msg.OK,
		fn:fn_callback,
		icon:Ext.Msg.ERROR
	});
}


