﻿

function originChanged() {
    var ddlOrigin = $(".ddlOrigin");
    var ddlDestination = $(".ddlDestination");
    ddlDestination.val("-1");

    if (ddlOrigin.val() == "-1") {
        ddlDestination.attr("disabled", "disabled");
    } else {
        ddlDestination.removeAttr("disabled");
    }
    var routes = $("[id$='_hdAllRoutes']").val();
    if (routes != null) {
        outputDestinations(routes, ddlOrigin);
    }
}

function outputDestinations(allRoutes, ddlOrigin) {
    var routes = allRoutes.split(',')
    
    var selectedAirport = ddlOrigin.val();
    var arrivalAirportsList = new Array();
    var allDepartAirports = selectedAirport.split(',');
    $.each(allDepartAirports, function(departIndex, departValue) {
        $.each(routes, function(index, value) {
            var newValue = value.replace('-', '');
            value = newValue;
            var departAirport = value.substring(0, 3);
            if (departAirport == departValue) {
                var arrivalAirport = value.substring(3, value.length);
                arrivalAirportsList.push(arrivalAirport);
            }
        });
    });

    $(".ddlDestination").children().remove().end();
    ddlOrigin.children().clone().appendTo($(".ddlDestination"));
    $(".ddlDestination").val("-1");

    $(".ddlDestination option").each(function() {
        if ($.inArray($(this).val(), arrivalAirportsList) > -1 || $(this).val() == "-1") {
//            $(this).append();
//            $(this).parent().append();
        } else {
            $(this).remove();
        }
    });

    $(".ddlDestination optgroup").each(function() {
        var $optGroup = $(this);
        var $child = $optGroup.children('option');
        if ($child.length < 1) {
            $optGroup.remove();
        }

        if ($child.length > 1) {
            var cityStr = "";
            $.each($child, function(index, value) {
                cityStr += value.value + ",";
            });

            cityStr = cityStr.substring(0, cityStr.length - 1);
            ddlOrigin.children("optgroup").children("option[value='" + cityStr + "']").clone().prependTo($optGroup);
        }
    });
}


function AdjustPaymentDetailsWidthIfIE() {
    // Called from BookingInfoGrid and PassengerInfoGrid (See OnInit() )
    if ($.browser.msie) {
        $(".payment-details").css("width", "450px");
    }
}


      var postbackElement = null;
      function RestoreFocus(source, args)
      {
        if(postbackElement!=null)
        {
            var d = document.getElementById(postbackElement.id);
            if(d!=null)
            {
                d.focus();
            }
        }
      }
      function SavePostbackElement(source, args)
      {
        postbackElement = args.get_postBackElement();
      }
      function AddRequestHandler()
      {
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_endRequest(RestoreFocus);
        prm.add_beginRequest(SavePostbackElement);
      }

//Alternative week view
      $(document).ready(function() {
          $("a.show-details-command").live("click", function(e) {
              var target = $(this).parent().find("div.flight-details");
              if (target.is(":visible")) {
                  target.hide();
                  $(document).unbind("click.flight-details");
              } else {
                  $("div.flight-details").hide();
                  setTimeout(function() {
                      target.show();
                      $(document).bind("click.flight-details", function() {
                          target.hide();
                          $(document).unbind("click.flight-details");
                      });
                  }, 0);
              }
              return false;
          });
          var tooltipTimeout = null;
          $("td.availability-cell").live("mouseover", function() {
              var tooltip = $(this).find("div.tooltip-data");
              clearTimeout(tooltipTimeout);
              tooltipTimeout = setTimeout(function() {
                  $("div.tooltip-data").hide();
                  tooltip.fadeIn("fast");
              }, 100);
          }).live("mouseout", function() {
              clearTimeout(tooltipTimeout);
              $("div.tooltip-data").hide();
          }).live("mousemove", function(e) {
              var tooltip = $(this).find("div.tooltip-data");
              tooltip.css({ left: (e.pageX + 10), top: (e.pageY + 10) });
          });

          originChanged();

//          var popupShown = document.cookie.match ( '(^|;) ?' + 'browserpopupwarning' + '=([^;]*)(;|$)' );

//          if (($.browser.safari || $.browser.webkit || $.browser.opera) && popupShown == null) {
//              alert(getTranslation("BrowserWarningPopup"));
//              var expires = new Date();
//              expires.setDate(expires.getTime() + 31536000000);
//              document.cookie = 'browserpopupwarning' + '=' + '1' + ';expires=' + expires.toUTCString();
//          }
      });

//Autocomplete
/*function OnClientSelected(source, eventArgs) {
    var results = eval('(' + eventArgs.get_value() + ')');
    var div = $("#" + results.Identifier);

    var tb = $("#" + results.Identifier + " [id$='_txtFirstName']");
    tb.val(results.FirstName);
    $("#" + results.Identifier + " [id$='_txtLastName']").val(results.LastName);
    $("#" + results.Identifier + " [id$='_txtPhone']").val(results.Phone);
    $("#" + results.Identifier + " [id$='_txtCellular']").val(results.Mobile);
    $("#" + results.Identifier + " [id$='_txtPEmail']").val(results.Email);
    $("#" + results.Identifier + " [id$='_txtPEmail']").val(results.Email);

    $("#" + results.Identifier + " [id$='_SelectedReceiver']").val(results.UserID);

    //Gender dropdownlist
    $("#" + results.Identifier + " [id$='_ddlGender']").val(results.Gender);
}*/

 //Common stuff
function DisableEnterButton(e) {
    var key;
    if (window.event)
        key = window.event.keyCode; //IE
    else
        key = e.which; //firefox     

    switch (key) {
        case 13:
            return false;
            break;
        default:
            return true;
    }

}
function MM_openBrWindow(theURL, winName, features) {
    var popUpWindow = window.open(theURL, winName, features);
    popUpWindow.focus();
};

function toggleClickEvent(strElementID) {
    try {
        var oElement = document.getElementById(strElementID);
        oElement.click();
    } catch (err) { }
    return true;
}

function InitShoppingCart() {
    $("#ShoppingCart div.toggle a").click(function() {
        $("#ShoppingCart div.detailed-view").slideToggle();
        $(this).toggleClass("open");
        return false;
    });
};

function onInvoke(sender, args) {
    var popupProgress = $find('popupProgress');
    if (popupProgress != null) {
        popupProgress.show();
    }
};

function onComplete(sender, args) {
    var popupProgress = $find('popupProgress');
    if (popupProgress != null) {
        popupProgress.hide();
    }
};

function onEndRequest(sender, args) {
    // Check to see if there's an error on this request.
    if (args.get_error() != undefined) {
        // If there is, show the custom error.
        //$get('Error').style.visibility = "visible";
        //        $get('Error').style.color = "red";
        if (typeof redirectToErrorPage == 'function') {
            redirectToErrorPage();
            // Let the framework know that the error is handled, 
            //  so it doesn't throw the JavaScript alert.
            args.set_errorHandled(true);
        }
    }
};

function pageUnload() {
    Sys.Net.WebRequestManager.remove_invokingRequest(onInvoke);
    Sys.Net.WebRequestManager.remove_completedRequest(onComplete);
};

function SetUniqueRadioButton(nameregex, current) {
    re = new RegExp(nameregex);
    for (i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i]
        if (elm.type == 'radio') {
            if (re.test(elm.name)) {
                elm.checked = false;
            }
        }
    }
    current.checked = true;
};



function checkDate(sender, args) {
    //create a new date var and set it to the
    //value of the senders selected date
    var selectedDate = new Date();
    selectedDate = sender._selectedDate;
    //create a date var and set it's value to today
    var todayDate = new Date();
    var mssge = "";

    if (selectedDate < todayDate) {
        //set the senders selected date to today
        sender._selectedDate = todayDate;
        //set the textbox assigned to the cal-ex to today
        sender._textbox.set_Value(sender._selectedDate.format(sender._format));
        //alert the user what we just did and why
        alert("Warning! - Date Cannot be in the past");
    }
};



function WatermarkOnFocus(objElement, defaultText) {
    if (objElement.value == defaultText) {
        objElement.value = "";
    }
};

function WatermarkOnBlur(objElement, defaultText) {

    var textValue = objElement.value;

    if (textValue == defaultText || textValue.length == 0) {
        objElement.value = defaultText;
    }

};

$(document).ready(function(event) {
    $("td.menurow").live("click", function(e) {
    $("div.menu-data").hide();

    // Show current
    var target = $(this).parent().find("div.menu-data");
    target.show();
    
    var x = e.pageX;
    var y = e.pageY;
    target.css({left:(x),top:(y)});
    });
        
});

// Activate Tooltips
$(document).ready(function(event) {

    $(".MAX .popup-menu a").live("mouseover", function() {
        
        $(this).css('background', '#333');
        $(this).css('color', '#FFFFFF');
    });
    $(".MAX .popup-menu a").live("mouseleave", function() {
        
        $(this).css('background', '#eee');
        $(this).css('color', '#333');
    });
    
    var tooltipTimeout = null;

    $("td.submenu-cell .javaScriptPopupOnMouseOver").live("mouseenter", function() {
        //Hide others
        $("div.menu-data").hide();

        // Show current
        var target = $(this).parent().parent().find("div.menu-data");
        target.show();

        // Set Possition
        var button = $(this).parent().parent().find("td.submenu-cell");
        var position = button.position();
        target.css({ left: (position.left), top: (position.top) });

        return false;
    });

    $("td.submenu-cell .javaScriptPopupOnClick").live("click", function() {
        //Hide others
        $("div.menu-data").hide();

        // Show current
        var target = $(this).parent().parent().find("div.menu-data");
        target.show();

        // Set Possition
        var button = $(this).parent().parent().find("td.submenu-cell");
        var position = button.position();
        target.css({ left: (position.left), top: (position.top) });

        return false;
    });

    $("div.menu-data").live("mouseleave", function() {

        var target = $(this).parent().find("div.menu-data");
        target.hide();

        return false;
    });

});

