﻿//AttachEvent(window, "onload", ScrollToCriteria);

var avgGoalSeries = 15;
var avgTargetSeries = 7;
var avgIndicatorSeries = 2;

var linkOffsetY = 25;
var mouseX, mouseY;
var divPopup;
var popupCountdown;
var popupTimer;

/*
 * Scroll to the critera pane when the window loads
 */
function ScrollToCriteria() {
//    var divCriteria = document.getElementById("divCriteria");
//    if (divCriteria) {
//        var pos = FindPosition(divCriteria);
//        scroll(pos[0], pos[1]);
//    }
}

/*
 * Invoked when the user's country selection changes
 */
function OnCountriesChanged() {
    // Delegate to the SeriesExplorer to find the selected series
    GetSelectedIds(OnSeriesSelectionChanged);
}

/*
 * Invoked when the user's selection has changed
 */
function OnSeriesSelectionChanged(goals, targets, indicators, series) {
    // Find out how many countries are selected
    var selectedCountries = GetSelectedCountries().split(",");
    var countryCount = selectedCountries.length;
    var isAllCountriesSelected = selectedCountries[0] == 0;
    
    // Guess how many series are selected
    var seriesCount = 
        (goals ? goals.split(",").length * avgGoalSeries : 0) +
        (targets ? targets.split(",").length * avgTargetSeries : 0) +
        (indicators ? indicators.split(",").length * avgIndicatorSeries : 0) +
        (series ? series.split(",").length : 0);
        
    // If no series selected, it means the root node - all - is selected
    if (seriesCount == 0) seriesCount = 124;
    
    // Display options
    var cbxGroup = document.getElementById("cbxGroup");
    var rbIndicator = document.getElementById("rbIndicator");
    var rbCountry = document.getElementById("rbCountry");
    
    // Adjust default display options based on the user's current selection
    cbxGroup.checked = !isAllCountriesSelected && countryCount < 7;
    rbIndicator.checked = isAllCountriesSelected || countryCount > 1;
}

/*
 * Fetch data associated with the nominated goals, targets, indicators, and series.
 */
function FetchData(goals, targets, indicators, series) {
    var selectedCountries = GetSelectedCountries();
    if (selectedCountries == "" || selectedCountries == null) {
        if (selectedCountries == "") {
            alert(label_Select1Country);
        }
        
        return;
    }
    
    ShowTab(document.getElementById("aSeriesData"), "DataTab");
    // Collapse the search criteria div, and display the data one
    //SetPanelVisible("divCriteria", false);
    SetPanelVisible("divData", true);
    
    // Display the "Loading data" message
    var divData = document.getElementById("divData");
    divData.innerHTML = GetProgressImage(label_Loading, null, "margin:80px;text-align:center;");

    // Determine what to group the data by
    var rbIndicator = document.getElementById("rbIndicator");
    var groupBy = rbIndicator.checked ? "Indicator" : "Country";
    
    // Should the CCM data nature be shown? And should we group series for the same indicator
    var cbxNature = document.getElementById("cbxNature");
    var cbxGroup = document.getElementById("cbxGroup");
    
    if (xmlHttp) {
        xmlHttp.abort();
    }
    
    var url = "Handlers/DataHandler.ashx?ServiceName=FetchData";
    url += BuildQueryStringParam("Countries", selectedCountries);
    url += BuildQueryStringParam("Goals", goals);
    url += BuildQueryStringParam("Targets", targets);
    url += BuildQueryStringParam("Indicators", indicators);
    url += BuildQueryStringParam("Series", series);
    url += BuildQueryStringParam("GroupBy", groupBy);
    url += BuildQueryStringParam("ShowNature", cbxNature.checked);
    url += BuildQueryStringParam("GroupSeries", cbxGroup.checked);

    SendXmlHttpRequest(url, OnDataFound, OnError);
}

/*
 * Event callback invoked after the FindSeries XmlHttpRequest has returned
 */
function OnDataFound(responseText) {
    var divData = document.getElementById("divData");
    divData.innerHTML = GetProgressImage(label_Rendering, null, "margin:80px;text-align:center;");

    divData.innerHTML = responseText && responseText != ""
        ? responseText
        : BuildMessageBox(label_NoResults, "warning");

    DiscardXmlHttpRequest();
}

