/*
* jQuery idleTimer plugin
* version 0.7.080609
* by Paul irish.
* http://github.com/paulirish/yui-misc/tree/
* MIT license
* adapted from YUI idle timer by nzakas:
* http://github.com/nzakas/yui-misc/
* Copyright (c) 2009 Nicholas C. Zakas
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
 
(function(jQuery){
 
jQuery.idleTimer = function(newTimeout){
 
    //jQuery.idleTimer.tId = -1 //timeout ID
 
    var idle = false, //indicates if the user is idle
        enabled = true, //indicates if the idle timer is enabled
        timeout = 30000, //the amount of time (ms) before the user is considered idle
        events = 'mousemove keydown DOMMouseScroll mousewheel mousedown', // activity is one of these events
        
    /* (intentionally not documented)
* Toggles the idle state and fires an appropriate event.
* @return {void}
*/
    toggleIdleState = function(){
    
        //toggle the state
        idle = !idle;
        
        //fire appropriate event
        jQuery(document).trigger((idle ? "idle" : "active") + '.idleTimer');
    },
 
    
    /**
* Indicates if the idle timer is running or not.
* @return {Boolean} True if the idle timer is running, false if not.
* @method isRunning
* @static
*/
    isRunning = function(){
        return enabled;
    },
    
    /**
* Indicates if the user is idle or not.
* @return {Boolean} True if the user is idle, false if not.
* @method isIdle
* @static
*/
    isIdle = function(){
        return idle;
    },
    
    /**
* Stops the idle timer. This removes appropriate event handlers
* and cancels any pending timeouts.
* @return {void}
* @method stop
* @static
*/
    stop = function(){
    
        //set to disabled
        enabled = false;
        
        //clear any pending timeouts
        clearTimeout(jQuery.idleTimer.tId);
        
        //detach the event handlers
        jQuery(document).unbind('.idleTimer');
    },
    
    
    /* (intentionally not documented)
* Handles a user event indicating that the user isn't idle.
* @param {Event} event A DOM2-normalized event object.
* @return {void}
*/
    handleUserEvent = function(){
    
        //clear any existing timeout
        clearTimeout(jQuery.idleTimer.tId);
        
        
        
        //if the idle timer is enabled
        if (enabled){
        
          
            //if it's idle, that means the user is no longer idle
            if (idle){
                toggleIdleState();
            }
        
            //set a new timeout
            jQuery.idleTimer.tId = setTimeout(toggleIdleState, timeout);
            
        }
     };
/**
* Starts the idle timer. This adds appropriate event handlers
* and starts the first timeout.
* @param {int} newTimeout (Optional) A new value for the timeout period in ms.
* @return {void}
* @method jQuery.idleTimer
* @static
*/
    
    
    
    //assign a new timeout if necessary
    if (typeof newTimeout == "number"){
        timeout = newTimeout;
    } else if (newTimeout === 'destroy') {
        stop();
        return;
    }
    
    //assign appropriate event handlers
    jQuery(document).bind(jQuery.trim((events+' ').split(' ').join('.idleTimer ')),handleUserEvent);
    
    
    //set a timeout to toggle state
    jQuery.idleTimer.tId = setTimeout(toggleIdleState, timeout);
  
    
 
    
}; // end of jQuery.idleTimer()
 
    
 
})(jQuery);