function filterStandbyTickets() {
    var allStandbyRows = $('table[id$="dgStandbyTickets"]').children('tbody').children('tr').not('.header');
    $(allStandbyRows).show();
    $(allStandbyRows).removeClass(); 
    var route = $('select[id$="ddlRoute"]').val();
    var paxType = $('select[id$="ddlPaxType"]').val();
    var article = $('select[id$="ddlPricedProduct"]').val();

    $.each(allStandbyRows, function(i, row) {

        if (route != "-1") {
            var routeValue = $(row).find('span[class="route"]').text();
            if (route != routeValue) {
                $(row).hide();
            }
        }

        if (paxType != "-1") {
            var paxTypeValue = $(row).find('span[class="paxtype"]').text();
            if (paxType != paxTypeValue) {
                $(row).hide();
            }
        }

        if (article != "-1") {
            var articleValue = $(row).find('span[class="article"]').text();
            if (article != articleValue) {
                $(row).hide();
            }
        }
    });
    $(allStandbyRows).filter(":visible").filter(":odd").addClass('alt');
}


//PhoneMobilValidatro
function inputCheck(source, args) {
    args.IsValid = false;
    if ($("[id$='_txtPhone']").val() == "" && $("[id$='_txtCellular']").val() == "") {
        args.IsValid = false;
    }
    else {
        args.IsValid = true;
    }
}



//PriceListDetails
$(document).ready(function() {
    $("a.show-price-details-command").live("click", function(e) {
        var target = $(this).parent().find("div.price-item-details");
        if (target.is(":visible")) {
            target.hide();
            $(document).unbind("click.price-item-details");
        } else {
            $("div.price-item-details").hide();
            setTimeout(function() {
                target.show();
                $(document).bind("click.price-item-details", function() {
                    target.hide();
                    $(document).unbind("click.price-item-details");
                });
            }, 0);
        }
        return false;
    });

});


//RebateListDetails
$(document).ready(function() {
    $("a.show-rebate-details-command").live("click", function(e) {
        var target = $(this).parent().find("div.price-item-details");
        if (target.is(":visible")) {
            target.hide();
            $(document).unbind("click.price-item-details");
        } else {
            $("div.price-item-details").hide();
            setTimeout(function() {
                target.show();
                $(document).bind("click.price-item-details", function() {
                    target.hide();
                    $(document).unbind("click.price-item-details");
                });
            }, 0);
        }
        return false;
    });

    $("a.show_payments").live("click", function(e) {
        var target = $(this).parent().find("div.payment-details");
        if (target.is(":visible")) {
            target.hide();
            $(document).unbind("click.payment-details");
        } else {
            $("div.payment-details").hide();
            setTimeout(function() {
                target.show();
                $(document).bind("click.payment-details", function() {
                    target.hide();
                    $(document).unbind("click.payment-details");
                });
            }, 0);
        }
        return false;
    });

});

//Tooltip

function myTooltip(caller, tooltip, showOnFocus, type, alignment) {
    if ($.browser.msie && $.browser.version == "6.0") {
        tooltip.removeClass().addClass("TooltipType" + type);
    } else
        tooltip.remove().appendTo($(document.body)).removeClass().addClass("TooltipType" + type);

    var showFn = function() {
        var pos = $(this).offset();
        switch (type) {
            case "1":
                if (alignment == "Right")
                    tooltip.css("left", pos.left + $(this).outerWidth());
                else
                    tooltip.css("left", pos.left);
                tooltip.css("top", pos.top - tooltip.outerHeight());
                break;
            case "2":
                if (alignment == "Left")
                    tooltip.css("left", pos.left - tooltip.outerWidth());
                else
                    tooltip.css("left", pos.left - tooltip.outerWidth() + $(this).outerWidth());
                tooltip.css("top", pos.top - tooltip.outerHeight());
                break;
            case "3":
                if (alignment == "Right")
                    tooltip.css("left", pos.left + $(this).outerWidth());
                else
                    tooltip.css("left", pos.left);
                tooltip.css("top", pos.top + $(this).outerHeight());
                break;
            case "4":
                if (alignment == "Left")
                    tooltip.css("left", pos.left - tooltip.outerWidth());
                else
                    tooltip.css("left", pos.left - tooltip.outerWidth() + $(this).outerWidth());
                tooltip.css("top", pos.top + $(this).outerHeight());
                break;
        };
        if ($.browser.msie && $.browser.version == "6.0") {
            tooltip.get(0).iframe = $('<iframe src="javascript:false" style="z-index:9;position:absolute;filter:alpha(opacity=0);"></iframe>').appendTo(document.body);
            tooltip.get(0).iframe.css({ left: tooltip.css("left"), top: tooltip.css("top"), width: tooltip.width(), height: tooltip.height() }).show();
        }
        tooltip.css("visibility", "visible");
    };
    var hideFn = function() {
        tooltip.css({ visibility: "hidden", left: 0, top: 0 });
        if (tooltip.get(0).iframe)
            tooltip.get(0).iframe.remove();
    }
    if (showOnFocus)
        caller.focus(showFn).blur(hideFn);
    else
        caller.mouseover(showFn).mouseout(hideFn);
}
var domReady = false;
$(document).ready(function() {
    domReady = true;
});
function InitTooltips() {
    if (domReady)
        $("div.TooltipType").each(function() {
            var controls = $(this).find("input.tooltipTargetControlId").val();
            var tooltipType = $(this).find("input.tooltipType").val();
            var tooltipShowOnFocus = $(this).find("input.tooltipShowOnFocus").val() != "";
            var tooltipAlignment = $(this).find("input.tooltipAlignment").val();
            myTooltip($("#" + controls), $(this), tooltipShowOnFocus, tooltipType, tooltipAlignment);
        });
    else {
        $(document).ready(function() {
            $("div.TooltipType").each(function() {
                var controls = $(this).find("input.tooltipTargetControlId").val();
                var tooltipType = $(this).find("input.tooltipType").val();
                var tooltipShowOnFocus = $(this).find("input.tooltipShowOnFocus").val() != "";
                var tooltipAlignment = $(this).find("input.tooltipAlignment").val();
                myTooltip($("#" + controls), $(this), tooltipShowOnFocus, tooltipType, tooltipAlignment);
            });
        });
    }
}



//Tooltip dropdown
$(document).ready(function() {
    function init() {
        $("div.voucher-dropdown-container").each(function() {
            var valueField = $(this).find("input[type=hidden]");
            var container = $(this);
            $(this).find("tr:not(.header):eq(" + valueField.attr("value") + ")").addClass("selected");
            $(this).find("tr:not(.header)").each(function(i) {
                $(this).attr("itemIndex", i);
            }).unbind("click").click(function(e) {
                valueField.attr("value", $(this).attr("itemIndex"));
                //toggle update
                container.find(".update-button").click();
            });
        });
    };
    Sys.Application.add_load(init);
    init();
});


function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}
function getTranslation(key) {
    if (_localization !== undefined) {
        return _localization[key];
    }
    return "Error: Key: "+key+" not defiend";
}

function loggedOutMessage() {
    var isSearchPage = $("#QuickSearchBox").length != 0;
    if (isSearchPage) {
        window.location.reload();
    }else{
        alert(getTranslation("BusterLoggedOutMessage"));
        window.location.href = "/";
    }
}

function  initTimeOutCheck(){
    var timeout = getCookie("Session.Timeout");
    if (timeout != "") {
        var now = new Date();
        var timeoutDate = new Date();
        timeoutDate.setTime(timeout);
        var diff = timeoutDate.getTime() - now.getTime();
        if (diff < 0) {
            loggedOutMessage();
        } else {
            window.setTimeout("initTimeOutCheck()", 5000);
        }
    }
}


