//   Principality JS

var ie6 = false;
var $j = jQuery.noConflict();

$j(document).ready(function () {

    fnJsClass();
    fnCheckIe();
    fnResize();
    fnAccountToggle();
    fnFormDefaultText();
    fnTabs();
    fnRowToggle();
    fnResetForm();
    fnPrint();
    fnToolTip();
	fnFooter();
	fnFlyout();
	fnVideoOverlay();
	fnImageOverlay();
	fnShowHide();
	fnBranchSelector();
	fnNewsTicker();

    /* IE6 Functions */
    if (ie6) {
        fnBgFlicker();
    }
    
    /* Optional js check to see if the function exists first */
    
    if(window.fnMortgageCalc){
    	fnMortgageCalc();
    }
    if(window.fnHomeCarousel){
    	fnHomeCarousel();
    }
    
});


/**
* jqEM to detect font size changes
*/
//set the text size that the default body computes to
var fontSize = 12;

$j.jqem.bind(function(a,b,c) {
	fnResize();
});
	
function fnResize(){
	if( $j.jqem.current() == fontSize) {			
		$j('body, #main').addClass('enh');
	}else if($j.jqem.current() != fontSize){		
		$j('body, #main').removeClass('enh');
	};
};

function fnJsClass(){
	$j('body').addClass('js');
}

/**
 * Assign simple hide and show default value for inputs like search box
 */
function fnFormDefaultText() {
	
	$j(".formDefault").each(function(){
		var $label = $j(this).prev('label');
		var txt = $label.text();
		if($label.has('em').length>0){
			txt = $j('em',$label).text();
		}
		
		if($j(this).next('.default').length){
			txt = $j(this).next('.default').text();
		}
		
		 if ($j(this).val() == "" || $j(this).val() == txt) {
			$j(this)[0].defaultValue = txt;
        	$j(this).val($j(this)[0].defaultValue);
     	}
		
	});
	
	$j(".formDefault").unbind("focus,blur").focus(function () {
		if ($j(this).val() == $j(this)[0].defaultValue) {
        	$j(this).val("");
        }
	 }).blur(function() {
        if ($j(this).val() == "") {
        	$j(this).val($j(this)[0].defaultValue);
     	}
	 });
}

function fnCheckIe(){
	if($j('#ie6').length>0){ie6 = true;}
}

function fnBgFlicker(){
	try {document.execCommand("BackgroundImageCache", false, true);} catch(err){}
}

function fnRowToggle(){
	//Product table accordions
	$j('.productTable .productDetail').hide();
	
	$j('.productTable .toggle').each(function(){
		$j(this).click(function(){
			$j(this).closest('tr').toggleClass('activeRow').next('.detailRow').find('.productDetail').slideToggle();
			return false;
		});	
	});
	
	//Guide accordions
	$j('.guideAccordion .productDetail').hide();
	
	$j('.guideAccordion .toggle').each(function(){
		$j(this).click(function(){
			$j(this).closest('tr').toggleClass('activeRow').next('.detailRow').find('.productDetail').slideToggle();
			return false;
		});	
	});
}
function fnResetForm() {
  $j('.resetForm').click(function(){
    $j(this).parent('form').each(function(){
      this.reset();
    });
    // ajax callback to go in here if required
    return false;
  });
}
function fnToolTip(){
  $j('.tooltip').tooltip({ 
      track: true, 
      delay: 0, 
      showURL: false, 
      showBody: " - ", 
      fade: 250 
  });
}
/** not used atm 
function fnMoreToggle(){
  var toggleHTML = '<a href="#" class="showMore toggle">Show <span class="more">more</span> features and benefits<span class="icon"></span></a>';
  var addInfo = $j('.addInfo')
  addInfo.hide().after(toggleHTML);
  $j('.toggle').click(function(){
    var thisToggle = $j(this);
    thisToggle.toggleClass('open').prev('.addInfo').slideToggle('fast');
    var word = thisToggle.children('.more');
    if (word.html() == 'more') word.html('fewer');
    else if (word.html() == 'fewer') word.html('more');
    return false;
  });
}
*/
function fnTabs() {
	if($j('div.tabs')){
		$j('div.tabs').tabs({
			// no options yet			
		});
		$j('div.tabs ul:first li:last').addClass('last');
		$j('div.tabs ul:first li:first').addClass('first');
	}
	
	$j('a.tabSwitch').click(function(){
		href = $j(this).attr('href');
		$j('div.tabs').tabs('select', href);
		
		return false;
	});
	
	//set active tab with js variable
	if (typeof initTab != "undefined"){
		$j('div.tabs').tabs( "select" , initTab );
	}
	
	
	$j('div.tabs').each(function(){
		
		$hideAreaTab = $j('.hideArea', $j('div.tabs ul:first'));
		
		if($hideAreaTab.length){
			$j(this).tabs({
			   select: function(event, ui) {
				   if($j(ui.tab).parent().hasClass('hideArea')){
				   $j('.areaHide').hide();
				   }else{
				   	 $j('.areaHide').show();
				   }
			   }
			});

		}
		
		//set active tab with css
		$activeTabs = $j('.active:first', $j('div.tabs ul:first'));
		if($activeTabs.length){
			index = $activeTabs.index();
			$j(this).tabs("select", index);
		}
		
	});
	
	$j('.calcTabs a').each(function(){
		if($j(this).width()<92){
			$j(this).css({'width': '90px'});
		}
	});
	
}

