
var dragapproved=false
var minrestore=0
var initialwidth,initialheight
var ie5=document.all&&document.getElementById
var ns6=document.getElementById&&!document.all
var HELP_WIN;
var httpRequest;


if( getCookie("IsLogOut") == "1" && ! ( location.href.indexOf('/secure/main/') >= 0 ) && ! (location.href.indexOf('/secure/help/') >= 0 ) && ! ( location.href.indexOf('inbox') > 0 ) && ! ( location.href.indexOf('/secure/shared/') >= 0 ) && ! ( location.href.indexOf('/secure/controls/') >= 0 ) && ! ( location.href.indexOf('/secure/error/') >= 0 ) && ! ( location.href.indexOf('/secure/newaccounts/ips/') >= 0 ) && ! ( location.href.indexOf('/secure/eprofile/fafn/') >= 0 ) && ! (location.href.indexOf('/') >= 0 ) ){	
	location.href = "/secure/main/logout.ashx?status=logout";
}

/* COMPLIANCE Helpers 2008 */

function confirmLinkAway(href)
/// <summary>Pops up a javascript confirm box with a message explaining the nature of the link.
/// <param name="href">The target link of the anchor tag.</param>
/// <returns>a confirm window</returns>
{
    //var whereTo = confirm(getMessage('leaveCLS2', href));
    if( window.confirm(getMessage('leaveCLS')) == true )
    {
        openWin( href, 'winAwayLink', '' );
    }
    else
    {
        return false;
    }
}

function getMessage(msg, href)
/// <summary>This method returns a message, for example, a disclaimer saying you are leaving the CLS site with the current link.</summary>
/// <param>msg: leaveCLS</param>
/// <param name="href">The target link of the anchor tag.</param>
/// <returns>string</returns>
{
    switch(msg) {
        case 'leaveCLS':
        return 'By selecting this link, you are navigating away from www.clsinvest.com to an unaffiliated web site. CLS is not responsible nor does CLS control the content of any unafilliated web site(s). Choose "OK" to continue to the link.';
        break;
        default: return('Error: No message provided.');
    }
}

/* END Compliance Helpers 2008

    BEGIN FLASH Interaction   */
    
function toggleSections(contentId)
/// <summary>This method allows you to call a javascript function from flash to show/hide content elements (divs, etc) that correspond with content in the flash movie.</summary>
/// <param name="contentId"></param>
/// <returns>void</returns>

{
    if( contentId == 'riskBudgeting' )
    {
        document.getElementById( contentId ).style.display = 'block';
        document.getElementById( 'riskBudgeting2').style.display = 'block';
        document.getElementById( 'enrollment').style.display = 'none';
        document.getElementById( 'enrollment2').style.display = 'none';
    }   
    
    if( contentId == 'enrollment' )
    {
        document.getElementById( contentId ).style.display = 'block';
        document.getElementById( 'enrollment2').style.display = 'block';
        document.getElementById( 'riskBudgeting').style.display = 'none';
        document.getElementById( 'riskBudgeting2').style.display = 'none';
    }
}
    
    
/* END FLash Interaction */
		



// END GLOBAL CODE

function getCookie(name) { // use: getCookie("name");
		var re = new RegExp(name + "=([^;]+)");
		var value = re.exec(document.cookie);
		return (value != null) ? unescape(value[1]) : "";
}



function setCookie(name, value) { // use: setCookie("name", value);
	var today = new Date();
	var expiry = new Date(today.getTime() + 28 * 24 * 60 * 60 * 1000); // plus 28 days
		//document.cookie=name + "=" + escape(value) + "; path=/; expires=" + expiry.toGMTString();
	document.cookie=name + "=" + escape(value) + "; path=/;"
}


function Init(){
	// body onload
	// This expands the menu to the item that was clicked
	var ids = getCookie('nav').split(":");
	for( var i = 0; i < ids.length; i++ ){
		if( i == 0 ) ids[0] = ids[0].replace("null",""); // don't know why this is happen.. Try to fix later.
		var who = document.getElementById(ids[i]);
		var itm = document.getElementById( ids[i] + 'Link');
		if( who != null) who.style.display = 'block';
		if( itm != null) itm.className = 'panelMenuItemsHover';
	}
	
	// force us not to be framed in.
	if (self != top && location.href.indexOf('/secure/main/login.aspx') >= 0){
		top.location.href = self.location.href;
	}

}