/* Wayfarer Tooltip
* Version 1.0.6
* Author Abel Mohler
* URI: http://www.wayfarerweb.com/wtooltip.php
* Released with the MIT License: http://www.wayfarerweb.com/mit.php
*/
(function($) { //jQuery.noConflict()compliant
    $.fn.wTooltip = function(o, callback) {
        o = $.extend({ //defaults, can be overidden
            content: null, //string content for tooltip.
            ajax: null, //path to content for tooltip
            follow: true, //does tooltip follow the cursor?
            auto: true, //If false, tooltip won't automatically transition, it must be manually shown/hidden
            fadeIn: 0, //fade in, in milliseconds ("fast, "slow", etc may also be used)
            fadeOut: 0, //fade out, in milliseconds ("fast, "slow", etc may also be used)
            appendTip: document.body, //should probably not need to be overridden
            degrade: false, //if true, in IE6 tooltip will degrade to a title attribute message
            offsetY: 10, //offsetY and offsetX properties designate position from the cursor
            offsetX: 1,
            style: {},
            className: null, //to style the tooltip externally, pass a className or id
            id: null,
            callBefore: function(tooltip, node, settings) {
            }, //called when mouse enters the area
            callAfter: function(tooltip, node, settings) {
            }, //called when mouse leaves the area (same as "callback" option)
            clickAction: function(tooltip, node) {
                $(tooltip).hide();
            }, //called when the element is clicked, with access to tooltip
            delay: 0, //delay (in milliseconds)before tooltip appears and callBefore executes
            timeout: 0 //delay (in milliseconds)before tooltip transitions away, and callAfter executes
        }, o ||
        {});

        if (!o.style && typeof o.style != "object") {
            o.style = {};
            o.style.zIndex = "1000";
        }
        else {
            o.style = $.extend({ //the default style rules of the tooltip
                border: "1px solid gray",
                background: "#edeef0",
                color: "#000",
                padding: "10px",
                zIndex: "1000",
                textAlign: "left"
            }, o.style ||
            {});
        }

        if (typeof callback == "function")
            o.callAfter = callback || o.callAfter;

        o.style.display = "none", o.style.position = "absolute"; //permanent defaults
        //private settings
        var title, timeout, timeout2, iId, over = {}, firstMove = true, hovered = false, maxed = false, tooltip = document.createElement('div'), ie6 = (typeof document.body.style.maxWidth == "undefined") ? true : false, talk = (typeof $.talk == "function" && typeof $.listen == "function") ? true : false;

        if (o.id)
            tooltip.id = o.id;
        if (o.className)
            tooltip.className = o.className;

        o.degrade = (o.degrade && ie6) ? true : false; //only degrades if also IE6
        for (var p in o.style)//apply styles to tooltip
            tooltip.style[p] = o.style[p];

        function fillTooltip(condition) {
            if (condition) {
                if (o.degrade)//replace html characters for proper degradation to title attribute
                    $(tooltip).html(o.content.replace(/<\/?[^>]+>/gi, ''));
                else //otherwise just fill the tooltip with content
                    $(tooltip).html(o.content);
            }
        }

        if (o.ajax) { //if o.ajax is selected, this will fill and thus override o.content
            $.get(o.ajax, function(data) {
                if (data)
                    o.content = data;
                fillTooltip(o.content);
            });
        }

        function offConditions(that) {
            function _offActions(that) {
                if (title && !o.content) {
                    title = null;
                }
            }
            function _execute() {
                if (!hovered && o.auto) {
                    clearInterval(iId);
                    if (o.fadeOut) {
                        $(tooltip).fadeOut(o.fadeOut, function() {
                            _offActions(that);
                        });
                    }
                    else {
                        _offActions(that);
                        tooltip.style.display = "none";
                    }
                }
                if (typeof o.callAfter == "function")
                    o.callAfter(tooltip, that, o);
                if (talk)
                    o = $.listen(o);
            }
            if (o.timeout > 0) {
                timeout2 = setTimeout(function() {
                    _execute();
                }, o.timeout);
            }
            else {
                _execute();
            }
        }

        $(tooltip).hover(function() {
            hovered = true;
        }, function() {
            hovered = false;
            offConditions(over);
        });

        //initialize
        if (talk) { //A "channel" for plugins to "talk" to each other, and callbacks to manipulate settings
            o.key = tooltip;
            o.plugin = "wTooltip";
            o.channel = "wayfarer";
            $.talk(o);
        }

        fillTooltip(o.content && !o.ajax);
        $(tooltip).appendTo(o.appendTip);

        return this.each(function() { //returns the element chain
            $(this).hover(function() {
                var that = this;
                clearTimeout(timeout2);
                if ((this.title || this.titleMemKeep) && !o.degrade && !o.content) {
                    title = this.title || this.titleMemKeep;
                    if (this.title) {
                        this.titleMemKeep = this.title;
                        this.title = null;
                    }
                }
                if (o.content && o.degrade)
                    this.title = tooltip.innerHTML;

                function _execute() {
                    if (typeof o.callBefore == "function")
                        o.callBefore(tooltip, that, o);
                    if (talk)
                        o = $.listen(o); //ping for new settings
                    if (o.auto) {
                        var display;
                        if (o.content) {
                            if (!o.degrade)
                                display = "block";
                        }
                        else
                            if (title && !o.degrade) {
                            $(tooltip).html(unescape(title));
                            display = "block";
                            title = null;
                        }
                        else {
                            display = "none";
                        }
                        if (display == "block" && o.fadeIn)
                            $(tooltip).fadeIn(o.fadeIn);
                        else
                            tooltip.style.display = display;
                    }
                }

                if (o.delay > 0) {
                    timeout = setTimeout(function() {
                        _execute();
                    }, o.delay);
                }
                else {
                    _execute();
                }
            }, function() {
                clearTimeout(timeout);
                var that = this;
                firstMove = true;
                if (!o.follow || maxed || (o.offsetX < 0 && o.offsetY < 0)) {
                    setTimeout(function() {
                        iId = setInterval(function() {
                            offConditions(that)
                        }, 1)
                    }, 1);
                }
                else {
                    offConditions(this);
                }
            });

            $(this).mousemove(function(e) {
                over = this; //tracks the event trigger in the plugin-global "over"
                if (o.follow || firstMove) {
                    var scrollY = $(window).scrollTop(), scrollX = $(window).scrollLeft(), top = e.clientY + scrollY + o.offsetY, left = e.clientX + scrollX + o.offsetX, outerH = $(o.appendTip).outerHeight(), innerH = $(o.appendTip).innerHeight(), maxLeft = $(window).width() + scrollX - $(tooltip).outerWidth(), maxTop = $(window).height() + scrollY - $(tooltip).outerHeight();

                    top = (outerH > innerH) ? top - (outerH - innerH) : top; //if appended area (usually BODY) has a border on top, adjust
                    maxed = (top > maxTop || left > maxLeft) ? true : false;

                    if (left - scrollX <= 0 && o.offsetX < 0)
                        left = scrollX;
                    else
                        if (left > maxLeft)
                        left = maxLeft;
                    if (top - scrollY <= 0 && o.offsetY < 0)
                        top = scrollY;
                    else
                        if (top > maxTop)
                        top = maxTop;

                    tooltip.style.top = top + "px";
                    tooltip.style.left = left + "px";
                    firstMove = false;
                }
            });

            if (typeof o.clickAction == "function") {
                $(this).click(function() {
                    o.clickAction(tooltip, this);
                });
            }
        });
    }
})(jQuery);


/*
* jQuery Autocomplete plugin 1.1
*
* Copyright (c) 2009 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 15 2009-08-22 10:30:27Z joern.zaefferer $
* Added Busterspecific modifications
*/

; (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) {
            // a keypress means the input has focus
            // avoids issue where input had focus before the autocomplete was applied
            hasFocus = 1;
            // 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: //  Busteradaptation, do not autofill on 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) {
                    var seperator = options.multipleSeparator.length;
                    var cursorAt = $(input).selection().start;
                    var wordAt, progress = 0;
                    $.each(words, function(i, word) {
                        progress += word.length;
                        if (cursorAt <= progress) {
                            wordAt = i;
                            return false;
                        }
                        progress += seperator;
                    });
                    words[wordAt] = v;
                    // TODO this should set the cursor to the right position, but it gets overriden somewhere
                    //$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
                    v = words.join(options.multipleSeparator);
                }
                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);
                if (!options.matchCase)
                    currentValue = currentValue.toLowerCase();
                request(currentValue, receiveData, hideResultsNow);
            } else {
                stopLoading();
                select.hide();
            }
        };

        function trimWords(value) {
            if (!value)
                return [""];
            if (!options.multiple)
                return [$.trim(value)];
            return $.map(value.split(options.multipleSeparator), function(word) {
                return $.trim(value).length ? $.trim(word) : null;
            });
        }

        function lastWord(value) {
            if (!options.multiple)
                return value;
            var words = trimWords(value);
            if (words.length == 1)
                return words[0];
            var cursorAt = $(input).selection().start;
            if (cursorAt == value.length) {
                words = trimWords(value)
            } else {
                words = trimWords(value.replace(value.substring(cursorAt), ""));
            }
            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)
                $(input).selection(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("");
				            $input.trigger("result", null);
				        }
				    }
				}
			);
            }
        };

        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({
                    type: "POST", //Buster specific adaptation (webmethod)                
                    // 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: "{prefixText:'" + lastWord(term) + "'}", //Buster specific adaptation (webmethod)
                    contentType: "application/json; charset=utf-8", //Buster specific adaptation (webmethod)
                    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);
        };

    };

    $.Autocompleter.defaults = {
        inputClass: "ac_input",
        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: 500,
        multiple: false,
        multipleSeparator: ", ",
        highlight: function(value, term) {
            return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
        },
        scroll: true,
        scrollHeight: 180
    };

    $.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 (options.matchContains == "word") {
                i = s.toLowerCase().search("\\b" + sub.toLowerCase());
            }
            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)
		.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();
                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();
            }
        };
    };

    $.fn.selection = function(start, end) {
        if (start !== undefined) {
            return this.each(function() {
                if (this.createTextRange) {
                    var selRange = this.createTextRange();
                    if (end === undefined || start == end) {
                        selRange.move("character", start);
                        selRange.select();
                    } else {
                        selRange.collapse(true);
                        selRange.moveStart("character", start);
                        selRange.moveEnd("character", end);
                        selRange.select();
                    }
                } else if (this.setSelectionRange) {
                    this.setSelectionRange(start, end);
                } else if (this.selectionStart) {
                    this.selectionStart = start;
                    this.selectionEnd = end;
                }
            });
        }
        var field = this[0];
        if (field.createTextRange) {
            var range = document.selection.createRange(),
			orig = field.value,
			teststring = "<->",
			textLength = range.text.length;
            range.text = teststring;
            var caretAt = field.value.indexOf(teststring);
            field.value = orig;
            this.selection(caretAt, caretAt + textLength);
            return {
                start: caretAt,
                end: caretAt + textLength
            }
        } else if (field.selectionStart !== undefined) {
            return {
                start: field.selectionStart,
                end: field.selectionEnd
            }
        }
    };

})(jQuery);

// notify that the script has been loaded <-- new!
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();



var acOptions = {
    minChars: 1,
    max: 100,
    dataType: 'json',
    extraParams: {
        format: 'json'
    },
    parse: function(data) {
        var parsed = [];
        data = data.d;
        for (var i = 0; i < data.length; i++) {
            parsed[parsed.length] = {
                data: data[i],
                value: data[i].FirstName,
                result: data[i].FirstName
            };
        }
        return parsed;
    },
    formatItem: function(item) {
        return item.FirstName + ' (' + item.LastName + ', ' + item.Phone + ', ' + item.Mobile + ',  ' + item.Email + ')';
    }
};

var acOptionsForLastName = {
    minChars: 1,
    max: 100,
    dataType: 'json',
    extraParams: {
        format: 'json'
    },
    parse: function(data) {
        var parsed = [];
        data = data.d;

        for (var i = 0; i < data.length; i++) {
            parsed[parsed.length] = {
                data: data[i],
                value: data[i].LastName,
                result: data[i].LastName
            };
        }

        return parsed;
    },
    formatItem: function(item) {
        return item.LastName + ' (' + item.FirstName + ', ' + item.Phone + ', ' + item.Mobile + ', ' + item.Email + ')';
    }
};

