/*
	Multifaceted Lightbox
	by Greg Neustaetter - http://www.gregphoto.net
	
	INSPIRED BY (AND CODE TAKEN FROM)
	==================================
	The Lightbox Effect without Lightbox
	PJ Hyett
	http://pjhyett.com/articles/2006/02/09/the-lightbox-effect-without-lightbox
	

	Lightbox JS: Fullsize Image Overlays 
	by Lokesh Dhakar - http://www.huddletogether.com

	For more information on this script, visit:
	http://huddletogether.com/projects/lightbox/

	Licensend under:
	Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
	(basically, do anything you want, just leave my name and link)
	
*/

var Lightbox = {
	lightboxType : null,
	lightboxCurrentContentID : null,
	
	showBoxString : function(content, boxWidth, boxHeight){
		this.setLightboxDimensions(boxWidth, boxHeight);
		this.lightboxType = 'string';
		var contents = $('lightboxContents');
		contents.innerHTML = content;
		this.showBox();
		return false;
	},


	showBoxImage : function(href) {
		this.lightboxType = 'image';
		var contents = $('lightboxContents');
		var objImage = document.createElement("img");
		objImage.setAttribute('id','lightboxImage');
		contents.appendChild(objImage);
		imgPreload = new Image();
		imgPreload.onload=function(){
			objImage.src = href;
			Lightbox.showBox();
		}
		imgPreload.src = href;
		return false;
	},

	showBoxByID : function(id, boxWidth, boxHeight) {
		this.lightboxType = 'id';
		this.lightboxCurrentContentID = id;
		this.setLightboxDimensions(boxWidth, boxHeight);
		var element = $(id);
		var contents = $('lightboxContents');
		contents.appendChild(element);
		Element.show(id);
		this.showBox();
		return false;
	},

	showBoxByAJAX : function(href, boxWidth, boxHeight) {
		this.lightboxType = 'ajax';
		this.setLightboxDimensions(boxWidth, boxHeight);
		var contents = $('lightboxContents');
		var myAjax = new Ajax.Updater(contents, href, {method: 'get'});
		this.showBox();
		return false;
	},
	
	setLightboxDimensions : function(width, height) {
		$('lightbox').style.width = width + 'px';
		$('lightbox').style.height = height + 'px';
	},


	showBox : function() {
	    // Hides the drop down boxes that are underneath the lightbox 
	    // Fixes issue with drop down boxes popping through the lightbox in IE6
	    SetUnderlyingDropDownAreasDisplay('none');
		Element.show('overlay');
		this.center('lightbox');	
		
		return false;
	},
	
	
	hideBox : function(){
	    // Shows the drop down boxes that underneath the lightbox
	    SetUnderlyingDropDownAreasDisplay('block');
		var contents = $('lightboxContents');
		if(this.lightboxType == 'id') {
			var body = document.getElementsByTagName("body").item(0);
			Element.hide(this.lightboxCurrentContentID);
			body.appendChild($(this.lightboxCurrentContentID));
		}
		contents.innerHTML = '';
		$('lightbox').style.width = null;
		$('lightbox').style.height = null;
		Element.hide('lightbox');
		Element.hide('overlay');
		return false;
	},
	
	// taken from lightbox js, modified argument return order
	getPageDimensions : function(){
		var xScroll, yScroll;
	
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.documentElement && document.documentElement.scrollWidth) { // Explorer 
			xScroll = document.documentElement.scrollWidth;
			yScroll = document.documentElement.scrollHeight;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		
		var windowWidth, windowHeight;
		if (self.innerHeight) {	// all except Explorer
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
	
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = windowWidth;
		} else {
			pageWidth = xScroll;
		}
		arrayPageSize = new Array(windowWidth,windowHeight,pageWidth,pageHeight) 
		return arrayPageSize;
	},
	
	center : function(element){
		try{
			element = document.getElementById(element);
		}catch(e){
			return;
		}
		var windowSize = this.getPageDimensions();
		var window_width  = windowSize[0];
		var window_height = windowSize[1];
		
		element.style.position = 'absolute';
		element.style.zIndex   = 99;
	
		var scrollY = 0;
	
		if ( document.documentElement && document.documentElement.scrollTop ){
			scrollY = document.documentElement.scrollTop;
		}else if ( document.body && document.body.scrollTop ){
			scrollY = document.body.scrollTop;
		}else if ( window.pageYOffset ){
			scrollY = window.pageYOffset;
		}else if ( window.scrollY ){
			scrollY = window.scrollY;
		}
		
		var scrollX = 0;
	
		if ( document.documentElement && document.documentElement.scrollLeft ){
			scrollX = document.documentElement.scrollLeft;
		}else if ( document.body && document.body.scrollLeft ){
			scrollX = document.body.scrollLeft;
		}else if ( window.pageXOffset ){
			scrollX = window.pageXOffset;
		}else if ( window.scrollX ){
			scrollX = window.scrollX;
		}
	
		var elementDimensions = Element.getDimensions(element);
		
		var elementWidth = 0;
		if(elementDimensions.width) {
			if(elementDimensions.width < windowSize[0]) {
				elementWidth = elementDimensions.width;
			} else {
				elementWidth = (windowSize[0] - 50);
			}
		}
		
		var elementHeight = 0;
		if(elementDimensions.height) {
			if(elementDimensions.height < windowSize[1]) {
				elementHeight = elementDimensions.height;
			} else {
				elementHeight = (windowSize[1] - 50);
			}
		}
		var setX = ( window_width  - elementWidth  ) / 2 + scrollX;
		var setY = ( window_height - elementHeight ) / 2 + scrollY;

	
		setX = ( setX < 0 ) ? 0 : setX;
		setY = ( setY < 0 ) ? 0 : setY;
	
		element.style.left = setX + "px";
		element.style.top  = setY + "px";
		Element.show(element);
		
		windowSize = this.getPageDimensions();
		$('overlay').style.height = windowSize[3] + 'px';
		$('overlay').style.width = windowSize[2] + 'px';	
	}
}


