var url = window.location + '';
function showLoading(container){
	var ele = Element.get(container);
	var pos = Element.getXY(ele);
	var size = Element.getSize(ele);
	// create new transparent div and attach to DOM
	var indicator = Element.create('div',{id: 'loading_'+container, className: 'loadingIndicator'},'', document.body);
	indicator.style.width = size.width+'px';
	indicator.style.height = size.height+'px';
	indicator.style.left = pos.x+'px';
	indicator.style.top = pos.y+'px';
	// create new loading gif and attach to new div
	var graphic = Element.create('img', {src:'../../common/img/loading/loading.gif',className:'loadingIndicator'}, '', indicator);
	graphic.style.left = parseInt(size.width / 2 - 15)+'px';
	graphic.style.top = parseInt(size.height / 2 - 15)+'px';
}
function hideLoading(container){Element.remove('loading_'+container)}
var RRailTabs = function(){
  $(".smallTabs li.inactive").live("click", function(){
    var type = this.id.split("_")[0];
    var typeID = this.id.split("_")[1];
    if(type == "fe"){
      $("#featuredEducation ul li").attr("class", "inactive");
      $("#" + this.id).attr("class", "active");
      $("#featuredEducation .featEventsDiv").attr("class", "featEventsDiv tabOff");
      $("#div_fe_" + typeID).attr("class", "featEventsDiv tabOn");
    }else if(type == "il"){
      $("#interactiveLearning ul li").attr("class", "inactive");
      $("#" + this.id).attr("class", "active");
      $("#interactiveLearning .interactiveLearningDiv").attr("class", "interactiveLearningDiv tabOff");
      $("#div_il_" + typeID).attr("class", "interactiveLearningDiv tabOn");
    }else if(type == "mp"){
      $("#mostPopular ul li").attr("class", "inactive");
      $("#" + this.id).attr("class", "active");
      $("#mostPopular .mostPopularDiv").attr("class", "mostPopularDiv tabOff");
      $("#div_mp_" + typeID).attr("class", "mostPopularDiv tabOn");
    }else if(type == "nb"){
      $(".notebookBlock ul li").attr("class", "inactive");
      $("#" + this.id).attr("class", "active");
      $(".notebookDiv").attr("class", "notebookDiv tabOff");
      $("#div_nb_" + typeID).attr("class", "notebookDiv tabOn");
    }
  });
}

var emailForm = function(){
	var el = $('img.emailBtn')[0];
	this.createBub(el);
	this.setEvents();
	$('img.emailBtn').bind('click', function(){email.bub.BlowBubble();});
}
emailForm.prototype.createBub = function(el){
	var content = '';
	content += "<form class='emailForm'>"
	content += '<table>';
	content += '<tr>';
	content += "<td><label for='sendName'>Your Name</label></td><td><input id='sendName' type='text'></input></td>";
	content += '</tr><tr>'
	content += "<td><label for='sendEmail'>Your E-mail</label></td><td><input id='sendEmail' type='text'></input></td>";
	content += '</tr><tr>'
	content += "<td><label for='recName'>Recipient Name</label></td><td><input id='recName' type='text'></input></td>";
	content += '</tr><tr>'
	content += "<td><label for='recEmail'>Recipient E-mail</label></td><td><input id='recEmail' type='text'></input></td>";
	content += '</tr><td>'
	content += "<td><input type='button' id='emailBtnSubmit' value='Send' /></td>";
	content += '<table>';
	content += "<input type='text' id='pot' style='display:none'></input>";
	content += "</form>";

	this.formHTML = $(content);

	this.bub = new InfoBubble();
	this.bub.bubbleWidth = 300;
	this.bub.title = 'E-mail Form';
	this.bub.enableRollOutPop = false;
	this.bub.SetContent(content);
	var xy = Element.getXY(el);
	var size = Element.getSize(el);
	this.bub.SetPoint = "none";
	this.bub.Init();
	this.bub.AttachBubble(Element.get("main"));
	this.bub.MoveBubble(xy.x, xy.y + 15, size);
}
emailForm.prototype.setEvents = function(bub){
	$('form.emailForm #emailBtnSubmit').live('click', function(){
		var valid = true;
		var docid = $('input#docId').val();
		var sendEmail = $('input#sendEmail').val();
		var recEmail = $('input#recEmail').val();
		if(!email.validateEmail(sendEmail) || !email.validateEmail(recEmail)){
			alert('Please enter valid e-mail addresses')
			valid = false;
		}
		var data = {
			sendName: $('input#sendName').val()
			,sendEmail: sendEmail
			,recName: $('input#recName').val()
			,recEmail: recEmail
			,url: document.location.href
			,docid: docid
			,pot: $('input#pot').val()
		}
		for(var a in data){
			if (a !== 'pot') {
				if (data[a] == '' || data[a] == ' ' || !data[a]) {
					alert('Please fill out all form fields.');
					valid = false;
				}
			}
		}
		if(valid){
			showLoading('infoBubble');
			if(data.pot == ''){
				$.ajax({
					type: 'POST'
					,url: '../../common/buffer/kcNew/kcEmailSend.asp'
					,data: data
					,error: function(){
						hideLoading('infoBubble');
						email.bub.PopBubble();
						alert('Error sending email.');
						}
					,success: function(data){
						hideLoading('infoBubble');

						//get bubble container
						$cc = $('#ibContentContainer');
						var height = $cc.css('height');
						height = height.replace('px','');
						height = Number(height - 10);
						height = height + 'px';

						if (data == 1 || data == '1') {
							$cc.empty().append('<span style="margin-top:10px;margin-left:10px;display:block; height:' + height + '">Your e-mail was sent successfully!</span>');
						}else{
							$cc.empty().append('<span style="margin-top:10px;margin-left:10px;display:block; height:' + height + '">There was an error sending your e-mail.</span>');
						}

						//set timeout to turn off bubble
						setTimeout(function(){
							email.bub.PopBubble();
							$('#ibContentContainer').empty().append(email.formHTML);
						}, 4000);
					}
				})
			}
		}
	});
}