function focusInit(){

}


function getObj( who ){ 

    // first try to look it up directly.
    var el = document.getElementById( who );
    if( el != null ){
        return el;
    }

    // scan all the elements
    var tagName = ( getObj.arguments[1] != null ? getObj.arguments[1] : '*' );
    var col = document.getElementsByTagName( tagName );
    
    for(var i=0;i<col.length;i++)
    {
	    el = col[i];

	    if(el.id != null) //MAC Safari Error with el.id.indexOf
	    {
		    if(el.id.indexOf( who ) > -1){
		        return el;	
		    }
	    }
    }
	
	return null;
}


function getVal( who ){ return ( getObj( who ) ? getObj( who ).value : "" ); }


function setElementFocus(who){
	if( document.getElementById(who) != null ) document.getElementById(who).focus();
}

function unloadHelp(){
	
}

function showHelp(referer){
	HELP_WIN = openWin( '/secure/help/helpLoader.aspx?help='+referer, 'helpWin', 'left=' + (screen.availWidth - 550) + ',top=0,width=550,height=' + screen.availHeight + ',toolbar=0,location=0,directories=0,status=1,menuBar=0,scrollBars=1,resizable=1' );
	HELP_WIN.focus();
}

function showHelpFromPageId( who ){
	HELP_WIN = openWin( '/secure/help/helpLoader.aspx?PageId=' + who, 'helpWin', 'left=' + (screen.availWidth - 550) + ',top=0,width=550,height=' + screen.availHeight + ',toolbar=0,location=0,directories=0,status=1,menuBar=0,scrollBars=1,resizable=1' );
	HELP_WIN.focus();
}

function maxWindow( win ){
	resizeWindow( win, screen.availWidth, screen.availHeight, 0, 0 );
}

function resizeWindow( win, w, h, x, y ){
	win.moveTo( x, y);
	win.resizeTo( w, h );
}

function showSearch( isClientList, isRepList, isBrokerDealerList, ControlName ){
	loadwindow( '/secure/controls/EntitySearch.aspx?isClientList=' + isClientList + '&isRepList=' + isRepList + '&isBrokerDealerList=' + isBrokerDealerList + '&ControlName=' + ControlName,350,400 );
}

function showParticipantSearch( ControlName ){
	loadwindow( '/secure/retirement/reports/participant/participant_search.aspx?ControlName=' + ControlName,350,400 );
}

function showProductSearch( entityLevel, ControlName ){
	loadwindow( '/secure/controls/ProductSearch.aspx?entity=' + entityLevel + '&ControlName=' + ControlName,350,400 );
}

function loadQuickDates( controlId, showInception ){
	if(location.href.indexOf('/atp/') >= 0){
		loadwindow('/secure/controls/calendar/QuickDates.aspx?isATP=1&controlId=' + controlId + "&showInception=" + showInception,350,400 );//,event.screenY + "px",event.screenX + "px");
	}
	else{
		loadwindow('/secure/controls/calendar/QuickDates.aspx?controlId=' + controlId + "&showInception=" + showInception,350,400 );
	}
}

function loadProductSearch(ff, sc, all, entityType, currProducts, numAllowSel ){
	//numAllowSel if 1, then only allow 1 product to be selected, otherwise, unlimited
	if(location.href.indexOf('/atp/') >= 0){
		loadwindow( '/secure/controls/ProductSearch.aspx?isATP=1&ff=' + ff + '&sc=' + sc + '&currProds=' + currProducts + '&numAllowSel=' + numAllowSel,350,420 );
	}
	else{
		loadwindow( '/secure/controls/ProductSearch.aspx?ff=' + ff + '&sc=' + sc + '&all=' + all + '&currProds=' + currProducts + '&numAllowSel=' + numAllowSel,350,420 );
	}
}

function SetCursorWait(){
	document.body.style.cursor = 'wait';
}

function SetCursorDefault(){
	document.body.style.cursor = 'default';
}

