﻿
var bugs = {};
var ptpointer = 1;
var pta = new Array();
var pageName="";
var pageType = "";
var timeout;
var hto;
var ctab = "";
$(document).ready(function () {



    $(".num").keypress(function (e) { return numbersOnly(e); });
    // handle submit for brochure and travel agent Request
    $("input[example], textarea[example]").live("focus", function () {
        if ($(this).val() == $(this).attr('example')) {
            $(this).val('');
            //$(this).addClass('ss-black');
        }
    });

    $("input[example], textarea[example]").live("blur", function () {
        if ($(this).val() == '' || $(this).val() == $(this).attr('example')) {
            // $(this).val($(this).attr('example')).removeClass('ss-black');
            $(this).val($(this).attr('example'))
        }
    });

    $(".submit-btn").live("click", function () {
        $("input[example], textarea[example]").each(function () {
            if ($(this).val() == $(this).attr('example')) {
                $(this).val('');
            }
        })
        $(this).parents('form').submit();


    });

    $(".print").live("click", function () {
        window.print();
        e.preventDefault();
    });

    pageName = $('meta[name=pageName]').attr("content");
    pageType = $('meta[name=pageType]').attr("content");

    switch (pageName) {
        case "search":
            $("ul.utility_buttons a.buttonb").addClass("current");
            break;
        case "rail-journeys":
            $("#nav_railjourneys").addClass("current");
            break;
        case "rail-getaways":
            $("#nav_railgetaways").addClass("current");
            break;

        case "our-destinations":
            $("#nav_destinations").addClass("current");
            break;

        case "vacation-experience":
            $("#nav_vacationexperience").addClass("current");
            break;

        case "specials":
            $("#nav_specials").addClass("current");
            break;

        case "newss":
            $("#nav_news").addClass("current");
            break;

        case "contactus":
            $("#nav_contactus").addClass("current");
            break;
        default:

            switch (pageType) {

                case "journeys":
                    $("#nav_railjourneys").addClass("current");
                    break;
                case "getaways":
                    $("#nav_railgetaways").addClass("current");
                    break;

                case "destinations":
                    $("#nav_destinations").addClass("current");
                    break;

                case "experience":
                    $("#nav_vacationexperience").addClass("current");
                    break;

                case "specials":
                    $("#nav_specials").addClass("current");
                    break;

                case "news":
                    $("#nav_news").addClass("current");
                    break;

                case "contactus":
                    $("#nav_contactus").addClass("current");
                    break;
            }

    }

    $("div.dropdown").hide();
    $("#c_overview").show();
    $("#c_journeys_overview").show();
    $("#c_programs_packages").show();

    locationCheck();

    var dropIt;
    var closeIt;

    zipTo();

    $(window).resize(function () {
        zipTo();
    });

    init();

    $("#slidewindow").live("click", function () {
        var ref = $("#slideshow_hp div.new a.link").attr("href");
        if (ref != '' && ref != undefined) {
            window.location = ref;
        }
    });

    $(".tab").live("click", function (e) {
        e.preventDefault();
        var baseURL = rootURL();
        var id = $(this).attr("id").substring(4);

        _gaq.push(['_trackEvent', 'Tab Click', id, document.title]);

        window.location = baseURL + "#" + id;
        $(".catab").hide();
        $("#c_" + id).show();
        $(".tab").removeClass("current");
        $(this).addClass("current");
        alternateRows();
        cktab();
    });

    $(".routeatlas").live("click", function () {
        $("#popover").css("width", "972px");
        $("#popover").css("height", "648px");
        $("#popover").html('<div class="routemapwrapper"><span class="closeme"></span><iframe src="http://tickets.amtrak.com/secure/content/routeatlas/index.html" width="968" height="632"></iframe></div>');
        $("#popover").centerInClient();
        if (pageName == "homepage") { $("#popover").css("left", "0") };
        $("#modal").show();
        $("#popover").show();
    });

    $(".clicktozoom, .rightpanel img.smallmap").live("click", function (e) {

        var s = $(".smallmap").attr("src");
        $("#popover").html('<div class="popinside"><span class="closeme"></span><img src="' + s + '" alt="Large Map View"/></div>');
        $("#popover").centerInClient();
        $("#modal").show();
        $("#popover").show();

    });

    $(".destinations>li").live("click", function (e) {
        var s = $(this).attr("class");
        var p = $(this).parent().attr("value");
        dbAJAX("destinationpopup.ajax", "?p=" + p + "&id=" + s, destinationPopup);
    });

    $(".closeme,#modal").live("click", function () {
        $("#popover").hide();
        $("#modal").hide();
        ss.start();
    });

    // search support
    $(".searchbutton>a").live("click", function (e) {
        e.preventDefault();
        var r = $('[name="tripregion"]').val();
        var d = $('[name="tripdestination"]').val();
        var t = $('[name="triptype"]').val();
        dbAJAX("filteroptions.ajax", "?r=" + r + "&d=" + d + "&t=" + t + salt(), updateResults);
    });
    $(".action .submit_button").live("click", function (e) {
        e.preventDefault();
        var r = $('[name="tripregion"]').val();
        var d = $('[name="tripdestination"]').val();
        var t = $('[name="triptype"]').val();
        dbAJAX("filteroptions.ajax", "?r=" + r + "&d=" + d + "&t=" + t, searchPage);
    });
    $(".pagelegend .goback").live("click", function (e) {
        e.preventDefault();
        dbAJAX("changepage.ajax", "?s=-1" + salt(), updateResults);
    });

    $(".pagelegend .goforward").live("click", function (e) {
        e.preventDefault();
        dbAJAX("changepage.ajax", "?s=1" + salt(), updateResults);
    });

    $(".sortbar .sort a").live("click", function (e) {
        e.preventDefault();
        var s = $(this).parent().attr("class").replace("current", "");
        s = s.substring(2);
        dbAJAX("sortpage.ajax", "?s=" + s + salt(), updateResults);
    });

    $("ul.pagecount a").live("click", function (e) {
        e.preventDefault();
        var s = $(this).attr("class").replace("current", "");
        s = s.substring(2);
        dbAJAX("selectpagelength.ajax", "?s=" + s + salt(), updateResults);
    });

    // travel elements image slider
    $(".elementslides a.leftarrow").live("click", function (e) {
        e.preventDefault();
        moveTile(".elementslides", -1, 4);
    });

    $(".elementslides a.rightarrow").live("click", function (e) {
        e.preventDefault();
        moveTile(".elementslides", 1, 4);
    });

    // home page features
    $("#promotiles a.leftarrow").live("click", function (e) {
        e.preventDefault();
        moveTile("#promotiles", -1, 3);
    });

    $("#promotiles a.rightarrow").live("click", function (e) {
        e.preventDefault();
        moveTile("#promotiles", 1, 3);
    });

    $(".hpsearch .tabs>a").live("click", function (e) {
        e.preventDefault();
        if ($(this).hasClass("journeys") == true) {
            $(".hpsearch .tabs").css("background-position", "left top");
            $(".hpsearch li.getaways").hide();
            $(".hpsearch li.journeys").show();
        } else {

            $(".hpsearch .tabs").css("background-position", "left -27px");
            $(".hpsearch li.journeys").hide();
            $(".hpsearch li.getaways").show();
        }

    });

    //AJAX Forms
    $("form.formwrapper").submit(function (e) {
        e.preventDefault();
        $("input[example], textarea[example]").each(function () {
            if ($(this).val() == $(this).attr('example')) {
                $(this).val('');
            }
        })
        var f = $(this)
        var serializedForm = $(f).serialize();
        var action = $(f).attr("action");
        if (serializedForm.length > 0 && action.length > 0) { serializedForm += "&sendto=" + action; }
        $.post("formsprocessor.aspx", serializedForm, function (data) {
            var ra = data.split("||");
            if (ra[0] == "OK") {
                switch (ra[2].toUpperCase()) {
                    case "SUCCESSREDIRECT":
                        if (ra[1].toLowerCase() == "refresh") {
                            window.location.href = window.location.href;
                        } else {
                            window.location.href = ra[1];
                        }
                        break;

                    case "SUCCESSFORM":
                        //set $(f).id to the new forms entity
                        $(f).html(ra[1]);
                        break;

                    default:
                        $(f).html(ra[1]);
                        break;
                }
            } else if (ra[0] == "HASERRORS") {
                $(f).html(ra[1]);
                $("#email-error").fadeIn(120);
                $("#emailID").focus();
                timeout = window.setTimeout(closeEmailError, 4000);
            } else {
                //uhoh :( internal errors or something??
            }
            init();
        });
    });

    /* Focus and Exit Form Fields  */
    $("input").focus(function () {
        var ex = $(this).attr("example");
        if (ex == $(this).val()) {
            $(this).val("");
        }
    });
    $("input").blur(function () {
        if ($(this).val() == "") {
            $(this).val($(this).attr("example"));
        }
    });

    /* ================ BUG Tracker ====================== */
    $("#reportBug").live("click", function () {
        serializedForm = "location=" + urlencode(window.location.href);
        var action = "BugReporter.aspx?action=show";
        $.post(action, serializedForm, bugs.showBugForm);
    });

    $("form#bugReporter .submit").live("click", function () {
        var serializedForm = $("#bugReporter").serialize();
        var action = "BugReporter.aspx?action=submit";
        $.post(action, serializedForm, bugs.showBugForm);
        $("form#bugReporter, #bugMask").remove();
    });

    $("form#bugReporter #levelID option").live("click", function () {
        $("form#bugReporter #levelID").attr("style", $(this).attr("style"));
    });

    $("form#bugReporter .bugClose").live("click", function () {
        $("form#bugReporter, #bugMask").remove();
    });

    alternateRows();
});

