$(document).ready(function () {
    // Drop down menus
    $("#region01 ul.sf-menu .maponly").remove();
    $("#region01 ul.sf-menu").supersubs({ minWidth: 12, maxWidth: 27, extraWidth: 6 }).superfish({ speed: 75, autoArrows: true, animation: { height: 'show'} }).find('ul').bgIframe({ opacity: false });
    $(":input[placeholder]").placeholder();

    //default button setting
    $btn = $('.btnsearch');
    var $form = $btn.parents('.form');
    $form.keypress(function (e) {
        if (e.which == 13 && e.target.type != 'textarea') {
            if ($btn[0].type == 'submit')
                $btn[0].click();
            else {
                eval($btn[0].href.replace(/%20/g, ' ') + ';');
            }
            return false;
        }
    });

    checkNews();

    $('.btn').each(function () {
        var span = document.createElement('span');
        $(span).addClass('shiny');
        $(this).append($(span));
    });
    $('#finder').change(function () { finderChanged(); });
    if ($('#rateselector').length > 0) {
        $('.expandable.calculator').toggle();
        $('#rateselector').change(function () { rateselectorChanged(); });
    }
    $('#cr004 tr:even').addClass('altrow');
    $('#cr004 tr:first-child').removeClass('altrow');

    if ($('#ctl01').length + $('#lwcmsmenu').length == 0) {
        $('.rates').hide();
        $('.rates:eq(0)').show();
        $('.colorboxinline').hide();

        // Redirect external links
        $.expr[':'].external = function (obj) { return !obj.href.match(/^mailto\:/) && !obj.href.match(/^javascript\:/) && !obj.href.match(/^https:\/\/obc.itsme247.com/) && !obj.href.match(/^http:\/\/obc.itsme247.com/) && (obj.hostname != location.hostname); };
        $('a:external').addClass('external').each(function () {
            var url = cleanRedirectUrl($(this).attr('href'));
            var prev = getPreviousUrl();
            //var prev = getQueryString()["prev"];
            //if (prev == undefined) { prev = location.href; }
            //if (url.substr(0, 1) == '/') { url = url.substr(1, url.length - 1); }
            //if (url.indexOf('&') > 0) { url = encodeURIComponent(url); }
            $(this).attr('target', '_blank').attr('href', '/redirect&loc=' + url + '&prev=' + encodeURIComponent(prev));
        });
        if ($('.continue-redirect').length > 0) {
            var prev = getQueryString()["prev"];
            if (prev == '' && document.referrer == '') { prev = '/home'; }
            else if (prev == '') { prev = document.referrer; }
            $('.continue-redirect').attr('href', getQueryString()["loc"]);
            //$('.cancel-redirect').attr('href', prev);
            $('.cancel-redirect').click(function () { window.close(); });
        }
    }
    else { $('.learnmore').css('top', 0); }

    $('.eligibility').colorbox({ innerWidth: 500, innerHeight: 200, inline: true, href: "#eligibility", onLoad: function () { $('#colorbox').show(); } });
    $('.identity').colorbox({ innerWidth: 500, innerHeight: 200, inline: true, href: "#identity", onLoad: function () { $('#colorbox').show(); } });
    $('.sf-menu li.first-level').hover(function () {
        $('.sf-menu li.sfHover').removeClass('sfHover');
        $(this).addClass('sfHover'); //.find('a.sf-with-ul:first').css('color', '#EC930B !important');
        $(this).prev('li').find('img').each(function () { $(this).hide(); });
        $(this).next('li').find('img').each(function () { $(this).hide(); });
    }, function () {
        $(this).removeClass('sfHover'); //.find('a.sf-with-ul:first').css('color', '#ffffff');
        $(this).prev('li').find('img').each(function () { $(this).show(); });
        $(this).next('li').find('img').each(function () { $(this).show(); });
    });
    if (location.href.indexOf('editpage.aspx') == 0) { rateselectorChanged(); }
});

function redirectUrl(url) {
    var prev = getPreviousUrl();
    url = cleanRedirectUrl(url);
    window.open('/redirect&loc=' + url + '&prev=' + encodeURIComponent(prev));
}
function getPreviousUrl() {
    var prev = getQueryString()["prev"];
    if (prev == undefined) { prev = location.href; }
    return prev;
}
function cleanRedirectUrl(url) {
    if (url.substr(0, 1) == '/') { url = url.substr(1, url.length - 1); }
    if (url.indexOf('?') > 0) { url = encodeURIComponent(url); }
    return url;
}
function cleanSiteMap() {
    $('#cr004 ul.sf-menu').removeClass('sf-menu').addClass('sitemap');
    $('ul.sitemap .menubar').parent().remove();
}

