/* customer type colors */
var type_cols = ['864c9e', 'ed2690', 'ff001a', 'f2a216', 'a4ce39', '0d9a48', '339999', '4b68b1', 'f15f22', '7d88bd', 'cb2027', '71c9f1', '2e58a1', 'e34982', 'f6f3ea', 'edf0f7'];

/*
* preloads an image (from amazon in this case), and
* calls a callback function with the image src, size
* that we're gonna resize it to, and a jquery reference to it
*/
{
	ImagePreloader = function(images, callback, size, ref){
		this.size = size;
		this.ref = ref;
		this.callback = callback;
	   	this.nLoaded = 0;
	   	this.nProcessed = 0;
	   	this.aImages = new Array;
	   	this.nImages = images.length;
	   	for ( var i = 0; i < images.length; i++ ){
	    	this.preload(images[i]);
	    }
	}
	
	ImagePreloader.prototype.preload = function(image){
		var oImage = new Image;
	   	this.aImages.push(oImage);
	   	oImage.onload = ImagePreloader.prototype.onload;
	   	oImage.onerror = ImagePreloader.prototype.onerror;
	   	oImage.onabort = ImagePreloader.prototype.onabort;
	   	oImage.oImagePreloader = this;
	   	oImage.bLoaded = false;
	   	oImage.src = image;
	} 
	
	ImagePreloader.prototype.onComplete = function(){
		this.nProcessed++;
	   	if ( this.nProcessed == this.nImages ){
	    	this.callback([this.aImages[0].src, this.aImages[0].width, this.aImages[0].height, this.size, this.ref]);
	   	}
	}
	
	ImagePreloader.prototype.onload = function(){
		this.bLoaded = true;
	   	this.oImagePreloader.nLoaded++;
	   	this.oImagePreloader.onComplete();
	}
	
	ImagePreloader.prototype.onerror = function(){
		this.bError = true;
	   	this.oImagePreloader.onComplete();
	}
	
	ImagePreloader.prototype.onabort = function(){
	   this.bAbort = true;
	   this.oImagePreloader.onComplete();
	}
}

