$(document).ready(function () {
	// Test is browser is IE
    var browserIsIE = null;
    if (jQuery.browser.msie == true) {
        browserIsIE = true;
    } else {
        browserIsIE = false;
    };
 // primary and secondary nav hover for IE < 9
    if (browserIsIE == true) {
        $(".primary-nav li, .secondary-nav li").hover(function () {
            $(this).addClass("hover");
        }, function () {
            $(this).removeClass("hover");
        });
    };
    
  // accordion
    $('.accordion h5').click(function () {
        $('.accordion h5').removeClass('open');
     // close all slides
        $('.accordion ul ul').slideUp('normal');
        if ($(this).next().is(':hidden') == true) {
            $(this).addClass('open');
            $(this).next().slideDown('normal');
        }
    });
    $('.accordion h5').mouseover(function () {
        $(this).addClass('hover');
    }).mouseout(function () {
        $(this).removeClass('hover');
    });
    $('.accordion ul ul').hide();
    
   // carousel
    $(".carousel .scrollable").scrollable();
    		
    $(".items figure.thumb a").click(function(e) {
    			e.preventDefault();
    			if ($(this).hasClass("active")) { return; }
    			var itemUrl = $(this).attr('href');
    			var content = '';
    			if(itemUrl.indexOf('vimeo.com') != -1) {
    				var id = itemUrl.match(/[0-9]{1,15}/i);
    				if (browserIsIE) {
    					content	= '<object width="644" height="370"><param name="wmode" value="opaque" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id='+id[0]+'&amp;server=vimeo.com&amp;color=00adef&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id='+id[0]+'&amp;server=vimeo.com&amp;color=00adef&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="644" height="370" wmode="opaque"></embed></object>';
    				} else{
    					content	= '<iframe src="http://player.vimeo.com/video/'+id[0]+'?title=0&amp;byline=0&amp;portrait=0" width="644" height="370" frameborder="0"></iframe>';
    				}
    			}
    			else if(itemUrl.indexOf('youtube.com') != -1) {
    				var id = itemUrl.match(/v=([a-zA-Z0-9_-]{1,99})/i);
    				content = '<iframe width="644" height="370" src="http://www.youtube.com/embed/'+id[1]+'?rel=0" frameborder="0" allowfullscreen></iframe>';
    			} else {
    				content	= '<img src="' + itemUrl + '">';
    			}
    			$('.carousel .placeholder').html(content);
    			if ($('.carousel .items figure.thumb').length <= 4) {
    				$('.carousel a.browse').addClass('disabled');
    			};
    			$(".items a").removeClass("active");
    			$(this).addClass("active");
    			return;
    	}).filter(":first").click();
    
   // timeline
    var timeline = $('.component.timeline');
    if (timeline.length) {
        var timeline_animating = false;
     // build a list of years
        var years = $('<ul class="years"></ul>');
        timeline.find('ol > li').each(function () {
            var h2 = $(this).find('h2');
            var year = h2.text();
            $(this).addClass('year-' + year);
            years.append('<li class="year-' + year + '">' + year + '</li>');
        });
        timeline.prepend(years);
        timeline.find('ol > li').each(function (i) {
            var h2 = $(this).find('h2');
            var previous = $('<a class="previous icon blue left"></a>');
            var next = $('<a class="next icon blue right"></a>');
            var next_year = years.find('li:eq(' + (i + 1) + ')');
            var previous_year = years.find('li:eq(' + (i - 1) + ')');
            previous.bind('click', function () {
                if (!previous_year.length) return;
                previous_year.click();
            });
            next.bind('click', function () {
                if (!next_year.length) return;
                next_year.click();
            });
            h2.prepend(previous);
            h2.append(next);
            var children = $(this).find('li');
            if (children.length > 1) {
                var ul = $(this).find('ul');
                ul.wrap('<div class="slider"/>');
                var div = $(this).find('div.slider');
                ul = div.find('ul');
                var pagination = $('<div class="pagination"></div>');
                var previous = $('<a class="previous icon blue left"></a>');
                var next = $('<a class="next icon blue right"></a>');
                var text = $('<span class="text"> <span class="current">1</span> of <span>' + children.length + '</span> </span>');
                pagination.append(previous);
                pagination.append(text);
                pagination.append(next);
                var current = 1;
                previous.bind('click', function () {
                    if (timeline_animating || current == 1) return;
                    timeline_animating = true;
                    current--;
                    text.find('.current').text(current);
                    ul.animate({
                        'left': '+=684px'
                    }, 'slow', function () {
                        timeline_animating = false;
                    });
                });
                next.bind('click', function () {
                    if (timeline_animating || current == children.length) return;
                    timeline_animating = true;
                    current++;
                    text.find('.current').text(current);
                    ul.animate({
                        'left': '-=684px'
                    }, 'slow', function () {
                        timeline_animating = false;
                    });
                });
                $(this).append(pagination);
            }
        });
     // space years equally, except for first year with fixed width
        var timeline_width = timeline.width();
        var year_one_width = years.find('li:first').width() + parseInt(years.find('li:first').css('margin-right'));
        var year_width = (timeline_width - year_one_width) / (years.find('li').length - 1);
        years.find('li:not(:first)').width(Math.floor(year_width));
     // add click handler
        years.find('li').bind('click', function () {
            timeline.find('li.selected').removeClass('selected');
            var year = $(this).text();
            $(this).addClass('selected');
            timeline.find('li.year-' + year).addClass('selected').find('ul').css('left', 0);
        }).bind('mouseover', function () {
            $(this).addClass('hover');
        }).bind('mouseout', function () {
            $(this).removeClass('hover');
        });
        timeline.find('ol ul').each(function () {
            var li = $(this).find('li');
            var w = li.width() * li.length;
            $(this).width(w);
        });
        years.find('li:first').click();
    }
    
 // equalise homepage columns
    if ($('body#home').length) {
        var min_height = 0;
        $('#spot, .get-started-search').each(function () {
            min_height += $(this).height() + parseInt($(this).css('margin-top')) + parseInt($(this).css('margin-bottom'));
        });
        min_height = min_height - 35;
        equaliseHeights('.column-third', min_height);
    }
    
 // Tabbed component
	if ($('#body.search-form .component.tab').length) {
		$('.tab-wrapper > div').not('.tab-wrapper > div:nth-child(2)').hide();
		tabcomponent();
	};
	// init tooltip
    initToolTip();

	// table zebra style
	$('article table tr:nth-child(even)').addClass('even');
	$('.subscribe article table tr:nth-child(odd)').addClass('odd');
	
});

