﻿var tnExpressWeb = tnExpressWeb || {};

tnExpressWeb.IsQASite = function () {
    return document.location.href.indexOf('_QA_') >= 0 || document.location.href.indexOf('_qa_') >= 0;
};

var buyNowText = "buy now";
var moreInfoText = "more information";
var soldOutText = "sold out";
var notOnSaleText = "tickets not on sale";
var setCalText = function (b, m, s, n) {
    buyNowText = (b.toString().length > 0) ? b : buyNowText;
    moreInfoText = (m.toString().length > 0) ? m : moreInfoText;
    soldOutText = (s.toString().length > 0) ? s : soldOutText;
    notOnSaleText = (n.toString().length > 0) ? n : notOnSaleText;
};

// 9.20.12 - V4 Additions 
// call API proxy via _util/AjaxData - relay to JS template

// hide order history divs
var initOrderDetails = function () {
    (function ($) {
        $('#order_details').dialog({ autoOpen: false });
        $('#order_details').dialog('option', 'buttons', { 'close': function () { $(this).dialog('close'); } });
        $('#order_details').dialog('option', 'height', 'auto');
    })(tnew.jQuery);
};

var getOrderDetails = function (url, orderNo, culture) {
    (function ($) {
        var fullUrl = url + "_util/AjaxData.aspx?methName=getorderdetails&orderNo=" + orderNo; // + "&culture=" + culture; //old version - TNEXWEB-1383
        //var dest = document.getElementById(destField);
        //var jqStateReq = $("#stateReq");
        //var msg = "";
        $.ajax({
            type: "GET",
            url: fullUrl,
            contentType: "html",
            success: function (txt) {
                //alert(txt);
                var $div = $("#order_details");

                $div.attr("title", "Order " + orderNo);
                $div.html(txt);

                $div.dialog({ open: function () { $(this).parent().children().first().children('button').hide(); } });
                $div.dialog('option', 'title', 'Order Details');
                $div.dialog('option', 'width', '800');
                $div.dialog('open');
            },
            error: function () {
                // alert("Your order data could not be retrieved.");
                $("#order_details").html("Your order data could not be retrieved.");
            }
        });
    })(tnew.jQuery);
};


// plugin to prevent double form submits
/*jQuery.fn.preventDoubleSubmit = function () {
jQuery(this).submit(function () {
if (this.beenSubmitted) {
return false;
} else
this.beenSubmitted = true;
});
};*/

// hide more info divs
var initMoreInfo = function (data) {
    (function ($) {
        $('.dialog').dialog({ autoOpen: false });
        $('.dialog').dialog('option', 'buttons', { 'close': function () { $(this).dialog('close'); } });
        $('.dialog').dialog('option', 'height', 'auto');
    })(tnew.jQuery);
};

// display performances per date
var viewPerfs = function (data) {

    (function ($) {

        var perfs = data.split("|");
        var links = "";
        // added 6.9.2010 - improve appearance when no perfs are listed:
        if (perfs.length > 1) {
            for (x = 0; x < perfs.length - 1; x++) {
                var perf = perfs[x].split(";")
                var perfT = perf[0];
                var perfTime = perf[1];
                var imgPath = perf[6];
                var info = "<a href=\"" + perf[5] + "?p=" + perf[2] + "\" class=\"moreInfo\">" + moreInfoText + "</a>";
                var avail = perf[3];
                if (avail == "Y") {
                    buyNow = "<a href=\"" + perf[4] + "?p=" + perf[2] + "\" class=\"purchaseSmall\">" + buyNowText + "</a>";
                } else if (avail == "N") {
                    buyNow = soldOutText;
                } else if (avail == "E") {
                    buyNow = "";
                } else if (avail == "U") {
                    buyNow = notOnSaleText;
                }
                if (info.length > 0 && buyNow.length > 0) {
                    buyNow = "&nbsp;&middot;&nbsp;" + buyNow;
                }
                var image = (imgPath.length > 0) ? "<img src=\"" + imgPath + "\" width=\"50\" style=\"padding-right: 4px;\" align=\"left\">" : "";
                //links += "<p><b>" + perfT + "</b><BR>" + perfTime + "<BR>" + info + buyNow + "</p>";
                links += "<p>" + image + "<b>" + perfT + "</b><BR>" + perfTime + "<BR>" + info + buyNow + "</p>";
            }
            $("display_perfs").show();
            $("#display_perfs").html("<BR>" + links);
            //$("#calendarContainer").height($("#boxContainer").height());
            // 4.6.2010 - making common (was in Custom_TNEW.js)
            if ($("#display_perfs").outerHeight() > $("#calendarContainer").height()) {
                $("#calendarContainer").height($("#display_perfs").outerHeight());
            }
            bumpHeight();
        } else {
            $("display_perfs").hide();
        }

    })(tnew.jQuery);

};

