﻿// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx.
// All other rights reserved.

Type.registerNamespace('TripzoomLib');

TripzoomLib.CollapsiblePanelExpandDirection = function() {
    /// <summary>
    /// The CollapsiblePanelExpandDirection enumeration describes whether the panel is opened vertically or horizontally
    /// </summary>
    /// <field name="Horizontal" type="Number" integer="true" />
    /// <field name="Vertical" type="Number" integer="true" />
    throw Error.invalidOperation();
}
TripzoomLib.CollapsiblePanelExpandDirection.prototype = {
    Horizontal : 0,
    Vertical: 1
}
TripzoomLib.CollapsiblePanelExpandDirection.registerEnum("TripzoomLib.CollapsiblePanelExpandDirection", false);


TripzoomLib.CollapsiblePanelBehavior = function(element) {
    /// <summary>
    /// The CollapsiblePanelBehavior allows you to add collapsible sections to your page
    /// </summary>
    /// <param name="element" type="Sys.UI.DomElement" domElement="true">
    /// Element to associate the behavior with
    /// </param>
    TripzoomLib.CollapsiblePanelBehavior.initializeBase(this, [element]);
    
    // property values
    this._collapsedSize = 0;
    this._expandedSize = 0;
    this._scrollContents = null;    
    this._collapsed = false;    
    this._expandControlID = null;
    this._collapseControlID = null;
    this._textLabelID = null;    
    this._collapsedText = null;
    this._expandedText = null;
    this._imageControlID = null;
    this._expandedImage = null;
    this._collapsedImage = null;
    this._suppressPostBack = null;
    this._autoExpand = null;
    this._autoCollapse = null;
    this._expandDirection = TripzoomLib.CollapsiblePanelExpandDirection.Vertical;
    
    // handler delegates
    this._collapseClickHandler = null;
    this._expandClickHandler = null;    
    this._mouseEnterHandler = null;    
    this._mouseLeaveHandler = null;
    
    // the div we wrap around the panel contents
    this._parentDiv = null;
    
    // Animation used to open/close the panel
    this._animation = null;
}
TripzoomLib.CollapsiblePanelBehavior.prototype = {    
    initialize : function() {
        /// <summary>
        /// Initialize the behavior
        /// </summary>
        TripzoomLib.CollapsiblePanelBehavior.callBaseMethod(this, 'initialize');
        
        var element = this.get_element();
        /*
        this._animation = new AjaxControlToolkit.Animation.LengthAnimation(element, .25, 10, 'style', null, 0, 0, 'px');
        if (this._expandDirection == AjaxControlToolkit.CollapsiblePanelExpandDirection.Vertical) {
            this._animation.set_propertyKey('height');
        } else if (this._expandDirection == TripzoomLib.CollapsiblePanelExpandDirection.Horizontal) {
           this._animation.set_propertyKey('width');
        }
        this._animation.add_ended(Function.createDelegate(this, this._onAnimateComplete));
        */
        
        // for checkboxes, we don't want to suppress the posback (e.g. return false)
        // because that stops them from toggling their state.
        //           
        if (this._suppressPostBack == null) {
            if (element.tagName == "INPUT" && element.type == "checkbox") {
                this._suppressPostBack = false;
                this.raisePropertyChanged('SuppressPostBack');
            }                    
            else if (element.tagName == "A") {
                this._suppressPostBack = true;
                this.raisePropertyChanged('SuppressPostBack');
            }
        }
        
        
        // Check our client state.  If it's present,
        // that means this is a postback, so we restore the state.
        //
        var lastState = TripzoomLib.CollapsiblePanelBehavior.callBaseMethod(this, 'get_ClientState');                
        if (lastState && lastState != "") {
            var wasCollapsed = Boolean.parse(lastState);  
            if (this._collapsed != wasCollapsed) {
                this._collapsed = wasCollapsed;
                this.raisePropertyChanged('Collapsed');       
            }
        }
        
        this._setupParentDiv();        
        
        // setup the initial size and state
        //
        if (this._collapsed) {
            this._setTargetSize(this._getCollapsedSize());            
        } else {            
            this._setTargetSize(this._getExpandedSize());
        } 
        
        this._setupState(this._collapsed);
        
        // setup all of our handlers.
        if (this._collapseControlID == this._expandControlID) {
            this._collapseClickHandler = Function.createDelegate(this, this._toggle);
            this._expandClickHandler = null; // we don't need both if we're toggling.
        } else {
            this._collapseClickHandler = Function.createDelegate(this, this._doClose);
            this._expandClickHandler = Function.createDelegate(this, this._doOpen);       
        }
        
        if (this._autoExpand) {
            this._mouseEnterHandler = Function.createDelegate(this, this._onMouseEnter);
            $addHandler(element, 'mouseover', this._mouseEnterHandler);
        }       
        if (this._autoCollapse) {
            this._mouseLeaveHandler = Function.createDelegate(this, this._onMouseLeave);
            $addHandler(element, 'mouseout', this._mouseLeaveHandler);
        }
        
        // attach the click handlers
        //
        if (this._collapseControlID) {
            var collapseElement = $get(this._collapseControlID);
            if (!collapseElement) {
                throw Error.argument('CollapseControlID', "Failed to find element '" + this._collapseControlID + "'");
            } else {
                $addHandler(collapseElement, 'click', this._collapseClickHandler);
            }
        }
        
        if (this._expandControlID) {
            if (this._expandClickHandler) { // if it's a toggle don't set up again
                var expandElement = $get(this._expandControlID);
                if (!expandElement) {
                    throw Error.argument('ExpandControlID', "Failed to find element '" + this._expandControlID + "'");
                } else {
                    $addHandler(expandElement, 'click', this._expandClickHandler);
                }
            }
        }
    },
    
    dispose : function() {
        /// <summary>
        /// Dispose the behavior
        /// </summary>
        
        var element = this.get_element();
        
        if (this._collapseClickHandler) {
            var collapseElement = (this._collapseControlID ? $get(this._collapseControlID) : null);
            if (collapseElement) {
                $removeHandler(collapseElement, 'click', this._collapseClickHandler);
            }
            this._collapseClickHandler = null;
        }
        
        if (this._expandClickHandler) {
            var expandElement = (this._expandControlID ? $get(this._expandControlID) : null);
            if (expandElement) {
                $removeHandler(expandElement, 'click', this._expandClickHandler);
            }
            this._expandClickHandler = null;
        }
        
        if (this._mouseEnterHandler) {
            $removeHandler(element, 'mouseover', this._mouseEnterHandler);
        }
        
        if (this._mouseLeaveHandler) {
            $removeHandler(element, 'mouseout', this._mouseLeaveHandler);
        }
        
        if (this._animation) {
            this._animation.dispose();
            this._animation = null;
        }
        
        TripzoomLib.CollapsiblePanelBehavior.callBaseMethod(this, 'dispose');
    },
    
    _checkCollapseHide : function() {
        /// <summary>
        /// Check if a control is collapsed and hidden
        /// (and set its display to none if it is supposed to be hidden)
        /// </summary>
        /// <returns type="Boolean">
        /// Whether the control is collapsed and hidden
        /// </returns>

        if (this._collapsed && this._getTargetSize() == 0) {
            var e = this.get_element();
            var display = CommonToolkitScripts.getCurrentStyle(e, 'display');
            if (!e.oldDisplay && display != "none") {
                e.oldDisplay = display;
                e.style.display = "none";
            }
            return true;
        }
        return false;
    },
    
    _doClose : function(eventObj) { 
    

    
		this._onAnimateComplete();
        this._setupState(true);
                
		startSize = this._getCollapsedSize();
		
		var e = this._element;
		if (!startSize) {
			e.style.display = 'none';
			e.style.height = '';
		} else { 
			e.style.height = startSize + 'px';
		} 		
		
        if (this._expandDirection == TripzoomLib.CollapsiblePanelExpandDirection.Vertical) {
            e.style.overflowY = "hidden";
            this._parentDiv.style.overflowY = ""; 
        } else {
            e.style.overflowX = "hidden";
            this._parentDiv.style.overflowX = ""; 
        }
            		
        // stop postback if necessary.
        //
        if (this._suppressPostBack) {
            if (eventObj && eventObj.preventDefault) {
                eventObj.preventDefault();
            } else {
                event.returnValue = false;
                return false;
            }
        }		
    }, 
    

    
    _doOpen : function(eventObj) { 
        this._element.style.display = 'block';
        this._element.style.height = '';
        
        this._onAnimateComplete();
        
        this._setupState(false);
        
        
        if (this._suppressPostBack) {
            if (eventObj && eventObj.preventDefault) {
                eventObj.preventDefault();
            } else {
                event.returnValue = false;
                return false;
            }
        }		
        
        
    }, 
    
  
    _onAnimateComplete : function() {
        /// <summary>
        /// Handler to listen for the end of the expand/collapse animation
        /// </summary>
    
        var e = this.get_element();
    
        // if we're fully expanded and the inner pannel is still smaller
        // than the size we've expanded to, fall back to auto
        //    
        if (!this._collapsed && !this._expandedSize && this._parentDiv.offsetHeight <= e.offsetHeight) {
            e.style.height = "auto";
            this.raisePropertyChanged('TargetHeight');
        } else {
            this._checkCollapseHide();
        }
        
        if (this._collapsed) {
        	this.raiseExpandComplete()
        } else {
	        this.raiseCollapseComplete();
       }
    },
    
    _onMouseEnter : function() {
        /// <summary>
        /// OnMouseOver Handler
        /// </summary>
        if (this._autoExpand) {
            this._doOpen();
        }
    },
    
    _onMouseLeave : function() {
        /// <summary>
        /// OnMouseOut Handler
        /// </summary>
        if (this._autoCollapse) {
           this._doClose();
        }
    },
    
    _getExpandedSize : function() {
        /// <summary>
        /// Get the size of the panel when fully expanded
        /// </summary>
        /// <returns type="Number" integer="true">
        /// Size of the panel when fully expanded
        /// </returns>
    
        if (this._expandedSize) {
            return this._expandedSize;
        }                
        
        if (this._expandDirection == TripzoomLib.CollapsiblePanelExpandDirection.Vertical) {
            return this._parentDiv.offsetHeight;
        } else if (this._expandDirection == TripzoomLib.CollapsiblePanelExpandDirection.Horizontal) {
            return this._parentDiv.offsetWidth;
        }
    },
    
    _getCollapsedSize : function() {
        /// <summary>
        /// Get the size of the panel when fully collapsed
        /// </summary>
        /// <returns type="Number" integer="true">
        /// Size of the panel when fully collapsed
        /// </returns>

        if (this._collapsedSize) {
            return this._collapsedSize;
        }
        
        return 0;
    },
    
     _getTargetSize : function() {
         /// <summary>
         /// Get the target size of the Panel
         /// </summary>
         /// <returns type="Number" integer="true">
         /// Target size of the Panel
         /// </returns>

        var value;
        if (this._expandDirection == TripzoomLib.CollapsiblePanelExpandDirection.Vertical) {
           value = this.get_TargetHeight();
        } else if (this._expandDirection == TripzoomLib.CollapsiblePanelExpandDirection.Horizontal) {
           value = this.get_TargetWidth();
        }       
        
        // Safari returns undefined if display is 'none'
        //
        if (value === undefined) {
            value = 0;
        }
        return value;
    },
    
    _setTargetSize : function(value) {
        /// <summary>
        /// Set the target size of the panel
        /// </summary>
        /// <param name="value" type="Number" integer="true">
        /// Target size of the panel
        /// </param>

        // we don't always want to set the target size here.
        // if we don't have an expanded size, and we're not collapsed,
        // and we're at (or past) our "maximum" size
        //
        var useSize = this._collapsed || this._expandedSize;
        var e = this.get_element();
        if (this._expandDirection == TripzoomLib.CollapsiblePanelExpandDirection.Vertical) {
            if (useSize || value < e.offsetHeight) {
                this.set_TargetHeight(value);
            } else {
                // if we're at our maximum size, flip to auto 
                // so that nested collapsible panels will
                // work properly.
                //
                e.style.height = "auto";
                this.raisePropertyChanged('TargetHeight');
            }
        } else if (this._expandDirection == TripzoomLib.CollapsiblePanelExpandDirection.Horizontal) {
            if (useSize || value < e.offsetWidth) {
                this.set_TargetWidth(value);
            }
            else {
                e.style.width = "auto";
                this.raisePropertyChanged('TargetWidth');
            }            
        }
        this._checkCollapseHide();
    },
    
    _setupParentDiv : function() {
        /// <summary>
        /// Set up a parent div to host our panel contents
        /// and then push the panel's children into it.
        /// </summary>

        
        var startSize = this._getTargetSize();
        
        var e = this.get_element();
                
        this._parentDiv = e.cloneNode(false);
        this._parentDiv.id = '';
        
        // move all children into the div.
        //
        while (e.hasChildNodes()) {            
            var child = e.childNodes[0];
            child = e.removeChild(child);
            this._parentDiv.appendChild(child);                
        }

        //Delete some style after cloneNode
        //On Clone
        this._parentDiv.style.position = ""; 
        this._parentDiv.style.border   = ""; 
        this._parentDiv.style.margin   = ""; 
        //On Parent
        e.style.padding = "";

                
        if (this._scrollContents) {        
            e.style.overflow = "scroll";
         }
         else {
            if (this._expandDirection == TripzoomLib.CollapsiblePanelExpandDirection.Vertical) {
                e.style.overflowY = "hidden";
                this._parentDiv.style.overflowY = ""; 
            } else {
                e.style.overflowX = "hidden";
                this._parentDiv.style.overflowX = ""; 
            }
            
         }
                
        // we optimize for the case where the original size is the collapsed size.
        // if that's the case, we go ahead and set the inner panel to auto so you 
        // can still expand it but not see it expanded by default when the page loads.
        //
        if (startSize == this._collapsedSize) {
            if (this._expandDirection == TripzoomLib.CollapsiblePanelExpandDirection.Vertical) {
                this._parentDiv.style.height = "auto"; 
            } else if (this._expandDirection == TripzoomLib.CollapsiblePanelExpandDirection.Horizontal) {
                this._parentDiv.style.width = "auto"; 
            }
        }
        
        e.appendChild(this._parentDiv);
        
        if (this._collapsed) {
            startSize = this._getCollapsedSize();
        }
        else {
            startSize = this._getExpandedSize();
        }
            
        // set up our initial size
        //    
        if (this._expandDirection == TripzoomLib.CollapsiblePanelExpandDirection.Vertical) {
            e.style.height = startSize + "px";
            e.style.width = CommonToolkitScripts.getCurrentStyle(this._parentDiv, 'width');
            
            if (!this._expandedSize) {                                         
                e.style.height = "auto";
            }
            else {
               e.style.height = this._expandedSize + "px";
            }
			this._parentDiv.style.height = "auto";

            
        } else if (this._expandDirection == TripzoomLib.CollapsiblePanelExpandDirection.Horizontal) {
            e.style.height = CommonToolkitScripts.getCurrentStyle(this._parentDiv, 'height');
            e.style.width = startSize + "px";
            
            //e.style.width = this._getExpandedSize() + "px";
  
            if (!this._expandedSize) {                                         
                e.style.width = "auto";
            }
            else {
               e.style.width = this._expandedSize + "px";
            }
        }    
    },
    
    _setupState : function(isCollapsed) {
        /// <summary>
        /// Get all the state set consistently when we change modes
        /// </summary>
        /// <param name="isCollapsed" type="Boolean">
        /// True to setup the state as if we're collapsed, false to setup the state as if we're expanded
        /// </param>

    
        if (isCollapsed) {           
        
            // change the text label ID if we have one.
            //
            if (this._textLabelID && this._collapsedText) {
                var e = $get(this._textLabelID);
                
                if (e) {
                    e.innerHTML = this._collapsedText;
                }
            }
            
            // Change the image if we have one
            if (this._imageControlID && this._collapsedImage) {
                var i = $get(this._imageControlID);
                if (i && i.src) {
                    i.src = this._collapsedImage;
                    if (this._expandedText || this._collapsedText) {
                        i.title = this._collapsedText;
                    }
                }
            }            
        }
        else {  
            if (this._textLabelID && this._expandedText) {
                var e = $get(this._textLabelID);
                
                if (e) {
                    e.innerHTML = this._expandedText;
                }
            }
            
            // Change the image if we have one
            if (this._imageControlID && this._expandedImage) {
                var i = $get(this._imageControlID);
                if (i && i.src) {
                    i.src = this._expandedImage;
                    if (this._expandedText || this._collapsedText) {
                            i.title = this._expandedText;
                    }
                }
            }        
        } 
        
        // set our member variable and set the client state to reflect it
        // 
        if (this._collapsed != isCollapsed) {
            this._collapsed = isCollapsed;        
            this.raisePropertyChanged('Collapsed');
        }
        TripzoomLib.CollapsiblePanelBehavior.callBaseMethod(this, 'set_ClientState', [this._collapsed.toString()]);                        
    },
    
    _toggle : function(eventObj) {
        /// <summary>
        /// Event handler to epxand or collapse the panel (based on its current state)
        /// </summary>
        /// <param name="eventObj" type="Sys.UI.DomEvent" mayBeNull="true" optional="true">
        /// Event Info
        /// </param>

        if (this.get_Collapsed()) {
            return this._doOpen(eventObj);
        } else {
            return this._doClose(eventObj);
        }
    },

    add_collapseComplete : function(handler) {
        /// <summary>
        /// Add a handler to the collapseComplete event
        /// </summary>
        /// <param name="handler" type="Function">
        /// Handler
        /// </param>
    	this.get_events().addHandler('collapseComplete', handler);
    },
    remove_collapseComplete : function(handler) {
        /// <summary>
        /// Remove a handler from the collapseComplete event
        /// </summary>
        /// <param name="handler" type="Function">
        /// Handler
        /// </param>
    	this.get_events().removeHandler('collapseComplete', handler);
    },
    raiseCollapseComplete : function() {
        /// <summary>
        /// Raise the collapseComplete event
        /// </summary>
    	var handlers = this.get_events().getHandler('collapseComplete');
    	if (handlers) {
    		handlers(this, Sys.EventArgs.Empty);
    	}
    },
    
    add_expandComplete : function(handler) {
        /// <summary>
        /// Add a handler to the expandComplete event
        /// </summary>
        /// <param name="handler" type="Function">
        /// Handler
        /// </param>
    	this.get_events().addHandler('expandComplete', handler);
    },
    remove_expandComplete : function(handler) {
        /// <summary>
        /// Remove a handler from the expandComplete event
        /// </summary>
        /// <param name="handler" type="Function">
        /// Handler
        /// </param>
    	this.get_events().removeHandler('expandComplete', handler);
    },
    raiseExpandComplete : function() {
        /// <summary>
        /// Raise the expandComplete event
        /// </summary>
    	var handlers = this.get_events().getHandler('expandComplete');
    	if (handlers) {
    		handlers(this, Sys.EventArgs.Empty);
    	}
    },

    get_TargetHeight : function() {
        /// <value type="Number" integer="true">
        /// Wrap the height of the panel
        /// </value>
        return this.get_element().offsetHeight;        
    },
    set_TargetHeight : function(value) {        
        this.get_element().style.height = value + "px";        
        this.raisePropertyChanged('TargetHeight');
    },
    
    get_TargetWidth : function() {
        /// <value type="Number" integer="true">
        /// Wrap the width of the panel
        /// </value>
        return this.get_element().offsetWidth;        
    },
    set_TargetWidth : function(value) {
        this.get_element().style.width = value + "px"        
        this.raisePropertyChanged('TargetWidth');
    },
        
    get_Collapsed : function() {
        /// <value type="Boolean">
        /// Whether or not the panel is collapsed
        /// </value>
        return this._collapsed;        
    },    
    set_Collapsed : function(value) {
        // if we're changing values, and we're live, toggle.
        if (this.get_isInitialized() && this.get_element() && value != this.get_Collapsed()) {
            this._toggle();
        }
        else {
            this._collapsed = value;
            this.raisePropertyChanged('Collapsed');
        }
    },
    
    get_CollapsedSize : function() {
        /// <value type="Number" integer="true">
        /// The size of the target, in pixels, when it is in the collapsed state
        /// </value>
        return this._collapsedSize;
    },
    set_CollapsedSize : function(value) {
        if (this._collapsedSize != value) {
            this._collapsedSize = value;
            this.raisePropertyChanged('CollapsedSize');
        }
    },
    
    get_ExpandedSize : function() {
        /// <value type="Number" integer="true">
        /// The size of the target, in pixels, when it is in the expanded state
        /// </value>
        return this._expandedSize;
    },
    set_ExpandedSize : function(value) {
        if (this._expandedSize != value) {
            this._expandedSize = value;
            this.raisePropertyChanged('ExpandedSize');
        }
    },
    
    get_CollapseControlID : function() {
        /// <value type="String">
        /// ID of the control used to collapse the target when clicked
        /// </value>
        return this._collapseControlID;
    },
    set_CollapseControlID : function(value) {
        if (this._collapseControlID != value) {
            this._collapseControlID = value;
            this.raisePropertyChanged('CollapseControlID');
        }
    },
    
    get_ExpandControlID : function() {
        /// <value type="String">
        /// ID of the control used to expand the target when clicked
        /// </value>
        return this._expandControlID;
    },    
    set_ExpandControlID : function(value) {
        if (this._expandControlID != value) {
            this._expandControlID = value;
            this.raisePropertyChanged('ExpandControlID');
        }
    },
    
    get_ScrollContents : function() {
        /// <value type="Boolean">
        /// Whether to add a scrollbar when the contents are larger than the target (the contents will be clipped if false)
        /// </value>
        return this._scrollContents;
    },
    set_ScrollContents : function(value) {
        if (this._scrollContents != value) {
            this._scrollContents = value;
            this.raisePropertyChanged('ScrollContents');
        }
    },
    
    get_SuppressPostBack : function() {
        /// <value type="Boolean">
        /// Whether or not to suppress postbacks generated when the CollapseControlID or ExpandControlID elements are clicked
        /// </value>
        return this._suppressPostBack;
    },
    set_SuppressPostBack : function(value) {
        if (this._suppressPostBack != value) {
            this._suppressPostBack = value;
            this.raisePropertyChanged('SuppressPostBack');
        }
    },
    
    get_TextLabelID : function() {
        /// <value type="String">
        /// ID of the element where the "status text" for the target will be placed
        /// </value>
        return this._textLabelID;
    },
    set_TextLabelID : function(value) {
        if (this._textLabelID != value) {
            this._textLabelID = value;
            this.raisePropertyChanged('TextLabelID');
        }
    },
    
    get_ExpandedText : function() {
        /// <value type="String">
        /// Text to show in the element specified by TextLabelID when the target is expanded.  This text is also used as the alternate text of the image if ImageControlID has been provided.
        /// </value>
        return this._expandedText;
    },
    set_ExpandedText : function(value) {
        if (this._expandedText != value) {
            this._expandedText = value;
            this.raisePropertyChanged('ExpandedText');
        }
    },
    
    get_CollapsedText : function() {
        /// <value type="String">
        /// Text to show in the element specified by TextLabelID when the target is collapsed.  This text is also used as the alternate text of the image if ImageControlID has been provided.
        /// </value>
        return this._collapsedText;
    },
    set_CollapsedText : function(value) {
        if (this._collapsedText != value) {
            this._collapsedText = value;
            this.raisePropertyChanged('CollapsedText');
        }
    },
    
    get_ImageControlID : function() {
        /// <value type="String">
        /// ID of the <img> element where an icon indicating the collapsed status of the target will be placed
        /// </value>
        return this._imageControlID;
    },
    set_ImageControlID : function(value) {
        if (this._imageControlID != value) {
            this._imageControlID = value;
            this.raisePropertyChanged('ImageControlID');
        }
    },
    
    get_ExpandedImage : function() {
        /// <value type="String">
        /// Path to an image to show in the element specified by ImageControlID when the target is expanded
        /// </value>
        return this._expandedImage;
    },
    set_ExpandedImage : function(value) {
        if (this._expandedImage != value) {
            this._expandedImage = value;
            this.raisePropertyChanged('ExpandedImage');
        }
    },
    
    get_CollapsedImage : function() {
        /// <value type="String">
        /// Path to an image to show in the element specified by ImageControlID when the target is collapsed
        /// </value>
        return this._collapsedImage;
    },
    set_CollapsedImage : function(value) {
        if (this._collapsedImage != value) {
            this._collapsedImage = value;
            this.raisePropertyChanged('CollapsedImage');
        }
    },
    
    get_AutoExpand : function() {
        /// <value type="Boolean">
        /// Whether to automatically expand the target when the mouse is moved over it
        /// </value>
        return this._autoExpand;
    },
    set_AutoExpand : function(value) {
        if (this._autoExpand != value) {
            this._autoExpand = value;
            this.raisePropertyChanged('AutoExpand');
        }
    },
    
    get_AutoCollapse : function() {
        /// <value type="Boolean">
        /// Whether to automatically collapse the target when the mouse is moved off of it
        /// </value>
        return this._autoCollapse;
    },
    set_AutoCollapse : function(value) {
        if (this._autoCollapse != value) {
            this._autoCollapse = value;
            this.raisePropertyChanged('AutoCollapse');
        }
    },    
    
    get_ExpandDirection : function() {
        /// <value type="TripzoomLib.CollapsiblePanelExpandDirection">
        /// Direction the panel will expand and collapse (can be either "Vertical" or "Horizontal")
        /// </value>
        return this._expandDirection == TripzoomLib.CollapsiblePanelExpandDirection.Vertical;
    },      
    set_ExpandDirection : function(value) {
        if (this._expandDirection != value) {
            this._expandDirection = value;
            this.raisePropertyChanged('ExpandDirection');
        }
    }
}
TripzoomLib.CollapsiblePanelBehavior.registerClass('TripzoomLib.CollapsiblePanelBehavior', AjaxControlToolkit.BehaviorBase);
//    getDescriptor : function() {
//        var td = TripzoomLib.CollapsiblePanelBehavior.callBaseMethod(this, 'getDescriptor');
//        
//        // lots of properties to add here
//        //
//        td.addProperty('CollapsedSize', Number);        
//        td.addProperty('ExpandedSize', Number);        
//        td.addProperty('CollapseControlID', String);        
//        td.addProperty('ExpandControlID', String);        
//        td.addProperty('Collapsed', Boolean);
//        td.addProperty('ScrollContents', Boolean);
//        td.addProperty('SuppressPostBack', Boolean);
//        td.addProperty('AutoExpand', Boolean);        
//        td.addProperty('AutoCollapse', Boolean);        
//        td.addProperty('CollapsedText', String);
//        td.addProperty('ExpandedText', String);
//        td.addProperty('TextLabelID', String);
//        td.addProperty('CollapsedImage', String);
//        td.addProperty('ExpandedImage', String);
//        td.addProperty('ImageControlID', String);
//        td.addProperty('ExpandDirection', TripzoomLib.CollapsiblePanelExpandDirection);
//        
//        // these are for internal use
//        //
//        td.addProperty('TargetHeight', Number);
//        td.addProperty('TargetWidth', Number);
//        
//        // events
//        //
//        td.addEvent('collapseComplete', true);
//        td.addEvent('expandComplete', true);
//        
//        return td;
//    },
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx.
// All other rights reserved.


