﻿

function initAjaxOnce()
{
    if ($('#filterHolder').length && location.hash != '' && location.hash.indexOf('|') != -1) {
        $('#rateTable').innerHTML = 'Loading...';
        var params = 'sort=' + location.hash.replace('#', '');
        ajaxRequest('/ajax/rates.aspx', null, params);
        document.getElementById('filterText').innerHTML = 'Showing previous search results.';
    } else {
        initAjax();
    }
}

function initAjax(){
    initAjaxLinks();
    initTierLinks();
}

function selectState(obj)
{
    if (obj.innerHTML.indexOf('<br')<1)
    {
        var params='returnUrl=' + location.href;
        ajaxRequest('/ajax/selectstate.aspx', obj, params);
    }
}


function initTierLinks() {
	var ajaxSpans = $('#content .list-banks .tieredApy');
	for (var i=0; i<ajaxSpans.length;i++){
	    ajaxSpans[i].onclick = function(){
		    var productId = this.className.replace('tieredApy ','');
		    var parts=this.innerHTML.split('%');
		    var collapse=parts[1].length>10;
		    var params='productId=' + productId + '&rate=' + parts[0] + '&collapse=' + collapse;
		    ajaxRequest('/ajax/tiers.aspx', this, params);
	    }
	}
	
}

function initAjaxLinks() {
	if ($('.rateTable').length){
		ajax_link = document.getElementsByTagName('a');
		for (var i=0; i<ajax_link.length;i++){
			if (ajax_link[i].rel && ajax_link[i].rev){
			    if (ajax_link[i].rel=='ajax')
			    {
				    ajax_link[i].href = 'javascript:;';
				    ajax_link[i].onclick = function(){
					    var param = 'sort=' + this.rev;
					    ajaxRequest('/ajax/rates.aspx', this, param);
				    }
				}
			}
		}
	}
}



function ajaxRequest(_action, link, param) {
    //alert("test");

    if (link != null && link.rev.indexOf('B|') == 0) {
            var sectionId = link.rev.split('|')[2]; holder = $('#rateContainer' + sectionId)[0];
    }

    $.get(_action, param, function (data) {

        if (typeof (holder) == 'undefined') {
            if (param.indexOf('true,false|') > -1) {
                if (document.getElementById('featuredRateContainer')) {
                    $('#featuredRateContainer')[0].innerHTML = data;
                }
                else {
                }

            } else {
                $('#rateContainer')[0].innerHTML = data;
            }
        } else {
            holder.innerHTML = data;
        }
        initAjax();
    });
}

if (window.addEventListener){
	window.addEventListener("load", initAjaxOnce, false);
}
else if (window.attachEvent && !window.opera){
	window.attachEvent("onload", initAjaxOnce);
}


function ajaxPost(_action, _this, param){
    //_this.innerHTML ='';    
	var _url = _action;
	var _Request = new Request({
		url: _url, 
		method: 'post',
		onSuccess: function(responseText) {
			   _this.outerHTML = responseText;
			   initAjax();
		}
	}).send(param);	
}







function initVoting(){
	var holders=elems = $('div').filter('.voteHolder');;//getElementsByClassName('voteholder');
	for (var i=0; i<holders.length;i++){
	    var idTag=holders[i].id;
	    var contentType='comment';
	    if (idTag.indexOf('post') > -1) contentType = 'post';
	    if (idTag.indexOf('promotion') > -1) contentType = 'promotion';

	    var contentId = idTag.replace('comment', '').replace('post', '').replace('promotion', '');
	    var votes = holders[i].innerHTML;
	    var newText = '';


	    if (contentType == 'promotion') {
	        newText = '<a href="javascript:vote(\'' + contentType + '\',\'' + contentId + '\',\'1\');"><img src="http://cdn.depositaccounts.com/images/icons/voteup.png"></a>';
	        newText += '<a href="javascript:vote(\'' + contentType + '\',\'' + contentId + '\',\'-1\');"><img src="http://cdn.depositaccounts.com/images/icons/votedown.png"></a>';
	    } else {
	        newText = '<i>Was this ' + contentType + ' helpful? <a href="javascript:vote(\'' + contentType + '\',\'' + contentId + '\',\'1\');"><img src="http://cdn.depositaccounts.com/images/icons/voteup.png"></a>';
	        if (votes.indexOf('-') > -1) newText += " " + votes; else newText += ' +' + votes;
	        newText += " votes</i>";
	        newText += ' <a href="javascript:vote(\'' + contentType + '\',\'' + contentId + '\',\'-1\');"><img src="http://cdn.depositaccounts.com/images/icons/spam.png" border="0"></a> <a href="javascript:showReportComment(' + contentId + ');">Report this Post</a>';
	    }
	    holders[i].innerHTML = newText;
	}
}

