var urlPrefix = "/trees/"
var slideshow;

function init_main()
{
	$("#lhm ul").sortable({
		update: function(event, ui){
			lhmUpdateOrder(this);
			//var test = $("#lhm ul#level1").serialize()
			//$("#dump").append($(test).dump());
			//alert($(this).serialize());
			//alert($("#lhm ul#level1").serialize());
			//$("#dump").append($(this).serialize());
			//$("#dump").append($(this).dump());
			//$("#dump").append($("#lhm ul").serialize());
			//$("#dump").append($(ui).dump());
			//$("#dump").append($(event).dump());
			
		}
	});
	view_attribute_values();
}

function startSlideShow(){
	slideshow = self.setInterval("slideshowStart()",2500);
}

function isset(varname) {
if(typeof( window[ varname ] ) != "undefined") return true;
else return false;
}

function stopSlideShow(){
		slideshow = window.clearInterval(slideshow);
		$('.pauseSlideShow').html('Play');
		
		$('.pauseSlideShow').removeClass('pauseSlideShow').addClass('playSlideShow');
	
}

function is_int(variable){
	return variable.constructor === Number && Math.round(variable, 0) === variable;
}

function slideshowStart(){

  	$('.slidePrice').fadeOut(100);
  	var curSlide = parseInt($('#currentSlide').html());
    var maxSlide = parseInt($('#maxSlide').html());
    
    if(curSlide==(maxSlide)){
      slideNumber = 1;
    	distance = '0px';
    }else{
    	slideNumber = (curSlide+1);
    	distance = '-=559px';
    }
    
    if(curSlide==(maxSlide-1)){
    	$('#arrowMainRight').hide();
    }else{
    	$('#arrowMainRight').show();
    }
    
    if(slideNumber!=1){
    	$('#arrowMainLeft').show();
    }else{
    	$('#arrowMainLeft').hide();
    }
    
    var newLink = $('#link-'+slideNumber).html();
  	$('#slide-link').attr('href',newLink);
  	
    $('#currentSlide').html(slideNumber);
  	$('#slideDigits').html($('#currentSlide').html()+' of '+$('#maxSlide').html());
  	$('#path-'+(curSlide+1)).html('<img src=\''+$('#imgsrc-'+(curSlide+1)).html()+'\'>');
    
  	$('#categorySlideshowTrack').animate({ 
    	marginLeft: distance
    	}, 0 , function(){
    		$('.slidePrice').fadeIn(500);
    		$('.slideThumbnailOn').removeClass('slideThumbnailOn');
    		$('#slide-thumb-'+slideNumber).addClass('slideThumbnailOn');
    		
    		if(is_int((parseInt(slideNumber)-1)/5)){
    			var thumbnailsInView = 5;
			  	var thumbnailWidth = 93;
			  	
			  	var curSlide = parseInt($('#currentThumbnail').html());
			    var maxSlide = parseInt($('#maxThumbnail').html());
			    
			    if(curSlide >= ((maxSlide-thumbnailsInView)+1)){
			     	$('#currentThumbnail').html(1);
			  		$('#categorySlideshowThumbnailTrack').animate({ 
			    	marginLeft: "0px"
			    	}, 1500 );
			    	
			    }else{
			    	var distance = (thumbnailsInView*thumbnailWidth);
			    	$('#currentThumbnail').html((curSlide+thumbnailsInView));
			  		$('#categorySlideshowThumbnailTrack').animate({ 
			    	marginLeft: "-="+distance+"px"
			    	}, 1500 );
					}
    		}
    		
    });
}


function init_manage()
{
/*	$('#addRow').click(function(){
		$('table#manage').addTableRow();
		tableInit();
		return false;
	});
	$('.removeRow').click(function(){
		$('table#manage').removeTableRow();
		//$('table#manage').removeTableRow($('table#manage tbody tr').index($(this).parent()));
		tableInit();
		return false;
	});
	
	$('#addCol').click(function(){
		$('table#manage').addTableCol();
		tableInit();
		return false;
	});
	$('.removeColumn').click(function(){
		//alert($('table#manage thead tr th').index($(this).parent()));
		//alert($.dump(this));
		$('table#manage').removeTableCol($('table#manage thead tr th').index($(this).parent()));
		tableInit();
		return false;
	});*/
	
	$('#saveChanges').click(function(){
		saveChanges();
		return false;
	});
	
	$("#dimSketchLink").toggle(
			function(){
				$("#dim-and-sketches-wrapper").show('slow');
				return false;
				},
			function(){
				$("#dim-and-sketches-wrapper").hide();
				return false;
				}
	);
	
	var t = $('table#manage');
	//$.uiTableEdit( t,{find:'tbody > tr > td, thead > tr > th'} ); // returns t
	//$('tbody > tr > td, thead > tr > th',t).editable('/products/keepAlive');
	//$('.edit',t).editable('/products/keepAlive');
	
	tableInit();
	
	//$('tr,th,tbody,thead').bind('change',function(){
	//	tableInit();
	//})
	
}






function lhmUpdateOrder(list)
{
	//$.post(urlPrefix+'lhm_update_order',$(list).serialize(),function(){
	$.post(urlPrefix+'lhm_update_order',$(list).sortable("serialize"),function(){
		$("#dump").append($(this).dump());
	});
}