//********************************************************************//
//**                                                                **//
//**                       Lightbox Methods                         **//
//**                                                                **//
//********************************************************************//

//  This variable is used to store off the token cookie before any changes
//  are made.  It is populated with the lightbox is first shown.
var originalCookie;

//  regionFirst is used to determine if a region needs to be choosen before 
//  a segment is.
var regionFirst = false;

//********************************************************************//
//**                                                                **//
//**                Miscellaneous Helper Methods                    **//
//**                                                                **//
//********************************************************************//

// Used to hide or show the drop down boxes underneath the lightbox.
function SetUnderlyingDropDownAreasDisplay(displayStyle)
{
    var dropDownAreas = document.getElementsByClassName('dimDropDown');
	for(i=0; i<dropDownAreas.length; i++)
	{
	    dropDownAreas[i].style.display = displayStyle;
	}
}

function GetCurrentSimulatorID()
{
    partialUrl = location.href.substring(location.href.indexOf('simulator'), location.href.length);
    parts = partialUrl.split('/');
    //simID = parts[1];
    //tabName = parts[2];
    
    return parts[1];
}

function GetCurrentTabName()
{
    partialUrl = location.href.substring(location.href.indexOf('simulator'), location.href.length);
    parts = partialUrl.split('/');
    //simID = parts[1];
    //tabName = parts[2];
    
    return parts[2];
}

function GetRegionFirst()
{
    var simID = GetCurrentSimulatorID();
    var tabName = GetCurrentTabName();
    regionFirst = Ine.UseRegionFirst(simID, tabName);
}



//********************************************************************//
//**                                                                **//
//**                     Dropdown Helper Methods                    **//
//**                                                                **//
//********************************************************************//

//  This method will "deselect" all segments when the selected index of 
//  one of the segment dropdowns is changed.  Basically it sets all the
//  other segment dropdowns to -- select --.
//  This method is called from the Segments.cs file.  Look for the
//  onchange event.
//  ResetAll is used to reset every segment dropdown, this is set to a 1 
//  when we have multi selects on the segment and we always want the
//  segment dropdown to display '-- select --'

//  Need to do some fancy calculations to determine which dropdowns to reset
//  The first dropdown has an id of ...SegmentTitles_0_1, but some of the
//  dropdown have a name of ...SegmentTitles_0_10, _0_11, etc...  These 
//  were getting past the index == -1 check.  So I'm checking the length
//  of the id.  If it doesn't equal the one stored off at the beginning
//  I'm resetting the dropdown
function SetSpecificSegmentDropDown(currentDropDown,resetAll)
{
    var list = document.getElementsByTagName("select");
    var targetLength = currentDropDown.length;
    
    for (i=0;i<list.length;i++)
    {
        if (list[i].id.indexOf("SegmentTitle") != -1)
        {
            if (list[i].id.indexOf(currentDropDown) == -1)
            {
                list[i].selectedIndex = 0;
            }
            else
            {
                var indxPos = list[i].id.indexOf(currentDropDown);
                var len = list[i].id.length;
                if ((indxPos + targetLength) != len)
                {
                    list[i].selectedIndex = 0;
                }
            }
        }
    }
    
    SelectOnChange(currentDropDown);
   
    if (resetAll == 1)
    {
        var list = document.getElementsByTagName("select");
        for (i=0;i<list.length;i++)
        {
            if (list[i].id.indexOf("SegmentTitle") != -1)
            {
                if (list[i].id.indexOf(currentDropDown) != -1)
                {
                    list[i].selectedIndex = 0;
                }
            }
        }
    }    
}

//  This method will return a 1 if a dimension has multiple selections
//  and a 0 if it doesn't.
function IsMultiSelect(dimensionName)
{
    var result = 0;
    var list = new Array();
    list = document.getElementsByTagName('div');

    for (var i=0;i<list.length;i++)
    {
        if (list[i].id.indexOf('delete_') != -1)
        {
            var dimName = list[i].id.substring(0,list[i].id.indexOf('delete_'));
            if (dimName == dimensionName)
                result = 1;
        }
    }
    return result;
}