function vote(contentType,contentId,vote)
{
    $('#' + contentType + contentId).load('/ajax/vote.aspx','contenttype=' + contentType + '&contentid=' + contentId + '&vote=' + vote);
}

function pollVote(questionId,width,height,answer)
{
    $('#pollAnswers').load('/ajax/poll.aspx','question=' + questionId + '&width=' + width + '&height=' + height + '&answer=' + answer);
}

function comment(contentType,contentId)
{
    var param='contentType=' + contentType + '&contentId=' + contentId;
    var _url = '/ajax/comment.aspx';
    var _this=document.getElementById('commentHolder');
    //var tinyScript = document.createElement('script');tinyScript.type = 'text/javascript';tinyScript.src = '/js/tiny_mce/tiny_mce.js';$('head')[0].appendChild(tinyScript);
    
    $.get(_url,param, function(data)
    {
        _this.innerHTML = data;
        
        //var captchaScript = document.createElement('script');captchaScript.type = 'text/javascript';captchaScript.src = 'http://api.recaptcha.net/js/recaptcha_ajax.js';_this.appendChild(captchaScript); 
        //var fbScript = document.createElement('script');fbScript.type = 'text/javascript';fbScript.src = 'http://connect.facebook.net/en_US/all.js#xfbml=1';_this.appendChild(fbScript); 
        var newScript = document.createElement('script');newScript.type = 'text/javascript';newScript.src = '/js/comment.js?ver=3';_this.appendChild(newScript);
        if ($('#postComment')!=null) document.location.hash='postComment';
    });
    return false;
}

function toggleProduct(obj,id,mode) {
   
    var row=obj.parentNode.parentNode;
    var table=row.parentNode.parentNode;
    if (obj.className=='e')
    {
        obj.className='c';
        
        var newRow=table.insertRow(row.rowIndex+1);
        newRow.className=row.className;
        newRow.setAttribute('id','productDetails' + id.toString());
        var cell;
        if (mode=='P') {
            newRow.insertCell(0);
            cell=newRow.insertCell(1);
            cell.colSpan=7;
        } else if (mode=='BP') {
            //newRow.insertCell(0);
            cell=newRow.insertCell(0);
            cell.colSpan=6;
        } else {
            cell=newRow.insertCell(0);
            cell.colSpan=5;
            cell.style.paddingLeft='20px';
        }
        //cell.innerHTML='<div style="display:none;">Loading...</div>';
        var params='id=' + id.toString() + '&mode=' + mode;
        if (row.className=='alt') params+='&alt=1';
        $.get('/ajax/accountdetails.aspx',params, function(data)
        {
            cell.innerHTML = data;
            $('#productDetails' + id.toString() + ' TD DIV').slideDown('slow');
        });
        
        
    } else {
        obj.className='e';
        var detailsRow=document.getElementById('productDetails' + id.toString());
        if (detailsRow!=null) {
          $('#productDetails' + id.toString() + ' TD DIV').slideUp('slow');
          setTimeout(function(){table.deleteRow(detailsRow.rowIndex);},600);
        }
    }

   
    return false;
}



function loadFilter(params)
{
    if (document.getElementById('filterHolder').innerHTML=='')
    {
        $.get('/ajax/filter.aspx',params, function(data)
        {
            document.getElementById('filterHolder').innerHTML=data;
            $('#filterControl').slideDown('slow');
        });
    } else {
        if ($('#filterControl')[0].style.display=='none') {
            $('#filterControl').slideDown('slow'); 
        }
        else {
            $('#filterControl').slideUp('slow');
        }
        //setTimeout(function(){document.getElementById('filterHolder').innerHTML='';},600);
    }
}