function set_product_id(id)
{
	$('#ProductId').val(id);
	$('#attributeForm').submit();
}

function show_image(image_id)
{
	$('div.image').hide();
	$(image_id).show();
	return false;
}

function view_attribute_values()
{
	$("#viewattributevalue").fancybox({
		'width'				: '90%',
		'height'			: '90%',
        'autoScale'     	: false,
        'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe'
	});

}

function show_ad_image()
{
	$(".ad_image").fancybox();
}

function manage_home_pages_init()
{
	//var height = $(window).height() - $("#admin-header").height();
	$("#maincontent-admin").height($(window).height() - $("#admin-header").height());
	$(window).resize(function() {
		$("#maincontent-admin").height($(window).height() - $("#admin-header").height());
		
	});
	
	
		$("#products2x2 img, #products3x3 img, #mainproductoffer img").click(function(){
			$(this).remove();
		});
		
		$("#products2x2, #products3x3, #mainproductoffer").droppable({ 
		drop: function(event,ui) { //alert($.dump(ui));
			$(this).append($(ui.draggable).clone());
			//remove existing click events then re-add
			$('img',this).unbind('click')
			$('img',this).click(function(){
				$(this).remove();
			});
		},
		activeClass: 'dropableactive',
		hoverClass: 'dropablehover',
		accept: '#product-links img'
	});
}

function manage_home_page_tree(treeid)
{
	$.getJSON("/admin/manage_home_page_treebrowser/"+treeid,function(data){
		var links = new Array;
		var products = new Array;
		$("#breadcrumbs, #product-links, #tree-links ul").empty();
		$(data.breadcrumbs).each(function(index,value){
			$("#breadcrumbs").append('<a onclick="manage_home_page_tree(' + value.Tree.id + ');return false;" href="#">'+ value.Tree.name +'</a> ')
		});
		
		$(data.children).each(function(index,value){
			if(value.Tree.type=='product')
			{
				products.push(value);
			}
			else
			{
				links.push(value);
			}
		});

		$(products).each(function(index,value){
			//alert($.dump(value));
			//$("#product-links").append('<a onclick="manage_home_page_tree(' + value.Tree.id + ');return false;" href="#">'+ value.Tree.name +'</a><br> ')
			
			$("#product-links").append('<img treeid="' + value.Tree.id + '" src="/img/catalog/T' + value.Product.LargeImage + '.jpg">'+ value.Tree.name +'<br> ');
			
		});
		$(links).each(function(index,value){
			$("#tree-links ul").append('<li><a onclick="manage_home_page_tree(' + value.Tree.id + ');return false;" href="#">'+ value.Tree.name +'</a></li>')
		});
		
		$("#product-links img").draggable({ helper: 'clone' });

		
	});
}
function manage_home_pages_submit()
{
	var temp = '';

	var mainOffer = $('#mainproductoffer img');
	$(mainOffer).each(function(){
		temp = temp + $(this).attr('treeid') + '#';
	})
	$('#MainContentMainofferid').val(temp);
	//$('#MainContentMainofferid').val($('#mainproductoffer img:first').attr('treeid'));
	
	var products2x2 = $('#products2x2 img');
	$(products2x2).each(function(){
		temp = temp + $(this).attr('treeid') + '#';
	})
	$('#MainContentIds2x2').val(temp);
	
	temp = '';
	var products3x3 = $('#products3x3 img');
	$(products3x3).each(function(){
		temp = temp + $(this).attr('treeid') + '#';
	})
	$('#MainContentIds3x3').val(temp);
	
	$("form:first").submit();


}

function resetpassword()
{
	$.post('/admin/resetpassword',$('form').serialize(),function(data){
		alert(data);
	});
}

function swapLargeImage(sourceClick){
		var smallImageClicked = sourceClick.find('img').attr('src');
		var imgPathParts = smallImageClicked.split("/");
		var largeImage = imgPathParts[3].substr(1,200);
		$('#swatchOverlay').find('img').attr('src','/img/catalog/'+largeImage);
}

function resetTabs(){
	var headroom = 3;
	var topTierWidth = parseInt($('.top-tab > ul').innerWidth());
	var botTierWidth = parseInt($('.bottom-tab > ul').innerWidth());
	
	$('.top-tab').css('width',(topTierWidth+headroom)+'px');
	$('.bottom-tab').css('width',(botTierWidth+headroom)+'px');
	
	/*alert('top tab width is '+topTierWidth+' and bot tab is '+botTierWidth);*/
}

function getResults(){
		
		if($("#typing").html()==0){
			$("#typing").html(1);
		 	$('#searchTermDisplay').show();
			$('#searchTermDisplay').html('Searching for: \''+$('#product-keyword').val()+'\'');
			
			if ($('#onlyActive').attr('checked')){
				var activeState = -1;
			}else{
				var activeState = 0;
			}
			
			
			if($('#product-keyword').val().length>2){
				$.post("/admin/get_product_results_by_keyword", {
        	keyword: $('#product-keyword').val(),
        	onlyActive: activeState
      	}, function(response){
      		$('#productResultSet').html(response);
      		$("#typing").html(0);
      	});
     	}else{
    		$('#searchTermDisplay').html('Searching for: \''+$('#product-keyword').val()+'\' Please enter more than 2 characters to begin.');
    		$("#typing").html(0);
     	}
  	}
}

