//
// this file contains Javascript written by the webapp developers,
//  as opposed to "scripts.js" which is written by the HTML folks downstairs
//
var printChildScripts = false;
	// ============================================================================


	/*
	 * this function doesn't actually DO anything; instead it's meant to be used
	 *  like <a href="javascript:openPopup()"> for clickable images; that way
	 *  the URL displayed in the browser status doesn't look "error-like" as
	 *  when it's reported as "javascript:Null()"
	 *
	 * rgitzel, 10.28.05
	 */
	function openPopup()
	{
		return( null ) ;
	}

	                                     
	// ============================================================================


	/*
	 * use this as target of a 'cancel' button on a popup
	 *
	 * rgitzel
	 */
	function cancelPopup()
	{
		window.close() ;

		return( false ) ;
	}

	
	// ============================================================================


	/*
	 * use this when you need to put the results of a form into a popup,
	 *  and when you need to know which button was pressed
	 *
	 * rgitzel
	 */
	function submitToPopUpWithButton( form, buttonName, popupAction, width, height ) 
	{
		return( submitToPopUpWithButton( form, buttonName, popupAction, width, height, 'yes' ) ) ;
	}

	
	// ============================================================================


	/*
	 * use this when you need to put the results of a form into a popup,
	 *  and when you need to know which button was pressed
	 * 
	 * --> new method to include argument for scrollbars (vchan).
	 * 
	 * rgitzel
	 */
	function submitToPopUpWithButton( form, buttonName, popupAction, width, height, scrollbars ) 
	{
		var windowName = "popup" ;
		
		// create the window for the form to be submitted to
		window.open( 'about:blank', windowName, 'directories=0, location=0, menubar=0, status=1, toolbar=0, resizable=yes, scrollbars=' + scrollbars + ', width=' + width + ', height=' + height ) ; // + ', top=' + yy + ', left=' + xx) ; 	
		
		// grab the current values for the form
		var currentAction = form.action ;
		var currentTarget = form.target ;
		
		// change the form and submit
		if( ( popupAction != null ) && ( popupAction != "" ) )
		{
			form.action = popupAction;
		}
		form.elements.selectedButton.value = buttonName ;
		form.target = windowName ;

		form.submit() ;
		
		// set them back (if you don't, your original window won't submit to itself, later)
		form.target = currentTarget ;
		form.action = currentAction ;
		form.elements.selectedButton.value = '' ;
		
		return( false ) ;
	}

	
	// ============================================================================


	function submitToPopUp( form, popupAction, width, height ) 
	{
		var windowName = "popup" ;
		
		
		// create the window for the form to be submitted to
		window.open( 'about:blank', windowName, 'directories=0, location=0, menubar=0, status=0, toolbar=0, resizable=yes, scrollbars=yes, width=' + width + ', height=' + height ) ; // + ', top=' + yy + ', left=' + xx) ; 	
		
		// grab the current values for the form
		var currentAction = form.action ;
		var currentTarget = form.target ;
		
		// change the form and submit
		if( ( popupAction != null ) && ( popupAction != "" ) )
		{
			form.action = popupAction;
		}
		form.target = windowName ;
		form.submit() ;
		
		// set them back (if you don't, your original window won't submit to itself)
		form.target = currentTarget ;
		form.action = currentAction ;
		
		return( false ) ;
	}


	
	function submitDispatchToPopUp(form, popup, width, height, buttonName, searchName) {
		window.open('about:blank', 'popup', 'directories=0, location=0, menubar=0, status=0, toolbar=0, resizable=yes, scrollbars=yes, width=' + width + ', height=' + height); // + ', top=' + yy + ', left=' + xx); 	
		var action = form.action;
		var target = form.target;
		if (popup == null || popup == "") {
			popup = action;
		}
		form.target='popup';
		form.submit();
		// set the button attribute in the form, since we have bypassed the html Submit process
		form.setAttribute("button(" + buttonName + ").x", "1");
		form.setAttribute("button(" + buttonName + ").y", "1");
		form.action = popup;
		form.target = target;
		form.action = action;
			
		return false;
	}
	
	// ============================================================================
	
	
	function openInParent( popWindow, destinationHref )
	{
		if (popWindow.opener != null)
		{
			popWindow.opener.location.href = destinationHref ;
			//popWindow.close();
		}
		// else do nothing
	}


	// rgitzel, 12.20.05
	function openInParentAndStayOpen( popWindow, destinationHref )
	{
		if( popWindow.opener != null )
		{
			popWindow.opener.location.href = destinationHref ;
		}
		
		return( false ) ;
	}



	function openPopupStatic(url, options)
	{
		var newwindow=window.open(url,'name',options);
		if (window.focus)
		{
			newwindow.focus()
		}
	}

	
	// ============================================================================


	/*
	 * create a plain old popup with its own URL (i.e. it's not showing
	 *  the output of an explicit HTML form	
	 *
	 * "blockFormChanges" should be true if there might be unsaved data
	 *  on the page... so typically set it to "false"
	 *
	 * rgitzel, 11.04.05
	 */
	function openPopupWindow( url, width, height, blockFormChanges )
	{
		if(width == null) width = 920;
		if(height == null) height = 690;
		var options, w ;
		
		
		if( blockFormChanges && ! _blockUserIfFormHasChanged( LEAVING_FORM_MESSAGE ) )
		{
			// skip the popup
		}
		else
		{
			options = "height=" + height + ",width=" + width + ",scrollbars=yes,resizable=yes" ;
			
			w = window.open( url, 'toolboxPopup', options ) ;
			//w.resizeTo( width, height ) ; 
			w.focus() ; 
		}
				
		return( false ) ;
	}
    /*
     * This function extract the content body out and put in a popup window for printing.
     *
     * Dependencies: 
     *  -- Forex site uses this function (jkoett@bstage.ca for more info).
     *  -- Toolbox site uses this file.
     *
     *  Jeff Li
     */
    function openPrintWindow(printTimestamp, html) {
	    	var w;
    	 if(html != null){
			w = window.open( "", "investools_print", "width=830,height=640,menubar=yes,status=no,scrollbars,resizable,screenX=20,screenY=40,left=20,top=40");
			
			var newContent = new StringBuffer();
          	newContent.append("<html>",
          		"<head>",
          		"</head>",
          		"<body class='printbody' onload='window.print();'>",
          		html,
          		"</body></html>");	
            w.document.write(newContent.toString());
            w.document.close();
            w.focus();
    	 } else {
	        if ($('#contentArea').length > 0 ) {
		        
	            var printHead = $('head');
	           	var pageTitle = $('#pageTitle').html();//document.getElementById('pageTitle').cloneNode(true).innerHTML;
				
				$('#contentArea').find('input').each(function(){
					if($(this).css("display") != "none"){
						var val = "";
						if($(this).attr("type") == "checkbox"){
							val = "N";
							if($(this).attr("checked")) val = "Y";
						}else{
							val = ""+$(this).val();
						}
						if(val == "undefined") val = "";
						$(this).attr("hold", val);
					}
				});
				
				$('#contentArea').find('select').each(function(){
					if($(this).css("display") != "none"){
						$(this).attr("hold", $(this).val());
					}
				});
				
				var printContentHTML;
				var tempReadyList = $.readyList;
				$.readyList = [];
				$.isReady = false;
				var printContent = $('<td/>').html($('#contentArea').html());
				
				$(printHead).find('script').remove();
	           	if(!printChildScripts){
				//	$(printContent).find('script').remove();
				}
				$(printContent).find('div').each(function(){
					if($(this).css("display") == "none")
						$(this).remove();
				}).find('ul.jd_menu').html("");
				//each(function(){
				//	if($(this).css("display") == "none" ||
				//	 $(this).is('jd_menu'))
				//		$(this).remove();
				//});
				$(printContent).find('input').each(function(){
					if($(this).css("display") != "none"){
						if($(this).attr("type") == "text" || $(this).attr("type") == "checkbox") {
							var val = ""+$(this).attr("hold");
							if(val == "undefined") val = "";
							$(this).after('<span>'+val+'</span>');
							$(this).remove();
						}
					}
				});
				
				$(printContent).find('select').each(function(){
					if($(this).css("display") != "none"){
						var val = ""+$(this).val();
						var vals = $(this).get(0).options;
						for(var i = 0; i < vals.length; i++){
							if($(vals[i]).val() == $(this).attr("hold")){
								val = $(vals[i]).html();
							}
						}
						$(this).after('<span>'+val+'</span>');
						$(this).remove();
					}
				});
				
	            printContentHTML =  pageTitle +
	                                "<img src='"+$.swim.uris.getImg('spacer')+"' width='200' height='10' border='0' />"+
	                                printTimestamp +" <br /> "+ $(printContent).html();//.innerHTML ;

	            printContent = null;       
				var printHeadHTML = $(printHead).html();//.innerHTML;
				printHead = null;            
	
	            // remove all the links so the print page won't be functional
				printContentHTML = printContentHTML.replace(/<a[^>]*href\s*=\s*("[^"]+"|'[^']+'|[^\s"'])/gi,'<a');
	            printContentHTML = printContentHTML.replace(/action\s*=\s*("[^"]+"|'[^']+'|[^\s"'])/gi,'');
	            printContentHTML = printContentHTML.replace(/<\s*form/gi,'<no_form');
	            printContentHTML = printContentHTML.replace(/\s+onclick/gi,' no_onclick');
				printContentHTML = printContentHTML.replace(/\s+onchange/gi,' no_onchange');
				printContentHTML = printContentHTML.replace(/\s+onmouseover/gi,' no_onmouseover');
				printContentHTML = printContentHTML.replace(/\s+onmouseout/gi,' no_onmouseout');
				
				w = window.open( "", "investools_print", "width=830,height=640,menubar=yes,status=no,scrollbars,resizable,screenX=20,screenY=40,left=20,top=40");
				
				var newContent = new StringBuffer();
	          	newContent.append("<html>",
	          		"<head>",printHeadHTML,
	          		"</head>",
	          		"<body class='printbody' onload='window.print();'>",
	          		printContentHTML,
	          		"</body></html>");	
	            w.document.write(newContent.toString());
	            w.document.close();
	            w.focus();
	            
	        	$.readyList = tempReadyList;
	        	$.isReady = true;
	        } else {
	            alert("Sorry, content cannot be found to display.");
	        }
    	 }
    }

    // empty function for helping LivePerson set text for links. 
    function setLivePersonVariables(){}
    /*
     * All the links open up live chat application should call this function instead of doing that by itself
     * This function also set necessary query strings.
     *
     *  Jeff Li
     */
    function openLiveChat(width, height){
        //alert(typeof setLivePersonVariables =="function");
        if(width == undefined) width=80;
        if(height == undefined) height=18;
        //if(color == undefined || color.length <=0)   color = "white";
        var iframeOut = '<!-- Begin Chat Code -->'
                +'<table cellpadding="0" cellspacing="0" border="0" >'
	            +'<tr><td valign="bottom"><iframe name="liveChatiframe" id="liveChatiframe" onload="if(typeof setLivePersonVariables) setLivePersonVariables(this);" src="'+contextPath+'/common/liveperson/chat_deployment_local-investools/investools-default-chat-english_text.jsp" frameborder="0" marginheight="0" marginwidth="0" scrolling="no"' 
                +' height="'+height+'" width="'+width+'"></iframe></td></tr></table>'
                +'<!-- End Chat Code -->';
         document.write(iframeOut);   
        
        //window.frames['liveChatiframe'].document.bgColor = color;
    }

/*    function openLiveChat(){
        var coachString;
        
        if(isCoached){
           coachString = 'Pre-Chat_Survey_Hotline';  
        }else{
           coachString = 'Pre-Chat_Survey_No_Hotline';    
        }
        var liveChatLink = 'https://server.iad.liveperson.net/hc/91632676/?cmd=file&file=visitorWantsToChat&site=91632676&SESSIONVAR!survey_pre-chat='+coachString+'&imageUrl=https://online.investools.com/livechat&referrer='+escape(document.location);
        
        //alert(coachString+" "+liveChatLink);
        
        window.open(liveChatLink,'chat91632676','width=472,height=320');
        return false;        
    }*/

   function openFXLiveChat(){
        var coachString;
        
        if(isFXCoached){
           coachString = 'FX pre-chat survey hotline';  
        }else{
           coachString = 'FX pre-chat survey no hotline';    
        }
        var liveChatLink = 'https://server.iad.liveperson.net/hc/91632676/?cmd=file&file=visitorWantsToChat&site=91632676&SESSIONVAR!skill=FXSales&survey_pre-chat='+coachString+'&imageUrl=https://online.investools.com/livechat&referrer='+escape(document.location);
        
        //alert(coachString+" "+liveChatLink);
        
        window.open(liveChatLink,'chat91632676','width=472,height=320');
        return false;        
    }
   
   
   // newer better more awesomer live chat link
   function liveChatAction(skill){
		var popup = window.open('http://sales.liveperson.net/hc/91632676/?cmd=file&file=visitorWantsToChat&site=91632676&SESSIONVAR!skill='+skill+'&imageUrl=http://sales.liveperson.net/hcp/Gallery/ChatButton-Gallery/English/General/1a/&referrer='+escape(document.location),'chat91632676','width=472,height=320,resizable=yes');
	   	popup.focus();
	   	return false;
   }
   
   /**
    * Events module - one to one coaching
    * same as one-to-one in coaching tab
    */
   function liveChatOneToOneCoaching()
   {
	   //the code below for lpMTagConfig was provided by liveperson support. The original code
	   //is in the ms-word doc attached to JIRA issue INVT-539 http://scm.iedlab.com/jira/browse/INVT-539
	   if (typeof(lpMTagConfig.sessionVar) == "undefined"){ lpMTagConfig.sessionVar = new Array();}
	   //lpMTagConfig.sessionVar[lpMTagConfig.sessionVar.length] = 'skill=Coaching';

	   return liveChatAction("Coaching");
   }

   /**
    * Investools Online - Student - No coaching 
    */
   function liveChatOnlineStudentNoCoaching()
   {
	   //the code below for lpMTagConfig was provided by liveperson support. The original code
	   //is in the ms-word doc attached to JIRA issue INVT-539 http://scm.iedlab.com/jira/browse/INVT-539
	   if (typeof(lpMTagConfig.sessionVar) == "undefined"){ lpMTagConfig.sessionVar = new Array();}
	   //lpMTagConfig.sessionVar[lpMTagConfig.sessionVar.length] = 'skill=Student';
	   
	   return liveChatAction("Student");
   }
   
   /**
    * Investools Online - Student - With coaching 
    */
   function liveChatOnlineStudentWithCoaching()
   {
	   //the code below for lpMTagConfig was provided by liveperson support. The original code
	   //is in the ms-word doc attached to JIRA issue INVT-539 http://scm.iedlab.com/jira/browse/INVT-539
	   if (typeof(lpMTagConfig.sessionVar) == "undefined"){ lpMTagConfig.sessionVar = new Array();}
	   //lpMTagConfig.sessionVar[lpMTagConfig.sessionVar.length] = 'skill=Student with Coaching';

	   return liveChatAction("Student%20with%20Coaching");
   }

   /**
    * Investools.com livechat 
    */
   function liveChatInvestoolsDotCom()
   {
	   //the code below for lpMTagConfig was provided by liveperson support. The original code
	   //is in the ms-word doc attached to JIRA issue INVT-539 http://scm.iedlab.com/jira/browse/INVT-539
	   if (typeof(lpMTagConfig.sessionVar) == "undefined"){ lpMTagConfig.sessionVar = new Array();}
	   //lpMTagConfig.sessionVar[lpMTagConfig.sessionVar.length] = 'skill=Investools.com';

	   return liveChatAction("Investools.com");
   }

   
   
   
   function knowledgeBaseSearchPopup(searchword){
       var attachedQuery = 'action=search&query='+searchword;  
       knowledgeBasePopup(attachedQuery);
       //return false;
   }


   function knowledgeBasePopup(attachedQuery){
       var w = window.open('https://server.iad.liveperson.net/hc/s-91632676/cmd/kbresource/front_page!PAGETYPE?VisitorProfile=Knowledgebase&MESSAGEVAR!NewUser=Yes&'+attachedQuery, "knowledgeBase",
               "width=750,height=900,status,scrollbars,resizable,screenX=20,screenY=40,left=20,top=40");
       w.focus();
       //return false;
   }

    function redirectToTOS(dontSavePreference, srcCode){
        // save the millisecond time for later stat reference.
        if (!dontSavePreference) {
	        savePreference('last.TOS.landing.redirect', new Date().getTime(), null);
	    }
	    var srcCode = srcCode ? srcCode : '0906_02';
        alertTOS();
        var w = window.open("https://www.thinkorswim.com/tos/displayITLanding.tos?srcCode=" + srcCode, "TOSpopup",'left=20, top=20,scrollbars=yes,menubar=yes,status=yes,resizable=yes');
        if(w) w.focus();
        return false;
   }

   function redirectToTOSCanada(){
        alertTOS();
        var w = window.open("http://www.thinkorswimcanada.com","TOSpopup",'left=20, top=20,scrollbars=yes,menubar=yes,status=no,resizable=yes');
        if(w) w.focus();
        return false;
   }

   function alertTOS() {
		alert("You are now leaving the Investools website. The website you have chosen to enter is created and maintained by thinkorswim, Inc., member FINRA | SIPC | NFA. thinkorswim, Inc. is a wholly owned subsidiary of TD AMERITRADE Holding Corporation. " + unescape("%A9") + " 2009 TD AMERITRADE IP Company, Inc.");
   }
   
   function redirectToTDA(){
        // save the millisecond time for later stat reference.
        savePreference('last.TDA.landing.redirect', new Date().getTime(), null);
        alertTDA();
        var w = window.open("https://wwwna.tdameritrade.com/cgi-bin/apps/AccountApServlet?segment=inve FO stools", "TDApopup",'left=20, top=20,scrollbars=yes,menubar=yes,status=yes,resizable=yes');
        if (w) w.focus();
        return false;
   }

   function alertTDA() {
       alert("You are now leaving the Investools website. The website you have chosen to enter is created and maintained by Investools' affiliated broker-dealer, TD AMERITRADE, Inc., member FINRA/SIPC. TD AMERITRADE is a trademark jointly owned by TD AMERITRADE IP Company, Inc. and The Toronto-Dominion Bank. " + unescape("%A9") + " 2009 TD AMERITRADE IP Company, Inc. All rights reserved. Used with permission.");
   }

   function openFlyBy() {
       w2 = window.open("http://education.investools.com/content/website/demos2/flyBy.html",
	            "investoolsInvestingFoundation", 
	            "width=820,height=535,left=200,top=150,menubar=no,toolbar=no");
	   w2.focus();
   }