function fnPrint(){
	
	$j('a.print').click(function(){
		window.print();	
		return false;
	});
	
}

/* SIFR Initiation */

/* This section adds the ability to use :not in the selectors to filter out anything that shouldn't be replaced */
parseSelector.pseudoClasses = {
  'not': function(nodes, selector) {
    var result = [];
    each: for(var i = 0, node; i < nodes.length; i++) {
      node = nodes[i];
      var ignore = parseSelector(selector, node.parentNode);
      for(var j = 0; j < ignore.length; j++) {
        if(ignore[j] == node) continue each;
      }
      result.push(node);
    }
    return result;
  }
};

	var scala = {src: '/principalityAssets/pbsAssets/flash/scala.swf'};
	
	// You probably want to switch this on, but read <http://wiki.novemberborn.net/sifr3/DetectingCSSLoad> first.
	sIFR.useStyleCheck = true;
	sIFR.activate();


function fnReplace(){	
	/* Selectors */
	/* Home page Feature Blocks 
	var homeSavingsFB = '.home .featureBlocks .fb.savings h2 a';
	var homeMortgagesFB = '.home .featureBlocks .fb.mortgages h2 a';
	var homeInsuranceFB = '.home .featureBlocks .fb.insurance h2 a';*/
	
	var h1Heading = 'h1, .mh-intro .lead-title';

	/*sIFR.replace(scala, {
		selector: homeSavingsFB
		,selectable: false
		,forceTextTransform : true
		,wmode: 'transparent'
		,css: ['.sIFR-root {color:#50bfca; padding:0; margin:0; text-transform:uppercase;}']
	});
	
	sIFR.replace(scala, {
		selector: homeMortgagesFB
		,selectable: false
		,forceTextTransform : true
		,wmode: 'transparent'
		,css: ['.sIFR-root {color:#ff0600; padding:0; margin:0; text-transform:uppercase;}']
	});
	
	sIFR.replace(scala, {
		selector: homeInsuranceFB
		,selectable: false
		,forceTextTransform : true
		,wmode: 'transparent'
		,css: ['.sIFR-root {color:#fa9801; padding:0; margin:0; text-transform:uppercase;}']
	});*/
	
	sIFR.replace(scala, {
		selector: h1Heading
		,selectable: false
		,forceTextTransform : true
		,wmode: 'transparent'
		,css: ['.sIFR-root {color:#ff0000; padding:0; margin:0}']
	});
}

fnReplace();

function fnAccountToggle(){
	var yourAccount = $j('#yourAccount');
	yourAccount.hide();
	//yourAccount.append('<a href="#"id="closeYourAccount">Close</a>');
	$j('#accountToggle').click(function() {
		yourAccount.slideToggle('slow','easeInOutCubic');
		return false;
	});
	$j('#closeYourAccount').click(function() {
		yourAccount.slideUp('slow');
		return false;
	});
};

function fnFooter(){
	
	var $fNav = $j('#fNav');
	var $fNavCont = $j('#fNavCont');
	
	$j('h4', $fNav).wrapInner('<a href="#"></a>');
	$fNavCont.hide();
	
	$fNav.addClass('closed');
	
	$j('h4 a', $fNav).click(function(){
		$fNav.toggleClass('open closed');
		$fNavCont.slideToggle();
		return false;
	});
	
	
}

function fnFlyout(){
	
	/* Mouse version */

	$j('#nav > ul li').hover(
		function(){
			$j(this).addClass('hover');
		},
		function(){
			$j(this).removeClass('hover');
		});

	/* Keyboard version */
	$j('#nav a').focus(
		function(){
			$j(this).parents('li').find('.flyout').parent().addClass('hover');
		});
	$j('#nav a').blur(
		function(){
			$j(this).parents('li').find('.flyout').parent().removeClass('hover');
		});	
}