// toggle calendar link
var toggleCalLink = function (t, l) {
    (function ($) {
        $("#toggleCalendar").attr("href", "javascript:toggleCal('" + t + "');void(0);");
        $("#toggleCalendar").text("View as " + l);
    })(tnew.jQuery);
};

// toggle calendar
var toggleCal = function (v) {
    (function ($) {
        if (v == "text") {
            $("#boxContainer").hide();
            $("#textContainer").show();
            toggleCalLink("box", "Calendar");
            $("#view").val("text");
            // set height 
            //$("#calendarContainer").height($("#textContainer").height());
        } else if (v == "box" || v == "") {
            $("#boxContainer").show();
            $("#textContainer").hide();
            toggleCalLink("text", "List");
            $("#view").val("box");
            // set height 
            //$("#calendarContainer").height($("#boxContainer").height());
        }
        // bumpHeight(); // added 4.6.2010
    })(tnew.jQuery);
};

function bumpHeight() {
    (function ($) {
        //alert("calendar height: " + $("#calendarContainer").outerHeight() + " vs. box height: " + $("#boxContainer").outerHeight());
        $("#calendarContainer").outerHeight(
                $("#boxContainer").outerHeight()
             );
    })(tnew.jQuery);
}

// toggle account info tabs
// toggle calendar link
var toggleAcctTab = function (a, validSummID) {
    var tab = a.parentNode.id;
    var tabCont = a.parentNode.parentNode;
    for (x = 0; x < tabCont.childNodes.length; x++) {
        if (tabCont.childNodes[x].id == tab) {
            activateTab(tabCont.childNodes[x]);
        } else {
            deactivateTab(tabCont.childNodes[x]);
        }
    }
};

var activateTab = function (t) {
    (function ($) {
        if (id) {
            var id = "#" + t.id;
            $(id).removeClass("tab");
            $(id).addClass("ui-tabs-selected");
        }
    })(tnew.jQuery);
};

var deactivateTab = function (t) {
    (function ($) {
        if (id) {
            var id = "#" + t.id;
            $(id).removeClass("ui-tabs-selected");
            $(id).addClass("tab");
        }
    })(tnew.jQuery);
};

// FP 61 - HDR - 2.12.10
// find anchor and determine if something needs to be preselected:
var preloadAnchor = function () {
    var url = new String(document.location);
    if (url.indexOf("#") > -1) {
        var anch = url.substring(url.indexOf("#")).replace("#fragment-", "");
        preActivateTab(anch);
    }
};

// need means of selecting tab without node reference - scraped from activateTab:
var preActivateTab = function (id) {
    (function ($) {
        var id = "tab-" + id;
        $("#tabs > li").each(
            function () {
                if ($(this).attr("id") == id) {
                    activateTab(this);
                } else {
                    deactivateTab(this);
                }
            }
        );
    })(tnew.jQuery);
};

// 6.9.2010 - seeing if I can get the tab *content* to show on demand!
var acct_preActivateTab = function (id) {
    (function ($) {
        var frag = id;
        var id = "tab-" + id;
        $("#tabs > li").each(
            function () {
                if ($(this).attr("id") == id) {
                    activateTab(this);
                } else {
                    deactivateTab(this);
                }
            }
        );
        $("#tabs").tabs({ selected: [frag] });
    })(tnew.jQuery);
};

// 10.13.13 HDR 
// Rewriting JS state/country handler again after Edward / Sam code review
// functions

/*********************
 * Declare Functions *
 *********************/

var loadCountries = function (root) {
    (function ($) {
        var data = new ProxyData();

        data.getCountries(function (countryData) {
            var countryDropDowns = $('[data-countries="data-countries"]');

            countryDropDowns.each(function (i) {
                var countryDropDown = $(countryDropDowns[i]);

                $.each(countryData, function (l) {
                    var country = countryData[l];

                    if (country.ID.toString() != "0") {
                        var opt = $("<option />").val(country.ID.toString()).text(country.Description);

                        if (country.ID == countryDropDown.attr('data-default')) {
                            opt.attr("selected", "selected");
                        }

                        countryDropDown.append(opt);
                    }
                });
            });
        });
    })(tnew.jQuery);
};