;(function(jQuery) {
    /*
    * ui.dropdownchecklist
    *
    * Copyright (c) 2008 Adrian Tosca
    * Dual licensed under the MIT (MIT-LICENSE.txt)
    * and GPL (GPL-LICENSE.txt) licenses.
    * 
    */
    // The dropdown check list jQuery plugin transforms a regular select html element into a dropdown check list. 
    jQuery.widget("ui.dropdownchecklist", {
        // Creates the drop container that keeps the items and appends it to the document
        _appendDropContainer: function() {
            var wrapper = jQuery("<div/>");
            // the container is wrapped in a div
            wrapper.addClass("ui-dropdownchecklist-dropcontainer-wrapper");
            // initially hidden
            wrapper.css({
                position: 'absolute',
                left: "-3300",
                top: "-3300px",
                width: '3000px',
                height: '3000px',
                zIndex: '1300'
            });
            var container = jQuery("<div/>"); // the actual container
            container.addClass("ui-dropdownchecklist-dropcontainer")
                .css("overflow-y", "auto");
            wrapper.append(container);
            jQuery(document.body).append(wrapper);
            // flag that tells if the drop container is shown or not
            wrapper.drop = false;
            return wrapper;
        },
        // Creates the control that will replace the source select and appends it to the document
        // The control resembles a regular select with single selection
        _appendControl: function() {
            var self = this, options = this.options, sourceSelect = this.sourceSelect;

            // the controls is wrapped in a span with inline-block display
            var wrapper = jQuery("<span/>");
            wrapper.addClass("ui-dropdownchecklist-wrapper");
            wrapper.css({
                display: "inline-block",
                cursor: "default"
            });

            // the actual control, can be styled to set the border and drop right image
            var control = jQuery("<span/>");
            control.addClass("ui-dropdownchecklist");
            control.css({
                display: "inline-block"
            });
            wrapper.append(control);

            // the text container keeps the control text that is build from the selected (checked) items
            var textContainer = jQuery("<span/>");
            textContainer.addClass("ui-dropdownchecklist-text")
            textContainer.css({
                display: "inline-block",
                overflow: "hidden"
            });
            control.append(textContainer);

            // add the hover styles to the control
            wrapper.hover(function() {
                if (!self.disabled) {
                    control.toggleClass("ui-dropdownchecklist-hover")
                }
            }, function() {
                if (!self.disabled) {
                    control.toggleClass("ui-dropdownchecklist-hover")
                }
            });

            // clicking on the control toggles the drop container
            wrapper.click(function(event) {
                if (!self.disabled) {
                    event.stopPropagation();
                    self._toggleDropContainer();
                }
            })

            wrapper.insertAfter(sourceSelect);

            return wrapper;
        },
        // Creates a drop item that coresponds to an option element in the source select
        _createDropItem: function(index, value, text, checked, indent, disabled) {
            var self = this, dropWrapper = this.dropWrapper, options = this.options;
            // the item contains a div that contains a checkbox input and a span for text
            // the div
            var item = jQuery("<div/>");
            item.addClass("ui-dropdownchecklist-item");
            item.css({whiteSpace: "nowrap"});
            // the checkbox
            var checkedString = checked ? ' checked="checked"' : '';
            var checkBox = jQuery('<input type="checkbox"' + checkedString + '/>')
                .attr("index", index)
                .val(value);

            item.append(checkBox);
            // the text
            var label = jQuery("<span/>");
            label.addClass("ui-dropdownchecklist-text")
                .css({
                    cursor: "default",
                    width: "100%"
                })
                .text(text);
            if (disabled) {
                checkBox.css({
                    display: "none",
                    visible: "hidden"
                });
                item.css({
                    display: "none",
                    visible: "hidden"
                });
            } 
            if(checkBox.val() == "ow" || checkBox.val() == "ka" || checkBox.val() == "bi" || checkBox.val() == "ma" || Math.floor(checkBox.val()).toString() == checkBox.val().toString())
            {
                item.addClass("ui-dropdownchecklist-indent");
            }
            if(checkBox.val() == "OHR" || checkBox.val() == "OHANA" || checkBox.val() == "CONDO")
            {
                checkBox.css({
                    display: "none",
                    visible: "hidden"
                });
                item.css({
                    fontWeight: "bold"
                });
            }
            if(checkBox.val() == "hi")
            {
                checkBox.css({
                    display: "none",
                    visible: "hidden"
                });
            }
            
			if (indent) {
				item.addClass("ui-dropdownchecklist-indent");
			}
            item.append(label);
            item.hover(function() {
                item.addClass("ui-dropdownchecklist-item-hover")
            }, function() {
                item.removeClass("ui-dropdownchecklist-item-hover")
            });
            // clicking on the checkbox synchronizes the source select
            checkBox.click(function(event) {
                event.stopPropagation();
                var checked = jQuery(this).attr("checked");  
                if(checkBox.val() == "ow" || checkBox.val() == "ka" || checkBox.val() == "bi" || checkBox.val() == "ma" || checkBox.val() == "gm"  || checkBox.val() == "fj"  || checkBox.val() == "at"  || checkBox.val() == "id"  || checkBox.val() == "th"   )
                    {                
                        var allCheckboxes = dropWrapper.find("input");
                        allCheckboxes.each(function(index) {
                            if (index > 0) {
                                jQuery(this).removeAttr("checked");
                            }
                        });
                    }
                jQuery(this).attr("checked", checked)
                self._syncSelected(jQuery(this));
                self.sourceSelect.trigger("change");            
            });
            // check/uncheck the item on clicks on the entire item div
            var checkItem = function(event) {
                if(checkBox.val() != "hi" && checkBox.val() != "OHR" && checkBox.val() != "OHANA" && checkBox.val() != "CONDO")
                {
                    event.stopPropagation();
                    var checked = checkBox.attr("checked");   
                    if(checkBox.val() == "ow" || checkBox.val() == "ka" || checkBox.val() == "bi" || checkBox.val() == "ma" || checkBox.val() == "gm"  || checkBox.val() == "fj"  || checkBox.val() == "at"  || checkBox.val() == "id"  || checkBox.val() == "th"   )
                    {                
                        var allCheckboxes = dropWrapper.find("input");
                        allCheckboxes.attr("checked", checkBox.attr("checked"));
                        allCheckboxes.each(function(index) {
                            if (index > 0) {
                                jQuery(this).removeAttr("checked");
                            }
                        });
                    }
                    checkBox.attr("checked", !checked)
                    self._syncSelected(checkBox);            
                }
            }
            label.click(checkItem);
            item.click(checkItem);
            return item;
        },
		_createGroupItem: function(text) {
			var self = this;
			var group = jQuery("<div />")
			group.addClass("ui-dropdownchecklist-group");
			group.css({whiteSpace: "nowrap"});
            var label = jQuery("<span/>");
            label.addClass("ui-dropdownchecklist-text")
                .css({
                    cursor: "default",
                    width: "100%"
                })
                .text(text);
			group.append(label);
			return group;
		},
        // Creates the drop items and appends them to the drop container
        // Also calculates the size needed by the drop container and returns it
        _appendItems: function() {
            var self = this, sourceSelect = this.sourceSelect, controlWrapper = this.controlWrapper, dropWrapper = this.dropWrapper;
            var dropContainerDiv = dropWrapper.find(".ui-dropdownchecklist-dropcontainer");
            dropContainerDiv.css({ float: "left" }); // to allow getting the actual width of the container
			sourceSelect.children("optgroup").each(function(index) { // when the select has groups
				var optgroup = jQuery(this);
				var text = optgroup.attr("label");
				var group = self._createGroupItem(text);
				dropContainerDiv.append(group);
				self._appendOptions(optgroup, dropContainerDiv, true);
			});
			self._appendOptions(sourceSelect, dropContainerDiv, false); // when no groups
            var divWidth = dropContainerDiv.outerWidth();
            var divHeight = dropContainerDiv.outerHeight();
            dropContainerDiv.css({ float: "" }); // set it back
            return { width: divWidth, height: divHeight };
        },
		_appendOptions : function(parent, container, indent) {
			var self = this;
            parent.children("option").each(function(index) {                
                var option = jQuery(this);
				var text = option.text();
				var value = option.val();
				var selected = option.attr("selected");
				var disabled = option.attr("disabled");
				var item = self._createDropItem(index, value, text, selected, indent, disabled);
				container.append(item);
            })
		},
        // Synchronizes the items checked and the source select
        // When firstItemChecksAll option is active also synchronizes the checked items
        // senderCheckbox parameters is the checkbox input that generated the synchronization
        _syncSelected: function(senderCheckbox) {
            var self = this, options = this.options, sourceSelect = this.sourceSelect, controlWrapper = this.controlWrapper, dropWrapper = this.dropWrapper;           
            var allCheckboxes = dropWrapper.find("input");
            if (options.firstItemChecksAll) {
                // if firstItemChecksAll is true, check all checkboxes if the first one is checked
                if (senderCheckbox.attr("index") == 0) {
                    allCheckboxes.attr("checked", senderCheckbox.attr("checked"));
                    if(allCheckboxes.attr("checked"))
                    {
                        dropWrapper.drop = true;
                        self._toggleDropContainer();
                        dropWrapper.drop = false;
                    }
                } else {
                    // check the first checkbox if all the other checkboxes are checked
                    var allChecked;
                    allChecked = true;
                    allCheckboxes.each(function(index) {
                        if (index > 0) {
                            var checked = jQuery(this).attr("checked");
                            if (!checked) allChecked = false;
                        }
                    });
                    var firstCheckbox = allCheckboxes.filter(":first");
                    firstCheckbox.attr("checked", false);
                    if (allChecked) {
                        firstCheckbox.attr("checked", true);
                        dropWrapper.drop = true;
                        self._toggleDropContainer();
                        dropWrapper.drop = false;
                    }
                }
            }

            // do the actual synch with the source select
            var selectOptions = sourceSelect.get(0).options;
            var anySelected = false;
            allCheckboxes.each(function(index) {
                jQuery(selectOptions[index]).attr("selected", jQuery(this).attr("checked"));
                if(jQuery(selectOptions[index]).attr("selected") == true)
                {
                    anySelected = true;
                }
            });

            // update the text shown in the control
            self._updateControlText();
            
            if(!anySelected)
            {
                self._setDefaultDisplay();
            }
        },
        // Updates the text shown in the control depending on the checked (selected) items
        _updateControlText: function() {
            var self = this, sourceSelect = this.sourceSelect, options = this.options, controlWrapper = this.controlWrapper, dropWrapper = this.dropWrapper;
            var firstSelect = sourceSelect.find("option:first");
            var allSelected = null != firstSelect && firstSelect.attr("selected");
            var selectOptions = sourceSelect.find("option");
            var text = self._formatText(selectOptions, options.firstItemChecksAll, allSelected);
            var controlLabel = controlWrapper.find(".ui-dropdownchecklist-text");
            var mySelected = sourceSelect.find("option:selected").length;
            if(mySelected > 1)
            {
                text = mySelected + "ホテル選択中（変更するにはここをクリック）";  
            }
            controlLabel.text(text);            
            controlLabel.attr("title", text);
        },
        // Formats the text that is shown in the control
        _formatText: function(selectOptions, firstItemChecksAll, allSelected) {
            var text;
            if (firstItemChecksAll && allSelected) {
                // just set the text from the first item
                text = selectOptions.filter(":first").text(); 
            } else {
                // concatenate the text from the checked items
                text = "";
                selectOptions.each(function() {
                    if (jQuery(this).attr("selected")) {
                        text += jQuery(this).text() + ", ";
                    }
                });
                if (text.length > 0) {
                    text = text.substring(0, text.length - 2);
                }
            }
            return text;
        },
        // Shows and hides the drop container
        _toggleDropContainer: function() {  
            var self = this, dropWrapper = this.dropWrapper, controlWrapper = this.controlWrapper;
            // hides the last shown drop container
            var hide = function() {  
                jQuery.idleTimer('destroy');  
                var instance = jQuery.ui.dropdownchecklist.drop;
                if (null != instance) {
                    instance.dropWrapper.css({
                        top: "-3300px",
                        left: "-3300px"
                    });
                    instance.controlWrapper.find(".ui-dropdownchecklist").toggleClass("ui-dropdownchecklist-active");
                    instance.dropWrapper.drop = false;
                    jQuery.ui.dropdownchecklist.drop = null;
                    jQuery(document).unbind("click", hide);           
                }                
            }
            // shows the given drop container instance
            var show = function(instance) {
                if (null != jQuery.ui.dropdownchecklist.drop) {
                    hide();
                }
                instance.dropWrapper.css({
                    top: instance.controlWrapper.offset().top + instance.controlWrapper.outerHeight() + "px",
                    left: instance.controlWrapper.offset().left + "px"
                })
                instance.controlWrapper.find(".ui-dropdownchecklist").toggleClass("ui-dropdownchecklist-active");
                instance.dropWrapper.drop = true;
                jQuery.ui.dropdownchecklist.drop = instance;
                jQuery(document).bind("click", hide);       
                jQuery.idleTimer(4000);  
                jQuery(document).bind("idle.idleTimer", hide);                      
            }
            if (dropWrapper.drop) {
                hide(self);          
            } else {
                show(self);
            }
        },
        // Set the size of the control and of the drop container
        _setSize: function(dropCalculatedSize) {
            var options = this.options, dropWrapper = this.dropWrapper, controlWrapper = this.controlWrapper;

            var controlWidth;
            // use the width from options if set, otherwise set the same width as the drop container
            if (options.width) {
                controlWidth = parseInt(options.width);
            } else {
                controlWidth = dropCalculatedSize.width;
                var minWidth = options.minWidth;
                // if the width is to small (usually when there are no items) set a minimum width
                if (controlWidth < minWidth) {
                    controlWidth = minWidth;
                }
            }
            controlWrapper.find(".ui-dropdownchecklist-text").css({
                width: controlWidth + "px"
            });

            // for the drop container get the actual (outer) width of the control. 
            // this can be different than the set one depening on paddings, borders etc set on the control
            var controlOuterWidth = controlWrapper.outerWidth();

            // the drop container height can be set from options
            var dropHeight = options.maxDropHeight ? parseInt(options.maxDropHeight) : dropCalculatedSize.height;
            // ensure the drop container is not less than the control width (would be ugly)
            var dropWidth = dropCalculatedSize.width < controlOuterWidth ? controlOuterWidth : dropCalculatedSize.width;

            jQuery(dropWrapper).css({
                width: dropWidth + "px",
                height: dropHeight + "px"
            });

            dropWrapper.find(".ui-dropdownchecklist-dropcontainer").css({
                height: dropHeight + "px"
            });
        },
        _setDefaultDisplay: function() {    
            var self = this, controlWrapper = this.controlWrapper, options = this.options;    
            var controlLabel = controlWrapper.find(".ui-dropdownchecklist-text");

            if(options.selectDefaultValue != null)
            {
                controlLabel.text(options.selectDefaultValue);
                controlLabel.attr("title", options.selectDefaultValue);    
            }
        },
        // Initializes the plugin
        _init: function() {
            var self = this, options = this.options;
			
            // sourceSelect is the select on which the plugin is applied
            var sourceSelect = self.element;
            self.initialDisplay = sourceSelect.css("display");
            sourceSelect.css("display", "none");
            self.initialMultiple = sourceSelect.attr("multiple");
            sourceSelect.attr("multiple", "multiple");
            self.sourceSelect = sourceSelect;

            // create the drop container where the items are shown
            var dropWrapper = self._appendDropContainer();
            self.dropWrapper = dropWrapper;
            
            // append the items from the source select element
            var dropCalculatedSize = self._appendItems();

            // append the control that resembles a single selection select
            var controlWrapper = self._appendControl();
            self.controlWrapper = controlWrapper;
            
            dropWrapper.find(".ui-dropdownchecklist-dropcontainer").hover(function() {
                //                                
            }, function(event) { 
               if (!self.disabled) {
                    event.stopPropagation();
                    dropWrapper.drop = true;
                    self._toggleDropContainer();
                    ////////////////////////////////////////////////////////////
                    if(self.sourceSelect.attr("id") == selectRegionId)
                    {
                        setHotels();                
                    }
                    //////////////////////////////////////////////////////////// 
                    dropWrapper.drop = false;
                }
            });
           
            // updates the text shown in the control
            self._updateControlText(controlWrapper, dropWrapper, sourceSelect);
            // set the sizes of control and drop container
            self._setSize(dropCalculatedSize);        
            
            var allCheckboxes = dropWrapper.find("input");            
            var selectOptions = sourceSelect.get(0).options;
            var anySelected = false;
            allCheckboxes.each(function(index) {
                jQuery(selectOptions[index]).attr("selected", jQuery(this).attr("checked"));
                if(jQuery(selectOptions[index]).attr("selected") == true)
                {
                    anySelected = true;
                }
            });
            
            if(options.showSelectDefault && !anySelected)
            {
                self._setDefaultDisplay();
            }

        },
        enable: function() {
            this.controlWrapper.find(".ui-dropdownchecklist").removeClass("ui-dropdownchecklist-disabled");
            this.disabled = false;
        },
        disable: function() {
            this.controlWrapper.find(".ui-dropdownchecklist").addClass("ui-dropdownchecklist-disabled");
            this.disabled = true;
        },
        destroy: function() {
            jQuery.widget.prototype.destroy.apply(this, arguments);
            this.sourceSelect.css("display", this.initialDisplay);
            this.sourceSelect.attr("multiple", this.initialMultiple);
            this.controlWrapper.unbind().remove();
            this.dropWrapper.remove();
        },
        toggle: function() {
            this._toggleDropContainer();
        },
        defaultDisplay: function() {
            this._setDefaultDisplay();
        }           
    });

    jQuery.extend(jQuery.ui.dropdownchecklist, {
        defaults: {
            width: null,
            maxDropHeight: null,
            firstItemChecksAll: false,
            minWidth: 50
        }
    });

})(jQuery);