/// <reference name="MicrosoftAjax.debug.js" />
/// <reference name="MicrosoftAjaxTimer.debug.js" />
/// <reference name="MicrosoftAjaxWebForms.debug.js" />
/// <reference path="../ExtenderBase/BaseScripts.js" />
/// <reference path="../Common/Common.js" />
/// <reference path="../DynamicPopulate/DynamicPopulateBehavior.js" />


Type.registerNamespace("TripzoomLib");

TripzoomLib.ScrollBars = function() { }
TripzoomLib.ScrollBars.prototype = {
    None : 0x00,
    Horizontal : 0x01,
    Vertical : 0x02,
    Both : 0x03,
    Auto : 0x04
}
TripzoomLib.ScrollBars.registerEnum("TripzoomLib.ScrollBars", true);

TripzoomLib.TabContainer = function(element) {
	TripzoomLib.TabContainer.initializeBase(this, [element]);
	this._cachedActiveTabIndex = -1;
	this._activeTabIndex = -1;
	this._scrollBars = TripzoomLib.ScrollBars.None;
	this._tablines = null;
	this._tabs = null;
	this._header = null;
	this._body = null;
	this._loaded = false;
	this._autoPostBackId = null;
	this._tabscroller = null;
	this._resizeDelegate = null;
	this._app_onload$delegate = Function.createDelegate(this, this._app_onload);


}
TripzoomLib.TabContainer.prototype = {

	add_activeTabChanged: function(handler) {
		this.get_events().addHandler("activeTabChanged", handler);
	},
	remove_activeTabChanged: function(handler) {
		this.get_events().removeHandler("activeTabChanged", handler);
	},
	raiseActiveTabChanged: function() {
		var eh = this.get_events().getHandler("activeTabChanged");
		if (eh) {
			eh(this, Sys.EventArgs.Empty);
		}
		if (this._autoPostBackId) {
			__doPostBack(this._autoPostBackId, "activeTabChanged:" + this.get_activeTabIndex());
		}
	},

	get_activeTabIndex: function() {
		if (this._cachedActiveTabIndex > -1) {
			return this._cachedActiveTabIndex;
		}
		return this._activeTabIndex;
	},
	set_activeTabIndex: function(value) {
		if (!this.get_isInitialized()) {
			this._cachedActiveTabIndex = value;
		} else {

			if (value < -1 || value >= this.get_tabs().length) {
				throw Error.argumentOutOfRange("value");
			}
			if (this._activeTabIndex != -1) {
				this.get_tabs()[this._activeTabIndex]._set_active(false);
			}
			this._activeTabIndex = value;
			if (this._activeTabIndex != -1) {
				this.get_tabs()[this._activeTabIndex]._set_active(true);
			}
			if (this._loaded) {
				this.raiseActiveTabChanged();
			}
			this.raisePropertyChanged("activeTabIndex");
		}
	},

	get_tabs: function() {
		if (this._tabs == null) {
			this._tabs = [];
		}
		return this._tabs;
	},

	get_tablines: function() {
		if (this._tablines == null) {
			this._tablines = [];
		}
		return this._tablines;
	},

	get_activeTab: function() {
		if (this._activeTabIndex > -1) {
			return this.get_tabs()[this._activeTabIndex];
		}
		return null;
	},
	set_activeTab: function(value) {
		var i = Array.indexOf(this.get_tabs(), value);
		if (i == -1) {
			throw Error.argument("value", AjaxControlToolkit.Resources.Tabs_ActiveTabArgumentOutOfRange);
		}
		this.set_activeTabIndex(i);
	},

	get_autoPostBackId: function() {
		return this._autoPostBackId;
	},
	set_autoPostBackId: function(value) {
		this._autoPostBackId = value;
	},
	get_scrollBars: function() {
		return this._scrollBars;
	},
	set_scrollBars: function(value) {
		if (this._scrollBars != value) {
			this._scrollBars = value;
			this._invalidate();
			this.raisePropertyChanged("scrollBars");
		}
	},

	get_tabscroller: function() {
		return this._tabscroller;
	},
	set_tabscroller: function(value) {
		this._tabscroller = value;
	},

	get_header: function() {
		return this._header;
	},
	get_body: function() {
		return this._body;
	},

	initialize: function() {
		TripzoomLib.TabContainer.callBaseMethod(this, "initialize");

		//Sys.Debug.trace("TabContainer.initialize() : " + this.get_id());

		var elt = this.get_element();
		elt.style.position = "relative";
		var header = this._header = $get(this.get_id() + "_header");
		var body = this._body = $get(this.get_id() + "_body");

		// default classes
		$common.addCssClasses(elt, [
            "ajax__tab_container",
            "ajax__tab_default"
        ]);
		Sys.UI.DomElement.addCssClass(header, "ajax__tab_header");
		Sys.UI.DomElement.addCssClass(body, "ajax__tab_body");


		this._invalidate();

		if (!this._resizeDelegate)
			this._resizeDelegate = Function.createDelegate(this, this._raiseResize);
		$addHandler(window, "resize", this._resizeDelegate); 	  // ie resize event
		$addHandler(document.body, "resize", this._resizeDelegate);   // firefox resize event

		//run delegate function on Application Load event
		Sys.Application.add_load(this._app_onload$delegate);
	},

	dispose: function() {
		Sys.Application.remove_load(this._app_onload$delegate);
		TripzoomLib.TabContainer.callBaseMethod(this, "dispose");
	},

	getFirstTab: function(includeDisabled) {
		var tabs = this.get_tabs();
		for (var i = 0; i < tabs.length; i++) {
			if (includeDisabled || tabs[i].get_enabled()) {
				return tabs[i];
			}
		}
		return null;
	},

	/// <summary>Used in TabScroller</summary>
	getFirstVisibleTab: function(includeDisabled) {
		var tabs = this.get_tabs();
		for (var i = 0; i < tabs.length; i++) {
			if (tabs[i].get_visible() && (includeDisabled || tabs[i].get_enabled())) {
				return tabs[i];
			}
		}
		return null;
	},


	getLastTab: function(includeDisabled) {
		var tabs = this.get_tabs();
		for (var i = tabs.length - 1; i >= 0; i--) {
			if (includeDisabled || tabs[i].get_enabled()) {
				return tabs[i];
			}
		}
		return null;
	},

	getLastHiddenTab: function(includeDisabled) {
		/// <summary>Used in TabScroller</summary>
		var tabs = this.get_tabs();
		for (var i = tabs.length - 1; i >= 0; i--) {
			if (!tabs[i].get_visible() && (includeDisabled || tabs[i].get_enabled())) {
				return tabs[i];
			}
		}
		return null;
	},

	getNextTab: function(includeDisabled) {
		var tabs = this.get_tabs();
		var active = this.get_activeTabIndex();
		for (var i = 1; i < tabs.length; i++) {
			var tabIndex = (active + i) % tabs.length;
			var tab = tabs[tabIndex];
			if (includeDisabled || tab.get_enabled())
				return tab;
		}
		return null;
	},
	getPreviousTab: function(includeDisabled) {
		var tabs = this.get_tabs();
		var active = this.get_activeTabIndex();
		for (var i = 1; i < tabs.length; i++) {
			var tabIndex = (tabs.length + (active - i)) % tabs.length;
			var tab = tabs[tabIndex];
			if (includeDisabled || tab.get_enabled())
				return tab;
		}
		return null;
	},
	getNearestTab: function() {
		var prev = this.getPreviousTab(false);
		var next = this.getNextTab(false);
		if (prev && prev.get_tabIndex() < this._activeTabIndex) {
			return prev;
		} else if (next && next.get_tabIndex() > this._activeTabIndex) {
			return next;
		}
		return null;
	},
	saveClientState: function() {
		var tabs = this.get_tabs();
		var tabState = [];
		for (var i = 0; i < tabs.length; i++) {
			Array.add(tabState, tabs[i].get_enabled());
		}
		var state = {
			ActiveTabIndex: this._activeTabIndex,
			TabState: tabState
		};
		return Sys.Serialization.JavaScriptSerializer.serialize(state);
	},

	_invalidate: function() {
		if (this.get_isInitialized()) {
			$common.removeCssClasses(this._body, [
                "ajax__scroll_horiz",
                "ajax__scroll_vert",
                "ajax__scroll_both",
                "ajax__scroll_auto"
            ]);
			switch (this._scrollBars) {
				case TripzoomLib.ScrollBars.Horizontal:
					Sys.UI.DomElement.addCssClass(this._body, "ajax__scroll_horiz");
					break;
				case TripzoomLib.ScrollBars.Vertical:
					Sys.UI.DomElement.addCssClass(this._body, "ajax__scroll_vert");
					break;
				case TripzoomLib.ScrollBars.Both:
					Sys.UI.DomElement.addCssClass(this._body, "ajax__scroll_both");
					break;
				case TripzoomLib.ScrollBars.Auto:
					Sys.UI.DomElement.addCssClass(this._body, "ajax__scroll_auto");
					break;
			}

		}
	},

	_raiseResize: function(evt) {
		if (this.get_tabscroller()) {
			var tabs = this.get_tabs();
			for (var i = 0; i < tabs.length; i++) {
				var tab = tabs[i];
				if (tab) 
					tab.set_visible(true);
			}
			this._init_tabscroller();
		}
	},

	_init_tabscroller: function() {
		if (this.get_tabscroller()) {
			var bounds_body = Sys.UI.DomElement.getBounds(this.get_body());
			var bounds_tab = Sys.UI.DomElement.getBounds(this.getLastTab(false).get_headerTab());
			var max_x = bounds_body.x + bounds_body.width;
			this.get_tabscroller().set_visible((bounds_tab.x + bounds_tab.width >= max_x));
		}
	},

	_app_onload: function(sender, e) {
		if (this._cachedActiveTabIndex != -1) {
			this.set_activeTabIndex(this._cachedActiveTabIndex);
			this._cachedActiveTabIndex = -1;
		}

		this._init_tabscroller();
		this._loaded = true;
	}
}
TripzoomLib.TabContainer.registerClass("TripzoomLib.TabContainer", AjaxControlToolkit.ControlBase);




