var playerObj = null;

// ***********************************
// Everything starts here
// ***********************************
$().ready(function() {

    // Variable Data
    switch (location.pathname.toLowerCase()) {
        // The contact/complete page uses a "thank you" message      
        case "/contact/complete":
        case "/contact/complete.aspx":
            setDefaultWelcome("Thank you for visiting", "Guthrie's Physician Recruitment Portal");
            break;
        // The contact page has a specific message      
        case "/contact":
        case "/contact.aspx":
            setDefaultWelcome("We're looking", "forward to speaking with you");
            break;
        // All other pages use the variable data, if present, otherwise a generic welcome message      
        default:
            try {
                var vardata = $.cookie('campaignUserInfo');
                if (vardata != null) {
                    var userInfo = vardata.split("&");
                    var firstname = userInfo[0].split("=")[1];
                    var lastname = userInfo[1].split("=")[1];
                    var credentials = "";
                    if (userInfo.length > 2) {
                        credentials = ", " + userInfo[2].split("=")[1];
                    }
                    if ((firstname != "") && (lastname != "")) {
                        $("li.welcome", "#var-data").text("Welcome");
                        $("li.variableDR", "#var-data").text(firstname + " " + lastname + credentials);
                    }
                    else {
                        setDefaultWelcome("Welcome to", "Guthrie's Physician Recruitment Portal");
                    }
                }
                else {
                    setDefaultWelcome("Welcome to", "Guthrie's Physician Recruitment Portal");
                }
            }
            catch (err) {
                setDefaultWelcome("Welcome to", "Guthrie's Physician Recruitment Portal");
            }
            break;
    }

    // ***********************************
    // Set up BOTR video links
    // ***********************************

    var conversion = "60354";
    var player = "38307";

    // Main video links
    $('li a[href*="bitsontherun."]', "#videos").each(function() {
        // Grab video ID from the url
        var videoID = $(this).attr('href').match(/\/preview\/(.+)+/)[1];
        // Get the first part for the image reference
        var videoKey = videoID.match(/([^-]+)/)[1];

        // Set the thumbnail icon on the link and embed the video on click.
        $(this).html("<img src='http://content.bitsontherun.com/thumbs/" + videoKey + "-120.jpg' /><h5>" + $(this).text() + "</h5>").click(function() {
            if (playerObj != null) {
                playerObj.sendEvent("LOAD", "http://content.bitsontherun.com/videos/" + videoKey + "-" + conversion + ".mp4");
                playerObj.sendEvent("PLAY", "true");
            }
            logAction("Watch", $(this).text(), location.pathname + "/" + videoKey, "Videos");
            return false;
        });
        $(this).qtip({
            content: "Watch '" + $(this).text() + "'", show: { delay: 0 }, position: { corner: { tooltip: 'bottomMiddle', target: 'topMiddle' }, adjust: { x: 0, y: -5} }, style: { width: 200, background: '#FFE580', color: '#010066', fontFamily: 'Arial, Sans-Serif', fontSize: '12px', lineHeight: '16px', fontWeight: 'bold', textAlign: 'center', border: { width: 6, radius: 5, color: "#CC6600" }, tip: { corner: 'bottomMiddle', color: '#CC6600'} }
        });
    });

    // Related video links
    $('li a[href*="bitsontherun."]', "#sidevideos").each(function() {
        // Grab video ID from the url
        var videoID = $(this).attr('href').match(/\/preview\/(.+)+/)[1];
        // Get the first part for the image reference
        var videoKey = videoID.match(/([^-]+)/)[1];

        // Set the thumbnail icon on the link and embed the video on click.
        $(this).html("<img src='http://content.bitsontherun.com/thumbs/" + videoKey + "-120.jpg' /><h5>" + $(this).text() + "</h5>").click(function() {
            if (playerObj != null) {
                playerObj.sendEvent("LOAD", "http://content.bitsontherun.com/videos/" + videoKey + "-" + conversion + ".mp4");
                playerObj.sendEvent("PLAY", "true");
            }
            logAction("Watch", $(this).text(), location.pathname + "/" + videoKey, "Videos");
            return false;
        });
        $(this).qtip({
            content: "Watch '" + $(this).text() + "'", show: { delay: 0 }, position: { corner: { tooltip: 'rightMiddle', target: 'leftMiddle' }, adjust: { x: 0, y: 0} }, style: { width: 200, background: '#FFE580', color: '#010066', fontFamily: 'Arial, Sans-Serif', fontSize: '12px', lineHeight: '16px', fontWeight: 'bold', textAlign: 'center', border: { width: 6, radius: 5, color: "#CC6600" }, tip: { corner: 'rightMiddle', color: '#CC6600'} }
        });
    });

    // ***********************************
    // Accordions:
    // ***********************************

    // On the map page
    $("#map-points-list").accordion({ event: 'click', header: 'h3', autoheight: false });

    // Let's talk
    $(".letsTalk").qtip({
        content: "Contact a recruiter.", show: { delay: 0 }, position: { corner: { tooltip: 'rightMiddle', target: 'leftMiddle' }, adjust: { x: -10, y: 0} }, style: { width: 150, background: '#FFE580', color: '#010066', fontFamily: 'Arial, Sans-Serif', fontSize: '12px', lineHeight: '16px', fontWeight: 'bold', textAlign: 'center', border: { width: 6, radius: 5, color: "#CC6600" }, tip: { corner: 'rightMiddle', color: '#CC6600'} }
    });

    // Set up Tabs
    $('#tabs').tabs().find("li a").click(function() {
        logAction("View Tab", $(this).text(), location.pathname, "Content");
    });

    // ***********************************
    // Highslides:
    // ***********************************

    // Global settings
    hs.graphicsDir = '/App_Themes/Default/highslide/graphics/';
    hs.outlineType = 'rounded-white';
    hs.showCredits = false;

    // Add Highslide to interactives
    $("li a", "#interactives").each(function() {
        $(this).click(function() {
            logAction("Open", $(this).text(), $(this).attr("href"), "Interactives");
            if (playerObj != null) {
                playerObj.sendEvent("PLAY", "false");
            }
            return hs.htmlExpand(this, { objectType: 'iframe', objectLoadTime: 'after', align: 'center', outlineType: 'rounded-white', preserveContent: false, width: 820, height: 645, dimmingOpacity: 0.75, allowSizeReduction: false });
        });
        $(this).parents().filter("li").qtip({
            content: "Explore '" + $(this).text() + "'", show: { delay: 0 }, position: { corner: { tooltip: 'bottomMiddle', target: 'topMiddle' }, adjust: { x: 0, y: 0} }, style: { width: 200, background: '#FFE580', color: '#010066', fontFamily: 'Arial, Sans-Serif', fontSize: '12px', lineHeight: '16px', fontWeight: 'bold', textAlign: 'center', border: { width: 6, radius: 5, color: "#CC6600" }, tip: { corner: 'bottomMiddle', color: '#CC6600'} }
        });
       });

       // Add Highslide to interactives on sidebar
       $("li a", "#interactivenav").each(function() {
       	$(this).click(function() {
       		logAction("Open", $(this).text(), $(this).attr("href"), "Interactives");
       		if (playerObj != null) {
       			playerObj.sendEvent("PLAY", "false");
       		}
       		return hs.htmlExpand(this, { objectType: 'iframe', objectLoadTime: 'after', align: 'center', outlineType: 'rounded-white', preserveContent: false, width: 820, height: 645, dimmingOpacity: 0.75, allowSizeReduction: false });
       	});
       	//$(this).parents().filter("li").qtip({
       	//	content: "Explore '" + $(this).text() + "'", show: { delay: 0 }, position: { corner: { tooltip: 'bottomMiddle', target: 'topMiddle' }, adjust: { x: 0, y: 0} }, style: { width: 200, background: '#FFE580', color: '#010066', fontFamily: 'Arial, Sans-Serif', fontSize: '12px', lineHeight: '16px', fontWeight: 'bold', textAlign: 'center', border: { width: 6, radius: 5, color: "#CC6600" }, tip: { corner: 'bottomMiddle', color: '#CC6600'} }
       	//});
       });

    // Add Highslide to Position Details link
    $("a", "#position-details").each(function() {
        $(this).click(function() {
            logAction("View", "Position Details", location.pathname, "Positions");
            return hs.htmlExpand(this, { objectType: 'iframe', objectLoadTime: 'after', align: 'center', outlineType: 'rounded-white', preserveContent: false, width: 820, height: 645, dimmingOpacity: 0.75, allowSizeReduction: true });
        });
    });

    // Add Highslide to the links in the header
    $("a[href^='http://www.guthrie']", "#header").each(function() {
        $(this).click(function() {
            logAction("External Link", $(this).text(), $(this).attr("href"), "Links");
            return hs.htmlExpand(this, { objectType: 'iframe', objectLoadTime: 'after', align: 'center', outlineType: 'rounded-white', preserveContent: false, width: 800, height: $(window).height() - 200, dimmingOpacity: 0.5, allowSizeReduction: true });
        });
    });

    // Add Highslide to the external links in the tabs - these are not be added to flash interactives
    $("a:not([href^='http://guthriehosting.'])", "#tabs").filter("a[href^='http://']").qtip({
        content: "Preview Website...", show: { delay: 0 }, position: { corner: { tooltip: 'rightBottom', target: 'leftMiddle' }, adjust: { x: -10, y: 0} }, style: { width: 140, background: '#FFE580', color: '#010066', fontFamily: 'Arial, Sans-Serif', fontSize: '12px', fontWeight: 'bold', border: { width: 6, radius: 5, color: "#CC6600" }, tip: { corner: 'rightBottom', color: '#CC6600'} }
    }).each(function() {
        $(this).click(function() {
            logAction("External Link", $(this).text(), $(this).attr("href"), "Links");
            return hs.htmlExpand(this, { objectType: 'iframe', objectLoadTime: 'after', align: 'center', outlineType: 'rounded-white', preserveContent: false, width: findBestWindowWidth(1030), height: $(window).height() - 200, dimmingOpacity: 0.5, allowSizeReduction: false });
        });
    });

    // Add Highslide to the interactives in the tabs
    $("a[href^='http://guthriehosting.']", "#tabs").each(function() {
        $(this).click(function() {
            logAction("Open", $(this).attr("title"), $(this).attr("href"), "Interactives");
            return hs.htmlExpand(this, { objectType: 'iframe', objectLoadTime: 'after', align: 'center', outlineType: 'rounded-white', preserveContent: false, width: 820, height: 645, dimmingOpacity: 0.75, allowSizeReduction: false });
        });
    });

    // ***********************************
    // Other Action Logging
    // ***********************************

    // Track external links that aren't to bitsontherun.com
    //    $("a[href^='http://']").click(function() {
    //        if ($(this).attr("href").indexOf("bitsontherun.com") == -1) {
    //            logAction("External Link", $(this).text(), $(this).attr("href"), "Links");
    //        }
    //    });

    // Expand the position links
    $("li", "#positions").click(function() {
        document.location.href = $(this).find("a").attr("href");
    });

});

