// 
$(document).ready(function(){
  
  loadWordPressBlog('http://yalebooks.wordpress.com/feed/');
  
  /* Clear live search box if a click is made anywhere */
  $("#livesearch_result").mouseleave(function(event){
     $(this).removeClass('borders').html("");
  });
  
// toDo: add memory - always have idx:0 open - re-order ul's and save order - show first 5 + more.. - 
	$('.closed').slideUp("fast");
	$("#menu li h4").css('cursor', 'pointer').click(function(){
	 	$(this).nextAll("ul").toggle("slow").toggleClass("closed");
	});      
	
// Tabbed Display	
	$(function() {
		// setup ul.tabs to work as tabs for each div directly under div.panes
		$("ul.tabs").tabs("div.panes > div", {
			effect: 'fade' 
		});
	});	
	
//Carousel script

	$('.caro_wrapper').each(function(i){
		i++; //increment each time we have a container!
		
		/*  next and previous buttons for 4 items showing */
		$('.caro_prev_4').each(function(i){
			i++;
			$(this).attr('id','caro_prev_4_' + (i));
		});
		$('.caro_next_4').each(function(i){
			i++;
			$(this).attr('id','caro_next_4_' + (i));
		});
		
		/*  next and previous buttons for 3 items showing */
		$('.caro_prev_3').each(function(i){
			i++;
			$(this).attr('id','caro_prev_3_' + (i));
		});
		$('.caro_next_3').each(function(i){
			i++;
			$(this).attr('id','caro_next_3_' + (i));
		});
		
		/* For the numbered pagination on the main slider */
		$('.caro_grey_pagination').each(function(i){
			i++;
			$(this).attr('id','caro_grey_pagination' + (i));
		});
		
		//pagination for 4 items
		$('.caro_pagination_4').each(function(i){
			i++
			$(this).attr('id','caro_pagination_4_' + (i));
		});
		
		//pagination for 3 items
		$('.caro_pagination_3').each(function(i){
			i++
			$(this).attr('id','caro_pagination_3_' + (i));
		});
		
		
		//for our unordered list 
		
		//for the main carousel
		$('.caro_carousel_main').each(function(i){
			i++;
			$(this).attr('id','caro_carousel_main' + (i));
		});
		//for our carousel with 4 items showing
		$('.caro_carousel_4').each(function(i){
			i++;
			$(this).attr('id','caro_carousel_4_' + (i));
		});
		//for our carousel with 3 items showing
		$('.caro_carousel_3').each(function(i){
			i++;
			$(this).attr('id','caro_carousel_3_' + (i));
		});
		
		//now we set the settings for each carousel
		//main carousel
		$('#caro_carousel_main'+(i)).carouFredSel({
				
			auto:  {
        play:true,
        pauseDuration:6000
      },
			circular: false,
			infinite: true,
			items: {
				visible:1, // show 1 visible items
				minimum:1 // has to have at least 1 item or the carousel won't have any pagination
			},
			
			pagination: "#caro_grey_pagination" + (i),
			padding:[0,0]
		});
		
		//4 items carousel
		$('#caro_carousel_4_'+(i)).carouFredSel({
			auto: false, //for auto play
			circular: false,
			infinite: true,
			items: {
				visible:4, // show 4 visible items
				minimum:4 // has to have at least 4 item or the carousel won't have any pagination
			},
			prev: {
				button: "#caro_prev_4_" + (i), 
				key: ".caro_prev_4"
			},
			next: {
				button:"#caro_next_4_" + (i),
				key : ".caro_next_4"
			} ,
			pagination: "#caro_pagination_4_" + (i),
			height:210
			
		});
		
		$('#caro_carousel_3_'+(i)).carouFredSel({
			auto: false, //for auto play
			circular: false,
			infinite: true,
			items: {
				visible:3, // show 3 visible items
				minimum:3 // has to have at least 3 item or the carousel won't have any pagination
			},
			prev: {
				button: "#caro_prev_3_" + (i), 
				key: ".caro_prev_3"
			},
			next: {
				button:"#caro_next_3_" + (i),
				key : ".caro_next_3"
			} ,
			pagination: "#caro_pagination_3_" + (i),
			height:280
		});
		
		//our default carousel that we have on the display page
		$('.caro_prev').each(function(i){
			i++;
			$(this).attr('id','caro_prev' + (i));
		});
		$('.caro_next').each(function(i){
			i++;
			$(this).attr('id','caro_next' + (i));
		});
		$('.caro_pagination').each(function(i){
			i++;
			$(this).attr('id','caro_pagination' + (i));
		});
		$('.caro_carousel').each(function(i){
			i++;
			$(this).attr('id','caro_carousel' + (i));
		});
		$('#caro_carousel'+(i)).carouFredSel({
			
			auto: false, //for auto play
			padding:[25,0], // padding for each item
			circular: false,
			infinite: true,
			items: {
				visible:4, // show 4 visible items
				minimum:4, // has to have at least 4 item or the carousel won't have any pagination
				height:250, // auto adjust the height depending on the item
				width:150 // has to have a fixed width or nothing will display in the tabs.
			},
			prev: {
				button: "#caro_prev" + (i), 
				key: ".caro_prev"
				},
			next: {
				button:"#caro_next" + (i),
				key : ".caro_next"
				} ,
			pagination: "#caro_pagination" + (i)
		});
		
	});




// ListProducts AJAX	element calls..
	$('listproducts').each(function() {
	 	var rel = $(this).attr('rel') + '&rid=' + $(this).attr('id');
	 	ldbLookUp(rel);
	});

// Basket animation
	$('.add2bqanimate').click(function(){
		$(this).spectrum({
			dest: $('.viewb'),
			spCss: {border: '1px solid #FFCC00'},
			duration: 1500,
			easing: 'easeOutQuart'
		});
		return true;
	});
	
// Search Ahead with LiveSearch..	
	$('#qsearch').livesearch({
		searchCallback: searchFunction,
		queryDelay: 450,
		innerText: "Search by Title, Author, Keyword...",
		minimumSearchLength: 3
	});
		
	function searchFunction(searchTerm) {
		searchTerm = searchTerm.replace(/\s+/ig, '+');
		lsLookup('bib','q=' + searchTerm + '&rid=livesearch_result&dbm=yale', function(errCode, rID, resTxt){
			$("#livesearch_result").addClass('borders').html(resTxt);
		});
	}
	
//capture the return key
	$("#searchform").keypress(function(event) {
	  	var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
      if (keycode == 13) { // keycode for enter key
      	event.preventDefault();
      	$('#searchform').submit();
         //return false;
      } else  {
         //return true;
      }

	});
			
});