function CheckWeightedBase()
{
    var simID = GetCurrentSimulatorID();
    var tabName = GetCurrentTabName();

    if ((tabName == 'optimization') || (tabName == 'crossTarget') || (tabName == 'reverso'))
    {
        techArray = GetDimensionValues('technology').split(',');
        segArray = GetDimensionValues('segment').split(',');
        regArray = GetDimensionValues('region').split(',');
        purScenArray = GetDimensionValues('purchasescenario').split(',');
        procArray = GetDimensionValues('processor').split(',');
            
        if (isNaN(procArray[0]) == true)
            procArray = [];
            
        if (isNaN(purScenArray[0]) == true)
            purScenArray = [];

        var multiRegion = IsMultiSelect('region');

        //  Reset everyting
        document.getElementById('selectrixOKButton').disabled = false;
        document.getElementById('errormessagelabel').innerHTML = '';
        for (iSeg=0;iSeg<segArray.length;iSeg++)
        {
            var label = document.getElementById('segmentlabelerror_' + iSeg);
            var div = document.getElementById('segmentlabeldiverror_' + iSeg)
            label.innerHTML = '';
            div.style.display = 'none';
        }

        var tokens = new Array();
        var messages = new Array();
        var segments = new Array();
        var i = 0;
        for (iTech=0;iTech<techArray.length;iTech++)
        {
            if (techArray[iTech] != 0)
            {
                techToken = 'technology:' + techArray[iTech];
                techText = GetDisplayTextForSpecificValue('technology',techArray[iTech]);

                for (iReg=0;iReg<regArray.length;iReg++)
                {
                    if (regArray[iReg] != 0)
                    {
                        regToken = 'region:' + regArray[iReg];
                        regText = GetDisplayTextForSpecificValue('region',regArray[iReg]);

                        for (iSeg=0;iSeg<segArray.length;iSeg++)
                        {
                            if (segArray[iSeg] != 0)
                            {
                                //  if there are multiple regions then region #1 is matched to segment #1 and
                                //  region #2 is matched to segment #2.  If there is only one region then
                                //  that region is matched to all segments.
                                if (((iSeg == iReg) && (multiRegion == 1)) || (multiRegion == 0))
                                {
                                    segToken = 'segment:' + segArray[iSeg];
                                    segText = GetDisplayTextForSpecificValue('segment',segArray[iSeg]);

                                    tokenlist = techToken + ',' + regToken + ',' + segToken;
                                
                                    messageText = '<font color=red>There is insufficient data for the segment above when combined with ';

                                    if (techText.length > 0)
                                        messageText = messageText + techText;
                                    if ((regText.length > 0) && (multiRegion == 1))
                                        messageText = messageText + ', ' + regText;

                                    for (iPur=0;iPur<purScenArray.length;iPur++)
                                    {
                                        if (purScenArray[iPur] != 0)
                                        {
                                            purToken = 'purchasescenario:' + purScenArray[iPur];
                                            purText = GetDisplayTextForSpecificValue('purchasescenario',purScenArray[iPur]);

                                            tokenlist = tokenlist + ',' + purToken;
                                            
                                            if (purText.length > 0)
                                                messageText = messageText + ' and ' + purText + ' Purchase Type.';
                                        }
                                    }
                                    
                                    for (iProc=0;iProc<procArray.length;iProc++)
                                    {
                                        if (procArray[iPur] != 0)
                                        {
                                            procToken = 'processor:' + procArray[iProc];
                                            procText = GetDisplayTextForSpecificValue('processor',procArray[iProc]);

                                            tokenlist = tokenlist + ',' + procToken;

                                            if (procText.length > 0)
                                                messageText = messageText + ' and ' + procText;
                                        }
                                    }

                                    messageText = messageText + '</font>';
                                
                                    tokens[i] = tokenlist;
                                    messages[i] = messageText;
                                    segments[i] = iSeg;
                                    i++;
                                }   //  if (((iSeg == iReg) && (multiRegion == 1)) || (multiRegion == 0))
                            }   //  if (segArray[iSeg] != 0)
                        }   //  for (iSeg=0;iSeg<segArray.length;iSeg++)
                    }   //  if (regArray[iReg] != 0)
                }   //  for (iReg=0;iReg<regArray.length;iReg++)
            }   //  if (techArray[iTech] != 0)
        }   //  for (iTech=0;iTech<techArray.length;iTech++)

        
        if (tokens.length > 0)
        {
            var badSelections = new Array();
            badSelections = eval(Ine.ShowInsufficientDataMessage(tokens, simID, tabName).value);
            if (badSelections.length > 0)
            {
                document.getElementById('selectrixOKButton').disabled = true;
                document.getElementById('errormessagelabel').innerHTML = 'Warning: Charting is disabled because of invalid selections below.';
                for (i=0;i<badSelections.length;i++)
                {
                    index = badSelections[i];
                    var label = document.getElementById('segmentlabelerror_' + segments[index]);
                    document.getElementById('segmentlabeldiverror_' + segments[index]).style.display = 'block';
                    label.innerHTML = label.innerHTML + messages[index] + '<br/><br/>';
                }
            }
        }
        
    }
}


