// NOTE: vntools.js requires prototype.js to already be loaded because of the use of the module pattern

/**
 * From now on, namespace all JavaScript as part of the VIANET object
 */
VIANET = $H({});

/**
 * Constants used across scripts accessible within the VIANET namespace
 */
VIANET.constants = {
    // event handlers
    CLICK       : 'click',
    MOUSEUP     : 'mouseup',
    MOUSEOUT    : 'mouseout',
    MOUSEOVER   : 'mouseover',
    MOUSEDOWN   : 'mousedown',
    MOUSEMOVE   : 'mousemove',
    DRAGSTART   : 'dragstart',
    // HTML tags
    DIV         : 'DIV',
    INPUT       : 'INPUT',
    LABEL       : 'LABEL',
    OPTION      : 'OPTION',
    // input types
    CHECKBOX    : 'checkbox',
    TEXT		: 'text',
    // misc
    HI          : '_hi.',
    PX          : 'px',
    LEFT        : 'left',
    NEXT        : 'next',
    PREVIOUS    : 'previous',
    DASH        : '-',
    SLASH       : '/',
    VIANET_URL	: 'vianet.travel'
};

/**
 * Functions for common GUI manipulations
 *
 * @method  selectCheckboxes  Set a collection of checkboxes to either checked or unchecked
 * @method  focusDelayed      Set focus on a form field after a specified delay
 */
VIANET.guiUtils = (function () {
    // private vars
    var _tmpls;
    _tmpls = {
        inputSelector : new Template('#{element} input[type="#{type}"]')
    };

    return {
        isIE: (function () {
            return (document.all && !window.opera);
        })(),
        isSafari: (function () {
            return (navigator.userAgent.indexOf('Safari') > -1);
        })(),
        isOpera: (function () {
            return ('undefined' !== typeof window.opera);
        })(),
        /**
         * Used for select all / select none links
         *
         * @param  string   selector  CSS selector pointing to the checkboxes
         * @param  boolean  checked   Value for whether to check or uncheck the checkboxes
         */
        selectCheckboxes: function (container, checked) {
            $$(container).each(function (checkbox) {
                checkbox.checked = checked;
            });
        },
        /**
         * Used to retrieve all the input by type of a given container/element
         *
         * @param string	container	CSS selector containing inputs to scan
         * @param string	type		Type of input to return, eg checkbox, button, password
         */
         selectInputsByType: function (container, type) {
            return $$(_tmpls.inputSelector.evaluate({element: container, type: type}));
         },
         /**
         * Used to set the value of input fields by type in a given container/element
         *
         * @param string	container	CSS selector containing inputs to scan
         * @param string	type		Type of input to return, eg checkbox, button, password
         * @param string	value		Value to assign to returned inputs
         */
         setInputValue: function (container, type, value) {
             var _inputs = VIANET.guiUtils.selectInputsByType(container, type);
             _inputs.each(function (input) {
                 input.value = value;
             });
         },
        /**
         * Set focus on a form field after a specified delay
         * This is useful when you want to set focus after a visual effect such as a blind down
         *
         * @param  string  fieldId  DOM ID for the form field on which you want to set focus
         * @param  int     delay    Length of time, in miliseconds, to wait before setting focus
         */
        focusDelayed: function (fieldId, delay) {
            setTimeout(function () {
                $(fieldId).focus();
                $(fieldId).select();
            }, delay);
        },
        /**
        * Pop-up a new window in a standard way and set focus on the new window
        * Usage: <a href="myurl.html" onclick="TRAVELBUG.guiUtils.popup(this.href, 'myWindow');return false;">
        */
        popup: function (url, windowName, popupParams) {
            var newWindow;
            popupParams = popupParams || 'location=no,toolbar=no,menubar=no,resizeable=no,width=600,height=500,left=100,top=0';
            newWindow = window.open(url, windowName, popupParams);
            if (window.focus) {
                newWindow.focus();
            }
            return false;
        },
        /**
        * Add an option to a select list
        *
        * @param object selObj DOM object of the select list we want to update
        * @param string value  Value to which to set the option
        * @param string text   Visible label for the option tag
        */
        addOption: function (selObj, value, text) {
            var option;
            option = document.createElement(VIANET.constants.OPTION);
            selObj.appendChild(option);
            option.value = value;
            option.text = text;
        }
    };
})();