emailForm.prototype.validateEmail = function(email){
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(email)){return true;}
	return false;
}

var feedbackForm = function(){
	var el = $('a.feedbackLink')[0];
	this.createBub(el);
	this.setEvents();
	$('a.feedbackLink').bind('click', function(){feedback.bub.BlowBubble();});
}
feedbackForm.prototype.createBub = function(el){
	var content = '';
	content += "<form class='feedbackForm'>"
	content += '<table>';
	content += '<tr>';
	content += "<td><label for='sendName'>Your Name</label></td><td><input id='sendName' type='text'></input></td>";
	content += '</tr><tr>'
	content += "<td><label for='sendEmail'>Your E-mail</label></td><td><input id='sendEmail' type='text'></input></td>";
	content += '</tr><tr>'
	content += "<td><label for='feedbackInput'>Feedback</label></td><td><textarea id='feedbackInput' type='text'></textarea></td>";
	content += '</tr><td>'
	content += "<td><input type='button' id='feedbackBtnSubmit' value='Send' /></td>";
	content += '<table>';
	content += "<input type='text' id='pot' style='display:none'></input>";
	content += "</form>";

	this.formHTML = $(content);

	this.bub = new InfoBubble();
	this.bub.bubbleWidth = 300;
	this.bub.title = 'Feedback Form';
	this.bub.enableRollOutPop = false;
	this.bub.SetContent(content);
	var xy = Element.getXY(el);
	var size = Element.getSize(el);
	this.bub.SetPoint = "none";
	this.bub.Init();
	this.bub.AttachBubble(Element.get("main"));
	this.bub.MoveBubble(xy.x, xy.y + 15, size);
}
feedbackForm.prototype.setEvents = function(bub){
	$('form.feedbackForm #feedbackBtnSubmit').live('click', function(){
		var valid = true;
		var docid = $('input#docId').val();
		var sendEmail = $('input#sendEmail').val();
		var feedbackContent = $('textarea#feedbackInput').val();
		var recipient = $('a.feedbackLink').attr('rel');
		recipient = recipient + '@scottrade.com';

		if(!feedback.validateEmail(sendEmail)){
			alert('Please enter valid e-mail addresses')
			valid = false;
		}
		if(feedbackContent == '' || feedbackContent == ' '){
			alert('Please enter feedback information.')
			valid = false;
		}
		var data = {
			recEmail: recipient
			,sendName: $('input#sendName').val()
			,sendEmail: sendEmail
			,feedbackContent: feedbackContent
			,url: document.location.href
			,pot: $('input#pot').val()
		}
		for(var a in data){
			if (a !== 'pot') {
				if (data[a] == '' || data[a] == ' ' || !data[a]) {
					alert('Please fill out all form fields.');
					valid = false;
				}
			}
		}
		if(valid){
			showLoading('infoBubble');
			if(data.pot == ''){
				$.ajax({
					type: 'POST'
					,url: '../../common/buffer/kcNew/feedbackBuffer.asp'
					,data: data
					,error: function(){
						hideLoading('infoBubble');
						feedback.bub.PopBubble();
						alert('Error sending email.');
						}
					,success: function(data){
						hideLoading('infoBubble');

						//get bubble container
						$cc = $('#ibContentContainer');
						var height = $cc.css('height');
						height = height.replace('px','');
						height = Number(height - 10);
						height = height + 'px';

						if (data == 1 || data == '1') {
							$cc.empty().append('<span style="margin-top:10px;margin-left:10px;display:block; height:' + height + '">Your feedback was sent successfully!</span>');
						}else{
							$cc.empty().append('<span style="margin-top:10px;margin-left:10px;display:block; height:' + height + '">There was an error sending you feedback.</span>');
						}

						//set timeout to turn off bubble
						setTimeout(function(){
							feedback.bub.PopBubble();
							$('#ibContentContainer').empty().append(feedback.formHTML);
						}, 4000);
					}
				})
			}
		}
	});
}