function getCategoryResults(){
		
		if($("#cat_typing").html()==0){
			$("#cat_typing").html(1);
		 	
			if($('#category-keyword').val().length>2){
				$('#ajax-loader').show();
				$.post("/admin/get_ajax_categories", {
				keyword: $('#category-keyword').val(),
				onlyActive: $('#onlyActive').val()
			}, function(response){
				$('#categoryResults').html(response);
				$("#cat_typing").html(0);
				$('#ajax-loader').hide();
			});
     	}else{
    		$("#cat_typing").html(0);
     	}
  	}
}

function getCategoryDropdownResults(){
		
		if($("#cat_drop_typing").html()==0){
			$("#cat_drop_typing").html(1);
		 	
			if($('#pathFinder').val().length>2){
				$('#ajax-loader').show();
				$.post("/admin/get_ajax_drop_categories", {
				keyword: $('#pathFinder').val(),
				current_parent: $('#current_parent').val()
			}, function(response){
				$('#parent_id').html(response);
				$("#cat_drop_typing").html(0);
				$('#ajax-loader').hide();
			});
     	}else{
    		$("#cat_drop_typing").html(0);
     	}
  	}
}

function typing(){
	var t=setTimeout('getResults();',2000);
}

function cat_typing(){ 
	var t=setTimeout('getCategoryResults();',2000);
}

function cat_drop_typing(){
	var t=setTimeout('getCategoryDropdownResults();',2000);
}

