var slideDirection;
fsFont = {
	isInteger : function(s){
		return (s.toString().search(/^-?[0-9]+$/) == 0);
	},
	getHtml : function(url,tabOnly,tab,objItem,fnSuccess,fnError){	
		var checkUrl = url.split('?');
		
		if(checkUrl.length > 1){
			var thisUrl = url + '&tabOnly=1&tab=' + tab;
		} else {
			var thisUrl = url + '?tabOnly=1&tab=' + tab;
		}

		$.ajax({
			url: thisUrl,
			type: 'GET',
			dataType: 'html',
			timeout: 15000,
			error: fnError,
			success: fnSuccess
		});		
	},
	changeData : function(html,currentItem,fsCustom)
	{

		if(slideDirection == "next"){
			
			$('.scrollArea').append('<div class="scrollItem">' + html + '</div>');
			$(".scrollArea").animate({ left:"-952px" }, 800, "swing", function(){
				if($.isFunction(fsCustom)){ 
					fsCustom(); 
				}
				$('.scrollArea .scrollItem:first').remove();
				$('.scrollArea').css('left','0px');
			});		
			
		} else if(slideDirection == "prev"){
			
			$('.scrollArea').prepend('<div class="scrollItem">' + html + '</div>').css('left','-952px');
			$(".scrollArea").animate({ left:"0px" }, 800, "swing", function(){
				if($.isFunction(fsCustom)){ 
					fsCustom(); 
				}
				$('.scrollArea .scrollItem:last').remove();
			});		
			
		}
		
		document.title = $('#font_list ul li.current').text()  + " - Fontsmith";
		
		return true;

	},
	fontDefaults : function(){
		
		$('#buyFontClose').bind('click',function(){
			$('#buy_font_product').slideToggle('normal');
			return false;
		 });		

		if($('#tab_selector ul li[class="current"] a').attr('class') == 'overview'){
			<!-- set font links -->
			$('#font_list ul li').each(function(i){
							
				$(this).bind('click',function(){
					$('#buy_font_product').slideUp('normal');
	
					thisIndexPos = $('#font_list ul li').index(this);
					selectedIndexPos = $('#font_list ul li').index($('#font_list ul li.current'));
					
					<!-- work out if this item is before or after the currently selected item -->
					if(thisIndexPos > selectedIndexPos){
						slideDirection = "next";
					} else if(thisIndexPos < selectedIndexPos){
						slideDirection = "prev";
					}
					
					$('#font_list ul li.current').attr('class','');
					$(this).attr('class','current');
	
					$('.buy_font .fontsList').selectOptions($('#font_list ul li.current').attr('id').replace(/fontList/,''),true);
					fsFont.step1($(this).attr('id').replace(/fontList/,''),$('.buy_font .fontsList').data('container'));	
		
					<!-- get the next webpath -->
					newWebpath = $('#font_list ul li.current a').attr('href');
					newWebpath = newWebpath.split('?');
					newWebpath = newWebpath[0] + '?';
					
					$('#tab_selector ul li').each(function(i){
						tabLink = $('a', this).attr('href');
						tabLink = tabLink.split('?');
						$('a', this).attr('href',newWebpath + tabLink[1]);
					});

					$('#buy_font_form #redirect').val($('#tab_selector ul li[class="current"] a').attr('href').replace("??","?") + "&buyfont=1");
				
					<!-- function to run if get call is successful -->
					fnSuccess = function(html){
						objItem = $('#tab_selector ul li:first a');
						fsFont.changeData(html,objItem,function(){
							tab = $('#tab_selector ul li.current a').attr('class');
							fsFont.fontLinks(tab);	
						
						});	
					};
					
					<!-- function to run if call is unsuccessful -->
					fnError = function(){
						document.location.href=$('#font_list ul li.current a').attr('href') + '?tab=' + $('#tab_selector ul li.current a').attr('class');
					};
		
					<!-- now call for the html -->
					fsFont.getHtml($('a', $(this)).attr('href'),1,$('#tab_selector ul li.current a').attr('class'),$('#tab_selector ul li:first a'),fnSuccess,fnError);								
								
					return false;							  
				});		
							
			});
		};

	},
	fontNav : function(direction){
		/* set global var */
		slideDirection = direction;
		
		tab = 'overview';
		objItem = $('#tab_selector ul li:first a');
		
		$('#buy_font_product').slideUp('normal');
				
		<!--Get current id-->
		currentId = $('#font_list ul li.current').attr('id').replace(/fontList/,'');	
		
		<!-- Get the current list item, then get its sibling-->
		if(direction == "next"){
			nextItem = $('#fontList' + currentId).next();
			if(!nextItem.length){
				<!-- end of the column, move to the next -->
				if($('#fontList' + currentId).parent().attr('class') == 'col8' || (!nextItem.length && $('#font_list ul.' + $('#fontList' + currentId).parent().attr('class') + ' li').index($('#fontList' + currentId)) != 5  )){
					<!-- end of all columns, move to the start -->
					nextItem = 	$('#font_list ul.col1 li:first');
				} else {
					nextItem = $('li:first',$('#fontList' + currentId).parent().next())
				}
			}
		} else {
			nextItem = $('#fontList' + currentId).prev();				
			
			if(!nextItem.length){
				<!-- start of the column, move to the previous -->
				if($('#fontList' + currentId).parent().attr('class') == 'col1' || (!nextItem.length && $('#font_list ul.' + $('#fontList' + currentId).parent().attr('class') + ' li').index($('#fontList' + currentId)) == 1  )){
					<!-- end of all columns, move to the start -->
					lastColumn = $('#font_list ul:has(li)').length;
					
					nextItem = 	$('#font_list ul.col' + lastColumn + ' li:last');
				} else {
					nextItem = $('li:last',$('#fontList' + currentId).parent().prev())
				}
			}
		}
		<!-- get the next webpath -->
		newWebpath = $('a', nextItem).attr('href');
		newWebpath = newWebpath.split('?');
		newWebpath = newWebpath[0] + '?';

<!-- function to run if get call is successful -->
		fnSuccess = function(html){
			objItem = $('#tab_selector ul li:first a');
			fsFont.changeData(html,objItem,function(){
				var tab = $('#tab_selector ul li[class="current"] a').attr('class');
				fsFont.fontLinks(tab);
			});	
		};
		
		<!-- function to run if call is unsuccessful -->
		fnError = function(){
			document.location.href=$('#font_list ul li[class="current"] a').attr('href');
		};

		<!-- now call for the html -->
		fsFont.getHtml(newWebpath,1,'overview',objItem,fnSuccess,fnError);

		$('#tab_selector ul li').each(function(i){
			tabLink = $('a', this).attr('href');
			tabLink = tabLink.split('?');
			$('a', this).attr('href',newWebpath + tabLink[1]);
		});

		$('#buy_font_form #redirect').val($('#tab_selector ul li[class="current"] a').attr('href').replace("??","?") + "&buyfont=1");

		$('#font_list ul li.current').attr('class','')
		
		nextItem.attr('class','current');

		$('.buy_font .fontsList').selectOptions(nextItem.attr('id').replace(/fontList/,''),true);

		fsFont.step1(nextItem.attr('id').replace(/fontList/,''),$('.buy_font .fontsList').data('container'));		

		return false;
	},
	fontLinks : function(tab){

		fsFont.doFavourites();

		$('.tabHeaderBuy').bind('click',function(){
			//$('#buy_font_product').toggle('normal');			
			hideBuyPanel('simpleLogin');
			showBuyPanel('buy_font_product');
			//$('#buy_font_product').slideToggle('normal'); 			
		
			selectedId = $('#buy_font_product .fontsList').selectedValues();
			selectedId = selectedId[0];
			fsFont.step1(selectedId);
			return false;
		 });
				
		if(tab=="overview"){		
			<!-- set overview "next" button -->
			fsRollover.init();
			$('#nextFont').unbind('click').bind('click',function(){
				fsFont.fontNav('next');
				return false;
			});
			
			<!-- set overview "next" button -->
			$('#prevFont').unbind('click').bind('click',function(){
				fsFont.fontNav('prev');
				return false;
			});
		} else if(tab=="testdrive"){
			fsFont.doTestDrive();
							
		} else if(tab=="detail"){
			fsRollover.init();
			$('a[rel*=modalPanel]').modalPanel();

			$('#scroll_area').cycle({ 
				fx:     'scrollHorz', 
				prev:   '#prevFont', 
				next:   '#nextFont', 
				timeout: 0,
				startingSlide: sCurrentSlide,
				before:function(){
					$('.detailListing li a.selected').removeClass('selected');	
					$('.detailListing li a[rel=' + this.id.replace(/galleryitem/,'') + ']').addClass('selected');	
				}
			});

			$('.detailListing li').each(function(){
				$('a', this).bind('click',function(){

					$('#scroll_area').cycle(parseInt(this.rel));
					return false;
				});
			});						
			
		
		};

	},
	fontBuyLinks : function(){
		$('#buy_font_product .fontsList').data('container','buy_font_product').bind('change',function(){
			selectedId = $(this).selectedValues();
			selectedId = selectedId[0];
			thisContainer = $(this).data('container');
			fsFont.step1(selectedId,thisContainer);		
		});
		
		$('.#buy_font_product .fontsVariations').data('container','buy_font_product').bind('change',function(){
			selectedId = $(this).selectedValues();
			selectedId = selectedId[0];
			thisContainer = $(this).data('container');
			fsFont.step2(thisContainer);		
		});
		
		
		
	},
	step1 : function(selectedId,container){
		/*selectedId = $('#font_list ul li.current').attr('id').replace(/fontList/,'');*/
	
		$('#' + container + ' .step3').slideUp('fast');
		$('#' + container + ' .step2').slideUp('fast',function(){

			if(selectedId != 0) {
				$('#' + container + ' .fontsList').selectOptions(String(selectedId), true);	
				$('#' + container + ' .fontsVariations').removeOption(/./);
				$('#' + container + ' .fontsVariations').addOption("","Please select");
				$('#' + container + ' .fontsVariations').ajaxAddOption("/_assets/fontvariations.cfm", { contentid:selectedId }, false, function(){
						$('#' + container + ' .step2').slideDown('fast');				
				});	
			
			}
								
		});
	}, 
	step2 : function(container){

		contentid = $('#' + container + ' .fontsList').selectedValues();
		catid = $('#' + container + ' .fontsVariations').selectedValues();
				
		$('#' + container + ' .step3').slideUp('fast', function(){
			
			if(catid != 0){
																
				$.getJSON("/_assets/getDetails.cfm?contentid=" + contentid + "&catid=" + catid,function(data){		
			
						$('#' + container + ' .fontName').text(data.fontName + " " + data.fontWeight);
						$('#' + container + ' .fontPrice').html("&pound;"+data.price);
						$('#' + container + ' .buyfontPreview').attr('src',data.webpath);					
						$('#' + container + ' .step3').slideDown('fast');
						
				});
			
			}
				
		});				
	},
	doTestDrive : function(fContainer, fTarget, fWeight, fList, fTitle, fFilename, fContentid, firstRun){

		fContainer = (fContainer == undefined) ? sContainer : fContainer;
		fTarget = (fTarget == undefined) ? sTarget : fTarget;
		fWeight = (fWeight == undefined) ? sWeight : fWeight;		
		fList = (fList == undefined) ? sList : fList;
		fTitle = (fTitle == undefined) ? sTitle : fTitle;
		fFilename = (fFilename == undefined) ? sFilename : fFilename;
		fContentid = (fContentid == undefined) ? sContentid : fContentid;
		firstRun = (firstRun == undefined) ? 1 : firstRun;

		if(!firstRun){
			fsFont.saveFlashText();
		};

		$(fContainer + " " + fTarget).flashembed({
			src:"/_assets/swf/testdrive.swf",
			scale: "noscale", 
			bgcolor:"#19171a", 
			allowScriptAccess:"always" ,
			id:"flash" + fContainer.replace('#','')
		},
		{
			sPath:    "/_assets/swf/fonts/",
			sFont:    fTitle,
			sText:   ($.cookie('testdriveText') == null) ? 'Enter your own text here...' : $.cookie('testdriveText'),
			sWeights: fList,
			sDefault: fWeight,
			sSizeIndex: ($.cookie('testdriveSize') == null) ? '5' : $.cookie('testdriveSize')
		});		

		/*
		$(fContainer + " .footer_test_drive .fontDetailsLink").attr('rel','testy').bind('click',function(){
			window.location.href = '/fonts/' + fFilename + '?tab=detail';			
			return false;
		});*/
		
		$(fContainer + ' .compareFonts').bind('change',function(){
			$.ajax({
				url: "/_assets/fontDetails.cfm?contentid=" + $(this).selectedValues(),
				type: 'GET',
				dataType: 'json',
				timeout: 15000,
				error: function(XMLHttpRequest, textStatus, errorThrown){ alert("There's currently a problem with the connection, please try again in a moment: " +textStatus) },
				success: function(data){

					var newId = $('.content_border .testdrive').length + 1;
								
					$('#tab_panel .scrollItem:last').clone().insertAfter('#tab_panel .scrollItem:last');
					$newItem = $('#tab_panel .scrollItem:last');
					
					$('.testdrive',$newItem).attr('id','testdrive' + newId)	
																	
					$('.font_name img', $newItem).attr('src', '/images/spacer.gif').attr('src', data.headerImage);	
					$('.buy_font p:last', $newItem).html(data.priceBlock);
					$('.content_border', $newItem).attr('style','border-top: #' + data.colour + ' 4px solid');				

					
					$('.tabHeaderBuy', $newItem).data('contentid',data.contentid).bind('click',function(){
						//$('#buy_font_product').toggle('normal');			
						hideBuyPanel('simpleLogin');
						showBuyPanel('buy_font_product');
						$('html, body').animate({scrollTop:$('#buy_font_product').position().top}, 'slow'); 
						//$('#buy_font_product').slideToggle('normal');	
						fsFont.step1($(this).data('contentid'),'buy_font_product');

						return false;
					 });
					
																	
																	
					$('#testdrive' + newId + ' .flash').html('');
					
					$('#testdrive' + newId + ' .fontDetailsLink').attr('href','/fonts/' + data.filename + '?tab=detail');
					
					/* now sort out favourites */
					
					$('#testdrive' + newId + ' .fontFavouritesLink').attr('href','/_assets/manageFavourites.cfm?font=' + data.contentid);

					$.ajax({
						url: "/_assets/manageFavourites.cfm?font=" + data.contentid + "&redirect=0&action=check",
						type: 'GET',
						dataType: 'json',
						timeout: 15000,
						error: function(XMLHttpRequest, textStatus, errorThrown){ alert("There's currently a problem with the connection, please try again in a moment: " +textStatus) },
						success: function(data){

							if(data.exists == "TRUE"){
								$('#testdrive' + newId + ' .fontFavouritesLink:last').text('Remove from font-favourites');
							} else {
								$('#testdrive' + newId + ' .fontFavouritesLink:last').text('Add to font-favourites');
							}
							
						}
					});	

					fsFont.doFavourites('#testdrive' + newId + ' .fontFavouritesLink');
					
					var weightList = [];
					$.each(data.variations, function(i,item){ 
						if(item.toLowerCase() != "family"){
							weightList.push(item);
						};
					}); 														


					fsFont.doTestDrive('#testdrive' + newId, ' .flash', data.defaultItem, weightList.toString() , data.title.replace(/ /,''), data.filename, data.contentid, 0);
					
					$('html, body').animate({scrollTop:$('#testdrive' + newId).position().top}, 'slow'); 

				}
			});
													  
		});		
		
		

	},
	saveFlashText : function(){
		
		var getMovie = function(movieName){
			if (window.document[movieName]){
				return window.document[movieName];
			}
			if (navigator.appName.indexOf("Microsoft Internet")==-1)
			{
				if (document.embeds && document.embeds[movieName])
					return document.embeds[movieName]; 
				}
				else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
				{
				return document.getElementById(movieName);
			}			
		};
		
		if($('#testdrive1').length){

			$.cookie('testdriveText', getMovie('flashtestdrive1').getText(), { expires: "never" });
			$.cookie('testdriveSize', getMovie('flashtestdrive1').getSizeIndex(), { expires: "never" });
		};
	},
	doFavourites : function(destId){

		var targetID = '.fontFavouritesLink';
		if(destId != null){
			targetID = destId;
		}

		$(targetID).bind('click',function(){

			var pageId = "";
			var thisItem = $(this);
			
			pageId = thisItem.attr('href').split( "=" );
			pageId = pageId[pageId.length-1];
			
			$.ajax({
				url: "/_assets/manageFavourites.cfm?font=" + pageId + "&redirect=0",
				type: 'GET',
				dataType: 'json',
				timeout: 15000,
				error: function(XMLHttpRequest, textStatus, errorThrown){ alert("There's currently a problem with the connection, please try again in a moment: " +textStatus) },
				success: function(data){

					if(thisItem.html() == 'Add to font-favourites'){
						thisItem.html('Remove from font-favourites');
					} else if(thisItem.html() == 'Remove from font-favourites'){
						thisItem.html('Add to font-favourites');
					}
									
					if(data.fSize > 0){
						$('#favouritesSize').html(data.fSize);
						$('#fontFavouritesWrapper').removeClass('hidden').addClass('show');
					} else {
						$('#fontFavouritesWrapper').removeClass('show').addClass('hidden');
						$('#favouritesSize').html('');					
					}
					
				}
			});	
			
			return false;
		});
			
	}
};