//  Find a select dropdown object which contains a specific word in it's ID
//  This method returns the id of the dropdown
function GetSpecificDropDownID(target)
{
    var list = new Array();
    list = document.getElementsByTagName("select");
    
    for (i=0;i<list.length;i++)
    {
        if (list[i].id.indexOf(target) != -1)
        {
            return list[i].id;
        }
    }
}

//  Get the text value of a specific value of a specific dropdown
function GetDisplayTextForSpecificValue(target,value)
{
    var returnText = '';
    
    if (target == 'segment')
    {
        target = 'SegmentTitles';
        returnText = GetDisplayValueForSpecificSegmentValue(target,value);
    }
    else
    {
        var targetID = GetSpecificDropDownID(target);
        if (targetID != null)
        {
            var tempTarget = document.getElementById(targetID);
            if (tempTarget != null)
            {
                for (var i=0;i<tempTarget.length;i++)
                {
                    if (tempTarget.options[i].value == value)
                    {
                        returnText = tempTarget.options[i].text;
                    }
                }
            }
        }
    }    
    return returnText;
}

//  Get the selected value for a specific dropdown
function GetSelectedValueForSpecificDropDown(ddlName)
{
    var returnValue = '';
    var targetID = GetSpecificDropDownID(ddlName);
    if (targetID != null)
    {
        var tempTarget = document.getElementById(targetID);
        if (tempTarget != null)
        {
            returnValue = tempTarget.options[tempTarget.selectedIndex].value;    
        }
    }
    return returnValue;
}

//  Performs the same function as the method above, but this methods
//  looks specifically at the segment dropdowns
function GetDisplayValueForSpecificSegmentValue(target,value)
{
    var returnText = '';
    var list = new Array();
    list = document.getElementsByTagName('select');

    for (var i=0;i<list.length;i++)
    {
        if (list[i].id.indexOf(target) != -1)
        {
            var tempTarget = list[i];
            if (tempTarget != null)
            {
                for (var j=0;j<tempTarget.options.length;j++)
                {
                    if (tempTarget.options[j].value == value)
                    {
                        returnText = tempTarget.options[j].text;
                    }
                }
            }

        }
    }
    return returnText;
}


//  This method will remove all the options from a select element which contains
//  the targetID in it's ID.
//  This is used when we have a dropdown that is filtered by the selection of 
//  another dropdown.
function RemoveOptions(targetID)
{
    var target = document.getElementById(GetSpecificDropDownID(targetID));

    for (i=target.options.length-1;i>=0;i--)
    {
        target.remove(i);
    }
 }
 
//  This method will add one option to the specified select element
//  This is used when we have a dropdown that is filtered by the selection of 
//  another dropdown.
function AddIndividualOptions(targetID,value,text)
{
    var target = document.getElementById(GetSpecificDropDownID(targetID));
    var option = document.createElement("OPTION");
    option.text = text;
    option.value = value;

    target.options.add(option);
}

//  If the user selects a dimension but presses the Cancel button the
//  drowdowns are "out of sync" with the values in the Cookie.
//  This method will get the value(s) from the Token cookie and
//  make sure the dropdown has the correct display.
function ResetSpecificDimensions(controlName,dimension)
{
    var cookieValue = GetDimensionValues(dimension);
    var list = document.getElementsByTagName("select");
    
    for (var i=0;i<list.length;i++)
    {
        if (list[i].id.indexOf(controlName) != -1)
        {
            if (list[i].options[list[i].selectedIndex].value != cookieValue)
            {
                list[i].selectedIndex = 0;
                for (j=0;j<list[i].options.length;j++)
                {
                    if (list[i].options[j].value == cookieValue)
                    {
                        list[i].selectedIndex = j;
                    }
                }
            }
        }
    }
}

//  This method will reset the dropdown a specific index value.
//  This is used in multi select tabs.
function ResetDropDownByIndexValue(dimensionName,index)
{
    var list = document.getElementsByTagName("select");
    var selectName = '_' + dimensionName;
    
    for (var i=0;i<list.length;i++)
    {
        if (list[i].id.indexOf(selectName) != -1)
        {
            list[i].selectedIndex = index;
        }
    }
}

//********************************************************************//
//**                                                                **//
//**                     Current Selection Methods                  **//
//**                                                                **//
//********************************************************************//

//  This method will set the text for a specific label
//  The dimensionName and index are used when the lightbox is first
//  loaded on multiselect tabs to set the correct button image
function SetCurrentSelectionLabel(labelName,text,dimensionName, index)
{
    var label = document.getElementById(labelName);
    if (label != null)
    {
        label.innerHTML = text;
    }
    if (dimensionName != undefined)
    {
        if (text != 'Available')
        {
            ToggleStepButtons(dimensionName,index,1);
        }
        else
        {
            ToggleStepButtons(dimensionName,index,0);
        }    
    }
}

//  This method will update the label(s) in Current Selection box
//  to keep them in sync with the token.  This method is called
//  by non Segment dropdowns.
function UpdateSelectionLabel(dimensionName)
{
    var ddl = new Array();
    var values = GetDimensionValues(dimensionName);

    if (values != null)
    {
        var parts = values.split(',');

        for (var i=0;i<parts.length;i++)
        {
            ddl[i] = parts[i];
            var selectName = '_' + dimensionName;
            var displayText = GetDisplayTextForSpecificValue(selectName,ddl[i]);
            if ((displayText == undefined) || (displayText == '-- select --') || displayText == '')
                displayText = 'Available';          
            SetCurrentSelectionLabel(dimensionName + 'label_' + i, displayText, dimensionName, i);
        }
    }
}