$(document).ready(function(){
	resetTabs();
	
	$('#product-keyword').live('keyup',function(){
		 typing();
	});
	
	$('#category-keyword').live('keyup',function(){
		cat_typing();
	});
	
	$('#pathFinder').live('keyup',function(){
		cat_drop_typing();
	});
	
	$('#treeTop').change(function(){
		var str = "";
    $("#treeTop option:selected").each(function () {
    	typeParts = $(this).val().split('-');
    	str += typeParts[1] + " ";
    });
    
    $.post("/admin/get_siblings", {
        matches: str
      }, function(response){
      	//var returnedOptions = $(".ajax-response", response).html();
      	$('#treeChild').html(response);
      });
  });
  
  $('#treeProduct').change(function(){
  	var str = "";
    $("#treeProduct option:selected").each(function () {
    	typeParts = $(this).val().split('-');
    	str += typeParts[1] + " ";
    });
    
    $.post("/admin/get_siblings", {
        matches: str
      }, function(response){
      	//var returnedOptions = $(".ajax-response", response).html();
      	if($.trim(response)!=''){
      		$('#treeProduct').html(response);
      	}
      });
  });
  
  $('#UserLOGONID').blur(function(){
	var container = $(this).parent().parent().attr('id');
	
	if(container == 'registrationForm'){
	$.post("/trees/check_username", {
        email: $(this).val()
      }, function(response){
		$('#usernameExistsError').remove();
      	if(response==1){
			$('#UserLOGONID').parent().before('<div class="input text" id="usernameExistsError"><label class="error">Sorry, this email address already exists. Click <a href="/users/login/">here</a> to log-in.</label></div>'); 
		}else{
			$('#usernameExistsError').remove();
		}
      });
	 }
  });
  
  $('#treeChild').change(function(){
		var str = "";
    $("#treeChild option:selected").each(function () {
    	typeParts = $(this).val().split('-');
    	str += typeParts[1] + " ";
    	returnType = typeParts[0];
    });
    
    var nodeStr = "";
    $("#treeChild option:selected").each(function () {
    	typeParts2 = $(this).val().split('-');
    	nodeStr += typeParts2[1] + " ";
    });
    
    $.post("/admin/get_product_results", {
        products: str
      }, function(response){
      	//var returnedProductOptions = $(".ajax-response", response).html();
      	/*
      	var typeValue = $(".first-option", response).val().split('-');
      	if(typeValue[0]=='prod'){
      	*/
      		$('#treeProduct').html(response);
      	/*
      	
      	}else{
      		alert('gettin ere');
      		$('#treeChild').html(response);
      	}
      	*/
      	
      });
      
     /*
     $.post("/admin/get_siblings", {
        matches: nodeStr
      }, function(response){
      	var returnedOptions = $(".ajax-response", response).html();
      	$('#treeChild').html(returnedOptions);
      });
      */
  });
  
  $("#order_select").change(function(){
 	 $("#filterForm").submit();
 	 return false;
  });
  $("#view_all").click(function(){
  		$("#datalimit").val($(this).attr("data-limit"));
 	 	$("#filterForm").submit();
 	 	return false;
  });
  
  
  
  $('.add-this-category').live('click',function(){
	
	var catPathCell = $(this).parent().prev('td');
	var catPath = catPathCell.html();
	var product_name = $('#name').val();
	var suggested_url_name = $('#suggested_url_name').val();
	var nameCell = catPathCell.prev('td');
	var parentName = nameCell.html();
	var catIdCell = nameCell.prev('td');
	var parentId = catIdCell.html();
	var suggestedPath = catPath+'/'+suggested_url_name;
	
	$.post("/admin/create_ajax_category", {
        parentId: parentId,
		productName: $('#name').val(),
		productId: $('#productId').val(),
		parentName: parentName,
		catPath: catPath,
		largeImg: $('#largeImage').val(),
		newPath: suggestedPath
      }, function(response){
		$('.category-table').append(response);
      });
	  
	return false;
  });
  
  $('#address-not-listed').live('click',function(){
  	$('#addressPicker').hide();
  	return false;
  });
  
  $('#chooseSelectedItems').live('click',function(){
  	var selectedProductsStr = "";
  	$("#treeProduct option:selected").each(function () {
    	typeParts = $(this).val().split('-');
    	selectedProductsStr += '<option value="'+typeParts[1] +'" id="selectedItem-'+typeParts[1]+'">'+$(this).text()+ "</option>\n";
    });
    $('#selectedProduct').append(selectedProductsStr);
    
  });
  
  $('#deleteSelectedItems').live('click',function(){
  		$("#selectedProduct option:selected").each(function () {
    		$(this).remove();
    	});
  
  });
  
  $('#saveSelectedItems').live('click',function(){
  	$('.ajax-loader').show();
  	var selectedProductsStr = '';
  	
  	$("#selectedProduct option").each(function () {
    	typeParts = $(this).val().split('-');
    	selectedProductsStr += $(this).val()+' ';
    });
    
    currentAdditionalInfoItem = $('#currentAdditionalInfoItem').val();
    
    $.post("/admin/save_additional_info_results", {
    		infoItem: currentAdditionalInfoItem,
      	products: selectedProductsStr
   		}, function(response){
    		$('.ajax-loader').hide();
   	});
      
  });
  
  $('.processFile').live('click',function(){
	$('#ajax-loader').show();
	$('.processFile').html('');
	
	var postTo = $(this).attr('data-post-to');	
	var csvFile = $(this).attr('id');
	console.log(postTo);
	$.post("/admin/"+postTo, {
    	csv: csvFile
	}, function(response){
    	$('#ajax-loader').hide();
		$('.processFile').html('completed');
		$('#processedFileData').html(response);
   	});
  });
  
  $('.show-guide').live('click',function(){
  	$('.guide').show();
  	$(this).removeClass('show-guide').addClass('hide-guide');
  	$(this).html('hide guide');
  });
  
  $('.hide-guide').live('click',function(){
  	$('.guide').hide();
  	$(this).removeClass('hide-guide').addClass('show-guide');
  	$(this).html('show guide');
  });
  
  $('.copyToAll').live('click',function(){
  	var idParts = $(this).attr('id').split('-');
  	$('.positionStore').val($('#position-'+idParts[1]).val());
  	$(".columnStore").val($('#column-'+idParts[1]).val());
  });
  
	$('.playSlideShow').live('click',function(){
	 startSlideShow();
	 $('.tab-active').removeClass('tab-active');
	 $('#show-slideshow').addClass('tab-active');
	 $('#slide-info-box').hide();
	 $('.playSlideShow').html('Pause');
	 $('.playSlideShow').removeClass('playSlideShow').addClass('pauseSlideShow');
	});
	
	$('.pauseSlideShow').live('click',function(){
		$('#slide-info-box').hide();
		$('.pauseSlideShow').html('Play');
		$('.pauseSlideShow').removeClass('pauseSlideShow').addClass('playSlideShow');
		stopSlideShow();
	});
	
	$('#swatchOverlayClose, #fullScreenOverlay').live('click',function(){
		$('#swatchOverlay').hide();
		$('#fullScreenOverlay').hide();
	});
  
  $('#colour_swatches > a > img').mouseenter(function(){
			
    	if($(this).parent().attr('class')!='active'){
		/*
    		$this.css('border','1px solid green !important');
      	
    		$(this).css('width','33px');
    		$(this).css('height','26px');
    		$(this).css('border','none');
    		$(this).css('margin','0px 1px 0px 0px');
    		$(this).css('background-color','#FFFFFF');
        $this.parent().css('border','none');
    		$this.parent().css('background-color','#FFFFFF');
    		$this.parent().css('text-decoration','none');
    		*/
      }
  });
  
  $('#colour_swatches > a > img').mouseleave(function(){
  	if($(this).parent().attr('class')!='active'){
    	/*
    	$(this).css('width','31px');
    	$(this).css('height','25px');
    	$(this).css('border','none');
    	$(this).css('margin','0px 2px 0px 1px');
    	*/
    }
    
  });
  
  $('#colour_swatches > a > img').click(function(){
			
    	if($(this).parent().attr('class')!='active'){
      	$(this).addClass('selected');
        $(this).css('width','31px');
    		$(this).css('height','25px');
        $(this).css('margin','0px 2px 0px 1px');
      
      	/*
        $(this).css('width','33px');
    		$(this).css('height','26px');
    		$(this).css('border','none');
    		$(this).css('margin','0px 1px 0px 0px');
    		$(this).css('background-color','#FFFFFF');
    		$this.parent().css('border','none');
    		$this.parent().css('background-color','#FFFFFF');
    		$this.parent().css('text-decoration','none');
    		*/
      }
  });
	
	$('#large_colour_swatch').live('click',function(){
		var imageClicked = $(this).find('img').attr('src');
		var imgPathParts = imageClicked.split("/");
		var largeImage = imgPathParts[3].substr(1,200);
		$('#swatchOverlay').find('img').attr('src','/img/catalog/'+largeImage);
		var documentHeight = $(document).height();
		var reposition = (($(window).scrollTop()) - 5);
		$('#swatchOverlay').css('margin-top', reposition + 'px');

		$('#fullScreenOverlay').css('height',documentHeight);
		$('#swatchOverlay').show();
		$('#fullScreenOverlay').show();
	});
	
	$('#large_colour_swatch').mouseenter(function(){
		$('#swatchZoom').show();
	});
	
	$('#large_colour_swatch').mouseleave(function(){
		$('#swatchZoom').hide();
	});
	
	$('#arrowMainLeft').click(function() {
		stopSlideShow();
		$('#slide-info-box').hide();
  	$('.slidePrice').hide();
  	var curSlide = parseInt($('#currentSlide').html());
    var maxSlide = parseInt($('#maxSlide').html());
    
    if(curSlide==(2)){
      $('#arrowMainLeft').hide();
    }
    $('#arrowMainRight').show();
    
    var newLink = $('#link-'+(curSlide-1)).html();
  	$('#slide-link').attr('href',newLink);
  	$('#path-'+(curSlide-1)).html('<img src=\''+$('#imgsrc-'+(curSlide-1)).html()+'\'>');
  	
    $('#currentSlide').html((curSlide-1));
  	$('#slideDigits').html($('#currentSlide').html()+' of '+$('#maxSlide').html());
  	$('#categorySlideshowTrack').animate({ 
    	marginLeft: "+=559px"
    	}, 0 , function(){
    		$('.slidePrice').show();
    });
	});
    
  $('#arrowMainRight').click(function() {
  	stopSlideShow();
  	$('#slide-info-box').hide();
  	$('.slidePrice').hide();
  	var curSlide = parseInt($('#currentSlide').html());
    var maxSlide = parseInt($('#maxSlide').html());
    var imgPath = $('#imgsrc-'+curSlide).html();
    
    $('#slide-'+curSlide).html('<a href="'+$('#linksrc-'+(curSlide)).html()+'"><img src="'+imgPath+'"></a>');
    
    if(curSlide==(maxSlide-1)){
      $('#arrowMainRight').hide();
    }
    $('#arrowMainLeft').show();
    
    var newLink = $('#link-'+(curSlide+1)).html();
  	$('#slide-link').attr('href',newLink);
  	$('#path-'+(curSlide+1)).html('<img src=\''+$('#imgsrc-'+(curSlide+1)).html()+'\'>');
  	
    $('#currentSlide').html((curSlide+1));
  	$('#slideDigits').html($('#currentSlide').html()+' of '+$('#maxSlide').html());
  	$('#categorySlideshowTrack').animate({ 
    	marginLeft: "-=559px"
    	}, 0 , function(){
    		$('.slidePrice').show();
    		
    });
			
	});
	
	$('.slideThumbnail').live('click',function(){
		stopSlideShow();
		var maxSlide = parseInt($('#maxThumbnail').html());
		
		$('#slide-info-box').hide();
		$('.slideshow-tab').removeClass('tab-active');
		$('#show-slideshow').addClass('tab-active');
		
		$('.slidePrice').fadeOut(100);
		$('.slideThumbnailOn').removeClass('slideThumbnailOn');
		$(this).addClass('slideThumbnailOn');
		
		var idParts = $(this).attr('id').split('-');
		
		if(idParts[2]==1){
			$('#arrowMainRight').show();
			$('#arrowMainLeft').hide();
		}else{
			$('#arrowMainLeft').show();
		}
		
		if(idParts[2] == maxSlide){
			$('#arrowMainRight').hide();
		}else{
			$('#arrowMainRight').show();
		}
		
    $('#currentSlide').html(idParts[2]);
    $('#slideDigits').html(idParts[2]+' of '+$('#maxSlide').html());
  	
  	var curSlide = parseInt($('#currentSlide').html());
  	
  	var newLink = $('#link-'+idParts[2]).html();
  	$('#slide-link').attr('href',newLink);
  	$('#path-'+(curSlide)).html('<img src=\''+$('#imgsrc-'+(curSlide)).html()+'\'>');
  	
  	var position = -1*((idParts[2]-1)*559);
  	$('#categorySlideshowTrack').animate({ 
    	marginLeft: position+"px"
    	}, 0 , function(){
    		$('.slidePrice').fadeIn(500);
    });
    	
	});
	
	$('#leftArrow').click(function() {
  	
  	var thumbnailsInView = 5;
  	var thumbnailWidth = 93;
  	var curSlide = parseInt($('#currentThumbnail').html());
    var maxSlide = parseInt($('#maxThumbnail').html());
    
    if(curSlide==(2)){
      /*$('#leftArrow').hide();*/
    }
    $('#rightArrow').show();
    
  	if(curSlide == 1){
  		$('#currentThumbnail').html(maxSlide); 
  		var newLocation = ((parseInt($('#maxThumbnail').html())*thumbnailWidth)-((thumbnailsInView*thumbnailWidth)));
  		var moduloValue = thumbnailsInView - (parseInt($('#maxThumbnail').html())%thumbnailsInView);
  		if(moduloValue!=0){
  			newLocation = (newLocation+(moduloValue*thumbnailWidth));
  		}
  		$('#categorySlideshowThumbnailTrack').animate({ 
    	marginLeft: "-"+newLocation+"px"
    	}, 1500 );
    	$('#currentThumbnail').html(maxSlide-(parseInt($('#maxThumbnail').html())%thumbnailsInView)+1);
  	}else{
  		var distance = (thumbnailsInView*thumbnailWidth);
  		$('#currentThumbnail').html((curSlide-thumbnailsInView));
  		$('#categorySlideshowThumbnailTrack').animate({ 
    	marginLeft: "+="+distance+"px"
    	}, 1500 );
  	}
	});
    
  $('#rightArrow').click(function() {
  	
		var thumbnailsInView = 5;
  	var thumbnailWidth = 93;
  	
  	var curSlide = parseInt($('#currentThumbnail').html());
    var maxSlide = parseInt($('#maxThumbnail').html());
    
    if(curSlide >= ((maxSlide-thumbnailsInView)+1)){
     	$('#currentThumbnail').html(1);
  		$('#categorySlideshowThumbnailTrack').animate({ 
    	marginLeft: "0px"
    	}, 1500 );
    	
    }else{
    	var distance = (thumbnailsInView*thumbnailWidth);
    	$('#currentThumbnail').html((curSlide+thumbnailsInView));
  		$('#categorySlideshowThumbnailTrack').animate({ 
    	marginLeft: "-="+distance+"px"
    	}, 1500 );
		}
	});
	
	$('#show-slideshow').live('click',function(){
		$('#slide-info-box').hide();
		$('.slideshow-tab').removeClass('tab-active');
		$(this).addClass('tab-active');
	});
	
	$('#show-info').live('click',function(){
		stopSlideShow();
		$('#slide-info-box').show();
		$('.slideshow-tab').removeClass('tab-active');
		$(this).addClass('tab-active');
	});
	
	$('#zoomSlide').live('click',function(){
		$('#swatchOverlay').find('img').attr('src','');
		var largeImage = $(this).next('.large-zoom-image').html();
		$('#swatchOverlay').find('img').attr('src','/img/catalog/'+largeImage+'.jpg');
		var documentHeight = $(document).height();
		var reposition = (($(window).scrollTop()) - 5);
		$('#swatchOverlay').css('margin-top', reposition + 'px');

		$('#fullScreenOverlay').css('height',documentHeight);
		$('#swatchOverlay').show();
		$('#fullScreenOverlay').show();
	});
	
	$('#showInfoPane').live('click',function(){
		$('#infoPane').fadeIn(200);
		$('#dataPane').hide();
		$('.infoTabOn').removeClass('infoTabOn').addClass('infoTabOff');
		$(this).removeClass('infoTabOff').addClass('infoTabOn');
	});
	
	$('#showDataPane').live('click',function(){
		$('#dataPane').fadeIn(200);
		$('#infoPane').hide();
		$('.infoTabOn').removeClass('infoTabOn').addClass('infoTabOff');
		$(this).removeClass('infoTabOff').addClass('infoTabOn');
	});
	
	$('#getAlsoInRange').live('click',function(){
		$('#upSellTrack').html($('#hidden-also-in-range-items').html());
		$('#upSellTrack').css('margin-left','0px');
		$('#upSellCurrentSlide').html(1);
		$('#upSellMaxSlide').html($("#hidden-also-in-range-items > div").length);
	});
	
	$('#getRelatedUpSell').live('click',function(){
		$('#upSellTrack').html($('#hidden-related-items').html());
		$('#upSellTrack').css('margin-left','0px');
		$('#upSellCurrentSlide').html(1);
		$('#upSellMaxSlide').html($("#hidden-related-items > div").length);
	});
	
	$('#getRecentlyViewed').live('click',function(){
		$('#upSellTrack').html($('#hidden-recently-viewed-items').html());
		$('#upSellTrack').css('margin-left','0px');
		$('#upSellCurrentSlide').html(1);
		$('#upSellMaxSlide').html($("#hidden-recently-viewed-items > div").length);
	});
	
	/* upsell related slideshow code */
	$('#upSellLeft').click(function() {
		
		var thumbnailsInView = 4;
  	var thumbnailWidth = 161;
  	var curSlide = parseInt($('#upSellCurrentSlide').html());
    var maxSlide = parseInt($('#upSellMaxSlide').html());
    
    if(curSlide==(2)){
      /*$('#leftArrow').hide();*/
    }
    $('#upSellLeft').show();
    
    
  	if(curSlide == 1){
  		$('#upSellCurrentSlide').html(maxSlide);
  		var newLocation = ((parseInt($('#upSellMaxSlide').html())*thumbnailWidth)-((thumbnailsInView*thumbnailWidth)));
  		var moduloValue = thumbnailsInView - (parseInt($('#upSellMaxSlide').html())%thumbnailsInView);
  		if(moduloValue!=0){
  			newLocation = (newLocation+(moduloValue*thumbnailWidth));
  		}
  		$('#upSellTrack').animate({ 
    	marginLeft: "-"+newLocation+"px"
    	}, 0 );
    	$('#upSellCurrentSlide').html(maxSlide-(parseInt($('#upSellMaxSlide').html())%thumbnailsInView)+1);
  	}else{
  		var distance = (thumbnailsInView*thumbnailWidth);
  		$('#upSellCurrentSlide').html((curSlide-thumbnailsInView));
  		$('#upSellTrack').animate({ 
    	marginLeft: "+="+distance+"px"
    	}, 0 );
  	}
	});
    
  $('#upSellRight').click(function() {
  	
  	var thumbnailsInView = 4;
  	var thumbnailWidth = 161;
  	
  	var curSlide = parseInt($('#upSellCurrentSlide').html());
    var maxSlide = parseInt($('#upSellMaxSlide').html());
    
    if(curSlide >= ((maxSlide-thumbnailsInView)+1)){
     	$('#upSellCurrentSlide').html(1);
  		$('#upSellTrack').animate({ 
    	marginLeft: "0px"
    	}, 0 );
    	
    }else{
    	var distance = (thumbnailsInView*thumbnailWidth);
    	$('#upSellCurrentSlide').html((curSlide+thumbnailsInView));
  		$('#upSellTrack').animate({ 
    	marginLeft: "-="+distance+"px"
    	}, 0 );
		}
			
	});
	
	$('.upSellTabOff').click(function() {
		$('.upSellTabOn').removeClass('upSellTabOn').addClass('upSellTabOff');
		$(this).removeClass('upSellTabOff').addClass('upSellTabOn');
	});
	
	$('.upSellTabOn').click(function() {
		$('.upSellTabOn').removeClass('upSellTabOn').addClass('upSellTabOff');
		$(this).removeClass('upSellTabOff').addClass('upSellTabOn');
	});
	
	$('#close-window').live('click',function(){
		$('.child-products').hide();
	});
	
	$('#show-window').live('click',function(){
		$('.child-products').show(); 
	});
	
	$('#remove-selected').live('click',function(){
		
		var selectedProductsStr = "";
  	var selectedProductsTextStr = "";
  	$("#child-product-selector option:selected").each(function () {
    	typeParts = $(this).val();
    	selectedProductsStr += typeParts+'|';
    	selectedProductsTextStr += $(this).text()+'<br />';
    	$('#option-'+typeParts).remove();
    });
    
    $('#confirm-list').html(selectedProductsTextStr);
    $('#remove-selected').hide();
    $('#confirm-delete').show();
    
		return false;
	});
	
	$('#confirm-selected').live('click',function(){
		var selectedProductsStr = "";
  	$("#child-product-selector option:selected").each(function () {
    	typeParts = $(this).val();
    	selectedProductsStr += typeParts+'|';

    });
    
    //$.post("/admin/delete_additional_info_results", {
    $.post("/admin/delete_products_from_category", {
    		items: selectedProductsStr
      }, function(response){
    		$('.ajax-loader').hide();
    		$('#remove-selected').show();
    		$('#confirm-delete').hide();
    		$('.child-products').fadeOut(500);
   	});
		
		return false;
    
	});
	/*
	$('.info-link-off').mouseenter(function(){
		$(this).removeClass('info-link-off').addClass('info-link-on');
	});
	
	$('.info-link').mouseout(function(){
		$(this).removeClass('info-link-on').addClass('info-link-off');
	});
	*/
	
	$('.product-item, .product-item-wide').mouseenter(function(){
		infoLink = $(this).find('.info-link'); 
		infoLink.removeClass('info-link-off').addClass('info-link-on');
	});
	
	$('.product-item, .product-item-wide').mouseleave(function(){
		infoLink = $(this).find('.info-link');
		infoLink.removeClass('info-link-on').addClass('info-link-off');
	});
	
	$('.dealOfTheWeek').mouseenter(function(){
		infoLink = $(this).find('.info-link-wide'); 
		infoLink.removeClass('info-link-wide-off').addClass('info-link-wide-on');
	});
	
	$('.dealOfTheWeek').mouseleave(function(){
		infoLink = $(this).find('.info-link-wide');
		infoLink.removeClass('info-link-wide-on').addClass('info-link-wide-off');
	});
	
	$('.delete-item').live('click',function(){
		var ItemToRemove = $(this).attr('id').split('-');
		var tableRow = $(this).parent();
		
		$.post("/admin/delete_item", {
    		item: ItemToRemove[1]
		}, function(response){
			tableRow.remove();
		});
		
		return false;
	});
	
	$('.activeField').live('focus',function(){
		
		$('#lastFocused').val($(this).attr('id'));
		$('.helper-panel').show();
		$('.helper-panel-top').html('<div style="width:470px;height: 200px;float:left;text-align:center;"><div class="loader">&nbsp;</div></div>');
		var idParts = $(this).attr('id').split('-');
		$.post("/admin/get_ajax_attribute_values", {
    		attribute: idParts[2]
		}, function(response){
			$('.helper-panel-top').html(response);
		});
   	
	});
	
	$('.helper-panel-top > ul > li').live('click',function(){
		var idParts = $(this).attr('id').split('-');
		var cosmeticName = $(this).find('span').html();
		var lastClicked = $('#lastFocused').val();
		$('#'+lastClicked).val(cosmeticName);
		$('#'+lastClicked).attr('data',idParts[1]);
		$('#real'+lastClicked).val(idParts[1]);
		$('.helper-panel').hide();
		$('.helper-panel-top').html('');
	});
	
	$('#add-attribute-value').live('click',function(){
		$.post("/admin/set_ajax_attribute_value", {
    		attributeData: $('#add-attribute').val(),
			attributeValue: $('#new-attribute-value').val(),
			attributePairImage: $('#attribute-pair-image-large').val(), 
			attribute: $('#lastFocused').val()
		}, function(response){
			$('.helper-panel-top > ul').prepend(response);
			$('#new-attribute-value').val('');
			$('#attribute-pair-image-large').val('');
			$('#smallAttributeImagePlaceholder').html('');
		});
	});
	
	$('#close-attribute-values').live('click',function(){
		$('.helper-panel').hide();
	});
	
	$('.closedSection').live('click',function(){
		var section = $(this).parent().next('.section');
		section.slideDown(0);
		$(this).removeClass('closedSection').addClass('openSection');
		$(this).html('-');
	});
	
	$('.openSection').live('click',function(){
		var section = $(this).parent().next('.section');
		section.slideUp(0);
		$(this).removeClass('openSection').addClass('closedSection');
		$(this).html('+');
	});
	
	$('#findRelatedItem').live('click',function(){
		$.post("/admin/get_ajax_related_item", {
    		keyword: $('#getRelated').val(),
    		masterProduct: $('#productId').val(), 
    		curQty: $('.related-table>tbody>tr').length
		}, function(response){
			if(response!=''){
				$('.related-table').append(response); 
			}else{
				alert('product not found! please enter a valid part number.');
			}
		});
		return false;
	});
	
	$('#menu-mk2-top > ul > li, #menu-mk2-bot > ul > li').mouseenter(function(){
		$(this).find('a').css('color','#FFF');
	});
	
	$('#menu-mk2-top > ul > li, #menu-mk2-bot > ul > li').mouseleave(function(){
		$(this).find('a').css('color','#333');
	});
	
	$('.removeRelated').live('click',function(){ 
		var idParts = $(this).attr('id').split('-');
		var tableRow = $(this).parent().parent();
		$.post("/admin/delete_ajax_related_item", {
    		id: idParts[1]
    }, function(response){
				tableRow.remove();
		});
		return false;
	});
	
	$('.removeFromCategory').live('click',function(){ 
		var idParts = $(this).attr('id').split('-');
		var tableRow = $(this).parent().parent();
		$.post("/admin/delete_product_from_category", {
    		id: idParts[1]
    }, function(response){
				tableRow.remove();
		});
		return false;
	});
	/*
	$('.swatch-click').live('click',function(){
		update_options($(this));
	})
	
	$('.swatchClick').change(function(){
		update_options($(this));
	})
	
	$('.drop-selected').live('change',function(){
		update_options($(this));
	})
	
	$('.dropSelected').change(function(){
		update_options($(this));
	})
	*/
	
	
});