function filterAccounts(mode, params)
{
    var _holder = $('#rateContainer')[0];
    
    
    var amount=document.getElementById('amountText').value.replace('$','').replace(/,/g,'');
    if (amount==null || amount=='') amount='10000';
    var physical=document.getElementById('physicalCheck').checked;
    var online=document.getElementById('onlineCheck').checked;
    var bank=document.getElementById('bankCheck').checked;
    var cu=document.getElementById('cuCheck').checked;
    var allCU=document.getElementById('allRad').checked;
    var national=document.getElementById('nationalCheck').checked;
    var local=document.getElementById('localCheck').checked;
    var stateControl=document.getElementById('filterState');
    var state=stateControl.options[stateControl.selectedIndex].value;
    var bools=physical.toString() + ',' + online.toString() + ',' + bank.toString() + ',' + cu.toString() + ',' + allCU + ',' + national.toString() + ',' + local.toString();
    //bools=bools.replace('true','1').replace('false','0');
    
    var rev1 = mode + '|' + params;
    rev1 +='|' + amount.toString();
    rev1 +='|' + bools;
    var rev2 = '|' + state + '|EstimatedEarnings desc';

    if ($('#featuredRateContainer').length>0)
    {
        ajaxRequest('/ajax/rates.aspx', null, 'sort=' + rev1 + ',true,false' + rev2);
        ajaxRequest('/ajax/rates.aspx', null, 'sort=' + rev1 + ',false,true' + rev2);
	} else {
	    ajaxRequest('/ajax/rates.aspx', null, 'sort=' + rev1 + rev2);
	}
	
	var filterText='';
	if (national)
	{
	    if (local)  
	    {
	        if (stateControl.selectedIndex==0) filterText='Showing <span>nationwide</span> and <span>all local</span> accounts';
	        else filterText='Showing <span>nationwide</span> and <span>' + stateControl.options[stateControl.selectedIndex].text +  '</span> accounts';
	    }else filterText='Showing <span>nationwide</span> accounts';
	} 
	else if (local) if (local) 
	{
	    if (stateControl.selectedIndex==0) filterText='Showing <span>all local</span> accounts';
	    else filterText='Showing <span>' + stateControl.options[stateControl.selectedIndex].text +  '</span> accounts';
	}
	if (filterText!='' && amount>0) filterText+=' based on a <span>' + formatCurrency(amount).replace('.00','') + '</span> deposit.'
	document.getElementById('filterText').innerHTML=filterText;
	loadFilter(params);
	
	window.location.href=window.location.pathname + '#' + rev1 + rev2;
	
	return false;
}

function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
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 (((sign)?'':'-') + '$' + num + '.' + cents);
}

function toggleSearchTerm()
{
    var searchTermHolder=document.getElementById('searchTermHolder');
    //var hidden=$('#searchTermHolder')[0].style.display=='none';
    var hidden=searchTermHolder.innerHTML=='';
    if (document.getElementById('searchCd').checked || document.getElementById('searchIra').checked) 
    {
        if (hidden)
        {
            searchTermHolder.innerHTML='<table cellpadding="0" cellspacing="0" style="margin-bottom:0px;"><tr><td>With terms up to: </td><td> &nbsp; <select id="searchTerm"><option value="6">6 months</option><option value="12">1 year</option><option value="24">2 years</option><option value="36">3 years</option><option value="48">4 years</option><option value="60">5 years</option></select></td></tr></table>';
            //$('#searchTermHolder').slideDown('slow');
        }
    } else {
        if (!hidden) 
        {
            //$('#searchTermHolder').slideUp('slow');
            searchTermHolder.innerHTML='';
        }
    }
}

function productSearch()
{
    var qs="amount=" + document.getElementById('searchAmount').value.replace('$','').replace(',','');
    qs+='&products=' + document.getElementById('searchSavings').checked.toString().replace('true','1').replace('false','0');
    qs+='|' + document.getElementById('searchMma').checked.toString().replace('true','1').replace('false','0');
    qs+='|' + document.getElementById('searchChecking').checked.toString().replace('true','1').replace('false','0');
    qs+='|' + document.getElementById('searchCd').checked.toString().replace('true','1').replace('false','0');
    qs+='|' + document.getElementById('searchIra').checked.toString().replace('true','1').replace('false','0');
    var searchTerm=document.getElementById('searchTerm');
    if (searchTerm!=null) qs+='&term=' + searchTerm.options[searchTerm.selectedIndex].value;
    if (qs.indexOf('0|0|0|0|0')>-1) alert('Please select at least one product.'); else location.href='/productsearch.aspx?' + qs;
}

