// JavaScript Document for common routines

// jquery onload actions
$(document).ready(function(){
	newsearch() // wait forinput from user in search box, click, keypress
	sendsearch() // change form, and send search
	highlight() // allow arrow keys to navigate a ul
	stopreturnpost()
	scroller()
	showpopupbasket()
	closepopupbasket()
	collateraltabs()
	showlightbox()
	togglefilters()
	homepageclass()
	addthisglobal()
	showloading()
	clearemailinput()
	showmenu()
	//hidehidden()
	datepicker()
	notify()
});

function notify() {
	$(".helper").click(function() {
		var state = $(this).hasClass("closed");
		if (state) {
    		$(this).removeClass("closed").addClass("open");
			$(".notify").fadeIn("fast");
  		} else {
    		$(this).removeClass("open").addClass("closed");
			$(".notify").fadeOut("fast");
  		}
		return false;
	});
	$(this).not("a.helper").click(function(){
		//alert("clicky");
		var state = $(".helper").hasClass("open");
		if (state) {
    		$(".helper").removeClass("open").addClass("closed");
			$(".notify").fadeOut("fast");
  		}
	});
}

function datepicker(){
	$('.date').datepick({
		dateFormat: 'DD dd MM yyyy',
		//showSpeed: 'fast',
		showAnim: 'fadeIn',
		changeMonth: false
	});
}

function showmenu() {
	$('#navigation-primary a.nav-ideas').click(function() {
		var state = $(this).hasClass('closed');
		if (state) {
    		$(this).removeClass("closed").addClass("open");
			$("#nav-ideas-filter").fadeIn('fast');
  		} else {
    		$(this).removeClass('open').addClass('closed');
			$('#nav-ideas-filter').fadeOut('fast');
  		}
		return false;
	});
	$(this).not('#navigation-primary a.nav-ideas').click(function(){
		//alert(this);
		var state = $('#navigation-primary a.nav-ideas').hasClass("open");
		if (state) {
    		$('#navigation-primary a.nav-ideas').removeClass('open').addClass('closed');
			$('#nav-ideas-filter').fadeOut('fast');
  		}
	});
}

function clearemailinput() {
	var defaulttext = ""
	$("#keepintouch #email").focusin(function(){
		defaulttext = $(this).val();
		if (defaulttext.indexOf("...") > 0) {
			$(this).val("");
		}
	});
	$("#keepintouch #email").focusout(function(){
		if ($(this).val() == "") {
			$(this).val(defaulttext);
		}
	});
}

function addthisglobal(){
	$('.item').each(function(){
		var WNhref = $(this).find('.button').attr('href');
		
		if (WNhref !==undefined) {
			var $thistoolbox = $(this).find('.addthis_toolbox') // find empty addthis toolbox element
			if (WNhref.substring(0, 4)=='http'){ // if it is a complete URL then add the attribute to the toolbox, anchors will inherit
				$thistoolbox.attr('addthis:url', WNhref);
			} else { // else assume it is a local page
				$thistoolbox.attr('addthis:url','http://www.barnabasinchurches.org.uk' + WNhref);
			}
		}
	});
	
}

function homepageclass() {
	$('a.hometype').live('click', function() {
		var filter = $(this).attr('id');
		var $whatsnew = $('#whatsnew');
		var $whatsnewitems = $('#whatsnewitems');
		$.post('/gethomepagecontent/', {ideaword : filter},
			function(data) {
				$whatsnewitems.replaceWith(data);
				$().unbind('keydown.cbox_close'); // Disable close on esc key press
			}
		, 'html')
		.complete(function() { 	
			$('a.hometype').removeClass('selected'); // remove the last one clicked
			$('#' + filter).toggleClass('selected'); // add css to make it look different
			
			addthisglobal();
			
			var script = 'http://s7.addthis.com/js/250/addthis_widget.js#domready=1';
			if (window.addthis){
				window.addthis = null;
			}
			$.getScript(script);
			var addthis_config = {
				pubid: 'brfadmin'
			}
			
		}); // Incase we have script, links etc in returned content
		return false;
	});
}