/*
* Enables autocomplete for first and last name of passanger information. Should only be invoked for logged in users
*/
var autoCompleteFirstNameAlreadyBound = false;
var autoCompleteLastNameAlreadyBound = false;

function EnableAutoComplete(){



    $(document).delegate(".firstName", "focus", function() {

        if (!autoCompleteFirstNameAlreadyBound) {
            jQuery.each($("[id$='_txtFirstName']"), function(index, item) {
                var elem = $(item);
                var firstNameTextBox = elem.parent().parent().find(".firstName");
                var lastNameTextBox = elem.parent().parent().find(".section").find(".lastName");
                var gender = elem.parent().parent().find(".section > .gender");
                var phone = elem.parent().parent().find(".section > .txtPhone");
                var cellular = elem.parent().parent().find(".section > .txtCellular");
                var email = elem.parent().parent().find(".section > .email");
                var selectedReceiver = elem.parent().parent().find(".section > .selectedReceiver");

                elem.autocomplete("/UserControls/MAX/Booking/AutoComplete.aspx/GetFirstNamesByPrefix", acOptions).result(function(e, data) {
                    firstNameTextBox.val(data.FirstName);
                    lastNameTextBox.val(data.LastName);
                    gender.val(data.Gender);
                    phone.val(data.Phone);
                    cellular.val(data.Mobile);
                    email.val(data.Email);
                    selectedReceiver.val(data.UserID);
                });
            });
            autoCompleteFirstNameAlreadyBound = true;
        }

    });

    $(document).delegate(".lastName", "focus", function() {

        if (!autoCompleteLastNameAlreadyBound) {
            jQuery.each($("[id$='_txtLastName']"), function(index, item) {
                var elem = $(item);
                var firstNameTextBox = elem.parent().parent().find(".firstName");
                var lastNameTextBox = elem.parent().parent().find(".section").find(".lastName");
                var gender = elem.parent().parent().find(".section > .gender");
                var phone = elem.parent().parent().find(".section > .txtPhone");
                var cellular = elem.parent().parent().find(".section > .txtCellular");
                var email = elem.parent().parent().find(".section > .email");
                var selectedReceiver = elem.parent().parent().find(".section > .selectedReceiver");

                elem.autocomplete("/UserControls/MAX/Booking/AutoComplete.aspx/GetLastNamesByPrefix", acOptionsForLastName).result(function(e, data) {
                    firstNameTextBox.val(data.FirstName);
                    lastNameTextBox.val(data.LastName);
                    gender.val(data.Gender);
                    phone.val(data.Phone);
                    cellular.val(data.Mobile);
                    email.val(data.Email);
                    selectedReceiver.val(data.UserID);
                });
            });
            autoCompleteLastNameAlreadyBound = true;
        }
    });
    
}




// -------------- jQuery (Ajax) functionality for selecting tickets and Vouchers ---------------- //
function SelectTicket(target) {
    
    // Disable fields
    $(".ticket").attr("disabled", true);
    $(".voucher").attr("disabled", true);
    $("[id$='_btnNext']").attr("disabled", true);
     
    var listOfPCSInfoArray = new Array();
    jQuery.each($("[id$='_ddlTicket']"), function(index, item) {

        // Ticket section
        var ticketSelectedValue = $(item).val();
        var ticketSelectedText = $(item).find("option:selected").text();

        // ReturnTicket section
        var returnTicketSection = $(item).parent().parent().parent().parent().parent().parent().parent().parent().find(".passenger-information");
        var returnTicketSelectedValue = $(returnTicketSection).find(".rticket").val();
        var returnTicketSelectedText = $(returnTicketSection).find(".rticket > option:selected").text();

        // Voucher section
        var voucherSection = $(item).parent().parent().find(".tdVoucher");
        var voucherSelectedText = voucherSection.find(".specialsection > .voucher :selected").text();
        var voucherSelectedValue = voucherSection.find(".specialsection > .voucher").val();

        // Manual voucher section
        var manualVoucherSection = $(item).parent().parent().parent().find(".tdManualVoucher");
        var manualVoucherText = manualVoucherSection.find(".section > .manualVoucher").val();

        // Return voucher section
        var returnVoucherSection = $(item).parent().parent().parent().parent().parent().parent().parent().parent().find(".passenger-information");
        var rvoucherSelectedText = returnVoucherSection.find(".rvoucher :selected").text();
        var rvoucherSelectedValue = returnVoucherSection.find(".rvoucher").val();
        var rmanualVoucherText = returnVoucherSection.find(".rmanualVoucher").val();

        
        // Rebooking section
        var rebookingSection = $(item).parent().parent().find(".rebookingFeeTd");
        var rebookingFee = rebookingSection.find(".section > .divRebookingFee >  .rebookingFee").val();

        // Special Needs section

        // Create object
        var passengerClientSideInformation = {
            'TicketSelectedValue': ticketSelectedValue,
            'TicketSelectedText': ticketSelectedText,
            'RticketSelectedValue': returnTicketSelectedValue,
            'RticketSelectedText': returnTicketSelectedText,
            'VoucherSelectedText': voucherSelectedText,
            'VoucherSelectedValue': voucherSelectedValue,
            'RVoucherSelectedText': rvoucherSelectedText,
            'RVoucherSelectedValue': rvoucherSelectedValue,
            'RebookingFee': rebookingFee,
            'ManualVoucher': manualVoucherText,
            'RManualVoucher': rmanualVoucherText
            
        };
        // Add object to array
        listOfPCSInfoArray.push(passengerClientSideInformation);
    });

    // Prepare list to send to server
    var listToSend = { listOfPCSInfo: listOfPCSInfoArray };

    $.ajax({
        type: "POST",
        url: "/UserControls/MAX/Booking/BookingService.asmx/SelectTicket",
        data: JSON.stringify(listToSend),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            // Enable fields
            $(".ticket").attr("disabled", false);


            jQuery.each($("[id$='_ddlTicket']"), function(index, item) {

                // populate the correct outbound ticket drop down with the correct data in the server respons
                var availableOutboundTickets = response.d.AvailableTicketsForPassenger[index].AvailableOutboundTickets;
                PopulateTicketDropDownList(availableOutboundTickets, item);


                // populate the correct inbound ticket drop down with the correct data in the server respons
                var availableInboundTickets = response.d.AvailableTicketsForPassenger[index].AvailableInboundTickets;
                if (availableInboundTickets.length > 0) {
                    PopulateReturnTicketDropDownList(availableInboundTickets, item);
                }

                SetNextButtonEnableState();
                
                try {
                    if ($(response.d.RedTicketInformation).length > 0) {
                        $("#RedTickedInformationTextDiv").html(response.d.RedTicketInformation);
                        $("#RedTicketInformationDiv").show();
                        $("#popupbackground").css({ "opacity": "0.7" }).show();
                        $("#btnClose").val(response.d.RedTicketButtonText);
                    }
                    if (response.d.IsRebooking === false) {

                        // populate the correct voucher drop down with the correct data in the server respons
                        var availableOutboundVouchers = response.d.AvailableVouchersForPassenger[index].AvailableOutboundVouchers;
                        PopulateVoucherDropDownList(availableOutboundVouchers, item, $(item).val())
                        var returnTicketSection = $(item).parent().parent().parent().parent().parent().parent().parent().parent().find(".passenger-information");
                        var returnTicketSelectedValue = $(returnTicketSection).find(".rticket").val();
                        var availableInboundVouchers = response.d.AvailableVouchersForPassenger[index].AvailableInboundVouchers;
                        PopulateReturnVoucherDropDownList(availableInboundVouchers, item, returnTicketSelectedValue)

                    }
                    else {
                        var availableOutboundVouchers = response.d.AvailableVouchersForPassenger[index].AvailableOutboundVouchers;
                        if (availableOutboundVouchers.length > 0) {
                            PopulateVoucherDropDownListReBooking(availableOutboundVouchers, item)
                        }
                        DisplayRebookingCost(item, response.d.UpgradeCost, response.d.RebookingFeeText,
                        response.d.RebookingFeeLabel, response.d.TotalRebookingCost)
                    }
                }
                catch (err) {
                }
            });
        },
        error: function(response) {
            alert('An error has occurred while fetching tickets, please contact the support!');
        }
    });



}
function DisplayRebookingCost(target, upgradeCost, rebookingFeeText, rebookingFeeLabelText, totalRebookingCost) {
    $(".rebookingCostHeader").show();
    var upgradeCostLabel = $(target).parent().parent().find(".section > .upgradecost");
    $(upgradeCostLabel).html(upgradeCost);
    if (rebookingFeeText !== null) {
        $(".rebookingFee").show();
        var rebookingSection = $(target).parent().parent().find(".rebookingFeeTd");
        var rebookingFeeTexbox = rebookingSection.find(".section > .divRebookingFee >  .rebookingFee");
        rebookingFeeTexbox.val(rebookingFeeText);
    }
    if (rebookingFeeLabelText !== null) {
        var rebookingSection = $(target).parent().parent().find(".rebookingFeeTd");
        var rebookingFeeLabel = rebookingSection.find(".section > .divRebookingFee >  .rebookingFeeLabel");
        $(rebookingFeeLabel).html(rebookingFeeLabelText); 
    }
   var totalRebookingCostLabel = $(target).parent().parent().parent().find(".section > .totalRebookingCost");
    $(totalRebookingCostLabel).html(totalRebookingCost);
}
function SelectReturnTicket(target) {

    // Disable fields
    $(".rticket").attr("disabled", true);
    $(".rvoucher").attr("disabled", true);
    $("[id$='_btnNext']").attr("disabled", true);
    
    var listOfPCSInfoArray = new Array();
    jQuery.each($("[id$='_ddlTicket']"), function(index, item) {

         // Ticket section
        var ticketSelectedValue = $(item).val();
        var ticketSelectedText = $(item).find("option:selected").text();

        //ReturnTicket section
        var returnTicketSection = $(item).parent().parent().parent().parent().parent().parent().parent().parent().find(".passenger-information");
        var returnTicketSelectedValue = $(returnTicketSection).find(".rticket").val();
        var returnTicketSelectedText = $(returnTicketSection).find(".rticket > option:selected").text();

        // Voucher section
        var voucherSection = $(item).parent().parent().find(".tdVoucher");
        var voucherSelectedText = voucherSection.find(".specialsection > .voucher :selected").text();
        var voucherSelectedValue = voucherSection.find(".specialsection > .voucher").val();

        // manual voucher section
        var manualVoucherSection = $(item).parent().parent().parent().find(".tdManualVoucher");
        var manualVoucherText = manualVoucherSection.find(".section > .manualVoucher").val();
        
        // Return voucher section
        var returnVoucherSection = $(item).parent().parent().parent().parent().parent().parent().parent().parent().find(".passenger-information");
        var rvoucherSelectedText = returnVoucherSection.find(".rvoucher :selected").text();
        var rvoucherSelectedValue = returnVoucherSection.find(".rvoucher").val();
        var rmanualVoucherText = returnVoucherSection.find(".rmanualVoucher").val();
        
        // Rebooking section
        var rebookingSection = $(item).parent().parent().find(".rebookingFeeTd");
        var rebookingFee = rebookingSection.find(".divRebookingFee > .section > .rebookingFee").val();

        // Create object
        var passengerClientSideInformation = {
            'TicketSelectedValue': ticketSelectedValue,
            'TicketSelectedText': ticketSelectedText,
            'RticketSelectedValue': returnTicketSelectedValue,
            'RticketSelectedText': returnTicketSelectedText,
            'VoucherSelectedText': voucherSelectedText,
            'VoucherSelectedValue': voucherSelectedValue,
            'RVoucherSelectedText': rvoucherSelectedText,
            'RVoucherSelectedValue': rvoucherSelectedValue,
            'RebookingFee': rebookingFee,
            'ManualVoucher': manualVoucherText,
            'RManualVoucher': rmanualVoucherText
        };

        // Add object to array
        listOfPCSInfoArray.push(passengerClientSideInformation);
    });

    // Prepare list to send to server
    var listToSend = { listOfPCSInfo: listOfPCSInfoArray };

    $.ajax({
        type: "POST",
        url: "/UserControls/MAX/Booking/BookingService.asmx/SelectReturnTicket",
        data: JSON.stringify(listToSend),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {

            // Enable fields
            $(".rticket").attr("disabled", false);

            jQuery.each($("[id$='_ddlTicket']"), function(index, item) {

            // populate the correct outbound ticket drop down with the correct data in the server respons
            var availableOutboundTickets = response.d.AvailableTicketsForPassenger[index].AvailableOutboundTickets;
            PopulateTicketDropDownList(availableOutboundTickets, item);

            // populate the correct inbound ticket drop down with the correct data in the server respons
            var availableInboundTickets = response.d.AvailableTicketsForPassenger[index].AvailableInboundTickets;
            if (availableInboundTickets.length > 0) {
                PopulateReturnTicketDropDownList(availableInboundTickets, item);
            }

            SetNextButtonEnableState();
            
                try {

                    if ($(response.d.RedTicketInformation).length > 0) {
                        $("#RedTickedInformationTextDiv").html(response.d.RedTicketInformation);
                        $("#RedTicketInformationDiv").show();
                        $("#popupbackground").css({ "opacity": "0.7" }).show();
                        $("#btnClose").val(response.d.RedTicketButtonText);
                    }

                    // populate the correct voucher drop down with the correct data in the server respons
                    var availableOutboundVouchers = response.d.AvailableVouchersForPassenger[index].AvailableOutboundVouchers;
                    PopulateVoucherDropDownList(availableOutboundVouchers, item, $(item).val())

                    var returnTicketSection = $(item).parent().parent().parent().parent().parent().parent().parent().parent().find(".passenger-information");
                    var returnTicketSelectedValue = $(returnTicketSection).find(".rticket").val();

                    var availableInboundVouchers = response.d.AvailableVouchersForPassenger[index].AvailableInboundVouchers;
                    PopulateReturnVoucherDropDownList(availableInboundVouchers, item, returnTicketSelectedValue)
                }
                catch (err) {
                }

            });


        },
        error: function(response) {
            alert('An error has occurred while fetching return tickets, please contact the support!');
        }
    });

}