/**
 * Manage logo slideshow on the Vianet homepage
 */
with ({
        // "Constants" within this object's scope
        IN       : 'in',
        OUT      : 'out',
        DURATION : 1000 // duration (in milliseconds) of fades
    }) {
    VIANET.logoShow = (function () {
        // private variables
        var _ids, _idx, _a, _as, _styleTemplate, _container, _logos;
        _ids   = $A(['homepage-logo-0', 'homepage-logo-1', 'homepage-logo-2']);
        _idx   = -1;
        _logo  =  2;
        _a = (function () {
            var a;
            a           = document.createElement('A');
            a.className = 'homepage-logo';
            return a;
        })();
        _as = $A([]);
        // private methods
        var _preloadImages, _setLinkProperties, _doFade, _next, _startShow;
        _preloadImages = function () {
            _logos.each(function (logo) {
                var img;
                img     = new Image();
                img.src = logo.imageSource;
            });
        };
        _setLinkProperties = function (a, props) {
            a.style.backgroundImage    = 'url(' + props.imageSource + ')';
            a.href = props.imageLink;
        };
        _doFade = function (img, dir) {
            var from, to;
            from = (IN === dir)? 0 : 1;
            to   = (IN === dir)? 1 : 0;
            img.fader.seekFromTo(from, to);
        };
        _next = function () {
            // advance counters
            ++_idx;
            if (_idx > _ids.length - 1)    _idx = 0;
            ++_logo;
            if (_logo > _logos.length - 1) _logo = 0;
            // fade out current image
            _doFade(_as[_idx], OUT);
            // change background image
            setTimeout(function () {
                _setLinkProperties(_as[_idx], _logos[_logo]);
            }, DURATION);
            // fade image back in
            setTimeout(function () {
                _doFade(_as[_idx], IN);
            }, DURATION * 2);
        };
        _startShow = function () {
            _ids.each(function (id) {
                var a;
                a       = _a.cloneNode(true);
                a.id    = id;
                a.target = "_blank";
                a.fader = new Animator({duration: DURATION}).addSubject(new NumericalStyleSubject(a, 'opacity', 0.0, 1.0));
                _setLinkProperties(a, _logos[_as.length]);

                _as.push(a);
                _container.appendChild(a);
            });
            // fade in the first three in quick succession
            setTimeout(function () {
                _doFade(_as[0], IN);
            }, 0);
            setTimeout(function () {
                _doFade(_as[1], IN);
            }, DURATION);
            setTimeout(function () {
                _doFade(_as[2], IN);
            }, DURATION * 2);
            // start rotating fades
            setTimeout(function () {
                setInterval(function () {
                    _next();
                }, DURATION * 2.1);
            }, DURATION * 3);
        };
        // public methods
        return {
            /**
             * Initialise the logo slideshow on the Vianet.travel homepage
             * @param array logos Array of logo image sources
             */
            init: function (logos) {
                _container = $('homepage-logos');
                _logos     = $A(logos) || [];
                if (_logos.length > 0) {
                    _preloadImages();
                    _startShow();
                }
            }
        };
    })();
};

function getParameter ( queryString, parameterName ) {
    var parameterName = parameterName + "=";
    if ( queryString.toString().length > 0 ) {
        begin = queryString.indexOf( parameterName );
        if ( begin != -1 ) {
            begin += parameterName.length;
            end = queryString.indexOf( "&" , begin );
            if ( end == -1 ) {
                end = queryString.length
            }
            return unescape ( queryString.substring ( begin, end ) );
        }
        return "null";
    }
}

function getNodeValue(obj,tag)
{
    return obj.getElementsByTagName(tag)[0].firstChild.nodeValue;
}
function applyPNGFilter(o)
{
    var arVersion = navigator.appVersion.split("MSIE")
    var version = parseFloat(arVersion[1])

    if ((version >= 5.5) && (document.body.filters)) {
        var t='http://www.vianet.travel/images/a_pixel.gif';
        if( o.src != t ) {
            var s=o.src;
            o.src = t;
            o.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+s+"',sizingMethod='scale')";
        }
    }
}
function isIE4(){

    return false;
}