function highlight(){
	window.displayBoxIndex = -1; 		// set global to keep track of where we are in list
	
	//mousover class toggle
	$('.searchcategory').mouseover(function(){
	  $('.searchcategory').removeClass('searchcategory_hover');
	  $(this).addClass('searchcategory_hover');
	});
	
	// keyup class toggle
	$('.sb_input').keyup(function(e){	// wait for keyup
		if (e.keyCode==40){  			// if it's cursor up
			navigatecat(1);  			// add one to the global and add a class to the corresponding li
		}
		if (e.keyCode==38){  			// if it's cursor down then minus one and add class to that li
			navigatecat(-1); 
		}
	});
	
	var navigatecat = function(diff){ 	// function to set the class based on index
		displayBoxIndex += diff;
		var BoxCollection = $('.searchcategory');
		if (displayBoxIndex >= BoxCollection.length){
			displayBoxIndex = 0;
		}
		if (displayBoxIndex < 0){
			displayBoxIndex = BoxCollection.length - 1;
		}
		var searchclass = 'searchcategory_hover'; // remove this class from all instances of the li, then add it to our selected li by index
		BoxCollection
			.removeClass(searchclass)
			.eq(displayBoxIndex)
			.addClass(searchclass);
		// Then set the hidden category field on the form so we can send it
		var searchcategory = BoxCollection.eq(displayBoxIndex).attr('id')
		$('#category').val(searchcategory);
	}
}

function newsearch(){
	var searchstring;
	$('.sb_input').bind('keyup click', function(){ 
		searchstring = $('.sb_input').val();
		if (searchstring.indexOf('...') > 0) { //if there is .. then clear it.
			searchstring = '';
			$(this).val('').css('color', 'black');
		}
		
		if (searchstring.length > 0){ // if we have a search then show the dropdown on keyup OR click if they leave and come back
			$('.searchcategory strong').text(searchstring);
			$('#searchform').find('.sb_dropdown').show();	// in the form, find the ul and show it
		} else {
			$('.searchcategory strong').text('');
			$('.sb_dropdown').hide();
		}
	});
	// Bind the mouseleave function in any case
	$('#searchform').bind('mouseleave',function(){ // was focusout, but found it odd 
		$('#searchform').find('.sb_dropdown').hide();
		$('.searchcategory').removeClass('searchcategory_hover');
	});
	
	
	$('#searchform').bind('focusout',function(){ // was focusout, but found it odd 
		var emptysearchstring = $('.sb_input').val(); // put default search phrase back in when moving away and it's empty.
		if (emptysearchstring.length == 0) {
			$('.sb_input').removeAttr('style');
			$('.sb_input').val('Enter search...');
		}
	});
	
}

function sendsearch(){
	$('.searchcategory').click(function() {
		var searchphrase = $('#search').val()
		if (searchphrase.length > 0){
			searchphrase = searchphrase.replace(" ", "+");
			var searchcategory = $(this).attr('id');
			$('#category').val(searchcategory);
			var searchcategory = $('#category').val()
			var searchurl = '/find/' + searchphrase + '/' + searchcategory + '/1'
			window.location = searchurl;
		}
		return false;
	});
}

function stopreturnpost(){
	$('#searchform').submit(function(){
		var searchphrase = $('#search').val()
		if (searchphrase.length > 0){
			searchphrase = searchphrase.replace(" ", "+");
			var searchcategory = $('#category').val()
			var searchurl = '/find/' + searchphrase + '/' + searchcategory + '/1'
			window.location = searchurl;
		}
		return false
	});
}

function hidehidden(){
	$('.showmore').each(function(){
		var hddcount = $(this).parent().siblings().has('a:not(:visible)').size();
		//var parent = $(this).parent().parent().find('dt');
		if (hddcount <=1){
			$(this).hide();
		}
		
	});
}

