/**
/**
*	Interactive Poster Utilities 1.0
*
*	Mark Lindros, Oracle Corporation
*	Last Modification: 07/15/2012
*
*/

//Global variables for convenience functions
var hotspotdata = null;
var subsystem = null;
var currentTab = null;

/**
 *    Global handler to initialize poster items
 *    Using window.load instead of document.ready because document.ready doesn't allow all images
 *    to load initially before executing all our code. This causes all image calculations and
 *    layouts to fail miserably.
 */
$(window).load(function() {
    $.ajaxSetup({ cache: false });

	//Initialize subsystem variable to first .map-viewport element
	subsystem = "#" + $('div.map-viewport:first').attr("id");
	
	//If user resizes browser window, then adjust hotspot window height
    $(window).resize(function() {
        adjustHotSpotHeight();
    });

	//Initialize Mapz plug-in for all images
	$('div.map-viewport').each(function() {
	    $(this).children('.draggable_map').each(function(){
			$(this).mapz({ zoom : true, createmaps : true, mousewheel : true });
		});	
	});

	//Handle hotspot click events: This is triggered in Mapz
    $(document).bind("displayhotspot", function(e, hsID) {
        displayHotSpot(hsID);
	});
	
	//Initialize image map highlight plug-in
	$('.current-level').maphilight();

    //Initialize nested image management
    init_nested_images();

	//Initialize clickable tabs at the top
	init_tabs();

    // Listen for click on home page red boxes (sort of like tabs but we don't track the current one
    $('ul.homelinks a,ul.homedesc a').click(function() {
        var clicked = $(this).attr('href');
        //Find the matching tab and act just like the tab was clicked by triggering its routine
        //This causes the content to display, and the tabs to function properly
        $('ul.tabs').find('a').each(function() {
            if ($(this).attr('href') == clicked) {
                $(this).trigger('click');
            }
        });
        // No follow.
        this.blur();
        return false;
    });

    //Calculate hotspot div height based on map-viewport height and hotspot-data padding
    adjustHotSpotHeight();
	initBgProcesses();
});


/**
* This code ensures that the hotspot-data div and map-viewport div are the same height. They
* can be different because both are based on % of screen size and we use a padding on the hotspot-data
* div to create a margin for text displayed for hotspots. This code is called when the browser first
* loads the page, and when the user resizes the browser. Also when the user switches between diagrams.
*/
function adjustHotSpotHeight(){
    //We must get the current subsystem of the diagram currently showing. We can't use
    //getCurrentSubsystem directly because it changes the global subsystem variable which may
    //currently be set for a particular selected hotspot. This subsystem may not have an image associated
    //with it, or have a different image size associated with it and cause the hotspot size to
    //calculate incorrectly. This wouldn't be important except for cases where the user
    //resizes or maximizes/minimizes the browser after selecting a hotspot.
    //For this reason, we must avoid setting the global variable.
    var sub;
    getCurrentTab();
    $(currentTab).find('ul.breadcrumbs a').each(function() {
        if ($(this).hasClass('current')) { sub = $(this).attr('href'); }
    });

    //Only adjust hotspot and other items if they exist on the current tab
    if (sub) {
        var curhs = $(currentTab).find('.hotspot-data');
        var vp_height = parseInt($(sub).height());
        var pad = parseInt($('.hotspot-data').css("padding-bottom").replace("px", ""));
        var newheight = vp_height - pad;
        $('.hotspot-data').css({"max-height":newheight});
        $('.hotspot-data').height(newheight);

        //Let's also properly calculate the location of the "View Subsystem" button while we're at it
        var x = curhs.position().left;
        var y = curhs.position().top;
        var hswidth = curhs.width();
        var imgwidth = 143; //$('.subsystem img').width();
        $('.subsystem').css({
            top: y - 12 +"px",
            left: x + (hswidth / 2) - (imgwidth / 2) + 15 +"px"
        });
    }
}

/**
 * This function writes the instructions for all hotspot data windows. It is called
 * in different ways in the script so it takes an argument to make sure the proper
 * data window is written to. The first time it is called is in a loop where all hotspot data
 * windows in the poster are initialized. Subsequent times this function is called is whenever
 * a subsystem is viewed or a tab/breadcrumb are clicked.
 */