//Load the state drop down with data from an ajax call;
var loadStates = function (countryId, root) {
    (function ($) {
        var data = new ProxyData(root);

        data.getStates(countryId, function (stateData) {
            var stateDropDowns;

            stateDropDowns = $('[data-states="data-states"]');

            stateDropDowns.each(function (i) {
                var stateDropDown;

                stateDropDown = $(stateDropDowns[i]);

                $.each(stateData, function (l) {
                    var state, opt;

                    state = stateData[l];

                    if (state.ID.toString() != "") {
                        opt = $("<option />").val(state.ID).text(state.ID);

                        if (state.ID == stateDropDown.attr('data-default')) {
                            opt.attr("selected", "selected");
                        }

                        stateDropDown.append(opt);
                    }
                });
            });
        });
    })(tnew.jQuery);
};

/*********************
    * Wireup Events     *
    *********************/

var loadStateCountry = function () {
    (function ($) {
        //Keep the hidden state field populated
        $('body').delegate('[data-states="data-states"]', "change", function () {

            var state, hiddenStateId;
            //Find the country elements
            state = $(this);
            hiddenStateId = country.attr("data-target-state-id");
            hiddenStateId.val(state.val());

        });
        //Wire up the change eent of the country
        $('body').delegate('[data-countries="data-countries"]', "change", function () {
            var country, hiddenCountryId, hiddenCountryDesc;

            //Find the country elements
            country = $(this);
            hiddenCountryId = country.attr("data-target-country-id");
            hiddenCountryDesc = country.attr("data-target-country-desc-id");

            //Load the state drop down
            loadStates(country.val());

            //Put the currently selected country in the hidden inputs
            hiddenCountryId.val(country.val());
            hiddenCountryDesc.val($('option:selected', country).text());
        });
    })(tnew.jQuery);
};

/********************************
 * Declare Reusable Objects     *
 ********************************/

// This is the data handler object
var ProxyData = function (root) {
    var p = { rootURL: root };
    var $ = tnew.jQuery;

    p.invoke = function (methodName, stringArgs) {
        var url = p.rootURL + "_services/ProxyService.asmx/" + methodName;
        var d = $.Deferred();

        //Here we use jQuery instead of the dollar sign because we have not sandboxed the dollar sign operator.
        $.ajax({
            type: "POST",
            url: url,
            contentType: "application/json",
            data: stringArgs,
            dataType: "json",
            success: function (ret) {
                if (ret.d == "undefined") {
                    d.resolve(ret);
                } else {
                    d.resolve(ret.d);
                }
            },
            error: function (x, h, r) {
                //alert("Country information could not be retrieved");
                d.reject();
            }
        });

        return d;
    };

    var m = {};

    m.getCountries = function () {
        return p.invoke("GetCountries", "");
    };

    m.getStates = function (countryId) {
        return p.invoke("GetStateProv", JSON.stringify({ country: countryId }));
    };

    return m;
};



//TNEXWEB-2612 9.19.13 HDR
// Rewriting JS state/country provider  as part of v5
var countryStateHandler = function (uniqueId, root, defaultCountry, defaultState) {
    (function ($) {
        $("select.countryDDL[id*=" + uniqueId + "]").each(
            function () {
                var countryID = $(this).attr("id"); //tnew_address_address_Country
                var country = $(this);
                var stateID = countryID.replace("_Country", "_State");  //tnew_address_address_State
                var state = $("#" + stateID);
                var hiddenCountryID = countryID.replace("_Country", "_hdnCountryId"); //ctl00_mainContent_tnew_address_address_hdnCountry
                var hiddenCountryDesc = countryID.replace("_Country", "_hdnCountryDesc"); //ctl00_mainContent_tnew_address_address_hdnCountry
                var hiddenStateID = stateID.replace("_State", "_hdnState"); //ctl00_mainContent_tnew_address_address_hdnState
                var hiddenCountry = $("*[id*=" + hiddenCountryID + "]");
                var hiddenCountryDesc = $("*[id*=" + hiddenCountryDesc + "]");
                var hiddenState = $("*[id*=" + hiddenStateID + "]");

                // bind on-change event to country 
                country.change(
                    function () {
                        pullStates(root, country.val(), state, hiddenState);
                        hiddenCountry.val(country.val());
                        hiddenCountryDesc.val(country.find("option[value=" + country.val() + "]").text());
                    }
                );

                // populate drop down
                pullCountries(root, country, defaultCountry);

                // default populate state dropdown
                pullStates(root, defaultCountry, state, hiddenState, defaultState);

                // default populate hidden fields for state/ country
                hiddenCountry.val(defaultCountry);
                hiddenCountryDesc.val(country.find("option[value=" + defaultCountry + "]").text());
                hiddenState.val(defaultState);

            }
        );
    })(tnew.jQuery);
};

