/*
 * Autocomplete - jQuery plugin 1.0.2
 *
 * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.autocomplete.js 5747 2008-06-25 18:30:55Z joern.zaefferer $
 *
 */

(function($) {

    $.fn.extend({
        autocomplete: function(urlOrData, options) {
            var isUrl = typeof urlOrData == "string";
            options = $.extend({}, $.Autocompleter.defaults, {
                url: isUrl ? urlOrData : null,
                data: isUrl ? null : urlOrData,
                delay: isUrl ? $.Autocompleter.defaults.delay : 10,
                max: options && !options.scroll ? 10 : 150
            }, options);

            // if highlight is set to false, replace it with a do-nothing function
            options.highlight = options.highlight || function(value) { return value; };

            // if the formatMatch option is not specified, then use formatItem for backwards compatibility
            options.formatMatch = options.formatMatch || options.formatItem;

            return this.each(function() {
                new $.Autocompleter(this, options);
            });
        },
        result: function(handler) {
            return this.bind("result", handler);
        },
        search: function(handler) {
            return this.trigger("search", [handler]);
        },
        flushCache: function() {
            return this.trigger("flushCache");
        },
        setOptions: function(options) {
            return this.trigger("setOptions", [options]);
        },
        unautocomplete: function() {
            return this.trigger("unautocomplete");
        }
    });

    $.Autocompleter = function(input, options) {

        var KEY = {
            UP: 38,
            DOWN: 40,
            DEL: 46,
            TAB: 9,
            RETURN: 13,
            ESC: 27,
            COMMA: 188,
            PAGEUP: 33,
            PAGEDOWN: 34,
            BACKSPACE: 8
        };

        // Create $ object for input element
        var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);

        var timeout;
        var previousValue = "";
        var cache = $.Autocompleter.Cache(options);
        var hasFocus = 0;
        var lastKeyPressCode;
        var config = {
            mouseDownOnSelect: false
        };
        var select = $.Autocompleter.Select(options, input, selectCurrent, config);

        var blockSubmit;

        // prevent form submit in opera when selecting with return key
        $.browser.opera && $(input.form).bind("submit.autocomplete", function() {
            if (blockSubmit) {
                blockSubmit = false;
                return false;
            }
        });

        // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
        $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
            // track last key pressed
            lastKeyPressCode = event.keyCode;
            switch (event.keyCode) {

                case KEY.UP:
                    event.preventDefault();
                    if (select.visible()) {
                        select.prev();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.DOWN:
                    event.preventDefault();
                    if (select.visible()) {
                        select.next();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.PAGEUP:
                    event.preventDefault();
                    if (select.visible()) {
                        select.pageUp();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.PAGEDOWN:
                    event.preventDefault();
                    if (select.visible()) {
                        select.pageDown();
                    } else {
                        onChange(0, true);
                    }
                    break;

                // matches also semicolon           
                case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
                case KEY.TAB:
                case KEY.RETURN:
                    if (selectCurrent()) {
                        // stop default to prevent a form submit, Opera needs special handling
                        event.preventDefault();
                        blockSubmit = true;
                        return false;
                    }
                    break;

                case KEY.ESC:
                    select.hide();
                    break;

                default:
                    clearTimeout(timeout);
                    timeout = setTimeout(onChange, options.delay);
                    break;
            }
        }).focus(function() {
            // track whether the field has focus, we shouldn't process any
            // results if the field no longer has focus
            hasFocus++;
        }).blur(function() {
            hasFocus = 0;
            if (!config.mouseDownOnSelect) {
                hideResults();
            }
        }).click(function() {
            // show select when clicking in a focused field
            if (hasFocus++ > 1 && !select.visible()) {
                onChange(0, true);
            }
        }).bind("search", function() {
            // TODO why not just specifying both arguments?
            var fn = (arguments.length > 1) ? arguments[1] : null;
            function findValueCallback(q, data) {
                var result;
                if (data && data.length) {
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].result.toLowerCase() == q.toLowerCase()) {
                            result = data[i];
                            break;
                        }
                    }
                }
                if (typeof fn == "function") fn(result);
                else $input.trigger("result", result && [result.data, result.value]);
            }
            $.each(trimWords($input.val()), function(i, value) {
                request(value, findValueCallback, findValueCallback);
            });
        }).bind("flushCache", function() {
            cache.flush();
        }).bind("setOptions", function() {
            $.extend(options, arguments[1]);
            // if we've updated the data, repopulate
            if ("data" in arguments[1])
                cache.populate();
        }).bind("unautocomplete", function() {
            select.unbind();
            $input.unbind();
            $(input.form).unbind(".autocomplete");
        });


        function selectCurrent() {
            var selected = select.selected();
            if (!selected)
                return false;

            var v = selected.result;
            previousValue = v;

            if (options.multiple) {
                var words = trimWords($input.val());
                if (words.length > 1) {
                    v = words.slice(0, words.length - 1).join(options.multipleSeparator) + options.multipleSeparator + v;
                }
                v += options.multipleSeparator;
            }

            $input.val(v);
            hideResultsNow();
            $input.trigger("result", [selected.data, selected.value]);
            return true;
        }

        function onChange(crap, skipPrevCheck) {
            if (lastKeyPressCode == KEY.DEL) {
                select.hide();
                return;
            }

            var currentValue = $input.val();

            if (!skipPrevCheck && currentValue == previousValue)
                return;

            previousValue = currentValue;

            currentValue = lastWord(currentValue);
            if (currentValue.length >= options.minChars) {
                $input.addClass(options.loadingClass);
                $input.next().show();
                if (!options.matchCase)
                    currentValue = currentValue.toLowerCase();
                request(currentValue, receiveData, hideResultsNow);
            } else {
                stopLoading();
                select.hide();
            }
        };

        function trimWords(value) {
            if (!value) {
                return [""];
            }
            var words = value.split(options.multipleSeparator);
            var result = [];
            $.each(words, function(i, value) {
                if ($.trim(value))
                    result[i] = $.trim(value);
            });
            return result;
        }

        function lastWord(value) {
            if (!options.multiple)
                return value;
            var words = trimWords(value);
            return words[words.length - 1];
        }

        // fills in the input box w/the first match (assumed to be the best match)
        // q: the term entered
        // sValue: the first matching result
        function autoFill(q, sValue) {
            // autofill in the complete box w/the first match as long as the user hasn't entered in more data
            // if the last user key pressed was backspace, don't autofill
            if (options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE) {
                // fill in the value (keep the case the user has typed)
                $input.val($input.val() + sValue.substring(lastWord(previousValue).length));
                // select the portion of the value not typed by the user (so the next character will erase)
                $.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length);
            }
        };

        function hideResults() {
            clearTimeout(timeout);
            timeout = setTimeout(hideResultsNow, 200);
        };

        function hideResultsNow() {
            var wasVisible = select.visible();
            select.hide();
            clearTimeout(timeout);
            stopLoading();
            if (options.mustMatch) {
                // call search and run callback
                $input.search(
				function(result) {
				    // if no value found, clear the input box
				    if (!result) {
				        if (options.multiple) {
				            var words = trimWords($input.val()).slice(0, -1);
				            $input.val(words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : ""));
				        }
				        else
				            $input.val("");
				    }
				}
			);
            }
            if (wasVisible)
            // position cursor at end of input field
                $.Autocompleter.Selection(input, input.value.length, input.value.length);
        };

        function receiveData(q, data) {
            if (data && data.length && hasFocus) {
                stopLoading();
                select.display(data, q);
                autoFill(q, data[0].value);
                select.show();
            } else {
                hideResultsNow();
            }
        };

        function request(term, success, failure) {
            if (!options.matchCase)
                term = term.toLowerCase();
            var data = cache.load(term);
            // recieve the cached data
            if (data && data.length) {
                success(term, data);
                // if an AJAX url has been supplied, try loading the data now
            } else if ((typeof options.url == "string") && (options.url.length > 0)) {

                var extraParams = {
                    timestamp: +new Date()
                };
                $.each(options.extraParams, function(key, param) {
                    extraParams[key] = typeof param == "function" ? param() : param;
                });

                $.ajax({
                    // try to leverage ajaxQueue plugin to abort previous requests
                    mode: "abort",
                    // limit abortion to this input
                    port: "autocomplete" + input.name,
                    dataType: options.dataType,
                    url: options.url,
                    data: $.extend({
                        q: lastWord(term),
                        limit: options.max
                    }, extraParams),
                    success: function(data) {

                        var parsed = options.parse && options.parse(data) || parse(data);
                        cache.add(term, parsed);
                        success(term, parsed);
                    }
                });
            } else {
                // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
                select.emptyList();
                failure(term);
            }
        };

        function parse(data) {
            var parsed = [];
            var rows = data.split("\n");
            for (var i = 0; i < rows.length; i++) {
                var row = $.trim(rows[i]);
                if (row) {
                    row = row.split("|");
                    parsed[parsed.length] = {
                        data: row,
                        value: row[0],
                        result: options.formatResult && options.formatResult(row, row[0]) || row[0]
                    };
                }
            }
            return parsed;
        };

        function stopLoading() {
            $input.removeClass(options.loadingClass);
            $input.next().hide();
        };

    };

    $.Autocompleter.defaults = {
        inputClass: "forminputlarge",
        resultsClass: "ac_results",
        loadingClass: "ac_loading",
        minChars: 1,
        delay: 400,
        matchCase: false,
        matchSubset: true,
        matchContains: false,
        cacheLength: 10,
        max: 100,
        mustMatch: false,
        extraParams: {},
        selectFirst: true,
        formatItem: function(row) { return row[0]; },
        formatMatch: null,
        autoFill: false,
        width: 0,
        multiple: false,
        multipleSeparator: ", ",
        highlight: function(value, term) {
            return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
        },
        scroll: true,
        scrollHeight: 250
    };

    $.Autocompleter.Cache = function(options) {

        var data = {};
        var length = 0;

        function matchSubset(s, sub) {
            if (!options.matchCase)
                s = s.toLowerCase();
            var i = s.indexOf(sub);
            if (i == -1) return false;
            return i == 0 || options.matchContains;
        };

        function add(q, value) {
            if (length > options.cacheLength) {
                flush();
            }
            if (!data[q]) {
                length++;
            }
            data[q] = value;
        }

        function populate() {
            if (!options.data) return false;
            // track the matches
            var stMatchSets = {},
			nullData = 0;

            // no url was specified, we need to adjust the cache length to make sure it fits the local data store
            if (!options.url) options.cacheLength = 1;

            // track all options for minChars = 0
            stMatchSets[""] = [];
            // loop through the array and create a lookup structure
            for (var i = 0, ol = options.data.length; i < ol; i++) {
                var rawValue = options.data[i];
                // if rawValue is a string, make an array otherwise just reference the array
                rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;

                var value = options.formatMatch(rawValue, i + 1, options.data.length);
                if (value === false)
                    continue;

                var firstChar = value.charAt(0).toLowerCase();
                // if no lookup array for this character exists, look it up now
                if (!stMatchSets[firstChar])
                    stMatchSets[firstChar] = [];

                // if the match is a string
                var row = {
                    value: value,
                    data: rawValue,
                    result: options.formatResult && options.formatResult(rawValue) || value
                };

                // push the current match into the set list
                stMatchSets[firstChar].push(row);

                // keep track of minChars zero items
                if (nullData++ < options.max) {
                    stMatchSets[""].push(row);
                }
            };

            // add the data items to the cache
            $.each(stMatchSets, function(i, value) {
                // increase the cache size
                options.cacheLength++;
                // add to the cache
                add(i, value);
            });
        }

        // populate any existing data
        setTimeout(populate, 25);

        function flush() {
            data = {};
            length = 0;
        }

        return {
            flush: flush,
            add: add,
            populate: populate,
            load: function(q) {
                if (!options.cacheLength || !length)
                    return null;
                /* 
                * if dealing w/local data and matchContains than we must make sure
                * to loop through all the data collections looking for matches
                */
                if (!options.url && options.matchContains) {
                    // track all matches
                    var csub = [];
                    // loop through all the data grids for matches
                    for (var k in data) {
                        // don't search through the stMatchSets[""] (minChars: 0) cache
                        // this prevents duplicates
                        if (k.length > 0) {
                            var c = data[k];
                            $.each(c, function(i, x) {
                                // if we've got a match, add it to the array
                                if (matchSubset(x.value, q)) {
                                    csub.push(x);
                                }
                            });
                        }
                    }
                    return csub;
                } else
                // if the exact item exists, use it
                    if (data[q]) {
                    return data[q];
                } else
                    if (options.matchSubset) {
                    for (var i = q.length - 1; i >= options.minChars; i--) {
                        var c = data[q.substr(0, i)];
                        if (c) {
                            var csub = [];
                            $.each(c, function(i, x) {
                                if (matchSubset(x.value, q)) {
                                    csub[csub.length] = x;
                                }
                            });
                            return csub;
                        }
                    }
                }
                return null;
            }
        };
    };

    $.Autocompleter.Select = function(options, input, select, config) {
        var CLASSES = {
            ACTIVE: "ac_over"
        };

        var listItems,
		active = -1,
		data,
		term = "",
		needsInit = true,
		element,
		list;

        // Create results
        function init() {
            if (!needsInit)
                return;
            element = $("<div/>")
		.hide()
		.addClass(options.resultsClass)
		.attr("id", "ac_results")
		.css("position", "absolute")
		.appendTo(document.body);

            list = $("<ul/>").appendTo(element).mouseover(function(event) {
                if (target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
                    active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
                    $(target(event)).addClass(CLASSES.ACTIVE);
                }
            }).click(function(event) {
                $(target(event)).addClass(CLASSES.ACTIVE);
                select();
                // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
                input.focus();
                return false;
            }).mousedown(function() {
                config.mouseDownOnSelect = true;
            }).mouseup(function() {
                config.mouseDownOnSelect = false;
            });

            if (options.width > 0)
                element.css("width", options.width);

            needsInit = false;
        }

        function target(event) {
            var element = event.target;
            while (element && element.tagName != "LI")
                element = element.parentNode;
            // more fun with IE, sometimes event.target is empty, just ignore it then
            if (!element)
                return [];
            return element;
        }

        function moveSelect(step) {
            listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
            movePosition(step);
            var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
            if (options.scroll) {
                var offset = 0;
                listItems.slice(0, active).each(function() {
                    offset += this.offsetHeight;
                });
                if ((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                    list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
                } else if (offset < list.scrollTop()) {
                    list.scrollTop(offset);
                }
            }
        };

        function movePosition(step) {
            active += step;
            if (active < 0) {
                active = listItems.size() - 1;
            } else if (active >= listItems.size()) {
                active = 0;
            }
        }

        function limitNumberOfItems(available) {
            return options.max && options.max < available
			? options.max
			: available;
        }

        function fillList() {
            list.empty();
            var max = limitNumberOfItems(data.length);
            for (var i = 0; i < max; i++) {
                if (!data[i])
                    continue;
                var formatted = options.formatItem(data[i].data, i + 1, max, data[i].value, term);
                if (formatted === false)
                    continue;
                var li = $("<li/>").html(options.highlight(formatted, term)).addClass(i % 2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
                $.data(li, "ac_data", data[i]);
            }
            listItems = list.find("li");


            if (options.selectFirst) {
                listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
                active = 0;
            }

            // apply bgiframe if available
            if ($.fn.bgiframe)
                list.bgiframe();
        }

        return {
            display: function(d, q) {
                init();
                data = d;
                term = q;
                fillList();
            },
            next: function() {
                moveSelect(1);
            },
            prev: function() {
                moveSelect(-1);
            },
            pageUp: function() {
                if (active != 0 && active - 8 < 0) {
                    moveSelect(-active);
                } else {
                    moveSelect(-8);
                }
            },
            pageDown: function() {
                if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
                    moveSelect(listItems.size() - 1 - active);
                } else {
                    moveSelect(8);
                }
            },
            hide: function() {
                element && element.hide();
                listItems && listItems.removeClass(CLASSES.ACTIVE);
                active = -1;
            },
            visible: function() {
                return element && element.is(":visible");
            },
            current: function() {
                return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
            },
            show: function() {
                var offset = $(input).offset();
                if ($.browser.msie) {
                    element.css({
                        width: $(input).width(),
                        top: offset.top + input.offsetHeight,
                        left: offset.left
                    }).show();
                }
                else {
                    element.css({
                        width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
                        top: offset.top + input.offsetHeight,
                        left: offset.left
                    }).show();
                }
                if (options.scroll) {
                    list.scrollTop(0);
                    list.css({
                        maxHeight: options.scrollHeight,
                        overflow: 'auto'
                    });

                    if ($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
                        var listHeight = 0;
                        listItems.each(function() {
                            listHeight += this.offsetHeight;
                        });
                        var scrollbarsVisible = listHeight > options.scrollHeight;
                        list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight);
                        if (!scrollbarsVisible) {
                            // IE doesn't recalculate width when scrollbar disappears
                            listItems.width(list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")));
                        }
                    }

                }
            },
            selected: function() {
                var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
                return selected && selected.length && $.data(selected[0], "ac_data");
            },
            emptyList: function() {
                list && list.empty();
            },
            unbind: function() {
                element && element.remove();
            }
        };
    };

    $.Autocompleter.Selection = function(field, start, end) {
        try {
            if (field.createTextRange) {
                var selRange = field.createTextRange();
                selRange.collapse(true);
                selRange.moveStart("character", start);
                selRange.moveEnd("character", end);
                selRange.select();
            } else if (field.setSelectionRange) {
                field.setSelectionRange(start, end);
            } else {
                if (field.selectionStart) {
                    field.selectionStart = start;
                    field.selectionEnd = end;
                }
            }
            field.focus();
        } catch (e) { 
        }
    };

})(jQuery);// Common.js starts here
function DescPop(url) {
    openWnd(url, "Description", 300, 600, 0, 0, 0, 1, 1, 0, 0)
} 
//open new window
function openWnd(url, name, height, width, directories, location, menubar, resizable, scrollbars, status, toolbar) 
{
	wnd = window.open(url, name, "alwaysRaised=1,height=" + height + ",width=" + width + ",directories=" + directories + ",locaton=" + location + ",menubar=" + menubar + ",resizable=" + resizable + ",scrollbars=" + scrollbars + ",status=" + status + ",toolbar=" + toolbar)
	wnd.focus()
}


//remove all name/value pairs with the passed name from url-encoded querystring
function remQStringName(qString, name) {
var i
var qStringNew = ""

if (qString != "") {
var curName
var arrNameVal = qString.split("&")

for (i = 0; i < arrNameVal.length ; i++) {
    
    curName = URLDecode(arrNameVal[i].split("=")[0])
    if (curName.toLowerCase() != name.toLowerCase()) qStringNew += "&" + arrNameVal[i]

}}

return qStringNew.substr(1)
}

function GetSelText(ctl) {
var selIdx = ctl.selectedIndex
return selIdx == -1 ? "" : ctl[selIdx].text
}

function URLDecode(urlStr) {
return unescape(urlStr.replace(/\+/g, " "))
}

//get select box value
function GetSelVal(ctl) {
var selIdx = ctl.selectedIndex
return selIdx == -1 ? "" : ctl[selIdx].value
}

function notNumber(number) {
number = number.toString()
for (var i=0; i<number.length; i++) {
if (number.charAt(i) > "9" || number.charAt(i) < "0") return true
}
return false
}

//check whether text-box is empty
function isEmpty(field, fieldName, msg){
if (Trim(field.value) == ""){
if (msg == null)
    msg = "Please enter " + fieldName + "."
    alert(msg);
	field.focus()
	return true

}
return false
}

//validate ASCII Character Set
function charCheck(field, message, toASCIIfield) {
if (toASCIIfield == null)
var txt = field.value
else
var txt = ToASCII(field)

for (var i=0; i<txt.length; i++) {
if (txt.charCodeAt(i) >= 128) {
alert(message)
field.focus()
return true
}}

return false
}

