Ext.onReady(function(){
    Ext.QuickTips.init();
	var aboutpanel = new Ext.Panel({
		bodyCssClass:'aboutpanel',
		width:400,
		layout:'fit',
		autoScroll:true,
		header: false,
		region: 'east',
		border:false,
		autoLoad:'/about.html',
		collapsible: true,
		collapsed: true,
		hideCollapseTool: true,
		collapseMode: 'mini'
	});
	var picasapanel = picasaview(); // Eventually refactor this into an object
	var tb2 = new Ext.Toolbar({
//		renderTo:'tb2',
		cls: 'x-toolbar-bottom hs-toolbar',
		hidden: true,
		items:[{
			text:'Canvas animation demo',
			id: 'stardemobtn',
			iconCls: 'stardemo',  // <-- icon
			tooltip: 'A solar texture simulator written in HTML5/javascript',
			enableToggle: true,
			toggleGroup: 'centerContent',
			toggleHandler: function(b,e){
				if (b.pressed){
					showCenter(loadpanel);
					loadpanel.load({url:'/demos/star/',callback:starDemo});
				} else {
					hideCenter();
				}
			}
			//  menu: menu  // assign menu by instance
		},'-',{
			text:'Picasa scraper',
			iconCls: 'picasascraper',  // <-- icon
			enableToggle: true,
			toggleGroup: 'centerContent',
			disabled: true,
			tooltip: 'A python cgi script coupled with extjs dataview object',
			toggleHandler: function(b,e){				
				if (b.pressed){
					showCenter(loadpanel);
					loadpanel.load({url:'/demos/picasa/',callback:picasaview});
				} else {
					hideCenter();
				}
			} 
		},'-',{
			text:'Fancy table',
			iconCls: 'icon-chart',  // <-- icon
			enableToggle: true,
			toggleGroup: 'centerContent',
			disabled: true,
			tooltip: 'A sencha editor grid object coupled using xml and python CGIs ',
			toggleHandler: function(b,e){				
				if (b.pressed){
					showCenter(loadpanel);
					loadpanel.load({url:'/demos/fancytable/',
						callback:function(){
						// create the editor grid
						var ftgrid = new HS.FancyTable({
						    store: ftstore,
						    cm: cm,
						    id: 'myfancytable',
						    width: 600,
						    height: 300,
						    autoExpandColumn: 'filldate', // column with this id will be expanded
						    title: 'STI Gas Mileage',
						    frame: true,
						    clicksToEdit: 1
						});
						ftgrid.render('fancytable');ftstore.load();},
						scripts:false});
				} else {
					hideCenter();
				}
			} 
//		},'-',{
//				  text:'Animated toolbar',
				//  iconCls: 'dpp',  // <-- icon
//				disabled: true,
//				tooltip: 'An animated extjs toolbar',
//				handler: function(b,e){window.location='/dogPoker';} 
			//  menu: menu  // assign menu by instance
		}]
	});
	
	var tb1 = new Ext.Toolbar({
//		renderTo:'tb1',
		cls:'hs-toolbar',
		items:[{
			id:'latestPicasa',
			text:'Latest Picasa Pictures',
			iconCls: 'picasa',  // <-- icon
			enableToggle: true,
			toggleGroup: 'centerContent',
			tooltip: 'Last 5 pictures uploaded to picasa web albums',
			toggleHandler: function(b,e){
				if (b.pressed){
					//Ext.getCmp('techDemoButton').toggle(false);
//					showCenter(latestpics);
					showCenter(picasapanel);
				} else {
					hideCenter();
				}
			} 
			//  menu: menu  // assign menu by instance
		},'-',{
			id: 'techDemoButton',
			text:'Tech Demos',
			iconCls: 'gear',  // <-- icon
			tooltip: 'Web Technology Demonstrations',
			enableToggle: true,
			toggleHandler: function(b,e){
				if (b.pressed){
					b.disable();
					tb2.show();
					tb2.disable();
					tb2.el.setWidth(b.el.getWidth());
					tb2.setPagePosition(b.getPosition()[0],tb1.getPosition()[1]);
					//console.log('tb2 set to '+tb2.getPosition()+' width: '+tb2.getWidth());
					//console.log('Moving from '+b.getPosition()+' to '+tb1.getPosition());
					tb2.el.shift({
						y:tb1.getPosition()[1]+tb1.getHeight(),
						easing: 'easeOut',
						opacity:1,
						duration:.5
					}).shift({
						width:tb1.getWidth(),
						x:tb1.getPosition()[0],
						easing: 'easeOut',
						duration:.5,
						callback: function(){tb2.enable();b.enable()}
					});
					//console.log('header height starts at '+header.getHeight());
					header.setHeight(114);
					header.ownerCt.doLayout();
					//console.log('header height ends at '+header.getHeight());
					b.addClass('x-toolbar-bottom');
					b.removeClass('x-btn-pressed');
				} else {
					b.disable();
					tb2.disable();
					tb2.el.shift({
						width:b.getWidth(),
						x:b.getPosition()[0],
						easing: 'easeOut',
						duration:.5
					}).shift({
						y:tb1.getPosition()[1],
						easing: 'easeOut',
						duration:.5,
						opacity:0,
						callback: function(){b.enable();tb2.hide();header.setHeight(92);header.ownerCt.doLayout();}
					});
					b.removeClass('x-toolbar-bottom');					
				}
			}
		},'-',{
			text:'Dogs Playing Poker',
			iconCls: 'dpp',  // <-- icon
			tooltip: 'A Javascript single player Texas Hold\'em game',
			handler: function(b,e){window.location='/dogPoker';} 
		//  menu: menu  // assign menu by instance
		},'->',{
			text:'About Pugswald',
			enableToggle: true,
			iconCls: 'about',  // <-- icon
			handler: function(b,e){
				if (b.pressed){
					aboutpanel.expand();
				} else {
					aboutpanel.collapse();
				}
			}
		}]
	});
	//tb1.doLayout();
	var tbp = new Ext.Panel({
		//renderTo:'tbp',
		x: 0,
		y:70,
		cls:'hs-toolbar',
		border:false,
		items:[tb1,tb2]
	});
//	tbp.doLayout();







	
var logo = new Ext.BoxComponent({
	el: 'header'
//	height: 70
});

/** 
 * Encode 64 from a user on the sencha forums and some webtoolkit.  Freakin' weird it's not in any standard libraries
 */
	// private method for UTF-8 encoding
	_utf8_encode = function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	};

var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

var encode64 = function(input) {
    input = _utf8_encode(input);
    //input = escape(input);
    console.log('input for encoding: '+input);
    var output = "";
    var chr1, chr2, chr3 = "";
    var enc1, enc2, enc3, enc4 = "";
    var i = 0;
    
    do {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);
        
        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;
        
        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }
        
        output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";
    } while (i < input.length);
    
    return output;
};
// turn on validation errors beside the field globally
Ext.form.Field.prototype.msgTarget = 'side';