function tabcomponent() {
    $('.tabset li a').click(function (e) {
        e.preventDefault();
        var index = $('.tabset li a').index(this) + 1;
        var selector = 'div#' + index;
        $('.tab-wrapper > div').hide();
        $('.tab-wrapper ' + selector).show();
        $('.tabset li a').removeClass('active');
        $(this).addClass('active');
    });
};


// flip search buttons

function submitform(form)	
{
  document.forms[form].submit();
}

function flipSearchButton()

{
   document.getElementById('search_clickable').style.display = 'none';
   document.getElementById('search_unclickable').style.display = 'block';
}


 function flipPersonSearchButton()

{
   document.getElementById('person_search_clickable').style.display = 'none';
   document.getElementById('person_search_unclickable').style.display = 'block';
}
 
 function flipAdvancedSearchButton()

 {
    document.getElementById('advanced_search_clickable').style.display = 'none';
    document.getElementById('advanced_search_unclickable').style.display = 'block';
 }
 
 function flipAddressSearchButton()

 {
    document.getElementById('address_search_clickable').style.display = 'none';
    document.getElementById('address_search_unclickable').style.display = 'block';
 }
 
 function flipBusinessSearchButton()

 {
    document.getElementById('business_search_clickable').style.display = 'none';
    document.getElementById('business_search_unclickable').style.display = 'block';
 }