function changeFocus(currentFocus, nextFocus, e) {
        realkey = new String(String.fromCharCode(e));
        asciiVal = realkey.charCodeAt();
        if (currentFocus.value.length == currentFocus.maxLength && asciiVal > 47 && asciiVal < 123) {
            nextFocus.focus();
        }
    }

function vn_update_date_from_inputs(input_element){
    month_value = $F(input_element+'_month');
    date_value =  $F(input_element+'_day') + '/' + month_value + '/' + $F(input_element+'_year') ;
    $(input_element).value = date_value;
}

function vn_update_inputs_from_date(input_element, date_value, fmt){
    var tmp = new Date(Date.parseDate(date_value, fmt));
    $(input_element+'_day').value = tmp.getDate();
    if($(input_element+'_month').options){
        $(input_element+'_month').options[tmp.getMonth()].selected = true
    }else{
        $(input_element+'_month').value = tmp.getMonth();
    }
    $(input_element+'_year').value = tmp.getFullYear();

}

function vn_update_start_and_finish_dates(start_date, finish_date, date_value, days, fmt)
{
    vn_update_inputs_from_date(start_date, date_value, fmt);
    increment_finish_date(days, fmt)

}

function increment_finish_date(days, fmt){
    //check for month rollovers.
    if (days ==''){
        days = 0
    }
    var tmp = new Date(Date.parseDate($('start_date').value, fmt));
    var finishtmp = new Date(Date.parseDate($('finish_date').value, fmt));
    tmp.setDate(tmp.getDate()+parseInt(days)+1);
    $('finish_date').value = tmp.getDate()+'/'+(tmp.getMonth()+1)+'/'+tmp.getFullYear();
    vn_update_inputs_from_date('finish_date', $('finish_date').value, fmt);
}
function getURI() {
      var uri = location.href;
      if (uri.indexOf('?') != -1)  return uri.substring(0,uri.indexOf('?'));
      return uri;
}
function goToLocation(obj) {
  var form = obj;
  uri = '/location/';
  if (!form || !form.location_id) return;

  selected = form.location_id.selectedIndex;
  if (selected < 0) selected = 0;

  var lid = form.location_id[selected].value;
  if (lid < 1) return;
  location.href = uri;
  uri = uri.substring(0,uri.lastIndexOf('/')+1);
  document.location.href = uri+lid;
}