feedbackForm.prototype.validateEmail = function(email){
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(email)){return true;}
	return false;
}

var popUpImg = function(){
	var $aTags = $('a.viewGraphic');
	for(var a = 0; a < $aTags.length; a++){
		if ($aTags[a].id) {
			this.loadImg($aTags[a]);
			this.createBox($aTags[a]);
		}
	}
}
popUpImg.prototype.loadImg = function(aTag){
	var src = aTag.id.replace(/_dot_/,'.');
	src = src.replace(/<graphic>/, '');
	src = src.replace(/<\/graphic>/, '');
	src = src.replace(/<[^>]+>/ig,"");
	var image = new Image();
	image.src = '../../common/img/kcdocs/' + src;

}
popUpImg.prototype.createBox = function(aTag){
	var src = aTag.id.replace(/_dot_/,'.');
	src = src.replace(/<[^>]+>/ig,"");
	var box = "<div class='popUpImg'>";
	box += "<div class='top'>";
	box += "<img src='../../common/img/kc/popImg_drag.gif' alt='drag' class='drag'/>";
	box += "<img src='../../common/img/kc/popImg_close.gif' alt='close' class='close' />";
	box += "</div>";
	box += "<div class='main'>";
	box += "<img src='../../common/img/kcdocs/" + src +"' alt='' />";
	box += "</div>";
	box += "</div>";
	$box = $(box);
	$('body').prepend($box);
	this.events($box, aTag);
}
popUpImg.prototype.events = function($box, aTag){
	$(aTag).bind('click', function(){
		$box.css({'display':'block'});
		var $imgs = $box.find('div.main img');
		var $img = $($imgs[0]);
		var width = $img.width();
		var height = $img.height();
		this.windowHeight = $(window).height();
		this.windowWidth = $(window).width();
		var t = parseInt((this.windowHeight/2) - (height/2)) < 0 ? $(window).scrollTop() : parseInt((this.windowHeight/2) - (height/2) + $(window).scrollTop());
		var l = (parseInt((this.windowWidth/2) - (width/2)) < 0) ? 0 : parseInt((this.windowWidth/2) - (width/2));
		$box.css({'display':'block','top': t, 'left': l});
		$img.css({'width': width, 'height': height});
		$img.parents('div.popUpImg').css({'width': width + 15, 'height': height + 20});
		if(width == 0 || height == 0){
			$img.attr({'alt': 'Image is unavailable.'});
			$img.css({'width': '150px', 'height': '75px'});
		}
	});
	$box.find('.close').bind('click', function(){$(this).parents('.popUpImg').css({'display':'none'});});
	$box.find('div.top').bind('mousedown', function(){
		$(this).parents('.popUpImg').draggable({zIndex: 2001});
		$(this).parents('.popUpImg').draggable('enable');
	}).bind('mouseup',function(){
		$(this).parents('.popUpImg').draggable('disable');
	});
}

