//reference local blank image
Ext.BLANK_IMAGE_URL = '/images/blank.gif';

var urlparams;
var viewport;

//COMP.LoadLibrary('rws_results');

Ext.QuickTips.init();

function alert(msg){
	var dlg = new RWS.Dialog({buttons:Ext.Msg.OKAY, message:msg, width: 300});
	dlg.show();
}

function RWS_Init()
{
    if(Ext.FlashComponent)
		alert("FLASH IS BACK GET RID OF IT NOW");
	var loader = Ext.get('loader');
	document.title = COMP.V.libraryname;
	COMP.V.session_timeout = COMP.Config.GetDefault('timeout');
	COMP.Prefs['dontShowTitleAvail'] = COMP.Config.GetDefault('dontShowTitleAvail');
	
	if(!COMP.Cookie)
	{
		COMP.Cookie = new Ext.state.CookieProvider({
			expires: new Date(new Date().getTime()+(1000*60*60*24*366)) // 1 year
		});
	}
	function ShowUCMsg(msg)
	{
		Ext.Msg.show({
			title:L(25965), //'Under Construction' 
			minWidth:150,
			msg:msg,
			icon:Ext.MessageBox.INFO
		});
	}

	Ext.Panel.prototype.ClearItems = function()
	{
		while (this.items && this.items.items && this.items.items.length)
			{this.remove(this.items.items[0]);}
	};
	
	LANG.prototype.getWidth=function(el){
		var el = el || COMP.metrics.plainText.el;
		return Ext.util.TextMetrics.measure(el, this.toString()).width;
	};
    var params = window.location.search;
	if(params){
		params = params.substring(1);
		params = params.split('=');
		if(params[0] == "search"){
			switch(params[1]){
				case "1":
					RWS.Layout.AdvancedSearch.show();
					RWS.Layout.SimpleSearch.hide();
					break;
				default:
				case "0":
					RWS.Layout.SimpleSearch.show();
					RWS.Layout.AdvancedSearch.hide();
			}
		}
	}

	COMP.startHash = window.location.hash.toString();
	var forceLogin = COMP.startHash.toLowerCase().startsWith('#login');
	var showDetails = COMP.startHash.toLowerCase().startsWith('#details=');
	var showResults = COMP.startHash.toLowerCase().startsWith('#results=');
	var simpleSearch = COMP.startHash.toLowerCase().startsWith('#simplesearch=');

	RWS.fromLWS = COMP.startHash.toLowerCase().startsWith('#fl');
	if (RWS.fromLWS)
		RWS.parentLWS = window.opener;
		
	var url = COMP.startHash;
    var rsn = COMP.startHash.toLowerCase().split('=');

	if (COMP.AddingPound())
	{
//		window.onload = RWS_Init;
		return false;
	};
		
	var siteID = null;
	if (COMP.startHash.toLowerCase().startsWith('#site='))
	{
		// Extract site and translate into it's numeric id.
		var site = COMP.startHash.after('#site=').toUpperCase();
		var cList = COMP.Prefs.collectionsList;
		for (var bookname in cList)
		{
			var book = cList[bookname];
			for (var i=0; i<book.length; i++)
			{
				if (book[i].site.toUpperCase() == site)
				{
					siteID = book[i].libID;
					break;
				}
			}
			if (siteID != null)
				break;
		}
		if (siteID != null)
			COMP.Cookie.set('localCollection',siteID);
	}

	//get the current url params
	var docurl = document.URL;
	urlparams = Ext.urlDecode(docurl.substring(docurl.indexOf('?') + 1));
	//Simple dom elements that represent particular css styles.  Used by textMetrics to determine string widths.
	COMP.metrics = {
		plainText: new Ext.form.Label({
			renderTo:document.body
		}),
		titleText: new Ext.form.Label({
			cls:'titleText'
			,renderTo:document.body
		}),
		textLink: new Ext.form.Label({
			cls:'textlink'
			,renderTo:document.body
		}),
		allCrumbs: new Ext.form.Label({
			cls:'allCrumbs'
			,renderTo:document.body
		}),
		bubbleButton: new Ext.form.Label({
			cls:'bubbleButton'
			,renderTo:document.body
		})
	};
		

//	if (COMP.V.homepage.length==0)
//		Ext.getCmp('homePagePanel').hide();


	RWS.Viewport = new Ext.Viewport({
		title: COMP.V.title
		,id:'viewport'
		,layout: 'border'
		,items:[{
			xtype:'container'
			,cls:'contentBox'
			,layout:'hbox'
			,layoutConfig:{align:'stretch'}
			,region:'center'
			,height:'100%'
			,style:'background:transparent;'
			,items:[{
					xtype:'spacer'
					,flex:1 
				},{
					xtype:'container'
					,layout:'fit'
					,style:'background: url("/images/RWS_Background.jpg") 50% 0% no-repeat white; border-left-style: solid; border-right-style: solid; border-width:1; border-color: #404040;'
					,width: 1024
					,items:[{
						xtype:'container'
						,cls:'contentBox'
						,layout:'border'
						,items:[RWS.Layout.NorthBar, RWS.Layout.Center, RWS.Layout.South]
					}]
				},{
					xtype:'spacer'
					,flex:1
			}]
		}]
	});
	if(!RWS.Layout.SimpleSearch.isVisible() && !RWS.Layout.AdvancedSearch.isVisible())
		RWS.Layout.SimpleSearch.show(); 
	RWS.Layout.ComboSearch.doLayout();
    
	setTimeout(function(){
		loader.fadeOut({remove:true});
	}, 250);

		
	Ext.getBody().addListener('mousemove',COMP.ResetLastAction);
	// 	RWS.Bread.Clear();
	RWS.Explore.RequestExplore();     
	// RWS.Search.CheckStartCommands();
	//COMP.AvoidBack(true);
	//COMP.Config.SetLanguage();
	
	Ext.History.init();
	Ext.History.add_old = Ext.History.add;
	Ext.History.add = function(a)
	{
		Ext.History.adding = true;
		return Ext.History.add_old(a);
	};
	Ext.History.on('change', function(token)
	{
		if (token)
		{
			if (token.toString().toLowerCase().startsWith('details='))
			{
				var rsn = token.split('=')[1];
				setTimeout(function() { if (RWS.Details) RWS.Details.CloseAll(); RWS.Search.SendDetailRequest(rsn) }, 0);
			}
			else
//			if (Ext.History.adding)
//			{
//				Ext.History.adding = false;
//				return;
//			}
//			else
//			{
				COMP.Back();
//			}
		}
		else
		{
			// This is the initial default state.  Necessary if you navigate starting from the
			// page without any existing history token params and go back to the start state.
			window.location.hash = '_';
		}
	});
	
	//COMP.Config.VerifyLocalCollection();
		
	if (forceLogin || COMP.Config.GetDefault('requireID_Password'))
		COMP.Login.HandleShowLogin(null,null, rsn[1]);
	if(showDetails){
		setTimeout(function() {COMP.LoadLibraries(['rws_results','rws_details']);}, 1);
		RWS.Search.SendDetailRequest(rsn[1]); 
	}
	if(showResults || simpleSearch){
		RWS.Search.CheckStartCommands(url);
	}
    
    if (window.opener) {
        window.isRunningResearcher = true;
        window.onunload = function() {
            window.opener.isRunningResearcher = false;
            window.isRunningResearcher = true;
        }
    }
};


//Disables highlighting of an html node for use when other custom selection 
//methods are being used (i.e. dataview, drag and drop, etc.).
function disableSelection(node) {
    node.onselectstart = function() {
        return false;
    };
    node.unselectable = "on";
    node.style.MozUserSelect = "none";
    node.style.cursor = "default";
};

var resetWhenShown;


function ResetFocus()
{
	var user = Ext.getCmp('user');
	if (user && user.isVisible())
	{
		Ext.getCmp('user').focus(true);
		return;
	}

	var simpleSearch = Ext.getCmp('simpleSearch');
	if (simpleSearch && simpleSearch.isVisible())
	{
		Ext.getCmp('simpleSearchBar_textfield').focus(true);
		return;
	}

	var advancedSearch = Ext.getCmp('advancedSearch');
	if (advancedSearch && advancedSearch.isVisible())
	{
		Ext.getCmp('advancedSearch').findById('advRow1_textfield').focus(true);
		return;
	}
    var comboSearch = Ext.getCmp('comboSearch');
}
if (window.COMP) COMP.Broadcast('scriptLoaded_rws');