// 
$(document).ready(function(){

  /* Clear live search box if a click is made anywhere */
  $(document).click(function(){
    $("#livesearch_result").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 Stuff	
	$('.caro_wrapper').each(function(i){
		i++;
		//alert(i);
		/*************************************************/
		//carousel settings for normal 4 item carousel
		/*************************************************/
		$('.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));
		});

		// Fred's jQuery scroller function
		$('#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)
		});
		/*************************************************/
		//carousel settings for home page carousel
		/*************************************************/
		$('.caro_prev_main').each(function(i){
			i++;
			$(this).attr('id','caro_prev_main' + (i));
		});
		$('.caro_next_main').each(function(i){
			i++;
			$(this).attr('id','caro_next_main' + (i));
		});
		$('.caro_carousel_main').each(function(i){
			i++;
			$(this).attr('id','caro_carousel_main' + (i));
		});
		// Fred's jQuery scroller function
		$('#caro_carousel_main'+(i)).carouFredSel({
			auto: true, //for auto play
			scroll: {
	        items           : null,      //  items.visible
	        fx              : "scroll",
	        easing          : "swing",
	        duration        : 1500,
	        pauseOnHover    : true
	    },
			padding:[0,0], // padding for each item
			circular: true,
			infinite: true,
			items: {
				visible:1, // show 4 visible items
				minimum:1, // has to have at least 4 item or the carousel won't have any pagination
				height:350, // auto adjust the height depending on the item
				width:600 // has to have a fixed width or nothing will display in the tabs.
			},
			prev: {
				button: "#caro_prev_main" + (i), 
				key: ".caro_prev_main"
				},
			next: {
				button:"#caro_next_main" + (i),
				key : ".caro_next_main"
				} 
		});
		
	}); //end of carousel settings!


// 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 Drop-Down
	$("#qsearch").focus(function(){
    if($(this).val() == "Enter search terms.."){
      $(this).val('');
    }
  }).autocomplete(give_me_a_baseref() + "include/auto.complete.asp", {
		width: 390,
		max: 12,
		scroll: true,
		scrollHeight: 330,
		formatResult: function(row) {
			row[0] = row[0].replace(/(\bnot\b )|(\band\b )|(\bthe\b )|(\b\w{1}\b )|(\b\w{2}\b )|(\(.+?\))|(\,)|(\?)|(\')/gi, ' ');
			return row[0].replace(/\s+/g, ' ');
		}
	});
	*/
	
	$('#qsearch').livesearch({
		searchCallback: searchFunction,
		queryDelay: 450,
		innerText: "Search",
		minimumSearchLength: 3
	});
		
	function searchFunction(searchTerm) {
		searchTerm = searchTerm.replace(/\s+/ig, '+');
		lsLookup('bib','q=' + searchTerm + '&rid=livesearch_result&dbm=kcathie', function(errCode, rID, resTxt){
			$("#livesearch_result").addClass('borders').html(resTxt).highlight(searchTerm);
			if (resTxt != "") {
				$("#livesearch_ref").html(resTxt);	//store for 'go' button in case of 1 result (this copy should survive user defocusing autosearch)
			}
		});
	}	
	
	/*
	$("a.livesearch").live('mouseenter',function(){
    var title = ($(this).attr('title')).replace(/(\bnot\b )|(\band\b )|(\bthe\b )|(\b\w{1}\b )|(\b\w{2}\b )|(\(.+?\))|(\,)|(\?)|(\')/gi,' ');
    $('#qsearch').val(title.replace(/\s+/g,' ')); 
  });
	*/
	var sf = $('#searchform');
	sf.submit(function() {
		//var autoItems = $('#livesearch_result div .livesearch');
		var autoItems = $('#livesearch_ref div .livesearch');
		if (autoItems.length == 1) {
			//go to the autosearched item.
			var linkdest = autoItems[0].href;
			window.location = autoItems[0].href;	//redirs
			return false;
		} else if (autoItems.length > 1) {
			//more than 1 autocomplete item. user expects search results to contain these,
			//and in effect the search has already been done via autosearch. Match results.
			return true;
		} else {
			return true;	//normal full search
		}
	});
	
//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 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, "KyleBooksAISheet", 800, 800);
				$("#ai_sheet").html("<a href='#' onclick='openWindow(\""+loc+"\", \"Kylebooks 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;
}