// toggle

 function HideDiv() {
	    $('.tabs').hide();
	}
	function ShowDiv(ctrl) {
	    HideDiv();
	    $('#' + ctrl).show();
	}
   ShowDiv('adv');

   
$(document).ready(function() {   
   
 $(".toggle").click(function() {
       if(!$(this).hasClass('active')){
           $('.active').not(this).toggleClass('active').next('.hidden').slideToggle(300);
           $(this).toggleClass('active').next().slideToggle("fast");
       }
   }).next(".hidden").hide();
});  
   
   
//init tool tip
function initToolTip() {
    var toolTipBox = $('<div class="tooltip"><div class="c"><div class="content"><p></p></div></div><div class="b"></div></div>').appendTo('body').css('left', '-9999px');
    var textHolder = $('p', toolTipBox);
    $('a.hint').each(function () {
        var link = $(this);
        var val = link.attr('title');
        link.removeAttr('title');
        if (val.length) {
            link.hover(function () {
                var _this = $(this);
                textHolder.html('').html(val);
                toolTipBox.css({
                    left: _this.offset().left + _this.width(),
                    top: _this.offset().top
                });
            }, function () {
                toolTipBox.css('left', '-9999px');
            });
        }
    });
};

function equaliseHeights(elements, min_height) {
    var elements = $(elements);
    var elements_max_height = min_height;
    elements.each(function () {
        var h = $(this).height() + parseInt($(this).css('padding-top')) + parseInt($(this).css('padding-bottom'));
        if (h > elements_max_height) elements_max_height = h;
    });
    elements.each(function () {
        var h = elements_max_height;
        $(this).height(h).css('padding-bottom', 0);
    });
}

//cycle spot
$(function () {
    $('#spot ul').cycle({
        delay: 0
    });
});

if ($('#spot ul') && ($('#spot ul').children().length == 1)) {
    $('#spot ul :first').show();
}

//cycle bannerShow
$(function () {
    $('#bannerShow ul').cycle({
        delay: 0
    });
});

if ($('#bannerShow ul') && ($('#bannerShow ul').children().length == 1)) {
    $('#bannerShow ul :first').show();
}

//yox view
$(function(){
	 $(".yoxview").yoxview({ skin: "top_menu" });
     $(".noLinkClasses").yoxview({ textLinksSelector: "" });
});

//family tree
function load(firstName, lastName) {
	//var load = window.open('familyTreeDisplay.action?action=A&firstName='+firstName+ '&lastName='+lastName ,'','scrollbars=no,menubar=no,height=680,width=1024,resizable=yes,toolbar=no,location=no,status=no');
	var load = window.open('http://familytree.Findmypast.co.uk/live/FamilyTreeExplorer3DS.html?newTree=true&firstName='+firstName+ '&lastName='+lastName ,'','scrollbars=no,menubar=no,height=680,width=1024,resizable=yes,toolbar=no,location=no,status=no');
}

function validateLogin(){
    var strerror = "";
    var formname = document.signin;
    var emailReg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
    var emailReg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,}|[0-9]{1,3})(\]?)$/; // valid

    if (formname.email.value.length < 1) {strerror = strerror + "Email\n";}
    if (formname.password.value.length < 1) {strerror = strerror + "Password\n";}

    if (strerror != "") {
      alert("Please enter the following fields:\n\n" + strerror);
	  return false;
    }
    else {
      document.signin.submit();
    }
  }

function setSelect(fld, value, defaultSelected) {
    if (defaultSelected == null)
    {
  	  defaultSelected = 0;
    }
    
    if (fld.selectedIndex != defaultSelected)
    {
   	  return;
    }	
    
    x = 0; 
    if (fld.length > 0)
    {
  	  value = value.toUpperCase();
  	  while (x < fld.length)   {
    	  if (fld.options[x].value.toUpperCase() == value) {
      	  fld.options[x].selected = true;
      	  return; }
    	  x++;        
      }
    }
    fld.options[defaultSelected].selected = true;
  }

//SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var popupStatus = 0;

//loading popup with jQuery magic!

