﻿/// <reference path="jquery-1.4.1-vsdoc.js" />
jQuery.fn.exists = function () { return jQuery(this).length > 0; }

String.format = function () {
    var s = arguments[0];
    for (var i = 0; i < arguments.length - 1; i++) {
        var reg = new RegExp("\\{" + i + "\\}", "gm");
        s = s.replace(reg, arguments[i + 1]);
    }
    return s;
}

function popUPcenter(url, target, w, h) {

    putItCenter = window.open(url, target, 'width=' + w + ',height=' + h + ',toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,left=' + ((screen.availWidth - w - 10) * .5) + ',top=' + ((screen.availHeight - h - 30) * .5));

    putItCenter.focus();

}
function getSearchURL() {
    if (document.forms[0].txtSiteSearch.value != "") {
        var queryString = "?q=" + document.forms[0].txtSiteSearch.value;
        queryString += "&entqr=" + document.forms[0].entqr.value;
        queryString += "&LangType=" + document.forms[0].LangType.value;
        queryString += "&output=" + document.forms[0].output.value;
        queryString += "&sort=" + document.forms[0].sort.value;
        queryString += "&client=" + document.forms[0].client.value;
        queryString += "&oe=" + document.forms[0].oe.value;
        queryString += "&site=" + document.forms[0].site.value;
        this.location.href = "/SiteCode/Integration/Search.aspx" + queryString;
    }
}
function nav() {
    $("div#TopNav ul li").mouseover(function () {
        $(this).find('ul:first').show();
    });

    $("div#TopNav ul li").mouseleave(function () {
        $("div#TopNav ul li ul").hide();
    });

    $("div#TopNav ul li ul").mouseleave(function () {
        $("div#TopNav ul li ul").hide();
    });

}
function BindFormEnterSubmit(wrapperId, buttonClientId) {
    var selector = "#" + wrapperId + " :input";
    var submitButton = "#" + buttonClientId;
    //form enter keypress submit
    $(document).ready(function () {
        //alert(wrapperId);
        $(selector).keypress(function (e) {

            if (e.which == 13 && $(this).hasClass("ignore") != true) {

                e.preventDefault();
                eval($(submitButton).attr('href'));
            }
        });
    });
}


function toggleExpandibleText(obj) {
    $(obj).parent().parent().toggleClass("expanded");
    //$(selector).toggleClass("expanded");
}

function FieldMatchesRegex(inputSelector, pattern) {
    var regex = new RegExp(pattern);
    return regex.test($(inputSelector).val());
}

function ValidateField(inputSelector, labelSelector, patterns) {
    var IsValid = true;
    for (i = 0; i < patterns.length; i++) {
        if (FieldMatchesRegex(inputSelector, patterns[i].pattern) != patterns[i].shouldMatch) {
            $(labelSelector).css("color", "red");
            $(labelSelector).addClass("error");
            IsValid = false;
        }
    }
    if (IsValid) {
        $(labelSelector).css("color", "");
        $(labelSelector).removeClass("error");
    }
    return IsValid
}

function SetValidationSummary(IsValid) {
    if (IsValid) {
        if ($("#contactUsForm span.label.error").length == 0)
            $("#valSummary").remove();
    }
    else {
        if ($("#valSummary").length == 0)
            $("#contactUsForm").before("<p id='valSummary' class='error'>There were errors processing your information. Please verify your information below and try again.</p>");
    }
}