function getQueryString() {
    var result = {}, queryString = location.href, re = /([^&=]+)=([^&]*)/g, m;
    while (m = re.exec(queryString)) {
        result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
    }
    return result;
}

function toggleCalculator(calculatorID, placeholderID) {
    var placeholder = $('#' + placeholderID);
    $('.calculatorplaceholder').each(function () { if ($(this).attr('id') != placeholderID) { $(this).hide(); } });
    if ($(placeholder).find('#' + calculatorID).length == 0) {
        $(placeholder).append($('#' + calculatorID));
        $('#' + calculatorID).show();
    }
    $(placeholder).toggle();
}

$(window).load(function () {
    $('#slider').nivoSlider({ pauseTime: 10000 });
});

function rateselectorChanged() {
    var selected = $('#rateselector option:selected');
    var selectedrates = $('#' + selected.val());
    $('.rates').hide();
    $(selectedrates).show();
}

function finderChanged() {
    var selected = $('#ddlFinder option:selected');
    var link = $('#finder #' + selected.val());
    $('#finder .btn').hide();
    $(link).show();
    if (selected.val() == 'xtend') {
        window.open($(link).attr('href'));
    }
    else if(selected.val() == 'local'){
        window.location.href=$(link).attr('href');
    }
}

function checkNews() {
    var news = $('#newsalert');
    if (news.length > 0 && news.html().trim().length == 0) {
            news.remove();
    }
}

function findATM() {
    if ($('#txtZip').length > 0 && $('#txtZip').val().length > 0) {
        redirectUrl('http://www.co-opfs.org/public/locators/ATMlocator/searchresults.cfm?zip=' + $('#txtZip').val());
    }
    else {
        redirectUrl('http://www.co-opfs.org/public/locators/ATMlocator/index.cfm');
    }
}

function findSharedBranch() {
    if ($('#txtZip').length > 0 && $('#txtZip').val().length > 0) {
        redirectUrl('http://www.cuservicecenter.com/ServiceCenters.aspx?zip=' + $('#txtZip').val());
    }
    else {
        redirectUrl('http://www.cuservicecenter.com');
    }
}

function notify(targetName) {
    $(targetName).animate({ marginBottom: '0px' }, 'slow', function () {
        $(targetName).delay(5000).animate({ marginBottom: '-15px' }, 'slow', function () { });
    });
}


//Calculator Functions
 
//By Daniel C. Peterson, 1998  All Rights Reserved.
//For commercial use rates send email to:
//webmaster@webwinder.com
 