function loadPopup() {
  //loads popup only if it is disabled
  if (popupStatus == 0) {
      $("#backgroundPopup").css({
          "opacity": "0.7"
      });
      $("#backgroundPopup").fadeIn("slow");
      $("#popupContent").fadeIn("slow");
      popupStatus = 1;
  }
}

//disabling popup with jQuery magic!

function disablePopup() {
  //disables popup only if it is enabled
  if (popupStatus == 1) {
      $("#backgroundPopup").fadeOut("slow");
      $("#popupContent").fadeOut("slow");
      popupStatus = 0;
  }
}

function MyPopUpWin() {

  var iMyWidth;
  var iMyHeight;
  //half the screen width minus half the new window width (plus 5 pixel borders).
  iMyWidth = (window.screen.width / 2) - (75 + 10);

  //half the screen height minus half the new window height (plus title and status bars).
  iMyHeight = (window.screen.height / 2) - (100 + 50);

  //Open the window.
  var win2 = window.open("filename.htm", "Window2", "status=no,height=200,width=150,resizable=yes,left=" + iMyWidth + ",top=" + iMyHeight + ",screenX=" + iMyWidth + ",screenY=" + iMyHeight + ",toolbar=no,menubar=no,scrollbars=no,location=no,directories=no");
  win2.focus();
}

//centering popup

function centerPopup() {
  //request data for centering
  var windowWidth = document.documentElement.clientWidth;
  var windowHeight = document.documentElement.clientHeight;
  var popupHeight = $("#popupContent").height();
  var popupWidth = $("#popupContent").width();
  //centering
  $("#popupContent").css({
      "position": "absolute",
      top: '70%',
      left: '50%',
      margin: '-300px 0 0 -325px'
  });
  //only need force for IE6
  $("#backgroundPopup").css({
      "height": windowHeight
  });
}

//CONTROLLING EVENTS IN jQuery
$(document).ready(function () {
  //LOADING POPUP
  //Click the button event!
  $(".load").click(function () {
      //centering with css
      centerPopup();
      //load popup
      loadPopup();
  });
  //CLOSING POPUP
  //Click the x event!
  $("#popupContentClose").click(function () {
      disablePopup();
  });

  $("#popupContentCloseBtm").click(function () {
      disablePopup();
  });
  //Click out event!
  $("#backgroundPopup").click(function () {
      disablePopup();
  });
  //Press Escape event!
  $(document).keypress(function (e) {
      if (e.keyCode == 27 && popupStatus == 1) {
          disablePopup();
      }
  });

});

function submitform(form)	
{
	document.forms[form].submit();
}

// Create cookie 

function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name)
{
	createCookie(name,"",-1);
}

//payment price band switch

function togglePrices(flag)
{
	if(flag){
			$(".Pricetrue").removeClass("hidden");
			$(".Pricefalse").addClass("hidden");
	}
    else{
		$(".Pricefalse").removeClass("hidden");
		$(".Pricetrue").addClass("hidden");
	}
}

function toggalPay(flag)
{
	if(flag.indexOf("S")>0){
		//$("#payButton").text('Subscribe');
	}else{
		//$("#payButton").text('Buy Credits');
	}
}

//newFunction
function printerFriendlyVersion(pageReference) {
	var width = screen.width; 
    var height = screen.height; 
	if (width == 800)
	{
	  printWindow = window.open(pageReference,"print","top=0,left=0,width=800,height=600,scrollbars=yes,resizable=yes");
	  if (navigator.appName.indexOf("Microsoft") != -1)
	  {
	    printWindow.resizeTo(screen.availWidth,screen.availHeight);
	  }		  
	  else
	  {
	    printWindow.moveTo(0,0);
	    printWindow.outerWidth = screen.availWidth;
	    printWindow.outerHeight = screen.availHeight;
	  }
	}
	else
	{
	  printWindow=window.open(pageReference,"print","status=no,top=50,left=50,scrollbars=yes,resizable=yes,width=800,height=600");
	}
	printWindow.focus();
}