TripzoomLib.TabLine = function(element) {
	TripzoomLib.TabLine.initializeBase(this, [element]);
	this._owner = null;
	this._active = false;
	this._cachedActiveTabIndex = -1;
	this._activeTabIndex = -1;
	this._scrollBars = TripzoomLib.ScrollBars.None;
	this._tabs = null;
	this._tabLineIndex = -1;
};

TripzoomLib.TabLine.prototype = {

	get_owner: function() {
		return this._owner;
	},
	set_owner: function(value) {
		if (this._owner != value) {
			if (this.get_isInitialized()) {
				throw Error.invalidOperation(String.format(AjaxControlToolkit.Resources.Tabs_PropertySetAfterInitialization, 'owner'));
			}
			this._owner = value;
			this.raisePropertyChanged("owner");
		}
	},

	get_tabs: function() {
		if (this._tabs == null) {
			this._tabs = [];
		}
		return this._tabs;
	},

	get_active: function() {
		return this._active;
	},
	set_active: function(value) {
		this._active = value;
		if (value)
			this._activate();
		else
			this._deactivate();
	},

	_activate: function() {
		var lines = this.get_owner().get_tablines();
		for (var i = 0; i < lines.length; i++) {
			Sys.UI.DomElement.removeCssClass(lines[i].get_element(), "ajax__tabline_active");
		}


		var elt = this.get_element();
		$common.setVisible(elt, true);
		var parent = elt.parentNode;
		parent.removeChild(elt);
		parent.appendChild(elt);

		Sys.UI.DomElement.addCssClass(elt, "ajax__tabline_active");

	},

	_deactivate: function() {
		//Sys.Debug.trace("deactivate : " + this.get_element().id);
		var elt = this.get_element();


		$common.setVisible(elt, false);
	},

	initialize: function() {
		TripzoomLib.TabLine.callBaseMethod(this, "initialize");

		//Sys.Debug.trace("TripzoomLib.TabLine.initialize() : " + this.get_id());

		var owner = this.get_owner();
		if (!owner) {
			throw Error.invalidOperation(AjaxControlToolkit.Resources.Tabs_OwnerExpected);
		}

		this._tabLineIndex = owner.get_tablines().length;

		Array.add(owner.get_tablines(), this);

		var elt = this.get_element();
		Sys.UI.DomElement.addCssClass(elt, "ajax__tabline");

	},
	dispose: function() {
		TripzoomLib.TabLine.callBaseMethod(this, "dispose");
	}
};

TripzoomLib.TabLine.registerClass("TripzoomLib.TabLine", AjaxControlToolkit.ControlBase);