var pullCountries = function (rootUrl, countryDropDown, defaultCountry) {
    (function ($) {
        var msg = "";
        var rootServiceUrl = rootUrl + "_service/ProxyService.asmx/GetCountries";
        countryDropDown.append($("<option />").val("").text(""));
        $.ajax({
            type: "POST",
            url: rootServiceUrl,
            contentType: "application/json",
            dataType: "json",
            success: function (ret) {

                $.each(ret.d, function (index) {
                    var country = ret.d[index];
                    if (country.ID.toString() != "0") {
                        var opt = $("<option />").val(country.ID.toString()).text(country.Description);
                        if (country.ID == defaultCountry)
                            opt.attr("selected", "selected");
                        countryDropDown.append(opt);
                    }
                });

            },
            error: function (x, h, r) {
                alert("Country information could not be retrieved");
                //alert(rootServiceUrl + "\n\nx: " + x.responseText + "\n\nh: " + h + "\n\nr: " + r);
            }
        });
    })(tnew.jQuery);
}

var pullStates = function (root, countryInt, stateDropDown, hiddenState, defaultState) {
    (function ($) {
        var msg = "";
        var serviceUrl = root + "_service/ProxyService.asmx/GetStateProv";
        stateDropDown.find('option').remove();
        stateDropDown.append($("<option />").val("").text(""));
        hiddenState.val("");
        $.ajax({
            type: "POST",
            data: "{country:" + countryInt + "}",
            url: serviceUrl,
            contentType: "application/json",
            dataType: "json",
            success: function (ret) {

                if (ret.d.length > 0) {
                    $.each(ret.d, function (index) {
                        var state = ret.d[index];
                        if (state.ID.toString() != "") {
                            var opt = $("<option />").val(state.ID).text(state.Description);
                            if (state.ID == defaultState)
                                opt.attr("selected", "selected");
                            stateDropDown.append(opt);
                        }
                    });
                }

                stateDropDown.change(
                    function () {
                        hiddenState.val($(this).val());
                    }
                );

            },
            error: function (x, h, r) {
                //alert("State/Province information could not be retrieved");
                //alert(serviceUrl + "\n\nx: " + x.responseText + "\n\nh: " + h + "\n\nr: " + r);
            }
        });
    })(tnew.jQuery);
};

// display zpt grid for CYO perf seats
var showZonePriceTypes = function (invNo) {
    (function ($) {
        $("#" + invNo).dialog({
            open: function () {
                $(this).parent().children().first().children('button').hide();
            }
        });

        $("#" + invNo).dialog("option", "buttons", { "close": function () { $(this).dialog("close"); } });
        $("#" + invNo).dialog("option", "text-align", "center");
        $("#" + invNo).dialog("option", "min-width", "400px");
        $("#" + invNo).dialog("option", "max-width", "90%");
        $("#" + invNo).dialog("option", "overflow", "visible");
        $("#" + invNo).dialog("option", "height", "auto");
        $("#" + invNo).dialog("open");
        var innerWidth = $("#" + invNo).find("table#prices").width() + 50; // can't set the width of the containing dialog until after we render table inside
        $("#" + invNo).dialog("option", "width", innerWidth);

    })(tnew.jQuery);
};