//  Same as purpose as the method above, however this one is only
//  called by Segment dropdowns.
function UpdateSegmentSelectionLabel()
{
    var ddl = new Array();
    var values = GetDimensionValues('segment');
    var displayText = '';

    if (values != null)
    {
        var parts = values.split(',');

        var list = document.getElementsByTagName("select");

        for (var i=0;i<parts.length;i++)
        {
            displayText = 'Available';          
            for (var j=0;j<list.length;j++)
            {
                if (list[j].id.indexOf('_SegmentTitle') != -1)
                {
                    currentValue = parts[i];
                    var selectName = list[j].id;
                    var tempDisplayText = GetDisplayTextForSpecificValue(selectName,currentValue);
                    if ((tempDisplayText != undefined) && (tempDisplayText != '-- select --') && (tempDisplayText != ''))
                        displayText = tempDisplayText;
                }
            }
            SetCurrentSelectionLabel('segmentlabel_' + i, displayText, 'segment', i);
        }
    }
}

//  Method to make sure the Current Selection labels are
//  up to date.
function UpdateCurrentSelectionText()
{
    UpdateSegmentSelectionLabel();
    UpdateSelectionLabel('title');
    UpdateSelectionLabel('technology');
    UpdateSelectionLabel('simulator');
    UpdateSelectionLabel('size');
    UpdateSelectionLabel('purchasescenario');
    UpdateSelectionLabel('awareness');
    UpdateSelectionLabel('actual');
    UpdateSelectionLabel('subtechnology');
    UpdateSelectionLabel('content');
    UpdateSelectionLabel('region');
    UpdateSelectionLabel('processor');
    UpdateSelectionLabel('actualspooled');
}

//********************************************************************//
//**                                                                **//
//**                         OnChange Methods                       **//
//**                                                                **//
//********************************************************************//


//  This method will get the current tab and see if that tab exists
//  in the selected simulator
function SimulatorTabExists(ddlName)
{
    var tabName = GetCurrentTabName();
    var simID = GetSelectedValueForSpecificDropDown(ddlName);
    var result = false;

    result = Ine.TabExistsInSim(simID, tabName);
    
    if (result.value == false)
    {
        alert("That is an invalid selection for this Simulator because it does not have the current Tab.");
        ResetSpecificDimensions('simulator','simulator');
    }
    else
    {
        UpdateCookieWithNewValue(ddlName);
        GetLightBoxDropDownValues();
    }
}


//  This method is called whenever a non Segment dropdown is changed.
//  A selected value of -99 means the user selected "-- Solution --" or
//  "-- Region --" from the drop down.  If this is the case we need to 
//  cancel the selection and reset the dropdown to the previous value/selection.
function SelectOnChange(ddlName)
{
    if (ddlName == 'simulator')
    {
        SimulatorTabExists(ddlName);
    }
    else
    {
        var val = GetSelectedValueForSpecificDropDown(ddlName);

        if ((val != -99) && (val != 0))
        {
            UpdateCookieWithNewValue(ddlName);
        }
        else
        {
            ResetSpecificDimensions(ddlName,ddlName)
        }
    }
    CheckWeightedBase();    
}

//  This method is used to filter one dropdown based on the value of another, in
//  CPI the brand is based on the technology. 
function SelectFilterOnChange(current,target,attributes)
{
//    partialUrl = location.href.substring(location.href.indexOf('simulator'), location.href.length);
//    parts = partialUrl.split('/');
//    simID = parts[1];
//    tabName = parts[2];

    simID = GetCurrentSimulatorID();
    tabName = GetCurrentTabName();

    var cookie = getCookie('token');
    var findCurrent = document.getElementById(GetSpecificDropDownID(current));

    if (findCurrent != null)
    {
        currentValue = findCurrent.options[findCurrent.selectedIndex].value;

        //  We need to handle the Segment dropdowns a little differently since there are multiples.
        renamedCurrent = current;
        if (current.indexOf('SegmentTitles_') != -1)
        {
            renamedCurrent = 'segment';
        }   

        var values = new Array();
        values = eval(Ine.ReturnFilteredDataSet(cookie, renamedCurrent, currentValue, target, simID, tabName, attributes).value);

        RemoveOptions(target);
        
        if (values.length > 0)
        {
            for (z=0;z<=values.length-1;z++)
            {
                parts = values[z].split(',');
                AddIndividualOptions(target,parts[0],parts[1]);
            }
        }
    }
    SelectOnChange(current);
    SelectOnChange(target);
}


//********************************************************************//
//**                                                                **//
//**                          Cookie Methods                        **//
//**                                                                **//
//********************************************************************//

//  This method will save off the token cookie when the Lightbox is made 
//  visible.  
function SaveOriginalCookie()
{
    originalCookie = getCookie('token');
    CheckWeightedBase();
}