/*
 * Invoked if an error is raised during an XmlHttpRequest
 */
function OnError(errorText) {
    var divData = FindElement("div", "divData");
    divData.innerHTML = BuildMessageBox(errorText, "error");
}

/*
 * Displays country data information for the nominated symbol
 */
function ShowCountryData(link, symbol) {
    if (divPopup || popupTimer) {
        HidePopup();
    }
    
    // Add the mouse out link
    link.onmouseout = OnPopupMouseOut;

    var mousePos = FindMousePosition(link);
	mouseX = mousePos[0];
	mouseY = mousePos[1];

    if (xmlHttp) {
        xmlHttp.abort();
    }
    
    var url = "Handlers/MetadataHandler.ashx?Service=FetchCountryData&Symbol=" + symbol;
    SendXmlHttpRequest(url, OnCountryDataFound, OnError);
}

/*
 * Display country data when retrieved from the database
 */
function OnCountryDataFound(responseText) {
    divPopup = document.createElement("div");
    divPopup.onmouseover = OnPopupMouseOver;
    divPopup.onmouseout = OnPopupMouseOut;
    divPopup.className = "Popup";

    // Reposition according to the link    
    PositionDiv(divPopup, 400, 200);

    // Insert the profile
    divPopup.innerHTML = responseText;
	document.getElementsByTagName("body")[0].appendChild(divPopup);
}

/*
 * Find the current x, y position of the mouse
 */
function FindMousePosition(link) {
    if (link.offsetParent) {
        for (var posX = 0, posY = 0; link.offsetParent; link = link.offsetParent ) {
            posX += link.offsetLeft;
            posY += link.offsetTop;
        }
    
        return [posX, posY];

    } else {
        return [link.x, link.y];
    }
}

/*
 * Positions the nominated div around the current link
 */
function PositionDiv(element, width, height) {
    // Move the div to the right co-ordinates
	element.style["left"] = (mouseX - width / 2) + "px";
	element.style["top"] = (mouseY + linkOffsetY) + "px";
		
	// Adjust left if we're off the screen
	if (window.innerWidth && ((mouseX + width) > window.innerWidth)) {
        element.style["left"] = (window.innerWidth - width - linkOffsetY) + "px";
        
	} else if (document.body.scrollWidth && ((mouseX + width) > document.body.scrollWidth)) {
        element.style["left"] = (document.body.scrollWidth - width - linkOffsetY) + "px";
	}
	
	if ((mouseX - width / 2) <= 10) {
	    element.style["left"] = (mouseX + 10) + "px";
	}

	// Adjust height if we're off the screen
	var scrollY = GetScrollTop();
	if ((mouseY - height - linkOffsetY - 1) < scrollY) {
	    element.style["top"] = (mouseY + linkOffsetY) + "px";
	}
}

/*
 * Work out how high up the page the user has scrolled
 */
function GetScrollTop() {
	if (window.innerHeight) {
        return window.pageYOffset;
	
	} else if (document.documentElement && document.documentElement.scrollTop) {
		return document.documentElement.scrollTop;
		
	} else if (document.body) {
        return document.body.scrollTop;
	}
	
	return 0;
}

/*
 * Invoked when the user moves the mouse over the popup
 */
function OnPopupMouseOver() {
    if (popupTimer) {
        clearInterval(popupTimer);
        popupTimer = null;
    }
}

/*
 * Event handler invoked when the mouse rolls out from the popup or the popup link
 */
function OnPopupMouseOut() {
    popupCountdown = 2;
    popupTimer = setInterval(function() {
        popupCountdown--;
        
        if (popupCountdown <= 0) {
            HidePopup();
        }
    }, 250);
}

/*
 * Hides the profile on mouseout
 */
function HidePopup() {
    // Clear the timer if needed
    if (popupTimer) {
        clearInterval(popupTimer);
        popupTimer = null;
    }
    
    // Abort the request if the user has moved their mouse away from the link before the profile was shown
    if (xmlHttp) {
        xmlHttp.abort();
    }
    
    if (divPopup) {
        divPopup.style["display"] = "none";
	    document.getElementsByTagName("body")[0].removeChild(divPopup);
        divPopup = null;
    }
}