TripzoomLib.TabPanel = function(element) {
	TripzoomLib.TabPanel.initializeBase(this, [element]);
	this._active = false;
	this._tab = null;
	this._headerOuter = null;
	this._headerInner = null;
	this._header = null;
	this._owner = null;
	this._enabled = true;
	this._visible = true;
	this._tabIndex = -1;
	this._dynamicContextKey = null;
	this._dynamicServicePath = null;
	this._dynamicServiceMethod = null;
	this._dynamicPopulateBehavior = null;
	this._scrollBars = TripzoomLib.ScrollBars.None;
	this._header_onclick$delegate = Function.createDelegate(this, this._header_onclick);
	this._header_onmouseover$delegate = Function.createDelegate(this, this._header_onmouseover);
	this._header_onmouseout$delegate = Function.createDelegate(this, this._header_onmouseout);
	this._header_onmousedown$delegate = Function.createDelegate(this, this._header_onmousedown);
	this._dynamicPopulate_onpopulated$delegate = Function.createDelegate(this, this._dynamicPopulate_onpopulated);
	this._oncancel$delegate = Function.createDelegate(this, this._oncancel);
}
TripzoomLib.TabPanel.prototype = {

	add_click: function(handler) {
		this.get_events().addHandler("click", handler);
	},
	remove_click: function(handler) {
		this.get_events().removeHandler("click", handler);
	},
	raiseClick: function() {
		var eh = this.get_events().getHandler("click");
		if (eh) {
			eh(this, Sys.EventArgs.Empty);
		}
	},

	add_populating: function(handler) {
		this.get_events().addHandler("populating", handler);
	},
	remove_populating: function(handler) {
		this.get_events().removeHandler("populating", handler);
	},
	raisePopulating: function() {
		var eh = this.get_events().getHandler("populating");
		if (eh) {
			eh(this, Sys.EventArgs.Empty);
		}
	},

	add_populated: function(handler) {
		this.get_events().addHandler("populated", handler);
	},
	remove_populated: function(handler) {
		this.get_events().removeHandler("populated", handler);
	},
	raisePopulated: function() {
		var eh = this.get_events().getHandler("populated");
		if (eh) {
			eh(this, Sys.EventArgs.Empty);
		}
	},

	get_headerText: function() {
		if (this.get_isInitialized()) {
			return this._header.innerHTML;
		}
		return "";
	},
	set_headerText: function(value) {
		if (!this.get_isInitialized()) {
			throw Error.invalidOperation(String.format(AjaxControlToolkit.Resources.Tabs_PropertySetBeforeInitialization, 'headerText'));
		}
		if (this._headerText != value) {
			this._headerTab.innerHTML = value;
			this.raisePropertyChanged("headerText");
		}
	},

	get_headerTab: function() {
		return this._header;
	},
	set_headerTab: function(value) {
		if (this._header != value) {
			if (this.get_isInitialized()) {
				throw Error.invalidOperation(String.format(AjaxControlToolkit.Resources.Tabs_PropertySetAfterInitialization, 'headerTab'));
			}
			this._header = value;
			this.raisePropertyChanged("value");
		}
	},

	get_visible: function() {
		return this._visible;
	},
	set_visible: function(value) {
		if (value != this._visible) {
			this._visible = value;
			if (this.get_isInitialized()) {
				if (!this._visible) {
					this._hide();
				} else if (this._enabled) {
					this._show();
				}
			}
			this.raisePropertyChanged("visible");
		}
	},

	get_enabled: function() {
		return this._enabled;
	},
	set_enabled: function(value) {
		if (value != this._enabled) {
			this._enabled = value;
			if (this.get_isInitialized()) {
				if (!this._enabled) {
					this._hide();
				} else if (this._visible) {
					this._show();
				}
			}
			this.raisePropertyChanged("enabled");
		}
	},

	get_container: function() {
		return this._container;
	},
	set_container: function(value) {
		if (this._container != value) {
			if (this.get_isInitialized()) {
				throw Error.invalidOperation(String.format(AjaxControlToolkit.Resources.Tabs_PropertySetAfterInitialization, 'container'));
			}
			this._container = value;
			this.raisePropertyChanged("container");
		}
	},


	get_owner: function() {
		return this._owner;
	},
	set_owner: function(value) {
		if (this._owner != value) {
			if (this.get_isInitialized()) {
				throw Error.invalidOperation(String.format(AjaxControlToolkit.Resources.Tabs_PropertySetAfterInitialization, 'owner'));
			}
			this._owner = value;
			this.raisePropertyChanged("owner");
		}
	},

	get_scrollBars: function() {
		return this._scrollBars;
	},
	set_scrollBars: function(value) {
		if (this._scrollBars != value) {
			this._scrollBars = value;
			this.raisePropertyChanged("scrollBars");
		}
	},

	get_tabIndex: function() {
		return this._tabIndex;
	},

	get_dynamicContextKey: function() {
		return this._dynamicContextKey;
	},
	set_dynamicContextKey: function(value) {
		if (this._dynamicContextKey != value) {
			this._dynamicContextKey = value;
			this.raisePropertyChanged('dynamicContextKey');
		}
	},

	get_dynamicServicePath: function() {
		return this._dynamicServicePath;
	},
	set_dynamicServicePath: function(value) {
		if (this._dynamicServicePath != value) {
			this._dynamicServicePath = value;
			this.raisePropertyChanged('dynamicServicePath');
		}
	},

	get_dynamicServiceMethod: function() {
		return this._dynamicServiceMethod;
	},
	set_dynamicServiceMethod: function(value) {
		if (this._dynamicServiceMethod != value) {
			this._dynamicServiceMethod = value;
			this.raisePropertyChanged('dynamicServiceMethod');
		}
	},

	_get_active: function() {
		return this._active;
	},
	_set_active: function(value) {
		this._active = value;
		if (value)
			this._activate();
		else
			this._deactivate();
	},

	initialize: function() {
		TripzoomLib.TabPanel.callBaseMethod(this, "initialize");

		//Sys.Debug.trace("TripzoomLib.TabPanel.initialize() : " + this.get_id())

		var container = this.get_container();
		if (!container) {
			throw Error.invalidOperation(AjaxControlToolkit.Resources.Tabs_OwnerExpected);
		}

		this._tabIndex = container.get_tabs().length;

		Array.add(container.get_tabs(), this);

		this._headerOuterWrapper = document.createElement('span');
		this._headerInnerWrapper = document.createElement('span');
		this._tab = document.createElement('span');
		this._tab.id = this.get_id() + "_tab";
		this._header.parentNode.replaceChild(this._tab, this._header);
		this._tab.appendChild(this._headerOuterWrapper);
		this._headerOuterWrapper.appendChild(this._headerInnerWrapper);
		this._headerInnerWrapper.appendChild(this._header);
		$addHandlers(this._header, {
			click: this._header_onclick$delegate,
			mouseover: this._header_onmouseover$delegate,
			mouseout: this._header_onmouseout$delegate,
			mousedown: this._header_onmousedown$delegate,
			dragstart: this._oncancel$delegate,
			selectstart: this._oncancel$delegate,
			select: this._oncancel$delegate
		});
		Sys.UI.DomElement.addCssClass(this._headerOuterWrapper, "ajax__tab_outer");
		Sys.UI.DomElement.addCssClass(this._headerInnerWrapper, "ajax__tab_inner");
		Sys.UI.DomElement.addCssClass(this._header, "ajax__tab_tab");
		Sys.UI.DomElement.addCssClass(this.get_element(), "ajax__tab_panel");

		if (!this._enabled || !this._visible) {
			this._hide();
		}
	},

	dispose: function() {
		if (this._dynamicPopulateBehavior) {
			this._dynamicPopulateBehavior.dispose();
			this._dynamicPopulateBehavior = null;
		}
		$common.removeHandlers(this._header, {
			click: this._header_onclick$delegate,
			mouseover: this._header_onmouseover$delegate,
			mouseout: this._header_onmouseout$delegate,
			mousedown: this._header_onmousedown$delegate,
			dragstart: this._oncancel$delegate,
			selectstart: this._oncancel$delegate,
			select: this._oncancel$delegate
		});
		TripzoomLib.TabPanel.callBaseMethod(this, "dispose");
	},

	populate: function(contextKeyOverride) {
		if (this._dynamicPopulateBehavior && (this._dynamicPopulateBehavior.get_element() != this.get_element())) {
			this._dynamicPopulateBehavior.dispose();
			this._dynamicPopulateBehavior = null;
		}
		if (!this._dynamicPopulateBehavior && this._dynamicServiceMethod) {
			this._dynamicPopulateBehavior = $create(AjaxControlToolkit.DynamicPopulateBehavior, { "ContextKey": this._dynamicContextKey, "ServicePath": this._dynamicServicePath, "ServiceMethod": this._dynamicServiceMethod }, { "populated": this._dynamicPopulate_onpopulated$delegate }, null, this.get_element());
		}
		if (this._dynamicPopulateBehavior) {
			this.raisePopulating();
			this._dynamicPopulateBehavior.populate(contextKeyOverride ? contextKeyOverride : this._dynamicContextKey);
		}
	},

	_activate: function() {
		var elt = this.get_element();
		$common.setVisible(elt, true);
		Sys.UI.DomElement.addCssClass(this._tab, "ajax__tab_active");

		this.get_owner().set_active(true);

		this.populate();

		this._show();

		this._container.get_element().style.visibility = 'visible';
	},
	_deactivate: function() {
		var elt = this.get_element();
		$common.setVisible(elt, false);
		Sys.UI.DomElement.removeCssClass(this._tab, "ajax__tab_active");
	},
	_show: function() {
		this._tab.style.display = '';
	},
	_hide: function() {
		this._tab.style.display = 'none';
		if (this.get_visible()) {
			if (this._get_active()) {
				var next = this._container.getNearestTab(false);
				if (!!next) {
					this._container.set_activeTab(next);
				}
			}
			this._deactivate();
		}
	},
	_header_onclick: function(e) {
		this.raiseClick();
		this.get_container().set_activeTab(this);
	},
	_header_onmouseover: function(e) {
		Sys.UI.DomElement.addCssClass(this._tab, "ajax__tab_hover");
	},
	_header_onmouseout: function(e) {
		Sys.UI.DomElement.removeCssClass(this._tab, "ajax__tab_hover");
	},
	_header_onmousedown: function(e) {
		e.preventDefault();
	},
	_oncancel: function(e) {
		e.stopPropagation();
		e.preventDefault();
	},
	_dynamicPopulate_onpopulated: function(sender, e) {
		this.raisePopulated();
	}
}
TripzoomLib.TabPanel.registerClass("TripzoomLib.TabPanel", Sys.UI.Control);

Type.registerNamespace("TripzoomLib");

TripzoomLib.TabScrollDirection = function() { };
TripzoomLib.TabScrollDirection.prototype = {
	Left : 0x00,
	Right : 0x01
};

TripzoomLib.TabScrollDirection.registerEnum("TripzoomLib.TabScrollDirection", false);

TripzoomLib.TabScroller = function(element) {
	TripzoomLib.TabScroller.initializeBase(this, [element]);

	this._visible = false;
	this._container = null;

	this._scrollLeft = null;
	this._scrollRight = null;

	this._scrollLeftDelegate = null;
	this._scrollRightDelegate = null;

	this._scrollLeftMouseOverDelegate = null;
	this._scrollLeftMouseOutDelegate = null;
	
	this._scrollRightMouseOverDelegate = null;
	this._scrollRightMouseOutDelegate = null;
}

TripzoomLib.TabScroller.prototype = {
	initialize: function() {
		TripzoomLib.TabScroller.callBaseMethod(this, "initialize");

		//Sys.Debug.trace("TripzoomLib.TabScroller.initialize()");

		var elt = this.get_element();

		elt.className = "ajax__tabscroller";
		this._scrollLeft = document.createElement("div");
		this._scrollLeft.className = "ajax__tabscroller_left";
		elt.appendChild(this._scrollLeft);

		this._scrollRight = document.createElement("div");
		this._scrollRight.className = "ajax__tabscroller_right";
		elt.appendChild(this._scrollRight);



		if (!this._scrollLeftDelegate) {
			this._scrollLeftDelegate = Function.createDelegate(this, this._raiseScrollLeft);
		}
		$addHandler(this._scrollLeft, "click", this._scrollLeftDelegate);


		if (!this._scrollLeftMouseOverDelegate) {
			this._scrollLeftMouseOverDelegate = Function.createDelegate(this, this._raiseScrollLeftMouseOver);
		}
		$addHandler(this._scrollLeft, "mouseover", this._scrollLeftMouseOverDelegate);

		if (!this._scrollLeftMouseOutDelegate) {
			this._scrollLeftMouseOutDelegate = Function.createDelegate(this, this._raiseScrollLeftMouseOut);
		}
		$addHandler(this._scrollLeft, "mouseout", this._scrollLeftMouseOutDelegate);


		if (!this._scrollRightDelegate) {
			this._scrollRightDelegate = Function.createDelegate(this, this._raiseScrollRight);
		}
		$addHandler(this._scrollRight, "click", this._scrollRightDelegate);


		if (!this._scrollRightMouseOverDelegate) {
			this._scrollRightMouseOverDelegate = Function.createDelegate(this, this._raiseScrollRightMouseOver);
		}
		$addHandler(this._scrollRight, "mouseover", this._scrollRightMouseOverDelegate);

		if (!this._scrollRightMouseOutDelegate) {
			this._scrollRightMouseOutDelegate = Function.createDelegate(this, this._raiseScrollRightMouseOut);
		}
		$addHandler(this._scrollRight, "mouseout", this._scrollRightMouseOutDelegate);




		if (!this._visible) {
			this._hide();
		}
	},

	dispose: function() {
		TripzoomLib.TabScroller.callBaseMethod(this, "dispose");

		$clearHandlers(this._scrollLeft);
		$clearHandlers(this._scrollRight);


	
	},


	_raiseScrollLeftMouseOver: function(evt) {
		this._scrollLeft.className = "ajax__tabscroller_left_over";
	},

	_raiseScrollLeftMouseOut: function(evt) {
		this._scrollLeft.className = "ajax__tabscroller_left";
	},

	_raiseScrollRightMouseOver: function(evt) {
		this._scrollRight.className = "ajax__tabscroller_right_over";
	},

	_raiseScrollRightMouseOut: function(evt) {
		this._scrollRight.className = "ajax__tabscroller_right";
	},


	_raiseScrollRight: function(evt) {
		var tab = this._container.getLastHiddenTab(false);
		if (tab) {
			tab.set_visible(true);
		} 
	},


	_raiseScrollLeft: function(evt) {
		var tab = this._container.getFirstVisibleTab(false);
		if (tab) {
			tab.set_visible(false);
		}
	},

	get_container: function() {
		return this._container;
	},
	set_container: function(value) {
		this._container = value;
	},
	get_visible: function() {
		return this._visible;
	},

	set_visible: function(value) {
		if (this._visible != value) {
			this._visible = value;
			if (this._visible) {
				this._show();
			} else {
				this._hide();
			}
		}
	},

	_show: function() {
		this.get_element().style.display = '';
	},
	_hide: function() {
		this.get_element().style.display = 'none';
	}

};

