var npath = window.location.pathname;

function getChangeCurrencyLink ( currency_id ) {
	var loc = window.location.protocol + '//' + 'www.tresbienshop.net' + window.location.pathname, search = location.search.replace(/(\&|\?)?new\_currency\=([0-9]+)/, '' );
	search = search=='' ? '?new_currency=' + currency_id : '?' + search.substring(1) + 'new_currency=' + currency_id;
	
	return loc + search + window.location.hash;
}

/*
if ( document.cookie.match(/currency\d{4}/ig) == null && window.location.toString().indexOf('new_currency') == -1 && document.domain.toString().indexOf('tresbienshop.net') !== -1 ){
	window.location = getChangeCurrencyLink ( 1 );
}
*/
function isiPhone() {
    var agent = navigator.userAgent.toLowerCase();
    return agent.match(/iPhone/i);
}

function getEntryId ( id ) {
	return id.substring(id.indexOf('.post-')+6, id.length );
}

function hasCategory ( category, categoryArray ) {
	if ( typeof categoryArray == 'undefined' )
		return true;
		
	if ( typeof categoryArray.term != 'undefined' )
	{
		return categoryArray.term == category;
	}
	else
	{
		for ( var i in categoryArray ) {
			if ( categoryArray[i]['term'] == category )
				return true;
		}
	}
	return false;
}

function getInGroupUpdates ( ) {
	var $updates = $('.tbs-updates,.tbs-updates-special');
	if ( $updates.length > 0 )
	{
		
		$updates.each(function(i, item){
			$obj = $(item);
			var itemdata = getBloggerUpdates ( $obj.attr('title'),function (data) {
				
				if ( data != false )
				{
					var link = '', cutoff = 40;
					if ( hasCategory ( 'News', data.value.items[0].category ) )
					{
						link = ' <a href="http://www.tresbienshop.net/en/page/sections.php#news/' + getEntryId ( data.value.items[0].id ) + '">Read more</a>';
					}
					else if ( data.value.items[0].first_image_link != undefined && data.value.items[0].first_image_link != 'false' && data.value.items[0].first_image_link != false)
					{
						link = ' <a href="' + data.value.items[0].first_image_link + '">Read more</a>';
					}
					else
					{
						cutoff = 50;
					}
					
					if ( $obj.hasClass('sale-text') )
						$obj.html(data.value.items[0].title);
					else
						$obj.html('&ndash; Updates: "' + data.value.items[0].title.substring(0,cutoff) + '..."' + link);
				}
				
			});
		});
		
	}
}

/* forb */

;(function($){$.forb={defaults:{initClass:false,initValue:false}};$.fn.extend({forb:function(options){return this.each(function(){var $obj=$(this),initValue,s=$.extend({},$.forb.defaults,options);if(s.initValue){initValue=s.initValue;$obj.val(initValue)}else if((df=$obj.val())!='')initValue=df;if(s.initClass)$obj.addClass(s.initClass);$obj.focus(function(){if($obj.val()==initValue)$obj.val('');if(s.initClass&&$obj.hasClass(s.initClass))$obj.removeClass(s.initClass);}).blur(function(){if($obj.val()=='')$obj.val(initValue);if(s.initClass&&$obj.val()==initValue)$obj.val(initValue).addClass(s.initClass);});});}});})(jQuery);


function relative_time(time_value) {
	var values = time_value.split(" ");
	time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	var parsed_date = Date.parse(time_value);
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	delta = delta + (relative_to.getTimezoneOffset() * 60);
	
	if (delta < 60) {
		return 'less than a minute ago';
	} else if(delta < 120) {
		return 'about a minute ago';
	} else if(delta < (60*60)) {
		return (parseInt(delta / 60)).toString() + ' minutes ago';
	} else if(delta < (120*60)) {
		return 'about an hour ago';
	} else if(delta < (24*60*60)) {
		return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
	} else if(delta < (48*60*60)) {
		return '1 day ago';
	} else {
		return (parseInt(delta / 86400)).toString() + ' days ago';
	}
}


/* article item page fixes */

function articleImageID ( src ) {
	return src.substring(src.lastIndexOf('/')+1,src.indexOf('-rescaled'));
}

function getEnlargedImageLink ( id ) {
	return 'http://www.tresbienshop.se/articleimage/img/' + id + '.jpg'
}

function getOriginalArticleImage(src) {
	return 'http://www.tresbienshop.net/en/articleimage.php?id=5688&image=' + articleImageID(src);
}