function loadWordPressBlog(bURL)
{
  $.ajax({
		type: "POST",
		url: give_me_a_baseref() + "include/xml.proxy.asp", 
		data:"ax=loadwordpressblog&rid=londonBlog&url="+bURL,
    dataType: "xml",
		success: function(xml){
		  var errCode = $("errorcode", xml).text();
			var errMsg = $("errormsg", xml).text();
			var response = $("responsetext", xml).text();
			var rID = $("rid", xml).text();
			if(errCode == 0){
				 	$('#'+rID).html(response).fadeIn("slow");
      }else{
			   response = "<p>Error connecting to Yale London Blog</p>";
         $('#'+rID).html(response).fadeIn("slow");
			}
    }
	});
}

function ldbLookUp(params){
// assume params already serialized
  $.ajax({
		type: "POST",
		url: give_me_a_baseref() + "include/xml.proxy.asp", 
		dataType: "xml",
		data: encodeURI(params),
		success: function(xml){
			
			var errCode = $("errorcode", xml).text();
			
			var errMsg = $("errormsg", xml).text();
			var response = $("responsetext", xml).text();
			var rID = $("rid", xml).text();
			
			
			if(errCode == 0){
				if (params.indexOf("listproducts")!=-1) {
					// IE no longer recognises the <listproducts> element (as it is non-standard) so you can't modify it in the dom
					// you can only use it as a point of reference!!
					$('#'+rID).after(response).fadeIn("slow");
				}else{
				 	$('#'+rID).html(response).fadeIn("slow");
				}
					
			}else{
			
			}
		}
	});

}