function fnVideoTracking(id){
	if(window.ns_onclick){
		ns_onclick (this,'',id,'clickin');
	}
	return false;
}

function fnVideoOverlay() {
	
		$j.fn.fancybox.defaults.overlayColor = '#000';
		$j.fn.fancybox.defaults.overlayOpacity = '0.75'; 
	
		$video = $j('a.video');
		
		if($video.length){
			$video.each(function(){
				
				href = $j(this).attr('href');

				if(!href){return true;}
				
				vars = 'flv=' +$j(this).attr('href');
				
				var data = $j(this).metadata();
				 
				if(data.xml){vars +='&amp;xml='+data.xml;}
				if(data.image){vars +='&amp;image='+data.image;}
				
				$j(this).fancybox({
					'padding'			: 0,
					'autoScale'			: false,
					'transitionIn'		: 'none',
					'transitionOut'		: 'none',
					'href'				: '/principalityAssets/pbsAssets/flash/player.swf',
					'type'				: 'swf',
					'width'				: 500,
					'height'			: 330,
					'titleShow'			: false,
					'onComplete'		: function(){
						var vidId = $j(this)[0].vidId;
						if(vidId){
							fnVideoTracking(vidId);
						}
					},
					'swf'				:{
					   	'wmode'				: 'transparent',
						'allowfullscreen'	: 'true',
						'flashvars'			: vars
						}
				});
			});
		}	
	
}



function fnImageOverlay() {
	
		$image = $j('a.image');
		
		if($image.length){
			$image.each(function(){
								
				$j(this).fancybox({
					'padding'	: 0,
					'autoScale'	: true,
					'titleShow'	: true,
					'type'		: 'image'
				});
			});
		}	
	
}

function fnShowHide() {
	
	$j(".accordion .reveal").hide();
	
	$j(".accordion h3 a").click(function() {
		
	    $j(".accordion h3 a.active").not(this).parent().next().slideToggle('fast');
	    $j(".accordion h3 a.active").not(this).removeClass("active");

	    $j(this).toggleClass("active");
	    $j(this).parent().next().slideToggle('fast');
	    return false; 

	}
	);    

	$j(".accordion h3 a.active").parent().next().slideToggle('fast');

}// //fnShowHide

function fnBranchSelector(){
	$j('select.branch').each(function(i){
		
		$obj = $j(this);
		
		var count = 1;
		var loop = 1;
		var total = $j('optgroup', $obj).length;
		var txt = $j(':selected', $obj).text();;
		
		var content ='<div class="branchLists" id="overlay'+i+'"><div class="row cfx">';
		
		$j('optgroup', $obj).each(function(){
			var markup ='<div class="col"><h2>'+$j(this).get(0).label+'</h2><ul>';
			
			$j('option', $j(this)).each(function(){
				markup+='<li><a href="#">'+$j(this).get(0).text+'</a></li>';
			});
			
			markup+='</ul></div>';
			
			content+= markup;
			
			
			if(count==total){
				content+='</div>';
			}else if(loop==5){
				content+='</div><div class="row cfx">';
				loop=1;
			}
			
			loop++;
			count++;
			
		});
		
		content+='</div>';
		
		
		$obj.hide().after('<span class="fld"><span class="branchName">'+txt+'</span> <a href="#overlay'+i+'" class="choose">Choose Branch</a></span><div class="branchOverlay hide"></div>');
		$j('.branchOverlay').html(content);
		
		$j('.branchOverlay .col:last').addClass('wide');
		$j('.col:last', $j('.branchOverlay .row')).addClass('last');
		$j('.branchOverlay .row:last').addClass('last');
	
		
		$j('a.choose').each(function(){
			$j(this).fancybox({
				'padding'	: 20,
				'autoScale'	: false,
				'titleShow'	: false,
				'type'		: 'inline'
			});	
		});
		
		$j('#fancybox-content .branchLists a').live('click', function(){
			index = $j(this).parents('.branchLists').find('li a').index($j(this));
			
			$j('select.branch')[0].selectedIndex = index+1;
			$j('.branchName').text($j(this).text());
			
			
			$j.fancybox.close();
			return false;
		});
		
		
	});
}

/* Function that gets run after the filters have reloaded content */
function fnFilterAjax(){
	fnRowToggle();
	fnToolTip();
}

function fnNewsTicker(){
	$j('.newsTicker').each(function(i){
		
		var id = 'nav-'+i;
		
		$j(this).after('<div class="tickerNav cfx" id="'+id+'"></div>');
		
		$j(this).cycle({
			pager : '#'+id
			//fx: 'scrollHorz'
		})
		
	});
}