function articleOnLoad ( ){
	
	if ( typeof articleImages == 'undefined' )
		return;
	
	var imageCount = articleImages.length, imageCurrent = 0, enlargedImages = [], cache = [], imageEnlargedCurrent = 0;
	
	/* preload images */
	
	for ( var i=0; i<imageCount; i++ )
	{
		if ( articleImages[i].id == undefined ) continue;
		enlargedImages[i] = getEnlargedImageLink ( articleImages[i].id );
	}
	
	if ( imageCount > 1 )
	{
		$('#articleImage > a').attr('href', '#').click ( function ( ){
			imageCurrent++;
			if ( imageCurrent == imageCount )
				imageCurrent = 0;
			
			articleSetImageNr(imageCurrent);
			$(this).find('img').attr('src', $(articleImages[imageCurrent].tag).attr('src'));
			return false;
		}).data('tip','Click picture for additional views').bientip();
	}
	else
	{
		$('#articleImage a').attr('href', '#').css('cursor', 'default').click(function(){return false;});
	}
	
	$('#articleImage').prepend($('<img/>').addClass('enlarge').attr({src:'http://www.tresbienshop.se/_pics/enlarge_default.png',alt:'enlarge product image'}));
	$('.enlarge').click(function(){
		imageEnlargedCurrent = imageCurrent;
		$.fn.colorbox({
			scrolling:false,
			href: enlargedImages[imageEnlargedCurrent],
			title: function(){ var title = $('h1.articleName').text(); return title.length > 40 ? title.substring(0,37) + '...' : title; },
			onComplete: function(){
				$('#cboxPhoto').css('cursor','pointer').data('tip','Click picture for additional views').bientip();
				$('#cboxPrevious,#cboxNext').unbind('click').show().filter('#cboxNext').click(function(){
					if ( imageCount==1 )
						return false;

					imageEnlargedCurrent++;
					if ( imageEnlargedCurrent==imageCount )
						imageEnlargedCurrent = 0;
					$('#cboxPhoto').attr('src', enlargedImages[imageEnlargedCurrent]);
					return false;
				}).end().filter('#cboxPrevious').click(function(){
					if ( imageCount==1 )
						return false;
					imageEnlargedCurrent--;
					if ( imageEnlargedCurrent===-1 )
						imageEnlargedCurrent = imageCount-1;
					$('#cboxPhoto').attr('src', enlargedImages[imageEnlargedCurrent]);
					return false;
				});
			}
		});
		return false;
	});
	
	$('#cboxPhoto').live('click',function(){
		if ( imageCount==1 )
			return false;
		
		imageEnlargedCurrent++;
		if ( imageEnlargedCurrent==imageCount )
			imageEnlargedCurrent = 0;
		$('#cboxPhoto').attr('src', enlargedImages[imageEnlargedCurrent]);
		return false;
	});
	
	$('.downloadlink').live('click', function(){
		window.location = enlargedImages[imageCurrent];
		return false;
	});
	
	$('.addthis_button').remove();
	$('#articleImage').append('<div id="articlesharelinks"><a href="http://www.addthis.com/bookmark.php?v=250&amp;pub=xa-4ab227175eabe994" class="addthis_button">Share</a><a href="#" class="embedlink">Embed</a><a href="#" title="Download image in high resolution" class="downloadlink">Download</a></div>');
	addthis.button('.addthis_button');
	$('.embedlink').live('click', function(){
		$.fn.colorbox({
			html: function() {
				var	productname = $('h1.articleName').text(),
					productimage = $('#articleImage a img').attr('src');
				return '<div id="shareembed"><h4>' + productname + '</h4><label>Embed<textarea id=\'embedinput\'>&lt;a href="' + window.location + '" title="' + document.title + '"&gt;&lt;img alt="' + productname + ' at Tr&egrave;s Bien Shop" src="' + productimage + '"&gt;&lt;br&gt;' + productname + '&lt;/a&gt; at &lt;a href="http://www.tresbienshop.net" title="Fashion and designer clothes at Tr&egrave;s Bien Shop -  Comme des Garçons, Our Legacy, A.P.C., etc"&gt;Tr&egrave;s Bien Shop&lt;/a&gt;</textarea></label><div class="embedclear">&nbsp;</div></div>';
			}
		});
		return false;
	});

	$('#embedinput').live('click',function(){
		$(this).select();
		return false;
	});
	
}