function PopulateTicketDropDownList(availableOutboundTickets, item) {

   
        // Save selected ticket
        var selectedOutboundTicketValue = $(item).val();
        var selectedOutboundTicketText = $(item).find("option:selected").text();
        // Remove all other options in drop down except at index 0 (= - Välj -)
        $.each($(item).find("option"), function(optionIndex, option) {

            if (optionIndex !== 0) {
                $(option).remove();
            }
        });
        // Add selected ticket (if any) (except if selected is index 0 (= - Välj -)
        if (selectedOutboundTicketValue !== null && selectedOutboundTicketText !== null &&
                selectedOutboundTicketValue !== '00000000-0000-0000-0000-000000000000') {
            $(item).append(
                $('<option></option>').val(selectedOutboundTicketValue).html(selectedOutboundTicketText));
        }
        // Add the available outbound tickets returned from the server (avoid duplicates)
        $.each(availableOutboundTickets, function(index, availableOutboundTicket) {
            if (selectedOutboundTicketValue !== availableOutboundTicket.TicketID &&
                        selectedOutboundTicketText !== availableOutboundTicket.DisplayPrice) {
                $(item).append(
                            $('<option></option>').val(availableOutboundTicket.TicketID).html(availableOutboundTicket.DisplayPrice));
  
            }
        });
        // Set correct selected value after altering in dropdowns
        $(item).val(selectedOutboundTicketValue).attr("selected", "selected");
    
}

function PopulateReturnTicketDropDownList(availableInboundTickets, item) {

        // ReturnTicket section
        var returnTicketSection = $(item).parent().parent().parent().parent().parent().parent().parent().parent().find(".passenger-information");
        var returnTicketDropDown = $(returnTicketSection).find(".rticket");
        
        // Save selected ticket
        var selectedInboundTicketValue = returnTicketDropDown.val();
        var selectedInboundTicketText = returnTicketDropDown.find("option:selected").text();
        // Remove all other options in drop down except at index 0 (= - Välj -)
        $.each($(returnTicketDropDown).find("option"), function(optionIndex, option) {

            if (optionIndex !== 0) {
                $(option).remove();
            }
        });
        // Add selected ticket (if any) (except if selected is index 0 (= - Välj -)
        if (selectedInboundTicketValue !== null && selectedInboundTicketText !== null &&
                selectedInboundTicketValue !== '00000000-0000-0000-0000-000000000000') {
            $(returnTicketDropDown).append(
                $('<option></option>').val(selectedInboundTicketValue).html(selectedInboundTicketText));
        }
        // Add the available inbound tickets returned from the server (avoid duplicates)
        $.each(availableInboundTickets, function(index, availableInboundTicket) {
            if (selectedInboundTicketValue !== availableInboundTicket.TicketID &&
                        selectedInboundTicketText !== availableInboundTicket.DisplayPrice) {
                $(returnTicketDropDown).append(
                            $('<option></option>').val(availableInboundTicket.TicketID).html(availableInboundTicket.DisplayPrice));
                
            }
        });
        // Set correct selected value after altering in dropdowns
        $(returnTicketDropDown).val(selectedInboundTicketValue).attr("selected", "selected");

}

