﻿Type.registerNamespace("Infragistics.Web.UI");

var $IG = Infragistics.Web.UI; 

/*****************GLOBAL CODE ************************/

/*ControlMain listens to onSubmit to determine when it should serialize it's postback data
 *into a hidden input field. However, onSubmit doesn't always fire. So in addition to that, 
 *we override __doPostBack so that we have a chance to store all ControlMain control's postback data*/
__igOldDoPostBack = window.__doPostBack;
window.__doPostBack = __igdoPostBack;

try
{
    Sys.Application.add_load(__igAppLoaded)    
    __igOldFormSubmit = theForm.submit;
    theForm.submit = __igFormSubmit;
}
catch(ex){};

function __igAppLoaded()
{
    if(Sys.WebForms.PageRequestManager)
    {
        var prm = Sys.WebForms.PageRequestManager.getInstance()
        __igOldWebFormsFormSubmit = prm._onFormSubmit;
        prm._onFormSubmit = __igdoPostBack2;
    }
}

if(typeof ig_controls !="object")
	var ig_controls=new Object();
function __igSubmit()
{
   if(ig_controls)
        for(var id in ig_controls)
            ig_controls[id]._onSubmitOtherHandler();
}
function __igdoPostBack2(evt)
{
    __igSubmit();
    this._onFormSubmit = __igOldWebFormsFormSubmit;
    this._onFormSubmit(evt);
}

function __igdoPostBack(eventTarget, eventArgument)
{
    __igSubmit();
    __igOldDoPostBack(eventTarget, eventArgument);
}

function __igFormSubmit()
{
    if(ig_controls)
        for(var id in ig_controls)
            ig_controls[id]._onSubmitOtherHandler();

    /* Firefox doesn't like it when you try to call submit off of anything besides the original form*/
    theForm.submit = __igOldFormSubmit;
    theForm.submit();
}
/*****************END GLOBAL CODE ********************/

/******************************************ControlMainProps ENUM************************************/
$IG.ControlMainProps = new function()
{
    this.Flags = [0, 0];
    this.Count = 1;
};
/******************************************END ControlMainProps ENUM********************************/

