//enumerating the tabs, numbers correspond to the index
var TABS=
{
	ROUTE:		0,
	NUMBERS:	1,
	PASSENGERS:	2,
	VEHICLES:	3,
	CONFIRMATION:4,
	PAYMENT:	5,
	AGENTBOOKINGINFO: 6
}


var TabMovDir =
{
    FWD : 	1,
    BCK : 	2,
    START: 	3,
    END: 	4,
    ALL:	5
}

var TabMapper=Class.create(
{
	initialize: function()
	{
		this.RouteTab=null;
		this.NumbersTab=null;
		this.PassengersTab=null;
		this.VehiclesTab=null;
		this.ConfirmationTab=null;
		this.PaymentTab=null;
		this.AgentBookingInfo=null;
	},
	registerTabController: function(tab,TabRef)
	{
		switch (tab)
		{
			case TABS['ROUTE']:
				this.RouteTab=TabRef;
				break;
			case TABS['NUMBERS']:
				this.NumbersTab=TabRef;
				break;
			case TABS['PASSENGERS']:
				this.PassengersTab=TabRef;
				break;
			case TABS['VEHICLES']:
				this.VehiclesTab=TabRef;
				break;
			case TABS['CONFIRMATION']:
				this.ConfirmationTab=TabRef;
				break;
			case TABS['PAYMENT']:
				this.PaymentTab=TabRef;
				break;
			case TABS['AGENTBOOKINGINFO']:
				this.AgentBookingInfo=TabRef;
				break;
		}
	}//end registerTabController
});

var BookingsTab=Class.create(
{
	initialize:function(Tab,Containers,Observables,Buttons,NotifyDiv,MsgController,TabMapper)
	{
		this.url=location.href;
		this.tab=Tab;
		this.registerDivs(Containers);
		this.registerObservables(Observables);
		this.displayDivs=null;
		if (Buttons!=null)
		{
			this.ButtonColl=Buttons;
			this.ButtonColl.setObserver(this);
		}
		this.isDisabled=false;
		if (NotifyDiv !=null)
		{
			this.NotifyDiv=NotifyDiv;
			Element.hide($(this.NotifyDiv));
		}
		this.MsgController=MsgController;
		this.TabMapper=TabMapper;
	},//end initialize
	registerDivs: function(Containers)
	{
		var k=1;
		Containers.each(function(container)
		{
			this.AddDiv(k++,container);
		},this);
	},//end registerDivs
	registerObservables: function(Observables)
	{
		if (Observables.size != undefined)
		{
			Observables.each(function(property)
			{
				this[property.key]=property.value;
				this[property.key].setObserver(this);
			},this);
			this.Observables=Observables;
		}
		else
		{
			this.Observables=null;
		}
	},//register Observables
	getContentDiv: function getContentDiv(divName)
	{
		return $(divName+'Content');
	},//end getContentDiv
	AddDiv: function(step,divName)
	{
		this['STEP'+step]=divName;  //yields a property of the form this.STEPx
	},
	setObservableEvent: function(sender)
	{
		//Must override in child classes
		//maybe use this to register number of callssss ?!?!
	},//end setObservableEvent
	disableControls: function()
	{
		this.ButtonColl.disableButtons();
		this.isDisabled=true;
	},//end disableControls
	enableControls: function()
	{
		this.ButtonColl.enableButtons();
		this.isDisabled=false;
	},//end enableControls
	getDiv: function(step)
	{
		return this['STEP'+step];
	}//end getDiv
});//end BookingsTab