function completeTheLook ( ) {
		
	if ( $('.gridArticleImageContainer img').length > 0 )
	{
		
		var completeHTML = '<div id="gfcsidebar"><h3 class="articleSidebarHeader rub3">' + $('.shopwindow_grid h3').text() + '</h3>';
	
		$('.shopwindow_grid .gridArticleContainer').each(function(i, item) {
			
			var $obj = $(item);
			completeHTML += '<div class="articleSidebarProduct"><a href="' + $obj.find('.gridArticleNameContainer a').attr('href') + '?_ctl" title="' + $obj.find('.gridArticleNameContainer a').text() + '"><img src="' + $obj.find('.gridArticleImageContainer img').attr('src') + '" alt="Product image"></a></div>';
			
		});
		
		completeHTML += '</div>';
		
		$('.shopwindow_grid,#gfcsidebar').remove();
		$('h1.articleName').before(completeHTML);
		
	}
	
	
	
	$('.fack-temp-answer').hide();
	$('.fack-temp-question').click(function ( ){
		$(this).toggleClass('active').next('.fack-temp-answer').toggle();
	});
	
}

function slideText ( item, stateofbig )
{
	var description = item.text, $desc = $(item.description), ret = {html:'',sidebar:''}, stateofbig = !!stateofbig, big='';
	
	if ( typeof $desc.find('img:first').attr('src') != 'undefined' )
	{
		var image = $desc.find('img:first').attr('src');
		var link = $desc.find('img:first').parent('a').not('.slideshow-desc-link').length > 0 ? $desc.find('img:first').parent('a').not('.slideshow-desc-link').attr('href') : false;
		if ( stateofbig ) big = '<div class="slideshow-image-overlay-text">' + $desc.text().replace(/^\s+|\s+$/g, '') + '</div>';
		
		if ( link )
		{
			if ( stateofbig )
			{
				return { html: '<div class="slideshow-soe"><a class="slideshow-image-placement" href="' + link + '"><img src="' + image + '" alt="' + item.title + '"></a><div class="slideshow-soe-description"><h3 class="slideshow-soe-description-title"><a href="' + link + '">' + item.title + '</a></h3><div class="slideshow-soe-description-text"><div class="topper">&nbsp;</div><div class="botter">&nbsp;</div><a href="' + link + '">' + $desc.text().replace(/^\s+|\s+$/g, '') + '</a></div></div></div>'};
			}
			ret.html = '<a class="slideshow-image-placement" href="' + link + '"><div class="slideshow-image-overlay"><div class="slideshow-image-overlay-header"><span>&nbsp;' + item.title + '&nbsp;</span></div>' + big + '</div><img src="' + image + '" alt="' + item.title + '"></a>';
			ret.sidebar = '<div class="picbox picbox-slide"><a href="' + link + '"><b>' + item.title + '</b><br>' + description + '</a><br></div>';
		}
		else
		{
			ret.html = '<div class="slideshow-image-placement"><div class="slideshow-image-overlay"><div class="slideshow-image-overlay-header"><span>&nbsp;' + item.title + '&nbsp;</span></div>' + big + '</div><img src="' + image + '" alt="' + item.title + '"></div>';
			ret.sidebar = '<div class="picbox picbox-slide"><b>' + item.title + '</b><br>' + description + '</div>';
		}
	}
	
	return ret;
}


/* currency drop-down */

function initCurrency ( ) {
	$('#tbscurrency').hover(function ( ) { $(this).addClass('tbscurrency-active') }, function ( ) { $(this).removeClass('tbscurrency-active') });
}


/* pop-up script -- not needed anymore? FIXME */

var win = null;
function NewWindow(mypage,myname,w,h,scroll){
	var LeftPosition = 0, TopPosition = 0;
	var settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable'
	win = window.open(mypage,myname,settings)
}


/* date function for getting week number */

Date.prototype.getMDay = function() {
return (this.getDay() + 6) %7;}
Date.prototype.getISOYear = function() {
var thu = new Date(this.getFullYear(), this.getMonth(), this.getDate()+3-this.getMDay());
return thu.getFullYear();}
Date.prototype.getISOWeek = function() {
var onejan = new Date(this.getISOYear(),0,1);
var wk = Math.ceil((((this - onejan) / 86400000) + onejan.getMDay()+1)/7);
if (onejan.getMDay() > 3) wk--;return wk;}



/* feed fetch functions */

