(function(){

/*
	Class: Stage 
	The base class for a collection of navigation components 
*/
function Stage()
{
	this.contents = new window['SB']['util']['List'];
	this.htmlObj = null;
	this.spacer = null;
	this.loadingObj = null;
	this.zoomSliderThumb;
	this.scaleFactor;
	this.zoomControl;
	this.loadMoreObj = null;
	this.dashboard = null;
}

Stage.prototype.setDashboard = function( obj ) 
{ 
	this.dashboard = new obj;
	this.dashboard.setConfig( { stage:this } );
};

Stage.prototype.toString = function() { return "[SB.ui.Stage]"; }

//Group: Basic Methods 
/*
	Function: setConfig
	Establishes the basic setup for the Stage.
	
	inConfig - A configuration array (key/value)

	Configuration Array Options:
	id - the id of the div to use as a template (default:none)
*/
Stage.prototype.setConfig = function( inConfig )
{
	if( inConfig.id )
	{
		this.htmlObj = YUIDom.get( inConfig.id );
		YUIEvent.addListener( window, "resize", this.resize, this, true );

		this.loadingObj = YUIDom.get("sb_loading_message_screen");
		this.searchingObj = YUIDom.get("sb_searching_message_screen");
		this.noResultsObj= YUIDom.get("sb_noresults_message_screen");
		this.loadMoreListObj = YUIDom.get("sb_stage_load_more_list_view");
		this.loadMoreGridObj = YUIDom.get("sb_stage_load_more_grid_view");
		this.loadMoreFreeObj = YUIDom.get("sb_stage_load_more_free_view");

		var arr = YUIDom.getElementsByClassName("load_more_text","div",this.loadMoreListObj );
		if( arr[0] ) { this.origLoadListText = arr[0].innerHTML; }

		var arr = YUIDom.getElementsByClassName("load_more_text","div",this.loadMoreGridObj );
		if( arr[0] ) { this.origLoadGridText = arr[0].innerHTML; }

		var arr = YUIDom.getElementsByClassName("load_more_text","div",this.loadMoreFreeObj );
		if( arr[0] ) { this.origLoadFreeText = arr[0].innerHTML; }


		SButil.EventManager.addListener("BoxItemActivated", onBoxActivated, this);
		SButil.EventManager.addListener("ContainerItemActivated", onContainerActivated, this);
		SButil.EventManager.addListener("BoxItemsLoaded", onLoadBoxes, this);
		SButil.EventManager.addListener("BoxDeleted", onBoxDeleted, this);
		SButil.EventManager.addListener("ItemMoved", onItemMoved, this);
		SButil.EventManager.addListener("ItemDeleted", onItemDeleted, this);
		SButil.EventManager.addListener("ContainerDeleted", onContainerDeleted, this);
		SButil.EventManager.addListener("SwitchViewMode", onViewSwitch, this);
		SButil.EventManager.addListener("SearchResultsAvailable", onSearchResultsReceived, this);
		SButil.EventManager.addListener("SearchStarted", onSearchStarted, this);

		SButil.EventManager.addListener("SEItemUpdate", onItemUpdate, this);
		
	}

	if( window['SB']['ui']['ZoomSlider'] )	
	{
		this.zoomSliderThumb = YUIDom.get("slider-thumb");
		this.zoomSliderObj = YUIDom.get("zoom_slider");
		this.zoomControl = window['SB']['ui']['ZoomSlider'];
		this.zoomControl.ZoomControl();
	}
};

Stage.prototype.resize = function( inEvent )
{
	var bottomBar = YUIDom.get( "bottom_bar" );
	var masthead  = YUIDom.get( "masthead" );
	this.htmlObj.style.height = YUIDom.getViewportHeight() - (bottomBar.offsetHeight + this.htmlObj.offsetTop)  + "px"; 
};
 
/*
	Function: addItem
	A simple method to add a <BarItem> into the Bar
*/
Stage.prototype.addItem = function( inItem, toFront )
{
	this.contents.append( inItem ); 
	if( toFront )
		this.htmlObj.insertBefore( inItem.getHtmlObj(), this.htmlObj.firstChild ); 
	else
		this.htmlObj.appendChild( inItem.getHtmlObj() ); 

	if( inItem.didAttach ) inItem.didAttach();
};	

/*
	Function: removeItem 
	A simple method to remove a <BarItem> from the Bar
*/
Stage.prototype.removeItem = function( inItem )
{
	this.contents.remove( inItem );

	if( inItem.htmlObj )
		this.htmlObj.removeChild( inItem.getHtmlObj() ); 

	if( inItem.didDetach ) inItem.didDetach();
};	

/*
	Function: removeItemsAfter 
	A simple method to remove a <BarItem> from the Bar
*/
Stage.prototype.removeItemsAfter = function( inItem )
{
	var index = this.contents.find( inItem );
	if( index >= 0 )
	{
		this.contents.removeAfter( index );
		var children = YUIDom.getChildren( this.htmlObj );	

		var removeNow = false;	

		//Get rid of everything after inItem
		for( el in children )
		{
			if( removeNow )
				this.htmlObj.removeChild( children[el] ); 

			if( children[el] == inItem.getHtmlObj() )
				removeNow = true;					
		}
	}
};	

/*
	Function: removeAllItems
	A simple method to remove all <BarItem> from the Bar
*/
Stage.prototype.removeAllItems = function( )
{
	while ( this.contents.size() )
	{
		this.removeItem( this.contents.get(0) );
	}	

	var arr = YUIDom.getChildren( this.htmlObj );

	if ( arr.length > 0  ) {
		for( el in arr ) {
			this.htmlObj.removeChild( arr[el] );
		}
	}
	
};	

//Group: Delegate Methods 
/*
	Function: addItemTransition 
	A stub function which is called just after <addItem> is called
*/
Stage.prototype.addItemTransition = function()
{
};

/*
	Function: removeItemTransition 
	A stub function which is called just after <removeItem> or <removeAllItems> is called
*/
Stage.prototype.removeItemTransition = function()
{
};

Stage.prototype.loadItems = function(offset)
{
	if( offset == 0 ) this.removeAllItems();

	if( this.loadingObj.parentNode === this.htmlObj)
	{
		this.htmlObj.removeChild( this.loadingObj );	
	}

	var mode = parseInt(this.currentBox.view_type);

	var i = offset;
	var item_list = this.currentBox.box_obj.item_list;

	for( ; i < item_list.size(); i++ )
	{
		var item = null;

		switch( mode )
		{
			case 1:  item = new SBui.ListViewItem(); break;
			case 2:  item = new SBui.GridViewItem(); break;
			case 3:  item = new SBui.FreeViewItem(); break;
			default: item = new SBui.ListViewItem(); break;
		}

		var conf = this.currentBox.box_obj.item_list.get(i).getConfig();
		conf.item_obj = this.currentBox.box_obj.item_list.get(i);

		item.setConfig( conf );
		this.addItem( item, (mode == 3) );		
	}

	if( this.currentBox.total_items > item_list.size() )
	{
		var upper = (this.currentBox.total_items > (offset + 20))?
				(offset + 20):this.currentBox.total_items;

		var lMore = null;
		var lMoreText = null;

		switch( mode )
		{
			case 1:  
				lMore = this.loadMoreListObj; 
				lMoreText = this.origLoadListText;	
				break;
			case 2:  
				lMore = this.loadMoreGridObj; 
				lMoreText = this.origLoadGridText;	
				break;
			case 3:  
				lMore = this.loadMoreFreeObj; 
				lMoreText = this.origLoadFreeText;	
				break;
			default: 
				lMore = this.loadMoreListObj; 
				lMoreText = this.origLoadListText;	
				break;
		}

		this.loadMoreObj = lMore;

		var arr = YUIDom.getElementsByClassName("load_more_text","div",lMore);
		if( arr[0] )
		{
			var text = lMoreText;
			text = text.replace("START",(offset+11));
			text = text.replace("END",(upper));
			text = text.replace("TOTAL",this.currentBox.total_items);
			arr[0].innerHTML = text;

			this.htmlObj.appendChild( lMore );	

			var button = YUIDom.getFirstChildBy( arr[0], function(el) { return ( el.nodeName == "TABLE" ); } );

			if( button )
			{
				YUIEvent.removeListener( button, "click" ); 
				YUIEvent.addListener( button, "click", onLoadMoreItems, this, true );
			}
		}

		arr = YUIDom.getElementsByClassName("load_all","div",lMore);
		if( arr[0] )
		{

			var button = YUIDom.getFirstChildBy( arr[0], function(el) { return ( el.nodeName == "TABLE" ); } );

			if( button )
			{
				YUIEvent.removeListener( button, "click" ); 
				YUIEvent.addListener( button, "click", onLoadAllItems, this, true );
			}
		}

	}
	else
	{
		var arr = YUIDom.getElementsByClassName("load_more_text","div",this.loadMoreObj);
		if( arr[0] ) { YUIEvent.purgeElement( arr[0], true ); }

		arr = YUIDom.getElementsByClassName("load_all","div",this.loadMoreObj);
		if( arr[0] ) { YUIEvent.purgeElement( arr[0], true ); }


		if(this.loadMoreObj && this.loadMoreObj.parentNode === this.htmlObj) {
			this.htmlObj.removeChild( this.loadMoreObj );	
		}
	}

	if(mode == 3) {
		this.zoomSliderThumb.parentNode.parentNode.style.visibility = "visible";
		this.zoomControl.Set(conf.zoom); 
	} else {
		this.zoomSliderThumb.parentNode.parentNode.style.visibility = "hidden";
	}

};

Stage.prototype.showDashboard = function( initpage )
{
	this.removeAllItems();
	this.htmlObj.appendChild( this.loadingObj );	
	this.zoomSliderThumb.parentNode.parentNode.style.visibility = "hidden";

	if( this.dashboard ) this.dashboard.display(initpage);	
};

Stage.prototype.showWebpage = function( page )
{
	this.removeAllItems();
	this.htmlObj.appendChild( this.loadingObj );	
	this.zoomSliderThumb.parentNode.parentNode.style.visibility = "hidden";

	var cb = { 
		success:onWebRequestComplete,
		arguments: { stage:this} };
	YUIRequest.asyncRequest( "GET", "/index/"+page, cb );	
};

function onWebRequestComplete( inReq )
{
	if( box = SButil.StateManager.currentBox )
	{
		SButil.EventManager.fireEvent( "BoxItemDeactivated", { box:box } );
	}

	var stage = this.arguments.stage;
	if( stage.loadingObj.parentNode )
	{
		stage.htmlObj.removeChild( stage.loadingObj );	
	}

	stage.htmlObj.innerHTML = inReq.responseText;
}

//Event Handlers
function onLoadBoxes( inEvent, inArgs )
{
	this.sendBeacon();

	if( this.loadingObj.parentNode )
	{
		var overlay = YUIDom.get( "overlay" );
		overlay.style.display="none";

		this.loadingObj.parentNode.removeChild( this.loadingObj );	
	}
	if( this.currentBox != inArgs[0].box )
	{
		this.currentBox = inArgs[0].box; 
		this.loadItems(0);
	}
	else
	{
		this.loadItems(inArgs[0].offset);
	}
}

function onContainerActivated( inEv )
{
	this.sendBeacon();
}

function onLoadMoreItems( inEvent )
{

	var overlay = YUIDom.get( "overlay" );
	overlay.appendChild( this.loadingObj );
	overlay.style.display="block";

	this.currentBox.loadMoreItems();

	YUIEvent.stopEvent( inEvent );
}

function onLoadAllItems( inEvent )
{
	if( this.loadMoreObj.parentNode )
	{
		this.loadMoreObj.parentNode.removeChild( this.loadMoreObj );	
	}

	var overlay = YUIDom.get( "overlay" );
	overlay.appendChild( this.loadingObj );
	overlay.style.display="block";

	this.currentBox.loadAllItems();

	YUIEvent.stopEvent( inEvent );
}

function onBoxActivated( inEvent, inArgs )
{
	this.removeAllItems();
	this.htmlObj.appendChild( this.loadingObj );	
}

function onBoxDeleted( inEvent, inArgs )
{
	if( this.currentBox == inArgs[0].box )
	{
		this.currentBox = null;
		this.showDashboard('');
	}
}


function onViewSwitch( inEvent, inArgs )
{
	this.sendBeacon();

	if( this.currentBox )
	{
		this.currentBox.view_type = inArgs[0]; 
		this.loadItems(0);

		if( !this.currentBox.box_obj.disable_update )
		{	
			var pd = "id="+this.currentBox.box_obj.id;
			    pd += "&view_type="+inArgs[0];
			YUIRequest.asyncRequest( "POST", "/box/update", null, pd);
		}
	}
}

function onItemMoved( inEvent, inArgs )
{
	if( this.currentBox != inArgs[0].to )
	{
		this.removeItem( inArgs[0].item );		
	}
}

function onContainerDeleted( inEvent, inArgs )
{
	if( this.currentBox && (this.currentBox.box_obj.container_id == inArgs[0].container_id ))
	{
		this.removeAllItems();
	}
}


function onItemDeleted( inEvent, inArgs )
{
	for( var i = 0; i < this.contents.size(); i++ )
	{
		if( this.contents.get(i).item_obj == inArgs[0] )
		{
			this.removeItem( this.contents.get(i) );		
			return;
		}
	}
}

function onSearchStarted( inEvent, inArgs )
{
	this.removeAllItems();
	this.htmlObj.appendChild( this.searchingObj );	
}


function onSearchResultsReceived( inEvent, inArgs )
{
	if( this.searchingObj.parentNode )
		this.htmlObj.removeChild( this.searchingObj );	

	if( !inArgs[0].results.length )
		this.htmlObj.appendChild( this.noResultsObj );

	var i = 0;
	for( ; i < inArgs[0].results.length; i++ )
	{
		var item = null;
		item = new SBui.ListViewItem();

		var conf = inArgs[0].results[i];
		var obj = new SBCore.Item();
		obj.setConfig(conf);
		conf.item_obj = obj;
		conf.from = 1;
		item.setConfig( conf );
		this.addItem( item, false );		
	}
}

function onItemUpdate( inEvent, inArgs )
{

	if( inArgs[0].modstatus == "0" && inArgs[0].box_id == this.currentBox.box_obj.id )
	{
		var item = null;
		var mode = this.currentBox.view_type;

		switch( mode )
		{
			case 1:  item = new SBui.ListViewItem(); break;
			case 2:  item = new SBui.GridViewItem(); break;
			case 3:  item = new SBui.FreeViewItem(); break;
			default: item = new SBui.ListViewItem(); break;
		}

		var coreItem = new SBCore.Item();
		coreItem.setConfig( inArgs[0] );

		var conf = inArgs[0];
		conf.item_obj = coreItem;

		item.setConfig( conf );
		this.addItem( item, (mode == 3) );		
	}

}


/*-------------------------------------------*/
Stage.prototype.ZoomStart = function(scaleFactor)
{
	var junk = 0;
	//alert("START:"+scaleFactor);
};

Stage.prototype.ZoomInProgress = function(scaleFactor)
{
	for(var ix=0; ix < this.contents.data.length; ix++){
		this.contents.data[ix].resizeImg(scaleFactor);
	}
};

Stage.prototype.ZoomEnd = function(scaleFactor)
{
	for(var ix=0; ix < this.contents.data.length; ix++){
		this.contents.data[ix].saveImgLayout(scaleFactor);
	}
	
	if( !this.currentBox.box_obj.disable_update )
	{	
		//Math.round(scaleFactor*100); // should it be int?
		var sUrl = "/box/update";
		var pd = "id="+this.currentBox.box_obj.id;
		    pd += "&zoom="+scaleFactor;

		YUIRequest.asyncRequest('POST', sUrl, null, pd);	
	}
};
/*---------------------------------------------*/

Stage.prototype.sendBeacon = function()
{
	/*  //Disabling beacon for now
	var dt = new Date();
	var sUrl = "";
	
	if( window["sb_language"] == "ja" )	
	{
		if( window["sb_beacon_host"] )
			sUrl = "http://"+window["sb_beacon_host"]+"/beacon/ja.gif?r="+dt.getTime();
	}
	else
	{
		if( window["sb_beacon_host"] )
			sUrl = "http://"+window["sb_beacon_host"]+"/beacon/a.gif?r="+dt.getTime();
	}

	var beacon = YUIDom.get("beacon");
	if( beacon && sUrl.length )
	{
		beacon.src = sUrl;
	}
	*/
};

window['SB']['ui']['Stage'] = new Stage();

})();