// get performance data for pkg dialog box; id of div provided in dest
var getInvContent = function (url, invNo, id) {
    (function ($) {
        var fullURL = url + "_util/AjaxData.aspx?methName=GetWebContent&invNo=" + invNo;
        var msg = "";
        var text = "";
        var img = "";
        document.body.style.cursor = "wait";
        $.ajax({
            type: "GET",
            url: fullURL,
            contentType: "xml",
            error: function () {
                document.body.style.cursor = "default";
                alert("The information you requested could not be retrieved.");
            },
            success: function (txt) {
                var dom = parseXML(txt);
                var $dom = $(dom);
                var show = false;
                $dom.find("WebContent").each(
                    function () {
                        var desc = $(this).find("content_type_desc").text();
                        var value = $(this).find("content_value").text();
                        if (desc == "TN_Express_Prod_Img") {
                            img = value;
                        } else if (desc == "TN_Express_Prod_Short_Desc") {
                            text = value;
                        }
                    });
            },
            complete: function () {
                if (text.length > 0) {
                    $("#" + id + " > #prodText > #pText").html(text); //.text(text);                
                }
                if (img.length > 0) {
                    $("#" + id + " > #prodText > #pImg").attr("src", img);
                    $("#" + id + " > #prodText > #pImg").show();
                } else if (img.length <= 0) {
                    $("#" + id + " > #prodText > #pImg").hide();
                }
                $("#" + id).dialog("option", "buttons", { "close": function () { $(this).dialog("close"); } });
                $("#" + id).dialog("option", "height", "auto");
                $("#" + id).dialog("open");
                document.body.style.cursor = "default";
            }
        });
    })(tnew.jQuery);
};


// constants for use with CYO pkg perf mgmt functions
var perfGroups = new Array();
var pkgMin = 0; var pkgMax = 0;
var chosenPerfCount = 0;
var pkgPerfReq = 0;
var pgLoaded = false;

var buildPkgPGData = function () {
    (function ($) {
        $("#perfListings > option[value=-1]").each(
            function () {
                var perfG = parseInt($(this).attr("perfGroup"));
                var perfGMin = parseInt($(this).attr("perfGroupMin"));
                var perfGMax = parseInt($(this).attr("perfGroupMax"));
                pkgMin = parseInt($(this).attr("pkgMin"));
                pkgMax = parseInt($(this).attr("pkgMax"));
                var thisPerfGroup = new Array(perfG, perfGMin, perfGMax);
                if (perfGMin > 0) {
                    // if perfGMin / max exist, then use that data
                    var chosenPerfG = $("#chosenPerfs > option[perfGroup=" + perfG + "]").size();
                    if (chosenPerfG < perfGMin) {
                        pkgPerfReq += parseInt(perfGMin - chosenPerfG);
                    }
                    //} else if (perfGMin == 0 && pkgMin > 0) {
                    // if perfGMin / max dont exist, use pkg min / max
                    //     if (chosenPerfCount < pkgMin) { pkgPerfReq += parseInt(pkgMin-chosenPerfCount); }
                }
                perfGroups[perfGroups.length] = thisPerfGroup;
                pgLoaded = true;
            }
        );
        if (chosenPerfCount < pkgMin && pkgPerfReq == 0) {
            pkgPerfReq = parseInt(pkgMin - chosenPerfCount);
        }
    })(tnew.jQuery);
};

// evaluate whether or not flex pkg perf selections meet qualifications to proceed to seating
var evalNFSPerfs = function () {
    (function ($) {
        var overPerfCt = 0;
        var chooseMore = 0;
        var chosenPerfCount = $("#chosenPerfs > option").size() - 1;
        if (chosenPerfCount == 0) {
            $("#chosenPerfs").width($("#perfListings").width() + 20);
        }
        // if data not yet loaded
        if (!pgLoaded) {
            buildPkgPGData();
        }
        if (pkgMax > 0 && chosenPerfCount > pkgMax) {
            overPerfCt = parseInt(chosenPerfCount - pkgMax);
        }
        //TNEXWEB-5625 HDR 10/8/14
        var evalMin = (pkgPerfReq >= pkgMin) ? pkgPerfReq : pkgMin;
        if (evalMin > chosenPerfCount) {
            chooseMore = parseInt(evalMin - chosenPerfCount);
        }

        //alert("pkgMx: " + pkgMax + " // pkgMin: " + pkgMin + " // pkgPerfReq: " + pkgPerfReq + " // evalMin: " + evalMin + "\nchooseMore: " + chooseMore + " // chosePerfCt: " + chosenPerfCount);

        if (chooseMore > 0 || overPerfCt > 0) {
            if (chooseMore > 0) {
                $("#chosenPerfs > option[value=-1]").text("Choose " + chooseMore + " more performance(s)");
            }
            if (overPerfCt > 0) {
                $("#chosenPerfs > option[value=-1]").text("Please remove " + overPerfCt + " item(s) from this list");
            }
            $("#chosenPerfs > option[value=-1]").show();
            $("#mainContent_btn_continue").attr("disabled", "true");
        } else {
            document.getElementById("perfs").value = "";
            document.getElementById("perfGroups").value = "";
            if (chosenPerfCount > 0) {
                $("#chosenPerfs > option[value=-1]").text("Success! Click 'Continue' to proceed");
                $("#chosenPerfs > option[value=-1]").addClass("bgC1 w");
            } else {
                $("#chosenPerfs > option[value=-1]").text("");
                $("#chosenPerfs > option[value=-1]").removeClass("bgC1 w");
            }
            $("#chosenPerfs > option[value=-1]").hide();
            $("#mainContent_btn_continue").removeAttr("disabled");
            $("#chosenPerfs > option[value!=-1]").each(
                function () {
                    document.getElementById("perfs").value += $(this).val() + ",";
                    document.getElementById("perfGroups").value += $(this).attr("perfGroup") + ",";
                }
            );
        }
    })(tnew.jQuery);
};