function getPipeFeed ( url, callback )
{
	
	if ( parent.location.protocol == 'https:' )
	{
		return;
	}

	$.getJSON(url, function ( data ) {
		callback ( data );
	});

}

function truncateText ( string, max )
{
	if ( string.length > max )
	{
		string = string.substr ( 0, max-3 );
		if ( string.charAt( string.length-1 ) == ' ' )
			string = string.substr ( 0, string.length-1 );
	}
	return string;
}

function getFilename(url)
{
	if (url)
	{
		var m = url.toString().match(/.*\/(.+?)\./);
		if (m && m.length > 1)
		{
			return m[1];
		}
	}
	return "";
}


function getBloggerUpdates ( label, callback, init ) {
	
	var labels = label.length > 0 ? label.split('/') : [], fetch = '', callback = (typeof callback=='function')?callback:function(){};
	
	if ( init == undefined ) /* fetch Global first, in case, ya kno' */
	{
		fetch = 'http://www.tresbienshop.se/news/api.php?mode=posts&label=Updates/Global&opt-max=1&callback=?';
	}
	else
	{
		fetch = 'http://www.tresbienshop.se/news/api.php?mode=posts&label=Updates/' + label + '&opt-max=1&callback=?';
		labels.pop(); // pop one off the top in case we go another round!
	}
	
	getPipeFeed ( fetch, function ( data ) {
		if ( data.count > 0  )
		{
			var ret = data;
		}
		else if ( labels.length > 0 )
		{
			return getBloggerUpdates ( labels.join('/'), callback, true );
		}
		else if ( labels.length == 0 )
		{
			
			return getBloggerUpdates ( [], callback, true );
			
		}
		else
			ret = false;
		
		if ( ret != undefined )
			callback ( ret );
	});
	
	
}

/* on ready js */