// Define the object literal store for districts
VIANET.retailer = {};
/**
 * Create a VIANET.Retailer namespace
 *
*/
VIANET.retailer.searchwidget = (function () {
    // private vars
    _displaySection = $H({});

    // private methods
    var _updateDistrictSelect, _updateDisplaySections, _updateWidgetSource
    /**
    * Manage regions / districts drop-down menus (requires VIANET.retailer.districtsAndRegions to be set inline on the page)
    */
    _updateDistrictSelect = function () {
            var region, selObj;
            region = $F('region');

            // Check the current region - only update districts if different
            if(region !== VIANET.retailer.searchwidget.currentRegion) {
                if ('none' === region) {
                    region = '';
                    $('region').selectedIndex = 0;
                }
                selObj = $('district');
                // blow away current district options
                selObj.options.length = 0;
                VIANET.guiUtils.addOption(selObj, '', 'Select district');
                VIANET.guiUtils.addOption(selObj, 'none', '');
                if (region === 'none' || region === '' || region === '0') {
                    selObj.disabled = true;
                    // Remove the current region from browser store
                    VIANET.retailer.searchwidget.currentRegion = undefined;
                } else {
                   selObj.disabled = false;
                    // Set the current region into browser store
                   VIANET.retailer.searchwidget.currentRegion = region;
                   // add new district options
                   for (var district in VIANET.retailer.districtsAndRegions[region]) {
                       VIANET.guiUtils.addOption(selObj, district, VIANET.retailer.districtsAndRegions[region][district]);
                   }
                }
           }
    };

    /*
     * Toggle the display styles from section checkboxes
     *
    */
    _updateDisplaySections = function () {
        var _displayCheckboxes, _currentSection, _regionValue;
        _displayCheckboxes = VIANET.guiUtils.selectInputsByType('div.col-display', VIANET.constants.CHECKBOX); // return all checkboxs of given container
        _displayCheckboxes.each(function (checkbox) {
            if(checkbox.checked) { 	// Ensure the disabled CSS style is not applied to checked container
                _currentSection = checkbox.identify().sub('display-', '');
                $((_currentSection + '-container')).removeClassName('no-option-display');
                // Set the displayed sections
                _displaySection.set(_currentSection, true);
            }
            else {
                if(checkbox.identify() == 'display-region') {
                    // validate that there is a region set
                    _regionValue = $('region').getValue();
                    if (_regionValue === 'none' || _regionValue === '' || _regionValue === '0') {
                        checkbox.checked = true;
                        _currentSection = checkbox.identify().sub('display-', '');
                        $((_currentSection + '-container')).removeClassName('no-option-display');
                        // Set the displayed sections
                        _displaySection.set(_currentSection, true);
                        alert('You must display the Region and District options if no default Region has been selected.');
                    }
                    else {
                        _currentSection = checkbox.identify().sub('display-', '');
                        $((_currentSection + '-container')).addClassName('no-option-display');
                        // Set the displayed sections
                        _displaySection.set(_currentSection, false);
                    }
                }
                else {
                    _currentSection = checkbox.identify().sub('display-', '');
                    $((_currentSection + '-container')).addClassName('no-option-display');
                    // Set the displayed sections
                    _displaySection.set(_currentSection, false);
                }
            }
        });
    };

    /*
     * Set the source code for the textarea tag
     *
    */
    _updateWidgetSource = function () {
        var _district, _url, _iframeHeight, _iframeWidth, _panelHeights, _iframeSource, _completeSource, _openSource, _querySource, _sectionSource, _closeSource;
        var _startDate, _endDate, _dateFormat, _subcats, _capacity, _rateLower, _rateUpper, _keywords, _defaultErrorMessage, _rgxp, _matches;

        _iframeHeight = 110; // Set an initial value and add sections as required
        _iframeWidth = 280;
        _panelHeights = $H({
            'region' 	: 45,
            'dates'   	: 55,
            'subcats' 	: 200,
            'capacity' 	: 35,
            'rates'		: 55,
            'keywords' 	: 35
        });

        // Only try to render the sample code if there is a region value set
        if(VIANET.retailer.searchwidget.currentRegion || $('display-region').checked) {
            //Build the sections part of the source text
            _sectionSource = '&sections=';
            _displaySection.each(function (section) {
                if(section.value) {
                    // If the current section is region, then add the district section also
                    (section.key == 'region') ? _sectionSource += section.key +  ',district,' : _sectionSource += section.key +  ',' ;

                    // Dynamically calculate the height by the number of sections requested
                    _iframeHeight += _panelHeights.get(section.key);
                }
            });

            // Upper & lower rate bounds are always set - use this to set query params order ? &
            _rateLower = $F('accom_rate_lower');
            _rateUpper = $F('accom_rate_upper');

            // Check user supplied url - if none given, use Vianet
            _url = $F('retailer-url-name').gsub(' ', '').toLowerCase();
            if(_url) {
                 _url = _url.replace(/[^a-z,0-9,\-,_,.]/g, ''); // Keep _.,-'s and alphanumerics on the lowercase string
            }
            (_url) ? _url = _url + '.' + VIANET.constants.VIANET_URL : _url = 'www.' + VIANET.constants.VIANET_URL;

            _openSource = '<iframe width="' + _iframeWidth + '" height="' + _iframeHeight + '" src="http://' + _url + '/search/searchcardForm';
            //Build the query source code
            //Set the region param to the currentRegion if set, else leave blank
            if(VIANET.retailer.searchwidget.currentRegion) {
                _querySource = '?region=' + VIANET.retailer.searchwidget.currentRegion.gsub(' ', '+');
                _district = $F('district');
                (_district) ? _querySource += '&district=' + _district.gsub(' ', '+') : '';
                _querySource += '&rate_lower=' + _rateLower + '&rate_upper=' + _rateUpper;
            }
            else {
                _querySource = '?rate_lower=' + _rateLower + '&rate_upper=' + _rateUpper;
            }

            _startDate = encodeURIComponent($F('avail_start_date'));
            _endDate = encodeURIComponent($F('avail_finish_date'));
            _dateFormat = '&iso8601_date_format=d%2FMM%2Fyy';
            _querySource += '&avail_start_date=' + _startDate + '&avail_finish_date=' + _endDate + _dateFormat;

            _subcats = VIANET.guiUtils.selectInputsByType('#subcats-container div.col-select', VIANET.constants.CHECKBOX);
            _subcats.each(function (subcat) {
                if(subcat.checked) {
                    _querySource += '&product_subcat[]=' + subcat.identify();
                }
            });

            _capacity = $F('capacity');
            if(_capacity) {
                _querySource += '&capacity=' + _capacity;
            }

            _keywords = $F('keyword');
            if(_keywords) {
                _querySource += '&keywords=' + _keywords.gsub(' ', '+');
            }

            _closeSource = '"></iframe>';

            // Join tags & escape html
            _iframeSource = 'http://' + _url + '/search/searchcardForm' + _querySource + _sectionSource.truncate(_sectionSource.length - 1, '');
            _completeSource = (_openSource + _querySource + _sectionSource.truncate(_sectionSource.length - 1, '') + _closeSource).escapeHTML();

            // Update the text area sample, set iframe source, hide error message
            $('source-text').update(_completeSource);
            $('widget-code-preview').writeAttribute('src', _iframeSource);
            $('widget-code-preview').writeAttribute('height', _iframeHeight);
            $('widget-code-preview').writeAttribute('width', _iframeWidth);
        }
    };

    // public variables and methods
    return {
        init: function () {
            _updateDistrictSelect();
            _updateDisplaySections();
            _updateWidgetSource();
        },
        updateDistrictSelect: function () {
            _updateDistrictSelect();
        }
    };
})();

