﻿
var disabled = true; //Used to indicate if the state checkboxes are disabled

/*
	Returns the datacenter id of the state
*/
function GetStateId(stateName)
{
	return jQuery('#cb_'+stateName+' input')[0].id.split('_')[3];
}


/*
	Indicator selection changed
*/
function indicatorChanged() {
    
	var count = GetSelectedCount('indicator');
	
	if (count > 0)
	{
		EnabledCheckBoxes('years',true,false); // Enables all year checkboxes
	}
	else
	{
		//The value in the indicator dropdown is no good, disable everything
		EnabledCheckBoxes('years',false,true); // Disables all year checkboxes
		EnabledCheckBoxes('states',false,true); // Disables all year checkboxes		
	}
}

/*
	Is called if any year checkbox is clicked
*/
function yearTicked()
{
	var count = GetSelectedCount('years');
	
	if(count > 0)
	{
		//runs through the state checkbox logic
		//It should enable all states
		StateTicked();
	}
	else
	{
		//No years were selected so disable the state
		//boxes
		EnabledCheckBoxes('states',false,true);
		disabled = true;
	}
}

function toggleStates(link) {

    if (disabled) {
        return;
    }

    // True if they are all checked, false otherwise
    var toggled = link.innerHTML == 'Clear';
    
    // First flip the toggle, then set the check box to the toggle state    
    var i = 0;
    jQuery('.states input').each(function(idx, state) { state.checked = !toggled; });

    // Change the link text
    link.innerHTML = toggled ? 'All' : 'Clear';
}

/*
	Is called if any state checkbox is clicked
*/
function StateTicked()
{	
	if (disabled) {
		//The user unchecked a box after we disabled all unchecked boxes
		//this will enable everything again
		EnabledCheckBoxes('states',true,false);
		disabled = false;
	}
}

/*
	If 8 state boxes are checked
	we want to disable only those boxes
	which are unchecked
*/
function DisableUncheckedStates()
{
	jQuery('.states input').each(
		function(state){
			if(!this.checked){
				this.disabled = true;
			}
		}
	);
	
	disabled = true;
}

/*
	This method will Enable or disable a series
	of inputs based on the boolean on variable.
	the clearState boolean variable determines if
	the checked state should be cleared
*/
function EnabledCheckBoxes(className,on,clearState)
{
	jQuery('.'+className+' input').each(
		function(state){
			this.disabled = !on;
			if(clearState) this.checked = false;
		}
	);
}

function validateSelectedState(dropdownId) {
    var dropdown = document.getElementById(dropdownId);
    if (dropdown.selectedIndex == 0) {
        alert('Please first choose a state from the "Select a State" dropdown box.');
        return false;
    }
    return true;
}

function validateComparison() {
    var errors = new Array();
       
    var tfCount = GetSelectedCount('years');
    if (tfCount < 1) {
        errors.push(' - Please select at least one year for the comparison.');
    }

    var locCount = GetSelectedCount('states');
    if (locCount < 1) {
        errors.push(' - Please select at least one state for the comparison.');
    }

    if (errors.length == 0) {
        return true;
    }
    
    alert('Some errors were found in the selected comparison.\n' + errors.join('\n'));
    return false;
}

function CreatePowerpoint()
{
	var bestWorstInput = document.getElementById('tbBestWorstId');
	var bestworst;
	if (bestWorstInput != null) {
	    bestworst = bestWorstInput.value;
	}

	var locations = FindVisibleLocationCount();
	if (locations.length == 0) {
	    alert("At least one state must be selected.");
	    return false;
	}

	if (locations.length > 5) {
	    var message = "Charts are most readable when five or fewer locations are selected.\n\n";
	    message += "Click 'OK' to continue with current selections.\n";
	    message += "Or, click 'Cancel' to change selections.";
	    var r = confirm(message);
	    if (r == false) {
	        return false;
	    }
	}
		
	var ind = parseUri(document.location).queryKey['ind'];
	var loc = getLocationUrlString(locations);		
	var tf = parseUri(document.location).queryKey['tf'];

	if (bestworst != "") {
	    bestworst = '&bestworst=' + bestworst;
	}
			
	var cat = jQuery('.CategoryId')[0].value;
	var powerpointURL = '/ssc/powerpointhandler.axd?ind=' + ind + '&loc=' + loc + '&tf=' + tf + '&cat=' + cat + bestworst;		
	window.location = powerpointURL;		
	
}

function formatNumber(value)
{
	return value.replace('.','_').replace(',','');
}

function FindVisibleLocationCount()
{
    var locations = new Array();

    jQuery('td.location_bar').each(function() {
        if (this.parentNode.style.display != 'none') {
            var id = this.id.substring(4);
            if (id != '') {
                locations.push(id);
            }
        }
    });

    return locations;
}

function AdjustStates()
{
	jQuery('.bar_chart img').each(
		function(b)
		{
			jQuery(this).animate({ 
        width: this.title + '%'
      }, 2000 );
		}
	);
}

function getLocationUrlString(locations)
{
	var locationString = '';
	for(var i = 0; i < locations.length; i++)
	{
		if(i > 0) locationString += ',';
		locationString += locations[i];
	}
			
	return locationString;
}

function ArrayContainsValue(array, value)
{
	var contains = false;
	for(var i = 0; i < array.length; i++)
	{
		if(array[i] == value)
		{
			contains = true;
			break;
		}
	}
	return contains;
}

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};


// attach ddl-arrow clicks to dropdown select
jQuery(document).ready(function() {

	// we have to re-attach events to DOM nodes because they are loaded dynamically post-page-load.
	jQuery('.ddl-arrow').live('mouseover', function() {
			
		jQuery('.ddl-arrow').click(function() {
			jQuery(this).next().focus();
		});
		
	});
});