TripzoomLib.TabScroller.registerClass("TripzoomLib.TabScroller", Sys.UI.Control);

ERROR_NO_ADDRESS_FOUND = "no_address_found";
WEBSERVICE_TIMEOUT = 30000;
MAXSEARCHRESULTS = 5;

var g_Status = 'OK';


Type.registerNamespace('TripzoomLib');

TripzoomLib.AddressBookBehavior = function(element) {
	TripzoomLib.AddressBookBehavior.initializeBase(this, [element]);
	this._AddressFormFocusObject = null;
	this._AddressNewButtonIDValue = null;
	this._AddressSearchButtonIDValue = null;
	this._AddressEditButtonIDValue = null;
	this._AddressEditCancelButtonIDValue = null;
	this._AddressDeleteButtonIDValue = null;
	this._AddressSelectButtonIDValue = null;
	this._AddressFormControlIDValue = null;
	this._AddressBookItemControlIDValue = null;
	this._AddressBookItemEditControlIDValue = null;
	this._AddressFormStreetText = null;
	this._AddressFormPotcodeText = null;
	this._AddressFormCityText = null;
	this._AddressFormCountrySelect = null;
	this._AddressFormFuzzyLinkCheck = null;
	this._xLocateServicePath = null;
	this._CookieName = null;
	this._cookie = null;
	this._TwoLetterISOLanguageName = "nl";
	this._isEditing = false;
	this._AddressBook = null;
	this._MaxSearchResults = 5;
	this._currentCallBackFunction = null;
	this._DoAppendNewAddress = false;
	this._AlwaysShowAddressForm = true;
	this._Collapsed = true;
	this._ExpandLastSaved = false;
	this._isDragging = false;
	this._MaxSavedItems = 0;
	this._HasDraggableItems = true;
	this._activeitem = null;
	this._AddressBookItemClickedHandler = Function.createDelegate(this, this._onAddressBookItemClicked);
};