//  This method will take a comma seperated string and return an array
//  of the elements
function CreateArray(values)
{
    var tempArray = values.split(',');
    return tempArray;
}

//  Find and return the 'token' cookie
function getCookie(cookieName)
{
    var cookies = document.cookie;
    
    if (cookies.indexOf(cookieName) != -1)
    {
        var startpos = cookies.indexOf(cookieName)+cookieName.length+1;
        var endpos = cookies.indexOf(";", startpos) - 0;
        
        if (endpos == -1)
        {
            endpos = cookies.length;
        }            
    }
    return cookies.substring(startpos,endpos);
}

//  This method is used to store the dropdown's selected value in
//  the temporary cookie.
function UpdateCookieWithNewValue(dimensionName)
{
    var ddl = new Array();
    var value
      
    var list = document.getElementsByTagName("select");
  
    tokenName = dimensionName;
    dimensionName = '_' + dimensionName;

    for (i=0;i<list.length;i++)
    {
        if (list[i].id.indexOf(dimensionName) != -1)
        {
            if (list[i].options[list[i].selectedIndex].value != 0)
            {
                value = list[i].options[list[i].selectedIndex].value;
            }
        }
    }
    
    if (tokenName.indexOf("SegmentTitle") != -1)
        tokenName = 'segment';

    SetDimensionValues(tokenName,value);
}

//  Get the value(s) from the Token cookie for a specific dimension
function GetDimensionValues(dimensionName)
{
    dimensionName = dimensionName + '":';

    var cookie = getCookie('token');
    var startPos = cookie.search(dimensionName);
    var endPos = cookie.indexOf("],", startPos);
    if (endPos == -1)
    {
        endPos = cookie.length - 3;
    }            
    var value = cookie.substring(startPos + dimensionName.length + 1, endPos);

    return value;
}

//  This method will override the existing token/dimension values with
//  the ones passed in
function OverrideTokenValues(dimensionName,newValues)
{
    var cookie = getCookie('token');
    dimensionName = dimensionName + '":';
    var startPos = cookie.search(dimensionName);
    if (startPos > 0)
    {
        var endPos = cookie.indexOf("],", startPos);

        if (endPos == -1)
        {
            endPos = cookie.length - 3;
        }

        var newCookie = cookie.substring(0,startPos + dimensionName.length);
        newCookie = newCookie + '[' + newValues + cookie.substring(endPos,cookie.length);
  
        createCookie('token',newCookie,0);
    }
}

//  Create the cookie.  This will overwrite the existing cookie.   For testing
//  purposes we need to check the URL to make sure the correct path is assigned
//  to the cookie.
function createCookie(name,value)
{
	var expires = "";
	var originalPath = location.href;
	var uppercasePath = originalPath.toUpperCase();
    var originalSplit = originalPath.split('/');
    var sim = 'simulator';
    var preSim = 'INE80';
    

    for (i=0;i<originalSplit.length;i++)
    {
        var current = originalSplit[i];
        if (current.toUpperCase() == 'SIMULATOR')
        {
            sim = current;
            preSim = originalSplit[i-1];
        }
    }
    
	if (uppercasePath.indexOf('LOCALHOST') != -1)
	{
        document.cookie = name+"="+value+expires+"; path=/" + sim + "/";
    }
    else
    {
	    document.cookie = name+"="+value+expires+"; path=/" + preSim + "/" + sim + "/";
	}

/*
	if (location.href.indexOf('localhost') != -1)
	{
    	document.cookie = name+"="+value+expires+"; path=/simulator/";
    }
    else
    {
	    document.cookie = name+"="+value+expires+"; path=/INE70/simulator/";
	}
*/	
    UpdateCurrentSelectionText();
}

//  This method is called by CleanupToken.  It removes 0 values
//  from the token because these are only used as placeholders for
//  potential multiselect dimensions.
function RemoveDimensionZeroValues(dimensionName)
{
    var currentDimensionValues = GetDimensionValues(dimensionName);
    var parts = new Array();
    var newValues = '';

    parts = CreateArray(currentDimensionValues);

    for (var i=0;i<parts.length;i++)
    {
        if (parts[i] != 0)
        {
            if (i != 0)
                newValues = newValues + ',';
            newValues = newValues + parts[i];
        }
    }
    
    OverrideTokenValues(dimensionName,newValues);
}

//  We need to put dummy entries in the temporary token for those dimensions with
//  multiple values.  We are doing this by counting the number of delete divs on
//  the page and then parsing the id to determine which dimension it applies to and 
//  how many dummy entries we need.    
function PadTokenForMultiSelect()
{
    var list = new Array();
    list = document.getElementsByTagName('div');
    
    for (var i=0;i<list.length;i++)
    {
        if (list[i].id.indexOf('delete_') != -1)
        {
            var dimensionName = list[i].id.substring(0,list[i].id.indexOf('delete_'));
            var index = list[i].id.substring(list[i].id.indexOf('delete_') + 7, list[i].id.length);
            var currentValues = GetDimensionValues(dimensionName);
            parts = CreateArray(currentValues);
            
            if (parts[0] == '')
            {
                numValues = 0;
            }
            else
            {
                numValues = parts.length;
            }
            
            if (numValues <= index)
            {
                if (numValues == 0)
                {
                    OverrideTokenValues(dimensionName,'0');
                }
                else
                {
                    OverrideTokenValues(dimensionName,currentValues + ',0');
                }                
            }
        }            
    }
}    