function writeHotSpotInstructions(hsdatawindow) {
    getCurrentSubsystem();
    var pdfFileName = "pdf/" + subsystem.replace("#", "") + ".pdf";
    $(hsdatawindow).html('<div class="instructions">' +
                        '  <h2 align="center">INSTRUCTIONS</h2>' +
                        '  <p>Use the mouse to drag or arrows to move the image on the left.</p>' +
                        '  <p>Use the mouse wheel or arrow up and down keys to zoom the image in or out.</p>' +
                        '  <p>Click a hotspot on the image to see more details related to that feature.</p>' +
                        '</div><p align="center">' +
                        '<div class="pdflink">' +
                        '  <a href="' + pdfFileName + '"><img src="img/pdf.jpg" alt=""/></a>' +
                        '</div>');
}

/**
*    This function will read the XML source data file and find the
*    hotspot element with the name that matches the id.
*/
function displayHotSpot(id){
	//First, get current interactive name (should be the same as map-viewport id with - for spaces)
    //FYI: getCurrentSubsystem() implicitly calls getCurrentTab() which sets global currentTab
    getCurrentSubsystem();
    var interactiveName = subsystem.replace(/-/g, " ").replace("#", "");
    $.ajax({
		type:"GET",
		url:"xml/poster.xml",
		dataType:"xml",
        success:function (xml) {
            var interactive = $(xml).find('interactive[name="' + interactiveName + '"]');
            var hotspot = $(interactive).find('hotspot[name="' + id + '"]');
            /* If there is a subsystem diagram:
             * - Set var to subsystem name (id) for mapping
             * - Show View Subsystem button
             * - Key off of XML hotspot attribute: subsystem which we will map to the breadcrumb href
             * Also, don't show View Subsystem button if already in that subsystem
             */
            subsystem = "#" + $(hotspot).attr("subsystem").replace(/ /g, "-"); //From XML
            var hasNested = $(currentTab).find('ul.breadcrumbs a[href="' + subsystem + '"]');
            if (($(hasNested).length > 0) &&
                (!$(hasNested).hasClass('current'))) {
                $('.subsystem').show();
            } else {
                $('.subsystem').hide();
            }

            getHotspotDataWindow(); //Get/Set the correct hotspot window for this tab
			$(hotspotdata).scrollTop(0);
            $(hotspotdata).html('<h2>' + $(hotspot).attr("name") + '</h2>');
            $(hotspotdata).append('<p>' + $(hotspot).attr("desc") + '</p>');
            if ($(hotspot).first().find('doc-refs').children().length > 0) {
                $(hotspotdata).append('<p><em>See the following documentation links for more information:</em></p>');
                $(hotspot).first().find('doc-refs').children().each(function () {
                    $(hotspotdata).append('<p><img src="img/bullet.jpg"/>&nbsp;<a href='
                        + $(this).attr("url") + ' target="_blank">' + $(this).attr("title") + '</a></p>');
                });
            }
        }
    });
}


/**
 * This function initializes all the tabs rendered by the poster. It should ensure
 * that the first tab is displayed as the current tab, and all other tabs are hidden.
 */
function init_tabs() {
	// Does element exist?
	if (!$('ul.tabs').length) {
		//If not, exit.
		alert("POSTER ERROR: There are no tabs defined. See poster.js: init_tabs()");
		return;
	}

	//If there is only one interactive defined, then don't show tabs
	if ($('ul.tabs').children().length == 1) {
      $('ul.tabs').hide();
    }

    //If there are 2 interactives, and one of them is the home tab, then don't show tabs or the home page
    if ($('ul.tabs').children().length == 2) { //for now assume 1 is Home
        //Show second element and hide others... also hide tabs
        $('div.tab_content:eq(1)').show().siblings('div.tab_content').hide();
        $('ul.tabs').find('a:eq(1)').addClass('current');
        $('ul.tabs').hide();
    } else {
        // Reveal initial content area(s).
        $('div.tab_content:first').show().siblings('div.tab_content').hide();
        $('ul.tabs').find('a:first').addClass('current');
    }

	// Listen for click on tabs.
	$('ul.tabs a').click(function() {
		// If not current tab.
		if (!$(this).hasClass('current')) {
			// Change the current indicator.
			$(this).addClass('current').parent('li').siblings('li').find('a.current').removeClass('current');

			// Show target, hide others.
			$($(this).attr('href')).show().siblings('div.tab_content').hide();

            //DO NOT REMOVE THIS LINE: This is an important custom JQuery event to
            //workaround an issue with the image map constraints not working correctly
            //when first engaged. This occurred after creating the home page and cannot
            //figure out why. This fixes things.
            $('.draggable_map').trigger('constraint');
			$(window).trigger('resize');
            //Set subsystem based on current tab, then id of currently showing image
            //and adjust hotspot height and instructions
            getCurrentSubsystem();
			$('.subsystem').hide(); //Hide view subsystem button because new instructions are displayed
            getHotspotDataWindow();
            writeHotSpotInstructions($(hotspotdata));
            adjustHotSpotHeight();
		}

		// No follow.
		this.blur();
		return false;
	});
}