TripzoomLib.AddressBookBehavior.prototype = {
	initialize: function() {
		TripzoomLib.AddressBookBehavior.callBaseMethod(this, 'initialize');

		control = $get(this._AddressBookItemControlIDValue);
		control.style.display = 'none';

		control = $get(this._AddressBookItemEditControlIDValue);
		control.style.display = 'none';

		control = $get(this._AddressFormControlIDValue);
		control.style.display = 'none';

		$addHandler(control, 'mousedown', function(evt) { evt.stopPropagation(); return false; });

		control = $get(this._AddressNewButtonIDValue);
		if (control)
			$addHandler(control, 'click', Function.createDelegate(this, this._onAddressNewButtonClicked));

		control = $get(this._AddressSearchButtonIDValue);
		if (control)
			$addHandler(control, 'click', Function.createDelegate(this, this._onAddressSearchButtonClicked));

		control = $get(this._AddressEditCancelButtonIDValue);
		if (control)
			$addHandler(control, 'click', Function.createDelegate(this, this._onAddressEditCancelButtonClicked));

		control = $get(this._AddressEditButtonIDValue);
		if (control)
			$addHandler(control, 'click', Function.createDelegate(this, this._onAddressEditButtonClicked));

		control = $get(this._AddressDeleteButtonIDValue);
		if (control)
			$addHandler(control, 'click', Function.createDelegate(this, this._onAddressDeleteButtonClicked));

		control = $get(this._AddressSelectButtonIDValue);
		if (control)
			$addHandler(control, 'click', Function.createDelegate(this, this._onAddressSelectButtonClicked));



		/* create ADDRESSBOOK root element  */
		this._AddressBook = this.get_element().appendChild(document.createElement("UL"));
		this._AddressBook.className = "AddressBook";
		this._AddressBook.position = 'relative';
		this._AddressBook.attributes.setNamedItem(document.createAttribute("activeid"));


		if (this.get_HasDraggableItems()) {
			$create(TripzoomLib.DropWatcherAddressBookBehavior, { "AddressBook": this }, null, null, this.get_element());
		}

		/* voeg resultaat toe aan cookie */
		if (this.get_CookieName() && this.get_CookieName() != "") {
			this._cookie = new TripzoomLib.Cookie();
			this._cookie.initialize();

			this.LoadAddressBook();
		} else {
			if (!this.get_Collapsed()) {
				this._onAddressNewButtonClicked();
			}
			this._raiseLoadReady();
		}

	},


	/*
	<summary>Public property to fetch any available address</summary>
	*/
	FetchActiveAddress: function(functionCallBack) {

		if (functionCallBack) {
			this._currentCallBackFunction = functionCallBack;
		}
		if (this._activeitem != null && this._isEditing) {
			/* if an address is being edited first do a geocode lookup */
			this._onAddressSearchButtonClicked();
		} else {
			var items = this._AddressBook.getElementsByTagName("LI");
			var collection = [];

			if (items) {
				for (var i = 0; i < items.length; i++) {
					if (items[i].attributes["address"] && items[i].attributes["address"].value != "")
						Array.add(collection, items[i].attributes["address"].value);
				}
			}
			this._currentCallBackFunction(this, ((this._activeitem) ? this._activeitem.attributes["address"].value : null), collection);
			this._currentCallBackFunction = null;
		}
		//		} else if (!DontSearch) {
		//			this._onAddressSearchButtonClicked();
		//		}
	},

	/*
	<summary>Callback function for populating the AddressBook with cookie saved items. Invoked at initialisation</summary>
	*/
	LoadAddressBook: function() {

		var data = this._cookie.getCookieData(this.get_CookieName());

		var addressList = [];
		if (data && data.length > 0) {
			addressList = data.split('|');
		}

		if (addressList.length > 0) {
			/* popuplate addressbook with saved items */
			addressList.reverse();
			for (var i = 0; i < addressList.length; i++) { // create all addresses
				if (addressList[i] != "") {

					var item = document.createElement("LI");
					var itemValue = document.createAttribute("address");
					itemValue.value = addressList[i];
					item.attributes.setNamedItem(itemValue);

					this._AddressBook.appendChild(item);

					this._AddAddressControl(item);

					/* add readable address content	*/
					var addressDescr = item.getElementsByTagName("ADDRESS");
					if (addressDescr) {
						this._internalDisableSelection(addressDescr[0]);

						var address = new TripzoomLib.Element.Address(addressList[i]);
						addressDescr[0].innerHTML = address.HTML();

						// load default map
						//this._raiseShowMap(addressList[i]);		
					}
				}
			}

			items = this._AddressBook.getElementsByTagName("LI");
			this._activeitem = items[0];
			if (this.get_Collapsed()) {
				if (this.get_ExpandLastSaved()) {
					this._onAddressEditButtonClicked(null);
				} else {
					this._OpenEditControl(this._activeitem);
				}
			} else {
				this._onAddressNewButtonClicked();
			}


		} else {
			this._onAddressNewButtonClicked();
		}


		this._raiseLoadReady();
	},


	add_LoadReady: function(handler) {
		this.get_events().addHandler("LoadReady", handler);
	},
	remove_LoadReady: function(handler) {
		this.get_events().removeHandler("LoadReady", handler);
	},

	_raiseLoadReady: function() {
		handler = this.get_events().getHandler("LoadReady");
		if (handler) {
			handler(this, Sys.EventArgs.Empty);
		}
	},


	/*
	<summary>EventHandler for click on buttoncontrol with id AddressNewButtonID</summary>
	*/
	_onAddressNewButtonClicked: function() {
		if (this._activeitem != null) {
			this._onAddressEditCancelButtonClicked();
			this._CloseEditControl();
			this._activeitem = null;
		}

		/* aanmaken nieuwe addressbookitem als ie al niet bestaat */
		this._activeitem = document.createElement("LI");
		var itemValue = document.createAttribute("address");
		itemValue.value = "";
		this._activeitem.attributes.setNamedItem(itemValue);


		if (this.get_DoAppendNewAddress()) {
			this._AddressBook.appendChild(this._activeitem);
		} else {
			/* voeg toe aan AddressBookControlID bovenaan */
			if (this._AddressBook.hasChildNodes()) {
				var firstaddressbookitem = this._AddressBook.firstChild;
				this._AddressBook.insertBefore(this._activeitem, firstaddressbookitem);
			} else {
				this._AddressBook.appendChild(this._activeitem);
			}


		}

		/* verplaatst de AddressFormControlID naar dit AddressBookItem */
		this._OpenSearchControl(this._activeitem);
	},

	/* 
	<summary>Callback function invoked by xLocateService</summary>
	*/
	_AddressSearchSucceededCallback: function(result, eventArgs) {
		if (!result || result.length == 0) {  // geen adres gevonden
			eventArgs._raiseError(ERROR_NO_ADDRESS_FOUND);
			return;
		} else if (result.length > 1) {
			eventArgs._raiseAddressSearch(result);
		} else if (result.length == 1) {
			if (eventArgs._currentCallBackFunction) {
				eventArgs.AddAddressBookItem(result[0].Address);
				var items = eventArgs._AddressBook.getElementsByTagName("LI");
				var collection = [];

				if (items) {
					for (var i = 0; i < items.length; i++) {
						if (items[i].attributes["address"] && items[i].attributes["address"].value != "")
							Array.add(collection, items[i].attributes["address"].value);
					}
				}
				eventArgs._currentCallBackFunction(eventArgs, result[0].Address, collection);
				eventArgs._currentCallBackFunction = null;
			} else {
				eventArgs._raiseAddressSearch(result);
			}
		}


	},


	FindAddressBookItemByAddress: function(address) {
		/// <summary>
		///	Searches the list of addressbookitems for the given address based on its position, and returns the LI-element or else NULL
		///</summary>	
		var retVal = null;

		addressArray = address.split("_");
		positionStr = addressArray[0] + "_" + addressArray[1];

		items = this._AddressBook.getElementsByTagName("LI");

		if (items) {
			for (var i = 0; i < items.length; i++) {
				if (items[i].attributes["address"] && items[i].attributes["address"].value != "") {
					if (items[i].attributes["address"].value.indexOf(positionStr) != -1) {
						retVal = items[i];
						break;
					}
				}
			}
		}
		return retVal;
	},


	/*
	<summary>Adds an address to the addressbook. If address position already exists it only activated this addressbookitem</summary>
	*/
	AddAddressBookItem: function(address, doShowMap) {

		this._CloseSearchControl();
		this._CloseEditControl();

		control = $get(this._AddressFormFuzzyLinkCheck);
		if (control) {
			if (control.checked) {
				address += "#FUZZY_LINKING";
			}
		}

		this._activeitem.attributes["address"].value = address;

		this._AddAddressControl(this._activeitem);

		var addressDescr = this._activeitem.getElementsByTagName("ADDRESS");
		if (addressDescr) {
			var addressObj = new TripzoomLib.Element.Address(address);
			addressDescr[0].innerHTML = addressObj.HTML();
		}


		/* voeg resultaat toe aan cookie */
		if (this.get_CookieName() && this.get_CookieName() != "") {
			this._cookie.setCookieData(this.get_CookieName(), address);
		}

		this._OpenEditControl(this._activeitem);
		if (doShowMap) {
			this._raiseShowMap(this._activeitem.attributes["address"].value);
		}

	},


	/* <summary>Hides or Shows the list of addressbookitems</summary> */
	Show: function(doShow) {
		if (doShow) {
			this._AddressBook.style.display = 'block';
		} else {
			this._AddressBook.style.display = 'none';
		}

	},

	/* <summary>Show the result of the search in a new addresbookitem</summary> */
	_ShowAddressSearchResult: function(activeitem, result) {

		if (null != this._activeitem) {
			for (var i = 0; i < activeitem.childNodes.length; i++) {
				child = activeitem.childNodes[i];
				child.style.display = 'block';
			}
		} else {
			this._AddAddressControl(activeitem);
		}

		var addressDescr = activeitem.getElementsByTagName("ADDRESS");
		if (addressDescr) {
			var address = new TripzoomLib.Element.Address(result);
			addressDescr[0].innerHTML = address.HTML();
		}


		/* fuzzy link appears in a via address  */
		control = $get(this._AddressFormFuzzyLinkCheck);
		if (control) {
			if (control.checked) {
				result += "#FUZZY_LINKING";
			}
		}

		activeitem.attributes["address"].value = result;

		this._isEditing = false;


		/* voeg resultaat toe aan cookie */
		if (this.get_CookieName() && this.get_CookieName() != "") {
			this._cookie.setCookieData(this.get_CookieName(), result);



		}

		/* voeg de referentie naar het AddressBookItemEditControl toe aan het huidige AddressBookItem */
		this._OpenEditControl(activeitem);

		if (this._currentCallBackFunction) {
			this._currentCallBackFunction(this, result);
			this._currentCallBackFunction = null;
		} else {
			this._raiseShowMap(activeitem.attributes["address"].value);
		}

	},

	/*
	<summary> callback er ging iets mis bij het aanroepen van de xLocateService </summmary>
	*/
	_AddressSearchFailedCallback: function(error, eventArgs) {
		//Sys.Debug.fail("_AddressSearchFailedCallback");
		eventArgs._raiseError(error);
	},


	/* 
	<summary>EventHandler for click on buttoncontrol with id AddressEditButtonID</summary>
	*/
	_onAddressSearchButtonClicked: function(eventArgs) {
	
		var street = "", postcode = "", city = "", country = "";

		control = $get(this._AddressFormStreetText);
		if (control)
			street = control.value;

		control = $get(this._AddressFormCityText);
		if (control)
			city = control.value;

		control = $get(this._AddressFormPostcodeText);
		if (control)
			postcode = control.value;

		control = $get(this._AddressFormCountrySelect);
		if (control)
			country = control.options[control.selectedIndex].value;


		var webRequest = Sys.Net.WebServiceProxy.invoke(this._xLocateServicePath, "Search", false,
        { "street": street, "postcode": postcode, "city": city, "country": country, "maxresults": this.get_MaxSearchResults(), "TwoLetterISOLanguageName": this.get_TwoLetterISOLanguageName() }
		, this._AddressSearchSucceededCallback, this._AddressSearchFailedCallback, this, WEBSERVICE_TIMEOUT);
	},

	/* 
	<summary>EventHandler for click on buttoncontrol with id AddressEditButtonID</summary>
	*/
	_onAddressEditButtonClicked: function(eventArgs) {
		for (var i = 0; i < this._activeitem.childNodes.length; i++) {
			child = this._activeitem.childNodes[i];
			child.style.display = 'none';
		}
		this._CloseEditControl();
		this._OpenSearchControl(this._activeitem);

		if (!eventArgs) {
			if (window.event) {
				window.event.cancelBubble = true;
			}
		} else {
			eventArgs.stopPropagation();
		}

		return false;
	},


	/* 
	<summary>Voor internal usage. Search in this addressbook for the index of an address</summary>
	*/
	_getAddressBookItemIndex: function(item) {
		var items = this.get_element().getElementsByTagName("LI");
		if (items) {
			for (var i = 0; i < items.length; i++) {
				if (items[i] == item) {
					return i;
				}
			}
		}
		return -1;
	},

	/* 
	<summary>EventHandler for click on buttoncontrol with id AddressEditButtonID</summary>
	*/
	_onAddressEditCancelButtonClicked: function(eventArgs) {
		this._CloseSearchControl();

		if (!this._activeitem) {
			return;
		}

		if (this._activeitem.attributes["address"].value != "") {
			for (var i = 0; i < this._activeitem.childNodes.length; i++) {
				child = this._activeitem.childNodes[i];
				child.style.display = 'block';
			}
			this._OpenEditControl(this._activeitem);
		} else {
			this._activeitem.parentNode.removeChild(this._activeitem);
			this._activeitem = null;
			if (this._AddressBook.hasChildNodes()) {
				this._activeitem = this._AddressBook.firstChild;
				this._OpenEditControl(this._activeitem);
			}
		}
	},


	/* <summary>Eventhandler is invoked when the Delete button is clicked</summary> */
	_onAddressDeleteButtonClicked: function(eventArgs) {
		this._CloseEditControl();
		/*  voeg resultaat toe aan cookie */
		if (this.get_CookieName() && this.get_CookieName() != "") {
			this._cookie.delCookieData(this.get_CookieName());
		}


		this._activeitem.parentNode.removeChild(this._activeitem);
		this._activeitem = null;

		if (this._AddressBook.hasChildNodes()) {
			this._activeitem = this._AddressBook.firstChild;
			this._OpenEditControl(this._activeitem);
		} else if (this.get_AlwaysShowAddressForm()) {
			this._onAddressNewButtonClicked();
		}

		if (!eventArgs)
			window.event.cancelBubble = true;
		else
			eventArgs.stopPropagation();

		return false;
	},


	/* 
	<summary>Evenhandler for ShowMap button</summary>
	*/
	_onAddressSelectButtonClicked: function(eventArgs) {
		this._raiseShowMap(this._activeitem.attributes["address"].value);
		if (!eventArgs)
			window.event.cancelBubble = true;
		else
			eventArgs.stopPropagation();

	},


	/* 
	<summary>EventHandler for click on control with AddressBookItemControlID to activate the addressbookitem</summary>    
	*/
	_onAddressBookItemClicked: function(eventArgs) {

		if (eventArgs.target && eventArgs.target.tagName == "ADDRESS") {
			this._raiseChange();

			this._onAddressEditCancelButtonClicked(null);

			// zoek het aangeklikte addressbookitem
			element = eventArgs.target;
			if (element) {
				var parent = element.parentNode;
				while (parent) {
					if (parent.tagName.toUpperCase() == "LI") {
						this._activeitem = parent;
						break;
					}
					parent = parent.parentNode;
				}
			}

			if (this._activeitem) {
				this._OpenEditControl(this._activeitem);
			}
		}

	},


	/* 
	<summary>Appends a clone of the AddressBookItemControl to the activeitem</summary>
	*/
	_AddAddressControl: function(activeitem) {

		/* clear contents of activeitem */
		activeitem.innerHTML = '';

		var addressbookitem = $get(this._AddressBookItemControlIDValue);
		addressbookitem = addressbookitem.cloneNode(true);

		addressbookitem.style.display = 'block';
		activeitem.appendChild(addressbookitem);
		$addHandler(activeitem, 'click', this._AddressBookItemClickedHandler);

		if (this.get_HasDraggableItems())
			$create(TripzoomLib.DraggableAddressBookItemBehavior, { "handle": activeitem.firstChild, "AddressBook": this }, null, null, activeitem);
	},

	_onAddressBookItemMouseMove: function(eventArgs) {
		if (eventArgs.get_IsDragging()) {
			window.status = eventArgs.x;
		}
	},

	_onAddressBookItemMouseDown: function(eventArgs) {

		eventArgs._raiseChange();


		eventArgs.set_IsDragging(true);

	},

	set_IsDragging: function(value) {
		this._isDragging = value;
	},

	get_IsDragging: function() {
		return this._isDragging;
	},

	_SetSelectedValue: function(selectObj, value) {
		for (var i = 0; i < selectObj.options.length; i++) {
			if (selectObj.options[i].value == value) {
				selectObj.options[i].selected = true;
			}
		}
	},

	/*
	<summary>Shows the Search control at AddressBookItem</summary>
	*/
	_OpenSearchControl: function(activeitem) {

		var address = new TripzoomLib.Element.Address(activeitem.attributes["address"].value);

		control = $get(this._AddressFormStreetText);
		if (control)
			control.value = address.Street;

		control = $get(this._AddressFormPostcodeText);
		if (control) {
			control.value = address.Postcode;
		}

		control = $get(this._AddressFormCityText);
		if (control)
			control.value = address.City;

		control = $get(this._AddressFormCountrySelect);
		if (control)
			this._SetSelectedValue(control, address.Country);

		control = $get(this._AddressFormFuzzyLinkCheck);
		if (control) {
			control.checked = (address.LinkType == "FUZZY_LINKING");
		}

		var cancelBtn = $get(this._AddressEditCancelButtonIDValue);
		if (cancelBtn) {
			cancelBtn.style.display = 'inline';
			var items = this.get_element().getElementsByTagName("LI");
			if (items.length == 1 && this._activeitem.attributes["address"].value.length == 0) {
				cancelBtn.style.display = 'none';
			}
		}

		addressitemformcontrol = $get(this._AddressFormControlIDValue);
		addressitemformcontrol.style.display = 'block';
		activeitem.appendChild(addressitemformcontrol);


		control = $get(this._AddressFormFocusObject);
		if (control) {
			control.focus();
		}

		this._isEditing = true;
	},



	/*
	<summary>Moves the address search control to the root</summary>
	*/
	_CloseSearchControl: function() {

		var addressformcontrol = $get(this._AddressFormControlIDValue);
		if (addressformcontrol) {
			this.get_element().appendChild(addressformcontrol);
			addressformcontrol.style.display = 'none';
		}

		this._isEditing = false;
	},

	/*
	<summary>Shows the Edit control at AddressBookItem</summary>
	<description>Activates the Addresbookitem (>bewerk >verwijder >kaart)</description>
	*/
	_OpenEditControl: function(activeitem) {

		if (!activeitem) {
			throw Error.argumentNull("activeitem", "activeitem may be null");
		}
		this._activeitem = activeitem;

		var addressbookitemeditcontrol = $get(this._AddressBookItemEditControlIDValue);

		if (!addressbookitemeditcontrol)
			throw Error.invalidOperation("addressbookitemeditcontrol may not be null");

		for (var i = 0; i < activeitem.childNodes.length; i++) {
			if (activeitem.childNodes[i] == addressbookitemeditcontrol) { // activeitem was al actief
				return;
			}
		}

		this._CloseSearchControl();

		/* wijzig className van _Active naar default */
		if (addressbookitemeditcontrol.parentNode.tagName.toUpperCase() == "LI") {
			var elems = addressbookitemeditcontrol.parentNode.getElementsByTagName("DIV");
			for (var i = 0; i < elems.length; i++) {
				elems[i].className = elems[i].className.replace(/_Active/, '');
			}
		}


		if (activeitem) {
			var elems = activeitem.getElementsByTagName("DIV");
			for (var i = 0; i < elems.length; i++) {
				if (!elems[i].className.endsWith("_Active")) {
					elems[i].className = elems[i].className + "_Active";
				}
			}
		}



		addressbookitemeditcontrol.style.display = 'block';
		activeitem.appendChild(addressbookitemeditcontrol);

	},

	/*
	<summary>Moves the edit control to the root</summary>
	*/
	_CloseEditControl: function() {


		var addressbookitemeditcontrol = $get(this._AddressBookItemEditControlIDValue);

		if (!addressbookitemeditcontrol) {
			throw Error.invalidOperation("addressbookitemeditcontrol may not be null");
		}


		addressbookitemeditcontrol.style.display = 'none';

		/* zet classNames op non active */
		if (addressbookitemeditcontrol.parentNode.tagName.toUpperCase() == "LI") {
			var elems = addressbookitemeditcontrol.parentNode.getElementsByTagName("DIV");
			for (var i = 0; i < elems.length; i++) {
				elems[i].className = elems[i].className.replace(/_Active/, '');
			}
		}

		/* verplaats editcontrol */
		this.get_element().appendChild(addressbookitemeditcontrol);

	},

	_internalDisableSelection: function(target) {

		if (typeof target.onselectstart != "undefined") //IE route
			target.onselectstart = function() { return false; }
		else if (typeof target.style.MozUserSelect != "undefined") //Firefox route
			target.style.MozUserSelect = "none";
		else /* All other route (ie: Opera) */
			target.onmousedown = function() { return false; }
	},

	get_ActiveAddress: function() { 
		return (this._activeitem) ? this._activeitem.attributes["address"].value : null;
	}, 

	get_AddressNewButtonID: function() {
		return this._AddressNewButtonIDValue;
	},

	set_AddressNewButtonID: function(value) {
		this._AddressNewButtonIDValue = value;
	},

	get_AddressSearchButtonID: function() {
		return this._AddressSearchButtonIDValue;
	},

	set_AddressSearchButtonID: function(value) {
		this._AddressSearchButtonIDValue = value;
	},

	get_AddressEditCancelButtonID: function() {
		return this._AddressEditCancelButtonIDValue;
	},

	set_AddressEditCancelButtonID: function(value) {
		this._AddressEditCancelButtonIDValue = value;
	},

	get_AddressEditButtonID: function() {
		return this._AddressEditButtonIDValue;
	},

	set_AddressEditButtonID: function(value) {
		this._AddressEditButtonIDValue = value;
	},

	get_AddressDeleteButtonID: function() {
		return this._AddressDeleteButtonIDValue;
	},

	set_AddressDeleteButtonID: function(value) {
		this._AddressDeleteButtonIDValue = value;
	},

	get_AddressSelectButtonID: function() {
		return this._AddressSelectButtonIDValue;
	},

	set_AddressSelectButtonID: function(value) {
		this._AddressSelectButtonIDValue = value;
	},

	get_AddressBookItemControlID: function() {
		return this._AddressBookItemControlIDValue;
	},

	set_AddressBookItemControlID: function(value) {
		this._AddressBookItemControlIDValue = value;
	},

	get_AddressBookItemEditControlID: function() {
		return this._AddressBookItemEditControlIDValue;
	},

	set_AddressBookItemEditControlID: function(value) {
		this._AddressBookItemEditControlIDValue = value;
	},

	get_AddressFormControlID: function() {
		return this._AddressFormControlIDValue;
	},

	set_AddressFormControlID: function(value) {
		this._AddressFormControlIDValue = value;
	},

	get_AddressFormStreetText: function() {
		return this._AddressFormStreetText;
	},

	set_AddressFormStreetText: function(value) {
		this._AddressFormStreetText = value;
	},

	get_AddressFormPostcodeText: function() {
		return this._AddressFormStreetText;
	},

	set_AddressFormFocusObject: function(value) {
		this._AddressFormFocusObject = value;
	},

	get_AddressFormFocusObject: function() {
		return this._AddressFormFocusObject;
	},


	set_AddressFormPostcodeText: function(value) {
		this._AddressFormPostcodeText = value;
	},

	get_AddressFormCityText: function() {
		return this._AddressFormCityText;
	},

	set_AddressFormCityText: function(value) {
		this._AddressFormCityText = value;
	},

	get_AddressFormCountrySelect: function() {
		return this._AddressFormCountrySelect;
	},

	set_AddressFormCountrySelect: function(value) {
		this._AddressFormCountrySelect = value;
	},

	get_AddressFormFuzzyLinkCheck: function() {
		return this._AddressFormFuzzyLinkCheck;
	},

	set_AddressFormFuzzyLinkCheck: function(value) {
		this._AddressFormFuzzyLinkCheck = value;
	},

	/// <summary>path to the GeocodeWebService.asmx</summary>
	get_xLocateServicePath: function() {
		return this._xLocateServicePath;
	},

	set_xLocateServicePath: function(value) {
		this._xLocateServicePath = value;
	},

	//    /// <summary>path to the AddressBookWebService.asmx</summary>
	//    get_AddressBookJSONService : function() {
	//        return this._AddressBookJSONService;
	//    },

	//    set_AddressBookJSONService : function(value) {
	//        this._AddressBookJSONService = value;
	//    }, 

	/* <summary>UL AddressBook DOM element</summary> */
	get_AddressBook: function() {
		return this._AddressBook;
	},

	set_AddressBook: function(value) {
		this._AddressBook = value;
	},


	/* <summary>path to the AddressBookWebService.asmx</summary> */
	get_CookieName: function() {
		return this._CookieName;
	},

	set_CookieName: function(value) {
		this._CookieName = value;
	},

	get_TwoLetterISOLanguageName: function() {
		return this._TwoLetterISOLanguageName;
	},

	set_TwoLetterISOLanguageName: function(value) {
		this._TwoLetterISOLanguageName = value;
	},

	get_Collapsed: function() {
		return this._Collapsed;
	},

	set_Collapsed: function(value) {
		this._Collapsed = value;
	},


	get_ExpandLastSaved: function() {
		return this._ExpandLastSaved;
	},

	set_ExpandLastSaved: function(value) {
		this._ExpandLastSaved = value;
	},

	get_HasDraggableItems: function() {
		return this._HasDraggableItems;
	},
	set_HasDraggableItems: function(value) {
		this._HasDraggableItems = value;
	},

	/* <summary>path to the AddressBookWebService.asmx</summary> */
	get_MaxSearchResults: function() {
		return this._MaxSearchResults;
	},

	set_MaxSearchResults: function(value) {
		this._MaxSearchResults = value;
	},

	get_MaxSavedItems: function() {
		return this._MaxSavedItems;
	},
	set_MaxSavedItems: function(value) {
		if (this._MaxSavedItems != value) {
			this._MaxSavedItems = value;
		}
	},

	get_DoAppendNewAddress: function() {
		return this._DoAppendNewAddress;
	},

	set_DoAppendNewAddress: function(value) {
		if (this._DoAppendNewAddress != value) {
			this._DoAppendNewAddress = value;
			this.raisePropertyChanged('DoAppendNewAddress');
		}
	},
	
	get_AlwaysShowAddressForm: function() { 
		return this._AlwaysShowAddressForm;
	},
	set_AlwaysShowAddressForm: function(value)   {
			this._AlwaysShowAddressForm = value;
	},

	add_ShowMap: function(handler) {
		this.get_events().addHandler("ShowMap", handler);
	},

	remove_ShowMap: function(handler) {
		this.get_events().removeHandler("ShowMap", handler);
	},

	_raiseShowMap: function(arg) {
		var handler = this.get_events().getHandler("ShowMap");
		if (handler) handler(this, arg);

	},


	add_Error: function(handler) {
		this.get_events().addHandler("Error", handler);
	},
	remove_Error: function(handler) {
		this.get_events().removeHandler("Error", handler);
	},
	_raiseError: function(arg) {
		var handler = this.get_events().getHandler("Error");
		if (handler) handler(this, arg);

	},


	add_AddressSearch: function(handler) {
		this.get_events().addHandler("AddressSearch", handler);
	},

	remove_AddressSearch: function(handler) {
		this.get_events().removeHandler("AddressSearch", handler);
	},

	_raiseAddressSearch: function(arg) {
		var handler = this.get_events().getHandler("AddressSearch");
		if (handler) handler(this, arg);
	},

	add_change: function(handler) {
		this.get_events().addHandler("change", handler);
	},

	remove_change: function(handler) {
		this.get_events().removeHandler("change", handler);
	},

	_raiseChange: function(arg) {
		var handler = this.get_events().getHandler("change");
		if (handler) handler(this, arg);
	},


	dispose: function() {

		control = $get(this._AddressNewButtonIDValue);
		if (control)
			$clearHandlers(control);

		control = $get(this._AddressSearchButtonIDValue);
		if (control)
			$clearHandlers(control);

		control = $get(this._AddressEditCancelButtonIDValue);
		if (control)
			$clearHandlers(control);

		control = $get(this._AddressEditButtonIDValue);
		if (control)
			$clearHandlers(control);

		control = $get(this._AddressDeleteButtonIDValue);
		if (control)
			$clearHandlers(control);

		control = $get(this._AddressSelectButtonIDValue);
		if (control)
			$clearHandlers(control);

		TripzoomLib.AddressBookBehavior.callBaseMethod(this, 'dispose');
	}



};