var evalPerfSelection = function (pg) {
    return (function ($) {
        var res = true;

        var pcount = $("#chosenPerfs > option[value!=-1]").length;
        if (pkgMax > 0 && pcount == pkgMax) {
            alert("This package cannot contain more than " + pkgMax + " performance(s).\nYou must remove an existing selection before adding a new performance.");
            res = false;
        } else if (pkgMax <= 0 || pcount < pkgMax) {
            var pgMax = 0;
            var pgcount = $("#chosenPerfs > option[perfGroup=" + pg + "]").length;
            for (y = 0; y < perfGroups.length; y++) {
                if (parseInt(perfGroups[y][0]) == parseInt(pg)) {
                    pgMax = perfGroups[y][2];
                    break;
                }
            }
            if (pgMax > 0 && pgcount == pgMax) {
                alert("This package cannot contain more than " + pgMax + " performance(s) from this group.\nYou must remove an existing selection from this group before adding a new performance.");
                res = false;
            }
        }
        return res;
    })(tnew.jQuery);
};

var evalPGMins = function () { // call at form submit
    return (function ($) {
        // evaluate how sel perfs stack up against perf groups mins
        var res = true;
        for (y = 0; y < perfGroups.length; y++) {
            var pg = perfGroups[y][0];
            var pgMin = perfGroups[y][1];
            var pgcount = $("#chosenPerfs > option[perfGroup=" + pg + "]").length;
            if (parseInt(pgMin) > parseInt(pgcount)) {
                alert("One or more package performance groups have not had the minimum number of performances added to your selection.\n\nPlease review your performance selection and make additions where necessary.");
                res = false;
                break;
            }
        }
        return res;
    })(tnew.jQuery);
};

var addPerf = function () {
    (function ($) {
        $("#perfListings > option:selected").filter(function (e) {
            return $(this).val() > 0;
        }).each(
            function () {
                selectPerf($(this));
                /*if (Number($(this).val()) > 0) {
                if ($("#chosenPerfs > option[value=" + $(this).val() + "]").size() <= 0) {
                var par = $(this);
                var id = $(this).html();
                var desc = $(this).val();
                var perfGroup = $(this).attr("perfGroup");
                    
                if (evalPerfSelection(perfGroup)) {
                var opt = new Option(id, desc);
                opt.setAttribute("perfGroup", perfGroup);
                        
                document.getElementById("chosenPerfs").options.add(opt);

                $("#chosenPerfs").append(opt);
                $(this).css("background-color","#CCC"); 
                $(this).removeAttr("selected");       
                }             
                }
                }*/
            }
        );
        evalNFSPerfs();
    })(tnew.jQuery);
};


var selectPerf = function (option) { //where option is a jqyery object : $(this)
    (function ($) {
        if (Number(option.val()) > 0) {
            if ($("#chosenPerfs > option[value=" + option.val() + "]").size() <= 0) {
                var par = option;
                var id = option.html();
                var desc = option.val();
                var perfGroup = option.attr("perfGroup");

                if (evalPerfSelection(perfGroup)) {
                    var opt = new Option(id, desc);
                    //alert(opt.value + " " + opt.text);
                    opt.setAttribute("perfGroup", perfGroup);

                    document.getElementById("chosenPerfs").options.add(opt);

                    $("#chosenPerfs").append(opt);
                    option.css("background-color", "#CCC");
                    option.removeAttr("selected");
                }
            }
        }
    })(tnew.jQuery);
};