/*
* App-specific functions
*/
var Imagini = {
	
	amz_selected_categ: '',
	tmp: 0,
	
	/*
	* Init stuff that needs to happen
	*/
	init: function ()
	{
		/*
		* stop image flicker on backgrounds in ie6
		*/
		if(jQuery.browser.msie && parseInt(jQuery.browser.version, 10) == 6) {
  			try {
    			document.execCommand("BackgroundImageCache", false, true);
  			} catch(err) {}
		}
		
		/*
		* we can't use css for the wizard-nav :hover effect in IE, so...
		*/
		{
			if($.browser.msie){
				$.each($("#shop-nav li"), function(){
					$(this).hover(function(){
						$(this).toggleClass("over");
					}, function(){
						$(this).toggleClass("over");
					})
					.find("em").css("top","4px");
				});
			}
		};
		
		/*
		* image pop on the analytics page
		*/
		{
			$('#show-trigger a').bind('click', function(){
				$('#show-panel').slideToggle('fast');
				$(this).toggleClass('up');
				($(this).hasClass('up'))? $(this).html('hide'):$(this).html('show all');
			});
		};
		
		/* 
		* analytics page - similar sites
		*/
		{
			$('#white-bg-short p.similar-sites').bind('click', function(){
				if($('#similar-sites textarea:visible').length>0){
					$('#similar-sites textarea').fadeOut('slow');
				}else{
					$('#similar-sites textarea').fadeIn('slow');
				}
			});
		};
		
		/*
		* customise shop stuff 
		*/
		{
			// background colour
			$.each($('#color-selection li').children().find('div'), function(){
				$(this).bind('click',function(){
					var color = $(this).attr('class').split('_');
					color = color[1];
					var fakecolor = color;
					if(fakecolor=='000000'){
						fakecolor = '000001';
					}
					$('#color-value').val(fakecolor);
					$('#user-color-value').val('#'+color);
					
					$(this).parents('ul').children('li').removeClass('selected');
					$(this).parents('li').addClass('selected');
					
					$('#save-change-color').fadeIn('slow');
				});
			});			
		};
		
		// login forms
		{
			// change it to submit only when keydown on the password field
			$("#password").bind("keydown", function(e) {
				if (e.keyCode == 13) {
					if ($("#header-login form"))
						$("#header-login form").submit();

					if ($("#register-form form"))
						$("#register-form form").submit();
					return false;
				}
			});
			
			// lose the background images
			$('#header-login form input').bind('click, focus', function(){
				$(this).css('background-image', 'none');
			});
			if($('#header-login')){
				$.each($('#header-login form input'), function(){
					if($(this).val()!=''){
						$(this).css('background-image', 'none');
					}
				});
			};

		};
		
		/*
		* add the 'add product' and 'remove product' actions on product page
		*/
		{
			$.each($("#amazon-results div.amazon-item"), function(){
				$(this).click(function(){
					var temp 	= $(this).attr("id").split("_");
					var asin 	= temp[1];
					if(!$(this).hasClass("selected")){
						Imagini.addProduct(asin, $(this), 'div')
					}else{
						var temp 	= $(this).children("div.white-product-box").attr('id').split('_');
						var id 		= temp[1];
						Imagini.deleteProduct(id, 'product', $(this))
					}
				});
				$(this).find('div.add a , div.delete a').click(function(){
					window.open($(this).attr("rel"));
					return false;
				});
			});
		};

		/*
		* performance table effects
		*/
		{
			$trs = $('#performanceTable tbody tr, #features tbody tr');
			$trs.bind('mouseover', function(){						
				$(this).addClass('over');
			});
			$trs.bind('mouseout', function(){						
				$(this).removeClass('over');
			});
			$('#performanceTable tbody tr').bind('click', function(){						
				var href = $(this).children().find('h4').children('a').attr('href');
				window.location.href = href;
			});
		};
		
		/*
		* nicely scrolls back to top
		*/
		{
			$('a.back-to-top').click(function() {  
    			$(document).scrollTo(0,500);
    			return false;  
			});
		};
		
		/*
		* calculates anchors on the faq pages, then nicely scrolls
		*/
		{
			$.each($('#terms a.anchor-type'), function(){
				$(this).click(function(){
					var rel = $(this).attr('rel');
					var pos = $('#'+rel).position();
					$(document).scrollTo(pos.top+153,500);
				});
			});
			$.each($("#helpmenu").children().find("li a"), function(){
				$(this).click(function(){
					var $parent = $(this).parents('ul');
					var ref = $parent.attr('rel');
					
					if ($(this).attr("rel") != "")
					{
						var anchor = "#" + $(this).attr("rel");
					}
					else
					{
						var anchor = "#" + ($parent.children('li').index($(this).parent()) + 1);	
					}
					
					var href = '/help/'+ref;
					if(window.location.pathname != href)
					{
						window.location.href = '/help/'+ref+anchor;
					}
					else
					{
						if ($(this).attr("rel") != "")
						{
							var pos = $(".standard-text h3#" + $(this).attr("rel")).position();
						}
						else
						{
							var text = $(this).html();
							var pos = $(".standard-text h3:contains("+text+")").position();
						}
						$(document).scrollTo(pos.top+153,500);
					}
				});
			});
			if ($("#this_page").html() == "help"){
				if(window.location.href.indexOf('#')!=-1){
					var num = window.location.href.split('#');
					num = num[1]-1;
					var pos = $('#content .standard-text').children('h3:nth('+num+')').position()
					$(document).scrollTo(pos.top+153,500);
				}
			}
		};
		
		/*
		* open/closes the nav in the help section
		*/
		{
			$.each($('#helpmenu').find('h3.folder'), function(){
				$(this).bind('click', function(){
					var i = $(this).parent().children('h3').index(this);
					var $parent = $(this).parent();
					$parent.children('h3').removeClass('active');
					$parent.children('h3').removeClass('closed');
					$(this).addClass('active');
					if($parent.children('ul:nth('+i+'):visible').length>0){
						$(parent).children('ul:nth('+i+')').hide();
						$(this).addClass('closed');
					}else{
						$parent.children('ul:visible').toggle();
						$parent.children('ul:nth('+i+')').toggle();
					}
				});
			});
		}
		
		/*
		* unknown. anyone?
		*/
		$.extend($.fn, {
			busy: function(flag){
				if (flag) {
					$(this).addClass('busy');
					$(this).attr('disabled', true);
					$(this).attr('readonly', true);
				} else {
					$(this).removeClass('busy');
					$(this).attr('disabled', false);
					$(this).attr('readonly', false);
				}
			}
		});
		
		/*
		* changes the shop usage graph on the dashboard/analytics page
		*/
		{
			$.each($(".analytics-page .shop-usage li a"),function(){
				$(this).click(function(){
					$.each($(".analytics-page .shop-usage .charts div"), function(){
						$(this).addClass('hide');
					});
					$(".analytics-page .shop-usage .charts div." + $(this).attr('class')).removeClass("hide");
					$(this).parents('ul').children('.selected').removeClass('selected');
					$(this).parent().addClass('selected');
				});
			});
		};
		
		/*
		* big click target for the analytics nav
		*/
		{
			$.each($(".analytics-page .analytics-nav li").children(),function(){
				$(this).click(function(){
					var href = $(this).find('a').attr('href');
					window.location.href = href;
				});
			});
		};
		
		/*
		* big click target for the choose shop page
		*/
		{
			$.each($("li.shop-type"), function(){
				$(this).click(function(){
					var href = $(this).find('.button a').attr('href');
					window.location.href = href;
				});
			});
		};
		
		/*
		* stuff to run at startup on customers page
		*/
		if ($("#this_page").html() == "customers")
		{
			Imagini.customersSetupSegments();
		}
		
		/*
		* hide the nav on certain pages
		*/
		{
			if ($("#this_page").html() == "shop")
			{
				$("#shop-nav").addClass("hide");
			};
			if ($("#this_page").html() == "register")
			{
				$("#shop-nav").addClass("hide");
			};
			if ($("#this_page").html() == "signin")
			{
				$("#shop-nav").addClass("hide");
			};
		};
		
		/*
		* stuff to run at startup on product browse/search page
		*/
		if ($("#this_page").html() == "product")
		{
			Imagini.addProduct(0);
			Imagini.attachCategoryOnChangeEvent();
			Imagini.getSortCriterias('<?= $this->category ?>', '<?= $this->sort ?>');
			$("#GO").click(function(){if ($("#q").val() == "") return false;});
			
			
			if (jQuery.cookie('vdnashops_showhide_bookmarklet') == "hide")
			{
				$("#bookmarklet-feature").removeClass("is_visible");
				$("#bookmarklet-feature").addClass("is_hidden");
				$("#bookmarklet-feature").hide();
				$("#bookmarkletShowHide").html("Show");
			}

			
			$("#bookmarkletShowHide").click(function() {
				if ($("#bookmarklet-feature").hasClass("is_visible"))
				{
					$("#bookmarklet-feature").removeClass("is_visible");
					$("#bookmarklet-feature").addClass("is_hidden");
					$("#bookmarklet-feature").hide();
					$("#bookmarkletShowHide").html("Show");
					
					jQuery.cookie('vdnashops_showhide_bookmarklet', 'hide', { expires: 360, path: '/' });
				}
				else
				{
					$("#bookmarklet-feature").removeClass("is_hidden");
					$("#bookmarklet-feature").addClass("is_visible");
					$("#bookmarklet-feature").show();
					$("#bookmarkletShowHide").html("Hide");
					
					jQuery.cookie('vdnashops_showhide_bookmarklet', 'show', { expires: 360, path: '/' });
				}
			});
		}
		
		/*
		* delays to get 'round flash 'bugs' on the analytic page
		*/
		{
			$("#analytics-date-filter").change(function(){ Imagini.reloadReportDateInterval(); });
			$("#geographyMap").fadeIn("fast");
		}
		
		/*
		* earnings page
		*/
		{
			$("#earnings-date-filter").change(function(){ Imagini.reloadEarningsReportDateInterval(); });
		}
		
		
		/*
		* stuff to run at startup on product management / assignment page
		*/
		if ($("#this_page").html() == "assign")
		{
			// setup behaviours/interactions for assignment controls
			Imagini.assignSetupSegments($(".segments"));
			Imagini.assignSetupGender($(".gender"));
			Imagini.assignSetupSell($(".sell"));

			// lazy loading via Ajax of all segments counts (count = total products per segment, in current shop)
			Imagini.assignGetAllSegmentsCount();
			Imagini.assignSetupRelatedTriggers();
			Imagini.assignAttachFilterEvents();
			
			// age sliders
			$.each($('#assignments_form .age-slider .slider'), function() {
				
				var slider1_default = $("#age_min_" + $(this).parent().attr("id").substr(4)).html();
				var slider2_default = $("#age_max_" + $(this).parent().attr("id").substr(4)).html();
				
				var _min = $(this).parents('div[@id^=product_container_]').children('input[@id$=_age_min]').val();
				var _max = $(this).parents('div[@id^=product_container_]').children('input[@id$=_age_max]').val()
				
				var offsetMin = 5, offsetMax = 5;
				if($(this).parents('div.unassigned').length>0){
					//offsetMin = 20;
					//offsetMax = 0;
				};
				
				var tmp = slider1_default+' '+slider2_default;	

				$(this).slider({
					range: true,
					step: 10,
					min: 0,
					max: 60,
					values: [_min-offsetMin, _max-offsetMax],
					change: function(event, ui) {
						var product_id = $(this).parent().attr("id").split("_");
						product_id = product_id[1];

						// determine wether this is the left or right slider
						if ($(ui.handle).hasClass("max"))
						{
							// right slider
							$("#product_" + product_id + "_age_max").val(ui.value+5);
						}
						else
						{
							// left slider
							var val = (ui.value==0)? 0:5;
							$("#product_" + product_id + "_age_min").val(ui.value+val);
						}

						Imagini.assignSaveSetting(product_id);
					}

				});	
			});
			
			
			$("a#no-recommandations-switch").click(function() {
				Imagini.toggleRecommandationsStatus(this);
			});
			
		}
		
	},
	
	/*
	* helper method to render one product from affiliate
	*/
	_itemToHtml: function (item, button)
	{
		var s, price_section = '';
		
		var star_rating_section = "";
		
		if (item.AverageRating&&item.AverageRating!='')
		{
			star_rating_section = '<span title="Rated ' + item.AverageRating + ' stars by Amazon users" class="tooltip"><img src="/skin/default/images/stars/' + item.AverageRating + '.png" alt="" class="pngfix" /></span>'
		}
		if (item.FormattedPrice)
		{
			price_section = '<p>' + item.FormattedPrice + '</p>';
		}
		var img = (item.SmallImageURL)? item.SmallImageURL:'/skin/default/images/general/no-image.gif';
		s = '<div class="amazon-item" id="_'+item.ASIN+'">' +
			'<div class="white-product-box corner">' +
				'<div class="image">' +
					'<img src="/skin/default/images/general/t.gif" rel="'+img+'" alt="'+item.Title+'" />' +
				'</div>' +
				'<div class="desc">' +
					'<h6>' + item.Title + '</h6>' +
				'<div class="price">' +
					price_section +
					star_rating_section + 
					'<div class="clear"></div>' +
				'</div>' +
				'</div>' +
				'<div class="clear"></div>' +
			'</div>';
		if (button == 1)
		{
			s += '<div class="add v-align">' +
				'<img src="/skin/default/images/icons/add.gif" alt="add" />' +
				'<a href="javascript:;" rel="' + item.DetailPageURL + '" title="view item\'s details on Amazon (opens in a new window)" target="_blank">details</a>' +
				'</div>';
		}
		if (button == 2)
		{
			s += '<div class="add v-align">' +
				'<a href="javascript: void(0)" onclick="Imagini.deleteProduct(\'' + item.ASIN + '\')">remove</a>' +
				'</div>';
		}
		s += '</div>';
		return s;
	},
	
	/*
	* helper method to render product used in carousel
	*/
	_itemToHtmlInCarousel: function (item)
	{
		var s, star_rating_section = "", price_section = "";
		var this_img = (item.SmallImageURL)  ? item.SmallImageURL : '/skin/default/images/general/no-image.gif';

		if (item.AverageRating&&item.AverageRating!='')
		{
			star_rating_section = '<span title="Rated ' + item.AverageRating + ' stars by Amazon users" class="tooltip"><img src="/skin/default/images/stars/' + item.AverageRating + '.png" alt="" class="pngfix" /></span>'
		}
		if (item.FormattedPrice)
		{
			price_section = '<p>' + item.FormattedPrice + '</p>';
		}
		
		s = '<li><div class="white-product-box corner">' +
			'<div class="image">' +
				'<img src="/skin/default/images/general/t.gif" rel="' + this_img + '" alt="' + item.Title + '" />' +
			'</div>' +
			'<div style="display:none;" class="related_asins">' + item.ASIN + '</div>' +
			'<div class="desc">' +
				'<h6>' + item.Title + '</h6>' +
				'<div class="price">' +
					price_section +
					star_rating_section +
					'<div class="clear"></div>' +
				'</div>' +
				'</div>' +
			'</div></li>';
		return s;
	},
	
	/*
	* helper method to render product used in assign page carousel
	*/
	_itemToHtmlAssign: function (item)
	{
		var s, star_rating_section = "", price_section = "";
		if (item.AverageRating&&item.AverageRating!='')
		{
			star_rating_section = '<span title="Rated ' + item.AverageRating + ' stars by Amazon users" class="tooltip"><img src="/skin/default/images/stars/' + item.AverageRating + '.png" alt="" class="pngfix" /></span>'
		}
		if (item.FormattedPrice)
		{
			price_section = '<p>' + item.FormattedPrice + '</p>';
		}
		var img = (item.SmallImageURL)? item.SmallImageURL:'/skin/default/images/general/no-image.gif';
		s = '<li><div class="blue-product-box corner">' +
			'<div class="image">' +
				'<img src="/skin/default/images/general/t.gif" rel="' + img + '" alt="'+item.Title+'" />' +
			'</div>' +
			'<div class="desc">';
				if(item.Title.length>=40){
					s += '<h6>' + item.Title.substr(0,40) + '...</h6>';
				}else{
					s += '<h6>' + item.Title + '</h6>';
				}
		s += '<div class="price">' +
				price_section +
			'</div>' +
			'</div>' +
			'<div class="clear"></div>' +
			'<div class="price">' +
				star_rating_section +
			'</div>';
		s += '</div>';
		s += '<div class="add">' +
			'<img src="/skin/default/images/icons/add.gif" alt="add" class="related-add-trigger" id="related-add-trigger_' + item.ASIN + '" />' +
			'</div>';
		
		s += '</li>';
		return s;
	},
	
	/*
	* reload browsable nodes/categories based on a given category
	*/
	reloadBrowseNodes: function (category)
	{
		$.getJSON(
			app_urls.ajax_reload_nodes, 
			{ 'category': category, 'shop_id': config.default_shop_id },
			function (response)
			{
				if (response.length)
				{
					var content = '<ul class="sub">';  	
					for (i = 0; i < response[0].Ancestors.length; i++)
					{
						content += '<li><a href="/product/browse/' + response[0].Ancestors[i].BrowseNodeId + '-' + category + '">' + response[0].Ancestors[i].Name + '</a></li>';
					}
					content += '</ul>';
					
					var content = '<ul>';  	
					content += '<li>' + response[0].Name;
					content += '<ul>';
					for (i = 0; i < response[0].Children.length; i++)
					{
						content += '<li><a href="/product/browse/' + response[0].Children[i].BrowseNodeId + '-' + category + '">' + response[0].Children[i].Name + '</a></li>';
					}
					content += '</ul></li></ul>';
				}
				
				$("#amazon-nodes").html(content);
			}
		);
	},
	
	
	/*
	* fetch related products
	*/
	refreshRelated: function (ASIN)
	{
		$("#related").hide();
		
		$.getJSON(
			app_urls.ajax_related, 
			{ 'affiliate_id' : $("#affiliate_id").html(), 'asin': ASIN, 'shop_id': config.default_shop_id },
			function (response)
			{
				var content = '';
				content += '<h5>Related products</h5>';
				content += '<p>Amazon customers who bought your recently added product also bought...</p>';
				
				if (response.length > 0)
				{
					for (var i=0; i < response.length; i++)
					{
						content += Imagini._itemToHtml(response[i], 1);
					}	
				}
				else
				{
					content += "<br /><p>There aren't any related products.</p>";
				}
				
				$("#related")[0].innerHTML = content;
				
				$('#previous-just-added').css('visibility', 'visible');
				$('#next-just-added').css('visibility', 'visible');
				
				$.each($("#related .amazon-item .image img"), function(){
					var foo = new ImagePreloader([$(this).attr('rel')], Imagini.calcImageSize, 61, $(this));
				});
				
				$("div.corner").corner("corner");
				$(".v-align").vAlign();
				
				$.each($("#related div.amazon-item"), function(){
					$(this).click(function(){
						var temp 	= $(this).attr("id").split("_");
						var asin 	= temp[1];
						if(!$(this).hasClass("selected")){
							Imagini.addProduct(asin, $(this), 'div')
						}
					});
					
					$(this).find('div.add a').click(function(){
						window.open($(this).attr("rel"));
						return false;
					});
					
				})
				
				$("#related").fadeIn("slow");
			}
		);
	},
	/*
	* add product to shop
	*/
	addProduct: function (ASIN, elem, type)
	{
		if(type=='img'){
			$(elem).parent().parent().addClass("selected");
			$(elem).parent().addClass("hide");
		}else{
			$(elem).addClass("selected");
			$(elem).children('div.add').addClass("hide");
			$(elem).children('div.delete').removeClass("hide");
		}
		
		
		$.each($("#items-in-shop ul").children('li'), function(){
			$(this).remove()
		});
		
		var precontent = '<img src="/skin/default/images/general/loader-big.gif" alt="loading" class="loader" id="loader" />';
		$("#items-in-shop").append($(precontent));
		$.getJSON(
			app_urls.ajax_shop_content, 
			{ 'affiliate_id' : $("#affiliate_id").html(), 'asin': ASIN, 'shop_id': config.default_shop_id },
			function (response)
			{
				// only show the just added box if we have any just added items
				if(response.total_count==0){
					$('#amazon-added-items').hide();
				}else{
					$('#amazon-added-items').show();
				}
				
				
				$("#loader").remove();
				
				if (response.new_product_id != 0)
				{
					$(elem).find(".white-product-box").attr({"id": "_" + response.new_product_id })	
				}
				
				
				if (ASIN)
				{
					Imagini.refreshRelated(ASIN);
				}
				else
				{
					if (response.items.length)
					{
						Imagini.refreshRelated(response.items[response.items.length-1].ASIN);
					}
					else
					{
						Imagini.refreshRelated(response.items.ASIN);
					}
					
				}
				
				var content = '';  	
				var show = 5; // how many items do we want to show in the carousel?
				if (response.items.length)
				{
					if(response.items.length<show){
						var count = response.items.length;
					}else{
						var count = show;
					}
					for (i = (response.items.length-count); i < response.items.length; i++)
					{
						content += 	Imagini._itemToHtmlInCarousel(response.items[i]);	
					}
					if(response.items.length>show){
						$("#products-count").html("displaying " + show + " of " + response.items.length + " in total");
					}else{
						$("#products-count").html(response.items.length + " in total");
					}
				}
				else
				{
					if (response.items.ASIN)
					{
						content += 	Imagini._itemToHtmlInCarousel(response.items);
						$("#products-count").html("1 product in total");
					}
				}

				$("#items-in-shop ul").html(content);
				
				// set the height of the LIs to the height of the last/visible product
				var foo = $("#items-in-shop ul").children('li:last').children('.white-product-box').height();
				if(foo>103){
					foo = foo + 19 + 'px';
				}else{
					foo = foo + 'px';
				}
				$("#items-in-shop ul").children('li').css('height',foo);
				
				if($("#items-in-shop").children('ul').children('li').length>0){

					$('#next-just-added').children().html('&nbsp;');
					$('#next-just-added').addClass('hide');
					$('#previous-just-added').children().html('&lt; previously added');
					
					if($("#items-in-shop").children('ul').children('li').length>1){
						$('#previous-just-added').removeClass('hide');
					}
					
					// timer container
					var carouseltimer = false;
					
					// setup carousel
					$("#items-in-shop").jCarouselLite({
						btnNext: "#next-just-added a",
				  		btnPrev: "#previous-just-added a",
						visible: 1,
						start: $("#items-in-shop").children('ul').children('li').size()-1,
						beforeStart: function(e){
							$("#related").fadeOut("slow");
							if(carouseltimer){
								window.clearTimeout(carouseltimer);
							}
						},
						afterEnd: function(e){
							var index = $(e[0]).parent().children('li').index(e[0]);
							var end = $(e[0]).parent().children('li').size()-1;
							vis = $(e[0]);
							
							$(e[0]).parent().children('li').css('height', $(e[0]).children('.white-product-box').height() + 'px');
							
							if(index==end){
								$('#next-just-added').addClass('hide');
							}
							if(index+1==end){
								$('#next-just-added').removeClass('hide');
								$('#next-just-added').children().html('just added &gt;');
							}
							if(index+1!=end){
								$('#next-just-added').children().html('more recently added &gt;');
							}
							if(index==0){
								$('#previous-just-added').addClass('hide');
								$('#next-just-added').removeClass('hide');
							}
							if(index!=0){
								$('#previous-just-added').removeClass('hide');
							}
							var current_asin = $(e[0]).find(".related_asins").html();
							carouseltimer = setTimeout(function(){ Imagini.refreshRelated(current_asin); }, 1000);
						}
				  	});
			  	
			  	}

				$.each($("#items-in-shop .image img"), function(){
					var foo = new ImagePreloader([$(this).attr('rel')], Imagini.calcImageSize, 91, $(this));
				});
				
				$("div.corner").corner("corner");
			}
		);
	},
	
	/*
	* remove a product from the shop
	*/
	deleteProduct: function (product_id, from, ref_elem)
	{
		var prompt = "Do you really want to remove this product from this shop?";
		if(from=='assign'){
			prompt += "You can put in on hold by deselecting the 'sell' button.";
		}
		$.prompt('<p>'+prompt+'</p>',{ 
			buttons: { "yes": true, "no": false }, 
			opacity: 0.5, 
			overlay: "fast", 
			promptspeed: "fast", 
			show: "fadeIn", 
			callback: function(v,m){
				if(v){
					if (from == "assign")
					{
						$("#product_container_" + product_id).remove();	
					}
					else if (from == "product")
					{
						$(ref_elem).children('div.delete').addClass("hide");
						$(ref_elem).children('div.add').removeClass("hide");
						$(ref_elem).removeClass('selected');						
					}
					
					$.getJSON(
						app_urls.ajax_delete_product, 
						{ 'product_id': product_id, 'shop_id': config.default_shop_id },
						function (response)
						{ 
							window.location = window.location.href;
						}
					);	
				
				}
			}
		});
	},
	
	/*
	* attach change event for product searching categories
	*/
	attachCategoryOnChangeEvent: function ()
	{
		$('select#category').change(
			function() {
				var category = $('select#category').val();
				Imagini.getSortCriterias(category);
			}
		)
	},
	
	/*
	* get search criterias based on selected category
	*/
	getSortCriterias: function(category, selected)
	{
		category = category != '' ? $('select#category').val() : category;
		if (category != "All_")
		{
			tmp = category.split("_");
			category = tmp[0];
		}
		else
		{
			category = "All";
		}
		
		$.getJSON(
		app_urls.ajax_get_order_criteria,
		{'cat': category},
		function (response)
		{
			if (response.length)
			{
				var options = '';
				for (var i=0; i<response.length; i++)
				{
					if (response[i].value == selected)
						options+= '<option selected value="' + response[i].value + '">' + response[i].display + '</option>';
					else
						options+= '<option value="' + response[i].value + '">' + response[i].display + '</option>';
				}
				$('select#sort').html(options);
				$('select#sort').parent().siblings('label[@for=sort]').fadeIn('slow');
				$('select#sort').fadeIn('slow');
			} else {
				//$('select#sort').parent().siblings('label[@for=sort]').hide();
				//$('select#sort').enabled = false;
				//$('select#sort').hide();
			}
		}
		);
	},
	
	/*
	* set up the image assignment 'pop-up'
	*/
	innitAssignPopUp: function()
	{
		Imagini.assignSetUpImages();
	},
	
	
	/*
	* set up the image clicks and hovers in the image assign 'pop-up'
	*/
	assignSetUpImages: function()
	{
		var totalImages = 3; // how many images can we select?
		
		$('#save-button').bind('click', function(){
			Imagini.saveAssignImages();
			
		})
		var image1_form = $("#image-assign #image1");
		var image2_form = $("#image-assign #image2");
		var image3_form = $("#image-assign #image3");
		{// this section creates the borders for any preselected divs
			if($('#image-assign .images .inner .on').size()){
				var i = 0;
				$.each($('#image-assign .images .inner'), function(){
					$.each($(this).children('.on'), function(){
						var q = $(this).parents('#image-assign').children('.images').index($(this).parents('.images'));
						var a = $(this).parent().children('.img').index(this);
						var border = document.createElement('div');
						$(border).attr('class', 'select');
						$(border).attr('id', "_"+q+a);
						$(border).prependTo($(this).parent());
						$(border).css('left', ($(this).parent().children('.img').index(this)*80)+'px');
						$(border).css('display', 'block'); // .show() not working with thickbox for some reason
						i++;
					});
				});
				if(i==totalImages){
					$('#image-assign .images .inner').children('div').not('.on').children('span').addClass('greyed');
				}
			}
		};
		
		$('#image-assign div.img')
		.bind('mouseover', function(){
			var total = $(this).parents('#image-assign').children().find('.select').size();
			if(total>=totalImages){ return; }
			var q = $(this).parents('#image-assign').children('.images').index($(this).parents('.images'));
			var a = $(this).parent().children('.img').index(this);
			var border = document.createElement('div');
			$(border).attr('class', 'hover');
			$(border).attr('id', "__"+q+a);
			$(border).prependTo($(this).parent());
			$(border).css('left', ($(this).parent().children('.img').index(this)*80)+'px');
			$(border).show();
		})
		.bind('mouseout', function(){
			$(this).siblings('.hover').remove();
		})
		.bind('click', function(){
			$('#save-button').removeClass('hide');
			var q = $(this).parents('#image-assign').children('.images').index($(this).parents('.images'));
			var a = $(this).parent().children('.img').index(this);
			var total = $(this).parents('#image-assign').children().find('.select').size();
			if($('#image-assign #_'+q+a).length>0){
				$('#image-assign #_'+q+a).remove();
				$('#image-assign #__'+q+a).remove();
				$(this).parents('#image-assign').children('.images').children('.inner').children('.img').children('span').removeClass('greyed');
				$(this).removeClass('on');
				// images has been deselected:
				var image_ref = $(this).children().find('img').attr('rel');
				if (image1_form.val() == image_ref){
					image1_form.val(0);
				}else if (image2_form.val() == image_ref){
					image2_form.val(0);
				}else if (image3_form.val() == image_ref){
					image3_form.val(0);
				}
				// end				
			}else{
				if(total<totalImages){
					var border = document.createElement('div');
					$(border).attr('class', 'select');
					$(border).attr('id', "_"+q+a);
					$(border).prependTo($(this).parent());
					$(border).css('left', ($(this).parent().children('.img').index(this)*80)+'px');
					$(border).show();
					if($(this).parents('#image-assign').children().find('.select').size()==totalImages){
						$(this).parents('#image-assign').children('.images').children('.inner').children('div').not('.on').children('span').addClass('greyed');
					}
					$(this).addClass('on');
					// images has been selected:
					var image_ref = $(this).children().find('img').attr('rel');
					if (image1_form.val() == 0){
						image1_form.val(image_ref);
					}else if (image2_form.val() == 0){
						image2_form.val(image_ref);
					}else if (image3_form.val() == 0){
						image3_form.val(image_ref);
					}
					// end
				}
			}			
		});
	},
	
	/*
	* save the image assign selections
	*/
	saveAssignImages: function()
	{
		$.getJSON(
			app_urls.ajax_assign_images_to_product, 
			{ 'shop_id': config.default_shop_id, 'product_id': $('#product_id').val(), 'image1': $("#image1").val(), 'image2': $("#image2").val(), 'image3': $("#image3").val() },
			function (response)
			{
				parent.Imagini.insertAssignedImages($('#product_id').val(),$("#image1").val(),$("#image2").val(),$("#image3").val());
				self.parent.tb_remove();
				
				var total_cnt = response.count_unassigned;
				if (total_cnt > 0)
				{
					parent.$("#unassigned_products_count").html(total_cnt);	
					parent.$(".info-text .blue").show();
				}
				else
				{
					parent.$(".info-text .blue").hide();
				}
			}
		);
	},

	/*
	* inserts the assigned image onto the page
	*/
	insertAssignedImages: function()
	{
		var thickbox = false; // let's only call thickbox again if it's needed
		
		// remove old images
		$.each($('#image_assign_list_' + arguments[0] + ' li'), function(){
			$(this).remove();
		});
		
		for(var i = 1; i < arguments.length; i++){
			if(arguments[i]!='0'){ // if it *is* an image
				var src = arguments[i].split('|');
				src = src[2];
				// create the LI
				var li = document.createElement('li');
				if(i==3){
					$(li).attr('class','last');
				}
				// create the A
				var a = document.createElement('a');
				$(a).attr('class', 'thickbox')
					.attr('title', 'open image selector')
					.attr('href', '/assign/pop/'+arguments[0]+'?KeepThis=true&amp;TB_iframe=true&amp;width=780');
				// create the IMG	
				var img = document.createElement('img');
				$(img).attr('alt', '')
					.attr('src', 'http://resources-us.youniverse.com/' + src);
				// add it all up	
				$(a).append($(img));
				$(li).append($(a))
				$('#image_assign_list_' + arguments[0]).append($(li));
				thickbox = true;
			}
		}
		
		// call thickbox if you really want
		if(thickbox){
			// we've got images, so call thickbox and make the product assigned
			tb_init('a.thickbox');
			$('#product_container_' + arguments[0]).children('div:first').removeClass('unassigned').addClass('assigned');
		}else{
			// we've no images, so we need to know if we have segments
			// and unassign it if we haven't
			if(!$('#segments_' + arguments[0]).children().find('a.active').size()){
				$('#product_container_' + arguments[0]).children('div:first').removeClass('assigned').addClass('unassigned');
			}
		}
	},
	
	/*
	* make segments clickable
	*/
	assignSetupSegments: function(segments_container)
	{
		
		$.each($(segments_container), function() {
			var product_id = $(this).attr("id").split("_");
			product_id = product_id[1];
			
			var segment1_form = $("#product_" + product_id + "_segment1");
			var segment2_form = $("#product_" + product_id + "_segment2");
			var segment3_form = $("#product_" + product_id + "_segment3");
			
			var links = $(this).find("dl dt a");
			
			// we were having problems with the nested $.each functions
			// (think it may have been a closure issue), so went old
			// school and used a for loop
			for(var i = 0; i < links.length; i++){
			
				var temp = links[i];
				$(temp).click(function(){
				
					var index = $(this).parent().parent().find('dt a').index(this);
					var segment_name = $(this).parent().attr("rel");
					var count = $(this).parent().parent().find('dt a.active').length;
					
					if (count <=2)
					{
						if ($(this).hasClass("active"))
						{
							$(this).removeClass("active");
							$(this).removeClass("typecol" + (index+1));
							
							if (segment1_form.val() == segment_name)
							{
								segment1_form.val("0");
							}
							if (segment2_form.val() == segment_name)
							{
								segment2_form.val("0");
							}
							if (segment3_form.val() == segment_name)
							{
								segment3_form.val("0");
							}
						}
						else
						{
							$(this).addClass("active");
							$(this).addClass("typecol" + (index+1));
							
							if (segment1_form.val() == 0)
							{
								segment1_form.val(segment_name);
							}
							else if (segment2_form.val() == 0)
							{
								segment2_form.val(segment_name);
							}
							else if (segment3_form.val() == 0)
							{
								segment3_form.val(segment_name);
							}
						}
					}
					else
					{
						if ($(this).hasClass("active"))
						{
							$(this).removeClass("active");
							$(this).removeClass("typecol" + (index+1));

							if (segment1_form.val() == segment_name)
							{
								segment1_form.val("0");
							}
							if (segment2_form.val() == segment_name)
							{
								segment2_form.val("0");
							}
							if (segment3_form.val() == segment_name)
							{
								segment3_form.val("0");
							}
						}
					}
					
					Imagini.assignGetUnassignedCount($(this));
					
					Imagini.assignSaveSetting(product_id);
					setTimeout("Imagini.assignUpdateSegmentCount('" + segment_name + "')", 1000);
				});
			}
		
		});
	},
	
	/*
	* gives the running total of unassigned products at top of page
	*/
	assignUpdateUnassignedCount: function()
	{
		$.getJSON(
			app_urls.ajax_get_unassigned_count, 
			{ 'shop_id': config.default_shop_id },
			function (response)
			{
				var total_cnt = response.count;
				if (total_cnt > 0)
				{
					$("#unassigned_products_count").html(total_cnt);	
					$(".info-text .blue").show();
				}
				else
				{
					$(".info-text .blue").hide();
				}		
			}
		);
	},
	
	/*
	* update unassigned products status
	*/
	assignGetUnassignedCount: function(elem)
	{
		var segcount = $(elem).parents('dl').children().find("a.active").length;
		var imgcount = $(elem).parents('.segments').siblings('.demographics-analytics').children('.image-assign').children().find('li').size();
		var allcount = segcount + imgcount;
		
		if (allcount == 0)
		{
			$(elem).parents('div.assigned')
				.removeClass('assigned')
				.addClass('unassigned');
				$("div.unassigned .blue-box").corner("corner");
				
				
			// toggle "recommended products" to ON, if OFF
			if ($("a#no-recommandations-switch").attr("rel") == 1)
			{
				Imagini.performToggleRecommandationsStatus(0, $("a#no-recommandations-switch"));	
			}
		}
		else
		{
			$(elem).parents('div.unassigned')
				.removeClass('unassigned')
				.addClass('assigned');
		}
	},
	
	/*
	* make gender clickable
	*/
	assignSetupGender: function(gender_container)
	{
		$.each($(gender_container), function() {
			var product_id = $(this).attr("id").split("_");
			product_id = product_id[1];
			$.each($(this).find("ul li a"), function() {
				$(this).click(function() {
					$(this).parent().toggleClass("selected");
					// add to array
					if ($(this).parent().hasClass("selected"))
					{
						var gender = $(this).parent().attr("rel");
						if (gender == "gender_male")
						{
							var gender_val = 2;
						}
						else
						{
							var gender_val = 3;
						}
						$("#product_" + product_id + "_" + gender).val(gender_val);
					}
					else
					// remove from array
					{
						var gender = $(this).parent().attr("rel");
						$("#product_" + product_id + "_" + gender).val("1");
					}
					
					Imagini.assignSaveSetting(product_id);
				});	
			});
			
		});
	},
	
	/*
	* make sell label clickable
	*/
	assignSetupSell: function(sell_container)
	{
		$.each($(sell_container), function() {
			var product_id = $(this).attr("id").split("_");
			product_id = product_id[1];

			$.each($(this).find("ul li a"), function() {
				$(this).click(function() {
					$(this).parent().toggleClass("selected");
					// add to array
					if ($(this).parent().hasClass("selected"))
					{
						$("#product_" + product_id + "_sell").val("1");
					}
					else
					// remove from array
					{
						$("#product_" + product_id + "_sell").val("0");
					}
					
					Imagini.assignSaveSetting(product_id);
				});	
			});
		});
	},

	/*
	* shows an ajax spinner when a setting is being saved, or a request being made
	*/
	assignLoading: function(product_id, show, type)
	{
		var o = $("#product_container_" + product_id);
		
		if(show)
		{
			var c = document.createElement('DIV');
			$(c).attr('class','loading-cloak');
			
			if(type=='message'){
				/*
				var l = document.createElement('DIV');
				$(l).attr('class','error');
				$(l).html('<p>Congratulations, this product is now available in your VisualDNA Shop.</p>');
				*/
			}else{
				var l = document.createElement('DIV');
				$(l).attr('class','loader');
			}
	
			$(o)
				.children('div:first')
				.prepend($(c)
						.height($("#product_container_" + product_id)
						.children('div:first')
						.height()))
				.prepend($(l));
		}
		else
		{
			if(type=='message'){
				$(o).find('div.error').remove();
			}else{
				$(o).find('div.loader').remove();
			}
			$(o).find('div.loading-cloak').remove();
		}
	},

	/*
	* save a setting immediately after it's made
	*/
	assignSaveSetting: function(product_id)
	{
		Imagini.assignLoading(product_id, true);
		
		var str = "&segment1=" + $("#product_" + product_id + "_segment1").val()
				+ "&segment2=" + $("#product_" + product_id + "_segment2").val()
				+ "&segment3=" + $("#product_" + product_id + "_segment3").val();
		
		var params = "id=" + product_id;
		params += "&shop_id=" + config.default_shop_id;
		params += "&segment1=" + $("#product_" + product_id + "_segment1").val();
		params += "&segment2=" + $("#product_" + product_id + "_segment2").val();
		params += "&segment3=" + $("#product_" + product_id + "_segment3").val();
		params += "&age_min=" + $("#product_" + product_id + "_age_min").val();
		params += "&age_max=" + $("#product_" + product_id + "_age_max").val();
		params += "&gender_male=" + $("#product_" + product_id + "_gender_male").val();
		params += "&gender_female=" + $("#product_" + product_id + "_gender_female").val();
		params += "&sell=" + $("#product_" + product_id + "_sell").val();
		
		$.ajax({
		   type: "POST",
		   url: app_urls.ajax_update_settings,
		   data: params,
		   success: function(msg) {
			Imagini.assignUpdateUnassignedCount();
		   	Imagini.assignLoading(product_id, false);
		   }
		 });
	},
	
	/*
	* get total number of products for a segment
	*/
	assignUpdateSegmentCount: function(segment)
	{
		$.getJSON(
			app_urls.ajax_get_products_segment_count,
			{ 'segment': segment, 'shop_id': config.default_shop_id },
			function (response)
			{
				$("." + segment + "_count").html((response.count != 0) ? response.count : "0");
			}
		);
	},
	
	/*
	* get total number of products for each segment
	*/
	assignGetAllSegmentsCount: function()
	{
		var segm_container = $(".segments");
		var segments = "";
		var segments_array = Array();
		$.each($(segm_container[0]).find("dl dt"), function() {
			var segment = $(this).attr("rel");
			segments += segment + ",";
			segments_array.push(segment);
		});

		$.getJSON(
			app_urls.ajax_get_all_segments_count,
			{ 'segments': segments, 'shop_id': config.default_shop_id },
			function (response)
			{
				$.each(segments_array, function(index, item) {
					$("." + item + "_count").html((response.counts[item] != 0) ? response.counts[item] : "0");
				});
			}
		);
	},
	
	/*
	* setup related products triggers on assign page
	*/
	assignSetupRelatedTriggers: function()
	{
		$("a.related-items-trigger").click(function() {
			var product_id = $(this).attr("id").split("_");
			product_id = product_id[1];
			
			var asin = $(this).attr("rel");
			
			$(this).parent().toggleClass('up'); 
			Imagini.assignGetRelated(product_id, asin);
		});
	},
	
	/*
	* calculates necessary size of a preloading amazon image
	*/
	calcImageSize: function(){
		var img = arguments[0];
		if(!img.length){
			return;
		}
		$(img[4]).attr('src',img[0]);
		var width 	= img[1],
			height	= img[2],
			size	= img[3];
		if(width>height){
			if(width>size){
				$(img[4]).width(size);
			}
		}else{
			if(height>size){
				$(img[4]).height(size)
			}
		}
		$(img[4]).css('display','block'); // DO NOT use show() or toggle()!
		$(img[4]).parent().css('background-image','none');
	},
	
	/*
	* fetch related products on assign page
	*/
	assignGetRelated: function (product_id, ASIN)
	{
		if ($("#related-items_" + product_id + " div.related-items div.related-inner div.items ul li").length < 1)
		{
			Imagini.assignLoading(product_id, true);
			
			$.getJSON(
				app_urls.ajax_assign_related, 
				{ 'asin': ASIN },
				function (response){
					Imagini.assignLoading(product_id, false);
					$("#related-items_" + product_id).toggle();
					$("#related-items-count_" + product_id).html(response.length);
					
					var content = '';
					for (var i = 0; i < response.length; i++)
					{
						content += Imagini._itemToHtmlAssign(response[i]);
					}
					
					$("#related-items_" + product_id + " div.related-items div.related-inner div.items ul").html(content);
					
					$.each($("#related-items_" + product_id + " li .image img"), function(){
						var foo = new ImagePreloader([$(this).attr('rel')], Imagini.calcImageSize, 61, $(this)); 
					});
					
					// setup add buttons
					$.each($("#related-items_" + product_id + " li img.related-add-trigger"), function(){
						$(this).click(function(){
							var asin = $(this).attr("id").split("_");
							asin = asin[1];
							
							Imagini.assignAddRelatedProduct(asin, $(this));
						});
					});

					$("div.corner").corner("corner");
					$(".v-align").vAlign();
					
					$('#previous' + product_id + ' a').addClass('hide');
					$('#next' + product_id + ' a').removeClass('hide');
					
					$("#related-items_" + product_id + " div.related-items div.related-inner div.items").jCarouselLite({
						btnNext: "#next" + product_id + " a",
				  		btnPrev: "#previous" + product_id + " a",
				  		afterEnd: function(e){				  			
				  			var index = $(e[0]).parent().children('li').index(e[0]);
				  			var end = response.length;
				  			
				  			if(index==0){
								$('#previous' + product_id + ' a').addClass('hide');
							}else{
								$('#previous' + product_id + ' a').removeClass('hide');
							}
							
							if(index+4==end){
								$("#next" + product_id + " a").addClass('hide');
							}else{
								$("#next" + product_id + " a").removeClass('hide');
							}
				  		}
				  	});
				  	
				  	$("#related-items_" + product_id + " div.related-items div.related-inner div.items ul").equalHeights();

				}
			);
		}
		else
		{
			$("#related-items_" + product_id).slideToggle();
		}
	},
	
	/*
	* add product to shop from assign page
	*/
	assignAddRelatedProduct: function (ASIN, elem)
	{
		var parentASIN = $(elem).parents('div.assigned').parent().attr('id').split("_");
		parentASIN = parentASIN[2];
		Imagini.assignLoading(parentASIN, true);
		$(elem).parents('li').addClass('selected');
		$(elem).addClass('hide');
		$.getJSON(
			app_urls.ajax_shop_content, 
			{ 'asin': ASIN, 'affiliate_id': $("#affiliate_id").html(), 'shop_id': config.default_shop_id },
			function (response)
			{
				window.location = window.location.href;
			}
		);
	},
	
	/*
	* customers page: setup segments events
	*/
	customersSetupSegments: function ()
	{
		var shop_name = $("#shop_name").html();
		var module_prefix = shop_name.substring(0,3).toLowerCase();
		
		$(".segment-menu ul li a").click(function() {
			
			$("#recommended-products-container").parents('div.products').addClass('hide');
			$("#rec-loader").removeClass("hide");
			
			var segment_name = $(this).parent().attr("title");
			var tmp = $(this).parent().attr("rel").split("__");
			var segment_ident = tmp[0];
			var segment_order = tmp[1];
			
			$(this).parents('ul').children('li.active').removeClass('active');
			
			$(this).parent('li').addClass("active");
			
			// change page color
			$("#blue-bg").removeClass();
			$("#blue-bg").addClass("customertypecol" + segment_order);

			// change title
			$("#customer-type-info .inner h3 span.type").html(segment_name);
			$("#what p.desc span#customer-type").html(segment_name)
			
			// change prefix+number
			$("#customer-type-info .inner h3 span.number").html('C' + segment_order);
			
			// why they buy image
			$("img#why_buy_img").attr("src", config.customer_segments_img_path + module_prefix + "_mb_C" + segment_order + ".jpg");

			// why they buy tags image
			$("img#why_buy_tags").attr("src", config.customer_segments_img_path + module_prefix + "_tc_C" + segment_order + ".gif");
			
			// demographics
			$.getJSON(
				app_urls.ajax_get_segment_demographics, 
				{ 'shop_id': config.default_shop_id, 'segment_order': segment_order },
				function (response)
				{
					$("#demographic_profile").html(response.demographic_profile);
					$("#demographic_age").html(response.demographic_age);
					$("#demographic_gender").html(response.demographic_gender);
					$("#segment_description").html(response.description);
				}
			);
			
			// recommandations
			$.getJSON(
				app_urls.ajax_get_products_from_recommandation_service, 
				{ 'segment_ident': segment_ident, 'shop_id': config.default_shop_id },
				function (response)
				{
					
					var content = '';  	
					var items = (response.length>6)? 6:response.length;
					for (var i = 0; i < items; i++)
					{
						content += Imagini._itemToRecHtml(response[i]);
					}
					
					$("#recommended-products-container").parents('div.products').removeClass('hide');
					$("#recommended-products-container").html(content);
					$("#rec-loader").addClass("hide");
					
					$.each($("#recommended-products-container div.sm-white-product-box .image img"), function(){
						var foo = new ImagePreloader([$(this).attr('rel')], Imagini.calcImageSize, 61, $(this)); 
					});
					
					$("div.corner").corner("corner");
					
				}
			);
		});
	},
			
	/*
	* helper method to render product used for recommended products
	*/
	_itemToRecHtml: function (item)
	{
		var s, star_rating_section = "", price_section = "";
		if (item.AverageRating&&item.AverageRating!='')
		{
			star_rating_section = '<span title="Rated ' + item.AverageRating + ' stars by Amazon users" class="tooltip"><img src="/skin/default/images/stars/' + item.AverageRating + '.png" alt="" class="pngfix" /></span>'
		}
		if (item.ListPrice)
		{
			price_section = '<p>' + item.FormattedSalePrice + '</p>';
		}
		var img = (item.SmallImageURL)? item.SmallImageURL:'/skin/default/images/general/no-image.gif';
		s = '<div class="sm-white-product-box corner">' +
			'<div class="image">' +
				'<img src="/skin/default/images/general/t.gif" rel="' + img + '" alt="' + item.Title + '" />' +
			'</div>' +
			'<div class="desc">' +
			'	<h6>' + item.Title + '</h6>' +
			'</div>' +
			'<div class="clear"></div>' +
			'<div class="price">' +
			price_section +
			star_rating_section +
			'	<div class="clear"></div>' +
			'</div>' +
			'</div>';
		return s;
	},
	
	/*
	* change the page from the select shop dropdown
	*/
	shopRedirect: function()
	{
		$.getJSON(
			app_urls.ajax_change_shop, 
			{ 'shop': $("#switch-shop").val() },
			function (response)
			{
				if (response.success) 
				{
					var on_product_page = window.location.href.indexOf('/product');
					if (on_product_page != -1)
					{
						window.location.href = '/product';
					}
					else
					{
						window.location.href = window.location.href;
					}
					return false;
				}	
			}
		);
	},
	
	/*
	* anyone? please comment
	*/
	saveEmail: function()
	{
		$('.error').html('');
		$.getJSON(
			app_urls.ajax_save_email, 
			{ 'email': $(".save_email").val() },
			function (response)
			{
				$('.error').html('');
				if (response.success) 
				{
					$('.replace_container').replaceWith('<br /><br /><p>' + response.msg + '</p><br /><br />');
					return false;
				}
				$('.error').append('<li>' + response.msg + '</li>');		
			}
		);
	},
	
	/*
	* changes analytics page from date filter
	*/
	reloadReportDateInterval: function()
	{
		window.location = '/dashboard?startDate=' + $("#analytics-date-filter").val();
	},

	/*
	* changes analytics page from date filter
	*/
	reloadEarningsReportDateInterval: function()
	{
		window.location = '/earnings?startDate=' + $("#earnings-date-filter").val();
	},

	/*
	* changes analytics page from age filter
	*/
	dashboardFilterAction: function()
	{
		window.location = '/dashboard?filters=' + $("#age_select").val() + '.' + $("#gender_select").val();
	},
	
	/*
	* attach change event for assign page filters
	*/
	assignAttachFilterEvents: function ()
	{
		var current_url = window.location;

		// available/unavailable
		$('select#sort_availability').change(
			function() {
				if ($(this).val() != "")
				{
					window.location = '/assign' + url_no_fassigned + '/favailability-' + $(this).val();	
				}
				else
				{
					window.location = '/assign/' + url_no_fassigned;
				}
			}
		);
		// assigned/unassigned
		$('select#sort_assigned').change(
			function() {
				if ($(this).val() != "")
				{
					window.location = '/assign' + url_no_fassigned + '/fassigned-' + $(this).val();	
				}
				else
				{
					window.location = '/assign/' + url_no_fassigned;
				}
			}
		);
		// sell/hold
		$('select#sort_sell').change(
			function() {
				if ($(this).val() != "")
				{
					window.location = '/assign' + url_no_fsell + '/fsell-' + $(this).val();	
				}
				else
				{
					window.location = '/assign' + url_no_fsell;
				}
			}
		);
		// male/female
		$('select#sort_gender').change(
			function() {
				if ($(this).val() != "")
				{
					window.location = '/assign' + url_no_fgender + '/fgender-' + $(this).val();	
				}
				else
				{
					window.location = '/assign' + url_no_fgender;
				}
			}
		);
		// customer types
		$('select#sort_customers').change(
			function() {
				if ($(this).val() != "")
				{
					window.location = '/assign' + url_no_fcustomers + '/fcustomers-' + $(this).val();	
				}
				else
				{
					window.location = '/assign' + url_no_fcustomers;
				}
			}
		);
		// age
		$('select#sort_age').change(
			function() {
				if ($(this).val() != "")
				{
					window.location = '/assign' + url_no_fage + '/fage-' + $(this).val();	
				}
				else
				{
					window.location = '/assign' + url_no_fage;
				}
			}
		);
		
	},

	/*
	* delete shop
	*/
	deleteShop: function(promtText, location)
	{
		$.prompt('<p>' + promtText + '</p>',{ 
			buttons: { "yes": true, "no": false }, 
			opacity: 0.5, 
			overlay: "fast", 
			promptspeed: "fast", 
			show: "fadeIn", 
			callback: function(v,m){
				if(v){
					window.location.href='/shop/deleteshop/?location=' + location;
				}
			}
		});
		return false;
	},

	/*
	* submit the invitation code before registeration
	*/
	checkcode: function()
	{
		$.each($('.error').children('li'), function(){ $(this).remove(); });
		$.getJSON(
			app_urls.ajax_check_invitation_code, 
			{ 'code': $('.invitation_code').val() },
			function (response)
			{
				if (response.success) 
				{
					self.parent.tb_remove();
					parent.window.location.href = '/shop';
					return false;
				}	
				$('.error').append('<li>' + response.error + '</li>');	
			}
		);
	},
	
	getShortUrl: function(myShopUrl)
	{
		$.getJSON(app_urls.ajax_get_short_url + '?myshopurl=' + escape(myShopUrl),
				function(response)
				{
					shortUrl = response.shortUrl;
				});
	},
	
	addToFacebook: function(fb_api_key, fb_api_tpl_bundle, shortUrl, shopType)
	{
		var comment_data = {"shoptype": shopType,"shoplink": shortUrl};
		FB_RequireFeatures(["XFBML", "Connect"], function(){
			FB.Facebook.init(fb_api_key, "/fbconnect/xd_receiver.htm", null);
			FB.Connect.requireSession(function(){
				FB.Connect.showFeedDialog(fb_api_tpl_bundle, comment_data);
			});
		});
	},

	addToTwitter: function(shopType)
	{
		$('#submitButton').hide();
		$('#loadingIndicator').show();
		
		username = $('.log_username').val();
		password = $('.log_password').val();
		$.post('/addtwitter', 
			{'username': username,
			'password': password,
			'url': shortUrl,
			'shop_type' : shopType}, 
			function(response)
			{
				if (response.success) 
					$('#formdiv').html('<br />' + response.msg);
				else 
				{
					$('#error').html('<br />' + response.msg + '<br />');
					$('#submitButton').show();
					$('#loadingIndicator').hide();
				}
			}, 'json');
	},

	addLocaleToUrl: function(key, value)
	{
	    key = escape(key); value = escape(value);
	
	    var kvp = document.location.search.substr(1).split('&');
	
	    var i=kvp.length; 
		var x; 
		while(i--) 
	    {
	        x = kvp[i].split('=');
	
	        if (x[0]==key)
	        {
	                x[1] = value;
	                kvp[i] = x.join('=');
	                break;
	        }
	    }
	
	    if(i<0) {kvp[kvp.length] = [key,value].join('=');}
	
	    //this will reload the page, it's likely better to store this until finished
	    document.location.search = kvp.join('&'); 
	},

	performToggleRecommandationsStatus: function(new_status, elem)
	{
		$.getJSON(
			app_urls.ajax_toggle_recommandations_status, 
			{ 'shop_id': config.default_shop_id, 'new_status': new_status },
			function (response)
			{
				if ($(elem).attr("rel") == 1)
				{
					$(elem).html("ON");
					$(elem).attr("rel", "0");
				}
				else
				{
					$(elem).html("OFF");
					$(elem).attr("rel", "1");
				}
			}
		);	
	},

	toggleRecommandationsStatus: function(elem)
	{
		$.getJSON(
			app_urls.ajax_get_unassigned_count, 
			{ 'shop_id': config.default_shop_id },
			function (response)
			{
				if (response.count_assigned < 1 && $(elem).attr("rel") == 0)
				{
					$("#no-recommandations-on").show();
				}
				else
				{
					$("#no-recommandations-on").hide();
					
					Imagini.performToggleRecommandationsStatus(($(elem).attr("rel") == 1) ? 0 : 1, elem);
				}
			}
		);
	}
	
	
	/* IF YOU ARE ADDING A FUNCTION AT THE END
	* DON'T INCLUDE THE TRAILING COMMA! danny */

};