//check whether text-box is empty
function isEmptyContact(field, fieldName, msg) 
{ //alert(field)
	if (Trim(field.value) == "") 
	{
		if (msg == null)
			msg = "Please enter " + fieldName + "."
			field.focus()
			return true
		
	}

		return false
}


//validate ASCII Character Set
function charCheckContact(field, message, toASCIIfield) 
	{
		if (toASCIIfield == null)
			var txt = field.value
		else
			var txt = ToASCII(field)
			for (var i=0; i<txt.length; i++) 
			{
				if (txt.charCodeAt(i) >= 128) 
				{
				field.focus()
				return true
				}
			}
		return false
	}
function notSelected(field, fieldName, msg) 
{
	if (field.selectedIndex == 0) 
	{
		if (msg == null)
			msg = "Please select " + fieldName + "."
			field.focus()
			return true
	}
		return false
}

var AllowDocLangClick;
var AllowDocCurrClick;

AllowDocLangClick = false;
AllowDocCurrClick = false;

var LangjustClicked;
LangjustClicked = false;

var CurrjustClicked;
CurrjustClicked = false;
//_______________________________________________________________________________________
//for handling lang and curr dropdown style.
//_______________________________________________________________________________________
var IsCollapsable = false;
var UPPER_LIMIT = LOWER_LIMIT = 0;
var IsMovingDownClicked,IsMovingUpClicked = false;
var ItemsTable ;
var ParentDiv ;
var ParentDiv_ID ;
var PixTop = 0;
var PixHeight = 0;
 
 //Image Click event handler
function ImageClick (ParentDivID, ItemsTableID)
{
    ItemsTable = document.getElementById(ItemsTableID);
    ParentDiv = document.getElementById(ParentDivID);
    ParentDiv_ID =  ParentDivID;
    if(ItemsTable.style.top == null || ItemsTable.style.top == '')
    {
        ItemsTable.style.top = (0 - ItemsTable.getElementsByTagName("TR").length * 22) + "px";
    }
    
    UPPER_LIMIT = ItemsTable.getElementsByTagName("TR").length * 22;
    LOWER_LIMIT = 0 - UPPER_LIMIT;
     
    if(ParentDiv.style.display == "none")
    {
       IsCollapsable = false;
       ParentDiv.style.height = "0px";
       ItemsTable.style.top = (0 - ItemsTable.getElementsByTagName("TR").length * 22) + "px";
    }
    PixTop = 0;
    PixHeight = 0;
    if(IsCollapsable)
    {
        IsCollapsable = false;
        IsMovingUpClicked = true;
        IsMovingDownClicked = false;
        MoveUp();
    }
    else
    {
        IsCollapsable = true;
        IsMovingDownClicked = true;
        IsMovingUpClicked = false;
        toggleDisplay(ParentDivID, "block");
        MoveDown();
    }
}
var MoveUp = function()
{
    if(LOWER_LIMIT >= PixTop)
    {
        toggleDisplay(ParentDiv_ID, "none");
       
        return;
    }
    if(IsMovingDownClicked)
    {
        return;
    }
     
    PixTop = parseInt(ItemsTable.style.top.replace("px",""));
    PixHeight = parseInt(ParentDiv.style.height.replace("px",""));
	PixTop = PixTop - 10; 
	PixHeight = PixHeight - 10;
    ItemsTable.style.top = PixTop.toString() + "px";
    ParentDiv.style.height = PixHeight.toString() + "px";
	setTimeout(MoveUp,0);      
}
var MoveDown = function()
{
    if(UPPER_LIMIT <= PixHeight || IsMovingUpClicked )
    {
         
        return;
    }
 
	PixTop = parseInt(ItemsTable.style.top.replace("px",""));
    PixHeight = parseInt(ParentDiv.style.height.replace("px",""));
    PixTop = PixTop + 10; 
	PixHeight = PixHeight + 10;
    ItemsTable.style.top = PixTop.toString() + "px";
    ParentDiv.style.height = PixHeight.toString() + "px";
    setTimeout(MoveDown,0);      
}

function langcurrMouseOver(currentObject, langTitle){
if(langTitle != ''){
var images = currentObject.getElementsByTagName("img");
currentObject.style.backgroundColor = "#eae7a8";       
var index = images.length == 2? 1: 0;
if(images.length >0)
{
images[index].style.visibility = "visible";
}}}

function langcurrMouseOut(currentObject, langTitle){
if(langTitle != ''){
var images = currentObject.getElementsByTagName("img");
currentObject.style.backgroundColor = "#f8f8f8";
var index = images.length == 2? 1: 0;
if(images.length >0){
    images[index].style.visibility = "hidden";
}}}

function toggleDisplay(divId, ops) {
    var div = document.getElementById(divId);
    if (document.getElementById(divId).style.display == "block") ops = "none";
    div.style.display = ops;
 
      if (divId == 'dropmenulang') {
        AllowDocLangClick = true;
        LangjustClicked = true;
        CurrjustClicked = false;
      }
      else {
        AllowDocCurrClick = true;
        CurrjustClicked = true;
        LangjustClicked = false;
      }
  
}

function toggleDisplay2(obj, msgShow, msgHide, msgTemplate) {
    var objTemplate = document.getElementById(obj)
    var objMsgTemplate = document.getElementById(msgTemplate)
    if (objTemplate.style.display == 'block') {
        objTemplate.style.display = 'none';
        objMsgTemplate.innerHTML = msgHide;
    } else {
    objTemplate.style.display = 'block';
        objMsgTemplate.innerHTML = msgShow;
    }
}

function showLangFalse() {
if (LangjustClicked == true){
    LangjustClicked = false;
	return;
}
if (AllowDocLangClick == true) {
document.getElementById('dropmenulang').style.display="none";
AllowDocLangClick = false;
}}

function showCurrFalse() {
if (CurrjustClicked == true) {
    CurrjustClicked = false;
	return;
}

if (AllowDocCurrClick == true) {
document.getElementById('dropmenucurr').style.display="none";
AllowDocCurrClick = false;
}}

function showDivsFalse() {
    showCurrFalse();
    showLangFalse();
}

document.onclick = showDivsFalse;

function ChangeValue(urlVar, varValue) {
if (varValue != "") {
var frm = document.MainLangSwitch
var URL = switch_URL(urlVar, varValue)

if (frm) {
	frm.action = URL
	frm.submit()
} else {
	location = URL
}}}

function switch_URL(urlVar, varValue) {
var qString = location.search.substr(1)
var arrQString = qString.split("&")
var varAdded = false

for (var i in arrQString) {
if (arrQString[i].split("=")[0].toLowerCase() == urlVar) {
	arrQString[i] = urlVar + "=" + varValue
	varAdded = true
}}
qString = arrQString.join("&")
if (!varAdded) {
if (qString != "") qString += "&"
qString += urlVar + "=" + varValue
}
return location.pathname + "?" + qString
}

function LTrim(str){
var whitespace = new String(" \t\n\r");
var s = new String(str);
if (whitespace.indexOf(s.charAt(0)) != -1) {
var j=0, i = s.length;
while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
j++;
s = s.substring(j, i);
}
return s;
}

function RTrim(str){
var whitespace = new String(" \t\n\r");
var s = new String(str);
if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
var i = s.length - 1;
while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
i--;
s = s.substring(0, i+1);
}
return s;
}

function Trim(str){
return RTrim(LTrim(str));
}

function Len(str)
{  return String(str).length;  }

function Left(str, n){
        if (n <= 0)     // Invalid bound, return blank string
                return "";
        else if (n > String(str).length)   // Invalid bound, return
                return str;                // entire string
        else // Valid bound, return appropriate substring
                return String(str).substring(0,n);
}
function Right(str, n){
        if (n <= 0)     // Invalid bound, return blank string
           return "";
        else if (n > String(str).length)   // Invalid bound, return
           return str;                     // entire string
        else { // Valid bound, return appropriate substring
           var iLen = String(str).length;
           return String(str).substring(iLen, iLen - n);
        }
}

function Mid(str, start, len){
        // Make sure start and len are within proper bounds
        if (start < 0 || len < 0) return "";

        var iEnd, iLen = String(str).length;
        if (start + len > iLen)
                iEnd = iLen;
        else
                iEnd = start + len;

        return String(str).substring(start,iEnd);
}
function InStr(strSearch, charSearchFor){
for (i=0; i < Len(strSearch); i++)
{
    if (charSearchFor == Mid(strSearch, i, Len(charSearchFor) ))
    {
		return i;
    }
}
return -1;
}

//trim string
function trim(stringToTrim) {
	var i, j

	//left trim
	for(i=0; i<stringToTrim.length; i++) {
		if (stringToTrim.charAt(i) != " ") break
	}

	//right trim
	for(j=stringToTrim.length-1; j>=i; j--) {
		if (stringToTrim.charAt(j) != " ") break
	}

	return stringToTrim.substring(i, j + 1)
}
//End of Utils.js


//replace or add name/value pairs in url-encoded querystring
function setQStringName(qString, name, arrVal) {
    var qStringNew = remQStringName(qString, name)
    var i
  
   
    var start = qStringNew == "" ? 1 : 0
    for (i = 0; i < arrVal.length; i++) {
        qStringNew += "&" + escape(name) + "=" + escape(arrVal[i])
    }
    return qStringNew.substr(start)
}


//extract (first!) value from querystring for the passed name
function GetQSVal(qsName) {
    var qsPair
    var qString = location.search.substr(1)
    var arrNameVal = qString.split("&")
    for (var i in arrNameVal) {
        qsPair = arrNameVal[i].split("=")
        if (URLDecode(qsPair[0]).toLowerCase() == qsName.toLowerCase()) return URLDecode(qsPair[1])
    }
    return ""
}

function Reload(name, val, totPageNo) {
    if (val < totPageNo + 1 && val > 0) {
        var qString = location.search.substr(1)
        //always resert page to 1
        if (name != "page") {
            var page = GetQSVal("page")
            if (page != "1" && page != "") qString = setQStringName(qString, "page", new Array("1"))
        }
        qString = setQStringName(qString, name, new Array(val.toString()))
        location = location.pathname + "?" + qString
    }
}


function setCriteria(val) {
    document.getElementById('SearchBy').value = val;
}

function invalidChars(validatedControl, validatedName, charString, msg) {
    var validatedString = trim(validatedControl.value).toLowerCase()
    charString = charString.toLowerCase()

    for (var i = 0; i < validatedString.length; i++) {
        for (var j = 0; j < charString.length; j++) {
            if (validatedString.charAt(i) == charString.charAt(j)) {

                if (typeof (Common_Scripts_FuncLib_Space) == "undefined")
                    Common_Scripts_FuncLib_Space = "space"

                var alertString = charString.split("").join("  ")
                alertString = alertString.split("     ").join("  " + Common_Scripts_FuncLib_Space + "  ")

                if (msg == null)
                    msg = validatedName + " cannot contain any of the following illegal characters:\n\n " + alertString

                msg = msg.replace(/\[IllegalCharacters\]/, alertString)
                alert(msg)
                validatedControl.focus()
                return true
            }
        }
    }

    return false
}

function submitForm() {

    //check that at least one star rating is selected

    if (document.getElementById('rating3').checked == false && document.getElementById('rating4').checked == false && document.getElementById('rating5').checked == false)  {
    if (typeof (Common_Scripts_SearchEngine_SelectStar) == "undefined")
    Common_Scripts_SearchEngine_SelectStar = "Please select at least one Star Rating."

    alert(Common_Scripts_SearchEngine_SelectStar)
    document.getElementById('rating5').focus()
    return false;
    }

    if ($("#SearchBy").val() == "LocationKey" & ($("#destination").val().length < 3 | $("#destination").val() == HINT_DRE)) {
        alert(Common_Scripts_ValidDestinationSearch);
        return false;
    }

    if (document.getElementById("SearchBy").value == "Name") {
        document.getElementById('hotelname').value = trim(document.getElementById('hotelname').value)
        if (typeof (Common_Scripts_SearchEngine_HotelName) == "undefined")
            Common_Scripts_SearchEngine_HotelName = "Hotel Name cannot contain any of the following illegal characters:\n\n%"

        if (typeof (Common_Scripts_SearchEngine_HotelNameLength) == "undefined")
            Common_Scripts_SearchEngine_HotelNameLength = "Hotel Name should be at least 3 characters long."

        if (invalidChars(document.getElementById('hotelname'), "", "%", Common_Scripts_SearchEngine_HotelName)) return false;
   

        if (typeof (document.getElementById('hotelname')) != 'undefined') {
            if (trim(document.getElementById('hotelname').value).length < 3) {
                alert(Common_Scripts_SearchEngine_HotelNameLength);
                return false;

            }
        }
    }
    else {
        if (document.getElementById("SearchBy").value == "LocationKey") {
            if(document.getElementById('LocationKey'))
                document.getElementById('LocationKey').value = trim(document.getElementById('LocationKey').value)
                
            if (document.getElementById('hdnLocationKey'))
                document.getElementById('hdnLocationKey').value = trim(document.getElementById('hdnLocationKey').value)
                
            if (typeof (Common_Scripts_SearchEngine_LocationName) == "undefined")
                Common_Scripts_SearchEngine_LocationName = "Hotel Name cannot contain any of the following illegal characters:\n\n%"

            if (typeof (Common_Scripts_SearchEngine_LocationLength) == "undefined")
                Common_Scripts_SearchEngine_LocationLength = "Location Name should be at least 3 characters long."
            if (document.getElementById('LocationKey')) {
                if (invalidChars(document.getElementById('LocationKey'), "", "%", Common_Scripts_SearchEngine_LocationName)) return false;

            }
                
            
/*            if (document.getElementById('destination')) {
                if (document.getElementById('destination').value.split("'").length > 2) 
                {
                    alert(Common_Scripts_SearchEngine_LocationName + "\\~`!@#$%^&*()-+{}|\"':;?/><");
                    return false;
                }
                if (CheckForSpecialChars(document.getElementById('destination').value, "\\,~,`,!,@,#,$,%,^,&,*,(,),-,+,{,},|,\",:,;,?,/,>,<" )) {
                    alert(Common_Scripts_SearchEngine_LocationName + "\\~`!@#$%^&*()-+{}|\"':;?/><");
                    return false;
                }
            }
*/            
            if (document.getElementById('hdnLocationKey')) {
                if (invalidChars(document.getElementById('hdnLocationKey'), "", "%", Common_Scripts_SearchEngine_LocationName)) return false;
            }

            if (document.getElementById('LocationKey')) {
                if (trim(document.getElementById('LocationKey').value).length < 3) {
                    alert(Common_Scripts_SearchEngine_LocationLength);
                    return false;

                }
            }
            
            
        }
    }

}

function CheckForSpecialChars(str, splchars) {
    var charArr = splchars.split(",");
    for (i = 0; i < charArr.length; i++) {
        if (str.indexOf(charArr[i]) >= 0) {
            return true;
        }
    }
return false;
}


//update all name/value pairs with the passed name from url-encoded querystring
function updateQStringName(qString, name, value) {
    var i
    var qStringNew="" 
    //var start = qStringNew == "" ? 1 : 0
    
    if (qString != "") {
        var curName
        var arrNameVal = qString.split("&")
         
       

        for (i in arrNameVal) {
            curName = URLDecode(arrNameVal[i].split("=")[0])
            if (curName.toLowerCase() != name.toLowerCase()) qStringNew += "&" + arrNameVal[i]
        }
    }
    
    qStringNew += "&" + escape(name) + "=" + value

    return qStringNew.substr(1)
}

function UpdateFilter() {

    var qString = location.search.substr(1)

    var qStringRating
    qStringRating = remQStringName(qString, "star3")
    qStringRating = remQStringName(qStringRating, "star4")
    qStringRating = remQStringName(qStringRating, "star5")

    if (document.getElementById('star5').checked == false &&
        document.getElementById('star4').checked == false &&
        document.getElementById('star3').checked == false) {
        qStringRating += "&star3=ON&star4=ON&star5=ON&starAll=ON"
        qString = qStringRating
    }
    else if( document.getElementById('chkRatingAll').checked == true)
    {
        qStringRating += "&star3=ON&star4=ON&star5=ON&starAll=ON"
        qString = qStringRating
    }
    else {
        if (document.getElementById('star3').checked == true) {
            qStringRating += "&star3=" + document.getElementById('star3').value
            qString = qStringRating
        }

        if (document.getElementById('star4').checked == true) {
            qStringRating += "&star4=" + document.getElementById('star4').value
            qString = qStringRating
        }

        if (document.getElementById('star5').checked == true) {
            qStringRating += "&star5=" + document.getElementById('star5').value
            qString = qStringRating
        }
    }
    
    //-------------------------getting accommodation filters.
    var accChk = "";
    
    if(document.getElementById("ACCOMMODATIONTYPEAll").checked == false)
    {
        var arraccommodationTypeId = accommodationTypeIds.split(",");
        for (index = 0; index < arraccommodationTypeId.length - 1; index++) {
            if(arraccommodationTypeId[index] != ""){
                var chkbox = document.getElementById("ACCOMMODATIONTYPE" + arraccommodationTypeId[index])
                if (chkbox != null && chkbox.checked == true) {
                  accChk += chkbox.value + ',';
                }
            }
        }
        
        if (accChk.length > 0) {   
          accChk = accChk.substring(0, accChk.length - 1);
        }
    }
    
    var qStringAcc = remQStringName(qString, "accChk");
    qStringAcc += "&accChk=" + accChk;
    qString = qStringAcc;           
    //-------------------------getting accommodation filters - Ends.
       
    // FacilitiesCount is calculated in searchfilter.inc
    var count = FacilitiesCount
    var facChk =""
    if (document.getElementById("FACILITIESAll").checked == false) 
    {
        var arrFacilitiesId = FacilitiesId.split(",")
        for (i = 0; i < count+1; i++) {
             var chkbox = document.getElementById("FACILITIES" + arrFacilitiesId[i]);
             if (chkbox != null && chkbox.checked == true) {
              facChk += chkbox.value + ','
            }
        }
    }
    var chkLen = facChk.substring(0, facChk.length - 1)
    /////////

    var qStringNew = remQStringName(qString, "facChk")
    
    var chkLen = facChk.substring(0, facChk.length - 1)
    
    if (chkLen.length > 0) {       
        var arrVal = new Array(chkLen)       
        var i
       qStringNew += "&facChk=" + arrVal[0]       
    }

    qString = qStringNew
    qString = remQStringName(qString, "page")
    location = location.pathname + "?" + qString
}

function replaceQueryString(initialQuery, keyString, newValue) {
var re = new RegExp("([?|&])" + keyString + "=.*?(&|$)", "i");

var matches = initialQuery.match(re);

if (matches && matches.length)
    return initialQuery.replace(re, '$1' + keyString + "=" + newValue + '$2');
else {
    if (initialQuery.indexOf('?') < 0)
        return initialQuery + '?' + keyString + "=" + newValue;
    else
        return initialQuery + '&' + keyString + "=" + newValue;
}}


function Querystring(qs) {
this.params = {};

if (qs == null) qs = location.search.substring(1, location.search.length);
if (qs.length == 0) return;

qs = qs.toLowerCase();
qs = qs.replace(/\+/g, ' ');
var args = qs.split('&'); // parse out name/value pairs separated via &

// split out each name=value pair
for (var i = 0; i < args.length; i++) {
var pair = args[i].split('=');
var name = decodeURIComponent(unescape(pair[0]));

var value = (pair.length == 2)
	? decodeURI(encodeURI(pair[1]))
	: name;

this.params[name] = value;
}}

Querystring.prototype.get = function(key, default_) {
    key = key.toLowerCase();
    var value = this.params[key];
    return (value != null) ? value : default_;
}