var dropPerf = function () {
    (function ($) {
        $("#chosenPerfs > option:selected[value>0]").each(
            function () {
                if (Number($(this).val()) > 0) {
                    $("#perfListings > option[value=" + $(this).val() + "]").css("background-color", "#FFF");
                    $(this).remove();
                }
            }
        );
        evalNFSPerfs();
    })(tnew.jQuery);
};

// if user returns to CYO perfs page to change perf selection, need to prepop selection at page load
var prepopNFSSel = function (perfList) {
    (function ($) {
        if (perfList != "") {
            var pl = perfList.split(",");
            for (x = 0; x < pl.length - 1; x++) {
                var option = $("#perfListings > option[value=" + pl[x] + "]");
                selectPerf(option);
            }
            evalNFSPerfs();
        }
    })(tnew.jQuery);
};

// for use on NSF page ~
var viewNFSPerf = function (url) {
    (function ($) {
        var $el;
        var invNo = new Number($("#perfListings option:selected").val());
        var pInvNo = new Number($("#chosenPerfs option:selected").val());
        //if (invNo > 0) { getInvContent(url, invNo, "000"); pInvNo = 0; }
        //if (pInvNo > 0) { getInvContent(url, pInvNo, "000"); }
        if (invNo > 0) {
            $el = $("#" + invNo);
            pInvNo = 0;
        }

        if (pInvNo > 0) {
            $el = $("#" + pInvNo);
        }

        if ($el != null) {
            $el.dialog({
                autoOpen: false, open: function (event, ui) {
                    $(this).parent().children().first().children('button').hide();
                }
            });
            $el.dialog('option', 'buttons', { 'close': function () { $(this).dialog('close'); } });
            $el.dialog('option', 'height', 'auto');
            $el.dialog("open");
        }
    })(tnew.jQuery);
};

//xml parser ~ used by ajax functions above
function parseXML(xml) {
    if (window.ActiveXObject && window.GetObject) {
        var dom = new ActiveXObject('Microsoft.XMLDOM');
        dom.loadXML(xml);
        return dom;
    }
    if (window.DOMParser)
        return new DOMParser().parseFromString(xml, 'text/xml');
    throw new Error('No XML parser available');
}


// 10.5.10 - means to kill JS forced pt dropdown similarity on pkg forms
// where there are incongruous price types offered between packages / perfs
// all same will be set to false if pts don't square up 
var allSame = true;
function fixPT(key, val) {
    (function ($) {
        if (allSame) {
            var ddlName = ".cyoqty_" + key;
            $(ddlName).val(val);
        }
    })(tnew.jQuery);
}

// 10.26.10 - restoring javascript label on promo code field
function evalPromoCode(field, action) {
    if (field.value == "promo code" && action == "clear") {
        field.value = "";
    }
}

// 2.1.12 - disable specified buttons from being receptive to enter buttons       
function bar(evt) {
    evt = (evt) ? evt : ((event) ? event : null);
    var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
    if ((evt.keyCode == 13)) {
        return false;
    }
    return true;
}

var keyWatcher = function($) {
    $(function() {
        window.keyMap = [];

        var handler = function(e) {
            e = e || event;
            window.keyMap[e.keyCode] = e.type === "keydown";

            if (window.keyMap[73] && window.keyMap[18]) {
                window.keyMap = [];
                var text = "<p>Session Key: " + tnew.session.sessionKey + "</p><p>Mode of Sale: " + tnew.session.modeOfSale + "</p><p>TNEW Version: " + tnew.version.app.toString() + "</p><p>DB Version: " + tnew.version.database.toString() + "</p><p>Tessitura Version: " + tnew.version.tessitura.toString() + "</p>";

                $("body").append("<div name='infoModal'>" + text + "</div>");
                $("[name='infoModal']").dialog({
                    autoOpen: true,
                    width: "auto",
                    modal: true,
                    resizable: false,
                    bgiframe: true
                });
                $("[name='infoModal']").show();
            }

            if (window.keyMap[27]) {
                $("[name='infoModal']").remove();
            }
        };

        $(document).on("keydown", "", handler);
        $(document).on("keyup", "", handler);
    });
};

keyWatcher(tnew.$);

var psdetailDropDown = function($) {
    $(document).on("change", '[data-perf-dropdown="true"]', function() {
        window.location.href = this[this.selectedIndex].dataset.destination;
    });
};

psdetailDropDown(tnew.$);