function updateDistricts () {
    function addOption (value, text) {
        var option = document.createElement("OPTION");
        selObj.appendChild(option);
        option.value = value;
        option.text = text;
    }
    var region = $F("region_id").toString();
    var selObj = $("district_id");
    // blow away current district options
    selObj.options.length = 0;

    addOption("none", "Select District");
    addOption("none", "");
    if (region == "none" || region == "") {
        selObj.disabled = true;
    } else {
        selObj.disabled = false;
        // add new district options
        for (var district in districts_json[region]) {
            addOption(district, districts_json[region][district]);
        }
    }
}

function rollover(id, image)
{
    $(id).src = image;
}

function calendarResize() {
    eTitle = $('product-details-column');
    adjustment = eTitle.getDimensions().width ;
    $("overflow").style.width=869 - adjustment + "px"; // Was 872px - changed to 869 to fix the FF issues of vertical white lines on scroll
}

/**
 * Debugging functions
 */
var DEBUG = (function () {
    var _defaultHTML, _init, _defaultCSS;
    _defaultHTML = '<a href="#" onclick="DEBUG.clear();return false;">Clear</a><hr/>';
    _defaultCSS = {
        position: "absolute",
        top: "10px",
        right: "10px",
        width: "400px",
        border: "solid 1px black",
        background: "#ccc",
        padding: "10px",
        font: "11px/1.2em verdana",
        textAlign: "left"
    };
    _init = function () {
        var debugDiv;
        debugDiv = document.getElementById('debug');
        if (!debugDiv) {
            debugDiv    = document.createElement('DIV');
            debugDiv.id = 'debug';
            for (var prop in _defaultCSS) {
                debugDiv.style[prop] = _defaultCSS[prop];
            }
            document.body.insertBefore(debugDiv, document.body.firstChild);
            DEBUG.clear();
        }
    };
    return $H({
        writeDebug: function (s) {
            _init();
            document.getElementById('debug').innerHTML += s + '<br />';
        },
        revealObject: function (obj) {
            for (prop in obj) {
                if ('function' !== typeof obj[prop]) {
                    this.writeDebug(prop + ': ' + obj[prop]);
                }
            }
        },
        clear: function () {
            document.getElementById('debug').innerHTML = _defaultHTML;
        }
    });
})();

function formatBCCell ( cell ) {
    if (cell.value.toUpperCase() == 'R')
    {
        cell.className = 'inventory confirmation';cell.className = 'inventory confirmation';
        cell.value = 'R';
    }
    else if (cell.value == '0' || !parseInt(cell.value) || parseInt(cell.value) < 0)
    {
        cell.value = '-';
        cell.className = 'inventory inventory-unavailable';
    }
    else if (cell.value > 999)
    {
        cell.value = 999;
    }
    else
    {
        cell.value = parseInt(cell.value);
        cell.className = 'inventory inventory-available'
    };
}