function scroller() {
	$("a.scroller-item-image").css('display', 'none');	//hide all the images
	$("#scroller-container li:eq(0) .scroller-item-tab").addClass("selected");	//set the first tab as selected
	$("#scroller-container li:eq(0) .scroller-item-image").css('display', 'block').addClass('fademe');	//display the first image
	$("#scroller-container li .scroller-item-tab").last().addClass("last");		//mark the last one

	scrollerintervalid = setInterval("cycledivs()", 8000);		//set a time to cycle through the items
	
	$("a.scroller-item-tab").click(function () {			//if someone clicks a dot
		$("a.scroller-item-tab").removeClass("selected");	//remove the active class
		$("a.scroller-item-image").css('display', 'none');	//hide all the images
		$(this).addClass("selected");						//add selected class to that tab
		$("a.selected").next().fadeIn('fast');				//show the selected image
		
		return false;
	});
	
	$("a.scroller-item-tab").mousedown(function () {				//cancel the timer when a user clicks a tab
		clearInterval(scrollerintervalid);
	});
	
	$("#scroller-container").hover(								//cancel the timer when a user hovers
		function () {
			clearInterval(scrollerintervalid);
		},
		function () {											//start it again when they move off
			scrollerintervalid = setInterval("cycledivs()", 8000);
		}
	);
}

function cycledivs() {
	if ($("#scroller-container li a.selected").hasClass("last")) { //if it is the last dot
		$("#scroller-container li a").first().click();
	} else {
		$("#scroller-container li a.selected").parent().next().children(".scroller-item-tab").click(); //click next
	}
}

function showpopupbasket() {
	$("#popupbasket a.edit").after(" | <span>Close</span>");
	$("#minibasket a").click(function () {
		$("#popupbasket").css("display", "block");
		return false;
    });	
}
function closepopupbasket() {
	$("#popupbasket span").click(function () {
		$("#popupbasket").css("display", "none");
    });	
}

function collateraltabs() {
	$("#product-collateral div").css("display", "none");
	$("#product-collateral #description").css("display", "block");
	$("#product-collateral-choices li a").click(function () {	
		$("#product-collateral-choices li a").removeClass("active")
		$("#product-collateral div").css("display", "none");

		var divid = $(this).attr("href");
		$(this).addClass("active")
		$(divid).css("display", "block");
		return false;
	});
}
function showlightbox() {
    $("a[rel*=lightbox]").fancybox();
	$(".feedback").fancybox({
		'hideOnContentClick': false,
		'autoDimensions'	: false,
		'width': 500, 
		'height': 'auto'
		});
}

function togglefilters() {
	$("#filter dd").css("display", "none");
	$("#filter dl").addClass("closed");
	$("#filter dd:has(a.remove)").siblings().removeClass("shown");
	$("#filter a.remove").parent().addClass("shown");
	//$("#filter dd.shown").parent().toggleClass("closed","collapsed");
	$("#filter dd.shown").css("display", "block");
	$("#filter dl:has(dd.shown)").removeClass("closed").addClass("collapsed");
	
	$("#filter dl.collapsed dd a.showmore").parent().css("display", "block");
	
	//$("#filter dl.closed dt").siblings().css("display", "none");
    
    $("#filter dt").click(function() {
    	$(this).parent().toggleClass("closed").toggleClass("collapsed");
    	//$(this).siblings(".shown").slideToggle();
    	$("#filter dl.closed dd").slideUp();
    	$("#filter dl.collapsed dd.shown").slideDown();
    	$("#filter dl.collapsed:has(a.showing)").children().slideDown();
    	$("#filter dd:has(a.remove)").siblings().removeClass("shown");
		$("#filter a.remove").parent().addClass("shown");
		$("#filter dl.collapsed dd a.showmore").parent().css("display", "block");
    	//$(this).siblings("a.showmore").click();
    	//$(this).siblings(".shown").slideToggle();
    });
    
    
    $("#filter a.showmore").toggle(function() {
			//alert('first click');
		$(this).parent().siblings().slideDown();
		$(this).addClass("showing");
		$(this).html('show fewer');
		return false;
    }, function() {
    	$(this).parent().siblings("dd:not(.shown)").slideUp();
	    $(this).html('show more');		
    	$(this).removeClass("showing");
    	return false;
    });
	
	hidehidden()
}

function showloading(){
	$("#loading").css('display', 'none');
	$("#filter a.add").click(function(){
		$("div.idea").css('display', 'none');
		$("#loading").css('display', 'block');
		 window.scrollTo(0,0);
		//$('<img src="/site/images/loading.gif" class="center" />').appendTo(".intro");
		//return false;
		//alert('new filter being added');
	});
}