function PopulateVoucherDropDownList(availableOutboundVouchers, target, ticketValue) {
       // voucher section
        var voucherSection = $(target).parent().parent().parent().find(".tdVoucher");
        var voucherDropDown = voucherSection.find(".specialsection > .voucher");
        var selectedOutboundVoucherValue;
        var selectedOutboundVoucherText;
        // If the ticket value is the same as the value used when retreiving the list last time
        // the voucher selected (if not default -Välj- or -Choose-) should remain in the drop down 
       if (ticketValue == $(target).parent().find(".lastTicketSelectedValueUsedToFetchVouchers").val()) {
            // Save selected voucher
            selectedOutboundVoucherValue = $(voucherDropDown).val();
            selectedOutboundVoucherText = $(voucherDropDown).find("option:selected").text();
            // Remove all other options in drop down except at index 0 (= - Välj -)
            $.each($(voucherDropDown).find("option"), function(optionIndex, option) {
                if (optionIndex !== 0) {
                    $(option).remove();
                }
            });
            // Add selected voucher (if any) (except if selected is index 0 (= - Välj -)
            if (selectedOutboundVoucherValue !== null && selectedOutboundVoucherText !== null &&
                selectedOutboundVoucherValue !== '-1') {
                $(voucherDropDown).append(
                $('<option></option>').val(selectedOutboundVoucherValue).html(selectedOutboundVoucherText));
            }
        }
        else {// If this method is called with a NEW ticketvalue, remove all old items (except default välj/choose)
            $.each($(voucherDropDown).find("option"), function(optionIndex, option) {
                if (optionIndex !== 0) {
                    $(option).remove();
                }
            });
        }
            var count = 0;
            // Add the available outbound vouchers returned from the server (avoid duplicates)
            $.each(availableOutboundVouchers, function(index, availableOutboundVoucher) {

                if (selectedOutboundVoucherValue !== availableOutboundVoucher.VBCodeKey &&
             selectedOutboundVoucherText !== availableOutboundVoucher.VBCodeValue) {
                    $(voucherDropDown).append(
                    $('<option></option>').val(availableOutboundVoucher.VBCodeKey).html(availableOutboundVoucher.VBCodeValue));
                    count++;
                }
            });

            // Update the hidden field that keeps track on what ticketvalue we just fetched theese vouchers on
            $(target).parent().find(".lastTicketSelectedValueUsedToFetchVouchers").val(ticketValue);
            
            // If any items in voucher drop down...
            if ($(voucherDropDown).find("option").length > 1) {
                // enable voucher drop down list
                $(voucherDropDown).attr("disabled", false);
                // Set correct selected value after altering in dropdowns
                $(voucherDropDown).val(selectedOutboundVoucherValue);
                // If IE change width on drop down....
                SetCorrectWidth(voucherDropDown);
            }
    }

    function PopulateVoucherDropDownListReBooking(availableOutboundVouchers, target) {
       
        // voucher section
        var voucherSection = $(target).parent().parent().parent().find(".tdVoucher");
        var voucherDropDown = voucherSection.find(".specialsection > .voucher");
        var voucherHeader = voucherSection.find(".specialsection > .voucherheader");           
            // Remove all other options in drop down 
        $(voucherDropDown).find("option").remove();
        // Add the available outbound vouchers returned from the server
        $.each(availableOutboundVouchers, function(index, availableOutboundVoucher) {
            
            $(voucherDropDown).append(
                    $('<option></option>').val(availableOutboundVoucher.VBCodeKey).html(availableOutboundVoucher.VBCodeValue));

        });

        $(voucherDropDown).show();
        $(voucherHeader).show();
            // If IE change width on drop down....
            SetCorrectWidth(voucherDropDown);
        
    }
    function PopulateReturnVoucherDropDownList(availableInboundVouchers, target, returnTicketValue) {

        // Return voucher section
        var returnVoucherSection = $(target).parent().parent().parent().parent().parent().parent().parent().parent().parent().find(".passenger-information");
        var rvoucherDropDown = returnVoucherSection.find(".rvoucher");
        
        var selectedInboundVoucherValue;
        var selectedInboundVoucherText;
        // If the ticket value is the same as the value used when retreiving the list last time
        // the voucher selected (if not default -Välj- or -Choose-) should remain in the drop down 

        if (returnTicketValue == $(rvoucherDropDown).parent().parent().parent().find(".lastReturnTicketSelectedValueUsedToFetchVouchers").val()) {
            // Save selected voucher
            selectedInboundVoucherValue = $(rvoucherDropDown).val();
            selectedInboundVoucherText = $(rvoucherDropDown).find("option:selected").text();
            // Remove all other options in drop down except at index 0 (= - Välj -)
            $.each($(rvoucherDropDown).find("option"), function(optionIndex, option) {
                if (optionIndex !== 0) {
                    $(option).remove();
                }
            });
            // Add selected voucher (if any) (except if selected is index 0 (= - Välj -)
            if (selectedInboundVoucherValue !== null && selectedInboundVoucherText !== null &&
                selectedInboundVoucherValue !== '-1') {
                $(rvoucherDropDown).append(
                $('<option></option>').val(selectedInboundVoucherValue).html(selectedInboundVoucherText));
            }
        }
        else {// If this method is called with a NEW ticketvalue, remove all old items (except default välj/choose)
            $.each($(rvoucherDropDown).find("option"), function(optionIndex, option) {
                if (optionIndex !== 0) {
                    $(option).remove();
                }
            });
        }
        // Add the available inbound vouchers returned from the server (avoid duplicates)
        $.each(availableInboundVouchers, function(index, availableInboundVoucher) {

            if (selectedInboundVoucherValue !== availableInboundVoucher.VBCodeKey &&
             selectedInboundVoucherText !== availableInboundVoucher.VBCodeValue) {
                $(rvoucherDropDown).append(
                    $('<option></option>').val(availableInboundVoucher.VBCodeKey).html(availableInboundVoucher.VBCodeValue));
            }
        });

        // Update the hidden field that keeps track on what ticketvalue we just fetched theese vouchers on
        $(rvoucherDropDown).parent().parent().parent().find(".lastReturnTicketSelectedValueUsedToFetchVouchers").val(returnTicketValue);
        // If any items in voucher drop down...
        if ($(rvoucherDropDown).find("option").length > 1) {
            // enable voucher drop down list
            $(rvoucherDropDown).attr("disabled", false);
            // Set correct selected value after altering in dropdowns
            $(rvoucherDropDown).val(selectedInboundVoucherValue);
            // If IE change width on drop down....
            SetCorrectWidth(rvoucherDropDown);
        }
    }
    
function RePopulateVoucherDropDownList(availableOutboundVouchers, target) {
        var voucherDropDown = $(target);
        // Save selected ticket
        var selectedOutboundVoucherValue = $(voucherDropDown).val();

        
        // ----------Cut off "(number)" from Display Text--------------//
        var selectedOutboundVoucherText;
        var cutIndex;
        var splitCharCount = -1;
        var voucherTextArray = $(voucherDropDown).find("option:selected").text().split("");
        for (var i = 0; i < voucherTextArray.length; i++) {
            if (voucherTextArray[i] == "(") {
                cutIndex = i;
                splitCharCount++;
            }
        }
        if (splitCharCount > 0) { // if more than one "("
            selectedOutboundVoucherText = $(voucherDropDown).find("option:selected").text().substring(0, cutIndex);
        }
        else {
            if (splitCharCount == 0) { // if only one "("
                if (IsNumeric($(voucherDropDown).find("option:selected").text().substring(cutIndex+1, voucherTextArray.length-1))) {
                    // remove "( )" if it contains only numbers (is numeric..)
                    selectedOutboundVoucherText = $(voucherDropDown).find("option:selected").text().split("(")[0];
                }
                else {
                    // Leave "(  )" if it not only contains numbers (is numeric) (can display other info)
                    selectedOutboundVoucherText = $(voucherDropDown).find("option:selected").text();
                }
            }
            else {
                // Display as is if default value (-Välj- or Choose...etc)
                selectedOutboundVoucherText = $(voucherDropDown).find("option:selected").text();
            }
        }
        // ---------- / Cut off "(number)" from Display Text--------------//
        // Remove all other options in drop down except at index 0 (= - Välj -)
        $.each($(voucherDropDown).find("option"), function(optionIndex, option) {
            if (optionIndex !== 0) {
                $(option).remove();
            }
        });
        // Add selected ticket (if any) (except if selected is index 0 (= - Välj -)
       if (selectedOutboundVoucherValue !== null && selectedOutboundVoucherText !== null &&
                selectedOutboundVoucherValue !== '-1') {
            $(voucherDropDown).append(
                $('<option></option>').val(selectedOutboundVoucherValue).html(selectedOutboundVoucherText));
        }
        // Add the available outbound vouchers returned from the server (avoid duplicates)
        $.each(availableOutboundVouchers, function(index, availableOutboundVoucher) {
            if (selectedOutboundVoucherValue !== availableOutboundVoucher.VBCodeKey &&
            selectedOutboundVoucherText !== availableOutboundVoucher.VBCodeValue) {
                $(voucherDropDown).append(
                    $('<option></option>').val(availableOutboundVoucher.VBCodeKey).html(availableOutboundVoucher.VBCodeValue));
            }
        });
        // If any items in voucher drop down...
        if ($(voucherDropDown).find("option").length > 1) {
            // enable voucher drop down list
            $(voucherDropDown).attr("disabled", false);
            // Set correct selected value after altering in dropdowns
            $(voucherDropDown).val(selectedOutboundVoucherValue);
            // If IE change width on drop down....
            SetCorrectWidth(voucherDropDown);
        }
    }

function RePopulateReturnVoucherDropDownList(availableInboundVouchers, target) {
      
        // Return voucher section
        var returnVoucherSection = $(target).parent().parent().parent().parent().parent().parent().parent().parent().find(".passenger-information");
        var rvoucherDropDown = returnVoucherSection.find(".rvoucher");
        
        // Save selected ticket
        var selectedInboundVoucherValue = $(rvoucherDropDown).val();
        // ----------Cut off "(number)" from Display Text--------------//
        var selectedInboundVoucherText;
        var cutIndex;
        var splitCharCount = -1;
        var rvoucherTextArray = $(rvoucherDropDown).find("option:selected").text().split("");
        for (var i = 0; i < rvoucherTextArray.length; i++) {
            if (rvoucherTextArray[i] == "(") {
                cutIndex = i;
                splitCharCount++;
            }
        }
        if (splitCharCount > 0) { // if more than one "("
            selectedInboundVoucherText = $(rvoucherDropDown).find("option:selected").text().substring(0, cutIndex);
        }
        else {
            if (splitCharCount == 0) { // if onlye one "("
                if (IsNumeric($(rvoucherDropDown).find("option:selected").text().substring(cutIndex+1, rvoucherTextArray.length-1))) {
                    // remove "( )" if it contains only numbers (is numeric..)
                    selectedInboundVoucherText = $(rvoucherDropDown).find("option:selected").text().split("(")[0];
                }
                else {
                    // Leave "(  )" if it not only contains numbers (is numeric) (can display other info)
                    selectedInboundVoucherText = $(rvoucherDropDown).find("option:selected").text();
                }
            }
            else {
                // Display as is if default value (-Välj- or Choose...etc)
                selectedInboundVoucherText = $(rvoucherDropDown).find("option:selected").text();
            }
        }
        // ---------- / Cut off "(number)" from Display Text--------------//
        // Remove all other options in drop down except at index 0 (= - Välj -)
        $.each($(rvoucherDropDown).find("option"), function(optionIndex, option) {
            if (optionIndex !== 0) {
                $(option).remove();
            }
        });
        // Add selected ticket (if any) (except if selected is index 0 (= - Välj -)
       if (selectedInboundVoucherValue !== null && selectedInboundVoucherText !== null &&
                selectedInboundVoucherValue !== '-1') {
            $(rvoucherDropDown).append(
                $('<option></option>').val(selectedInboundVoucherValue).html(selectedInboundVoucherText));
        }
        // Add the available inbound vouchers returned from the server (avoid duplicates)
        $.each(availableInboundVouchers, function(index, availableInboundVoucher) {
            if (selectedInboundVoucherValue !== availableInboundVoucher.VBCodeKey &&
            selectedInboundVoucherText !== availableInboundVoucher.VBCodeValue) {
                $(rvoucherDropDown).append(
                    $('<option></option>').val(availableInboundVoucher.VBCodeKey).html(availableInboundVoucher.VBCodeValue));
            }
        });
        // If any items in voucher drop down...
        if ($(rvoucherDropDown).find("option").length > 1) {
            // enable voucher drop down list
            $(rvoucherDropDown).attr("disabled", false);
            // Set correct selected value after altering in dropdowns
            $(rvoucherDropDown).val(selectedInboundVoucherValue);
            // If IE change width on drop down....
            SetCorrectWidth(rvoucherDropDown);
        }
    }

