var $j=jQuery.noConflict();
var alertText = "Please be advised that you are leaving Esquire Bank's website. This link is provided as a courtesy. Esquire Bank does not endorse or control the content of third party websites.";
var customFolder = "_templateSECONDBranch";
var slideSpeed = 500;
var tabEffect = "fade";

(function($j){      
	$j.fn.searchComplete = function(whereToGetData){
		var element = this;
		var focusHere = null;
		var terms = new Array;
		
		$j.ajax({
			url: whereToGetData,
      		async: false,
		    success: function(data){
         		$j(data).find('a').each( function(){
					terms[terms.length] = $j(this).text().toLowerCase();
				});
				terms = unique(terms);
      		}	
		});

		element.parent().after('<ul id="searchComplete"></ul>');

		$j(element).keyup(function(e){
			
								   
			var matches = new Array;
			var currentValue = element.attr("value").toLowerCase();
			if( currentValue.length > 1 ){
				var numTerms = terms.length;
				for( var i = 0; i < numTerms; i++ ){
					var thisTerm = terms[i];
					if( thisTerm.indexOf(currentValue) >= 0 ){
						matches[matches.length] = terms[i];
					}
				}
				
				var numMatches = matches.length;
				if( numMatches > 0 ){
					var htmlMatches = '';
					for( var i = 0; i < numMatches; i++ ){
						if( i == 0 )
							htmlMatches += '<li class="first">' + matches[i] + '</li>';
						else if( i == numMatches-1 )
							htmlMatches += '<li class="last">' + matches[i] + '</li>';
						else
							htmlMatches += '<li>' + matches[i] + '</li>';
					}
					$j('#searchComplete').html(htmlMatches);
				}
			}
			else{
				$j('#searchComplete').html("");
			}
			
			if (e == null) { // ie
				keycode = event.keyCode;
			} else { // mozilla
				keycode = e.which;
			}
			
			if( keycode == 13 ){//enter
				return false;
			}
			else if( keycode == 40 ){//down arrow
				if( focusHere != null ){
					var found = false;
					focusHere.removeClass('focus');
					$j('#searchComplete li').each( function(){
						if( $j(this).text() == focusHere.text() && !found){
							found = true;
							if( $j(this).next() != null ){
								focusHere = $j(this).next();
								focusHere.addClass('focus');
							}
						}
					});
				}
				else{
					focusHere = $j('#searchComplete li:eq(0)');
					focusHere.addClass('focus');
				}
			}
			else if( keycode == 38 ){//up arrow
				if( focusHere != null ){
					var found = false;
					focusHere.removeClass('focus');
					$j('#searchComplete li').each( function(){
						if( $j(this).text() == focusHere.text() && !found){
							found = true;
							if( $j(this).prev() != null ){
								focusHere = $j(this).prev();
								focusHere.addClass('focus');
							}
						}
					});
				}
				else{
					focusHere = $j('#searchComplete li:last');
					focusHere.addClass('focus');
				}
			}
			return false;
		});
		
		$j('#searchComplete li').live('click', function(){
			var selectedTerm = $j(this).text();
			element.attr('value', selectedTerm).focus();
			$j('#searchComplete').html("");
		}).live('mouseover mouseout', function(event) {
			if (event.type == 'mouseover'){
				$j('#searchComplete li').removeClass('focus');
				$j(this).addClass('focus');
				focusHere = $j(this);
			}
			else{
				$j(this).removeClass('focus');
				focusHere = null;
			}
		});
		
		function unique(a){
		   var r = new Array;
		   o:for(var i = 0, n = a.length; i < n; i++) {
			  for(var x = i + 1 ; x < n; x++)
			  {
				 if(a[x]==a[i]) continue o;
			  }
			  r[r.length] = a[i];
		   }
		   return r;
		}
	};
})(jQuery);