var TabButtons=Class.create(
{
    initialize: function(Containers,ConfirmationMessages)
    {
        this.Top=$(Containers.Top); //Convience property - otherwise use Containers[0]
        this.Bottom=$(Containers.Bottom); //Convience property
        this.TabControl=Containers.TabControl;
        this.Containers=[this.Top,this.Bottom];
        this.buttons=[];
        this.fwdId='btnNext'; //constant name, can be changed from backend when initing
        this.bckId='btnPrevious'; //ditto above
        this.startId='btnStart'; //ditto above
        this.BackButtons=[];
        this.FowardButtons=[];
        this.registerButtons(this.Containers);
        this.disableButtons();
        this.observer=null;
        this.NextMsg=null;
        this.PrevMsg=null;
        this.StartMsg=null;
        if (ConfirmationMessages=='undefined' || ConfirmationMessages==null)
        	this.ConfirmationMessages=null;
        else
        {
			this.registerMessages(ConfirmationMessages);
		}
		//alert('Has Msgs:' + this.hasMessages());

    },
    hasMessages: function()
    {
    	return (this.ConfirmationMessages!=null);
    },
    registerMessages: function(Messages)
    {
			$H(Messages).each(function(property)
			{
				this[property.key]=property.value;
			},this);
			this.ConfirmationMessages=Messages;
    },
    setObserver: function(observer)
    {
        this.observer=observer;
    },
    RaiseButtonPress: function(args)
    {
    	var Dir=args[0];
    	//alert(Dir);
    	if (this.hasMessages())
    	{
    		var confirmed=false;
			/* IMP NOTE
				For some obscure reason switch was not working here...did it as if then else instead
			*/
			var showConfirmAfterHandler=false;

			if (args.length>1)
				showConfirmAfterHandler=args[1];

    		if (Dir==TabMovDir['FWD'])
    		{
    			if (this.NextMsg!=null && !showConfirmAfterHandler)
    			{
    				confirmed=confirm(this.NextMsg);
    			}
    			else
    			{
    				confirmed=true; //since message does not exist then we don't need it or else confirm will be handled by the controller
    			}
    		}
    		else if (Dir==TabMovDir['BCK'])
    		{
    			if (this.PrevMsg!=null && !showConfirmAfterHandler)
					confirmed=confirm(this.PrevMsg);
				else
					confirmed=true; //since message does not exist then we don't need it
    		}
			if (confirmed)
				this.observer.setObservableEvent(this,args);
			else
				return false;
    	}
    	else
    	{
        	this.observer.setObservableEvent(this,args);
        }
        return false; //DO NOT TOUCH THIS - Sometimes may post....if any error is encountered in js it will also post so amend code with care!
    },
    registerButtons: function(Containers) //Back and Foward button logic added after, buttons array left not to break. Should change it to be a bit smarter
    {
       Containers.each(function(Container)
       {
            $(Container).select('button').each(function(btn)
            {
            	var btnId=$(btn).identify();

            	if (btnId.lastIndexOf(this.fwdId)!=-1) //therefore a match
            		this.FowardButtons.push($(btn));
            	else if (btnId.lastIndexOf(this.bckId)!=-1 || btnId.lastIndexOf(this.startId)!=-1) //therefore a match - Both the start and back buttons are considered to be back buttons
            		this.BackButtons.push($(btn));

                this.buttons.push($(btn)); //add the button to the this.buttons collection
            },this);
       },this);
    },
    showAll: function(blnEffects)
    {
        if (blnEffects)
            this.Containers.each(Effect.Appear);
            //for some reason invoke does not work with this..to examine further
        else
            this.Containers.each(Element.show);
            //ditto comment above
        this.enableButtons(); //enable the buttons just in case they are disabled
    },
    hideAll: function(blnEffects)
    {
        if (blnEffects)
            this.Containers.each(Effect.SwitchOff);
        else
            this.Containers.each(Element.hide);
    },
    disableButtons: function(NavType)
    {
		if (NavType=='undefined' || NavType==null)
			NavType=TabMovDir['ALL'];

        switch (NavType)
		{
			case (TabMovDir['ALL']):
			{
        		this.buttons.each(function (b)
        		{
            		$(b).addClassName('disable'); //$ is needed due to ie 6 bug - in theory not needed
            		Form.Element.disable($(b));
        		});
				break;
			}
			case (TabMovDir['FWD']):
			{
        		this.FowardButtons.each(function (b)
        		{
            		$(b).addClassName('disable'); //$ is needed due to ie 6 bug - in theory not needed
            		Form.Element.disable($(b));
        		});
				break;
			}
			case (TabMovDir['BCK']):
			{
        		this.BackButtons.each(function (b)
        		{
            		$(b).addClassName('disable'); //$ is needed due to ie 6 bug - in theory not needed
            		Form.Element.disable($(b));
        		});
				break;
			}
		}
    },
    enableButtons: function(NavType)
    {
		if (NavType=='undefined' || NavType==null)
			NavType=TabMovDir['ALL'];

		switch (NavType)
		{
			case TabMovDir['ALL']:
			{
				this.buttons.each(function (b)
        		{
            		$(b).removeClassName('disable'); //$ is needed due to ie 6 bug - in theory not needed
            		Form.Element.enable($(b));
        		});
				break;
			}
			case TabMovDir['FWD']:
			{
				this.FowardButtons.each(function (b)
        		{
            		$(b).removeClassName('disable'); //$ is needed due to ie 6 bug - in theory not needed
            		Form.Element.enable($(b));
        		});
				break;
			}
			case TabMovDir['BCK']:
			{
				this.BackButtons.each(function (b)
        		{
            		$(b).removeClassName('disable'); //$ is needed due to ie 6 bug - in theory not needed
            		Form.Element.enable($(b));
        		});
				break;
			}
		}
    },
    MoveToTab: function(direction)
    {
        var webTab = igtab_getTabById(this.TabControl);
        var numTabs= webTab.Tabs.length;
        var currTab = webTab.getSelectedIndex();
        var newSelTab=0;
        if (direction==TabMovDir['FWD'])
        {
            if ((currTab+1) < numTabs) //Then we can proceed
            {
                newSelTab=currTab+1;
            }
        }
        else if (direction==TabMovDir['BCK'])
        {
            if ((currTab-1) >= 0) //Then we can proceed
            {
                newSelTab=((currTab-1)>0 ? (currTab-1) : 0);
                this.DisableTab(currTab);
            }
        }
        webTab.setSelectedIndex(newSelTab);
        webTab.setEnabled(true);
    },//end MoveToTab - Name should be MoveTab
    MoveToTabIndex: function(index)
	{
    	var webTab = igtab_getTabById(this.TabControl);
    	var numTabs= webTab.Tabs.length;
    	var currTab = webTab.getSelectedIndex();
    	if (index < numTabs)
    	{
        	webTab.setSelectedIndex(index);
        	webTab.setEnabled(true);
    	}
	},//end MoveToTabIndex;
	DisableTab: function(idx)
	{
		var webTab = igtab_getTabById(this.TabControl);
    	var tab = webTab.Tabs[idx];
    	tab.setEnabled(false);
	},//end DisableTab
	EnableTab: function(idx)
	{
		var webTab = igtab_getTabById(this.TabControl);
    	var tab = webTab.Tabs[idx];
    	tab.setEnabled(true);
	}//end EnableTab
}); //end Tab Buttons