function init_nested_images() {
	$('.subsystem').hide();
	//Reveal initial Mapz image and hide the rest
	$('div.tab_content').each(function() {
		$(this).find('div.map-viewport:first').show().siblings('div.map-viewport').hide();
		$(this).find('ul.breadcrumbs').find('a:first').addClass('current');
		//Only show first breadcrumb
		$(this).find('ul.breadcrumbs').find('li:first').show().siblings('li').hide();
	});

    //Init all initial hotspot data windows with instructions
    $('div.hotspot-data').each(function() {
        getCurrentSubsystem();
        var pdfFileName = "pdf/" + subsystem.replace("#", "") + ".pdf";
        writeHotSpotInstructions($(this));
    });
	
	// Listen for click on links for subsystem breadcrumbs
	$('ul.breadcrumbs a').click(function() {
		$('.subsystem').hide(); //To automatically not show the View Subsystem button when going into the nested diagram
		update_nested_images(this);
		return false;
	});
	
	// Listen for click on subsystem links in hotspot data and map to breadcrumb
	$('.subsystem').click(function() {
		$('.subsystem').hide(); //To automatically not show the View Subsystem button when going into the nested diagram
		//Find matching breadcrumb with same href as subsystem name and pass to nested image update function
        getCurrentTab();
        update_nested_images($(currentTab).find($('ul.breadcrumbs a[href="' + subsystem + '"]')));
		return false;
	});
}


/**
 * Purposely made this a separate function rather than inline so that it can
 * be called either by a click handler, or by other functions directly when needed
 * for more control. This function manages nested image & breadcrumb display and usage.
 */
function update_nested_images(breadcrumb) {
	// If not current image
	if (!$(breadcrumb).hasClass('current')) {
		
		//Determine the subsystem of the currently clicked breadcrumb
		subsystem = $(breadcrumb).attr('href');

		// Change the current breadcrumb indicator.
		$(breadcrumb).addClass('current').parent('li').siblings('li').find('a.current').removeClass('current');

		// Show target image map, hide others.
		$($(breadcrumb).attr('href')).show().siblings('div.map-viewport').hide();
		
		//Only show top layer through current layer breadcrumbs
		$(breadcrumb).parent('li').show();

        //Loop through current breadcrumb list and hide the ones after the "current" crumb
		var trigger = 0;
        getCurrentTab();
		$(currentTab).find('ul.breadcrumbs a').each(function() {
			if (trigger == 1) {
				$(this).parent('li').hide();
			}
			if ($(this).hasClass('current')) {
				trigger = 1;
			}
		});

        $('.draggable_map').trigger('constraint'); //causes all maps to rebuild constraints to make sure they view properly
        writeHotSpotInstructions($(hotspotdata));
        $(window).trigger('resize');
		adjustHotSpotHeight();
    }
	
	// No follow.
	this.blur();
	return false;
}


function getHotspotDataWindow() {
    $('ul.tabs').find('a').each(function() {
		if ($(this).hasClass('current')) {
			hotspotdata = $($(this).attr('href')).find("div.hotspot-data");
		}
	});
}

function getCurrentTab() {
    $('ul.tabs').find('a').each(function() {
        if ($(this).hasClass('current')) {
            currentTab = $($(this).attr('href'));
        }
    });
}

function getCurrentSubsystem() {
    getCurrentTab();
    $(currentTab).find('ul.breadcrumbs a').each(function() {
        if ($(this).hasClass('current')) { subsystem = $(this).attr('href'); }
    });
}


/*
 function processXML(){
 $.ajax({
 type:"GET",
 url:"xml/poster.xml",
 dataType:"xml",
 success:function(xml){
 $(xml).find('interactives').children().each(function(){
 var curNode = $(this);
 if (curNode.attr("style") == "diagram") {
 createHotSpotsFromXml(curNode);
 }
 });
 }
 });
 }*/


/**
 *	This function will read the XML source data file and create the HTML
 *	image map and area hotspots dynamically for the first loaded image

 function createHotSpotsFromXml(interactive){
 $(interactive).find('hotspots').children().each(function(){
 var curNode = $(this);

 if (curNode.attr("coords") != "0,0,0,0") {
 $('#html-map').append('<area class="hotspot" shape="' + curNode.attr("shape") + '" '
 + 'coords="' + curNode.attr("coords") + '" '
 + 'href="#" id="' + curNode.attr("name") + '" />');
 }
 });
 }
 */