//  When dealing with multiselect dimensions we added zeroes to take the places
//  of blank entries.  The app doesn't want zero's so remove them.
function CleanupToken()
{
    RemoveDimensionZeroValues('technology');
    RemoveDimensionZeroValues('segment');
    RemoveDimensionZeroValues('content');
    RemoveDimensionZeroValues('region');
}

//********************************************************************//
//**                                                                **//
//**                      Step Button Methods                       **//
//**                                                                **//
//********************************************************************//

//  This method is called when a dropdown is called.  It will hide or
//  display a div depending on the deleteEnabled flag
function ToggleStepButtons(dimensionName,index,deleteEnabled)
{
    var deletediv = dimensionName + 'delete_' + index;
    var bulletdiv = dimensionName + 'bullet_' + index;

    var deleteButton = document.getElementById(deletediv);
    var bulletButton = document.getElementById(bulletdiv);

    if (deleteButton != undefined)
    {
        if (deleteEnabled == 1)
        {
            deleteButton.style.display = 'block';
            bulletButton.style.display = 'none';
        }
        else
        {
            deleteButton.style.display = 'none';
            bulletButton.style.display = 'block';
        }
    }
}

//  This method is called when the "delete.gif" image is clicked
//  It calls the ToggleStepButtons and SetDimensionValues methods
//  to reset the Current Selection box and the cookie.
function ClearButtonClick(dimensionName,index)
{
    dimensionName = dimensionName.toLowerCase();
    SetDimensionValues(dimensionName,'0',index);
    CheckWeightedBase();    
}

//  This method is called by the Clear All delete.gif images on multi select dimensions
//  It will find the correct divs (e.g. technologydelete_0, technologydelete_1, 
//  technologydelete_2) parse out the index e.g. (0,1,2) and then call the 
//  ToggleStepButtons and SetDimensionValues methods to reset the cookie as
//  well as the Current Selections box
function ClearAllButtonClick(dimensionName)
{
    dimensionName = dimensionName.toLowerCase();
    var list = document.getElementsByTagName("div");
    var deletediv = dimensionName + 'delete_';
    
    for (var i=0;i<list.length;i++)
    {
        if (list[i].id.indexOf(deletediv) != -1)
        {
            var index = list[i].id.substring(list[i].id.indexOf('_')+1,list[i].id.length);
            //  The first value is always poped off, so if we are clearing all the entries
            //  we want to always remove the first (0) one.
            SetDimensionValues(dimensionName,'0',0);
        }
    }
    CheckWeightedBase();
}

//********************************************************************//
//**                                                                **//
//**                    Form Releated Methods                       **//
//**                                                                **//
//********************************************************************//

//  Called when the lightbox Ok button is pressed.  This method calls
//  CleanupToken and then resubmits the form.
function GetLightBoxDropDownValues()
{
    CleanupToken();
    theForm.submit();
}

function SubmitRequestForTraining(name, email, phone, text)
{
    var message = Ine.SubmitRequestForTraining(name, email, phone, text);
    if (message.value != null) {
        alert('Send failed: ' + message.value);
        return;
    }
    Lightbox.hideBox();
}

//  This method is called when the Cancel button in the lightbox is clicked.
//  It will reapply the cookie which was originally saved before any changes
//  were made and then reset the dropdowns to their original values
function ResetAllDimensions()
{
    if (regionFirst.value == true)
        ProcessRegionFirst();
    createCookie('token',originalCookie,0);
    ResetSpecificDimensions('SegmentTitle','segment');
    ResetSpecificDimensions('title','title');
    ResetSpecificDimensions('technology','technology');
    ResetSpecificDimensions('simulator','simulator');
    ResetSpecificDimensions('size','size');
    ResetSpecificDimensions('awareness','awareness');
    ResetSpecificDimensions('purchasescenario','purchasescenario');
    ResetSpecificDimensions('actual','actual');
    ResetSpecificDimensions('subtechnology','subtechnology');
    ResetSpecificDimensions('content','content');
    ResetSpecificDimensions('region','region');
    ResetSpecificDimensions('processor','processor');
    ResetSpecificDimensions('actualspooled','actualspooled');
}

//  This method is called when the "Change/Add Selection" hyperlink is clicked 
//  on the main page.  It saves off a copy of the cookie, makes sure the
//  current selection labels are correct and pads the cookie for any
//  multiselect dropdowns.
function InitializeDropDowns()
{
    SaveOriginalCookie();
    GetRegionFirst();
    UpdateCurrentSelectionText();
    PadTokenForMultiSelect();
    if (regionFirst.value == true)
    {
        ShowSegmentDropDowns(0);
        ProcessRegionFirst();
    }
    else
        ShowSegmentDropDowns(1);
}