function formatNum(Vnum) {
 
   if(Vnum > 99000000) {
   alert("Sorry, this will not generate numbers larger that 99 million.");
   focus();
   } else {
   
   var V10million = parseInt(Vnum / 10000000);
 
   var V1million = (Vnum % 10000000)  / 1000000;
      if(V1million / 1000000 == 1) {
      V1million = 1;
      } else
      if(V1million < 1) {
      V1million = "0";
     } else {
      V1million = parseInt(V1million,10);
     }
 
    var V100thousand = (Vnum % 1000000)  / 100000;
      if(V100thousand / 100000 == 1) {
      V100thousand = 1;
      } else
      if(V100thousand < 1) {
      V100thousand = "0";
     } else {
      V100thousand = parseInt(V100thousand,10);
     }
 
   var V10thousand = (Vnum % 100000)  / 10000;
      if(V10thousand / 10000 == 1) {
      V10thousand = 1;
      } else
      if(V10thousand < 1) {
      V10thousand = "0";
      } else {
      V10thousand = parseInt(V10thousand,10);
      }
 
   var V1thousand = (Vnum % 10000)  / 1000;
      if(V1thousand / 1000 == 1) {
      V1thousand = 1;
      } else
      if(V1thousand < 1) {
      V1thousand = "0";
     } else {
      V1thousand = parseInt(V1thousand,10);
     }
 
   var Vhundreds = (Vnum % 1000)  / 100;
      if(Vhundreds / 100 == 1) {
      Vhundreds = 1;
      } else
      if(Vhundreds < 1) {
      Vhundreds = "0";
     } else {
      Vhundreds = parseInt(Vhundreds,10);
     }
 
   var Vtens = (Vnum % 100)  / 10;
      if(Vtens / 10 == 1) {
      Vtens = 1;
      } else
      if(Vtens < 1) {
      Vtens = "0";
     } else {
      Vtens = parseInt(Vtens,10);
     }
 
   var Vones = (Vnum % 10)  / 1;
      if(Vones / 1 == 1) {
      Vones = 1;
      } else
      if(Vones < 1) {
      Vones = "0";
     } else {
      Vones = parseInt(Vones,10);
     }
 
  var Vcents = parseInt(((Vnum % 1) * 100),10);
 
 if(Vcents < 1) {
  Vcents = "00";
  }
  else
  if(Vcents % 10 == 0) {
  Vcents = Vcents + "0";
  }
  else
  if(Vcents % 10 == Vcents) {
  Vcents = "0" + Vcents;
  } else {
  Vcents = Vcents;
  }
 
  if(Vcents == "900") {
  Vcents = "90";
  } else
  if(Vcents == "800") {
  Vcents = "80";
  } else 
  if(Vcents == "700") {
  Vcents = "70";
  } else 
  if(Vcents == "600") {
  Vcents = "60";
  } else 
  if(Vcents == "500") {
  Vcents = "50";
  } else 
  if(Vcents == "400") {
  Vcents = "40";
  } else 
  if(Vcents == "300") {
  Vcents = "30";
  } else
  if(Vcents == "200") {
  Vcents = "20";
  } else
  if(Vcents == "100") {
  Vcents = "10";
  } else {
  Vcents = Vcents;
  }
 
   
   var Vformat = "";
 
   if(Vnum >= 10000000) {
   Vformat = (V10million + "" + V1million + "," + V100thousand + "" + V10thousand + "" + V1thousand + "," + Vhundreds + "" + Vtens + "" + Vones + "." + Vcents);
   }
   else
   if(Vnum >= 1000000) {
   Vformat = (V1million + "," + V100thousand + "" + V10thousand + "" + V1thousand + "," + Vhundreds + "" + Vtens + "" + Vones + "." + Vcents);
   }
   else
   if(Vnum >= 100000) {
   Vformat = (V100thousand + "" + V10thousand + "" + V1thousand + "," + Vhundreds + "" + Vtens + "" + Vones + "." + Vcents);
   }
   else
   if(Vnum >= 10000) {
   Vformat = (V10thousand + "" + V1thousand + "," + Vhundreds + "" + Vtens + "" + Vones + "." + Vcents);
   }
   else
   if(Vnum >= 1000) {
   Vformat = (V1thousand + "," + Vhundreds + "" + Vtens + "" + Vones + "." + Vcents);
   }
   else
   if(Vnum >= 100) {
   Vformat = (Vhundreds + "" + Vtens + "" + Vones + "." + Vcents);
   }
   else
   if(Vnum >= 10) {
   Vformat = (Vtens + "" + Vones + "." + Vcents);
   }
   else
   if(Vnum >= 1) {
   Vformat = (Vones + "." + Vcents);
   } else {
   Vformat = ("0." + Vcents);
   }
  return Vformat;
 
  }
}

function checkNumber(input, min, max, msg) {
    msg = msg + " field has invalid data: " + $(input).val();
    var str = $(input).val();

    for (var i = 0; i < str.length; i++) {
        var ch = str.substring(i, i + 1)
        if ((ch < "0" || "9" < ch) && ch != '.') {
            alert(msg);
            return false;
        }
    }
    
    var num = 0 + str;
    if (num < min || max < num) {
        alert(msg + " not in range [" + min + ".." + max + "]");
        return false;
    }
    $(input).val() = str;
    return true;
}