// **************************************************************************************
// Set's the two variale data spots at the top of the page
// **************************************************************************************
function setDefaultWelcome(text1, text2) {
    $("li.welcome", "#var-data").text(text1);
    $("li.variableDR", "#var-data").text(text2);
}

// **************************************************************************************
// Find an optimal window width based on screen size
// **************************************************************************************
function findBestWindowWidth(width) {
    return ($(window).width() < width) ? $(window).width() - 75 : width;
}

// **************************************************************************************
// Function that is called by BOTR videos when they are ready
// **************************************************************************************
function playerReady(obj) {
    playerObj = document.getElementById(obj['id']);
    switch (location.pathname.toLowerCase()) {
        // If on the homepage, autoplay the video
        case "/positions/guthrie-physicians":
        case "/":
        case "/default.aspx":
            setTimeout('playerObj.sendEvent("PLAY", "true")', 1000);    
            break;
    }
};

// **************************************************************************************
// Adds points to the map
// **************************************************************************************
function addPoints() {
    if (GBrowserIsCompatible()) {
        var hPoints = new Hashtable();
        var bounds = new GLatLngBounds();

        // Add a marker for each point using the indicated lat/long/icon/etc...
        // Store the marker in a hashtable so we can get at it later
        $("ul.points li.point").hide().each(function() {
            var lat = $(this).find("ul li.lat").text();
            var lng = $(this).find("ul li.lng").text();
            var htmlContent = $(this).find("div.popup").html();
            var pinIcon = $(this).find("img.icon").attr("src");
            var point = new GLatLng(lat, lng);
            var marker = createMarker(point, pinIcon, htmlContent);
            hPoints.put($(this).attr("id"), marker);
            map.addOverlay(marker);
            bounds.extend(point);
        });

        map.setCenter(bounds.getCenter());
        map.setZoom(map.getBoundsZoomLevel(bounds));

        // Add a click event to each of the location points so the info window is displayed
        $("ul.pointslist li.point").each(function() {
                $(this).click(function() {
                logAction("Click Map Location", $(this).children("h4").text(), location.pathname, "Maps");
                var marker = hPoints.get($(this).attr("id").replace("loc_", "point_"));
                map.setCenter(marker.getLatLng(), 15);
                marker.openInfoWindowHtml($(this).find("div.popup").html());
            }).find("div.popup").hide();
        });
    }
}

// **************************************************************************************
// Creates a map marker object
// **************************************************************************************
function createMarker(point, pinIcon, htmlContent) {
    // Create a custom icon for this point using our icon class
    var customIcon = new GIcon(G_DEFAULT_ICON);
    if (pinIcon != null) {
        customIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        customIcon.image = pinIcon;
        customIcon.iconSize = new GSize(20, 27);
        //customIcon.shadowSize = new GSize(54, 30);
        //customIcon.iconAnchor = new GPoint(9, 34);
        //customIcon.infoWindowAnchor = new GPoint(16, 2)
        //customIcon.infoShadowAnchor = new GPoint(18, 25);
    }

    // Set up our GMarkerOptions object
    markerOptions = { icon: customIcon };
    var marker = new GMarker(point, markerOptions);

    // Hook up event for the info window
    GEvent.addListener(marker, "click", function() {
        try {
            logAction("Click Map Icon", htmlContent.match(/<h4>(.+)<\/h4>/)[1], location.pathname, "Maps");
        }
        catch (err) {
        }
        marker.openInfoWindowHtml(htmlContent);
    });

    return marker;
}