function doModal(elementName)
{
    $(elementName).modal(
    {
        onOpen: function (dialog) {
            dialog.overlay.fadeIn('fast', function () {
                dialog.data.hide();dialog.container.fadeIn('fast', function () {dialog.data.slideDown('fast');});
            });
        },
        onClose: function (dialog) {
            dialog.data.fadeOut('fast', function () {
                dialog.container.hide('fast', function () {dialog.overlay.slideUp('fast', function () {$.modal.close();});});
            });
        }
    })
}
function subscribe(contentType,contentId)
{
    var params='contentType=' + contentType + '&contentid=' + contentId;
    $.get('/ajax/subscribe.aspx',params, function(data)
    {
        var elem=document.getElementById('dialog');
        if (elem==null)
        {
            elem=document.createElement('DIV');
            elem.id='dialog';
            elem.title='Subscribe';
            elem.style.display='none';
        }
        elem.innerHTML=data;
        var node=document.getElementById('subscribeLink');
        node.parentNode.insertBefore(elem,node.nextSibling);
        doModal('#dialog');
    });
}

function subscribeAjax()
{
    var subscriptionType=document.getElementById('subscriptionType');
    var contentType=document.getElementById('subscriptionContentType').value;
    var contentId=document.getElementById('subscriptionContentId').value;
    var params='contenttype=' + contentType + '&contentid=' + contentId + '&subscriptionType=' + subscriptionType.options[subscriptionType.selectedIndex].value;
    $.get('/ajax/subscribe.aspx',params,null);           
    $.modal.close();
}

function showWiki(container,contentType,contentId,includeStates)
{
    var height=360;
    if (includeStates) height=750;
    document.getElementById(container).innerHTML='<iframe src="/cp/wiki/edit.aspx?contentType=' + contentType + '&contentId=' + contentId + '" frameborder="0" width="100%" height="' + height + '"></iframe>';
}
function showWikiHistory(container,contentType,contentId)
{
    document.getElementById(container).innerHTML='<iframe src="/cp/wiki/history.aspx?contentType=' + contentType + '&contentId=' + contentId + '" frameborder="0" width="100%" height="360"></iframe>';
}

function forumReply(container,threadId,postId)
{
    document.getElementById(container).innerHTML='<iframe id="replyFrame" name="replyFrame" src="/forum/replyframe.aspx?threadid=' + threadId + '&postid=' + postId + '" frameborder="0" width="100%" height="390"></iframe>';
    scrollToElement(document.getElementById(container));
}

function scrollToElement(element){
    var y = 0;
    while(element != null){
        y += element.offsetTop;
        element = element.offsetParent;
    }
    window.scrollTo(0,y);
}


function loadForumFilter(params)
{
    if (document.getElementById('filterHolder').innerHTML=='')
    {
        $.get('/ajax/forumfilter.aspx',params, function(data)
        {
            document.getElementById('filterHolder').innerHTML=data;
            $('#filterControl').slideDown('slow');
        });
    } else {
        if ($('#filterControl')[0].style.display=='none') {
            $('#filterControl').slideDown('slow'); 
        }
        else {
            $('#filterControl').slideUp('slow');
        }
        //setTimeout(function(){document.getElementById('filterHolder').innerHTML='';},600);
    }
}

function filterThreads(baseUrl)
{
    var nationwide=document.getElementById('nationalCheck').checked;
    var includeState=document.getElementById('localCheck').checked;
    var filterState=document.getElementById('filterState');
    var state=filterState.options[filterState.selectedIndex].value;
    
    var params='';
    if (!nationwide) params+='?nationwide=false';
    if (!includeState) {
        if (params=='') params+='?state='; else params+='&state=';
    } else if (state!='all'){
        if (params=='') params+='?state=' + state; else params+='&state=' + state;
    }
    var url='/forum/' + baseUrl + params;
    location.href=url;
}