$j(document).ready( function() {
	$j('a[href*=.pdf]').attr('target', '_blank');
							 
	//$j('#roi_input').searchComplete('http://esquirebank.fipreview.com/search-complete.html');

	productTabs();

	$j(".confirm").click( function() {						   
		if (!confirmAlert($j(this).attr('href'))){
			return false;			
		}
	});
		
	// New page for INMO
	$j('a.newPage').each( function(){
		this.target = "_blank";
	});
	
	//Primary Nav
	$j('#primaryNav li').hover( function(){
		$j(this).attr('id', 'over');
	}, function(){
		$j(this).attr('id', '');
	});

	// FancyBox popup on applications
	$j("a#ssnWhy").fancybox({
		'frameWidth': 300,
		'frameHeight': 190
	});
	
	// Tell Me More, calculator, and online banking login popups provided by FancyBox 
	$j('#questions a, #ultraTopNav li a:contains("Online Banking"), #financialCalculators li a').addClass('iframe');
	
	$j("#questions a").fancybox({
		'hideOnContentClick': false,
		'frameWidth': 540,
		'frameHeight': 340,
		'overlayOpacity': 0.8
	});
	
	$j("#ultraTopNav li a.iframe").fancybox({
		'hideOnContentClick': false,
		'frameWidth': 190,
		'frameHeight': 205,
		'overlayOpacity': 0.8
	});

	$j("#financialCalculators li a").fancybox({
		'hideOnContentClick': false,
		'frameWidth': 670,
		'frameHeight': 415,
		'padding': 10,
		'overlayOpacity': 0.8
	});
	
	$j(".iCase").attr("rel", "group1").fancybox({
		'hideOnContentClick': false,
		'overlayOpacity': 0.8
	});
	
	$j(".makeMeBigger a").fancybox({
		'hideOnContentClick': false,
		'overlayOpacity': 0.8
	});

	//Home Page
	$j('#loginLinks').submit( function(){
		if( $j("#loginLinks input:radio:checked").length > 0 )
			window.open($j("#loginLinks input:radio:checked").attr('value'));
		return false;
	});
	$j('#obNav a').attr('target', '_blank');
	$j('#flashDNA img').live('click', function(){
		window.location = $j('#flashClick a').attr('href');
	});
	
	clickableContainer($j('#newsAnnouncements li'));
	clickableContainer($j('#depositExpress'));
	clickableContainer($j('#settlementDebitCards'));
	
	//Homepage rate thingy
	$j('.thisRate img:even').hover( function(){
		$j(this).attr('src', 'image/our-rates-previous-hover.png');
	}, function(){
		$j(this).attr('src', 'image/our-rates-previous.png');
	});
	
	$j('.thisRate img:odd').hover( function(){
		$j(this).attr('src', 'image/our-rates-next-hover.png');
	}, function(){
		$j(this).attr('src', 'image/our-rates-next.png');
	});
	
	if( $j('#featuredRates li').length > 0 ){
		$j('#featuredRates li').not('li:eq(0)').hide();
		$j('#featuredRates li:eq(0)').addClass('visible');
		
		$j('.thisRate').prepend('<img src="/custom/esquirebank/image/featured-rate-previous.png" class="previousRate" alt="Previous Rate" />').append('<img src="/custom/esquirebank/image/featured-rate-next.png" class="nextRate" alt="Next Rate" />');
		
		$j('.thisRate img:even').live('click', function(){
			var holdThis = $j('#featuredRates li.visible');
			if( $j(holdThis).prev().length > 0 ){
				$j(holdThis).removeClass('visible').hide('slide', {direction: 'left'}, 500, function(){
					$j(holdThis).prev().addClass('visible').show('slide', {direction: 'right'}, 500);
				});
			}
			else{
				$j(holdThis).removeClass('visible').hide('slide', {direction: 'left'}, 500, function(){
					$j('#featuredRates li:last').addClass('visible').show('slide', {direction: 'right'}, 500);;
				});
			}
		});
		$j('.thisRate img:odd').live('click', function(){
			var holdThis = $j('#featuredRates li.visible');
			if( $j(holdThis).next().length > 0 ){
				$j(holdThis).removeClass('visible').hide('slide', {direction: 'right'}, 500, function(){
					$j(holdThis).next().addClass('visible').show('slide', {direction: 'left'}, 500);
				});
			}
			else{
				$j(holdThis).removeClass('visible').hide('slide', {direction: 'right'}, 500, function(){
					$j('#featuredRates li:first').addClass('visible').show('slide', {direction: 'left'}, 500);
				});
			}
		});
		intervalID = setInterval( function(){rotate();}, 5000 );
		$j('#featuredRates .thisRate img').click( function(){
			clearInterval(intervalID)
		});
	}
	
	//Category Page
	clickableContainer($j('#productCategory li'));
	$j('#productCategory li:last').css('border-bottom', '0');
	
	//Search Page
	$j('#froisearch-results li').live('click', function(){
        window.location=$j(this).find("a").attr("href");
	}).live('mouseover mouseout', function(event) {
		if (event.type == 'mouseover')
        	$j(this).addClass('over');
		else
			$j(this).removeClass('over');
	});
	
	//photo border
	if (typeof document.addEventListener == 'function'){
		$j('#dsPhoto, #productPhoto').css('position', 'relative').append('<img class="" id="photoBorder" alt="" src="http://esquirebank.fipreview.com/custom/esquirebank/image/photo-border.png">');
		$j('#photoBorder').css({'position':'absolute', 'left':'0', 'top':'0'});
	}
	
	//locations page
	$j('.locationAddress, .locationContact, .locationHours').live('mouseover mouseout', function(event) {
		if (event.type == 'mouseover')
        	$j(this).parent().addClass('over');
		else
			$j(this).parent().removeClass('over');
	});
	
	//account disclosures
	if( $j('h1:contains("Account Disclosures")').length > 0 ){
		$j('.individualPage h2').each( function(){
			$j(this).attr('id', $j(this).children('a').attr('class'));
		});
		$j('.individualPage h2 a').click( function(){return false;});
	}
	
	//Partnerships
	if( $j('h1:contains("Affinity Partnerships")').length > 0 ){
		$j('#categoryHeader p').css('margin-bottom', '1em');
	}
	$j('#catBreadcrumb a:contains("Affinity Partnerships")').text('Esquire Bank Affinity Partnerships')
	
	//Contact
	if( $j('h1:contains("Contact Us"), h1:contains("Sorry - Page Not Found")').length > 0 ){
		$j('#roi-captchaCode').attr('tabindex', '4');
		$j('.submitButton').attr('tabindex', '6');
	}
	
	//Videos
	if( $j('h1:contains("CDARS")').length > 0 ){
		$j('dl#productTabs').css('height', '582px');
		$j('dt:contains("Summary")').next().append('<div id="safeVideo"></div>');
		var safe = new SWFObject("/custom/esquirebank/flash/player-safe.swf", "playerplayon", "520", "346", "9");
		safe.write("safeVideo");
		
		$j('dt:contains("How")').next().append('<div id="howVideo"></div>');
		var how = new SWFObject("/custom/esquirebank/flash/player-how.swf", "playerplayon", "520", "346", "9");
		how.write("howVideo");
	}
	/*if( $j('h1:contains("LP Management Suite")').length > 0 ){
		//$j('dl#productTabs').css('height', '582px');
		$j('dt:contains("Deposit")').next().append('<div id="diVideo"></div>');
		var how = new SWFObject("/custom/esquirebank/flash/player-bank.swf", "playerplayon", "520", "346", "9");
		how.write("diVideo");
		console.log('here');
	}*/
	if( $j('#diVideo').length > 0){
		//$j('dl#productTabs').css('height', '785px');
		//$j('dt:contains("Summary")').next().append('<div id="diVideo"></div>');
		var how = new SWFObject("/custom/esquirebank/flash/player-bank.swf", "playerplayon", "520", "346", "9");
		how.write("diVideo");
		//console.log('here2');
	}
});