TripzoomLib.AddressBookBehavior.registerClass('TripzoomLib.AddressBookBehavior', AjaxControlToolkit.BehaviorBase);

TripzoomLib.Collection = function() {
	TripzoomLib.Collection.initializeBase(this);
	this.items = new Array();
};

TripzoomLib.Collection.prototype = {
	Parse: function(strValue) {
		return strValue;
	},

	Render: function() {
		return "No implementation";
	}
};

TripzoomLib.Collection.registerClass("TripzoomLib.Collection", Sys.Component);

/* AddressCollection
description: Array of Address objects
*/
TripzoomLib.AddressCollection = function() {
	TripzoomLib.AddressCollection.initializeBase(this);
};

TripzoomLib.AddressCollection.prototype = {

	Parse: function(addressStr) {
		if (addressStr.length > 0) {
			var addressArray = addressStr.split('|');

			for (var i = 0; i < addressArray.length; i++) {
				this.items[i] = new TripzoomLib.Element.Address(addressArray[i]);
			}
		} else {
			var err = Error.create("No address found");
			throw err;
		}
		return addressStr;
	},
	Render: function() {
		var retVal = "";
		for (var i = 0; i < this.Items.length; i++) {
			retVal += this.items[i].Description() + "|";
		}
		return retVal;
	}
};
TripzoomLib.AddressCollection.registerClass("TripzoomLib.AddressCollection", TripzoomLib.Collection);

/* define class AddressTable
description: fill address layer with results
*/
TripzoomLib.AddressResultTable = function(element) {
	TripzoomLib.AddressResultTable.initializeBase(this, [element]);

	this._control = null;
	this._sender = null;

	this._clickDelegate = null;
};

TripzoomLib.AddressResultTable.prototype = {

	initialize: function() {
		TripzoomLib.AddressResultTable.callBaseMethod(this, 'initialize');

		this._control = document.createElement("ul");
		this._control.className = "AddressResultTable";

		this.get_element().appendChild(this._control);

		if (this._clickDelegate == null) {
			this._clickDelegate = Function.createDelegate(this, this._raiseClick);
		}
	},

	dispose: function() {
		this._clickDelegate = null;
		TripzoomLib.AddressResultTable.callBaseMethod(this, 'dispose');
	},

	SetAddresses: function(result) {
		this.PopulateAddresses(result);
	},

	PopulateAddresses: function(collection) {
		for (var i = 0; i < collection.length; i++) {
			this._CreateRow(i, collection[i]);
		}
	},


	_CreateRow: function(i, address) {

		var obj = this._control.appendChild(document.createElement("li"));

		obj.className = "resultaddress_off";


		obj.onmousedown = function() { return false; };
		obj.onmouseup = function() { return false; };

		obj.onmouseover = function() {
			this.className = "resultaddress_on";
		}
		obj.onmouseout = function() {
			this.className = "resultaddress_off";
		}

		var radio = null;
		if (Sys.Browser.agent == Sys.Browser.InternetExplorer) {
			radio = obj.appendChild(document.createElement("<input type='radio'>"));
		} else {
			radio = obj.appendChild(document.createElement("input"));
			radio.setAttribute("type", "radio");
		}
		radio.name = this.get_element().id + "_listitem";
		radio.id = this.get_element().id + "_" + i;
		radio.value = address.Address;

		$addHandler(radio, "click", this._clickDelegate);


		var label = obj.appendChild(document.createElement("label"));
		label.htmlFor = this.get_element().id + "_" + i;

		label.innerHTML = ((address.Name != "") ? address.Name + " " : "") + address.Description;

	},


	add_click: function(handler) {
		this.get_events().addHandler("click", handler);
	},
	remove_click: function(handler) {
		this.get_events().removeHandler("click", handler);
	},

	_raiseClick: function(evt) {
		evt.preventDefault();
		evt.stopPropagation();
		var handler = this.get_events().getHandler("click");
		if (handler) handler(this, evt.target.value);

	},

	get_sender: function() {
		return this._sender;
	},

	set_sender: function(value) {
		this._sender = value;
	},
	get_control: function() {
		return this._control;
	}

};
TripzoomLib.AddressResultTable.registerClass("TripzoomLib.AddressResultTable", Sys.UI.Control);
var g_Status = 'OK';

Type.registerNamespace('TripzoomLib');

TripzoomLib.DraggableAddressBookItemBehavior = function(element) {
    TripzoomLib.DraggableAddressBookItemBehavior.initializeBase(this, [element]);

	/* mousedown event handler */
	this._mouseDownHandler = Function.createDelegate(this, this._handleMouseDown);
	this._mouseUpHandler = Function.createDelegate(this, this._handleMouseUp);
	this._mouseMoveHandler = Function.createDelegate(this, this._handleMouseMove);

	/* the transparent element when dragging the item */
	this._visual = null;
	this._handle = element;
	
	this._index = -1;
	this._AddressBook = null;
	
	this._mouseDown = false;
	this._isDragging = false;

}

TripzoomLib.DraggableAddressBookItemBehavior.prototype = {

    initialize : function() {
        TripzoomLib.DraggableAddressBookItemBehavior.callBaseMethod(this, 'initialize');
		
		$addHandler(this.get_element(), "mousedown", this._mouseDownHandler);
		$addHandler(this.get_element(), "mouseup", this._mouseUpHandler);
		$addHandler(this.get_element(), "mousemove", this._mouseMoveHandler);

    },

    dispose : function() {
    
		$clearHandlers(this.get_element());
    
		this._mouseDownHandler = null;
		this._mouseUpHandler = null;
		this._mouseMoveHandler = null;		
		
	
        TripzoomLib.DraggableAddressBookItemBehavior.callBaseMethod(this, 'dispose');
    },

	get_handle : function() {
		return this._handle;
	},

	set_handle : function(value) {
		this._handle = value; 
	},
	
	get_visual :function() { 
		return this._visual;
	}, 
	
	get_index : function() {
		return this._index;
	},
	
	set_index : function(value) { 
		this._index = value;
	},
	
	get_AddressBook : function() { 
		return this._AddressBook;
	}, 
	
	set_AddressBook : function(value) {
		this._AddressBook = value;
	}, 
	
    /* Type get_dragDataType() */
    get_dragDataType: function() { 
		return "AddressBookItem";
	},
    /* Object getDragData(Context) */
    getDragData: function() { 
		return this;
	},
	
    /* DragMode get_dragMode() */
    get_dragMode: function() { 
		return AjaxControlToolkit.DragMode.Move;
    },

	/* this method will be called when user starts dragging */
	onDragStart: function() {
	},
	 
	/* this method will be called when user is dragging */
	onDrag: function() {
	},

	
    /* void onDragEnd(Cancelled) */
    onDragEnd: function() {    

		/* deactivate the active addressbookitem in the current addressbook */
		if (this._isDragging) {
			this._AddressBook._CloseEditControl();
//			this._AddressBook._activeitem = this.get_element();
			this._AddressBook._OpenEditControl(this.get_element());				
		}

		if (this._visual) {   /* remove the transparent element */
			document.body.removeChild(this._visual);
		}
	},   

	/* mousemove event handler */
	_handleMouseDown: function(ev) {
		if (!this._isDragging)
			this._mouseDown = true;
	},
	
	_handleMouseUp: function(ev) {
		this._mouseDown = false; 
		this._isDragging = false;
	},
	
	_handleSelectStart: function(ev) {
		return false; 
	},	

	/* mousemove event handler	 */
	_handleMouseMove: function(ev) {
		if (!this._isDragging && this._mouseDown) {
			window._event = ev; 

			/* what is the index of the dragged addressbookitem */
			var items = this.get_element().parentNode.getElementsByTagName("LI");
			for (var i = 0; i < items.length; i++) { 
				if (items[i] == this.get_element()) { 
					this._index = i;
					break;
				} 
			} 
			
					 
			/* set the style of the transparent element which follows the cursor */ 
			this._visual = document.createElement("UL");
			this._visual.className = "AddressBook";
			this._visual.appendChild(this.get_element().cloneNode(true));
			this._visual.style.opacity = "0.7";
			this._visual.style.filter = 
				"progid:DXImageTransform.Microsoft.BasicImage(opacity=0.7)";
			this._visual.style.zIndex = 99999;
			document.body.appendChild(this._visual);
			

			var location = CommonToolkitScripts.getLocation(this.get_element());
			
			this._visual.style.position = 'absolute';
			this._visual.style.borderWidth = '1px'
			this._visual.style.borderStyle = 'dotted';
			this._visual.style.borderColor = 'black';
			this._visual.style.left = location.x + 'px';
			this._visual.style.top = location.y + 'px';
			
			if (Sys.Browser.agent == Sys.Browser.InternetExplorer) {
				this._visual.style.width = CommonToolkitScripts.getSize(this.get_element()).width + 'px';
			} else { 
				this._visual.style.width = '300px';
			} 
			
			
			/* start dragging    */
			AjaxControlToolkit.DragDropManager.startDragDrop(this, this._visual, null);
			
			
			this._isDragging = true;
			
		}
	}  
    
}