/******************************************CONTROL MAIN********************************************/
$IG.ControlMain = function(elem)
{
    $IG.ControlMain.initializeBase(this, [elem]);
    this._elements = {};
    this._callbackManager = new $IG.ControlCallbackManager(this);
    this._callbackManager.setResponseComplete(this._responseComplete, this);
}
$IG.ControlMain.prototype =
{
    /**********OVERRIDES**************/
	 initialize:function()
	 {	    
	    this._setupCollections();
	    var now1  = new Date();
	    
	    this.__walkThrough(this._element, true);
	    
	    this._setupMarkerElements();
	    $IG.ControlMain.callBaseMethod(this, 'initialize');	    
	    this.__attachEvents();
	    this.__attachOtherEvents();
	    this._uniqueID = this._get_clientOnlyValue("uid"); 	    
	    ig_controls[this._id] = this;	    

//	    var now2 = new Date() - now1;
//	    window.status += "Initialize Time:" + now2 + "; ";
	 },
	 
 	 dispose:function()
 	 {
 	    this._objectsManager.dispose();
	    this._collectionsManager.dispose();
	    $clearHandlers(this.get_element());
	    this.__clearOtherEvents(); 
	   
	  	$IG.ControlMain.callBaseMethod(this, 'dispose');
	 },
	 /**********END OVERRIDES**************/
	 
	 /********PRIVATE METHODS***********/
	 __attachEvents:function()
	 {
	    this._addHandlers();  	    
	    if(this._handlers && this._handlers.length > 0)
	    {
	        var evnts = {};
	        for(var i in this._handlers)
	        {
	           var evnt = this._handlers[i];
	           evnts[evnt] = this._onEventHandler;	           
	        }
	        $addHandlers(this.get_element(), evnts, this);
	    }	    
	 },
	 
	 __clearOtherEvents:function()
	 {
	    for(var array in this._otherHandlers)
	    {
	        for(var evnt in this._otherHandlers[array])
                $removeHandler(this._otherHandlers[array][evnt], evnt, this.__otherHandlerDelegate);
	    }
	 },
	 
	 __attachOtherEvents:function()
	 {
	    this._addOtherHandlers();
	    /*SJZ - Need to keep a reference to the delegate, so that we can remove it from the elements later */
	    this.__otherHandlerDelegate = Function.createDelegate(this, this._onOtherEventHandler);
	    if(this._otherHandlers && this._otherHandlers.length > 0)
	    {
	        for(var array in this._otherHandlers)
	        {
	           for(var evnt in this._otherHandlers[array])
	                $addHandler(this._otherHandlers[array][evnt], evnt, this.__otherHandlerDelegate);   
	        }
	    }
	 },	 
	 
	 _handleEvent:function(elem, adrElement, adr, e)
	 {
	    var func = this["_on" + e.type.substring(0,1).toUpperCase() + e.type.substring(1) + "Handler"];
	    if(func)
	        func.apply(this, [e.target, adr, e]);
	 },
	 
	__walkThrough:function(elem, topItem)
	{
		if($util._initAttr(elem))
			/* condition to stop walk: not main element and elem has normal id */
			if(!topItem)
				return;
        var adr = elem.getAttribute("adr");
        var mkr = elem.getAttribute("mkr");
        var obj = elem.getAttribute("obj");
        
        if(adr)
            this._createItem(elem, adr);
        else if(obj)
            this._createObject(elem, obj);
        else if(mkr)
            this._elements[mkr] = elem;
           
        // AK - moved down here. The element itself should be counted, but its children should not.
        // donp - added this check to ensure that we don't walk down into other controls using adr tags (as in templates)
        // control must define this attribute on an element that is not meant to be walked.
        var ctl = elem.getAttribute("nw");
        if(ctl)
            return;
            
        var children = elem.childNodes;
        for(var i = 0; i < children.length; i++)
        {
            var element = children[i];
            if(element.getAttribute)	            
              this.__walkThrough(element, false);
        }
	},
	
	__getViewStateEnabled:function()
	{
	    var vse = this._get_clientOnlyValue("vse");
	    if(vse == null)
	        return true;
	    else if(vse == 0)
	        return false;
	    else if(vse == 1)
	        return true;
	},
	 
	 /*********END PRIVATE METHODS*********/
	 
	 /*********EVENT HANDLERS***************/
	 _onEventHandler:function(e)
	 {
        var obj = $util.resolveMarkedElement(e.target, true);
        
        if(obj != null)
        {
            /* SJZ 9/11/07 - obj[2] is the control object on the element's parent. 
             * We need to make sure that the control this event is firing for
             * is our actual control, and not the control's parent, which could also inherit from ControlMain*/
            if(obj[2] == this)
                this._handleEvent(e.target, obj[0], obj[1], e);
        }
	 },
	 
	 _onOtherEventHandler:function(e)
	 {
	    if(e.type != null)
	    {
	        var func = this["_on" + e.type.substring(0,1).toUpperCase() + e.type.substring(1) + "OtherHandler"];
	        if(func)
	            func.apply(this, [e.target, e])
	    }
	 },
	 
	 _onSubmitOtherHandler:function(e)
	 {
	    var clientState = document.getElementById(this._id + "_clientState");
	    if(clientState) 
	    {	 
	        var vse = this.__getViewStateEnabled();       
	         var state = [[this._clientStateManager.get_serverProps(vse), this._objectsManager.getServerObjects(vse), this._collectionsManager.getServerCollection(vse)]];
	         
	         state[1] = [this._clientStateManager.get_transactionList(),
	                     this._collectionsManager.get_allTransactionLists()];
	        
	         state[2] = this._saveAdditionalClientState();
	         
	        clientState.value = Sys.Serialization.JavaScriptSerializer.serialize(state);
	    }
	        
	        
	 },
	 	 
	 /*********END EVENT HANDLERS***************/
	 
	 /*********PROTECTED VIRTUAL METHODS********/
	 _setupMarkerElements:function()
	 {
	 
	 },
	 _addHandlers:function()
	 {
	     /*TO BE IMPLEMENTED ON DERIVED CLASS*/
	 },
	 
	 _addOtherHandlers:function()
	 {
	    this._registerOtherHandlers([{"submit":theForm}]);
	 },
	
	 _createItem:function(element, adr)
	 {
	 
	 },
	 
	 _createObject:function(element, obj)
	 {
	 
	 },
	 
	 _responseComplete:function(callbackObject, responseObject)
	 {
	    
	 },
	 
	 _setupCollections:function()
     {
        this._itemCollection = this._collectionsManager.register_collection(0,$IG.ObjectCollection);
     },
     
     _saveAdditionalClientState:function()
     {
     },
   
	 /*********END PROTECTED VIRTUAL METHODS********/
	
		
	 /*********PROTECTED METHODS********/
	 
	 _set_value:function(index, value)
     {
         this._clientStateManager.set_value(index, value);
     },
    
     _get_value:function(index, isBool)
     {
         return this._clientStateManager.get_value(index, isBool);
     },
     
     _get_clientOnlyValue:function(propName)
     {
         return this._clientStateManager.get_clientOnlyValue(propName);
     },
     
     _get_occasionalProperty:function(propName)
     {
 	    return this._clientStateManager.get_occasionalProperty(propName);
     },
     
     _set_occasionalProperty:function(propName, val)
     {
 	    this._clientStateManager.set_occasionalProperty(propName, val);
     },
	 
 	 _cancelEvent: function(e)
     {
	    e.stopPropagation();
	    e.preventDefault();
     },
     
     _registerHandlers: function(handlers)
     {
       if(!this._handlers)
            this._handlers = [];
	   
	   this._handlers = this._handlers.concat(handlers);
     },
     
      _registerOtherHandlers: function(handlers)
     {
       if(!this._otherHandlers)
            this._otherHandlers = [];
	   
	   this._otherHandlers = this._otherHandlers.concat(handlers);
     },
     
     _add_item:function(adr, item)
     {
        this._items[adr] = item;
        this.__itemCount++;
     },
     
     _remove_item:function(adr)
     {
        if(adr in this._items)
        {
            delete this._items[adr];
            this.__itemCount--;
        }
     },

	_initClientEvents: function(vals)
	{
		this._initClientEventsForObject(this, vals);
	},
	_initClientEventsForObject: function(owner, vals)
	{
		owner._clientEvents = new Object();
		var i = vals ? vals.length : 0;
		while(i-- > 0)
		{
			var evt = vals[i].split(':');
			this.setClientEvent(owner, evt[0], evt[1], evt[2]);
		}
	},
	/* raise postback */
	/* args - postback-flag (1-full, 2-async) or EventArgs after raising a ClientEvent */
	/*  in this case args._props[1] contains postback-flag and all other _props[i] contain values which can be passed to server */
	/* evtName - name of event to raise */
	_postAction:function(args, evtName)
	{
		var act = args._props ? args._props[1] : args;
		if(act == 1)/* raise full postback */
		{
			/* VS 04/12/2007 adjust view/clent states */
			// ??
			/* VS 04/12/2007 parameters must be fixed */
			__igdoPostBack(this._id, evtName + ':extraParams');
			this._posted = true;
		}
		if(act == 2)/* raise async postback */
		{
			/* VS 04/12/2007 adjust view/clent states */
			// ??
			var cb = this._callbackManager.createCallbackObject();
			/* VS 04/12/2007 parameters/members of cbo.serverContext must be fixed */
			/* pass to server name of event */
			cb.serverContext.eventName = evtName;
			/* pass to server all properties used by EventArgs as props0, props1, props2, etc. */
			var i = args._props ? args._props.length : 0;
			while(--i > 1)
				eval('cb.serverContext.props' + (i - 2) + '="' + args._props[i] + '"');
			if(args._context)
			{
				for(var contextProp in args._context)
					cb.serverContext[contextProp] = args._context[contextProp];
			}
			/* pass to server all extra parameters which control may wish to */
			if(this._filterAsyncPostBack)
				this._filterAsyncPostBack(cb.serverContext, evtName, args);
			this._callbackManager.execute(cb);
			this._posted = true;
		}
	},

	/* It raises client side event: notify users and/or adjust postback flag */
	/* 1st param - name of event to fire or array of all parameters */
	/* 2nd param - null, or Xxx prefix of XxxEventArgs, or instance of EventArgs */
	/* 3rd param - original event of browser (optional) */
	/* 4th param - PostBackAction (or null) */
	/* 5th, 6th, ... - additional params to match with order of XxxEventArgs._props array */
	/* return: null or instance of XxxEventArgs */
	/* Examples: */
	/* this._raiseEvent('Initialize'); will raise "Initialize" event. If no listeners, then it returns null, otherwise, it returns Sys.EventArgs */
	/* this._raiseEvent('Click', null, e); will raise "Click" event. If no listerners, then it returns null, otherwise, it returns $IG.EventArgs */
	/* this._raiseEvent('Click', '', e); same as above */
	/* this._raiseEvent('Click', 'PostBack', e); will raise "Click" event. If no listerners and no postback, then it returns null, otherwise, it returns $IG.PostBackEventArgs */
	/* this._raiseEvent('Click', 'Cancel', e); will raise "Click" event. If no listerners and no postback, then it returns null, otherwise, it returns $IG.CancelEventArgs */
	/* this._raiseEvent('Click', new MyObject()); will raise "Click" event. It returns 2nd parameter as it is. */
	/* this._raiseEvent('Resizing', 'Resize', e, null, 1, 2, 3, 4); will raise "Resizing" event.  If no listerners and no postback, then it returns null, otherwise, it returns Infragistics.Web.UI.ResizeEventArgs();, which _props will be filled by 1-value returned by evt.get_height(), 2-value returned by evt.get_height(), etc. */
	/* this._raiseEvent('MyPostAct', null, null, 1); will raise "MyPostAct" event (if it is defined) and raise FullPostBack. It will return $IG.EventArgs. */
	/* this._raiseEvent('MyAsyncAct', 'Cancel', null, 2); will raise "MyAsyncAct" event (if it is defined) and raise AsyncPostBack. It will return $IG.CancelEventArgs. */
	/* this._raiseEvent('MyAsyncAct', new MyObject(), e, 2); will raise "MyAsyncAct" event (if it is defined) and raise AsyncPostBack. It will return 2nd parameter as it is. */
	_raiseClientEventStart:function(param)
	{
		var params = param;/* array of parameters which may come from the Infragistics.Web.UI.Behavior */
		if(params.substring)
			params = arguments;
		return this._raiseCE_0(this, params[0], this.getClientEventPostBack(params[0]), params[1], params);
	},
	_raiseClientEvent:function(param)
	{
		var args = this._raiseClientEventStart(param.substring ? arguments : param);
		return args ? this._raiseClientEventEnd(args, args._name) : null;
	},
	_raiseClientEventEnd:function(args)
	{
		///<summary>Triggers possible post back to end client event processing.</summary>
		///<param name="args">Event arguments.</param>
		///<returns>First parameter</returns>
		if(args && args._props && !(args.get_cancel && args.get_cancel()))
			this._postAction(args, args._name);
		return args;
	},
	_raiseSenderClientEvent:function(sender, clientEvent, eventArgs)
	{
		///<summary>Raises and triggers post back for a notify event.</summary>
		///<param name="sender">Object that raises the event and contains the clientEvents array.</param>
		///<param name="clientEvent">Client event object.</param>
		///<param name="eventArgs">Event arguments. Generally an object derived from Infragistics.Web.UI.CancelEventArgs.</param>
		///<returns>Event arguments object, the same object that is passed as the third parameter.</returns>
		eventArgs = this._raiseSenderClientEventStart(sender, clientEvent, eventArgs);
		return this._raiseClientEventEnd(eventArgs);
	},
	_raiseSenderClientEventStart:function(sender, clientEvent, eventArgs)
	{
		///<summary>Raises a cancelable before event but does not trigger post back.</summary>
		///<param name="sender">Object that raises the event and contains the clientEvents array.</param>
		///<param name="clientEvent">Client event object.</param>
		///<param name="eventArgs">Event arguments. Generally an object derived from Infragistics.Web.UI.CancelEventArgs.</param>
		///<returns>Event arguments object, the same object that is passed as the third parameter.</returns>
		return this._raiseCE_0(sender, clientEvent.name, clientEvent.postBack, eventArgs);
	},
	_raiseCE_0:function(me, evtName, post, args, params)
	{
		var fnc = me.get_events().getHandler(evtName);
		var str = args && args.substring;
		/* nothing to process and no request for autopostback */
		if(!fnc && post == null)/* if 2nd param is EvtArgs object, then return that object as it is */
			return str ? null : args;
		if(str)/* if 2nd param is string, then assume that is prefix for EventArgs */
			eval('try{args = new Infragistics.Web.UI.' + args + 'EventArgs();}catch(ex){args = null;}');
		var i = 1, len = params ? params.length : 0;
		if(!args)/* if EventArgs is missing or invalid, then create default args */
			args = (len < 3) ? new Sys.EventArgs() : new $IG.EventArgs();
		/* if it is our EventArgs object, then initialize its properties */
		if(args._props)
			while(++i < len) if(params[i] != null)
				args._props[i - 2] = params[i];
		/* initialize default postback action */
		if(post)
		{
			if(!args._props)
				args._props = new Array();
			if(!args._props[1] || args._props[1] == 0)
				args._props[1] = post;
		}
		/* fire event (notify listeners) */
		if(fnc)
			fnc(this, args);
		if(args._props)/* if it is our EventArgs object, then delete reference to browser event */
			delete args._props[0];
		args._name = evtName;
		return args;
	},

	_getFlags:function()
	{
	    if(this._flags == null)
	    {
	        this.__flagHelper = new $IG.FlagsHelper();
            var key = [$IG.ObjectBaseProps.Count + 0, this.__getDefaultFlags()]
            this._flags = new $IG.FlagsObject(this._get_value(key), this);
        }
        return this._flags;
	}, 
	
	_updateFlags:function(flags)
    {
        var key = [$IG.ObjectBaseProps.Count + 0, this.__getDefaultFlags()]
        this._set_value(key, flags)
    },
    
    _ensureFlags:function()
    {
        this._ensureFlag($IG.ClientUIFlags.Visible, $IG.DefaultableBoolean.True);
        this._ensureFlag($IG.ClientUIFlags.Enabled, $IG.DefaultableBoolean.True);
    },
    
    __getDefaultFlags:function()
    {
        if(this.__defaultFlags == null)
        {
            this._ensureFlags();
            this.__defaultFlags = this.__flagHelper.calculateFlags();
        }
        return this.__defaultFlags;
    },
    
    _ensureFlag:function(flag, val)
    {
        this.__flagHelper.updateFlag(flag, val);
    },
    
     /*********END PROTECTED METHODS********/
     
     /*********PROTECTED PROPERTIES*********/
     
     _get_clientStateManager:function(){return this._clientStateManager;},
	 
	 _get_item:function(adr)
	 {
        return this._itemCollection._getObjectByAdr(adr);
	 },
     
     /*********END PROTECTED PROPERTIES*********/
   
	 /*********PUBLIC PROPERTIES************/
	 set_id: function(id){ this._id = id;}, 
	 get_name: function(name){return this.get_element().name;},
	 set_name: function(value){this.get_element().name = value;},
	 get_uniqueID:function()
	 {
	   ///<summary>
	   /// Return's the Unique ID of the control. 
	   ///</summary>
	    return this._uniqueID
	 },

	/* add/remove a function-handler to process a ClientEvent */
	/* evtName - name of event, fnc - name of function or reference to function */
	addClientEventHandler:function(owner, evtName, fnc){$util.addClientEvent(owner, evtName, fnc);},
	removeClientEventHandler:function(owner, evtName, fnc){$util.removeClientEvent(owner, evtName, fnc);},

	getClientEventPostBack:function(name)
	{
		return this.getClientEventPostBackForObject(this, name);
	},
	getClientEventPostBackForObject:function(owner, name)
	{
		var ce = owner._clientEvents[name];
		return ce ? ce.postBack : null;
	},
	getClientEventFunction:function(name)
	{
		return this.getClientEventFunctionForObject(this, name);
	},
	getClientEventFunctionForObject:function(owner, name)
	{
		var ce = this._clientEvents[name];
		return ce ? ce.fnc : null;
	},
	setClientEvent:function(owner, evtName, fnc, postBack)
	{
		/* AK if postBack flag is provided convert it to a number */
		if (postBack)
			postBack = parseInt(postBack, 10);
		else
			postBack = 0;
		owner._clientEvents[evtName] = {name:evtName, fnc:fnc, postBack:postBack};
		if(evtName && fnc)
			this.addClientEventHandler(owner, evtName, fnc);
	},
	
	 get_props:function(){ return this._props; },
	 set_props:function(value)
	 {
	    this._dataStore = value;
	    this._props = value[0];
	    this._clientStateManager = new $IG.ObjectClientStateManager(this._props);
	    this._objectsManager = new $IG.ObjectsManager(this, value[1]);
	    this._collectionsManager = new $IG.CollectionsManager(this, value[2]);
	    this._initClientEvents(value[3]);
	 }
	 /*********END PUBLIC PROPERTIES************/
}
$IG.ControlMain.registerClass('Infragistics.Web.UI.ControlMain', Sys.UI.Control);
/******************************************END ControlMain*****************************************/

/******************************************NavControlProps ENUM************************************/
$IG.NavControlProps = new function()
{
     this.Count =$IG.ControlMainProps.Count + 0;
};
/******************************************END NavControlProps ENUM********************************/

/******************************************Nav Control************************************/

$IG.NavControl = function(elem)
{    
    $IG.NavControl.initializeBase(this, [elem]);    
}

$IG.NavControl.prototype =
{
    initialize:function()
    {        
        $IG.NavControl.callBaseMethod(this, 'initialize');
    },
    
    _setupCollections:function()
    {
        this._itemCollection = this._collectionsManager.register_collection(0,$IG.NavItemCollection);
        this._collectionsManager.registerUIBehaviors(this._itemCollection);
    }
}

$IG.NavControl.registerClass('Infragistics.Web.UI.NavControl', $IG.ControlMain);

/******************************************END Nav Control********************************/
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();