//Functions

function init() {
    //see if we have and option boxes to restyle
    try {
        oHandler = $(".searchselect").msDropDown().data("dd");
        oHandler.visible(true);
        $("#ver").html($.msDropDown.version);
    } catch (err) { };
    
    	$("input[example], textarea[example]").each(function () {
            if ($(this).val() == '' || $(this).val() == $(this).attr('example')) {
            //$(this).val($(this).attr('example')).removeClass('ss-black');
	    $(this).val($(this).attr('example'))
	    }
	    //else $(this).addClass('ss-black');
        })    
}

function locationCheck() {
    var i = location.href.indexOf('#')
    if (i > 0) {
        var s = location.href.substring(i + 1);
        if (s.substring(0, 4) == "page") {
            s = s.substring(4);
            dbAJAX("searchrefresh.ajax", "?s=" + s, updateResults);
        } else {
            ctab = s;
            $(".catab").hide();
            $("#c_" + s).show();
            $(".tab").removeClass("current");
            $("#tab_" + s).addClass("current");
            alternateRows();
            hto = window.setTimeout(cktab, 250);
        }
    } else {
    if (ctab != "") {
        $(".catab").hide();
        $("#c_overview").show();
        $("#c_journey_overview").show();
        $(".tab").removeClass("current");
        $("#tab_journey_overview").addClass("current");
        $("#tab_overview").addClass("current");
        hto = window.setTimeout(cktab, 250);
    }
    }

}
function cktab() {
    var i = location.href.indexOf('#')
    if (i > 0) {
        var s = location.href.substring(i + 1);
        if (s != ctab) {
            locationCheck();
        }
    }
    hto = window.setTimeout(cktab, 250);
}