/*  Hides steps for the given nodes
Note: More than 1 item must be present in the node list
*/
function HideSteps(nodeList,useEffects)
{
    try
    {
        if (useEffects)
        {
            nodeList.each(Effect.BlindUp);
        }
        else
        {
            nodeList.invoke('hide');
        }
    }
    catch (err)
    {
        //do nothing...its only because the node name was not found and lib could not clip it
    }
}

var ReservationList=Class.create(
{
	initialize: function(ControlHierarchy,Controls)
	{
		this.registerControls(ControlHierarchy,Controls);
	},//end initialize
	registerControls: function(ControlHierarchy,Controls)
	{
		if (Controls.size != undefined)
		{
			Controls.each(function(property)
			{
				if (property.key=='ListTable')
					this[property.key]=$(property.value);
				else if (property.key=='ListTableBody')
					this[property.key]=$(property.value);
				else if (property.key=='ListRadioRef')
					this[property.key]=property.value;
				else
					this[property.key]=$(ControlHierarchy + property.value);
			},this);
			this.Controls=Controls;
		}
		else
		{
			this.Controls=null;
		}
	},//end Register Controls
	setBookingId: function(BookingId)
	{
		this.BookingId.innerHTML=BookingId;
	},//end setBookingId
	getBookingId: function()
	{
		return this.BookingId.innerHTML;
	},//end getBookingId
	setObserver: function(observer)
	{
		this.observer=observer;
	},//end setObserver
	RaiseItemSelected: function(objId,rowIndex)
	{
		this.observer.setObservableEvent(this,[$F(objId),this.ListTableBody,rowIndex]);
	},//end ItemSelectedEvent
	buildResTable: function(selIndex,ItemCollection)
	{
		try
		{
			var tbl=this.ListTableBody;
			var rowCount=tbl.rows.length;
			//delete all rows from the existing tbody
			while (tbl.rows.length>0)
			{
				tbl.deleteRow(0);
			}
			//build all rows again
			rowCount=0;
			var ObjectRef=this.observer.InstanceName+'.'+this.ListRadioRef; //This builds an object string reference of the form insPassengerController.PassList
			//which is then used to build the radio button
			//if (ItemCollection.size()>0) //check added but no
		//	{
			ItemCollection.each(function(i)
			{
				//should use the builder object in prototype to do this
				//need to experiment with it
				var blnSel=false;
				if (rowCount==selIndex)
					blnSel=true;

				var item=i.value;
				tbl.insertRow(-1); //append to end
				var td=tbl.rows[rowCount].insertCell(-1);
				td.innerHTML=item.getRadioAndImageHTML(rowCount,blnSel,ObjectRef);
				if (blnSel)
				{
					$(tbl.rows[rowCount]).addClassName('highlight');
				}
				var td=tbl.rows[rowCount].insertCell(-1);
				td.innerHTML=item.getNameHTML(rowCount);
				var td=tbl.rows[rowCount].insertCell(-1);
				td.innerHTML=item.getReservationIdHTML(rowCount);
				rowCount++;
			},this);
			this.ListContainer.style.display='block';
			//}
		}
		catch (err)
		{
			//do nothing - and do not switch on an alert
			//this is on purpose so that
			alert(err); //feed the error object and log in database or email admin
		}
	}//end buildResTable
});