TripzoomLib.DraggableAddressBookItemBehavior.registerClass('TripzoomLib.DraggableAddressBookItemBehavior', AjaxControlToolkit.BehaviorBase, AjaxControlToolkit.IDragSource);


TripzoomLib.DropWatcherAddressBookBehavior = function(element) {	
	TripzoomLib.DropWatcherAddressBookBehavior.initializeBase(this, [element]);	
	
	this._AddressBook = null;
} 

TripzoomLib.DropWatcherAddressBookBehavior.prototype = { 

	initialize: function() {
	  TripzoomLib.DropWatcherAddressBookBehavior.callBaseMethod(this, "initialize");
	    
	  AjaxControlToolkit.DragDropManager.registerDropTarget(this);
	},
	 
	dispose: function() {
	  AjaxControlToolkit.DragDropManager.unregisterDropTarget(this);
	    
	  TripzoomLib.DropWatcherAddressBookBehavior.callBaseMethod(this, "dispose");
	},

	/* return the DOM element of the AddressBook */
	get_dropTargetElement: function() {
		return this.get_element();
	},


	/* if this draggable item can be dropped into this drop target */
	canDrop: function(dragMode, dataType, data) {
		return (dataType == "AddressBookItem");
	},

	/* drop this draggable item into this drop target */
	drop : function(dragMode, dataType, data) {
		if (dataType == "AddressBookItem") {
			
			items = this.get_element().getElementsByTagName("LI");
			var visual = data.get_visual();
			
			var target_index = items.length - 1; 
			
			if (items.length > 0) { 
				var item = null;
				var target = null, miny = 10000000000;
				for (var i = 0; i < items.length; i++) {
					item = items[i];
					if (item != data.get_element()) { 
						var point =	CommonToolkitScripts.getLocation(item);
						if (parseInt(visual.style.top) < point.y) {
							if (miny > Math.min(miny, point.y, parseInt(visual.style.top))) { 
								miny = point.y - parseInt(visual.style.top) ;
								target = item;
								target_index = i;
							} 
						}
					}
				} 
				
				if (target) {												  
					this.moveBefore(data.get_element(), target);
				} else {
					this._AddressBook.get_AddressBook().appendChild(data.get_element());
				}
			} else {
				this._AddressBook.get_AddressBook().appendChild(data.get_element());
			}
			this._AddressBook._CloseSearchControl();

			for (var i = 0; i < items.length; i++) { 
				if (items[i].attributes["address"].value == "") { 
					items[i].parentNode.removeChild(items[i]);
				} 
			} 
			
			var newIndex = this._AddressBook._getAddressBookItemIndex(data.get_element());
			var oldAddressBook = data.get_AddressBook();
			
			if (oldAddressBook.get_CookieName() != this._AddressBook.get_CookieName()) { 
				
				/* zet een nieuwe active item in oude addressbook  */
				if (oldAddressBook._AddressBook.hasChildNodes()) {
					if (oldAddressBook._AddressBook.firstChild.attributes["address"].value == "") { 
						oldAddressBook._onAddressNewButtonClicked();
					} else {
						oldAddressBook._OpenEditControl(oldAddressBook._AddressBook.firstChild);
					}
				} else {
					oldAddressBook._onAddressNewButtonClicked();
				}
			

				div = data.get_element().firstChild;
				var suffix = "";				
				if (div.className.endsWith("Active")) {		
					suffix = "_Active";
				}
				if (this._AddressBook.get_element().className.toLowerCase().indexOf("via") != -1) { 
					div.className = "viaAddressBookItem" + suffix;
				} else { 
					div.className = "AddressBookItem" + suffix;
				}				
				
				$clearHandlers(data.get_element());				
				
				
				data.set_AddressBook(this._AddressBook);
				$addHandler(data.get_element(), 'click', data.get_AddressBook()._AddressBookItemClickedHandler);
				
				var behavior = Sys.UI.Behavior.getBehaviorByName(data.get_element(), "TripzoomLib.DraggableAddressBookItemBehavior");
				if (!behavior)  {
					$create(TripzoomLib.DraggableAddressBookItemBehavior, {"handle":data.get_element().firstChild, "AddressBook" : this._AddressBook}, null, null, data.get_element());
				} 
				
			} 
				
			
			
			
			
			/* gebruik JSON service om ook in cookie het verplaatste adres bij te werken */
//			url = this._AddressBook.get_AddressBookJSONService() + '?task=moveAddress' +
//				'&from_index=' + data.get_index() +  '&from_book=' + oldAddressBook.get_CookieName() + 
//				'&to_index=' + newIndex + '&to_book=' + this._AddressBook.get_CookieName();
//				
//			var req = new JSONScriptRequest();
//			req.open('GET', url);
//			req.onreadystatechange = function() {
//				  if (req.readyState == 4) {
//					  alert(req.responseJSON);
//				  }
//			  }		
//			req.send(null);
			
		}
	},


	/* this method will be called when a draggable item is entering this drop target */
	onDragEnterTarget : function(dragMode, dataType, data) {
		if (dataType == "AddressBookItem") {
			/* set background color of shopping cart element to gray */
			/*this.get_element().style.backgroundColor = "#E0E0E0";*/
		}
	},
	 
	/*this method will be called when a draggable item is leaving this drop target	*/
	onDragLeaveTarget : function(dragMode, dataType, data) {
		if (dataType == "AddressBookItem") {				  
			/* set background color of shopping cart element to white */
			/*this.get_element().style.backgroundColor = "#fff"; */
		}
	},
	 
	/* this method will be called when a draggable item is hovering on this drop target */
	onDragInTarget : function(dragMode, dataType, data) {
	},

    /* <summary>path to the AddressBookWebService.asmx</summary> */
    get_AddressBook: function() {
        return this._AddressBook;
    },

    set_AddressBook: function(value) {
        this._AddressBook= value;
    }, 


	moveBefore : function(item1, item2) {
		var parent = item1.parentNode
		parent.removeChild(item1)
		parent = item2.parentNode;
		return parent.insertBefore(item1, item2)
	},

	moveAfter : function(item1, item2) {
		var parent = item1.parentNode
		parent.removeChild(item1)
		return parent.insertBefore(item1, item2 ? item2.nextSibling : null)
	}
} 

TripzoomLib.DropWatcherAddressBookBehavior.registerClass('TripzoomLib.DropWatcherAddressBookBehavior', AjaxControlToolkit.BehaviorBase, AjaxControlToolkit.IDropTarget);


function moveAddress(data) {
	var text='';
	if(data==null)
		alert('error');
	else {
		text = data["status"];
	}
	g_Status = text;
}


/* Goto: http://www.supersloper.net/new/code.php?s=cookie.js&c=javascript */

Type.registerNamespace("TripzoomLib");


/**
 * Class for working with name|value pair cookies.
 * @param      string       cookie name we will be working on.
 */
TripzoomLib.Cookie = function (sCookieName)
{
	TripzoomLib.Cookie.initializeBase(this);
    this.sCookieName   = sCookieName || 'routenet';
    this.nExpires      = (1*365*24*60*60*1000); /* default expires 1 years   */
    this.sPath         = '/';                   /* default path			 */
    this.sDomain       = '';                    /* default domain	   */
    this.sDelimiter    = '|';                   /* default delimiter */
    this.bValidCookie  = false;                 /* set true if cookie found */
    this.aData         = new Array();           /* Associative array of cookie Array[name] => value */
    
};  
    
/**
 * Read in the cookie into an associative array cData[name] => value
 * @return     aReturn
 */
TripzoomLib.Cookie.prototype = {

	initialize: function() {

		TripzoomLib.Cookie.callBaseMethod(this, "initialize");
		/* reset vars in case we are re-reading the cookie */
		this.bValidCookie = false;
		this.aData = Array();


		var aAll = document.cookie.split(';');
		var sFull = '';
		var aFull = new Array();


		if (aAll) {
			// set up the regex to get the correct cookie
			var sPattern = '(^' + this.sCookieName + '=)';
			var oCookieReg = new RegExp(sPattern, "g");

			// loop through all the cookies to get the one we want
			for (i = 0; i < aAll.length; i++) {
				// trim each value so the RegExp matches the beginning of the line correctly
				aAll[i] = aAll[i].replace(/^\s+|\s+$/g, '');
				if (oCookieReg.test(aAll[i])) {
					sFull = aAll[i];
					continue;
				}
			}

			// if we found our cookie put into the aData array
			if (sFull) {
				aFull = sFull.slice(sFull.indexOf('=') + 1);
				aFull = aFull.split("&");
				for (i = 0; i < aFull.length; i++) {
					keyValue = aFull[i].split("=");
					this.aData[keyValue[0]] = unescape(keyValue[1]);
				}

				this.bValidCookie = true;
			}
		}
	},

	dispose: function() {
		TripzoomLib.Cookie.callBaseMethod(this, "dispose");
	},


	/**
	* Set when the cookie expires
	* @param       int      microseconds till cookies should expire
	*/
	setExpires: function(nExpires) {
		this.nExpires = nExpires;
	},

	/**
	* Set the path for the cookie
	* @param     sPath
	*/
	setPath: function(sPath) {
		this.sPath = sPath;
	},

	/**
	* Set the domain for the cookie
	* @param     sDomain
	*/
	setDomain: function(sDomain) {
		this.sDomain = sDomain;
	},


	/**
	* Return the cookie as a string
	* @return    sReturn
	*/
	cookieToString: function() {
		var sReturn = this.sCookieName + ":\n";
		for (i in this.aData) {
			sReturn += i + ' => ' + this.aData[i] + "\n";
		}
		return sReturn;
	},

	/**
	* Set the value for a given param name
	* @param      string      param name
	* @param      string      param value
	*/
	setCookieData: function(sName, sValue) {
		this.aData[sName] = escape(sValue);
		this.writeCookieData();
		return sValue;
	},

	/**
	* Set the value for a given param name
	* @param      string      param name
	* @param      string      param value
	*/
	setCookie: function(sName, sValue) {
		this.aData[sName] = escape(sValue);
		this.writeCookie();
		return sValue;
	},
	/**
	* Delete the cookie for a given param name
	* @param      string      param name
	*/
	delCookieData: function(sName) {
		this.aData[sName] = null;
		this.writeCookieData();
	},

	/**
	*   Return the value for the given name
	*   @param      string      cookie param name
	*   @return     string      cookie value
	*/
	getCookieData: function(sName) {
		return (this.aData[sName]);
	},

	/**
	*   Check if cookie is valid
	*   @return     boolean
	*/
	isValidCookie: function() {
		return this.bValidCookie;
	},


	/**
	* Write the cookie
	*/
	writeCookie: function() {
		// build the cookie from the array
		var aTemp = new Array();
		var sValue = '';
		var k = 0;
		for (key in this.aData) {
			if (this.aData[key] != null) {
				aTemp[k] = key + "=" + this.aData[key];
				sValue = aTemp.join("&");
				k++;
			}
		}

		// set expiration        
		var oExpdate = new Date();
		oExpdate.setTime(oExpdate.getTime() + this.nExpires);

		var aCookie = new Array();
		aCookie.push(sValue + ';');
		aCookie.push('expires=' + oExpdate.toGMTString() + ';');
		aCookie.push('path=' + this.sPath + ';');
		if (this.sDomain.length > 0) aCookie.push('domain=' + this.sDomain + ';');

		document.cookie = aCookie.join('');

		this.bValidCookie = true;
	},
	
	/**
	* Write the cookie
	*/
	writeCookieData: function() {
		// build the cookie from the array
		var aTemp = new Array();
		var sValue = '';
		var k = 0;
		for (key in this.aData) {
			if (this.aData[key] != null) {
				aTemp[k] = key + "=" + this.aData[key];
				sValue = aTemp.join("&");
				k++;
			}
		}

		// set expiration        
		var oExpdate = new Date();
		oExpdate.setTime(oExpdate.getTime() + this.nExpires);

		var aCookie = new Array();
		aCookie.push(this.sCookieName + "=" + sValue + ';');
		aCookie.push('expires=' + oExpdate.toGMTString() + ';');
		aCookie.push('path=' + this.sPath + ';');
		if (this.sDomain.length > 0) aCookie.push('domain=' + this.sDomain + ';');

		document.cookie = aCookie.join('');

		this.bValidCookie = true;
	},

	/**
	* Clear the cookie by setting expires to beginning of UNIX time
	*/
	clearCookie: function() {
		aCookie = new Array();
		aCookie.push(this.sCookieName + '=;');
		aCookie.push('expires=Thu, 01-Jan-70 00:00:01 GMT;');
		aCookie.push('path=' + this.sPath + ';');
		if (this.sDomain.length > 0) aCookie.push('domain=' + this.sDomain + ';');

		document.cookie = aCookie.join('');

		// re-read the cookie
		this.readCookie();
	},


	Exists: function(cookieName) {
		var cookie = document.cookies[cookieName];
		if (!cookie) {
			return false;
		}
		return true;
	}
};

TripzoomLib.Cookie.registerClass("TripzoomLib.Cookie", Sys.Component);

if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();