$(document).ready(function () {

    //contact us form validation
    /* $("#contactUsForm #FirstName").blur(function () {
    SetValidationSummary(ValidateField("#FirstName", "#contactUsForm span.label.firstname", [{ pattern: "^\s*$", shouldMatch: false}]));
    });

    $("#contactUsForm #LastName").blur(function () {
    SetValidationSummary(ValidateField("#LastName", "#contactUsForm span.label.lastname", [{ pattern: "^\s*$", shouldMatch: false}]));
    });

    $("#contactUsForm #E-mailAddress").blur(function () {
    SetValidationSummary(ValidateField("#E-mailAddress", "#contactUsForm span.label.emailaddress",
    [{ pattern: "^\s*$", shouldMatch: false },
    { pattern: "^[^@]+?@.+\\.[a-zA-Z]+$", shouldMatch: true}]));
    });

    $("#contactUsForm #MessageTopic").blur(function () {
    SetValidationSummary(ValidateField("#MessageTopic", "#contactUsForm span.label.messagetopic", [{ pattern: "\(Select\)", shouldMatch: false}]));
    });*/

    $("#contactUsForm #FirstName, #contactUsForm #LastName, #contactUsForm #E-mailAddress, #contactUsForm #Message").val("");

    if($("#contactUsForm #MessageTopic").length > 0)
        $("#contactUsForm #MessageTopic")[0].selectedIndex = 0;

    $("#contactUsForm .ekt_form_submit").click(function () {
        var IsValid = true;
        IsValid = ValidateField("#FirstName", "#contactUsForm span.label.firstname", [{ pattern: "^\s*$", shouldMatch: false}]);

        tempIsValid = ValidateField("#LastName", "#contactUsForm span.label.lastname", [{ pattern: "^\s*$", shouldMatch: false}]);
        IsValid = (IsValid ? tempIsValid : IsValid);

        tempIsValid = ValidateField("#E-mailAddress", "#contactUsForm span.label.emailaddress",
            [{ pattern: "^\s*$", shouldMatch: false },
            { pattern: "^[^@]+?@.+\\.[a-zA-Z]+$", shouldMatch: true}]);
        IsValid = (IsValid ? tempIsValid : IsValid);

        tempIsValid = ValidateField("#MessageTopic", "#contactUsForm span.label.messagetopic", [{ pattern: "\(Select\)", shouldMatch: false}]);
        IsValid = (IsValid ? tempIsValid : IsValid);

        SetValidationSummary(IsValid);
        if (IsValid) {
            var description = $("input[name='EktFormDescription']").val();
            description = "<p>Thank you for your feedback. We take all comments seriously, and we will respond within 72 hours.</p>";
            $("#contactUsForm").before(description);
            $("#contactUsForm").css("display", "none");
        }
        return IsValid;
    });

    //userinfo
    if ($("#userinfoholder").length > 0) {

        // $("#userinfoholder").load("/ch/uc/userinfo.aspx");
        $.ajax({
            cache: false,
            type: "GET",
            url: "/ch/uc/userinfo.aspx",
            success: function (data) {
                $("#userinfoholder").html(data);

            }
        });
    }




    $("#btnEmail").live("click", function (e) {
        e.preventDefault();
        $("#emailLoad").show();
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            data: { "action": "ProcessEmail",
                "email": $("#txtEmail").val()

            },
            url: "/ch/handlers/EmailSignupMail2.ashx",

            success: function (data) {
                $("#emailLoad").hide();
                if (data.isError) {
                    $("#emailStatus").html(data.message);
                    $("#emailStatus").show();
                }
                else {
                    window.location = data.message;

                    //$("#emailStatus").html(data.message);
                }
            }
        });
    });


    $(".updates_email").live("focusin", function () {
        $("#emailStatus").hide();
        if ($(this).val() == "Sign up for E-Mail Updates") {
            //   alert("true");
            $(this).val("");
        }
        else {
            //alert($(this).val());
        }
    });


    //    $(".updates_email").focusin(function () {
    //        //  alert($(this).val());
    //        if ($(this).val() == "Email For Updates") {
    //            $(this).val("");
    //        }
    //    });
    $(".updates_email").live("focusout", function () {
        // alert("focus out");
        //  $(".updates_email").focusout(function () {
        if ($(this).val() == "") {
            $(this).val("Sign up for E-Mail Updates");
        }
    }
    );

    $(".updates_email").keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $("#btnEmail").trigger("click");
            return false;
        } else {
            return true;
        }
    });


    $("#txtSiteSearch").focusin(function () {
        //  alert($(this).val());
        if ($(this).val() == "Search Carnegie Hall") {
            $(this).val("");
        }
    });

    $("#txtSiteSearch").focusout(function () {
        if ($(this).val() == "") {
            $(this).val("Search Carnegie Hall");
        }
    }
    );


    $("#txtEmailWrapper  #txtEmail").focusin(function () {
        //  alert($(this).val());
        if ($(this).val() == "Sign Up for E-Mail Updates") {
            $(this).val("");
        }
    });

    $("#txtEmailWrapper #txtEmail").focusout(function () {
        if ($(this).val() == "") {
            $(this).val("Sign Up for E-Mail Updates");
        }
    }
    );

    $("#txtSiteSearch").keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            getSearchURL();
            return false;
        } else {
            return true;
        }
    });

    //nav();

    //    //topnav menu flyouts
    $(".li_nav").mouseenter(function (e) {
        $(this).find("ul").show();
        $(this).find(".navigation_headers").attr("class", "navigation_headers_selected");

    });
    $(".li_nav").mouseleave(function (e) {
        $(this).find("ul").hide();
        $(this).find(".navigation_headers_selected").attr("class", "navigation_headers");
    });



    $(".txt-bmk-title").submit(function (e) {
        e.preventDefault();
        $(this).parent.find(".bmk-title-update").click();
    });

    $(".edit-bmk").live("click", function (e) {
        e.preventDefault();
        var p = $(this).parent().parent();
        p.find(".bmk-title").hide();
        p.find(".txt-bmk-title").show();
        p.find(".bmk-title-update").show();
        p.find(".bmk-title-cancel").show();
    });

    //bmk-title-cancel
    $(".bmk-title-cancel").live("click", function (e) {
        e.preventDefault();
        var p = $(this).parent().parent();
        p.find(".bmk-title").show();
        p.find(".txt-bmk-title").hide();
        p.find(".bmk-title-update").hide();
        p.find(".bmk-title-cancel").hide();
    });


    //full cal close
    $("#full-cal-close").live("click", function (e) {
        e.preventDefault();
        $("#full-cal-wrapper").hide();
    });
    //full cal click
    $("#full-cal-open").live("click", function (e) {
        e.preventDefault();
        $("#full-cal-wrapper").slideDown();
    });

    //remove event from MyCalendar
    $(".remove-cal").live("click", function (e) {
        e.preventDefault();
        if (confirm("Remove this Event?")) {
            var id = $(this).attr("href").replace("#", "");
            var requestData = {
                "action": "DeleteEvent",
                "id": id
            };
            $.ajax({ url: "/ch/handlers/profile.ashx", type: "POST", data: requestData, success: function (data) {

                //alert success
                LoadProfileLists();
                // $(".btnReloadBookmarks").click();
            }
            });
        }
    });

    //remove bookmark
    $(".remove-bmk").live("click", function (e) {
        e.preventDefault();

        if (confirm("Remove this Bookmark?")) {

            var id = $(this).attr("href").replace("#", "");

            var requestData = {
                "action": "DeleteBookmark",
                "id": id
            };
            $.ajax({ url: "/ch/handlers/profile.ashx", type: "POST", data: requestData, success: function (data) {

                //alert success
                LoadProfileLists();
                // $(".btnReloadBookmarks").click();
            }
            });

        }
    });


    $(".expand-bio").click(function (e) {
        e.preventDefault();

        var expand = $(this).parent().find(".bio-expand");
        if (expand.hasClass("short")) {
            expand.removeClass("short").css("height", "auto");
            $(this).text("Close");
        }
        else {
            expand.addClass("short").css("height", "110px");
            $(this).text("More Info");

        }
    });



});