function confirmAlert(url){
			jConfirm(alertText, "Confirm", function(r) {
				if( r ){
					window.open(url);
				} else {
					return false;
			}
		});
		return false;
}

function confirmAlert2(url){
	if (!confirmAlert(url)) 
		return false; 
}

function productTabs(){
	if( $j('#productTabs').length > 0 ){
		$j('#productTabs').addClass('on');
		var offset = 60;
		$j('#productTabs dt').each(function(){
			if( $j(this).text().length > 15 )
				$j(this).addClass('longer');
		});
		$j('#productTabs dt:eq(0)').addClass('selected');
		$j('#productTabs dd').addClass('pane');
		$j('#productTabs dd').css('position','absolute');
		$j('#productTabs dd').not("dd:eq(0)").hide();
		$j('#productTabs').css('height', $j('#productTabs dd:eq(0)').height() + offset);
		
		$j('#productTabs dt').click( function(){
			var holdThis = $j(this);
			if( !holdThis.hasClass('selected') ){
				$j('#productTabs dt').removeClass('selected');
				holdThis.addClass('selected');
				if(tabEffect == "slide"){
					$j('#productTabs dd').slideUp(slideSpeed);
					$j('#productTabs').animate({ height : holdThis.next().height() + offset }, slideSpeed, function(){
						holdThis.next().slideDown(slideSpeed);									 
					});
				}
				else{
					$j('#productTabs dd').fadeOut(slideSpeed);
					$j('#productTabs').animate({ height : holdThis.next().height() + offset }, slideSpeed, function(){
						holdThis.next().fadeIn(slideSpeed);									 
					});
				}
			}
		});
	}
}

function rotate(){
	var holdThis = $j('#featuredRates li.visible');
	if( $j(holdThis).next().length > 0 ){
		$j(holdThis).removeClass('visible').hide('slide', {direction: 'right'}, 500, function(){
			$j(holdThis).next().addClass('visible').show('slide', {direction: 'left'}, 500);
		});
	}
	else{
		$j(holdThis).removeClass('visible').hide('slide', {direction: 'right'}, 500, function(){
			$j('#featuredRates li:first').addClass('visible').show('slide', {direction: 'left'}, 500);
		});
	}
}

function clickableContainer(what){
	what.click( function(){
		var href = $j(this).find("a").attr("href");
		if( href.indexOf('.pdf') >= 0 )
			window.open(href);
		else
			window.location = href;
		return false;
	}).hover( function(){
		$j(this).addClass('over');
	}, function(){
		$j(this).removeClass('over');
	});
}