function zipTo() {
    $("#homepageWrap").centerInClient();
    $("#homepageWrap").css("top", "0px");
    $(".hp_slide_ledgend").centerInClient();
    $(".hp_slide_ledgend").css("top", "480px");
    var y = ($(window).width() + $(window).scrollLeft()) / 2;
    $(".hp_slide_ledgend").css("left", y - 460 + "px");
    $("#slideshow_hp .slidecontrols").css("left", y - 460 + "px");
}

function closeEmailError() {
    $("#email-error").fadeOut(300);
    
}
function destinationPopup(r) {

    var ra = r.split("||");
    if (ra[0] == "OK") {
        $("#popover").css("width", "880px");
        $("#popover").css("height", "406px");
        $("#popover").css("background-color", "#eff2f4");
        
        $("#popover>div").css("height", "404px");
        $("#popover").html(ra[1]);
        $("#popover").centerInClient();
        $("#modal").show();
        $("#popover").show();
    }

};


function updateResults(r) {
    var ra = r.split("||");
    if (ra[0] == "OK") {
        var bpage = '<li class="bottom pagination">' + $("li.bottom.pagination").html() + '</li>';
        switch (ra[1]) {
            case "p":
                var baseURL = rootURL();
                window.location = baseURL + "#page" + ra[5];
                $(".searchresults .results").html(ra[2]);
                $(".searchresults .results").append(bpage);
                $(".pagelegend>span").html(ra[3]);
                $(".itemcount span").html(ra[4]);
                break;

            case "r":
                $(".searchresults .results").html(ra[2]);
                $(".searchresults .results").append(bpage);
                $(".pagelegend>span").html(ra[3]);
                break;
            case "s":
                $(".searchresults .results").html(ra[2]);
                $(".searchresults .results").append(bpage);
                $(".sortbar .sort").html(ra[3]);
                $(".itemcount span").html(ra[4]);
                $(".pagelegend>span").html(ra[5]);
                break;
            case "c":
                $(".searchresults .results").html(ra[2]);
                $(".searchresults .results").append(bpage);
                $("ul.pagecount").html(ra[3]);
                $(".itemcount span").html(ra[4]);
                $(".pagelegend>span").html(ra[5]);
                break;
            case "f":
                $(".searchresults .results").html(ra[2]);
                $(".searchresults .results").append(bpage);
                $(".itemcount span").html(ra[4]);
                $(".pagelegend>span").html(ra[5]);
                break;
                       }
    }
}

