//custom.js
//all settings for jquery based interactions


String.prototype.splitCSV = function(sep) {
  for (var foo = this.split(sep = sep || ","), x = foo.length - 1, tl; x >= 0; x--) {
    if (foo[x].replace(/"\s+$/, '"').charAt(foo[x].length - 1) == '"') {
      if ((tl = foo[x].replace(/^\s+"/, '"')).length > 1 && tl.charAt(0) == '"') {
        foo[x] = foo[x].replace(/^\s*"|"\s*$/g, '').replace(/""/g, '"');
      } else if (x) {
        foo.splice(x - 1, 2, [foo[x - 1], foo[x]].join(sep));
      } else foo = foo.shift().split(sep).concat(foo);
    } else foo[x].replace(/""/g, '"');
  } return foo;
};





//TOOTIPS FOR AGENT PAGE ETC

		$(document).ready(function()
			{
				$('.tipped').each(function(i) {
					$(this).qtip({
							content: {
									text: $('.tipCon', this)
										},
							style: {
									classes: 'ui-tooltip-aq'
										},
							position: {
									viewport: $(window),
									my: 'left center',  // Position my top left...
									at: 'right center', // at the bottom right of...
									target: $(this) // my target
										}
					});
				});
				
				
				$('.team-tip').each(function(i) {
					$(this).qtip({
							content: {
									text: $('.tipCon', this)
										},
							style: {
									classes: 'ui-tooltip-aq'
										},
							position: {
									viewport: $(window),
									my: 'top center',  // Position my top left...
									at: 'bottom center', // at the bottom right of...
									target: $(this) // my target
										}
					});
				});
				
				
				$('.info').each(function(i) {
					$(this).qtip({
							content: {
									text: $('.tipCon', this),
									title: {
											text: 'Important',
											button: 'Close'
											}
										},
							style: {
									classes: 'ui-tooltip-aq'
										},
							position: {
									viewport: $(window),
									my: 'left center',  // Position my top left...
									at: 'right center', // at the bottom right of...
									target: $(this)// my target									
										},
							hide: {
									event: false
									}
					});
				});
		});
		
//END TOOTIPS

//RAQ FORM TABS


//END RAQ FORM TABS

//SLIDESHOW SETTINGS

			$(function(){
				$('#slides').slides({
					preload: true,
					preloadImage: 'img/loading.gif',
					play: 5000,
					pause: 2500,
					hoverPause: true,
					generatePagination: true,
					slideSpeed: 700,
					animationStart: function(current){
						$('.caption').animate({
							top:300
						},100);
						if (window.console && console.log) {
							// example return of current slide number
							console.log('animationStart on slide: ', current);
						};
					},
					animationComplete: function(current){
						$('.caption').animate({
							top:20
						},200);
						if (window.console && console.log) {
							// example return of current slide number
							console.log('animationComplete on slide: ', current);
						};
					},
					slidesLoaded: function() {
						$('.caption').animate({
							top:20
						},200);
					}
				});
			});

//END SLIDESHOW SETTINGS


//TABLE ROW HILIGHTING

  // Hover a row in <tbody> 
  $(document).ready(function(){
$("table tbody tr").hover( 
    function()  
    { 
        // This gets executed on mouse-over 
        $(this).addClass('thover'); 
    },  
    function()  
    { 
        // This is the callback, so it gets executed on mouse-out 
        $(this).removeClass('thover'); 
    } 
); 
});


  // Hover a row in <tbody> for sitemap page 
  $(document).ready(function(){
$("table tbody tr.t").hover( 
    function()  
    { 
        // This gets executed on mouse-over 
        $(this).addClass('nohover'); 
    },  
    function()  
    { 
        // This is the callback, so it gets executed on mouse-out 
        $(this).removeClass('nohover'); 
    } 
); 
});
//END TABLE ROW HILIGHTING

//Hide Show Div

			$(document).ready(function(){
			 $('.hidden').hide();
			  $('#dropdown-options').change(function() {
				$('.hidden').hide();
				$('#div' + $(this).val()).show();
			 });
			});

//END Hide show Div

//MEGA DROPDOWN

$(document).ready(function() {
	
 
	function megaHoverOver(){
		$(this).find(".sub").stop().fadeTo('fast', 1).show();
			
		//Calculate width of all ul's
		(function($) { 
			jQuery.fn.calcSubWidth = function() {
				rowWidth = 0;
				//Calculate row removed cause we're using divs instead

				//Additional from TP to allow use of divs in the sub if needed
				$(this).find("div").each(function() {					
					rowWidth += $(this).width(); 
				});	
			};
		})(jQuery); 
		
		if ( $(this).find(".row").length > 0 ) { //If row exists...
			var biggestRow = 0;	
			//Calculate each row
			$(this).find(".row").each(function() {							   
				$(this).calcSubWidth();
				//Find biggest row
				if(rowWidth > biggestRow) {
					biggestRow = rowWidth;
				}
			});
			//Set width
			$(this).find(".sub").css({'width' :biggestRow});
			$(this).find(".row:last").css({'margin':'0'});
			
		} else { //If row does not exist...
			
			$(this).calcSubWidth();
			//Set Width
			$(this).find(".sub").css({'width' : rowWidth});
			
		}
	}
	
	function megaHoverOut(){ 
	  $(this).find(".sub").stop().fadeTo('fast', 0, function() {
		  $(this).hide(); 
	  });
	}
 
 
	var config = {    
		 sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
		 interval: 100, // number = milliseconds for onMouseOver polling interval    
		 over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
		 timeout: 500, // number = milliseconds delay before onMouseOut    
		 out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
	};
 
	$("ul#topnav li .sub").css({'opacity':'1'});
	$("ul#topnav li").hoverIntent(config);
});


//END MEGA DROPDOWN


//AGENT MODAL AND COOKIE STUFF

jQuery(function($) {
	var href,
		pageAgentID = $("#agentText").attr("data-agent-id"),
		cookiesettings = {
			expires: 365,
			path: '/',
			domain: 'nfumutual.co.uk'
		};
	
	function populateAgentFields(agentID) {
		if (agentID) {
			$.get('/agent-csv/locations.csv', function(data) {
				var lines = data.split("\n"), csv, name;
				for (var i = 0, length = lines.length; i < length; i++) {
					csv = lines[i].splitCSV();
					if (typeof csv[12] != 'undefined' && csv[12] == agentID) {
						var name = csv[0];
						if (name.length > 20) {
							name = name.substr(0, 20) + '...';
						}
						$('#dynAgentName').text(name);
						$('#dynAgentTel').text(csv[5]);
						$('#agent-help, a.agentName, a.agentGo')
							.addClass('agent')
							.attr('href', csv[7]);
						return;
					}
				}
			});
		}
	}
	
	populateAgentFields($.cookie("agent-id"));
	
	// set up the button events in the agent modal window
	$(".setLink[data-agent-id]").live('click',function(e) {
		var id = $(this).attr('data-agent-id');
		
		if (id && id != $.cookie('agent-id')) {
			$.cookie("agent-id", id , cookiesettings);
			populateAgentFields(id);
			_gaq = _gaq || [];
			_gaq.push(['_trackEvent', 'Agents', 'Set Local Agent', id]);
			window.console && console.log('Local agent set', id, _gaq);
		}
		return false;
	});
	
	// set up the button events in the agent modal window
	$("#agent-modal a").click(function(e) {
		if ($(this).hasClass("saveAgent")) {
			$.cookie("agent-id", pageAgentID , cookiesettings);
		} else if ($("#agent-dont-ask").attr("checked")) {
			$.cookie("agent-dont-ask", 1,   cookiesettings);
		}
//		$("#agent-modal").closeDOMWindow();

		$(window).attr("location", href);
	});
	
	// set the link click events
	$("a").click(function(e) {
		var link = $(this),
			acookie =  $.cookie("agent-id"),
			dontaskcookie = $.cookie("agent-dont-ask");
		
		if (link.hasClass('no-modal') || link.hasClass('agent')) {
			return;
		}
		
		// store the link target
		href = link.attr("href");
		
		if ($('#local-agent2').has(this).length > 0) {
			// clicked link is inside local agent box - show help link
			$.colorbox({
				width: "735px",
				inline: true,
				href: '#agent-help-Content',
				opacity: 0.5
			});
			return false;
		} else if (pageAgentID && pageAgentID != acookie && !dontaskcookie) {
/*			// navigating away from a (different) agent page
			$.colorbox({
				width: "725px",
				height: "450px",
				inline: true,
				href: '#agent-modal',
				opacity: 0.5
			});*/
			$.openDOMWindow({ 
				windowSourceID:'#agent-modal',
				modal: true,
				height:450,
				width:725,
				overlay:1,
				overlayColor:'rgb(127,127,127)',
//				overlayOpacity:'82',
				windowPadding:8,
				windowBGColor:'#FFF',
				borderSize:10,
				borderColor:'rgb(0,0,0)',
				positionType:'relative',
				positionLeft:0, 
				positionTop:0
			});
			return false;
		}
	});
});

//END AGENT MODAL AND COOKIE STUFF


//VARIOUS MODAL WINDOW SETTINGS
$(document).ready(function(){

/*
		$('.aDOMWindow').click(function(){ 
			$.openDOMWindow({ 
				windowSourceID:'#tim', 
				height:392,  
				width:835, 
				overlay:1, 
				overlayColor:'#FFF',
				overlayOpacity:'85',
				positionType:'anchoredSingleWindow',  
				windowPadding:8,  
				windowBGColor:'#FFF',  
				borderSize:8, 
				borderColor:'#DBDBDB',
				anchoredSelector:'#local-agent', 
				positionLeft:-590, 
				positionTop:-7
			}); 
			return false; 
		}); 
	*/	
		/*$('.extraWindow').click(function(){ 
			$.openDOMWindow({ 
				windowSourceID:'#extraWindowContent',
				width:950, 
				overlay:1, 
				height:80,
				positionType:'centered',
				overlayColor:'#000',
				overlayOpacity:'65',
				windowPadding:8,  
				windowBGColor:'#FFF',  
				borderSize:8, 
				borderColor:'#000'
			}); 
			$(window).trigger("resize");
			return false; 
		});
		
		//$('.closeExtra').closeDOMWindow({eventType:'click'});*/
		
		/*
		$('.searchAgain').live('click',function(){ 
			
			$.openDOMWindow({ 
				windowSourceID:'#searchAgain-modal',
				width:850, 
				overlay:1, 
				height:350,
				positionType:'centered',
				overlayColor:'#000',
				overlayOpacity:'65',
				windowPadding:0,  
				windowBGColor:'#FFF',  
				borderSize:0, 
				borderColor:'#000'
			});
			return false; 
		});
		*/
		//setting agent help
		/*$('#agent-help').live('click',function(){ 
						
			$.openDOMWindow({ 
				windowSourceID:'#agent-help-modal',
				width:750, 
				overlay:1, 
				height:600,
				positionType:'centered',
				overlayColor:'#000',
				overlayOpacity:'65',
				windowPadding:0,  
				windowBGColor:'',  
				borderSize:0, 
				borderColor:'#000'
			});
			return false; 
		});*/
//		$("#agent-help").colorbox({width:"735px", inline:true, href:"#agent-help-Content",opacity:0.5});
		$(".searchAgain").colorbox({width:"850px", inline:true, href:"#searchAgainContent",opacity:0.5});
		$(".extraWindow").colorbox({width:"850px", maxHeight: "80%", inline:true, href:"#extraWindowContent",opacity:0.5});
		$(".extraWindowVid1").colorbox({width:"630px", maxHeight: "75%", inline:true, href:"#extraVid1",opacity:0.5});
		$(".extraWindowVid2").colorbox({width:"630px", maxHeight: "75%", inline:true, href:"#extraVid2",opacity:0.5});
		$(".extraWindowVid3").colorbox({width:"630px", maxHeight: "75%", inline:true, href:"#extraVid3",opacity:0.5});

		$('.searchAgainJS').live('click', function() {
		
					
			$.fn.colorbox({width:"850px", inline:true, href:"#searchAgainContent",top:"10%"});
			
			$("html").animate({
				scrollTop: $("#mapWrapResults").offset().top
			}, "slow");
			
			
			})
		//
		
		
		$('form[name="search"]').live('submit',function(e) {
			//$('#searchAgainContent').closeDOMWindow();
			$(".searchAgain").colorbox.close();
			$("html").animate({
				scrollTop: $("#mapWrapResults").offset().top
			}, "slow");
		});
	});	
//END VARIOUS MODAL WINDOW SETTINGS