var ReservationDetails=Class.create(
{
	//NOTE: This super class assumes that there is always a title and a button verify
	initialize: function(ControlHierarchy,Controls)
	{
		this.registerControls(ControlHierarchy,Controls);
		this.numErrors=0;
		this.observer=null;
		this.ValidationErrors=new Array();
		this.disableControls();
	},
	setObserver: function(observer)
	{
		this.observer=observer;
	},
	registerControls: function(ControlHierarchy,Controls)
	{
		if (Controls.size != undefined)
		{
			Controls.each(function(property)
			{
				this[property.key]=$(ControlHierarchy + property.value);

				//alert('Registered ' + property.key + ' As ' + this[property.key]);
			},this);
			this.Controls=Controls;
		}
		else
		{
			this.Controls=null;
		}
	},//Register Controls
	disableControls: function() //FromInit indicates if this call is being made from the initialize method, in this case infragistics has not initied its own ids so no reference to the date object
	{
		this.Controls.each(function(property)
		{
			Form.Element.disable(this[property.key]);
		},this);
		//although its in the list form element disable does not take it
		this.VerifyButton.addClassName('disable');
	},
	enableControls: function()
	{
		this.Controls.each(function(property)
		{
			Form.Element.enable(this[property.key]);
		},this);
		this.VerifyButton.removeClassName('disable');
	},
	setTitle: function(str)
	{
		$(this.Title).innerHTML=str;
	},
	getTitle: function() //should never be needed but for consistency
	{
		return $(this.Title).innerHTML;
	}
});