function searchPage(r) {
    window.location = "/search"
}
function moveTile(tilewrapper,i,tilecount) {

    if (tilewrapper === undefined) { tilewrapper = '#promotiles' };
    if (i === undefined) { i = 1 };
    if (tilecount === undefined) { tilecount = 3 };

    if (pta.length > tilecount) {
        ptpointer += i;
        if (ptpointer < 1) { ptpointer = pta.length - 1 };
        if (ptpointer > pta.length - 1) { ptpointer = 1 };

        i = ptpointer;
        var x = 1;
        for (x = 1; x <= tilecount; x++) {
            setTile(x, i, tilewrapper);
            i += 1;
            if (i > pta.length - 1) { i = 1 };
            if (i < 1) { i = pta.length - 1 };
        }
    }
}

function setTile(tileid, index,tilewrapper) {

    if (index > pta.length - 1) { index = 1 };
    if (index <  1) { index = pta.length-1 };
    var za = pta[index].split("|");
    $(tilewrapper + " li.tile" + tileid + " a").css("background", "url(" + za[0] + ") no-repeat scroll");
    $(tilewrapper + " li.tile" + tileid + " a").attr("href", za[3]);
    $(tilewrapper + " li.tile" + tileid + " h4").html(za[1]);
    $(tilewrapper + " li.tile" + tileid + " h5").html(za[2]);
    $(tilewrapper + " li.tile" + tileid + ">img").attr("src",za[0]);

}

function alternateRows() {
    $(".pricetable tbody tr").removeClass("tra trb");
    $(".pricetable tbody tr").each(function (i) {
        if (isEven(i)) {
            $(this).addClass("tra");
        } else {
            $(this).addClass("trb");
        }
    });

}

function rootURL() {
    var baseURL = "";
    var i = location.href.indexOf('#');
    if (i > 0) {
        baseURL = location.href.slice(0, location.href.indexOf('#'));
    } else {
        baseURL = location.href;
    }
    return baseURL;
}

//Bug Reporting
bugs.showBugForm = function (r) {
    $("form#bugReporter, #bugMask").remove();
    $("body").append(r);

    $("form#bugReporter #levelID option").css({ "color": "white","width":"100%"});
    $("form#bugReporter #levelID option:eq(0)").css({"color": "black", "background-color": "white"});
    $("form#bugReporter #levelID option:eq(1)").css("background-color", "red");
    $("form#bugReporter #levelID option:eq(2)").css("background-color", "orange");
    $("form#bugReporter #levelID option:eq(3)").css("background-color", "gold");
    $("form#bugReporter #levelID option:eq(4)").css("background-color", "blue");
    $("form#bugReporter #levelID option:eq(5)").css("background-color", "green");
    $("form#bugReporter #levelID").attr("style", $("form#bugReporter #levelID option:selected").attr("style"));
}