function calculateLoan() {
    // This function checks for empty required fields
    var amount = $('#amount').val();
    var payment = $('#payment').val();
    var rate = $('#rate').val();
    var months = $('#months').val();
    var comma = ","
    var temparry = new Array(10)

    temparray = amount.split(comma)
    amount = temparray.join("")
    temparray = payment.split(comma)
    payment = temparray.join("")
    temparray = rate.split(comma)
    rate = temparray.join("")
    temparray = months.split(comma)
    months = temparray.join("")

    if (isNaN(amount)) {
        alert("Amount must be a number!");
        $('#amount').focus();
        return false;
    }
    if (isNaN(payment)) {
        alert("Payment must be a number!");
        $('#payment').focus();
        return false;
    }
    if (isNaN(rate)) {
        alert("Rate must be a number!");
        $('#rate').focus();
        return false;
    }
    if (isNaN(months)) {
        alert("Length of Loan must be a number!");
        $('#months').focus();
        return false;
    }

    if (((amount != 0) && (amount != "")) &&
		((payment != 0) && (payment != ""))) {
        alert("Please clear either the loan payment or the loan amount to continue.");
        $('#amount').focus();
        return false;
    }
    if (((amount == 0) || (amount == "")) &&
		((payment == 0) || (payment == ""))) {
        alert("You must select either the loan payment or the loan amount!");
        $('#amount').focus();
        return false;
    }
    if ((rate == 0) || (rate == "")) {
        alert("You must select a loan rate!");
        $('#rate').focus();
        return false;
    }
    else {
        rate = rate / 1200;
    }

    if ((months == 0) || (months == "")) {
        alert("You must provide the term of the loan!");
        $('#months').focus();
        return false;
    }
    else {
        if ($('#frequency').attr('selectedIndex') == '1') {
            months = months * 12;
        }
    }

    var result = '';
    if (payment == 0 || payment == "") {
        result = parseInt(100 * ((amount * (rate / (1 - (Math.pow(1 + rate, -months))))) + .005)) / 100;
        $('#payment').val(result);
        $('#results label').val('Payment: $');
    }
    else {
        result = parseInt(100 * ((((Math.pow(1 + rate, -months) * (-payment + (Math.pow(1 + rate, months) * payment)))) / rate) + .005)) / 100;
        $('#amount').val(result);
        $('#results label').val('Loan Amount: $');
    }
    $('#result').html(result);

    return false;
}

function computeField(input) {
    if ($(input).val() != null && $(input).val().length != 0) {
        $(input).val('' + eval($(input).val()));
    }
    computeForm(input.form);
}

function computeForm(form) {
    if (($('#singlepayments').val() == null || $('#singlepayments').val() == 0) ||
        ($('#singleinterest').val() == null || $('#singleinterest').val().length == 0) ||
        ($('#singleprincipal').val() == null || $('#singleprincipal').val().length == 0)) {
        return;
    } 
    /*if (!checkNumber($('#payments'), 1, 480, "# of payments") ||
        !checkNumber($('#interest'), .001, 99, "Interest") ||
        !checkNumber($('#principal'), 1, 10000000, "Principal")) {
        $('#futurevalue').html('Invalid');
        return;
    }*/

    var duration = $('#singlepayments').val();
    if ($('#singlelengthunit').attr('selectedIndex') == '0') {
        duration = duration / 12;
    }

    var i = $('#singleinterest').val();
    i = i / 100.0;
    i /= 12;
    var pow = $('#singleprincipal').val();
    for (var j = 0; j < duration * 12; j++) {
        pow = (pow * i) + (pow * 1);
    }

    var Vfv = pow;
    $('#singlefuturevalue').html('$' + formatNum(pow));
    var Vtotalint = (Vfv - $('#singleprincipal').val());
    $('#singleinterestearned').html('$' + formatNum(Vtotalint));
    return false;
}

function computeFormMultiple(form) {

    if ($('#interest').val() == "") {
        alert("Please enter the Interest Rate.");
    } else {
        if ($('#moAdd').val() == "") {
            alert("Please enter the Monthly Addition.");
        }
        else {
            if ($('#payments').val() == "") {
                alert("Please enter the Number of Years.");
            } else {
                var i = $('#interest').val();
                i = i / 100;
                i /= 12;
                var ma = eval($('#moAdd').val());
                var duration = $('#payments').val();
                
                if ($('#multilengthunit').attr('selectedIndex') == '0') {
                    duration = duration / 12;
                }

                if ($('#principal').val() == "") { $('#principal').val('0'); }
                var prin = eval($('#principal').val());
                var pmts = eval(duration * 12);
                var count = 0;
                //alert(pmts);
                while (count < pmts) {
                    newprin = prin + ma;
                    prin = (newprin * i) + eval(prin + ma);
                    count = count + 1;
                }
                var Vfv = prin;
                $('#futurevalue').html('$' + formatNum(prin));
                var totinv = eval(count * ma) + eval($('#principal').val());
                var Vtotalint = eval(prin - totinv);
                $('#interestearned').html('$' + formatNum(Vtotalint));
                //END NESTED IF TO CHECK FOR NON-NUMERIC ENTRIES
            }
        }
    }
}

function clearForm(form) {
    $('#payments').val('');
    $('#interest').val('');
    $('#principal').val('');
    $('#singlepayments').val('');
    $('#singleinterest').val('');
    $('#singleprincipal').val('');
    $('#moAdd').val('');
}