function getPageOffsetLeft(obj) {
	var ol=obj.offsetLeft;
	while ((obj=obj.offsetParent) != null) { ol += obj.offsetLeft; }
	return ol;
}

function getPageOffsetTop(obj) {
	var ot=obj.offsetTop;
	while((obj=obj.offsetParent) != null) { ot += obj.offsetTop; }
	return ot;
}

/* DHTML Windows */


function iecompattest(){
return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function drag_drop(e){
if (ie5&&dragapproved&&event.button==1){
document.getElementById("dwindow").style.left=tempx+event.clientX-offsetx+"px"
document.getElementById("dwindow").style.top=tempy+event.clientY-offsety+"px"
}
else if (ns6&&dragapproved){
document.getElementById("dwindow").style.left=tempx+e.clientX-offsetx+"px"
document.getElementById("dwindow").style.top=tempy+e.clientY-offsety+"px"
}
}

function initializedrag(e){
offsetx=ie5? event.clientX : e.clientX
offsety=ie5? event.clientY : e.clientY
document.getElementById("dwindowcontent").style.display="none" //extra
tempx=parseInt(document.getElementById("dwindow").style.left)
tempy=parseInt(document.getElementById("dwindow").style.top)

dragapproved=true
document.getElementById("dwindow").onmousemove=drag_drop
}

function loadwindow(url,width,height){
	w = ( document.all ? document.body.clientWidth : window.innerWidth );
	h = ( document.all ? document.body.clientHeight : window.innerHeight );
	w = ( w - width );
	if( w < 2 ) w = 2;
	h = ( h - height );
	if( h < 2 ) h = 2;

	if (!ie5&&!ns6)
	window.open(url,"","width=width,height=height,scrollbars=1")
	else{
	document.getElementById("dwindow").style.display=''
	document.getElementById("dwindow").style.left= (w/2) + "px";
	document.getElementById("dwindow").style.top = ns6? window.pageYOffset*1+30+"px" : iecompattest().scrollTop*1+30+"px"; //50; //= (h/2) + "px"; //ns6? window.pageYOffset*1+30+"px" : iecompattest().scrollTop*1+30+"px"
	document.getElementById("dwindow").style.width = width+"px";
	document.getElementById("dwindow").style.height = height+"px";


	document.getElementById("cframe").src=url
	}
}



function stopdrag(){
dragapproved=false;
document.getElementById("dwindow").onmousemove=null;
document.getElementById("dwindowcontent").style.display="" //extra
}




function closeit(){
  document.getElementById("dwindow").style.display="none"
}


function openWin( windowURL, windowName, windowFeatures ) { 
	return window.open( windowURL, windowName, windowFeatures ) ; 
} 

function openPdf( urlPath ){
	var newWindow = openWin( urlPath, 'pdfWin', 'left=0,top=0,width=350,height=400,toolbar=0,location=0,directories=0,status=1,menuBar=0,scrollBars=1,resizable=1' );
	newWindow.focus();
}

function openSelfSizedWebPage( urlPath, w, h ){
	var newWindow = openWin( urlPath, 'webPage', 'width=' + w + ',height=' + h + ',toolbar=1,location=0,directories=0,status=1,menuBar=1,scrollBars=1,resizable=1' );
	newWindow.focus()
}

function openSelfSizedWebPageNoToolbar( urlPath, w, h ){
	var newWindow = openWin( urlPath, 'webPage', 'width=' + w + ',height=' + h + ',toolbar=0,location=0,directories=0,status=1,menuBar=1,scrollBars=1,resizable=1' );
	newWindow.focus()
	return newWindow;
}

function openSelfSizedWebPageNoMenu( urlPath, w, h ){
	var newWindow = openWin( urlPath, 'webPage', 'width=' + w + ',height=' + h + ',toolbar=0,location=0,directories=0,status=1,menuBar=0,scrollBars=1,resizable=0' );
	newWindow.focus()
	return newWindow;
}

function openAlert( urlPath ){
	var newWindow = openWin( urlPath, 'webAlert', 'width=450,height=250,toolbar=0,location=0,directories=0,status=1,menuBar=0,scrollBars=1,resizable=1' );
	newWindow.focus();
}
function openWebPage( urlPath ){
	var newWindow = openWin( urlPath, 'webPage', 'width=775,height=575,toolbar=1,location=0,directories=0,status=1,menuBar=1,scrollBars=1,resizable=1' );
	newWindow.focus();
}

function openWebPageAllTools( urlPath ){
	var newWindow = openWin( urlPath, 'webPage', 'width=775,height=575,toolbar=1,location=1,directories=1,status=1,menuBar=1,scrollBars=1,resizable=1' );
	newWindow.focus();
}


function showHide( el ){
	var who = document.getElementById(el);
	var itm = document.getElementById( el + 'Link');
	if( who.style.display == '' || who.style.display == 'none' ){
		who.style.display = 'block';
		if( itm != null) itm.className = 'panelMenuItemsHover';
		setCookie('nav' , getCookie('nav') + el + ':' );
	}else{
		who.style.display = 'none';
		if( itm != null ) itm.className = 'panelMenuItems';
		var re = new RegExp ( el + ':' , 'gi') ;
		setCookie( 'nav', getCookie('nav').replace(re,"") );
	} 
}

/* ex.
mask(this,'2,5','/,/'); //date
<INPUT onblur="javascript:return mask(this,'0,4,8','(,),-');" onkeyup="javascript:return mask(this,'0,4,8','(,),-');" onfocus="this.select();">
*/
function mask(me,l,d){
	var ls = l.split(',');
	var ds = d.split(',');
	var s = me.value;

	for (var i = 0; i <= ls.length; i++){
		for (var n = 0; n <= s.length; n++){
	 		if (n == ls[i]){
	  			if (s.substring(n, n+1) != ds[i]){
	   				s = s.substring(0,n) + ds[i] + s.substring(n,s.length)
	  			}
	 		}
		}
	}
	me.value = s
}

function formatDate( me ){
	return 1;
}

function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num)) return num;
cents = Math.floor((num*100+0.5)%100);
num = Math.floor((num*100+0.5)/100).toString();
if(cents < 10 && cents > -1 ) cents = "0" + cents;	
if(cents < 0) cents = "00";
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
return ('$' + num + '.' + cents);
//return (num + '.' + cents);
}