$(document).ready ( function ( ) {
	var smallbasket = $('.smallbasket_title');
	if(smallbasket.text().indexOf('is empty')>0){
		smallbasket.addClass('emptybag').text('Your bag is empty').css('visibility', 'visible');
	} else {
		smallbasket.text('Your bag').css('visibility', 'visible');
	}
	var articlequantity = $('#articleQuantityFormInput');
	
	if(articlequantity.length>0){
		$('#articleImage a').attr('href','#');
		/*articlequantity.find('a.buy').text('Add to bag');*/
	}

	if ( $('.gridArticleContainer').length > 0 )
	{
		var rss_link = 'http://www.tresbienshop.se/rss.php?url='+location.href;
		
		var d = new Date();
		
		if ( d.getMonth() == 11 )
			$('#tbs-category-links a:contains(Outerwear), #tbs-category-links a:contains(Outerwear)').append(' <span style="color:#aa0000;">(20% off)</span>');
		
		if(getFilename(location.href)!='search'){
			var rss_obj = $('<link/>').attr({href:rss_link,rel:'alternate',type:'application/rss+xml',title:document.title+' RSS' });
			
			var rappend = $('#inpagenews');
			if ( rappend.length == 0 )
			{
				rappend = $('.mainheader:first');
			}
			
			if ( !rappend.hasClass('no-rss') )
			{
				rappend.append('<span class="category_rss"><a href="' + rss_link + '" class="speciallink" title="RSS feed for this page"><img src="http://www.tresbienshop.se/_pics/illustrations/rss.jpg"></a></span>');
				$('head').append(rss_obj);
			}
			
			/* add zoom image to product grid images */
			if ( $('.twscontentgrouppage').length>0 )
			{
				$('.twscontentgrouppage .gridArticleContainer').each(function(){
					var prod = $(this);
					if ( prod.find ('.gridArticleImageContainer a').length > 0 )
					{
						var produrl = prod.find('.gridArticleImageContainer a').attr('href');
						var prodid = produrl.substring(produrl.lastIndexOf('/')+1, produrl.lastIndexOf('.php'));
						var imghref = 'http://www.tresbienshop.se/articleimage/img/grid/' + prodid + '.jpg', alt = prod.find('.gridArticleName').text() + ' - ' + prod.find('.gridArticleText').text();
					
					// var imghref = 'http://www.tresbienshop.se/articleimage/img/' + articleImageID ( prod.find('.gridArticleImageContainer img').attr('src') ) + '.jpg'
					
						prod
							.find('.gridArticleImageContainer a').attr('title', alt).end()
							.find('.gridArticleImageContainer').prepend ( $('<a/>').addClass('doenlarge').attr({rel:'prodcbox',href:imghref,title:alt}).data('url',produrl).css({opacity:0}).append( $('<img/>').addClass('enlarge').attr({src:'http://www.tresbienshop.se/_pics/enlarge_default.png',alt:'enlarge product image'}) ) );
						;
					}
				}).hover(function(){
					$(this).find('.doenlarge').animate({opacity:1}, 400);
				}, function(){
					$(this).find('.doenlarge').stop().css({opacity:0});
				});
		
				/* zoom enable zoom images! */
				
				$('.doenlarge').hover(function(){$(this).css({opacity:1})}).colorbox({
					title: function ( ) {
						var t = $(this);
						var title = t.attr('title');
						title = title.length > 40 ? title.substring(0,37) + '...' : title;
						return '<a href="' + t.data('url') + '">' + title + '</a>';
					},
					photoCycle: false,
					onComplete: function ( ) {
						$('#cboxPhoto')
							.css('cursor','pointer')
							.data('tip','Go to product page')
								.unbind().click(function(){
							window.location = $('#cboxTitle a').attr('href');
							return false;
						}).bientip();
					},
					onClosed: function ( ){
						$('#tooltip').remove();
					}
				});
				
			}
		}
		
	}
	
	if( $('#tabarea').length>0 ){ $('#tabarea').tabs({selected:0}); }

	if ( $('.libraryman-fix').length > 0 ) {
		$('body').addClass('libraryman-style-fix').find('#articleImage img').css({height:'auto',width:'700px'});
	}
	
	$('.atbutton, .addthis_button img').replaceWith('Bookmark &amp; share');
	
	if ( typeof ArticleImage == 'function' ) {
		$('#gfcsidebar').html('');
		completeTheLook();
		$('#articleText a[href=http://www.tresbienshop.se/help/contact.html]').attr('href', 'http://www.tresbienshop.se/help/contact.html#' + document.title );
	}
	
	initCurrency ( );
	
	//$('.picslide').trescycle('http://www.tresbienshop.se/news/api.php?mode=posts&label=Slideshow&callback=?', { pager: '#slidenav' } );
	
	
	/* in-group updates */
	
	/*getInGroupUpdates ( );*/
	
	/* Hide shopping list stuff */
	$('input[name=saveAsShoppinglist]').hide();
	
	/* remove false when sale no more... */
	if ( $('.twscontentshopfrontpage').length > 0 )
	{
		
		/* latest features */
		
		
		$pc = $('.puff-contaminator').html('');
		
		getPipeFeed ( 'http://www.tresbienshop.se/news/api.php?mode=posts&label=Features&opt-max=14&callback=?', function ( data ) {
		//$.getJSON('test.json',function(data){
			var j = 0, slidehtml = [], slidesidebar = [], pginit = false, slideshowLength = 3, pufflength = 4, stateofbig = false, bull = false;
			
			
			$.each ( data.value.items, function ( i, item ) {
				
				/*if ( i===0 && (hasCategory ( 'STATEOFEMERGENCY', item.category ) && !hasCategory('BULL', item.category)) )
				{
					var ret = slideText ( item, true );
					stateofbig = true;
					$('.slideshow-container').html('').append(
						$('<div/>').addClass('slideshow-soe').html(ret.html)
					);
					
					
				}
				//else if ( (i==0 && hasCategory ( 'BULL', item.category )) || (bull && i<slideshowLength) )
				else */
				if ( hasCategory ( 'BULL', item.category ) )
				{
					
					var ret = slideText ( item, true );
					bull = true;
					
					if ( i==0 )
						$('.slideshow-container').html('').after($('<ul/>').addClass('slideshow-soe-nav'));
					
					$('.slideshow-container').append(ret.html);
					
					
				}
				else if ( j<pufflength )
				{
					
					var $desc = $(item.description), text = item.text, img = item.first_image;
					var link = item.first_image_link != 'false' || item.first_image_link != 'null' ? item.first_image_link : '#';
					//$pc.append ( '<li' + (j==pufflength-1?' class="last"':'') +'><a href="' + link + '" title="' + item.title + '"><div class="puff-header">' + item.title + '</div><img src="http://www.tresbienshop.se/_pics/features/img/' + encodeURIComponent ( encodeURIComponent ( img.substring(7) ) ) + '" class="puffimg" alt="' + item.title +'"><div class="puff-text">' + $desc.text().replace(/^\s+|\s+$/g, '') + '</div></a></li>' );
					$pc.append ( '<li><a href="' + link + '" title="' + item.title + '"><img src="http://www.tresbienshop.se/_pics/features/img/' + encodeURIComponent ( encodeURIComponent ( img.substring(7) ) ) + '" class="puffimg" alt="' + item.title +'"><div class="puff-header"><span>' + item.title + '</span></div><div class="puff-text">' + $desc.text().replace(/^\s+|\s+$/g, '') + '</div></a><div class="puff-breaker">&nbsp;</div></li>' );
					
					j++;
				
				}
				else
				{
					return;
				}
				/*else if ( !hasCategory('BULL', item.category ) || !hasCategory('STATEOFEMERGENCY', item.category ) )
				{
					$('.picslide-2').css({position: 'relative'}).cycle(
					{
						fx: 'fade',
						timeout: 8000,
						random: 0,
						fit: 1,
						speed: 1000,
						pager: '.picboxcontainer',
						pagerAnchorBuilder: function(idx, slide) {
							return '.picboxcontainer .picbox-slide:eq(' + idx + ')';
						},
						before: function ( curr, next, opts ) {
							var next = opts.nextSlide;
							if ( !pginit )
							{
								next = 0;
								pginit = true;
							}
							$('.picboxcontainer .picbox-slide').filter(':eq(' + opts.currSlide + ')').removeClass('picbox-slide-current').end().filter(':eq(' + next + ')').addClass('picbox-slide-current');
						},
						next: '#slidenext',
						prev: '#slideprev'
					}).find('.slideshow-image-placement').hover(function(){
						$(this).find('.slideshow-image-overlay').css({display:'block'});
					},function(){
						$(this).find('.slideshow-image-overlay').hide();
					});
				}**//*
				else if ( i<slideshowLength && !stateofbig && !bull )
				{
					
					var ret = slideText ( item );
					slidehtml.push ( ret.html );
					slidesidebar.push ( ret.sidebar );
					
					if ( i==slideshowLength-1 )
					{
						$('.picbox-dyn-container').append(slidesidebar.join(''));
						$('.picslide-2').append ( slidehtml.join('') ).css({position: 'relative'}).cycle(
						{
							fx: 'fade',
							timeout: 8000,
							random: 0,
							fit: 1,
							speed: 1000,
							pager: '.picboxcontainer',
							pagerAnchorBuilder: function(idx, slide) {
								return '.picboxcontainer .picbox-slide:eq(' + idx + ')';
							},
							before: function ( curr, next, opts ) {
								var next = opts.nextSlide;
								if ( !pginit )
								{
									next = 0;
									pginit = true;
								}
								$('.picboxcontainer .picbox-slide').filter(':eq(' + opts.currSlide + ')').removeClass('picbox-slide-current').end().filter(':eq(' + next + ')').addClass('picbox-slide-current');
							},
							next: '#slidenext',
							prev: '#slideprev'
						}).find('.slideshow-image-placement').hover(function(){
							$(this).find('.slideshow-image-overlay').css({display:'block'});
						},function(){
							$(this).find('.slideshow-image-overlay').hide();
						});
						delete slidehtml;
						delete slidesidebar;
						
					}
				}
				else
				{
					
					
					var $desc = $(item.description), text = item.text, img = item.first_image;
					var link = item.first_image_link != 'false' || item.first_image_link != 'null' ? item.first_image_link : '#';
					//$('#puffcontaminator .puff-5:eq(' + j + ')').addClass('puff-loaded').html('<a href="' + link + '" title="' + item.title + '"><img src="http://www.tresbienshop.se/_pics/features/img/' + encodeURIComponent ( encodeURIComponent ( img.substring(7) ) ) + '" class="puffimg" alt="' + item.title +'"><div class="puff-header">' + item.title + '</div></a>');
					$pc.append ( '<li><a href="' + link + '" title="' + item.title + '"><img height="113" width="169" src="http://www.tresbienshop.se/_pics/features/img/' + encodeURIComponent ( encodeURIComponent ( img.substring(7) ) ) + '" class="puffimg" alt="' + item.title +'"><div class="puff-header">' + item.title + '</div></a></li>' );
				
				}*/
			});
			/*$('.picslide-2').css({position: 'relative'}).cycle(
			{
				fx: 'fade',
				timeout: 8000,
				random: 0,
				fit: 1,
				speed: 1000,
				pager: '.picboxcontainer',
				pagerAnchorBuilder: function(idx, slide) {
					return '.picboxcontainer .picbox-slide:eq(' + idx + ')';
				},
				before: function ( curr, next, opts ) {
					var next = opts.nextSlide;
					if ( !pginit )
					{
						next = 0;
						pginit = true;
					}
					$('.picboxcontainer .picbox-slide').filter(':eq(' + opts.currSlide + ')').removeClass('picbox-slide-current').end().filter(':eq(' + next + ')').addClass('picbox-slide-current');
				},
				next: '#slidenext',
				prev: '#slideprev'
			}).find('.slideshow-image-placement').hover(function(){
				$(this).find('.slideshow-image-overlay').css({display:'block'});
			},function(){
				$(this).find('.slideshow-image-overlay').hide();
			});*/
			$pc.append($('<li/>')
				.addClass('readmore')
				.append($('<a/>')
					.attr({href:'http://www.tresbienshop.net/en/page/sections.php#news'})
					.addClass('speciallink')
					.html('<span>Read all the news</span>')
				)
			).append(
				$('<li/>').addClass('last').addClass('twitterbox').text(' ')
			);
			$('.slideshow-container').css({position: 'relative'}).cycle(
			{
				fx: 'fade',
				timeout: 8000,
				random: 0,
				speed: 1000,
				pager: '.slideshow-soe-nav',
				pagerAnchorBuilder: function(idx, slide) {
					return '<li><a href="#">&bull;</a></li>';
				}
			});
			
			/*
			$pc.jcarousel({
				scroll: 1,
				visible: 4,
				animation: 450,
				easing: 'swing',
				buttonNextHTML: '<div>&gt;</div>',
				buttonPrevHTML: '<div>&lt;</div>'
			});
			*/
		});
		//$('.picbox-currentweek').html('Current, week ' + new Date().getISOWeek() );
		/* twitter */
		getPipeFeed ( 'http://www.tresbienshop.se/news/api.php?mode=twitter&callback=?', function ( twitters ) {
			var ele = $('.twitterbox');
			if ( ele.length == 0 )
				return;

			var statusHTML = [];
			for (var i=0; i<twitters.length; i++){
				var username = twitters[i].user.screen_name;
				var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
					return '<a href="'+url+'">'+url+'</a>';
				}).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
					return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
				});
				statusHTML.push('<a href="http://twitter.com/tresbienshop" class="twitter-title-link" title="Très Bien Shop on Twitter"><img src="http://www.tresbienshop.se/_pics/illustrations/twitter.jpg" alt="Twitter" id="twittericon"></a> <span class="tweettext"><span class="curl">"</span>'+status+'<span class="curl">"</span></span> <a class="tweettime" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a>');
			}
			ele.html( statusHTML.join('') );
		});
		
	}
	
	$('.subheader').each ( function ( i, item ) {
		$osub = $(item);
		$osub.append ( '<a href="' + $osub.find('a').attr('href') + '" class="submorelink speciallink" title="All ' + $osub.text() + '">All ' + $osub.text() + '</a>');
	});
	
	$('.forb').forb({initClass: 'searchblur'});
	
	$('.special-toggle-readmore').live( 'click', function(){
		$(this).css('display','none').parents('.special-toggle').find('.special-toggle-hidden').css('display','inline');
	});
	
	/*$('#refreshcaptcha').live('click', function (){ $('#validform').attr('src', 'http://www.tresbienshop.se/contact/securimage_show.php?s=' + Math.random() ); return false; });*/
	
	/* fix currency links */
	var currHost = window.location.hostname;
	if ( currHost != 'shop.textalk.se' )
	{
		var currencyLinkPrefix = window.location.protocol + '//' + window.location.hostname + window.location.pathname,
		currPath = window.location.pathname,
		currSearch = window.location.search != '' ? window.location.search.substring(1).replace(/(\&|\?)?new\_currency\=([0-9]+)/, '' ) : '';
		$('.tbscurrency-currencies li a').each(function(i,obj){
			$a = $(this);
			var currAppend = currencyLinkPrefix + '?' + (currSearch==''? '' : currSearch + '&' );
			$a.attr('href', currAppend + $a.attr('href').substring(1) );
		});
	}
	else
	{
		$('#tbscurrency .tbscurrency-currencies').html('Currency changer is not available in checkout...');
	}
	
});