function generateAISheet(barcode,rectimestamp) {
	$("#ai_sheet").html("<img src='images/loading.gif' alt='Generating AI Sheet' style='border:0px;' /><br /><a href='#'>Generating AI Sheet</a>");
	
	$.ajax({
		type: "POST",
		url: "include/ajax.client.asp", 
		dataType: "xml",
		data: "ax=generatepdf&barcode="+barcode+"&rectimestamp="+rectimestamp,
		success: function(xml){
			var code = $("errorcode", xml).text();
			if(code == 0)
			{
				var loc = ($("responsetext", xml).text()).toString();
				openWindow(loc, "VanillaSiteAISheet", 800, 800);
				$("#ai_sheet").html("<a href='#' onclick='openWindow(\""+loc+"\", \"VanillaSite AI Sheet\", 800, 800);'>View AI Sheet</a>");
			}
			else
			{
				alert("Error retrieving AI Sheet");
			}
		}
	});
}
	
function extdLU(isbn, fields, action){
	var msg;
	var frmParams = {
		k: isbn,
		ax: action
	};

	$.ajax({
		type: "POST",
		url: give_me_a_baseref() + "include/xml.proxy.asp", 
		dataType: "xml",
		data: frmParams,
		success: function(xml){
			
			$.each(fields.split(','), function(idx, val){
				var t = $(val, xml).text();
				msg += '[' + val + ':' + t + ']\r\n';
				if(t){$('#'+val).append(t).fadeIn("slow")};
			});
			//alert(msg);
		}
	});

}

function openWindow(theURL, theName, width, height)
	{
		/*
			openWindow modification - JES [15/03/2011]
			Work around added to get around opening from mod rewritten pages and dev/live configuration
		
		*/
		
		if(!theURL.toLowerCase().match('http://'))	//If it's an external link ignore it
		{
			theURL = give_me_a_baseref() + theURL;
		}
    
		var theWindow = window.open(theURL , ""+theName+"" ,"width=" + width + ",height="+ height + ",toolbar=no,directories=no,menubar=no,status=no,resizable=yes,location=no,scrollbars=yes,copyhistory=0,alwaysRaised=yes,top=0,left=0");
		theWindow.title = theName;
		theWindow.focus();
	}

  function give_me_a_baseref()
  {
    //Is the location path a script?
    var _isScript = (location.pathname.split('/')[1]).match(/\./);
		    _isScript = !(_isScript == null);
    var _barePath = (location.pathname.toString() == "/");
    
    return ((location.pathname.split('/')[1] == 'pid')||(_isScript)||(_barePath) ? 'http://' + location.hostname + '/' :'http://' + location.hostname +'/' + location.pathname.split('/')[1] + '/');
  }


function hvalidate() {
	var x = document.forms[0].elements;
	var blob = '';
	// loop through everything and check it
	for (var i=0;i<x.length;i++)
	{
		var sreg = /identifier/ig;
		if (sreg.test(x[i].value)){
			var reg = /\-|\s+/g;
			x[i+1].value = x[i+1].value.replace(reg, '');
		}
		//blob += x[i].name + ' ' + x[i].value + "\n";
	}
	//alert(blob);	
}

function GetISBNs(iTxt){
	
	var myhash = new Hash(); 
	var blob = "";
	var reg = /\-/g;
	iTxt = iTxt.replace(reg, "");
	
	var reg = /(\d{10}|\d{9}X)/ig;
	var parts = iTxt.match(reg, "$1");
	if(parts){
		for (var i=0; i<parts.length; i++)
		{
			if(parts[i].substring(0,3) != ('978'||'979') ){
				myhash.set(parts[i], '');  
			}
		}
	}

	var reg = /(978\d{10}|979\d{10})/ig;
	var parts = iTxt.match(reg, "$1");
	if(parts){
		for (var i=0; i<parts.length; i++)
		{
			myhash.set(parts[i], '');  
		}
	}
	
	myhash.each(function(item) {
    blob += item.key + '\n';
		//blob += item.value + '\n';
	});
	
	document.searchISBN.ISBNList.value = blob;
}

function _check_email(form,email)
{
  $(document).ready(function(){
    
    $("#mce-response").html("");
    
    var _email = $("#"+email).val();
    var mailfilter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if(!mailfilter.test(_email))
    {
      $("#mce-response").html("<h4>Please enter a valid email address</h4>");
      return false;
    }
    else
    {
      $("#"+form).submit();
    }
  });
}