function VoucherSelected(target) {

    // Disable fields
    $(".ticket").attr("disabled", true);
    $(".voucher").attr("disabled", true);
    $(".rvoucher").attr("disabled", true);
    $("[id$='_btnNext']").attr("disabled", true);
    
    var listOfPCSInfoArray = new Array();
    jQuery.each($("[id$='_ddlTicket']"), function(index, item) {

        // Ticket section
        var ticketSelectedValue = $(item).val();
        var ticketSelectedText = $(item).find("option:selected").text();

        //ReturnTicket section
        var returnTicketSection = $(item).parent().parent().parent().parent().parent().parent().parent().parent().find(".passenger-information");
        var returnTicketSelectedValue = $(returnTicketSection).find(".rticket").val();
        var returnTicketSelectedText = $(returnTicketSection).find(".rticket > option:selected").text();
        
        // voucher section
        var voucherSection = $(item).parent().parent().find(".tdVoucher");
        var voucherSelectedText = voucherSection.find(".specialsection > .voucher :selected").text();
        var voucherSelectedValue = voucherSection.find(".specialsection > .voucher").val();

        // Return voucher section
        var returnVoucherSection = $(item).parent().parent().parent().parent().parent().parent().parent().parent().parent().find(".passenger-information");
        var rvoucherSelectedText = returnVoucherSection.find(".rvoucher :selected").text();
        var rvoucherSelectedValue = returnVoucherSection.find(".rvoucher").val();

        var passengerClientSideInformation = {
            'TicketSelectedValue': ticketSelectedValue,
            'TicketSelectedText': ticketSelectedText,
            'RticketSelectedValue': returnTicketSelectedValue,
            'RticketSelectedText': returnTicketSelectedText,
            'VoucherSelectedText': voucherSelectedText,
            'VoucherSelectedValue': voucherSelectedValue,
            'RVoucherSelectedText': rvoucherSelectedText,
            'RVoucherSelectedValue': rvoucherSelectedValue
        };
        listOfPCSInfoArray.push(passengerClientSideInformation);
    });
    var listToSend = { listOfPCSInfo: listOfPCSInfoArray };

    
    
    $.ajax({
        type: "POST",
        url: "/UserControls/MAX/Booking/BookingService.asmx/SelectVoucher",
        data: JSON.stringify(listToSend),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {

            // Enable fields
            $(".ticket").attr("disabled", false);
            SetNextButtonEnableState();
            
            jQuery.each($("[id$='_ddlTicket']"), function(index, item) {
                try {
                    var voucher = $(item).parent().parent().parent().parent().parent().parent().parent().parent().parent().find(".passenger-information");
                    var voucherDropDown = $(voucher).find(".voucher");
                    var availableOutboundVouchers = response.d.AvailableVouchersForPassenger[index].AvailableOutboundVouchers;
                    RePopulateVoucherDropDownList(availableOutboundVouchers, voucherDropDown)
                }
                catch (err) {
                }
                try {
                    var returnVoucher = $(item).parent().parent().parent().parent().parent().parent().parent().parent().find(".passenger-information");
                    var rvoucherDropDown = returnVoucher.find(".rvoucher");
                    var availableInboundVouchers = response.d.AvailableVouchersForPassenger[index].AvailableInboundVouchers;
                    RePopulateReturnVoucherDropDownList(availableInboundVouchers, rvoucherDropDown)
                }
                catch (err) {
                }
            });
        },
        error: function(response) {
            alert('An error has occurred while fetching vouchers, please contact the support!');
        }
    });
}

function UpdateRebookingFee(target) {

    if (IsNumericWithDecimals($(target).val())) {
        // Disable fields
        $("[id$='_btnNext']").attr("disabled", true);
        $.ajax({
            type: "POST",
            url: "/UserControls/MAX/Booking/BookingService.asmx/SetRebookingFee",
            data: "{'reBookingFee' : '" + $(target).val() + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(response) {
                // Enable fields
                SetNextButtonEnableState();
                
                // Update cost information
                jQuery.each($("[id$='_ddlTicket']"), function(index, item) {
                    DisplayRebookingCost(item, response.d.UpgradeCost, response.d.RebookingFeeText,
                        response.d.RebookingFeeLabel, response.d.TotalRebookingCost)
                });
            },
            error: function(response) {
                alert('An error has occurred while setting rebooking fee, please contact your system administrator');
            }
        });
    }
}

function UpdateManualVoucher() {

    //For now just resend SelectTicket
    SelectTicket($("[id$='_ddlTicket']")[0]);
}

//  check for valid numeric strings	
function IsNumeric(strString) {
    var strValidChars = "0123456789";
    var strChar;
    var blnResult = true;
    if (strString.length == 0) return false;
    //  test strString consists of valid characters listed above
    for (i = 0; i < strString.length && blnResult == true; i++) {
        strChar = strString.charAt(i);
        if (strValidChars.indexOf(strChar) == -1) {
            blnResult = false;
        }
    }
    return blnResult;
}
//  check for valid double strings	
function IsNumericWithDecimals(strString) {
    var strValidChars = ",0123456789";
    var strChar;
    var blnResult = true;
    if (strString.length == 0) return false;
    //  test strString consists of valid characters listed above
    for (i = 0; i < strString.length && blnResult == true; i++) {
        strChar = strString.charAt(i);
        if (strValidChars.indexOf(strChar) == -1) {
            blnResult = false;
        }
    }
    return blnResult;
}
// Adjust width if IE (used for voucher drop downs)
function SetCorrectWidth(target) {
    if ($.browser.msie) {
        $(target).css("width", "auto");
        // adjust div wrapping element
        $(target).parent().css("width", "auto");
    }
}

function CloseRedTicketInfo() {
    $("#RedTicketInformationDiv").hide();
    $("#popupbackground").hide();
}

function SetNextButtonEnableState() {
    var disabledState = false;
    jQuery.each($("[id$='_ddlTicket']"), function(index, item) {
        var ticketSelectedValue = $(item).val();
        var returnTicketSection = $(item).parent().parent().parent().parent().parent().parent().parent().parent().find(".passenger-information");
        var returnTicketSelectedValue = $(returnTicketSection).find(".rticket").val();
        if (ticketSelectedValue == '00000000-0000-0000-0000-000000000000' ||
        returnTicketSelectedValue == '00000000-0000-0000-0000-000000000000') {
            disabledState = true;
        }
    });
    $("[id$='_btnNext']").attr("disabled", disabledState);
}

// -------------- /jQuery (Ajax) functionality for selecting tickets and Vouchers ---------------- //


// ------------------------ javascript functionality for GeneralSearchControl.ascx ---------------- //
function rbRoundTripSelected() {
    $("[id$='_lDeparture2']").show();
    $("[id$='_txtHomeBoundDay']").show();
    $("[id$='_ibHomeBoundDayCalendar']").show();
    if ($("[id$='_txtHomeBoundDay']").val().length == 0) {
        $("[id$='_txtHomeBoundDay']").val($("[id$='_txtOutBoundDay']").val());
    }
}
function rbOneWayTripSelected() {
    $("[id$='_lDeparture2']").hide();
    $("[id$='_txtHomeBoundDay']").hide();
    $("[id$='_ibHomeBoundDayCalendar']").hide();
}
function txtOutBoundDayChanged() {
    //handle when 1 box is empty (then copy in the other date)
    if (CopyValueIfEmpty($("[id$='_txtHomeBoundDay']"), $("[id$='_txtOutBoundDay']"))) {
        return;
    }
    
    var outBoundDay = ConvertTextToDate($("[id$='_txtOutBoundDay']").val());
    var homeBoundDay = ConvertTextToDate($("[id$='_txtHomeBoundDay']").val());
    
    //Exit if no real dates
    if (outBoundDay == null || outBoundDay == NaN ||
        homeBoundDay == null || homeBoundDay == NaN) {
        return;
    }
    
    //Inbound date must be the same day or later than outbound date
    if (homeBoundDay < outBoundDay) {
        $("[id$='_txtHomeBoundDay']").val($("[id$='_txtOutBoundDay']").val());
        $find("homeBoundCal")._selectedDate = outBoundDay;
    }
}
function txtHomeBoundDayChanged() {
    //handle when 1 box is empty (then copy in the other date)
    if (CopyValueIfEmpty($("[id$='_txtOutBoundDay']"), $("[id$='_txtHomeBoundDay']"))) {
        return;
    }

    var outBoundDay = ConvertTextToDate($("[id$='_txtOutBoundDay']").val());
    var homeBoundDay = ConvertTextToDate($("[id$='_txtHomeBoundDay']").val());

    //Exit if no real dates
    if (outBoundDay == null || outBoundDay == NaN ||
        homeBoundDay == null || homeBoundDay == NaN) {
        return;
    }

    //Outbound date must be the same day or earlier than inbound date
    if (outBoundDay > homeBoundDay) {
        $("[id$='_txtOutBoundDay']").val($("[id$='_txtHomeBoundDay']").val());
        $find("outBoundCal")._selectedDate = homeBoundDay;
    }
}
function CopyValueIfEmpty(copyToIfEmpty, copyFrom) {
    if (copyToIfEmpty.val() == "") {
        copyToIfEmpty.val(copyFrom.val());
        return true;
    }
    return false;
}
function ConvertTextToDate(text) {

    var year = null;
    var month = null;
    var day = null;

    //If text contains '-' then Swedish format (yyyy-MM-dd)
    if (text.indexOf("-") != -1) {
        var parts = text.split("-");
        year = parts[0];
        month = parts[1];
        day = parts[2];
    }
    //If text contains '/' then US English format (M/d/yyyy)
    else if (text.indexOf("/") != -1) {
        var parts = text.split("/");
        year = parts[2];
        month = parts[0];
        day = parts[1];
    }

    if (year == null || year == NaN || !IsNumeric(year) ||
        month == null || month == NaN || !IsNumeric(month) ||
        day == null || day == NaN || !IsNumeric(day)) {
        return null;
    }

    //month is 0-11
    return new Date(year, month - 1, day);
}
// ----------------------- /javascript functionality for GeneralSearchControl.ascx ---------------- //