function showpopup(cid,parentobj, x, y) {
    var topoffset = 18;
    if( x == 'undefined' ) x = 0 ; 
    if( y == 'undefined' ) y = 0 ;
	obj = document.getElementById(cid);
	mainobj = document.getElementById(parentobj);
	var curleft = curtop = 0;
	if (mainobj.offsetParent) {
	curleft = mainobj.offsetLeft;
	curtop = mainobj.offsetTop;
	while (mainobj = mainobj.offsetParent) {
	curleft += mainobj.offsetLeft;
	curtop += mainobj.offsetTop;
		}
	}
	obj.style.position = "absolute";
	obj.style.display = "";
	obj.style.left = (curleft + x) + 'px'; //Fix for bug#1737
	obj.style.top =  (curtop + topoffset + y) + 'px';
}


function hidepopup(divid) {
	objid = divid;
	document.getElementById(objid).style.display = "none";
}


function navigateToDirectHotelPage(hotelid,checkin,checkout, locKey, locID, isDRE, isByHotelName, hotelName, refinfo) {
  var directHotelString;
    if (isDRE == 'True')
    {
     
      directHotelString = "directhotel.asp?id=" + hotelid + "&ncl=&checkin=2009-03-10&checkout=2009-03-12&locKey=&locID=&locDispName=" + locDispName;
      directHotelString = replaceQueryString(directHotelString, "locKey", locKey);
      directHotelString = replaceQueryString(directHotelString, "locID", locID);
    }
    else if (isByHotelName == 'True')
    {
        directHotelString = "directhotel.asp?id=" + hotelid + "&ncl=&checkin=2009-03-10&checkout=2009-03-12&hotelName=";
        directHotelString = replaceQueryString(directHotelString, "hotelName", hotelName);        
    }
    else
    {
        directHotelString = "directhotel.asp?id=" + hotelid + "&ncl=&checkin=2009-03-10&checkout=2009-03-12";
    }    
    directHotelString = replaceQueryString(directHotelString, "id", hotelid);
    directHotelString = replaceQueryString(directHotelString, "checkin", checkin);
    directHotelString = replaceQueryString(directHotelString, "checkout", checkout);
    
    var varDMName = ""
    if (document.domain.length > 0) {
        varDMName = document.domain
    }
    directHotelString = directHotelString + "&rpage=" + varDMName + "/" + refinfo;

    window.location.href = directHotelString;
    }
    
    function navigateToDirectHotelPageRatingTab(hotelid,checkin,checkout, locKey, locID, isDRE) {
  var directHotelString;
    if (isDRE == 'True')
    {
      directHotelString = "directhotel.asp?id=" + hotelid + "&ncl=&checkin=2009-03-10&checkout=2009-03-12&locKey=&locID=&tab=2";
      directHotelString = replaceQueryString(directHotelString, "locKey", locKey);
      directHotelString = replaceQueryString(directHotelString, "locID", locID);
    }
    else
    {
    directHotelString = "directhotel.asp?id=" + hotelid + "&ncl=&checkin=2009-03-10&checkout=2009-03-12&tab=2";
    }    
    directHotelString = replaceQueryString(directHotelString, "id", hotelid);
    directHotelString = replaceQueryString(directHotelString, "checkin", checkin);
    directHotelString = replaceQueryString(directHotelString, "checkout", checkout);

    window.location.replace(directHotelString);
    }

function refreshattabclick(refreshval) {
    var pagecode = GetQSVal("vw");
    if (pagecode != refreshval)
    {
        var qString = location.search.substr(1)
        qString = location.pathname + "?" + qString
        qString = replaceQueryString(qString, "vw", refreshval)
        qString = replaceQueryString(qString, "page", "1")
        location =  qString;
    }
}

function logoutclick(){   
var qString = location.search.substr(1)
qString = location.pathname + "?" + qString
qString = replaceQueryString(qString, "lgt", "1")
//location = qString;
location = "/logout.asp";
}

function ChangeCurrencies(currencycode,currencyname, refinfo){
document.getElementById('txtCurrency').innerHTML  = document.getElementById(currencycode).innerHTML ;
toggleDisplay('dropmenucurr','none');

    var squery = "";
    var sFquery = "";
    var varDMName = "";
    if (document.domain.length > 0) {
        varDMName = document.domain
    }
    
    sFquery = window.location.toString();
    squery = replaceQueryString(sFquery, "curr",currencycode);
    squery = replaceQueryString(squery, "rpage", varDMName + "/" + refinfo);

    window.location.replace(squery);
}

function ChangeLang(languagecode, languagename, refinfo) {
    document.getElementsByName("imgLang")[0].id = languagecode + "Smallgif";
    document.getElementsByName("imgLang")[0].src = "SiteEngine/HTC/Images/lang/" + languagecode + "Small.gif";
    toggleDisplay('dropmenulang', 'none');
    
    var squery = "";
    var sFquery = "";
    var varDMName = "";
    if (document.domain.length > 0) {
        varDMName = document.domain
    }
    
    sFquery = window.location.toString();
    squery = replaceQueryString(sFquery, "lc", languagecode);
    squery = replaceQueryString(squery, "rpage", varDMName + "/" + refinfo);

    window.location.replace(squery);
}

function unCheckOptions(currentObject, parentObjectId){
if (currentObject.checked){
var parentObejct = document.getElementById(parentObjectId);
var childOptions = parentObejct.getElementsByTagName("input");
for(index=0; index<childOptions.length; index++){
if (childOptions[index].type == "checkbox" ){
    childOptions[index].checked = false;
}}
currentObject.checked = true;
}}

function unCheckAll(AllOption){
    document.getElementById(AllOption).checked = false;
}

function DisplayMemberDollar(mainobj, currencysign, roomtotal, memberdollars, earnpercentage,optionalparam) {
obj = document.getElementById("areyoumember");

var curleft = curtop = 0;
if (mainobj.offsetParent) {
 curleft = mainobj.offsetLeft;
 curtop = mainobj.offsetTop;
 while (mainobj = mainobj.offsetParent) {
     curleft += mainobj.offsetLeft ;
     curtop += mainobj.offsetTop - 70;
}}

obj.style.position = "absolute";
obj.style.display = "block";
if(curleft - 640 < 5)
    obj.style.left = '5px';
else
    obj.style.left = curleft - 640 + 'px';
    var IE = /*@cc_on!@*/false;
    if (IE) {
        obj.style.top = document.documentElement.scrollTop + 50 + 'px';
    }
    else {
        obj.style.top = window.pageYOffset + 50 + 'px';
    }

var _memberdollar = document.getElementById("memberdollar")

if (_memberdollar != null)
 _memberdollar.innerHTML = currencysign + " " + memberdollars;

var _currencysign = document.getElementById("currencysign")
if (_currencysign != null)
 _currencysign.innerHTML = currencysign;

var _roomtotal = document.getElementById("roomtotal")
if (_roomtotal != null)
 _roomtotal.innerHTML = roomtotal;

var _earnpercentage = document.getElementById("earnpercentage")

if (_earnpercentage != null)
 _earnpercentage.innerHTML = earnpercentage; 
}

function HideMemberDollarPopup() {
 document.getElementById("areyoumember").style.display = "none";
}

function JEscape(str) {
str = str.replace(/<jstab>/g, "\t");
str = str.replace(/<jsbr>/g, "\n");
return str;
}


//check whether passed parameter is a valid number
function notNumber(number) {
number = number.toString()
for (var i = 0; i < number.length; i++) {
    if (number.charAt(i) > "9" || number.charAt(i) < "0") return true
}
return false
}

//validate email address
function notEmail(field, fieldName, msg) {
var email = trim(field.value)

if (email == "") return false

var at = false
var dot = false

for (var i = 0; i < email.length; i++) {
    if (email.charAt(i) == "@") at = true
    if (email.charAt(i) == "." && at) dot = true
}

if (!(at && dot && email.length > 5)) {
    if (msg == null)
        msg = "The " + fieldName + " you entered is not a valid e-mail address."

    alert(msg)
    field.focus()
    field.select()
    return true
}

//check for invalid characters
if (invalidChars(field, "E-mail", '%,;|" <>\\/')) return true

return false
}


function makeHttpRequest(url) {
    http_request = false
    if (window.XMLHttpRequest) {
        http_request = new XMLHttpRequest()
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml')
        }
    }
    else if (window.ActiveXObject) {
        try {
            if (IeVersion()['Version'] > 6) {
                http_request = new ActiveXObject("MSXML2.DOMDocument")
            } else {
                http_request = new ActiveXObject("MSXML2.XMLHTTP.3.0")
            }
        }
    catch (e) {
        onError(e)
        try {
            if (IeVersion()['Version'] > 6) {
                http_request = new ActiveXObject("Microsoft.XMLHTTP")
            } else {
                http_request = new ActiveXObject("MSXML2.XMLHTTP.3.0")
            }
        }
        catch (e) {
            onError(e) 
        }
    }
}
    if (!http_request) {
        onError()
        return false
    }
    http_request.onreadystatechange = refreshPage
    http_request.open('GET', url , true)
    http_request.send(null)
}


function refreshPage() {
    if (http_request.readyState == 4) {
        window.location.reload(false);
    }
}
SearchEngineCookie = function(){}
//saves the search type
SearchEngineCookie.SetSearchBy = function(strSearchBy) {
var oSECookie = SearchEngineCookie.GetSearchCookie()
    oSECookie.searchBy = strSearchBy;
    SaveCookie(oSECookie);
}

SearchEngineCookie.SetLocationForDre = function(strLocation) {
var oSECookie = SearchEngineCookie.GetSearchCookie();
    oSECookie.suburb = strLocation;
    SaveCookie(oSECookie);
}

//saves the location 
SearchEngineCookie.SetLocationCookie = function(strCountry, strCity, strSuburb) {
var oSECookie = SearchEngineCookie.GetSearchCookie()
    oSECookie.country = strCountry;
    oSECookie.city = strCity;
    oSECookie.suburb = strSuburb;
    SaveCookie(oSECookie);
}

//save dates to cookie
SearchEngineCookie.SetDatesCookie = function(inDate, outDate) {
    var oSECookie = SearchEngineCookie.GetSearchCookie();
    oSECookie.inDate = inDate;
    oSECookie.outDate = outDate;
    SaveCookie(oSECookie);
}

SearchEngineCookie.SetSearchEngineCookieForDRE = function(inDate, outDate, strLocation) {
    var oSECookie = SearchEngineCookie.GetSearchCookie();
    oSECookie.inDate = inDate;
    oSECookie.outDate = outDate;
    oSECookie.suburb = strLocation;
    oSECookie.searchBy = "LocationKey";
    SaveCookie(oSECookie);
}


SearchEngineCookie.SetSearchEngineCookie = function(inDate, outDate, strCountry, strCity, strSuburb) {
    var oSECookie = SearchEngineCookie.GetSearchCookie();
    oSECookie.inDate = inDate;
    oSECookie.outDate = outDate;
    oSECookie.country = strCountry;
    oSECookie.city = strCity;
    oSECookie.suburb = strSuburb;
    oSECookie.searchBy = "criteria";
    SaveCookie(oSECookie);
}

SearchEngineCookie.SetSearchEngineCookieWithSearchBy = function(inDate, outDate, strCountry, strCity, strSuburb , strSearchBy) {
    var oSECookie = SearchEngineCookie.GetSearchCookie();
    oSECookie.inDate = inDate;
    oSECookie.outDate = outDate;
    oSECookie.country = strCountry;
    oSECookie.city = strCity;
    oSECookie.suburb = strSuburb;
    oSECookie.searchBy = strSearchBy;
    SaveCookie(oSECookie);
}


function SaveCookie(oSECookie) {
    var CheckinDate;   
    var CheckoutDate;    
    var dfmt = GetDateFormat();

    var inDArray;
    var outDArray;
    if (oSECookie.inDate.indexOf("/") > 0) {
        inDArray = oSECookie.inDate.split("/")
        outDArray = oSECookie.outDate.split("/")
    }
    else {
        inDArray = oSECookie.inDate.split("-")
        outDArray = oSECookie.outDate.split("-")
    }


    if (dfmt == "dd/mm/yyyy") {
        defInD = inDArray[0]
        defInM = inDArray[1]
        defInY = inDArray[2]
        defOutD = outDArray[0]
        defOutM = outDArray[1]
        defOutY = outDArray[2]
    }
    else if (dfmt == "yyyy/mm/dd") {
        defInY = inDArray[0]
        defInM = inDArray[1]
        defInD = inDArray[2]
        defOutY = outDArray[0]
        defOutM = outDArray[1]
        defOutD = outDArray[2]
    }

    var strInDate = defInY + "-" + defInM + "-" + defInD;
    var strOutDate = defOutY + "-" + defOutM + "-" + defOutD;
    document.cookie =
		escape("|SearchEng|") + "=" +
		escape("|" + oSECookie.country + "|" + oSECookie.city + "|" + oSECookie.suburb + "|" + strInDate + "|" + strOutDate + "|" + oSECookie.searchBy + "|") +
		";path=/"
}

function GetDateFormat() {
    if (typeof (window['calDateFormat']) != 'undefined') {
        if (calDateFormat == "yyyy/mm/dd")
            return "yyyy/mm/dd";
        else if (calDateFormat == "dd/mm/yyyy")
            return "dd/mm/yyyy";
    }
    else {
        return "dd/mm/yyyy";
    }
}

//returns object containing search engine cookie elements
SearchEngineCookie.GetSearchCookie = function() {
    
    var oSECookie = new Object()
    oSECookie.searchBy = ""
    oSECookie.country = ""
    oSECookie.city = ""
    oSECookie.suburb = ""
    oSECookie.inDate = ""
    oSECookie.outDate = ""

    var cookieArray = URLDecode(document.cookie).split("|")

    for (var i = 0; i < cookieArray.length; i++) {
        if (cookieArray[i] == "SearchEng") {
            oSECookie.country = cookieArray[i + 2]
            oSECookie.city = cookieArray[i + 3]
            oSECookie.suburb = cookieArray[i + 4]
            oSECookie.inDate = cookieArray[i + 5]
            oSECookie.outDate = cookieArray[i + 6]
            oSECookie.searchBy = cookieArray[i + 7]
            break
        }
    }
    return oSECookie
}


function ProcessSearchEngineSubmit() {
    
    if (ValidateDate()) {
        var strChkin = document.getElementById('Cal1').value;
        var strChkout = document.getElementById('Cal2').value;
        var strCountry = document.getElementById('country').value;
        var strCity = document.getElementById('city_region').value;
        var strSuburb = document.getElementById('location').value;
        var strSrchBy = document.getElementById('SearchBy').value;
        SearchEngineCookie.SetSearchEngineCookieWithSearchBy(strChkin, strChkout, strCountry, strCity, strSuburb, strSrchBy);
        //return false;
        return true;        
    }
    else {
        return false;
    }
    

}//SEP03
var AXPAGE = "ajaxxsl.asp";
var HINT_DRE = "City, Region, Suburb or Landmark"
var gc_country ="";
var gc_city ="";
var gc_suburb ="";
var gc_searchby = "";
var gc_lc = "";

var _cache = new Cache(); //Cache object

function UpdateDirectHotelLink() {
    var checkInDate, checkOutDate;
    checkInDate = document.getElementById("inYear").value + "-" + document.getElementById("inMonth").value + "-" + document.getElementById("inDay").value
    checkOutDate = document.getElementById("outYear").value + "-" + document.getElementById("outMonth").value + "-" + document.getElementById("outDay").value

    for (var i = 0; i < 3; i++) {
        var LMDealUrl, lmArr1, lmArr2;
        if (document.getElementById("LMDeals" + i).href) {
            lmArr1 = document.getElementById("LMDeals" + i).href.split("Checkin=");
            lmArr2 = lmArr1[1].split("Checkout=");

            if (document.getElementById("LMDeals" + i).href) {
                LMDealUrl = lmArr1[0] + "Checkin=" + checkInDate + "&Checkout=" + checkOutDate;
                document.getElementById("LMDeals" + i).href = LMDealUrl;
            }
        }
    }

    var MemberReviewUrl, mrArr1, mrArr2;
    if (document.getElementById("MemberReview").href) {
        mrArr1 = document.getElementById("MemberReview").href.split("Checkin=");
        mrArr2 = mrArr1[1].split("Checkout=");

        if (document.getElementById("MemberReview").href) {
            MemberReviewUrl = mrArr1[0] + "Checkin=" + checkInDate + "&Checkout=" + checkOutDate;
            document.getElementById("MemberReview").href = MemberReviewUrl;
        }
    }
}

function changeSearchByAndLMDeals() {
    document.getElementById('SearchBy').value = 'LocationKey';
    FavTopCitiesLMDealsAJAXRequest(document.getElementById('country').value, "");
}

function changeToClassicSearch(ctl) {
    FavTopCitiesLMDealsAJAXRequest(document.getElementById('country').value, document.getElementById('city').value);
}

function FavTopCitiesLMDealsAJAXRequest(county, city) {
    var destinationControl;
    var action;
    action = "getlmdeals";
    destinationControl = "divfavtopcitieslmdeals";

    $("#" + destinationControl).html("<div id='pageloaderwrap'><img src='SiteEngine/HTC/images/page-loader-grey.gif' alt='' width='94' height='12' /><br /><span>Loading ...</span></div>");
    $.ajax({
    url: AXPAGE + '?action=' + action + '&country=' + county + '&city=' + escape(city) + "&proxyid=" + DRE_GUID,
        type: 'get',
        cache: true,
        success: function(results) {
            $("#" + destinationControl).html(results);
        }
    });
}

function loginmember() {

    var destinationControl;
    var action;
    var email;
    var password;

    email = $('#email').val();
    password = $('#pwd').val();
    $("#error_message").hide();

    action = "validatememberlogin";
    destinationControl = "MemberLoginTemplate";

    $("#loadingmemberlogin").show();
    $("#MemberLoginTemplate").hide();

    $.ajax({
        url: AXPAGE + '?action=' + action + '&email=' + email + '&password=' + password + "&proxyid=" + DRE_GUID,
        type: 'get',
        cache: true,
        success: function(results) {
            $("#loadingmemberlogin").hide();
            $("#MemberLoginTemplate").show();
            if (results == "") {
                $("#error_message").show();
            }
            else {
                $("#error_message").hide();
                $("#" + destinationControl).html(results);
            }
        }

    });

}

function logoutMember() {

    var destinationControl;
    destinationControl = "MemberBoxCanvas";
    $.ajax({
        url: AXPAGE + "?action=logoutMember" + "&proxyid=" + DRE_GUID,
        type: 'get',
        cache: true,
        success: function(results) {
            $("#" + destinationControl).html(results);
        }

    });

}

/* Ajax Load for Search Box using JQuery syntax */