function clean( me ){
	var s = me.value;
	if( s.substring(s.length-1,s.length) ) return s.substring(0,s.length-1);
}

function setLoadingText( who ){
	setLoadingTextSaveValue( who, false );
}

function setLoadingTextSaveValue( who, saveValue ){
	sel = document.getElementById(who);
	if( sel ){
		var o = new Option();
		o.text = 'Loading...';
		o.value = ( saveValue ? sel[sel.selectedIndex].value : '' );
		sel.options[0] = o;
		sel[0].selected = true;
	}
}

function PostToPage( f, loc ){

	f.__ViewState.value = '';
	f.action = loc;
	f.submit();

}


/* DOM functions */
function BindGrid( dataSet, tbodyId, fields, bClear ){


	var tbody = document.getElementById( tbodyId );
	var dt = dataSet.Tables[0];
	
	
	if( bClear ){ ClearNodes( tbody ); }
	var expression = 0;
	
	if( dt.Rows.length == 0 ){
		var trNone = document.createElement("tr");
		var tdNone = document.createElement("td");
		tdNone.colSpan = fields.length+1;
		tdNone.appendChild( document.createTextNode( "No results were found." ) )
		trNone.appendChild( tdNone );
		tbody.appendChild( trNone );
		return expression;
	}
	
	for( var i = 0; i < dt.Rows.length; i++ ){
		var tr = document.createElement( "tr" );
		tr.className = "";
		tr.className = ( (i % 2) == 0 ? "gridrow" : "gridrowalt" );
		
		for( var f = 0; f < fields.length; f++ ){
			var td = document.createElement( "td" );
			//var val = "";
			//if( fields[f]['ColumnName'] ){
				var val = eval( 'dt.Rows[' + i + '].' + fields[f]['ColumnName'] );
				//if( ! val ) val = fields[f]['ColumnName'];
			//}
			
			//if( fields[f]['ColumnText'] ){
				//var = fields[f]['ColumnText'];
			//}
			
		
			if( fields[f]['Style'] ){
				td.style.cssText = fields[f]['Style'];
			}
			td.className = ( (i % 2) == 0 ? "gridcell" : "gridcellalt" );
			
			// Evaluate the expression
			if( fields[f]['Expression'] ){ 
				if( fields[f]['Expression'] == 'Sum' ){
					expression += val; 
				}
				if( fields[f]['Expression'] == 'Value' ){
					expression = val;
				}
			}
			
			// The field is a link
			if( fields[f]['Link'] ){
				var arg = eval( 'dt.Rows[' + i + '].' + fields[f]['LinkArgument'] );
				val = '<a href="javascript:' + fields[f]['Link'] + '(' + arg + ');">' + val + '</a>';
			}
			
			// The field is a checkbox
			/*
			if( fields[f]['Checkbox'] ){
				var arg = eval( 'dt.Rows[' + i + '].' + fields[f]['LinkArgument'] );
				val = '<input type="checkbox" id="' + fields[f]['Checkbox'] + '" name="' + fields[f]['Checkbox'] + '" value="' + arg + '" onclick="alert(this.value);">';
			
			}
			*/
			
			// Formatting
			if( fields[f]['Format'] ){
				if( fields[f]['Format'] == 'Currency' ){
					val = Math.round(val*100)/100 
					var isNeg = false; 
					var valCopy = val;
					if( val < 0 ){
						isNeg = true;
						valCopy = val * -1;
					}
					valCopy = formatCurrency( valCopy );
					if( isNeg ){
						valCopy = '(' + valCopy + ')';
					}
					td.innerHTML = valCopy;
					//td.appendChild( document.createTextNode( valCopy ) );
				}else if( fields[f]['Format'] == 'Round3' ){
					td.innerHTML = Math.round( val * 1000 )/1000;
					//td.appendChild( document.createTextNode( Math.round( val * 1000 )/1000 ) );
				}else if( fields[f]['Format'] == 'Round4' ){
					td.innerHTML = Math.round( val * 10000 )/10000;
				}else if( fields[f]['Format'] == 'Round6' ){
					td.innerHTML = Math.round( val * 1000000 )/1000000;
				}else if( fields[f]['Format'] == 'Date' ){
					//val = new Date( val );
					td.innerHTML = val; // javascript new Date(val) does not convert correctly.  (val.getMonth() + 1) + '/' + val.getDay() + '/' + val.getFullYear();
				}else if( fields[f]['Format'] == 'Percent' ){
					if( val < 1){ val = Math.round((val*100)*1000)/1000; }
					td.innerHTML = val + '%';
					//td.appendChild( document.createTextNode( (val.getMonth() + 1) + '/' + val.getDay() + '/' + val.getFullYear() ) );
				}else{
					td.innerHTML = val;
					//td.appendChild( document.createTextNode( val ) );
				}
			}else{
				td.innerHTML = val;
				//td.appendChild( document.createTextNode( val ) );
			}
			
			
			
			tr.appendChild( td );
		}
		tbody.appendChild( tr );
	}
	
	return expression;
}

function ClearNodes( theNode )
{
	while( theNode.rows.length != 0 ){
		theNode.deleteRow(0);
	}
}

//checks all DataGrid CheckBoxes with the given name with the given value

function CheckAllDataGridCheckBoxes(aspCheckBoxID, checkVal) {
    re = new RegExp( aspCheckBoxID );  //dgRMDClients//generated control name starts with a colon

    for(i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i];

        if (elm.type == 'checkbox') 
        {

            if (re.test(elm.name)) 
            {
                elm.checked = checkVal;
            }
        }
        
       // alert( aspCheckBoxID );
    }
}

function CheckSubmit(e, btnName) {
    var key = '';
    if (window.event){
       key = event.keyCode;
    }
    else{
       key = e.which;  
    }
    
    if (key == 13){
        alert('Using the Enter key is not supported. Please click the ' + btnName + ' button instead.');
    }
    return (key != 13);
}

function ObjectToArray(obj) {
    if(!obj) return new Array();
    if(!obj.length) return new Array(obj);
    return obj;
}