// -----------------------  ajax functionality for Move Pax In Batch ------------------------------//
function MovePaxInBatch() {

   $('.btnMovePaxInBatch').attr("disabled", true);
    var index = 0;
    if ($(".movedPaxInBatchCurrentIndex").val() !== "")
    {
        index = $(".movedPaxInBatchCurrentIndex").val();
        }
    else {
        $('#movePaxInBatchStatus').html("starting to move pax....");
            ShowStatusPopup();
    }
    $.ajax({
        type: "POST",
        url: "/UserControls/MAX/Booking/BookingService.asmx/MovePaxInBatch",
        data: "{'index' : '" + index + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {

            if (response.d.TotalNumberOfPassengers > 0) { 
                $(".movedPaxInBatchCurrentIndex").val(response.d.Index);
                if (index >= response.d.TotalNumberOfPassengers) {
                    $(".button-next").attr("disabled", false);
                    $("[id$='_btnNextTab']").click();
                    HideStatusPopup();
                }
                else {
                    $('#movePaxInBatchStatus').html(response.d.Status);
                    ShowStatusPopup();    
                    if (response.d.BatchMovedSuccessfully)
                        MovePaxInBatch(); 
                    else
                        $("#btnCloseMovePaxInBatchPopup").attr("disabled", false);
                }
            }
        },
        error: function(response) {
            $('#movePaxInBatchStatus').html('An error has occurred while attempting to move pax in batch, please contact your system administrator');
            $("#btnCloseMovePaxInBatchPopup").attr("disabled", false);
        }
    });

}
function ShowStatusPopup() {
    $('#movePaxInBatchStatusWrapper').show();
    $('#movePaxWarning').show();
    
    if ($('#movePaxInBatchStatusWrapper').height() > 550)
        $('#movePaxInBatchStatusWrapper').css({ "overflow": "scroll" }).height(550)
    
    $("#popupbackground").css({ "opacity": "0.7" }).show();
}
function HideStatusPopup() {
    $('#movePaxInBatchStatusWrapper').hide();
    $('#movePaxWarning').hide();
    $("#popupbackground").css({ "opacity": "0.7" }).hide();
}
function CloseMovePaxBatchStatus() {
    $('#movePaxInBatchStatusWrapper').hide();
    $("#popupbackground").hide();
    $("[id$='_btnPreviousTab']").click();
}
// ---------------------- / ajax functionality for Move Pax In Batch ------------------------------//




// notify that the script has been loaded
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

/*
http://www.JSON.org/json2.js
2010-08-25

Public Domain.

NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

See http://www.JSON.org/js.html


This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html

USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.


This file creates a global JSON object containing two methods: stringify
and parse.

JSON.stringify(value, replacer, space)
value       any JavaScript value, usually an object or array.

replacer    an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.

space       an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or '&nbsp;'),
it contains the characters used to indent at each level.

This method produces a JSON text from a JavaScript value.

When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value

For example, this would serialize Dates as ISO strings.

Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}

return this.getUTCFullYear()   + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate())      + 'T' +
f(this.getUTCHours())     + ':' +
f(this.getUTCMinutes())   + ':' +
f(this.getUTCSeconds())   + 'Z';
};

You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.

If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.

Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.

The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.

If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.

Example:

text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'


text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'


JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.

The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.

Example:

// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.

myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});

myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});


This is a reference implementation. You are free to copy, modify, or
redistribute.
*/

/*jslint evil: true, strict: false */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/


// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (!this.JSON) {
    this.JSON = {};
}

(function() {

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function(key) {

            return isFinite(this.valueOf()) ?
                   this.getUTCFullYear() + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate()) + 'T' +
                 f(this.getUTCHours()) + ':' +
                 f(this.getUTCMinutes()) + ':' +
                 f(this.getUTCSeconds()) + 'Z' : null;
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function(key) {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

        // If the string contains no control characters, no quote characters, and no
        // backslash characters, then we can safely slap some quotes around it.
        // Otherwise we must also replace the offending characters with safe escape
        // sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function(a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder) {

        // Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

        // If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

        // If we were called with a replacer function, then call the replacer to
        // obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

        // What happens next depends on the value's type.

        switch (typeof value) {
            case 'string':
                return quote(value);

            case 'number':

                // JSON numbers must be finite. Encode non-finite numbers as null.

                return isFinite(value) ? String(value) : 'null';

            case 'boolean':
            case 'null':

                // If the value is a boolean or null, convert it to a string. Note:
                // typeof null does not produce 'null'. The case is included here in
                // the remote chance that this gets fixed someday.

                return String(value);

                // If the type is 'object', we might be dealing with an object or an array or
                // null.

            case 'object':

                // Due to a specification blunder in ECMAScript, typeof null is 'object',
                // so watch out for that case.

                if (!value) {
                    return 'null';
                }

                // Make an array to hold the partial results of stringifying this object value.

                gap += indent;
                partial = [];

                // Is the value an array?

                if (Object.prototype.toString.apply(value) === '[object Array]') {

                    // The value is an array. Stringify every element. Use null as a placeholder
                    // for non-JSON values.

                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || 'null';
                    }

                    // Join all of the elements together, separated with commas, and wrap them in
                    // brackets.

                    v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }

                // If the replacer is an array, use it to select the members to be stringified.

                if (rep && typeof rep === 'object') {
                    length = rep.length;
                    for (i = 0; i < length; i += 1) {
                        k = rep[i];
                        if (typeof k === 'string') {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                } else {

                    // Otherwise, iterate through all of the keys in the object.

                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                }

                // Join all of the member texts together, separated with commas,
                // and wrap them in braces.

                v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
                gap = mind;
                return v;
        }
    }

    // If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function(value, replacer, space) {

            // The stringify method takes a value and an optional replacer, and an optional
            // space parameter, and returns a JSON text. The replacer can be a function
            // that can replace values, or an array of strings that will select the keys.
            // A default replacer method can be provided. Use of the space parameter can
            // produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

            // If the space parameter is a number, make an indent string containing that
            // many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

                // If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

            // If there is a replacer, it must be a function or an array.
            // Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

            // Make a fake root object containing our value under the key of ''.
            // Return the result of stringifying the value.

            return str('', { '': value });
        };
    }


    // If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function(text, reviver) {

            // The parse method takes a text and an optional reviver function, and returns
            // a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

                // The walk method is used to recursively walk the resulting structure so
                // that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


            // Parsing happens in four stages. In the first stage, we replace certain
            // Unicode characters with escape sequences. JavaScript handles many characters
            // incorrectly, either silently deleting them, or treating them as line endings.

            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function(a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

            // In the second stage, we run the text against regular expressions that look
            // for non-JSON patterns. We are especially concerned with '()' and 'new'
            // because they can cause invocation, and '=' because it can cause mutation.
            // But just to be safe, we want to reject all unexpected forms.

            // We split the second stage into 4 regexp operations in order to work around
            // crippling inefficiencies in IE's and Safari's regexp engines. First we
            // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
            // replace all simple value tokens with ']' characters. Third, we delete all
            // open brackets that follow a colon or comma or that begin the text. Finally,
            // we look to see that the remaining characters are only whitespace or ']' or
            // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

                // In the third stage we use the eval function to compile the text into a
                // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
                // in JavaScript: it can begin a block or an object literal. We wrap the text
                // in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

                // In the optional fourth stage, we recursively walk the new structure, passing
                // each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function' ?
                    walk({ '': j }, '') : j;
            }

            // If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
} ());


function AdjustQuickSearchBoxForInternetExplorer() {
    if ($.browser.msie) {
        $('.articleList').css('width', 'auto');
        $('.first').css('width', 'auto');
        $('.header').css('width', 'auto');
        $('.second').css({ 'float': 'right' });
       var qsWidth = $('.articleList').width() + $('.voucherAmount').width() + 50; //50px for css padding
        $('#QuickSearchBox').width(qsWidth);
    }
}

function CheckAllCheckboxes(sender) {
    ToggleSelectAllCheckbox(sender);

    jQuery.each($(sender).parent().parent().parent().find("[id$='_chkChecked']"), function(index, item) {
        CheckOrUnCheckCheckbox(sender,item);        
    })

}

function CheckAllVoucherCheckboxes(sender) {
    ToggleSelectAllCheckbox(sender);
    
    jQuery.each($(sender).parent().parent().find("[id$='_chbChangeVBOwner']"), function(index, item) {
        CheckOrUnCheckCheckbox(sender, item);
    })
}

function CheckAllMembers(sender) {
    $(sender).parents('fieldset:eq(0)').find(':checkbox').attr('checked', sender.checked);
}


function ToggleSelectAllCheckbox(sender) {
    if ($(sender).is(':checked')) {
        $(sender).next().text('Deselect all');
    } else {
        $(sender).next().text('Select all');
    }
}


function CheckOrUnCheckCheckbox(sender,item){
    if (!$(sender).is(':checked')) {
        $(item).attr('checked', false);
    }
    if ($(sender).is(':checked')) {
        $(item).attr('checked', true);
    }
}


function ToggleSpecialNeed(sender) {
    if (!$(sender).is(':checked')) {
        $('.specialNeedTextBox').val('');
        $('.specialNeedTextBox').attr('disabled', 'disabled');
    } else {
        $('.specialNeedTextBox').removeAttr('disabled');
    }
}