liveEventsForm = function(){
  $('#txtZip').keyup(function(e) {if(e.keyCode == 13) {le.Submit();}});
  $('form input#btnSearchLE').bind('click',function(){le.Submit()});
}
liveEventsForm.prototype.Submit = function(){
  var cityZip = $('#txtZip').val();
  var miles = $('form select#selMiles').val();
  var url = '';
  if(isNaN(parseInt(cityZip))){
    cityZip = cityZip.replace(/^[ \t]+|[ \t]+$/,'');
    var parts = '';
    if(cityZip.indexOf(',') > -1){
      parts = cityZip.split(',')
      url = '../../events/overview/overview.asp?city=' + parts[0] + '&state=' + parts[1].replace(/ /g, '') + '&zip=Zip&miles=' + miles + '&topic=&find=true';
    }else if(cityZip.indexOf('+') > -1){
      parts = cityZip.split('+')
      url = '../../events/overview/overview.asp?city=' + parts[0] + '&state=' + parts[1].replace(/ /g, '') + '&zip=Zip&miles=' + miles + '&topic=&find=true';
    }else if(cityZip.indexOf(' ') > -1){
      parts = cityZip.split(' ')
      url = '../../events/overview/overview.asp?city=' + parts[0] + '&state=' + parts[1].replace(/ /g, '') + '&zip=Zip&miles=' + miles + '&topic=&find=true';
    }
  }else{
    var url = '../../events/overview/overview.asp?city=City&state=&zip=' + cityZip + '&miles=' + miles + '&topic=&find=true';
  }

  $.ajax({
    url: '../../common/buffer/kc_lestoreBuffer.asp',
    data:{miles:miles,location:cityZip},
    type:'POST',
    error:function(data){alert(data)},
    success:function(data){window.location = url;}
  });
}
liveEventsForm.prototype.error = function(){$('form span.leError').css({'display': 'block'});}

kcOverview = function(){
  $('span.spriteSquare').css({'opacity': '0'});
  $('.smallModule').bind('mouseenter', function(){
    $(this).find('span.spriteSquare').animate({'opacity': '1'}, 'fast');
    //switch icon color
    var icon = $(this).find('img.square').attr("src");
    icon = icon.split('_')[0];
    icon += '_purple.gif';
    $(this).find('img.square').attr("src", icon);
  }).bind('mouseleave', function(){
    $(this).find('span.spriteSquare').animate({'opacity': '0'}, 'fast');
    //switch icon color
    var icon = $(this).find('img.square').attr("src");
    icon = icon.split('_')[0];
    icon += '_gray.gif';
    $(this).find('img.square').attr("src", icon);
  });
}
var ILOverview = function(){
  $('.smallLEModule').bind('mouseenter', function(){mOver(this)}).bind('mouseleave', function(){mOut(this)});
  $('.BigLEModule').bind('mouseenter', function(){mOver(this)}).bind('mouseleave', function(){mOut(this)});

  function mOver(el){
    $(el).find('span.sprite').animate({'opacity': '1'}, 'fast');
    //switch icon color
    var icon = $(el).find('img.square').attr("src");
    icon = icon.split('_')[0];
    icon += '_purple.gif';
    $(el).find('img.square').attr("src", icon);
  }

  function mOut(el){
    $(el).find('span.sprite').animate({'opacity': '0'}, 'fast');
    //switch icon color
    var icon = $(el).find('img.square').attr("src");
    icon = icon.split('_')[0];
    icon += '_gray.gif';
    $(el).find('img.square').attr("src", icon);
  }
}
var DefHover = function(){$(".deflink")}
function PrintDoc(id, qry){
  if(!qry){qry = '';}
  var wURL = '../../knowledgecenter/print/print.asp?id=' + id + qry;
  popwin(wURL,825,600);
}
$(document).ready(function(){
  rrtabs = new RRailTabs();
  if($('a.viewGraphic').length > 0){popUp = new popUpImg();}
  if($('img.emailBtn').length > 0){email = new emailForm();}
  if($('a.feedbackLink').length > 0){feedback = new feedbackForm();}
  if($('form#liveEventsMod').length > 0){le = new liveEventsForm();}
  if($(".deflink").length > 0){dl = new DefHover()}
  if(url.indexOf('overview/overview') > -1){kcOverviewJS = new kcOverview();}
  if (url.indexOf('interactiveLearning') > -1) {ilOverview = new ILOverview();}
});