$(function() {



if ($.browser.opera)
{
    LoadSearchEngineFromCookie();
}
else {
    // Initiate Lm Deals population
    //FavTopCitiesLMDealsAJAXRequest($("select#country").val(), $("select#city_region").val());
}

function FadeSearchEngine() {
    $('#TabbedPanels1 :input').attr('disabled', true);
    $('#TabbedPanels1 :input').css('opacity', '0.1');
    $('#TabbedPanels1 :input').css('filter', 'alpha(opacity=10)');
    $('#TabbedPanels1 :input').css('-ms-filter', 'progid:DXImageTransform.Microsoft.Alpha(opacity=10)');
}

function ShineSearchEngine() {
    $('#TabbedPanels1 :input').attr('disabled', false);
    $('#TabbedPanels1 :input').css('opacity', '');
    $('#TabbedPanels1 :input').css('filter', '');
    $('#TabbedPanels1 :input').css('-ms-filter', '');
}

function FadeDetailSearch() {
    $('#detailedsearch :input').attr('disabled', true);
    $('#detailedsearch :input').css('opacity', '0.1');
    $('#detailedsearch :input').css('filter', 'alpha(opacity=10)');
    $('#detailedsearch :input').css('-ms-filter', 'progid:DXImageTransform.Microsoft.Alpha(opacity=10)');
}

function ShineDetailSearch() {
    $('#detailedsearch :input').attr('disabled', false);
    $('#detailedsearch :input').css('opacity', '');
    $('#detailedsearch :input').css('filter', '');
    $('#detailedsearch :input').css('-ms-filter', '');
}


function LoadSearchEngineFromCookie() {

   // FadeSearchEngine();


    // Populate from coolie to gc_ variables
    ReadFromCookie()

    if (gc_searchby.toLowerCase() == "criteria") {
        $("#default_search").val("dest")
        switchoption();
    }
    else if (gc_searchby.toLowerCase() == "locationkey" || gc_searchby.toLowerCase() == "name") {
        $("#default_search").val("crit")
        if (gc_searchby.toLowerCase() == "locationkey") {
            $("#sbdest").attr("checked", "true");
        }
        else if (gc_searchby.toLowerCase() == "name") {
            $("#sbhname").attr("checked", "true");
        }
        if (gc_lc.toLowerCase() == "en") switchoption();
        //ShineSearchEngine();
       // FadeDetailSearch();
    }
    else {
        var i;
        i = 0;
       // ShineSearchEngine();
      //  FadeDetailSearch();
    }


    // select coumtry if cookie as country
    if (gc_country != "") {
        $("#country").val(gc_country);
    }

    var cityname;
    $.getJSON(AXPAGE, { param1: $("#country").val(), action: 'getcities', proxyid: DRE_GUID }, function(j) {
        _cache.setItem("C_" + $("#country").val(), j); 
        //$.jCache.setItem("C_" + $("#country").val(), j);
        popCities(j);
        // select city
        if (gc_city != "") {
            $("#city_region").val(gc_city);
        }
        // Initiate Lm Deals population
        FavTopCitiesLMDealsAJAXRequest($("select#country").val(), $("select#city_region").val());
        $.getJSON(AXPAGE, { param1: $("#city_region").val(), action: 'getlocations', proxyid: DRE_GUID }, function(j) {
            _cache.setItem("L_" + $("#city_region").val(), j); 
            //$.jCache.setItem("L_" + $("#city_region").val(), j);
            popLoc(j)
            // select location
            $("#location").val(gc_suburb);
        });

    });

}
    
    $("select#country").change(function() {
        $("#city_regionAJAXloading").show();
        if(_cache.getItem("C_" + $("#country").val()))
        {
            var k = _cache.getItem("C_" + $("#country").val())
            popCitiesAndLoc(k);
            FavTopCitiesLMDealsAJAXRequest($("select#country").val(), $("select#city_region").val());
            return;
        }
        /*
        if ($.jCache.hasItem("C_" + $("#country").val())) {
            var k = $.jCache.getItem("C_" + $("#country").val());
            popCitiesAndLoc(k);
            FavTopCitiesLMDealsAJAXRequest($("select#country").val(), $("select#city_region").val());
            return;
        }
        */
        $.getJSON(AXPAGE, { param1: $(this).val(), action: 'getcities', proxyid: DRE_GUID }, function(j) {
            _cache.setItem("C_" + $("#country").val(), j); 
            //$.jCache.setItem("C_" + $("#country").val(), j);
            popCitiesAndLoc(j);
            SaveCookieFromClient();
            FavTopCitiesLMDealsAJAXRequest($("select#country").val(), $("select#city_region").val());
        });
    });

    /*

    function popCities(j) {
        var options = '';
        ct = j.cities;
        for (var i = 0; i < ct.length; i++) {
            if (ct[i].name != -2)
                options += '<option value="' + ct[i].name + '">' + ct[i].displayname + '</option>';
            else
                options += '<option disabled="disabled" value="' + ct[i].name + '">' + ct[i].displayname + '</option>';
        }
        $("select#city_region").html(options);

        $("#city_regionAJAXloading").hide();
    }



    function popCitiesAndLoc(j) {
        var options = '';
        ct = j.cities;
        for (var i = 0; i < ct.length; i++) {
            if (ct[i].name != -2)
                options += '<option value="' + ct[i].name + '">' + ct[i].displayname + '</option>';
            else
                options += '<option disabled="disabled" value="' + ct[i].name + '">' + ct[i].displayname + '</option>';
        }
        $("select#city_region").html(options);

        options = '';
        lo = j.locations;

        for (var i = 0; i < lo.length; i++) {
            options += '<option value="' + lo[i].name + '">' + lo[i].displayname + '</option>';
        }
        $("select#location").html(options);
        $("#city_regionAJAXloading").hide();
    }

    function popLoc(j) {
        var options = '';
        lo = j.locations;

        for (var i = 0; i < lo.length; i++) {
            options += '<option value="' + lo[i].name + '">' + lo[i].displayname + '</option>';
        }
        $("select#location").html(options);
        $("#locationAJAXloading").hide();
    }
    
    */

    function popCities(j) {
        var options = '';
        
        dc = j.DefaultCities;
        
         for (var i = 0; i < dc.length; i++) {
            if (dc[i].Name != -2)
                options += '<option value="' + dc[i].Name + '">' + dc[i].DisplayName + '</option>';
            else
                options += '<option disabled="disabled" value="' + dc[i].Name + '">' + dc[i].DisplayName + '</option>';
        }
        if(dc.length > 0)
            options += '<option disabled="disabled" value="-2">---------------</option>';
        ct = j.Cities;
        for (var i = 0; i < ct.length; i++) {
            if (ct[i].Name != -2)
                options += '<option value="' + ct[i].Name + '">' + ct[i].DisplayName + '</option>';
            else
                options += '<option disabled="disabled" value="' + ct[i].Name + '">' + ct[i].DisplayName + '</option>';
        }
        $("select#city_region").html(options);

        $("#city_regionAJAXloading").hide();
    }



    function popCitiesAndLoc(j) {
        var options = '';
        ct = j.Cities;
        
        dc = j.DefaultCities;
        
         for (var i = 0; i < dc.length; i++) {
            if (dc[i].Name != -2)
                options += '<option value="' + dc[i].Name + '">' + dc[i].DisplayName + '</option>';
            else
                options += '<option disabled="disabled" value="' + dc[i].Name + '">' + dc[i].DisplayName + '</option>';
        }
        if(dc.length > 0)
            options += '<option disabled="disabled" value="-2">---------------</option>';
        for (var i = 0; i < ct.length; i++) {
            if (ct[i].Name != -2)
                options += '<option value="' + ct[i].Name + '">' + ct[i].DisplayName + '</option>';
            else
                options += '<option disabled="disabled" value="' + ct[i].Name + '">' + ct[i].DisplayName + '</option>';
        }
        $("select#city_region").html(options);

        options = '';
        lo = j.Locations;

        for (var i = 0; i < lo.length; i++) {
            options += '<option value="' + lo[i].Name + '">' + lo[i].DisplayName + '</option>';
        }
        $("select#location").html(options);
        $("#city_regionAJAXloading").hide();
    }

    function popLoc(j) {
        var options = '';
        lo = j.Locations;

        for (var i = 0; i < lo.length; i++) {
            
            options += '<option value="' + lo[i].Name + '">' + lo[i].DisplayName + '</option>';
        }
        $("select#location").html(options);
        $("#locationAJAXloading").hide();
    }

    //Unused function bcoz,item with text '------' cannot be selectable now.
    function cancelAjaxLoad(ctl) {
        var oldValue, oldIndex;
        oldIndex = 0;

        for (j = 0; j < ctl.options.length; j++) {

            if (ctl.options[j].defaultSelected) {
                ctl.options[j].defaultSelected = false;
                oldValue = ctl.options[j].value;
                oldIndex = j;
            }

        }

        // If the selected city is "---------" (value -2); Change event to be cancelled  and previous value selected
        if (ctl.value == -2) {
            ctl.selectedIndex = oldIndex;
            ctl.options[oldIndex].defaultSelected = true;
            return false;
        }
        ctl.options[ctl.selectedIndex].defaultSelected = true;

        // Some cities are duplicated above and below "---------"; Change event to be cancelled if selected city is a duplicate city
        if (oldValue == ctl.options[ctl.selectedIndex].value) {
            return false;
        }
    }

    function ReadCookie(cookieName) {
        var theCookie = "" + document.cookie;
        var ind = theCookie.indexOf(cookieName);
        if (ind == -1 || cookieName == "") return "";
        var ind1 = theCookie.indexOf(';', ind);
        if (ind1 == -1) ind1 = theCookie.length;
        return unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
    }

    function ReadFromCookie() {
        var cookietext = document.cookie.indexOf("%7CSearchEng%7C=");
        var c_start = document.cookie.indexOf("%7CSearchEng%7C=");
        var c_end = document.cookie.length;
        var cookiedetails = document.cookie.substring(c_start, c_end);

        var cookieArray = cookiedetails.split("%7C");
        var country;
        var cityname;
        var suburbname;
        var searchby;
        for (var i = 0; i < cookieArray.length; i++) {

            if (cookieArray[i] == "SearchEng") {
                country = cookieArray[i + 2];
                cityname = cookieArray[i + 3];
                suburbname = cookieArray[i + 4];
                searchby = cookieArray[i + 7];
                //alert(country + "***" + cityname + "***" + suburbname + "***" + searchby);
                gc_country = URLDecode(country);
                gc_city = URLDecode(cityname);
                gc_suburb = URLDecode(suburbname);
                gc_searchby = searchby;
                break;
            }
        }
        gc_lc = ReadCookie("lc");
    }

    function populateFromCookie() {

        ReadFromCookie()
        if ((gc_city == "") || (typeof (gc_city) == 'undefined')) {
            return;
        }

        $("#city_region").val(URLDecode(gc_city));
        if ($("#city_region").val() == "undefined") {
            return;
        }
        $.getJSON(AXPAGE, { param1: $("#city_region").val(), action: 'getlocations', proxyid: DRE_GUID }, function(j) {
            _cache.setItem("L_" + $("#city_region").val(), j); 
            //$.jCache.setItem("L_" + $("#city_region").val(), j);
            popLoc(j)
            FavTopCitiesLMDealsAJAXRequest($("select#country").val(), $("select#city_region").val());
        });
    }


    $("select#city_region").change(function() {
        //if (cancelAjaxLoad(document.getElementById("city_region")) == false) return; -- unused bcoz,item with text '------' cannot be selectable now.
        $("#locationAJAXloading").show();
        if(_cache.getItem("L_" + $("#city_region").val()))
        {
            var k = _cache.getItem("L_" + $("#city_region").val())
            popLoc(k);
            FavTopCitiesLMDealsAJAXRequest($("select#country").val(), $("select#city_region").val());
            return;
        }
        /*
        if ($.jCache.hasItem("L_" + $("#city_region").val())) {
            var k = $.jCache.getItem("L_" + $("#city_region").val());
            popLoc(k);
            FavTopCitiesLMDealsAJAXRequest($("select#country").val(), $("select#city_region").val());
            return;
        }
        */
        $.getJSON(AXPAGE, { param1: $(this).val(), action: 'getlocations', proxyid: DRE_GUID }, function(j) {
            _cache.setItem("L_" + $("#city_region").val(), j); 
            //$.jCache.setItem("L_" + $("#city_region").val(), j);
            popLoc(j)
            SaveCookieFromClient();
            FavTopCitiesLMDealsAJAXRequest($("select#country").val(), $("select#city_region").val());
        });

    });

    $("select#location").change(function() {
        SaveCookieFromClient();
    });

});



$().ready(function() {

    $("#destination").keydown(function() {
        if ($("#destination").val() == HINT_DRE) {
            $("#destination").val("");
        }
        $("#destination").css("color", "#000");
    });

    $("#destination").click(function() {
        if ($("#destination").val() == HINT_DRE) {
            $("#destination").val("");
        }
        $("#destination").css("color", "#000");
    });


    $("#location").mouseover(function() {
        if ($.browser.msie) {
            $("#location").css("position", "absolute");
            $("#detailedsearch").css("height", "99px");
            $("#location").css("width", "270px");
        }
    });

    $("#location").change(function() {
        ShrinkLocationCombo();
    });

    $("#city_region").mouseover(function() {
        ShrinkLocationCombo();
    });

    $("#divsubmit").mouseover(function() {
        ShrinkLocationCombo();
    });

    $("#divstars").mouseover(function() {
        ShrinkLocationCombo();
    });

    $("#divcaption").mouseover(function() {
        ShrinkLocationCombo();
    });



    function ShrinkLocationCombo() {
        if ($.browser.msie) {
            $("#location").css("position", "");
            $("#location").css("width", "150px");
        }
    }

    $(".radio_button").click(function(evt) {
        var selopt = $(".radio_button:checked").val();
        if (selopt == "dest") {
            $("#SearchBy").val("LocationKey");
            $("#hotelname").hide();
            $("#destination").val(HINT_DRE);
            $("#destination").css("color", "#C0C0C0");
            $("#destination").show();
            $("#destination").focus();
        }
        else if (selopt == "hname") {
            $("#SearchBy").val("Name");
            $("#hotelname").show();
            $("#destination").hide();
            $("#hotelname").val("");
        }
        SaveCookieFromClient();
    });

    var autocompleteJSON = function(raw) {
        var json = typeof (raw) === "array" ? raw : raw.destinations;
        var parsed = [];
        for (var i = 0; i < json.length; i++) {
            var row = json[i];
            parsed.push({
                data: row,
                value: row["text"] + ' [' + row["id"] + ']',
                result: row["text"]
            });
        }

        return parsed;
    };

    $("input[name='destination']").result(function(event, data,
            formatted) {

        $("input[name='hdnLocationID']").val(data["id"]);
        $("input[name='hdnLocationKey']").val(data["loc"]);
    });


    $("input[name='destination']").autocomplete("DREWebServiceProxy.asp?lc=EN&affid=5&ctryid=3&SiteCode=HTC&proxyid=" + DRE_GUID,
                  { width: "inherit"
                   , minChars: 3
                   , max: 25
                   , delay: 900
                   , dataType: "json"
                   , parse: autocompleteJSON
                   , formatItem: function(row) { return row["text"] }
                   , mustMatch: false
                   , selectFirst: false
                  });


    $("#destination").val(HINT_DRE);
    $("#destination").css("color", "#C0C0C0");
    $("#destination").focus();
});




function URLDecode(urlStr) {
    return unescape(urlStr.replace(/\+/g, " "))
}

function setDestination(locationid, location) {

    if (document.getElementById('destination') != null)
        document.getElementById('destination').value = location;
    if (document.getElementById('hdnLocationKey') != null)

        document.getElementById('hdnLocationKey').value = location;
    if (document.getElementById('hdnLocationID') != null)
        document.getElementById("hdnLocationID").value = locationid;
}

function activateDRESearch(enable) {
    var searchBy = document.getElementById("SearchBy");

    if (searchBy != null) {
        searchBy.value = (enable ? "LocationKey" : "criteria");
    }
}


function CheckVal(form) {
    var str = trim($("#membershipid").val());
        
    if (str.indexOf("@") != -1) {
        if (typeof (Membership_MemLogin_MemID) == "undefined")
            Membership_MemLogin_MemID = "The e-mail you entered is not a valid e-mail address."

        if (notEmail(form.membershipid, "", Membership_MemLogin_MemID)) return false
    } else {
        if (notNumber(trim(form.membershipid.value))) {
            if (typeof (Membership_MemLogin_NotVldEmail) == "undefined")
                Membership_MemLogin_NotVldEmail = "The e-mail you entered is not a valid e-mail address."

            alert(Membership_MemLogin_NotVldEmail)            
            return false
        }
    }

    if (typeof (Membership_MemLogin_EntEmail) == "undefined")
        Membership_MemLogin_EntEmail = "Please enter E-mail."

    if (isEmpty(form.membershipid, "", Membership_MemLogin_EntEmail)) return false
    if (typeof (Membership_MemLogin_EntPsw) == "undefined")
        Membership_MemLogin_EntPsw = "Please enter Password."

    if (isEmpty(form.password, "", Membership_MemLogin_EntPsw)) return false
    return true;
}

function Retrivevalues() {
    $.getJSON(AXPAGE, { action: 'retrivevalues', proxyid: DRE_GUID }, function(j) {
        var results = j.values;
        if (results[0].data == "True" && (results[2].data == "LocationKey" ||  results[2].data == "HotelName")) {
            $("#default_search").val("crit");
            $("input[name='hdnLocationID']").val("");
            $("#destinationsearch").show();
            $("#detailedsearch").hide();
            $("#caption").html('Use our classic search');
            if (results[2].data == "LocationKey") {
                document.getElementById("sbdest").checked = true;
                document.getElementById("sbhname").checked = false;
                $("#SearchBy").val("LocationKey");
                $("#hotelname").hide();
                $("#destination").show();
                $("#destination").val(HINT_DRE);
                $("#destination").css("color", "#C0C0C0");
            }
            else if (results[2].data == "HotelName") {
                document.getElementById("sbhname").checked = true;
                document.getElementById("sbdest").checked = false;
                $("#SearchBy").val("Name");
                $("#hotelname").show();
                $("#destination").hide();
                $("#hotelname").val("");
            }
        }
        else if  (results[0].data == "True" ) {
            document.getElementById("sbdest").checked = true;
            document.getElementById("sbhname").checked = false;
            $("#default_search").val("dest");
            $("#SearchBy").val("criteria");
            $("#destinationsearch").hide();
            $("#detailedsearch").show();
            $("#caption").html('Use our new search now!');
            $("input[name='hdnLocationID']").val("");
        }
    });
    if (navigator.userAgent.indexOf("Firefox") != -1)
        clearTimeout(timerID);
}