console.log(window.location.protocol);
var login = new Ext.FormPanel({
	//url:'login.py',
	//title: 'Login',
	//monitorValid:true,
	cls: 'relmedlogin',
	hidden: (window.location.protocol == 'https:') ? false:true,
	x: 300,
	y: 0,
	width:500,
	//labelWidth: 75,
	items:[{
		xtype: 'container',
		layout: 'hbox',
	    layoutConfig : {
	      align : 'stretch',
	    },
		defaultType: 'textfield',
		items: [{
			xtype:'fieldset',
			items:[{
				xtype:'textfield',
				fieldLabel:'Email',
				labelWidth: 75,
				name:'uname',
				allowBlank:false,
				vtype:'email',
				flex: 1
			}]
		},{
			xtype:'fieldset',
			items:[{
				xtype:'textfield',
				fieldLabel:'Password',
				labelWidth: 75,
				name:'upass',
				allowBlank:false,
				inputType:'password',
				flex: 1
			}]
		}]
	}],
	buttons:[{
		text:'Login',
		//formBind: true,
		handler:function(){
//			var form = login.getForm().getFieldValues();
			var form = login.form.getFieldValues();
			console.log('n:'+form.uname+' p:'+form.upass+' url:'+'https://'+window.location.host+'/relmed');
			Ext.Ajax.request({
		    	url : 'https://'+window.location.host+'/relmed',
		    	method : 'GET',
		    	headers : { 'Authorization' : 'Basic '+ encode64(form.uname+':'+form.upass) },
				success:function(){
					Ext.Msg.alert('Status','Login Successful!', function(btn, text){
						   if (btn == 'ok'){
		                        var redirect = 'https://'+window.location.host+'/relmed'; 
		                        window.location = redirect;
                           }
					});
				},
                failure:function(res, opts){ 
					console.log('Login failed with '+res.statusText);
					//if(action.failureType == 'server'){ 
                    //    obj = Ext.util.JSON.decode(action.response.responseText); 
                    //    Ext.Msg.alert('Login Failed!', obj.errors.reason); 
                    //}else{ 
                    //    Ext.Msg.alert('Warning!', 'Authentication server is unreachable : ' + action.response.responseText); 
                    //} 
                    login.getForm().reset(); 
                } 
            }); 
		} 
	}] 
});
					



var footer = new Ext.BoxComponent({
//	height:30,
	border: false,
	region:'south',
	el: 'footer'
});
var header = new Ext.Panel({
	height:92,
	layout:'absolute',
//	layout:'anchor',
//	minHeight: 92,
	border: false,
	region:'north',
//	split: true,
//	layout:'row',
	items:[logo,login,tbp]
});
//header.doLayout();
var center = new Ext.Panel({region:'center', border:false,autoScroll:true,layout:'fit'});
var loadpanel = new Ext.Panel({border:false,autoScroll:true,bodyCssClass:'purple'});
var layout = new Ext.Viewport({
	layout: 'border',
//    items: [header, mainpic,aboutpanel,footer]
    items: [header, center,aboutpanel,footer]
});

var showCenter = function(comp) {
//	console.log('Showing '+comp.getId()+' in center '+center.getId());
	hideCenter();
	comp.show();
	center.add(comp);
	center.ownerCt.doLayout();
}

var hideCenter = function() {
	var arr = center.removeAll(false);
	if (arr.length > 0) arr[0].hide();
}
var shortcut = window.location.hash.toLowerCase();
switch(shortcut){
	case '#demos':
		Ext.getCmp('techDemoButton').toggle(true);
		break;
	case '#stardemo':
		Ext.getCmp('techDemoButton').toggle(true);
		Ext.getCmp('stardemobtn').toggle(true);
		break;
	default:
		Ext.getCmp('latestPicasa').toggle(true);
}

});