//********************************************************************//
//**                                                                **//
//**            Keep the UI & Cookie in sync methods                **//
//**                                                                **//
//********************************************************************//


//	This method will update the cookie when a selection has changed.  It
//	is also being called with the delete button is clicked or the clear all 
//	button is pressed.
function SetDimensionValues(dimensionName,dimensionValue,index)
{
    if (dimensionValue.length > 0)
    {
        var currentDimensionValues = GetDimensionValues(dimensionName);
        var newValues = '';
        var parts = CreateArray(currentDimensionValues);

        //  if index is undefined then we are adding/replacing a value in the
        //  token.  index is undefined when a dropdown has changed.
        if (index == undefined)
        {
            //  single selects have a parts.length of 1
            if (parts.length == 1)
            {
                newValues = dimensionValue;
            }

            //  multi selects have a parts.length greater then 1                
            if (parts.length > 1)
            {
                for (var i=0;i<parts.length;i++)
                {
                    if (dimensionValue == 0)
                    {
                        newValues = newValues + parts[i];
                    }
                    if (dimensionValue != 0)
                    {
                        if (parts[i] == 0)
                        {          
                            newValues = newValues + dimensionValue;
                            dimensionValue = 0;
                            ToggleStepButtons(dimensionName,i,1);
                        }
                        else
                        {
                            newValues = newValues + parts[i];
                        }
                    }
                    if (i < parts.length -1)
                    {
                     newValues = newValues + ',';
                    }
                }
                //  Reset the dropdown to '-- select --'
                ResetDropDownByIndexValue(dimensionName,0);
            }
        }

        //  index does not equal undefined when a clear button has been pressed in a 
        //  a multiselect tab.
        if (index != undefined)
        {
            newValues = '';
            //  first we need to remove the value, identified by it's index value from the list
            for (var i=0;i<parts.length;i++)
            {
                if (i == index)
                {
                    newValues = newValues + 0;
                }
                else
                {
                    newValues = newValues + parts[i];
                }
                if (i < parts.length - 1)
                {
                 newValues = newValues + ',';
                }
            }
            //	now we need to add zero to be place holders for values which could be added
            var newParts = CreateArray(newValues);
            newValues = '';
            var count = 0;
            for (var i=0;i<newParts.length;i++)
            {
                if (newParts[i] != 0)
                {
                    newValues = newValues + newParts[i];
                    count = count + 1;
					newValues = newValues + ',';
                }
            }
            //  Add zeroes if need to equal the maxdimension
            if ((newValues == '') || (count > 0))
            {
                for (var i=0;i<newParts.length - count;i++)
                {
                    newValues = newValues + '0';
                    if (i < parts.length - count - 1)
                    {
                        newValues = newValues + ',';
                    }
                }
            }

            //  finally toggle the bullets as needed
            var newParts = CreateArray(newValues);
            for (var i=0;i<newParts.length;i++)
            {
                if (newParts[i] != 0)
                {
					ToggleStepButtons(dimensionName,i,1);
                }
                else
                {
					ToggleStepButtons(dimensionName,i,0);
                }
            }
        }
        
        OverrideTokenValues(dimensionName,newValues);
        if (regionFirst.value == true)
            ProcessRegionFirst();
    }
}



function ProcessRegionFirst()
{
    var regionCount = 0;
    var segmentCount = 0;
    var regionParts = new Array();
    var segmentParts = new Array();
    
    regionParts = CreateArray(GetDimensionValues('region'));
    segmentParts = CreateArray(GetDimensionValues('segment'));

    for (var i=0;i<regionParts.length;i++)
    {
        if (regionParts[i] != 0)
            regionCount = regionCount + 1;
        else
        {
            SetCurrentSelectionLabel('segmentlabel_' + i, 'Select a Region first', 'segment', i);
            ToggleStepButtons('segment',i,0);
        }
    }

    for (var i=0;i<segmentParts.length;i++)
    {
        if (segmentParts[i] != 0)
            segmentCount = segmentCount + 1;
    }

    if (regionCount <= segmentCount)
        ShowSegmentDropDowns(0);
    else
        ShowSegmentDropDowns(1);

    if ((regionCount > 0) && (segmentCount > 0))
    {
    
        for (var i=0;i<regionCount;i++)
        {
            var regionText = GetDisplayTextForSpecificValue('region',regionParts[i]);
            var segmentText = GetDisplayTextForSpecificValue('segment',segmentParts[i]);
            if ((i < regionCount) && (segmentParts[i] != 0))
            {
                SetCurrentSelectionLabel('segmentlabel_' + i, regionText + ': ' + segmentText, 'segment', i);
            }
            else
            {
            }
        }
    }

        
}    

//  This method will show or hide all the segment dropdowns
//  It is used by those sims & tabs which have a RegionFirst setting
function ShowSegmentDropDowns(show)
{
    var list = document.getElementsByTagName("div");
    for (var i=0;i<list.length;i++)
    {
        if (list[i].id.indexOf("_segmentdiv") != -1)
        {
            if (show == 0)
            {
                list[i].style.display = 'none';
            }
            else
            {
                list[i].style.display = 'block';
            }
        }
    }
}