function SaveCookieFromClient() {
    var strChkin = document.getElementById('Cal1').value;
    var strChkout = document.getElementById('Cal2').value;
    var strCountry = document.getElementById('country').value;
    var strCity = document.getElementById('city_region').value;
    var strSuburb = document.getElementById('location').value;
    var strSrchBy = document.getElementById('SearchBy').value;
    SearchEngineCookie.SetSearchEngineCookieWithSearchBy(strChkin, strChkout, strCountry, strCity, strSuburb, strSrchBy);
}
(function($) { $.extend($.ui, { datepicker: { version: "1.7.1"} }); var PROP_NAME = 'datepicker'; function Datepicker() { this.debug = false; this._curInst = null; this._keyEvent = false; this._disabledInputs = []; this._datepickerShowing = false; this._inDialog = false; this._mainDivId = 'ui-datepicker-div'; this._inlineClass = 'ui-datepicker-inline'; this._appendClass = 'ui-datepicker-append'; this._triggerClass = 'ui-datepicker-trigger'; this._dialogClass = 'ui-datepicker-dialog'; this._disableClass = 'ui-datepicker-disabled'; this._unselectableClass = 'ui-datepicker-unselectable'; this._currentClass = 'ui-datepicker-current-day'; this._dayOverClass = 'ui-datepicker-days-cell-over'; this.regional = []; this.regional[''] = { closeText: 'Done', prevText: 'Prev', nextText: 'Next', currentText: 'Today', monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], dateFormat: 'mm/dd/yy', firstDay: 0, isRTL: false }; this._defaults = { showOn: 'focus', showAnim: 'show', showOptions: {}, defaultDate: null, appendText: '', buttonText: '...', buttonImage: '', buttonImageOnly: false, hideIfNoPrevNext: false, navigationAsDateFormat: false, gotoCurrent: false, changeMonth: false, changeYear: false, showMonthAfterYear: false, yearRange: '-10:+10', showOtherMonths: false, calculateWeek: this.iso8601Week, shortYearCutoff: '+10', minDate: null, maxDate: null, duration: 'normal', beforeShowDay: null, beforeShow: null, onSelect: null, onChangeMonthYear: null, onClose: null, numberOfMonths: 1, showCurrentAtPos: 0, stepMonths: 1, stepBigMonths: 12, altField: '', altFormat: '', constrainInput: true, showButtonPanel: false, customTriggerElementID: null }; $.extend(this._defaults, this.regional['']); this.dpDiv = $('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>') } $.extend(Datepicker.prototype, { markerClassName: 'hasDatepicker', log: function() { if (this.debug) console.log.apply('', arguments) }, setDefaults: function(settings) { extendRemove(this._defaults, settings || {}); return this }, _attachDatepicker: function(target, settings) { var inlineSettings = null; for (var attrName in this._defaults) { var attrValue = target.getAttribute('date:' + attrName); if (attrValue) { inlineSettings = inlineSettings || {}; try { inlineSettings[attrName] = eval(attrValue) } catch (err) { inlineSettings[attrName] = attrValue } } } var nodeName = target.nodeName.toLowerCase(); var inline = (nodeName == 'div' || nodeName == 'span'); if (!target.id) target.id = 'dp' + (++this.uuid); var inst = this._newInst($(target), inline); inst.settings = $.extend({}, settings || {}, inlineSettings || {}); if (nodeName == 'input') { this._connectDatepicker(target, inst) } else if (inline) { this._inlineDatepicker(target, inst) } }, _newInst: function(target, inline) { var id = target[0].id.replace(/([:\[\]\.])/g, '\\\\$1'); return { id: id, input: target, selectedDay: 0, selectedMonth: 0, selectedYear: 0, drawMonth: 0, drawYear: 0, inline: inline, dpDiv: (!inline ? this.dpDiv : $('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))} }, _connectDatepicker: function(target, inst) { var input = $(target); inst.trigger = $([]); if (input.hasClass(this.markerClassName)) return; var appendText = this._get(inst, 'appendText'); var isRTL = this._get(inst, 'isRTL'); if (appendText) input[isRTL ? 'before' : 'after']('<span class="' + this._appendClass + '">' + appendText + '</span>'); var showOn = this._get(inst, 'showOn'); if (showOn == 'focus' || showOn == 'both') input.focus(this._showDatepicker); if (showOn == 'customclick') { input.focus(this._showDatepicker); var customTriggerElementID = this._get(inst, 'customTriggerElementID'); if (customTriggerElementID) { inst.trigger = $('#' + customTriggerElementID).addClass(this._triggerClass); inst.trigger.click(function() { if ($.datepicker._datepickerShowing && $.datepicker._lastInput == target) $.datepicker._hideDatepicker(); else $.datepicker._showDatepicker(target); return false }) } } if (showOn == 'button' || showOn == 'both') { var buttonText = this._get(inst, 'buttonText'); var buttonImage = this._get(inst, 'buttonImage'); inst.trigger = $(this._get(inst, 'buttonImageOnly') ? $('<img/>').addClass(this._triggerClass).attr({ src: buttonImage, alt: buttonText, title: buttonText }) : $('<button type="button"></button>').addClass(this._triggerClass).html(buttonImage == '' ? buttonText : $('<img/>').attr({ src: buttonImage, alt: buttonText, title: buttonText }))); input[isRTL ? 'before' : 'after'](inst.trigger); inst.trigger.click(function() { if ($.datepicker._datepickerShowing && $.datepicker._lastInput == target) $.datepicker._hideDatepicker(); else $.datepicker._showDatepicker(target); return false }) } input.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).bind("setData.datepicker", function(event, key, value) { inst.settings[key] = value }).bind("getData.datepicker", function(event, key) { return this._get(inst, key) }); $.data(target, PROP_NAME, inst) }, _inlineDatepicker: function(target, inst) { var divSpan = $(target); if (divSpan.hasClass(this.markerClassName)) return; divSpan.addClass(this.markerClassName).append(inst.dpDiv).bind("setData.datepicker", function(event, key, value) { inst.settings[key] = value }).bind("getData.datepicker", function(event, key) { return this._get(inst, key) }); $.data(target, PROP_NAME, inst); this._setDate(inst, this._getDefaultDate(inst)); this._updateDatepicker(inst); this._updateAlternate(inst) }, _dialogDatepicker: function(input, dateText, onSelect, settings, pos) { var inst = this._dialogInst; if (!inst) { var id = 'dp' + (++this.uuid); this._dialogInput = $('<input type="text" id="' + id + '" size="1" style="position: absolute; top: -100px;"/>'); this._dialogInput.keydown(this._doKeyDown); $('body').append(this._dialogInput); inst = this._dialogInst = this._newInst(this._dialogInput, false); inst.settings = {}; $.data(this._dialogInput[0], PROP_NAME, inst) } extendRemove(inst.settings, settings || {}); this._dialogInput.val(dateText); this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null); if (!this._pos) { var browserWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var browserHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; var scrollY = document.documentElement.scrollTop || document.body.scrollTop; this._pos = [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY] } this._dialogInput.css('left', this._pos[0] + 'px').css('top', this._pos[1] + 'px'); inst.settings.onSelect = onSelect; this._inDialog = true; this.dpDiv.addClass(this._dialogClass); this._showDatepicker(this._dialogInput[0]); if ($.blockUI) $.blockUI(this.dpDiv); $.data(this._dialogInput[0], PROP_NAME, inst); return this }, _destroyDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return } var nodeName = target.nodeName.toLowerCase(); $.removeData(target, PROP_NAME); if (nodeName == 'input') { inst.trigger.remove(); $target.siblings('.' + this._appendClass).remove().end().removeClass(this.markerClassName).unbind('focus', this._showDatepicker).unbind('keydown', this._doKeyDown).unbind('keypress', this._doKeyPress) } else if (nodeName == 'div' || nodeName == 'span') $target.removeClass(this.markerClassName).empty() }, _enableDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return } var nodeName = target.nodeName.toLowerCase(); if (nodeName == 'input') { target.disabled = false; inst.trigger.filter("button").each(function() { this.disabled = false }).end().filter("img").css({ opacity: '1.0', cursor: '' }) } else if (nodeName == 'div' || nodeName == 'span') { var inline = $target.children('.' + this._inlineClass); inline.children().removeClass('ui-state-disabled') } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value == target ? null : value) }) }, _disableDatepicker: function(target) { var $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return } var nodeName = target.nodeName.toLowerCase(); if (nodeName == 'input') { target.disabled = true; inst.trigger.filter("button").each(function() { this.disabled = true }).end().filter("img").css({ opacity: '0.5', cursor: 'default' }) } else if (nodeName == 'div' || nodeName == 'span') { var inline = $target.children('.' + this._inlineClass); inline.children().addClass('ui-state-disabled') } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value == target ? null : value) }); this._disabledInputs[this._disabledInputs.length] = target }, _isDisabledDatepicker: function(target) { if (!target) { return false } for (var i = 0; i < this._disabledInputs.length; i++) { if (this._disabledInputs[i] == target) return true } return false }, _getInst: function(target) { try { return $.data(target, PROP_NAME) } catch (err) { throw 'Missing instance data for this datepicker'; } }, _optionDatepicker: function(target, name, value) { var settings = name || {}; if (typeof name == 'string') { settings = {}; settings[name] = value } var inst = this._getInst(target); if (inst) { if (this._curInst == inst) { this._hideDatepicker(null) } extendRemove(inst.settings, settings); var date = new Date(); extendRemove(inst, { rangeStart: null, endDay: null, endMonth: null, endYear: null, selectedDay: date.getDate(), selectedMonth: date.getMonth(), selectedYear: date.getFullYear(), currentDay: date.getDate(), currentMonth: date.getMonth(), currentYear: date.getFullYear(), drawMonth: date.getMonth(), drawYear: date.getFullYear() }); this._updateDatepicker(inst) } }, _changeDatepicker: function(target, name, value) { this._optionDatepicker(target, name, value) }, _refreshDatepicker: function(target) { var inst = this._getInst(target); if (inst) { this._updateDatepicker(inst) } }, _setDateDatepicker: function(target, date, endDate) { var inst = this._getInst(target); if (inst) { this._setDate(inst, date, endDate); this._updateDatepicker(inst); this._updateAlternate(inst) } }, _getDateDatepicker: function(target) { var inst = this._getInst(target); if (inst && !inst.inline) this._setDateFromField(inst); return (inst ? this._getDate(inst) : null) }, _doKeyDown: function(event) { var inst = $.datepicker._getInst(event.target); var handled = true; var isRTL = inst.dpDiv.is('.ui-datepicker-rtl'); inst._keyEvent = true; if ($.datepicker._datepickerShowing) switch (event.keyCode) { case 9: $.datepicker._hideDatepicker(null, ''); break; case 13: var sel = $('td.' + $.datepicker._dayOverClass + ', td.' + $.datepicker._currentClass, inst.dpDiv); if (sel[0]) $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]); else $.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration')); return false; break; case 27: $.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration')); break; case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, 'stepBigMonths') : -$.datepicker._get(inst, 'stepMonths')), 'M'); break; case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, 'stepBigMonths') : +$.datepicker._get(inst, 'stepMonths')), 'M'); break; case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target); handled = event.ctrlKey || event.metaKey; break; case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target); handled = event.ctrlKey || event.metaKey; break; case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D'); handled = event.ctrlKey || event.metaKey; if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, 'stepBigMonths') : -$.datepicker._get(inst, 'stepMonths')), 'M'); break; case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D'); handled = event.ctrlKey || event.metaKey; break; case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D'); handled = event.ctrlKey || event.metaKey; if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, 'stepBigMonths') : +$.datepicker._get(inst, 'stepMonths')), 'M'); break; case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D'); handled = event.ctrlKey || event.metaKey; break; default: handled = false } else if (event.keyCode == 36 && event.ctrlKey) $.datepicker._showDatepicker(this); else { handled = false } if (handled) { event.preventDefault(); event.stopPropagation() } }, _doKeyPress: function(event) { var inst = $.datepicker._getInst(event.target); if ($.datepicker._get(inst, 'constrainInput')) { var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat')); var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode); return event.ctrlKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1) } }, _showDatepicker: function(input) { input = input.target || input; if (input.nodeName.toLowerCase() != 'input') input = $('input', input.parentNode)[0]; if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) return; var inst = $.datepicker._getInst(input); var beforeShow = $.datepicker._get(inst, 'beforeShow'); extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {})); $.datepicker._hideDatepicker(null, ''); $.datepicker._lastInput = input; $.datepicker._setDateFromField(inst); if ($.datepicker._inDialog) input.value = ''; if (!$.datepicker._pos) { $.datepicker._pos = $.datepicker._findPos(input); $.datepicker._pos[1] += input.offsetHeight } var isFixed = false; $(input).parents().each(function() { isFixed |= $(this).css('position') == 'fixed'; return !isFixed }); if (isFixed && $.browser.opera) { $.datepicker._pos[0] -= document.documentElement.scrollLeft; $.datepicker._pos[1] -= document.documentElement.scrollTop } var offset = { left: $.datepicker._pos[0], top: $.datepicker._pos[1] }; $.datepicker._pos = null; inst.rangeStart = null; inst.dpDiv.css({ position: 'absolute', display: 'block', top: '-1000px' }); $.datepicker._updateDatepicker(inst); offset = $.datepicker._checkOffset(inst, offset, isFixed); inst.dpDiv.css({ position: ($.datepicker._inDialog && $.blockUI ? 'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none', left: offset.left + 'px', top: offset.top + 'px' }); if (!inst.inline) { var showAnim = $.datepicker._get(inst, 'showAnim') || 'show'; var duration = $.datepicker._get(inst, 'duration'); var postProcess = function() { $.datepicker._datepickerShowing = true; if ($.browser.msie && parseInt($.browser.version, 10) < 7) $('iframe.ui-datepicker-cover').css({ width: inst.dpDiv.width() + 4, height: inst.dpDiv.height() + 4 }) }; if ($.effects && $.effects[showAnim]) inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess); else inst.dpDiv[showAnim](duration, postProcess); if (duration == '') postProcess(); if (inst.input[0].type != 'hidden') inst.input[0].focus(); $.datepicker._curInst = inst } }, _updateDatepicker: function(inst) { var dims = { width: inst.dpDiv.width() + 4, height: inst.dpDiv.height() + 4 }; var self = this; inst.dpDiv.empty().append(this._generateHTML(inst)).find('iframe.ui-datepicker-cover').css({ width: dims.width, height: dims.height }).end().find('button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a').bind('mouseout', function() { $(this).removeClass('ui-state-hover'); if (this.className.indexOf('ui-datepicker-prev') != -1) $(this).removeClass('ui-datepicker-prev-hover'); if (this.className.indexOf('ui-datepicker-next') != -1) $(this).removeClass('ui-datepicker-next-hover') }).bind('mouseover', function() { if (!self._isDisabledDatepicker(inst.inline ? inst.dpDiv.parent()[0] : inst.input[0])) { $(this).parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover'); $(this).addClass('ui-state-hover'); if (this.className.indexOf('ui-datepicker-prev') != -1) $(this).addClass('ui-datepicker-prev-hover'); if (this.className.indexOf('ui-datepicker-next') != -1) $(this).addClass('ui-datepicker-next-hover') } }).end().find('.' + this._dayOverClass + ' a').trigger('mouseover').end(); var numMonths = this._getNumberOfMonths(inst); var cols = numMonths[1]; var width = 17; if (cols > 1) { if (window.navigator.userAgent.indexOf("MSIE") > -1 && window.navigator.userAgent.indexOf("8.0") == -1) { inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', '360px') } else { inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', 'auto') } } else { inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width('') } inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') + 'Class']('ui-datepicker-multi'); inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') + 'Class']('ui-datepicker-rtl'); if (inst.input && inst.input[0].type != 'hidden' && inst == $.datepicker._curInst) $(inst.input[0]).focus() }, _checkOffset: function(inst, offset, isFixed) { var dpWidth = inst.dpDiv.outerWidth(); var dpHeight = inst.dpDiv.outerHeight(); var inputWidth = inst.input ? inst.input.outerWidth() : 0; var inputHeight = inst.input ? inst.input.outerHeight() : 0; var viewWidth = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) + $(document).scrollLeft(); var viewHeight = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight) + $(document).scrollTop(); offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0); offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0; offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0; offset.left -= (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0; offset.top -= (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(offset.top + dpHeight + inputHeight * 2 - viewHeight) : 0; return offset }, _findPos: function(obj) { while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) { obj = obj.nextSibling } var position = $(obj).offset(); return [position.left, position.top] }, _hideDatepicker: function(input, duration) { var inst = this._curInst; if (!inst || (input && inst != $.data(input, PROP_NAME))) return; if (inst.stayOpen) this._selectDate('#' + inst.id, this._formatDate(inst, inst.currentDay, inst.currentMonth, inst.currentYear)); inst.stayOpen = false; if (this._datepickerShowing) { duration = (duration != null ? duration : this._get(inst, 'duration')); var showAnim = this._get(inst, 'showAnim'); var postProcess = function() { $.datepicker._tidyDialog(inst) }; if (duration != '' && $.effects && $.effects[showAnim]) inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess); else inst.dpDiv[(duration == '' ? 'hide' : (showAnim == 'slideDown' ? 'slideUp' : (showAnim == 'fadeIn' ? 'fadeOut' : 'hide')))](duration, postProcess); if (duration == '') this._tidyDialog(inst); var onClose = this._get(inst, 'onClose'); if (onClose) onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ''), inst]); this._datepickerShowing = false; this._lastInput = null; if (this._inDialog) { this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' }); if ($.blockUI) { $.unblockUI(); $('body').append(this.dpDiv) } } this._inDialog = false } this._curInst = null }, _tidyDialog: function(inst) { inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar') }, _checkExternalClick: function(event) { if (!$.datepicker._curInst) return; var $target = $(event.target); if (($target.parents('#' + $.datepicker._mainDivId).length == 0) && !$target.hasClass($.datepicker.markerClassName) && !$target.hasClass($.datepicker._triggerClass) && $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI)) $.datepicker._hideDatepicker(null, '') }, _adjustDate: function(id, offset, period) { var target = $(id); var inst = this._getInst(target[0]); if (this._isDisabledDatepicker(target[0])) { return } this._adjustInstDate(inst, offset + (period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), period); this._updateDatepicker(inst) }, _gotoToday: function(id) { var target = $(id); var inst = this._getInst(target[0]); if (this._get(inst, 'gotoCurrent') && inst.currentDay) { inst.selectedDay = inst.currentDay; inst.drawMonth = inst.selectedMonth = inst.currentMonth; inst.drawYear = inst.selectedYear = inst.currentYear } else { var date = new Date(); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear() } this._notifyChange(inst); this._adjustDate(target) }, _selectMonthYear: function(id, select, period) { var target = $(id); var inst = this._getInst(target[0]); inst._selectingMonthYear = false; inst['selected' + (period == 'M' ? 'Month' : 'Year')] = inst['draw' + (period == 'M' ? 'Month' : 'Year')] = parseInt(select.options[select.selectedIndex].value, 10); this._notifyChange(inst); this._adjustDate(target) }, _clickMonthYear: function(id) { var target = $(id); var inst = this._getInst(target[0]); if (inst.input && inst._selectingMonthYear && !$.browser.msie) inst.input[0].focus(); inst._selectingMonthYear = !inst._selectingMonthYear }, _selectDay: function(id, month, year, td) { var target = $(id); if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) { return } var inst = this._getInst(target[0]); inst.selectedDay = inst.currentDay = $('a', td).html(); inst.selectedMonth = inst.currentMonth = month; inst.selectedYear = inst.currentYear = year; if (inst.stayOpen) { inst.endDay = inst.endMonth = inst.endYear = null } this._selectDate(id, this._formatDate(inst, inst.currentDay, inst.currentMonth, inst.currentYear)); if (inst.stayOpen) { inst.rangeStart = this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)); this._updateDatepicker(inst) } }, _clearDate: function(id) { var target = $(id); var inst = this._getInst(target[0]); inst.stayOpen = false; inst.endDay = inst.endMonth = inst.endYear = inst.rangeStart = null; this._selectDate(target, '') }, _selectDate: function(id, dateStr) { var target = $(id); var inst = this._getInst(target[0]); dateStr = (dateStr != null ? dateStr : this._formatDate(inst)); if (inst.input) inst.input.val(dateStr); this._updateAlternate(inst); var onSelect = this._get(inst, 'onSelect'); if (onSelect) onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); else if (inst.input) inst.input.trigger('change'); if (inst.inline) this._updateDatepicker(inst); else if (!inst.stayOpen) { this._hideDatepicker(null, this._get(inst, 'duration')); this._lastInput = inst.input[0]; if (typeof (inst.input[0]) != 'object') inst.input[0].focus(); this._lastInput = null } }, _updateAlternate: function(inst) { var altField = this._get(inst, 'altField'); if (altField) { var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat'); var date = this._getDate(inst); dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst)); $(altField).each(function() { $(this).val(dateStr) }) } }, noWeekends: function(date) { var day = date.getDay(); return [(day > 0 && day < 6), ''] }, iso8601Week: function(date) { var checkDate = new Date(date.getFullYear(), date.getMonth(), date.getDate()); var firstMon = new Date(checkDate.getFullYear(), 1 - 1, 4); var firstDay = firstMon.getDay() || 7; firstMon.setDate(firstMon.getDate() + 1 - firstDay); if (firstDay < 4 && checkDate < firstMon) { checkDate.setDate(checkDate.getDate() - 3); return $.datepicker.iso8601Week(checkDate) } else if (checkDate > new Date(checkDate.getFullYear(), 12 - 1, 28)) { firstDay = new Date(checkDate.getFullYear() + 1, 1 - 1, 4).getDay() || 7; if (firstDay > 4 && (checkDate.getDay() || 7) < firstDay - 3) { return 1 } } return Math.floor(((checkDate - firstMon) / 86400000) / 7) + 1 }, parseDate: function(format, value, settings) { if (format == null || value == null) throw 'Invalid arguments'; value = (typeof value == 'object' ? value.toString() : value + ''); if (value == '') return null; var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff; var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort; var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames; var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort; var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames; var year = -1; var month = -1; var day = -1; var doy = -1; var literal = false; var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches }; var getNumber = function(match) { lookAhead(match); var origSize = (match == '@' ? 14 : (match == 'y' ? 4 : (match == 'o' ? 3 : 2))); var size = origSize; var num = 0; while (size > 0 && iValue < value.length && value.charAt(iValue) >= '0' && value.charAt(iValue) <= '9') { num = num * 10 + parseInt(value.charAt(iValue++), 10); size-- } if (size == origSize) throw 'Missing number at position ' + iValue; return num }; var getName = function(match, shortNames, longNames) { var names = (lookAhead(match) ? longNames : shortNames); var size = 0; for (var j = 0; j < names.length; j++) size = Math.max(size, names[j].length); var name = ''; var iInit = iValue; while (size > 0 && iValue < value.length) { name += value.charAt(iValue++); for (var i = 0; i < names.length; i++) if (name == names[i]) return i + 1; size-- } throw 'Unknown name at position ' + iInit; }; var checkLiteral = function() { if (value.charAt(iValue) != format.charAt(iFormat)) throw 'Unexpected literal at position ' + iValue; iValue++ }; var iValue = 0; for (var iFormat = 0; iFormat < format.length; iFormat++) { if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else checkLiteral(); else switch (format.charAt(iFormat)) { case 'd': day = getNumber('d'); break; case 'D': getName('D', dayNamesShort, dayNames); break; case 'o': doy = getNumber('o'); break; case 'm': month = getNumber('m'); break; case 'M': month = getName('M', monthNamesShort, monthNames); break; case 'y': year = getNumber('y'); break; case '@': var date = new Date(getNumber('@')); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "'": if (lookAhead("'")) checkLiteral(); else literal = true; break; default: checkLiteral() } } if (year == -1) year = new Date().getFullYear(); else if (year < 100) year += new Date().getFullYear() - new Date().getFullYear() % 100 + (year <= shortYearCutoff ? 0 : -100); if (doy > -1) { month = 1; day = doy; do { var dim = this._getDaysInMonth(year, month - 1); if (day <= dim) break; month++; day -= dim } while (true) } var date = this._daylightSavingAdjust(new Date(year, month - 1, day)); if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day) throw 'Invalid date'; return date }, ATOM: 'yy-mm-dd', COOKIE: 'D, dd M yy', ISO_8601: 'yy-mm-dd', RFC_822: 'D, d M y', RFC_850: 'DD, dd-M-y', RFC_1036: 'D, d M y', RFC_1123: 'D, d M yy', RFC_2822: 'D, d M yy', RSS: 'D, d M y', TIMESTAMP: '@', W3C: 'yy-mm-dd', formatDate: function(format, date, settings) { if (!date) return ''; var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort; var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames; var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort; var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames; var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches }; var formatNumber = function(match, value, len) { var num = '' + value; if (lookAhead(match)) while (num.length < len) num = '0' + num; return num }; var formatName = function(match, value, shortNames, longNames) { return (lookAhead(match) ? longNames[value] : shortNames[value]) }; var output = ''; var literal = false; if (date) for (var iFormat = 0; iFormat < format.length; iFormat++) { if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else output += format.charAt(iFormat); else switch (format.charAt(iFormat)) { case 'd': output += formatNumber('d', date.getDate(), 2); break; case 'D': output += formatName('D', date.getDay(), dayNamesShort, dayNames); break; case 'o': var doy = date.getDate(); for (var m = date.getMonth() - 1; m >= 0; m--) doy += this._getDaysInMonth(date.getFullYear(), m); output += formatNumber('o', doy, 3); break; case 'm': output += formatNumber('m', date.getMonth() + 1, 2); break; case 'M': output += formatName('M', date.getMonth(), monthNamesShort, monthNames); break; case 'y': output += (lookAhead('y') ? date.getFullYear() : (date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100); break; case '@': output += date.getTime(); break; case "'": if (lookAhead("'")) output += "'"; else literal = true; break; default: output += format.charAt(iFormat) } } return output }, _possibleChars: function(format) { var chars = ''; var literal = false; for (var iFormat = 0; iFormat < format.length; iFormat++) if (literal) if (format.charAt(iFormat) == "'" && !lookAhead("'")) literal = false; else chars += format.charAt(iFormat); else switch (format.charAt(iFormat)) { case 'd': case 'm': case 'y': case '@': chars += '0123456789'; break; case 'D': case 'M': return null; case "'": if (lookAhead("'")) chars += "'"; else literal = true; break; default: chars += format.charAt(iFormat) } return chars }, _get: function(inst, name) { return inst.settings[name] !== undefined ? inst.settings[name] : this._defaults[name] }, _setDateFromField: function(inst) { var dateFormat = this._get(inst, 'dateFormat'); var dates = inst.input ? inst.input.val() : null; inst.endDay = inst.endMonth = inst.endYear = null; var date = defaultDate = this._getDefaultDate(inst); var settings = this._getFormatConfig(inst); try { date = this.parseDate(dateFormat, dates, settings) || defaultDate } catch (event) { this.log(event); date = defaultDate } var maxDate = this._get(inst, 'maxDate'); if (date > maxDate) date = defaultDate; inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); inst.currentDay = (dates ? date.getDate() : 0); inst.currentMonth = (dates ? date.getMonth() : 0); inst.currentYear = (dates ? date.getFullYear() : 0); this._adjustInstDate(inst) }, _getDefaultDate: function(inst) { var date = this._determineDate(this._get(inst, 'defaultDate'), new Date()); var minDate = this._getMinMaxDate(inst, 'min', true); var maxDate = this._getMinMaxDate(inst, 'max'); date = (minDate && date < minDate ? minDate : date); date = (maxDate && date > maxDate ? maxDate : date); return date }, _determineDate: function(date, defaultDate) { var offsetNumeric = function(offset) { var date = new Date(); date.setDate(date.getDate() + offset); return date }; var offsetString = function(offset, getDaysInMonth) { var date = new Date(); var year = date.getFullYear(); var month = date.getMonth(); var day = date.getDate(); var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g; var matches = pattern.exec(offset); while (matches) { switch (matches[2] || 'd') { case 'd': case 'D': day += parseInt(matches[1], 10); break; case 'w': case 'W': day += parseInt(matches[1], 10) * 7; break; case 'm': case 'M': month += parseInt(matches[1], 10); day = Math.min(day, getDaysInMonth(year, month)); break; case 'y': case 'Y': year += parseInt(matches[1], 10); day = Math.min(day, getDaysInMonth(year, month)); break } matches = pattern.exec(offset) } return new Date(year, month, day) }; date = (date == null ? defaultDate : (typeof date == 'string' ? offsetString(date, this._getDaysInMonth) : (typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : date))); date = (date && date.toString() == 'Invalid Date' ? defaultDate : date); if (date) { date.setHours(0); date.setMinutes(0); date.setSeconds(0); date.setMilliseconds(0) } return this._daylightSavingAdjust(date) }, _daylightSavingAdjust: function(date) { if (!date) return null; date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); return date }, _setDate: function(inst, date, endDate) { var clear = !(date); var origMonth = inst.selectedMonth; var origYear = inst.selectedYear; date = this._determineDate(date, new Date()); inst.selectedDay = inst.currentDay = date.getDate(); inst.drawMonth = inst.selectedMonth = inst.currentMonth = date.getMonth(); inst.drawYear = inst.selectedYear = inst.currentYear = date.getFullYear(); if (origMonth != inst.selectedMonth || origYear != inst.selectedYear) this._notifyChange(inst); this._adjustInstDate(inst); if (inst.input) { inst.input.val(clear ? '' : this._formatDate(inst)) } }, _getDate: function(inst) { var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null : this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); return startDate }, _generateHTML: function(inst) { var today = new Date(); today = this._daylightSavingAdjust(new Date(today.getFullYear(), today.getMonth(), today.getDate())); var isRTL = this._get(inst, 'isRTL'); var showButtonPanel = this._get(inst, 'showButtonPanel'); var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext'); var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat'); var numMonths = this._getNumberOfMonths(inst); var showCurrentAtPos = this._get(inst, 'showCurrentAtPos'); var stepMonths = this._get(inst, 'stepMonths'); var stepBigMonths = this._get(inst, 'stepBigMonths'); var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1); var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) : new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); var minDate = this._getMinMaxDate(inst, 'min', true); var maxDate = this._getMinMaxDate(inst, 'max'); var drawMonth = inst.drawMonth - showCurrentAtPos; var drawYear = inst.drawYear; if (drawMonth < 0) { drawMonth += 12; drawYear-- } if (maxDate) { var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(), maxDate.getMonth() - numMonths[1] + 1, maxDate.getDate())); maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw); while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) { drawMonth--; if (drawMonth < 0) { drawMonth = 11; drawYear-- } } } inst.drawMonth = drawMonth; inst.drawYear = drawYear; var prevText = this._get(inst, 'prevText'); prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText, this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)), this._getFormatConfig(inst))); var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ? '<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepMonths + ', \'M\');"' + ' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + (isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' : (hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + (isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>')); var nextText = this._get(inst, 'nextText'); nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText, this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)), this._getFormatConfig(inst))); var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ? '<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepMonths + ', \'M\');"' + ' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + (isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' : (hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + (isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>')); var currentText = this._get(inst, 'currentText'); var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today); currentText = (!navigationAsDateFormat ? currentText : this.formatDate(currentText, gotoDate, this._getFormatConfig(inst))); var controls = (!inst.inline ? '<div class="hc_close_hold"><a  class="hc_close" onclick="DP_jQuery.datepicker._hideDatepicker();">' + this._get(inst, 'closeText') + '</a></div>' : ''); var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') + (this._isInRange(inst, gotoDate) ? '' : '') + (isRTL ? '' : controls) + '</div>' : ''; var firstDay = parseInt(this._get(inst, 'firstDay'), 10); firstDay = (isNaN(firstDay) ? 0 : firstDay); var dayNames = this._get(inst, 'dayNames'); var dayNamesShort = this._get(inst, 'dayNamesShort'); var dayNamesMin = this._get(inst, 'dayNamesMin'); var monthNames = this._get(inst, 'monthNames'); var monthNamesShort = this._get(inst, 'monthNamesShort'); var beforeShowDay = this._get(inst, 'beforeShowDay'); var showOtherMonths = this._get(inst, 'showOtherMonths'); var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week; var endDate = inst.endDay ? this._daylightSavingAdjust(new Date(inst.endYear, inst.endMonth, inst.endDay)) : currentDate; var defaultDate = this._getDefaultDate(inst); var html = ''; for (var row = 0; row < numMonths[0]; row++) { var group = ''; for (var col = 0; col < numMonths[1]; col++) { var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay)); var cornerClass = ' ui-corner-all'; var calender = ''; if (isMultiMonth) { calender += '<div class="ui-datepicker-group ui-datepicker-group-'; switch (col) { case 0: calender += 'first'; cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break; case numMonths[1] - 1: calender += 'last'; cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break; default: calender += 'middle'; cornerClass = ''; break } calender += '">' } calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' + (/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') + (/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') + this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate, selectedDate, row > 0 || col > 0, monthNames, monthNamesShort) + '</div><table class="ui-datepicker-calendar"><thead>' + '<tr>'; var thead = ''; for (var dow = 0; dow < 7; dow++) { var day = (dow + firstDay) % 7; thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' + '<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>' } calender += thead + '</tr></thead><tbody>'; var daysInMonth = this._getDaysInMonth(drawYear, drawMonth); if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth) inst.selectedDay = Math.min(inst.selectedDay, daysInMonth); var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7; var numRows = (isMultiMonth ? 6 : Math.ceil((leadDays + daysInMonth) / 7)); var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays)); for (var dRow = 0; dRow < numRows; dRow++) { calender += '<tr>'; var tbody = ''; for (var dow = 0; dow < 7; dow++) { var daySettings = (beforeShowDay ? beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']); var otherMonth = (printDate.getMonth() != drawMonth); var unselectable = otherMonth || !daySettings[0] || (minDate && printDate < minDate) || (maxDate && printDate > maxDate); tbody += '<td class="' + ((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + (otherMonth ? ' ui-datepicker-other-month' : '') + ((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || (defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ? ' ' + this._dayOverClass : '') + (unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled' : '') + (otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + (printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? ' ' + this._currentClass : '') + (printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + ((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + (unselectable ? '' : ' onclick="DP_jQuery.datepicker._selectDay(\'#' + inst.id + '\',' + drawMonth + ',' + drawYear + ', this);return false;"') + '>' + (otherMonth ? (showOtherMonths ? printDate.getDate() : '&#xa0;') : (unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' + (printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') + (printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? ' ui-state-active' : '') + '" href="#">' + printDate.getDate() + '</a>')) + '</td>'; printDate.setDate(printDate.getDate() + 1); printDate = this._daylightSavingAdjust(printDate) } calender += tbody + '</tr>' } drawMonth++; if (drawMonth > 11) { drawMonth = 0; drawYear++ } calender += '</tbody></table>' + (isMultiMonth ? '</div>' + ((numMonths[0] > 0 && col == numMonths[1] - 1) ? '<div class="ui-datepicker-row-break"></div>' : '') : ''); group += calender } html += group } html += buttonPanel + ($.browser.msie && parseInt($.browser.version, 10) < 7 && !inst.inline ? '<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : ''); inst._keyEvent = false; return html }, _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, selectedDate, secondary, monthNames, monthNamesShort) { minDate = (inst.rangeStart && minDate && selectedDate < minDate ? selectedDate : minDate); var changeMonth = this._get(inst, 'changeMonth'); var changeYear = this._get(inst, 'changeYear'); var showMonthAfterYear = this._get(inst, 'showMonthAfterYear'); var html = '<div class="ui-datepicker-title">'; var monthHtml = ''; if (secondary || !changeMonth) monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span> '; else { var inMinYear = (minDate && minDate.getFullYear() == drawYear); var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear); monthHtml += '<select class="ui-datepicker-month" ' + 'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'M\');" ' + 'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' + '>'; for (var month = 0; month < 12; month++) { if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) monthHtml += '<option value="' + month + '"' + (month == drawMonth ? ' selected="selected"' : '') + '>' + monthNamesShort[month] + '</option>' } monthHtml += '</select>' } if (!showMonthAfterYear) html += monthHtml + ((secondary || changeMonth || changeYear) && (!(changeMonth && changeYear)) ? '&#xa0;' : ''); if (secondary || !changeYear) html += '<span class="ui-datepicker-year">' + drawYear + '</span>'; else { var years = this._get(inst, 'yearRange').split(':'); var year = 0; var endYear = 0; if (years.length != 2) { year = drawYear - 10; endYear = drawYear + 10 } else if (years[0].charAt(0) == '+' || years[0].charAt(0) == '-') { year = drawYear + parseInt(years[0], 10); endYear = drawYear + parseInt(years[1], 10) } else { year = parseInt(years[0], 10); endYear = parseInt(years[1], 10) } year = (minDate ? Math.max(year, minDate.getFullYear()) : year); endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear); html += '<select class="ui-datepicker-year" ' + 'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'Y\');" ' + 'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' + '>'; for (; year <= endYear; year++) { html += '<option value="' + year + '"' + (year == drawYear ? ' selected="selected"' : '') + '>' + year + '</option>' } html += '</select>' } if (showMonthAfterYear) html += (secondary || changeMonth || changeYear ? '&#xa0;' : '') + monthHtml; html += '</div>'; return html }, _adjustInstDate: function(inst, offset, period) { var year = inst.drawYear + (period == 'Y' ? offset : 0); var month = inst.drawMonth + (period == 'M' ? offset : 0); var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period == 'D' ? offset : 0); var date = this._daylightSavingAdjust(new Date(year, month, day)); var minDate = this._getMinMaxDate(inst, 'min', true); var maxDate = this._getMinMaxDate(inst, 'max'); date = (minDate && date < minDate ? minDate : date); date = (maxDate && date > maxDate ? maxDate : date); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); if (period == 'M' || period == 'Y') this._notifyChange(inst) }, _notifyChange: function(inst) { var onChange = this._get(inst, 'onChangeMonthYear'); if (onChange) onChange.apply((inst.input ? inst.input[0] : null), [inst.selectedYear, inst.selectedMonth + 1, inst]) }, _getNumberOfMonths: function(inst) { var numMonths = this._get(inst, 'numberOfMonths'); return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths)) }, _getMinMaxDate: function(inst, minMax, checkRange) { var date = this._determineDate(this._get(inst, minMax + 'Date'), null); return (!checkRange || !inst.rangeStart ? date : (!date || inst.rangeStart > date ? inst.rangeStart : date)) }, _getDaysInMonth: function(year, month) { return 32 - new Date(year, month, 32).getDate() }, _getFirstDayOfMonth: function(year, month) { return new Date(year, month, 1).getDay() }, _canAdjustMonth: function(inst, offset, curYear, curMonth) { var numMonths = this._getNumberOfMonths(inst); var date = this._daylightSavingAdjust(new Date(curYear, curMonth + (offset < 0 ? offset : numMonths[1]), 1)); if (offset < 0) date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth())); return this._isInRange(inst, date) }, _isInRange: function(inst, date) { var newMinDate = (!inst.rangeStart ? null : this._daylightSavingAdjust(new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay))); newMinDate = (newMinDate && inst.rangeStart < newMinDate ? inst.rangeStart : newMinDate); var minDate = newMinDate || this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); return ((!minDate || date >= minDate) && (!maxDate || date <= maxDate)) }, _getFormatConfig: function(inst) { var shortYearCutoff = this._get(inst, 'shortYearCutoff'); shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); return { shortYearCutoff: shortYearCutoff, dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'), monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')} }, _formatDate: function(inst, day, month, year) { if (!day) { inst.currentDay = inst.selectedDay; inst.currentMonth = inst.selectedMonth; inst.currentYear = inst.selectedYear } var date = (day ? (typeof day == 'object' ? day : this._daylightSavingAdjust(new Date(year, month, day))) : this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst)) } }); function extendRemove(target, props) { $.extend(target, props); for (var name in props) if (props[name] == null || props[name] == undefined) target[name] = props[name]; return target }; function isArray(a) { return (a && (($.browser.safari && typeof a == 'object' && a.length) || (a.constructor && a.constructor.toString().match(/\Array\(\)/)))) }; $.fn.datepicker = function(options) { if (!$.datepicker.initialized) { $(document).mousedown($.datepicker._checkExternalClick).find('body').append($.datepicker.dpDiv); $.datepicker.initialized = true } var otherArgs = Array.prototype.slice.call(arguments, 1); if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate')) return $.datepicker['_' + options + 'Datepicker'].apply($.datepicker, [this[0]].concat(otherArgs)); return this.each(function() { typeof options == 'string' ? $.datepicker['_' + options + 'Datepicker'].apply($.datepicker, [this].concat(otherArgs)) : $.datepicker._attachDatepicker(this, options) }) }; $.datepicker = new Datepicker(); $.datepicker.initialized = false; $.datepicker.uuid = new Date().getTime(); $.datepicker.version = "1.7.1"; window.DP_jQuery = $ })(jQuery);var dtCh = "/";
function RedefineDate(DateValue) {
    if (DateValue == "") return "";
    var RefinedDate = DateValue;
    var dateSplits = DateValue.split(GetDateSeperator());
    var ddmmyyyyReg = /\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}/
    var yyyymmddReg = /\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}/
    var strMonth; 
    var strDay;
    var strYear;
   
    if (ddmmyyyyReg.test(DateValue)) {
        strDay = dateSplits[0];
        strMonth = dateSplits[1];
        strYear = dateSplits[2];
    }
    else if (yyyymmddReg.test(DateValue)) {
        strDay = dateSplits[2];
        strMonth = dateSplits[1];
        strYear = dateSplits[0];
    }
    var dfmt = GetDateFormat();
    if (dfmt == "dd/mm/yyyy") {
        RefinedDate = strDay + GetDateSeperator() + strMonth + GetDateSeperator() + strYear;
    }
    else if (dfmt == "yyyy/mm/dd") {
        RefinedDate = strYear + GetDateSeperator() + strMonth + GetDateSeperator() + strDay;
    }
    return RefinedDate;
}
function isInteger(s) {
    var i;
    for (i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    return true;
}
function GetDateFormat() {
    if (typeof (window['calDateFormat']) != 'undefined') {
        if (calDateFormat == "yyyy/mm/dd")
            return "yyyy/mm/dd";
        else if (calDateFormat == "dd/mm/yyyy")
            return "dd/mm/yyyy";
    }
    else {
        return "dd/mm/yyyy";
    }
}
function GetDateSeperator() { return dtCh; }
function stripCharsInBag(s, bag) {
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function GetDateDiff(Date1, Date2) {
    var one_day = 1000 * 60 * 60 * 24;
    var startDate = new Date(ConvertToSysFormat(Date1));
    var endDate = new Date(ConvertToSysFormat(Date2));
    _Diff = Math.ceil((endDate.getTime() - startDate.getTime()) / (one_day));
    return _Diff;
}

function ResetDate(InOut, Date1, Date2) {
    var checkinDate = new Date(Date1);
    var checkoutDate = new Date(Date2);
    var checkDate, incremet
    if (InOut == "in") {
        checkDate = checkoutDate
        incremet = -1
    } else {
        checkDate = checkinDate
        incremet = 2
    }
    if (checkinDate >= checkoutDate) {
        var newDate = new Date(checkDate.getFullYear(), checkDate.getMonth(), checkDate.getDate() + incremet)
        SetDateVal(newDate.getFullYear(), newDate.getMonth() + 1, newDate.getDate(), InOut)
    }
}

function SetDateVal(year, month, varday, inOut) {
    var dfmt = GetDateFormat();
    if (month.toString.length < 2) month = "0" + month
    if (varday.toString.length < 2) varday = "0" + varday

    if (inOut == "in") {
        if (dfmt == "dd/mm/yyyy") {
            document.getElementById("Cal1").value = varday + GetDateSeperator() + month + GetDateSeperator() + year;
        }
        else if (dfmt == "yyyy/mm/dd") {
            document.getElementById("Cal1").value = year + GetDateSeperator() + month + GetDateSeperator() + varday;
        }
    } else {
        if (dfmt == "dd/mm/yyyy") {
            document.getElementById("Cal2").value = varday + GetDateSeperator() + month + GetDateSeperator() + year;
        }
        else if (dfmt == "yyyy/mm/dd") {
            document.getElementById("Cal2").value = year + GetDateSeperator() + month + GetDateSeperator() + varday;
        }
    }
    DateDiff();
}


function DateDiff() {
    dtCheckIn = document.getElementById("Cal1").value;
    var StartDate, EndDate;
    if (dtCheckIn != "") {
        var dateSplits = dtCheckIn.split(GetDateSeperator());
        if (dateSplits.length != 3 || isDate(dtCheckIn) != true) {
            $('#Cal1').datepicker('setDate', minDate);
            dtCheckIn = document.getElementById("Cal1").value;
        }
        CheckinDayEle = document.getElementById("day1");
        StartDate = new Date(ConvertToSysFormat(dtCheckIn));
        setDay(StartDate, CheckinDayEle);

    }
    dtCheckOut = document.getElementById("Cal2").value;
    if (dtCheckOut != "") {
        var dateSplits = dtCheckOut.split(GetDateSeperator());
        if (dateSplits.length != 3 || isDate(dtCheckOut) != true) {
            $('#Cal2').datepicker('setDate', minDate2);
            dtCheckOut = document.getElementById("Cal2").value;
        }
        CheckoutDayEle = document.getElementById("day2");
        EndDate = new Date(ConvertToSysFormat(dtCheckOut));
        setDay(EndDate, CheckoutDayEle);
    }
    if (dtCheckIn != "" && dtCheckOut != "") {
        document.getElementById('dateDiff').innerHTML = GetDateDiff(dtCheckIn, dtCheckOut);
        AutoUpdateCheckout(StartDate, EndDate, "up");
    }
}

function DateDiff2() {
    dtCheckIn = document.getElementById("Cal1").value;
    var StartDate, EndDate;
    if (dtCheckIn != "") {
        var dateSplits = dtCheckIn.split(GetDateSeperator());
        if (dateSplits.length != 3 || isDate(dtCheckIn) != true) {
            $('#Cal1').datepicker('setDate', minDate);
            dtCheckIn = document.getElementById("Cal1").value;
        }
        CheckinDayEle = document.getElementById("day1");
        StartDate = new Date(ConvertToSysFormat(dtCheckIn));
        setDay(StartDate, CheckinDayEle);
    }
    dtCheckOut = document.getElementById("Cal2").value;
    if (dtCheckOut != "") {
        var dateSplits = dtCheckOut.split(GetDateSeperator());
        if (dateSplits.length != 3 || isDate(dtCheckOut) != true) {
            $('#Cal2').datepicker('setDate', minDate2);
            dtCheckOut = document.getElementById("Cal2").value;
        }
        CheckoutDayEle = document.getElementById("day2");
        EndDate = new Date(ConvertToSysFormat(dtCheckOut));
        setDay(EndDate, CheckoutDayEle);
    }
    if (dtCheckIn != "" && dtCheckOut != "") {
        document.getElementById('dateDiff').innerHTML = GetDateDiff(dtCheckIn, dtCheckOut);
        AutoUpdateCheckout(StartDate, EndDate, "down");
    }
}

function DateDiff3() {
    dtCheckIn = document.getElementById("Cal3").value;
    var StartDate, EndDate;
    if (dtCheckIn != "") {
        var dateSplits = dtCheckIn.split(GetDateSeperator());
        if (dateSplits.length != 3 || isDate(dtCheckIn) != true) {
            $('#Cal3').datepicker('setDate', minDate);
            dtCheckIn = document.getElementById("Cal3").value;
        }
        CheckinDayEle = document.getElementById("day3");
        StartDate = new Date(ConvertToSysFormat(dtCheckIn));
        setDay(StartDate, CheckinDayEle);

    }
    dtCheckOut = document.getElementById("Cal4").value;
    if (dtCheckOut != "") {
        var dateSplits = dtCheckOut.split(GetDateSeperator());
        if (dateSplits.length != 3 || isDate(dtCheckOut) != true) {
            $('#Cal4').datepicker('setDate', minDate2);
            dtCheckOut = document.getElementById("Cal4").value;
        }
        CheckoutDayEle = document.getElementById("day4");
        EndDate = new Date(ConvertToSysFormat(dtCheckOut));
        setDay(EndDate, CheckoutDayEle);
    }
    if (dtCheckIn != "" && dtCheckOut != "") {
        AutoUpdateCheckout1(StartDate, EndDate, "up");
    }
}

function DateDiff4() {
    dtCheckIn = document.getElementById("Cal3").value;
    var StartDate, EndDate;
    if (dtCheckIn != "") {
        var dateSplits = dtCheckIn.split(GetDateSeperator());
        if (dateSplits.length != 3 || isDate(dtCheckIn) != true) {
            $('#Cal3').datepicker('setDate', minDate);
            dtCheckIn = document.getElementById("Cal3").value;
        }
        CheckinDayEle = document.getElementById("day3");
        StartDate = new Date(ConvertToSysFormat(dtCheckIn));
        setDay(StartDate, CheckinDayEle);
    }
    dtCheckOut = document.getElementById("Cal4").value;
    if (dtCheckOut != "") {
        var dateSplits = dtCheckOut.split(GetDateSeperator());
        if (dateSplits.length != 3 || isDate(dtCheckOut) != true) {
            $('#Cal4').datepicker('setDate', minDate2);
            dtCheckOut = document.getElementById("Cal4").value;
        }
        CheckoutDayEle = document.getElementById("day4");
        EndDate = new Date(ConvertToSysFormat(dtCheckOut));
        setDay(EndDate, CheckoutDayEle);
    }
    if (dtCheckIn != "" && dtCheckOut != "") {
        AutoUpdateCheckout1(StartDate, EndDate, "down");
    }
}

function AutoUpdateCheckout(CheckinDate, CheckoutDate, Dir) {
    var month, day, year, dfmt;
    if (CheckoutDate.getTime() < CheckinDate.getTime() && Dir == "up") {
        CheckoutDate.setTime(CheckinDate.getTime() + oneDay * 2);

        month = CheckoutDate.getMonth() + 1; month = AddPrecedingZero(month);
        day = CheckoutDate.getDate(); day = AddPrecedingZero(day);
        year = CheckoutDate.getFullYear();

        dfmt = GetDateFormat();
        if (dfmt == "dd/mm/yyyy") {
            document.getElementById("Cal2").value = day.toString() + GetDateSeperator() + month.toString() + GetDateSeperator() + year.toString();
        }
        else if (dfmt == "yyyy/mm/dd") {
            document.getElementById("Cal2").value = year.toString() + GetDateSeperator() + month.toString() + GetDateSeperator() + day.toString();
        }
        DateDiff();
    }
    else if (CheckoutDate.getTime() < CheckinDate.getTime() && Dir == "down") {
        CheckinDate.setTime(CheckoutDate.getTime() - oneDay * 2);
        month = CheckinDate.getMonth() + 1; month = AddPrecedingZero(month);
        day = CheckinDate.getDate(); day = AddPrecedingZero(day);
        year = CheckinDate.getFullYear();

        dfmt = GetDateFormat();
        if (dfmt == "dd/mm/yyyy") {
            document.getElementById("Cal1").value = day.toString() + GetDateSeperator() + month.toString() + GetDateSeperator() + year.toString();
        }
        else if (dfmt == "yyyy/mm/dd") {
            document.getElementById("Cal1").value = year.toString() + GetDateSeperator() + month.toString() + GetDateSeperator() + day.toString();
        }
        DateDiff();
    }
}

function AutoUpdateCheckout1(CheckinDate, CheckoutDate, Dir) {
    var month, day, year, dfmt;
    if (CheckoutDate.getTime() < CheckinDate.getTime() && Dir == "up") {
        CheckoutDate.setTime(CheckinDate.getTime() + oneDay * 2);

        month = CheckoutDate.getMonth() + 1; month = AddPrecedingZero(month);
        day = CheckoutDate.getDate(); day = AddPrecedingZero(day);
        year = CheckoutDate.getFullYear();

        dfmt = GetDateFormat();
        if (dfmt == "dd/mm/yyyy") {
            document.getElementById("Cal4").value = day.toString() + GetDateSeperator() + month.toString() + GetDateSeperator() + year.toString();
        }
        else if (dfmt == "yyyy/mm/dd") {
            document.getElementById("Cal4").value = year.toString() + GetDateSeperator() + month.toString() + GetDateSeperator() + day.toString();
        }
        DateDiff3();
    }
    else if (CheckoutDate.getTime() < CheckinDate.getTime() && Dir == "down") {
        CheckinDate.setTime(CheckoutDate.getTime() - oneDay * 2);
        month = CheckinDate.getMonth() + 1; month = AddPrecedingZero(month);
        day = CheckinDate.getDate(); day = AddPrecedingZero(day);
        year = CheckinDate.getFullYear();

        dfmt = GetDateFormat();
        if (dfmt == "dd/mm/yyyy") {
            document.getElementById("Cal3").value = day.toString() + GetDateSeperator() + month.toString() + GetDateSeperator() + year.toString();
        }
        else if (dfmt == "yyyy/mm/dd") {
            document.getElementById("Cal3").value = year.toString() + GetDateSeperator() + month.toString() + GetDateSeperator() + day.toString();
        }
        DateDiff3();
    }
}

function setDay(DateInput, Control) {
    Control.innerHTML = arrDayNames[DateInput.getDay()];
}
function AddPrecedingZero(InputString) {
    if (InputString.toString().charAt(0) != "0" && InputString.toString().length != 2) { InputString = "0" + InputString.toString(); }
    return InputString;
}
function RemovePrecedingZero(InputString) {
    if (InputString.toString().charAt(0) == "0" && InputString.toString().length == 2) { InputString = InputString.charAt(1); }
    return InputString;
}

function SetDefaultDate() {
    if (document.getElementById("Cal1") && document.getElementById("Cal2")) {
        var dtCheckIn = document.getElementById("Cal1").value;
        var dtCheckOut = document.getElementById("Cal2").value;
        var dfmt = GetDateFormat();
        if (dtCheckIn == "" || dtCheckOut == "") {
            var sDate = new Date();
            var one_day = 1000 * 60 * 60 * 24;
            sDate.setTime(sDate.getTime() + one_day * 17);

            var inDay = sDate.getDate(); inDay = AddPrecedingZero(inDay);
            var inMonth = sDate.getMonth() + 1; inMonth = AddPrecedingZero(inMonth);
            var inYear = sDate.getFullYear();

            var eDate = new Date();
            eDate.setTime(eDate.getTime() + one_day * 19);
            var outDay = eDate.getDate(); outDay = AddPrecedingZero(outDay);
            var outMonth = eDate.getMonth() + 1; outMonth = AddPrecedingZero(outMonth);
            var outYear = eDate.getFullYear();
            if (dfmt == "dd/mm/yyyy") {
                document.getElementById('Cal1').value = inDay + GetDateSeperator() + inMonth + GetDateSeperator() + inYear;
                document.getElementById('Cal2').value = outDay + GetDateSeperator() + outMonth + GetDateSeperator() + outYear;
            }
            else if (dfmt == "yyyy/mm/dd") {
                document.getElementById('Cal1').value = inYear + GetDateSeperator() + inMonth + GetDateSeperator() + inDay;
                document.getElementById('Cal2').value = outYear + GetDateSeperator() + outMonth + GetDateSeperator() + outDay
            }
        }
    }
}

function SetSeoDefaultDate() {

    var dtCheckIn = document.getElementById("Cal3").value;
    var dtCheckOut = document.getElementById("Cal4").value;
    var dfmt = GetDateFormat();

    if (dtCheckIn == "" || dtCheckOut == "") {
        var sDate = new Date();
        var one_day = 1000 * 60 * 60 * 24;
        sDate.setTime(sDate.getTime() + one_day * 17);

        var inDay = sDate.getDate(); inDay = AddPrecedingZero(inDay);
        var inMonth = sDate.getMonth() + 1; inMonth = AddPrecedingZero(inMonth);
        var inYear = sDate.getFullYear();

        var eDate = new Date();
        eDate.setTime(eDate.getTime() + one_day * 19);
        var outDay = eDate.getDate(); outDay = AddPrecedingZero(outDay);
        var outMonth = eDate.getMonth() + 1; outMonth = AddPrecedingZero(outMonth);
        var outYear = eDate.getFullYear();
        if (dfmt == "dd/mm/yyyy") {
            document.getElementById('Cal3').value = inDay + GetDateSeperator() + inMonth + GetDateSeperator() + inYear;
            document.getElementById('Cal4').value = outDay + GetDateSeperator() + outMonth + GetDateSeperator() + outYear;
        }
        else if (dfmt == "yyyy/mm/dd") {
            document.getElementById('Cal3').value = inYear + GetDateSeperator() + inMonth + GetDateSeperator() + inDay;
            document.getElementById('Cal4').value = outYear + GetDateSeperator() + outMonth + GetDateSeperator() + outDay
        }
    }
}

function initSEOCalendar() {
    SetSeoDefaultDate();
    if (document.getElementById('Cal3')) {
        document.getElementById('Cal3').value = RedefineDate(document.getElementById('Cal3').value);
        var CheckInDate = document.getElementById('Cal3').value
        var dtCheckInDate = new Date(ConvertToSysFormat(CheckInDate));
        checkInday = dtCheckInDate.getDate();
        checkInMonth = dtCheckInDate.getMonth() + 1;
        checkInyear = dtCheckInDate.getFullYear();
        setDay(dtCheckInDate, document.getElementById('day3'));
    }
    if (document.getElementById('Cal4')) {
        document.getElementById('Cal4').value = RedefineDate(document.getElementById('Cal4').value);
        var CheckOutDate = document.getElementById('Cal4').value
        var dtCheckOutDate = new Date(ConvertToSysFormat(CheckOutDate));
        checkOutday = dtCheckOutDate.getDate();
        checkOutMonth = dtCheckOutDate.getMonth() + 1;
        checkOutyear = dtCheckOutDate.getFullYear();
        setDay(dtCheckOutDate, document.getElementById('day4'));
    }
}

function initCalendar() {
    var dfmt = GetDateFormat();
    var qs = new Querystring(location.search.substr(1))
    var inDay = qs.get("inDay")
    var inMonth = qs.get("inMonth")
    var inYear = qs.get("inYear")

    var outDay = qs.get("outDay")
    var outMonth = qs.get("outMonth")
    var outYear = qs.get("outYear")

    /* added check for directhotel when the 6 variables above are not available */
    var qsCheckInDate = qs.get("checkin");
    var qsCheckOutDate = qs.get("checkout");
    if ((typeof (inDay) == 'undefined' || inDay == null) &&
        (typeof (qsCheckInDate) != 'undefined' || qsCheckInDate != null)) {
        inYear = qsCheckInDate.split("-")[0];
        inMonth = qsCheckInDate.split("-")[1].length > 1 ? qsCheckInDate.split("-")[1] : "0" + qsCheckInDate.split("-")[1];
        inDay = qsCheckInDate.split("-")[2].length > 1 ? qsCheckInDate.split("-")[2] : "0" + qsCheckInDate.split("-")[2];

        outYear = qsCheckOutDate.split("-")[0];
        outMonth = qsCheckOutDate.split("-")[1].length > 1 ? qsCheckOutDate.split("-")[1] : "0" + qsCheckOutDate.split("-")[1];
        outDay = qsCheckOutDate.split("-")[2].length > 1 ? qsCheckOutDate.split("-")[2] : "0" + qsCheckOutDate.split("-")[2];
    }

    SetDefaultDate();

    var checkInday, checkInMonth, checkInyear
    var checkOutday, checkOutMonth, checkOutyear

    if (document.getElementById('Cal1')) {
        document.getElementById('Cal1').value = RedefineDate(document.getElementById('Cal1').value);
        var CheckInDate = document.getElementById('Cal1').value
        var dtCheckInDate = new Date(ConvertToSysFormat(CheckInDate));
        checkInday = dtCheckInDate.getDate();
        checkInMonth = dtCheckInDate.getMonth() + 1;
        checkInyear = dtCheckInDate.getFullYear();
        setDay(dtCheckInDate, document.getElementById('day1'));
    }
    if (document.getElementById('Cal2')) {
        document.getElementById('Cal2').value = RedefineDate(document.getElementById('Cal2').value);
        var CheckOutDate = document.getElementById('Cal2').value
        var dtCheckOutDate = new Date(ConvertToSysFormat(CheckOutDate));
        checkOutday = dtCheckOutDate.getDate();
        checkOutMonth = dtCheckOutDate.getMonth() + 1;
        checkOutyear = dtCheckOutDate.getFullYear();
        setDay(dtCheckOutDate, document.getElementById('day2'));
    }
    /*********set month, day, year in the hidden text *******/
    if (document.getElementById('inDay')) {
        document.getElementById('inDay').value = checkInday;
        document.getElementById('inMonth').value = checkInMonth;
        document.getElementById('inYear').value = checkInyear;

        document.getElementById('outDay').value = checkOutday;
        document.getElementById('outMonth').value = checkOutMonth;
        document.getElementById('outYear').value = checkOutyear;
    }
    /*******************************************************/
    if (typeof (inDay) != 'undefined' && inDay != null && document.getElementById('inDay')) {

        document.getElementById('inDay').value = inDay;
        document.getElementById('inMonth').value = inMonth;
        document.getElementById('inYear').value = inYear;

        document.getElementById('outDay').value = outDay;
        document.getElementById('outMonth').value = outMonth;
        document.getElementById('outYear').value = outYear;

        checkInday = inDay;
        checkInMonth = inMonth;
        checkInyear = inYear;

        checkOutday = outDay;
        checkOutMonth = outMonth;
        checkOutyear = outYear;

        if (dfmt == "dd/mm/yyyy") {
            document.getElementById('Cal1').value = inDay + GetDateSeperator() + inMonth + GetDateSeperator() + inYear;
            document.getElementById('Cal2').value = outDay + GetDateSeperator() + outMonth + GetDateSeperator() + outYear;
        }
        else if (dfmt == "yyyy/mm/dd") {
            document.getElementById('Cal1').value = inYear + GetDateSeperator() + inMonth + GetDateSeperator() + inDay;
            document.getElementById('Cal2').value = outYear + GetDateSeperator() + outMonth + GetDateSeperator() + outDay
        }
        var Cal1 = inMonth + GetDateSeperator() + inDay + GetDateSeperator() + inYear;
        var chkInDate = new Date(eval('"' + Cal1 + '"'))
        setDay(chkInDate, document.getElementById('day1'));


        var Cal2 = outMonth + GetDateSeperator() + outDay + GetDateSeperator() + outYear;
        var chkOutDate = new Date(eval('"' + Cal2 + '"'))
        setDay(chkOutDate, document.getElementById('day2'));

    }
    if (document.getElementById('hdnDateDiff') != null) {
        //********Length of stay *******/////  
        var strDiff = document.getElementById('hdnDateDiff').value
        var actualDiffStr = document.getElementById('hdnDateDiff').value;
        strDiff = strDiff.substring(strDiff.indexOf("]") + 1, strDiff.length);
        document.getElementById('lenStay').innerHTML = "<strong>" + actualDiffStr.substring(0, actualDiffStr.indexOf("[")) + "</strong>";
        document.getElementById('spnnight').innerHTML = strDiff;
        DateDiff();
    }
}

function ChangeDates() {
    if (ValidateDate() == true) {
        var qString = location.search.substr(1)
        qString = remQStringName(qString, "page")
        var strCheckIn = DateFormat(strCheckIn = document.getElementById('Cal1').value)
        var strCheckOut = DateFormat(document.getElementById('Cal2').value)
        qString = remQStringName(qString, "inDay")
        qString = remQStringName(qString, "inMonth")
        qString = remQStringName(qString, "inYear")
        qString = remQStringName(qString, "outDay")
        qString = remQStringName(qString, "outMonth")
        qString = remQStringName(qString, "outYear")
        qString = remQStringName(qString, "vw")
        qString += "&" + "inDay" + "=" + document.getElementById('inDay').value
        qString += "&" + "inMonth" + "=" + document.getElementById('inMonth').value
        qString += "&" + "inYear" + "=" + document.getElementById('inYear').value
        var outDate = document.getElementById('outDay').value
        if (outDate.length < 2)
        { qString += "&" + "outDay" + "=0" + outDate }
        else
        { qString += "&" + "outDay" + "=" + outDate }
        qString += "&" + "outMonth" + "=" + document.getElementById('outMonth').value
        qString += "&" + "outYear" + "=" + document.getElementById('outYear').value
        qString += "&" + "vw=D"
        qString = setQStringName(qString, "Checkin", new Array(strCheckIn))
        qString = setQStringName(qString, "Checkout", new Array(strCheckOut))
        location = location.pathname + "?" + qString
    }
}

function ValidateDate() {

    var strChkin = document.getElementById('Cal1').value;
    var strChkout = document.getElementById('Cal2').value;

    if (isDate(strChkin) == false) {
        document.getElementById('Cal1').focus()
        return false
    }
    if (isDate(strChkout) == false) {
        document.getElementById('Cal2').focus()
        return false
    }

    UpdateDates();
    var one_day = 1000 * 60 * 60 * 24;
    var date1 = new Date(ConvertToSysFormat(strChkin));
    var date2 = new Date(ConvertToSysFormat(strChkout));

    var dateDiff = Math.ceil((date2.getTime() - date1.getTime()) / (one_day));

    if (parseInt(dateDiff) < 1) {

        if (typeof (Common_Scripts_TravelDates_OutAfterIn) == "undefined")
            Common_Scripts_TravelDates_OutAfterIn = "Please ensure that the Check-out Date is after the Check-in Date."

        alert(Common_Scripts_TravelDates_OutAfterIn)
        return false;
    }
    var mnDate = new Date(minDate);
    minDate = new Date(mnDate.toDateString());
  
    if (date1 < minDate || date1 > maxDate) {
        alert("Please enter valid checkin date between " + minDate.toDateString() + " and " + maxDate.toDateString())
        return false
    }
    if (date2 < minDate2 || date2 > maxDate) {
        alert("Please enter valid checkout date between " + minDate2.toDateString() + " and " + maxDate.toDateString())
        return false
    }
    if (parseInt(dateDiff) > 25) {
        if (typeof (Common_Scripts_TravelDates_StayTooLong) == "undefined") {
            Common_Scripts_TravelDates_StayTooLong = 'Your period of stay should be not longer than 25 nights.\n\nIf you wish to book for more than 25 nights, please send us an e-mail with your request.'

        }
        alert(Common_Scripts_TravelDates_StayTooLong);
        return false;
    }
    return true
}

function ConvertToSysFormat(dtStr) {
    var dfmt = GetDateFormat();
    var dateSplits = dtStr.split(GetDateSeperator());
    var strMonth, strDay, strYear;
    if (dfmt == "dd/mm/yyyy") {
        strDay = dateSplits[0];
        strMonth = dateSplits[1];
        strYear = dateSplits[2];
    }
    else if (dfmt == "yyyy/mm/dd") {
        strDay = dateSplits[2];
        strMonth = dateSplits[1];
        strYear = dateSplits[0];
    }
    return strMonth + GetDateSeperator() + strDay + GetDateSeperator() + strYear;
}

function DateFormat(strDate) {
    var dfmt = GetDateFormat();
    var dateSplits = strDate.split(GetDateSeperator());
    var strMonth, strDay, strYear;
    var strMonth, strDay, strYear;
    if (dfmt == "dd/mm/yyyy") {
        strDay = dateSplits[0];
        strMonth = dateSplits[1];
        strYear = dateSplits[2];
    }
    else if (dfmt == "yyyy/mm/dd") {
        strDay = dateSplits[2];
        strMonth = dateSplits[1];
        strYear = dateSplits[0];
    }
    newDate = strYear + '-' + strMonth + '-' + strDay
    return newDate
}

function isDate(dtStr) {
    var dfmt = GetDateFormat();

    var dateSplits = dtStr.split(GetDateSeperator());
    if (dateSplits.length != 3) {
        alert("Enter a valid date");
        return false;
    }
    var strMonth, strDay, strYear;
    if (dfmt == "dd/mm/yyyy") {
        strDay = dateSplits[0];
        strMonth = dateSplits[1];
        strYear = dateSplits[2];
    }
    else if (dfmt == "yyyy/mm/dd") {
        strDay = dateSplits[2];
        strMonth = dateSplits[1];
        strYear = dateSplits[0];
    }
    var daysInMonth = DaysArray(12)
    strDay = AddPrecedingZero(strDay); strMonth = AddPrecedingZero(strMonth);
    if (isInteger(strDay) != true && isInteger(strMonth) != true && isInteger(strYear) != true)
        return false;
    var month = parseInt(strMonth, 10)
    var day = parseInt(strDay, 10)
    var year = parseInt(strYear, 10)

    if (strMonth.length < 1 || month < 1 || month > 12) {
        alert("Please enter valid month")
        return false
    }
    if (strDay.length < 1 || day < 1 || day > 31 || (month == 2 && day > daysInFebruary(year)) || day > daysInMonth[month]) {
        alert("Please enter valid date")
        return false
    }
    if (strYear.length != 4 || year == 0) {
        alert("Please enter valid 4 digit year")
        return false
    }

//    var dt = new Date(ConvertToSysFormat(dtStr));
//    if (dt < minDate || dt > maxDate) {
//        alert("Please enter valid date between " + minDate.toDateString() + " and " + maxDate.toDateString())
//        return false
//    }
    return true
}
function DaysArray(n) {
    for (var i = 1; i <= n; i++) {
        this[i] = 31
        if (i == 4 || i == 6 || i == 9 || i == 11) { this[i] = 30 }
        if (i == 2) { this[i] = 29 }
    }
    return this
}
function daysInFebruary(year) {
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ((!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28);
}
function UpdateDates() {
    var dfmt = GetDateFormat();
    var CheckInDate = document.getElementById('Cal1').value
    var checkInday, checkInMonth, checkInyear
    var CheckInDateSplits = CheckInDate.split(GetDateSeperator());
    if (dfmt == "dd/mm/yyyy") {
        checkInday = CheckInDateSplits[0];
        checkInMonth = CheckInDateSplits[1];
        checkInyear = CheckInDateSplits[2];
    }
    else if (dfmt == "yyyy/mm/dd") {
        checkInday = CheckInDateSplits[2];
        checkInMonth = CheckInDateSplits[1];
        checkInyear = CheckInDateSplits[0];
    }
    checkInday = AddPrecedingZero(checkInday); checkInMonth = AddPrecedingZero(checkInMonth);

    var CheckOutDate = document.getElementById('Cal2').value
    var checkOutday, checkOutMonth, checkOutyear
    var CheckOutDateSplits = CheckOutDate.split(GetDateSeperator());
    if (dfmt == "dd/mm/yyyy") {
        checkOutday = CheckOutDateSplits[0];
        checkOutMonth = CheckOutDateSplits[1];
        checkOutyear = CheckOutDateSplits[2];
    }
    else if (dfmt == "yyyy/mm/dd") {
        checkOutday = CheckOutDateSplits[2];
        checkOutMonth = CheckOutDateSplits[1];
        checkOutyear = CheckOutDateSplits[0];
    }

    checkOutday = AddPrecedingZero(checkOutday); checkOutMonth = AddPrecedingZero(checkOutMonth);

    document.getElementById('inDay').value = checkInday;
    document.getElementById('inMonth').value = checkInMonth;
    document.getElementById('inYear').value = checkInyear;

    document.getElementById('outDay').value = checkOutday;
    document.getElementById('outMonth').value = checkOutMonth;
    document.getElementById('outYear').value = checkOutyear;
}

function CheckIrrelevantDates() {
    var qs = new Querystring(location.search.substr(1))
    var inDay = qs.get("inDay"); var inMonth = qs.get("inMonth"); var inYear = qs.get("inYear"); var outDay = qs.get("outDay")
    var outMonth = qs.get("outMonth"); var outYear = qs.get("outYear"); var qsCheckInDate = qs.get("checkin");
    var qsCheckOutDate = qs.get("checkout");
    /*if ((typeof (inDay) == 'undefined' || inDay == null) && (typeof (qsCheckOutDate) == 'undefined' || qsCheckOutDate == null)) {
    //CheckInDate
    }*/

    if (typeof (qsCheckInDate) == 'undefined' || qsCheckInDate == null) {
        qsCheckInDate = varCheckInDate;
    }


    if (typeof (qsCheckOutDate) == 'undefined' || qsCheckOutDate == null) {
        qsCheckOutDate = varCheckOutDate;
    }


    if (typeof (inDay) == 'undefined' || inDay == null) {
        inYear = qsCheckInDate.substring(0, 4);
        inMonth = qsCheckInDate.substring(5, 7);
        inDay = qsCheckInDate.substring(8, 10);
        outYear = qsCheckOutDate.substring(0, 4);
        outMonth = qsCheckOutDate.substring(5, 7);
        outDay = qsCheckOutDate.substring(8, 10);
    }
    var DtCheckIn = new Date(inMonth + GetDateSeperator() + inDay + GetDateSeperator() + inYear);
    var DtCheckOut = new Date(outMonth + GetDateSeperator() + outDay + GetDateSeperator() + outYear);
    var one_day = 1000 * 60 * 60 * 24;

    var mnDate = new Date() ;
    mnDate.setTime(mnDate.getTime() - one_day);
    var minDate = new Date(mnDate.toDateString());
    var CurrentYear = mnDate.getFullYear();
    var MaxYear = CurrentYear + 2
    var mxDate = new Date("12/31/" + MaxYear);
   
    if (DtCheckIn > mxDate || DtCheckIn < minDate || DtCheckOut > mxDate || DtCheckOut < minDate || DtCheckIn > DtCheckOut) {
        var sDate = new Date();
        sDate.setTime(sDate.getTime() + one_day * 17);
        var eDate = new Date();
        eDate.setTime(eDate.getTime() + one_day * 19);
        var qString = location.search.substr(1)
        qString = remQStringName(qString, "page")
        qString = remQStringName(qString, "inDay")
        qString = remQStringName(qString, "inMonth")
        qString = remQStringName(qString, "inYear")
        qString = remQStringName(qString, "outDay")
        qString = remQStringName(qString, "outMonth")
        qString = remQStringName(qString, "outYear")
        inDay = sDate.getDate(); inDay = AddPrecedingZero(inDay);
        inMonth = sDate.getMonth() + 1; inMonth = AddPrecedingZero(inMonth);
        inYear = sDate.getFullYear();
        outDay = eDate.getDate(); outDay = AddPrecedingZero(outDay);
        outMonth = eDate.getMonth() + 1; outMonth = AddPrecedingZero(outMonth);
        outYear = eDate.getFullYear();
        var strCheckIn = DateFormat(inDay + GetDateSeperator() + inMonth + GetDateSeperator() + inYear);
        var strCheckOut = DateFormat(outDay + GetDateSeperator() + outMonth + GetDateSeperator() + outYear);
        qString += "&" + "inDay" + "=" + inDay;
        qString += "&" + "inMonth" + "=" + inMonth;
        qString += "&" + "inYear" + "=" + inYear;
        qString += "&" + "outDay" + "=" + outDay;
        qString += "&" + "outMonth" + "=" + outMonth;
        qString += "&" + "outYear" + "=" + outYear;
        qString = setQStringName(qString, "Checkin", new Array(strCheckIn))
        qString = setQStringName(qString, "Checkout", new Array(strCheckOut))
        location = location.pathname + "?" + qString
    }
}/*
MIT LICENSE
Copyright (c) 2007 Monsur Hossain (http://www.monsur.com)

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.
*/

// ****************************************************************************
// CachePriority ENUM
// An easier way to refer to the priority of a cache item
var CachePriority = {
    Low: 1,
    Normal: 2,
    High: 4
}

// ****************************************************************************
// Cache constructor
// Creates a new cache object
// INPUT: maxSize (optional) - indicates how many items the cache can hold.
//                             default is -1, which means no limit on the 
//                             number of items.
function Cache(maxSize) {
    this.items = {};
    this.count = 0;
    if (maxSize == null)
        maxSize = -1;
    this.maxSize = maxSize;
    this.fillFactor = .75;
    this.purgeSize = Math.round(this.maxSize * this.fillFactor);
    
    this.stats = {}
    this.stats.hits = 0;
    this.stats.misses = 0;
}

// ****************************************************************************
// Cache.getItem
// retrieves an item from the cache, returns null if the item doesn't exist
// or it is expired.
// INPUT: key - the key to load from the cache
Cache.prototype.getItem = function(key) {

    // retrieve the item from the cache
    var item = this.items[key];
    
    if (item != null) {
        if (!this._isExpired(item)) {
            // if the item is not expired
            // update its last accessed date
            item.lastAccessed = new Date().getTime();
        } else {
            // if the item is expired, remove it from the cache
            this._removeItem(key);
            item = null;
        }
    }
    
    // return the item value (if it exists), or null
    var returnVal = null;
    if (item != null) {
        returnVal = item.value;
        this.stats.hits++;
    } else {
        this.stats.misses++;
    }
    return returnVal;
}

// ****************************************************************************
// Cache.setItem
// sets an item in the cache
// parameters: key - the key to refer to the object
//             value - the object to cache
//             options - an optional parameter described below
// the last parameter accepts an object which controls various caching options:
//      expirationAbsolute: the datetime when the item should expire
//      expirationSliding: an integer representing the seconds since
//                         the last cache access after which the item
//                         should expire
//      priority: How important it is to leave this item in the cache.
//                You can use the values CachePriority.Low, .Normal, or 
//                .High, or you can just use an integer.  Note that 
//                placing a priority on an item does not guarantee 
//                it will remain in cache.  It can still be purged if 
//                an expiration is hit, or if the cache is full.
//      callback: A function that gets called when the item is purged
//                from cache.  The key and value of the removed item
//                are passed as parameters to the callback function.
Cache.prototype.setItem = function(key, value, options) {

    function CacheItem(k, v, o) {
        if ((k == null) || (k == ''))
            throw new Error("key cannot be null or empty");
        this.key = k;
        this.value = v;
        if (o == null)
            o = {};
        if (o.expirationAbsolute != null)
            o.expirationAbsolute = o.expirationAbsolute.getTime();
        if (o.priority == null)
            o.priority = CachePriority.Normal;
        this.options = o;
        this.lastAccessed = new Date().getTime();
    }

    // add a new cache item to the cache
    if (this.items[key] != null)
        this._removeItem(key);
    this._addItem(new CacheItem(key, value, options));
    
    // if the cache is full, purge it
    if ((this.maxSize > 0) && (this.count > this.maxSize)) {
        this._purge();
    }
}

// ****************************************************************************
// Cache.clear
// Remove all items from the cache
Cache.prototype.clear = function() {

    // loop through each item in the cache and remove it
    for (var key in this.items) {
      this._removeItem(key);
    }  
}

// ****************************************************************************
// Cache._purge (PRIVATE FUNCTION)
// remove old elements from the cache
Cache.prototype._purge = function() {
    
    var tmparray = new Array();
    
    // loop through the cache, expire items that should be expired
    // otherwise, add the item to an array
    for (var key in this.items) {
        var item = this.items[key];
        if (this._isExpired(item)) {
            this._removeItem(key);
        } else {
            tmparray.push(item);
        }
    }
    
    if (tmparray.length > this.purgeSize) {

        // sort this array based on cache priority and the last accessed date
        tmparray = tmparray.sort(function(a, b) { 
            if (a.options.priority != b.options.priority) {
                return b.options.priority - a.options.priority;
            } else {
                return b.lastAccessed - a.lastAccessed;
            }
        });
        
        // remove items from the end of the array
        while (tmparray.length > this.purgeSize) {
            var ritem = tmparray.pop();
            this._removeItem(ritem.key);
        }
    }
}

// ****************************************************************************
// Cache._addItem (PRIVATE FUNCTION)
// add an item to the cache
Cache.prototype._addItem = function(item) {
    this.items[item.key] = item;
    this.count++;
}

// ****************************************************************************
// Cache._removeItem (PRIVATE FUNCTION)
// Remove an item from the cache, call the callback function (if necessary)
Cache.prototype._removeItem = function(key) {
    var item = this.items[key];
    delete this.items[key];
    this.count--;
    
    // if there is a callback function, call it at the end of execution
    if (item.options.callback != null) {
        var callback = function() {
            item.options.callback(item.key, item.value);
        }
        setTimeout(callback, 0);
    }
}

// ****************************************************************************
// Cache._isExpired (PRIVATE FUNCTION)
// Returns true if the item should be expired based on its expiration options
Cache.prototype._isExpired = function(item) {
    var now = new Date().getTime();
    var expired = false;
    if ((item.options.expirationAbsolute) && (item.options.expirationAbsolute < now)) {
        // if the absolute expiration has passed, expire the item
        expired = true;
    } 
    if ((expired == false) && (item.options.expirationSliding)) {
        // if the sliding expiration has passed, expire the item
        var lastAccess = item.lastAccessed + (item.options.expirationSliding * 1000);
        if (lastAccess < now) {
            expired = true;
        }
    }
    return expired;
}

Cache.prototype.toHtmlString = function() {
    var returnStr = this.count + " item(s) in cache<br /><ul>";
    for (var key in this.items) {
        var item = this.items[key];
        returnStr = returnStr + "<li>" + item.key.toString() + " = " + item.value.toString() + "</li>";
    }
    returnStr = returnStr + "</ul>";
    return returnStr;
}