function update_options(obj){
	
	var objId = obj.attr('id');
	
	var idParts = obj.attr('id').split('-');
	var item = idParts[1];
	if(idParts.length == 2){
		var swatchClicked = false;
		var attribute = idParts[1];
	}else{
		var swatchClicked = true;
		var attribute = idParts[2];
	}
	
	var productId = $('#productId').val();
	var currentlySelected = '';
	var currentlySelectedName = obj.attr('alt');
	var swatchSrc = obj.find('img').attr('src');
	
	if(swatchSrc){
		var swatchSrcParts = swatchSrc.split("/");
		var newPath = '/'+swatchSrcParts[1]+'/'+swatchSrcParts[2]+'/i'+swatchSrcParts[3].substr(1,500);
	}
	
	if(obj.hasClass('swatch-click')){
		attribute = idParts[1];
		var attributeValue = idParts[2];
	}else{
		var attributeValue = $("#"+objId).val();
	}
	
	$('.drop-selected').each(function(index) {
		dropParts = $(this).attr('id').split('-');
		currentlySelected += dropParts[1]+'-'+$(this).val()+'|';
	});
	
	$('.swatch-click').each(function(index) {
		swatchParts = $(this).attr('id').split('-');
		if($(this).hasClass('active')){
			if(swatchClicked==true && swatchParts[2]==attribute){
				currentlySelected += idParts[1]+'-'+idParts[2]+'|';
			}else{
				currentlySelected += swatchParts[1]+'-'+swatchParts[2]+'|';
			}
		}
	});
	
	$.post("/trees/get_revised_attributes", {
		
 		objId: objId,
 		item: item,
		productId: productId,
 		attribute: attribute,
 		itemIds: $('#itemIds').val(),
 		attributeValue: attributeValue,
		currentlySelected: currentlySelected
		
 	}, function(response){
		var responseSections = response.split('||||');
 		var responseParts = responseSections[0].split('-');
		
		//if(responseParts==0){
			//alert('Sorry not available');
		//	$('.add-to-bag').hide();
		//}else{
			
			var matchingItemId = responseParts[1];
			var matchingItemOrderCode = responseParts[2];
			
			obj.parent().parent().find('#swatchlabel').html(currentlySelectedName);
			obj.parent().parent().find('.large_colour_swatch>img').attr('src',newPath);
			
			$('#ItemId').val(matchingItemId);
			$('.productNo').html('Product no: '+matchingItemOrderCode);
			if(responseParts[4]!=''){
				$('.rrp').html('RRP &pound;'+responseParts[4]);
			}else{
				$('.rrp').html('');
			}
			$('.saleprice').html('&pound;'+responseParts[3]);
			$('.add-to-bag').show();
		//}
		//alert(responseSections[0]);
		//if(responseSections[0]!='0'){
			$('.innerSelection').html(responseSections[1]);
		//}
	});
	return false;
	
}