jQuery(function ($) {
    $.fn.analytics = function (param, custom) {
        var event_string = custom ? custom + ".analytics" : "keydown.analytics mousedown.analytics";
        return this.one(event_string, function (e) {
            if (!(typeof click === "undefined") && click || (e.type === "click" || e.type === "mousedown" || e.which === 13)) {
                if (typeof param === "function") {
                    param.apply(this);
                } else if (param instanceof Array) {
                    param.splice(0, 0, "_trackEvent");
                    _gaq.push(param);
                }
            }
        });
    };


    var purchase_step = $(".stepNavigationContainer .active").text();
    var purchase_step_num = $(".stepNavigationContainer .activeNumber").text();
    /*Purchase Funnel*/
    if (purchase_step.length && purchase_step_num.length) {
        _gaq.push(["_trackEvent", "Purchase Funnel", purchase_step_num + ": " + purchase_step]);
    }


    /*click "go" button on sign up for email*/
    $("#btnEmail").analytics(["Clicks - Header", "Signup Go"]);

    /*click "support the hall" in header*/
    $(".navigation_headers").last().analytics(["Clicks - Header", "Support the Hall"]);

    /*click "become a member" in header*/


    /*HOMEPAGE*/
    if (location.pathname === "/" || location.pathname === "/default.aspx") {

        /* Click "make donation" in footer*/
        $("#footer-menu a").filter("a[href='/SiteCode/Integration/OneStepMakeDonation.aspx']").analytics(["Clicks - Home Page", "Make a Donation"]);

        /* clicks on homepage upcoming events links */
        $(".upcoming-events a").analytics(function () {
            $this = $(this);
            _gaq.push(["_trackEvent", "Home Page", "Clicks - Upcoming Events", $this.text(), $this.attr("href")]);
        });
        /* clicks on homepage calendar  links */
        $("#homepage_calendar a").analytics(function () {
            $this = $(this);
            _gaq.push(["_trackEvent", "Home Page", "Clicks - Home Page Calendar", $this.text(), $this.attr("href")]);
        });
    }

    /*CALENDAR PAGE*/
    if (location.pathname.match(/^\/Calendar/)) {
        /* Clicked Event Search Buy*/
        $(".evnt-search-buy a").analytics(function () {
            $this = $(this);
            var cal_event_name = $this.closest(".cal_event").children("li:first").text().trim();
            _gaq.push(["_trackEvent", "Calendar Page", "Clicks - Buy Now", cal_event_name]);
        });

        $(".event_title a").analytics(function () {
            $this = $(this);
            _gaq.push(["_trackEvent", "Calendar Page", "Clicks - Event Names", $this.text()]);
        });

        /*TODO type into artists box*/
        /*TODO type into composers box*/
    }

    /*EVENT PAGES*/
    if (location.pathname.toLowerCase() === "event.aspx") {
        var event_name = $("h1.eventTitle").text().trim();

        $(".buy-button-wrapper").not(".ADALinks").analytics(function () {
            _gaq.push(["_trackEvent", "Event Page", "Clicks - Buy Now", event_name]);
        });

        $("#seatinglink").analytics(["Event Page", "Clicks - Seating Chart", event_name], "click");

        $(".evnt-social a").analytics(function () {
            _gaq.push(["_trackEvent", "Event Page", $(this).text(), event_name]);
        });

        $(".event-notes a").analytics(["Event Page", "Clicks - Program Notes", event_name]);

        /*TODO click listen to audio*/
        /*TODO click video*/

    }
    /*SERIES PAGES*/
    if (location.pathname.toLowerCase() === "series.aspx") {
        var series_name = $(".series-headline").text().trim();

        $("#SeriesBuyCallout a").not(".small_accessibility_link").analytics(function () {
            var num_tix = +$("select[name='ticketQuantity']").val() || 0;
            _gaq.push(["_trackEvent", "Series Page", "Clicks - Buy Button", series_name, num_tix]);
        });
    }

    if (location.pathname === "/SiteCode/Purchase/OrderSummary.aspx") {
        $("a.md_btn_red").analytics(function () {
            var amount = parseInt($(".total").first().text().replace("$", ""), 10) || 0;
            _gaq.push(["_trackEvent", "Clicks - Order Summary", $(this).text(), amount]);
        });

        /*TODO: Click audio*/

        /*TODO: Click video*/
    }

    /* External Link Tracking*/
    $(document).delegate("a[href^='http']", 'mousedown.analytics keydown.analytics', function (e) {
        var dest = $(this).attr("href");
        if (!this.hostname.match(/carnegiehall\.org/)) {
            var action = (/(facebook|twitter|youtube)(\.com)/i).test(dest) ? "social" : "external";
            _gaq.push(['_trackEvent', 'External Links', action, dest]);
        }
    });


    /* Facebook Like Tracking. Requires FB SDK*/
    if (window.FB && FB.Event) {
        FB.Event.subscribe('edge.create', function (response) {
            _gaq.push(["_trackSocial", "facebook", "Like", response]);
        });

        FB.Event.subscribe('edge.remove', function (response) {
            _gaq.push(["_trackSocial", "Facebook", "Unlike", response]);
        });
    }


    if (window.twttr) {
        var event_names = {
            "click": "",
            "tweet": "",
            "retweet": "source_tweet_id",
            "follow": "screen_name",
            "favorite": "tweet_id"
        };
        $.each(event_names, function (event_name, attribute) {
            twttr.events.bind(event_name, function (intent_event) {
                if (intent_event) {
                    var label = intent_event.type === "click" ? intent_event.region : (intent_event.data) ? intent_event.data[attribute] : "";
                    _gaq.push(["_trackSocial", "Twitter", intent_event.type, label]);
                }
            });
        });
    }
});