function showForumRss(params)
{
    $.get('/ajax/forumrss.aspx',params.replace('?',''), function(data)
    {
    
        var elem=document.getElementById('dialog');
        if (elem==null)
        {
            elem=document.createElement('div');
            elem.id='dialog';
            elem.title='Subscribe';
            elem.style.display='none';
        }
        elem.innerHTML=data;
        var node=document.getElementById('subscribeLink');
        node.parentNode.insertBefore(elem,node.nextSibling);
        doModal('#dialog');  
    });
    
}

function showRegister()
{
    var params='width=350&height=250&src=' + escape('/ajax/register.aspx');
    getModal('/ajax/frame.aspx',params);
}

function showLogin()
{
    var params='width=300&height=200&src=' + escape('/ajax/loginbox.aspx');
    getModal('/ajax/frame.aspx',params);
}

function showReportComment(commentId)
{
    var params='width=400&height=235&src=' + escape('/ajax/reportcomment.aspx?id=' + commentId.toString());
    getModal('/ajax/frame.aspx',params);
}

function showModal(data)
{
    var elem=document.getElementById('dialog');
    if (elem==null)
    {
        elem=document.createElement('DIV');
        elem.id='dialog';
        elem.title='Login';
        elem.style.display='none';
    }
    elem.innerHTML=data;
    var node=document.getElementById('headerTable');
    node.parentNode.insertBefore(elem,node.nextSibling);
    doModal('#dialog');
}

function getModal(url,params)
{
    $.get(url,params, function(data)
    {
        showModal(data);
    });
}

function sortComments(contentType,contentId,sort)
{
    var params='contenttype=' + contentType + '&contentid=' + contentId + '&sort=' + sort;
    $('#commentsHolder').load('/ajax/comments.aspx',params,function(){
        initVoting();
    });
}

function loadBankStat(id) { $('#healthDiv').load('/ajax/health.aspx', 'id=' + id.toString()); }

function hideSponsored() {
    $.get('/ajax/hidesponsored.aspx', '', function(data) {
        location.href = location.pathname;
    });
}

function addAlert(bankId) {
    $.get('/ajax/addalert.aspx', 'bankId=' + bankId.toString(), function(data)
    {
        var elem=document.getElementById('dialog');
        if (elem==null)
        {
            elem=document.createElement('DIV');
            elem.id='dialog';
            elem.title='Subscribe';
            elem.style.display='none';
        }
        elem.innerHTML=data;
        var node=document.getElementById('alertLink');
        node.parentNode.insertBefore(elem,node.nextSibling);
        doModal('#dialog');
    });
    $.modal.close();
}

function addAlertPost(bankId) {
    var errorMessage = '';
    var alertRateChange = document.getElementById('alertRateChange');
    var alertPromotion = document.getElementById('alertPromotion');
    var alertBlogPost = document.getElementById('alertBlogPost');
    var alertForumThread = document.getElementById('alertForumThread');
    var subscriptionType = document.getElementById('subscriptionType');
    var alertEmail = document.getElementById('alertEmail');
    
    var tags = [];
    if (alertRateChange.checked) tags[tags.length] = 'ratechange';
    if (alertRateChange.checked) tags[tags.length] = 'promotion';
    if (alertBlogPost.checked) tags[tags.length] = 'blogpost';
    if (alertForumThread.checked) tags[tags.length] = 'forumthread';
    if (tags.length == 0) errorMessage = 'You must select at least one alert type.';

    var frequency = subscriptionType.options[subscriptionType.selectedIndex].value;
    
    var emailAddress = '';
    if (alertEmail != null) {
        emailAddress = alertEmail.value;
        if (emailAddress.indexOf('@') == -1) errorMessage = 'Invalid email address';
    }

    if (errorMessage != '') {
        document.getElementById('alertError').innerHTML = errorMessage;
    } else {
        var params = 'bankid=' + bankId.toString() + '&tags=' + tags.join(',') + '&frequency=' + frequency + '&email=' + emailAddress;
        $.get('/ajax/addalert.aspx', params, null);
        $.modal.close();
    }
}
