/**
 * @author joolsson
 * this is a SVN check test: 002
 */

/* ========================  ======================== */
/* ------------------------  ------------------------ */
/* ........................  ........................ */

/* ======================== Main objects and properties ======================== */

var cpbe = (!cpbe) ? {} : cpbe;

cpbe.browser = {};

cpbe.browser.init = function() {
	cpbe.browser.gecko = ($.browser.mozilla == true) ? true : false;
	cpbe.browser.webkit = ($.browser.safari == true) ? true : false;
	cpbe.browser.ie = ($.browser.msie == true) ? true : false;
	cpbe.browser.ie6 = ($.browser.msie == true && parseInt($.browser.version) < 7) ? true : false;
	cpbe.browser.ie7 = ($.browser.msie == true && parseInt($.browser.version) < 8) ? true : false;
	if ($.browser.msie == true && parseInt($.browser.version) < 8) {
		cpbe.browser.ie6 = false;
		cpbe.browser.ie7 = true;
	} else {
		cpbe.browser.ie7 = false;
	}
	
	cpbe.browser.flash = swfobject.getFlashPlayerVersion();
	cpbe.browser.flash = cpbe.browser.flash.major;
};

cpbe.getFlash = function(name) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
		window[name] = $('#'+name)[0];
        return window[name];
    } else {
        return document[name];
    }
};

/* ======================== Methods ======================== */

/* ------------------------ Debug ------------------------ */

/* ........................ Logging ........................ */

cpbe.log = function(msg) {
	if (window.console) {
		console.log(cpbe.log.index + ': ' + msg);
	}
	cpbe.log.index++;
};

cpbe.log.index = 0;


/* ------------------------ Dynamic tracking for Google Analytics ------------------------ */

cpbe.trackStats = function(urlStr) {
	if (window.pageTracker) {
		pageTracker._trackPageview();
	} else {
		cpbe.log('Google Analytics not porperply loaded - could not track ' + urlStr);
	}
}

/* ------------------------ Querystring to object ------------------------ */

cpbe.query2object = function(str) {
	if (str !== undefined) {
		if (str.indexOf(';') == (str.length - 1)) {
			str = str.substr(0,(str.length - 1));
		}
		str = str.split(';');
		var obj = {};
		for (var i=0, il=str.length; i<il; i++) {
			str[i] = str[i].split('=');
			obj[str[i][0]] = str[i][1];
		}
		return obj;
	} else {
		return false;
	}
	
}

/* ------------------------ Insert wordbreaks ------------------------ */

cpbe.wordbreaker = function(str,sepArr,putBeforeSep) {
	if (str !== undefined) {
		if (cpbe.browser.ie6) {
			var wbr = '<wbr />';
		} else {
			var wbr = '&#8203;';
		}
		
		for (var i=0, il=sepArr.length; i<il; i++) {

			if (sepArr[i] == '.') {
				var rplc = /\./g;
			} else {
				var rplc = new RegExp(sepArr[i],'g');
			}
			
			if (putBeforeSep === true) {
				str = str.replace(rplc,wbr+sepArr[i]);
			} else {
				str = str.replace(rplc,sepArr[i]+wbr);
			}
		}
		
		return str;
	} else {
		return false;
	}
	
}

/* ------------------------ jQuery History (deep linking) ------------------------ */

cpbe.history = function(hash) {
	
	if(hash) { // restore
		
		if (cpbe.bigView.dontHashMeBro == false) {
			//alert(window.location.href);
			cpbe.trackStats(window.location.href);
		} else {
			cpbe.bigView.dontHashMeBro = false;
		}
		
		
		if (cpbe.history.dontrun == false) {
			if($.browser.msie) {
				hash = encodeURIComponent(hash);
			}

			if (hash == $(cpbe.bigView.previousHash).prev().attr('id')) { // prev item was the one to the left
				cpbe.bigView.prev();
				
			} else if (hash == $(cpbe.bigView.previousHash).next('.bigView_item').attr('id')) { // prev item was the one to the right
				cpbe.bigView.next();
				
			} else if (hash == $('.bigView_item:first').attr('id')) { // prev item was the first one
				cpbe.bigView.next();
				
			} else if (hash == $('.bigView_item:last').attr('id')) { // prev item was the last one
				cpbe.bigView.prev();
				
			}

		} else {
			cpbe.history.dontrun = false;
		}
	} else { // default

	}
};

cpbe.history.dontrun = true;

/* ------------------------ Navigation ------------------------ */

/* ........................ Main ........................ */

cpbe.mainNavInit = function() {
	var folds = $('#nav1 .navItem > div');
	$('#nav1 .navItem').hover(function(){
		folds.hide();
		$(this).find('div:first').fadeIn();
	},function(){
		folds.hide();
	});
}

/* ........................ Footer ........................ */

cpbe.footerNavInit = function() {
	$('#nav2 .navItem > a').click(function(){
		if ($(this).parent().find('div').length > 0) {
			$(this).parent().removeClass('selected');
			return false;
		}
	});
};

/* ------------------------ Fake Table ------------------------ */

cpbe.fakeTable = function(jQSel,measureSel) {
	var fakeTable = $('#sys_fakeTable');
	
	if (fakeTable.length == 0) {
		$(document.body).append('<table id="sys_fakeTable"></table>');
		fakeTable = $('#sys_fakeTable');
	} else {
		fakeTable.find('tr, td').remove();
	}
	
	$('ul',jQSel).each(function(i){
		fakeTable.append('<tr></tr>\n');
		
		$('li',this).each(function(){
			$('tr',fakeTable).eq(i).append('<td></td>\n');
		});
		
		$('li',this).each(function(i2){
			var measureElem = $(measureSel,this).clone();
			$('tr',fakeTable).eq(i).find('td').eq(i2).append(measureElem);
		});
	});
	
	$('#searchOptions li').each(function(i){
		var currentElem = fakeTable.find('td').eq(i);
		var calcWidth =  currentElem.width() - parseInt(currentElem.css('border-left-width'));
		var calcHeight =  currentElem.height() - parseInt(currentElem.css('border-bottom-width'));
		
		$(this).width(calcWidth).height(calcHeight);
	});
}

/* ------------------------ custom select elements ------------------------ */

cpbe.customSelects = {};

cpbe.customSelects.init = function() {
	$('.inputSelect').each(function(){
		var that = $(this);
		var selected = $(this).find('.selected');
		if (selected.length > 0) {
			$(this)
				.addClass('selected')
				.data('value',selected.attr('rel'))
				.find('.val')
					.text(selected.text())
				.trigger('setVal.inputSelect');	
		}
		
		$(this).find('a:eq(0)').click(function(){
			if ($(this).parents('.noneChoosen').length > 0) {
				return false;
			}
			$('.inputSelect').not(that).removeClass('active');
			that.toggleClass('active');
			return false;
		});
		
		$(this).find('.opts a').click(function(){
			$(this).parent().find('a').removeClass('selected');
			$(this).addClass('selected');
			
			that
				.addClass('selected')
				.data('value',$(this).attr('rel'))
				.find('.val')
					.text($(this).text());
					
			that.removeClass('active');
			
			that.trigger('setVal.inputSelect');
			return false;
		});
		
		$(this).click(function(){
			return false;
		});
		
		$(document.body).click(function(){
			$('.inputSelect').removeClass('active');
		});
	});
}


/* ------------------------ Big View ------------------------ */

cpbe.bigView = {};

cpbe.bigView.itemCountViewMode = 0;
cpbe.bigView.navigating = false;
cpbe.bigView.currentIndex = 0;
cpbe.bigView.previousHash = '';
cpbe.bigView.navDirection = 0;
cpbe.bigView.contentSizeInterval = false;
cpbe.bigView.contentSizeVal = 0;
cpbe.bigView.dontHashMeBro = false;

/* ........................ set/reset current image status ........................ */

cpbe.bigView.prepareStage = function() {
	var items = $('#bigView .bigView_item');
	
	var hash = window.location.hash;
	
	if (hash !== undefined && hash !== '') {
		var itemSelected = items.filter(function(){
			return '#'+$(this).attr('id') === hash;
		});
	} else {
		var itemSelected = items.filter('.selected');
	}
	
	if (itemSelected.length > 0) { // rearrange items so that "selected" or the hash item is first
		var itemSelectedIndex = items.index(itemSelected);
		$('#bigView').prepend(items.slice(itemSelectedIndex));
	}
	
	items = $('#bigView .bigView_item'); // reset after rearrangement
	var itemImages = [];
	
	items.each(function(i){
		itemImages[i] = $(this).find('a[rel=bigViewImgUrl]').attr('href') + ',' + i;
	})
		
	if (hash === '' || hash === undefined) { // if hash was empty, set hash
		cpbe.bigView.dontHashMeBro = true;
		window.location.hash = $('.bigView_item').eq(0).attr('id');
		document.title = $('.bigView_item').eq(0).attr('title');
	}
	
	cpbe.bigView.previousHash = window.location.hash; // set previous hash
	
	if (items.length == 1) {
		cpbe.bigView.itemCountViewMode = 1;
		$('#bigView_prev, #bigView_next').hide();
	} else if (items.length == 2) {
		cpbe.bigView.itemCountViewMode = 2;
	} else if (items.length >= 3) {
		cpbe.bigView.itemCountViewMode = 3;
	}
	
	cpbe.bigView.styleArrows($('.bigView_item').eq(0).attr('id'));
	
	var bw_flashvars = {
		images: itemImages.join(';'),
		fncOnAniStart: 'cpbe.bigView.animationStart',
		fncOnAniComplete: 'cpbe.bigView.animationEnd',
		startImage: 0,
		previewSize: 50
	};
	
	var bw_params = {
		menu: 'false',
		wmode: 'opaque',
		allowscriptaccess: 'always',
		scale: 'noScale'
	}
	
	var bw_attr = {
		id: 'bigView_viewport',
		name: 'bigView_viewport'
	}
	
	swfobject.embedSWF("/Templates/Public/Swf/bigViewer.swf", "bigView_viewport", "100%", "100%", "9.0.0", 
		false, bw_flashvars, bw_params, bw_attr);
		
	$('#content [class*=_small] .bigView_text').live('click',function(){
		var linkUrl = $(this).find('a').attr('href');
		window.location = linkUrl;
	});

};


/* ........................ navigate ........................ */

cpbe.bigView.next = function() {
	cpbe.bigView.navigating = true;
	cpbe.bigView.setContentSize(false);
	
	cpbe.bigView.currentIndex++;
	if (cpbe.bigView.currentIndex == $('.bigView_item').length) {
		cpbe.bigView.currentIndex = 0;
	}
	
	cpbe.bigView.previousHash = '#' + $('.bigView_item').eq(cpbe.bigView.currentIndex).attr('id');
	
	cpbe.bigView.removeContent();
	
	document.title = $('.bigView_item').eq(cpbe.bigView.currentIndex).attr('title');
	//cpbe.bigView.styleArrows($('.bigView_item').eq(cpbe.bigView.currentIndex).attr('id'));
	
	if (cpbe.bigView.itemCountViewMode == 2) {
		$('#bigView_next').hide();
		$('#bigView_prev').show();
	}
	
	cpbe.getFlash("bigView_viewport").step(1);

};

cpbe.bigView.prev = function() {
	cpbe.bigView.navigating = true;
	cpbe.bigView.setContentSize(false);
	
	cpbe.bigView.previousIndex = cpbe.bigView.currentIndex;
	cpbe.bigView.currentIndex--;
	if (cpbe.bigView.currentIndex == -1) {
		cpbe.bigView.currentIndex = $('.bigView_item').length - 1;
	}
	
	//cpbe.bigView.previousHash = '#' + $('.bigView_item').eq(cpbe.bigView.currentIndex).attr('id');
	
	cpbe.bigView.removeContent();
	
	
	document.title = $('.bigView_item').eq(cpbe.bigView.currentIndex).attr('title');
	cpbe.bigView.styleArrows($('.bigView_item').eq(cpbe.bigView.currentIndex).attr('id'));
	
	if (cpbe.bigView.itemCountViewMode == 2) {
		$('#bigView_prev').hide();
		$('#bigView_next').show();
	}
	
	cpbe.getFlash("bigView_viewport").step(-1);
	
};

cpbe.bigView.animationStart = function(startIndex){};

cpbe.bigView.animationEnd = function(targetIndex){
	cpbe.bigView.addContent();
	cpbe.bigView.styleArrows($('.bigView_item').eq(targetIndex).attr('id'));
};


/* ........................ apply style to arrows ........................ */

cpbe.bigView.styleArrows = function(idRef){
	var arrows = $('#bigView_next, #bigView_prev');
	var checkVal = $('#'+idRef+' .bigView_content').attr('class');
	
	cpbe.log('Setting arrow style: ' + checkVal);
	
	arrows.removeClass('m2m collections styleGuide storeLocator');
	
	if (checkVal.indexOf('m2m') > -1) {
		arrows.addClass('m2m');
	} else if (checkVal.indexOf('collections') > -1) {
		arrows.addClass('collections');
	} else if (checkVal.indexOf('styleGuide') > -1) {
		arrows.addClass('styleGuide');
	} else if (checkVal.indexOf('storeLocator') > -1) {
		arrows.addClass('storeLocator');
	} 
};


/* ........................ add content ........................ */

cpbe.bigView.addContent = function(){
	var newContent = $('#'+window.location.hash+' .bigView_content').clone(true);
	var mediaFlash = false;
	var mediaContent = newContent.find('.bigView_media');
	
	if (mediaContent.length > 0) {
		var media = mediaContent.find('a');
		if (media.hasClass('image') === true) {
			media.replaceWith('<img src="'+media.attr('href')+'" alt="" />');
		} else {
			mediaFlash = true;
		}
	}
	
	newContent
		.css('visibility','hidden')
		.appendTo($('#content'))
		
	cpbe.bigView.setContentSize();
		
	newContent
		.hide()
		.css('visibility','visible')
		.fadeIn('normal',function(){

			if (mediaFlash === true) {
				media.attr('id','bigViewFlashContent');
				var flashVars = cpbe.query2object(media.find('.flashVars').html());
				var params = {
					allowFullscreen: true, 
					bgcolor: "#000000",
					wmode: 'opaque'
				};
				swfobject.embedSWF(media.attr('href'), "bigViewFlashContent", "640", "360", "9.0.0", "", 
					flashVars, params, false);
			}
			//setTimeout(function(){
				cpbe.bigView.navigating = false;
			//},150);
		});
};

/* ........................ setContentSize ........................ */

cpbe.bigView.setContentSize = function(off) {
	//cpbe.log('setContentSize');
	
	if (off === false) {
		//cpbe.log('clearing interval');
		clearInterval(cpbe.bigView.contentSizeInterval);
	} else {
		cpbe.bigView.contentSizeVal = 0;
		
		var contentBg = $('#content .bigView_content');
		var contentWrap = contentBg.find('.bigView_text');
		var content = contentWrap.find('div:first');
		
		//cpbe.log('setting interval');
		
		cpbe.bigView.contentSizeInterval = setInterval(function(){
			contentBg.css('min-height','1px');
			contentBg.css('height','auto');
			
			var height = contentBg.height();
			//cpbe.log(height);
			var contentHeight = content.outerHeight(true);
			
			if (height != cpbe.bigView.contentSizeVal) {
				if (contentHeight > height) {
					height = contentHeight;
				}
				
				cpbe.bigView.contentSizeVal = height;
				contentWrap.height(height);
				
				contentBg.css('min-height',height+'px');
			} 
		},200);
		
	}
};



/* ........................ remove content ........................ */

cpbe.bigView.removeContent = function(){
	$('#content object, #content embed')
			.remove();
	
	if(cpbe.browser.ie) {
		$('#content > div').hide();
		if ($('body').hasClass('StartPage')) {
			cpbe.bigView.setContentSize(false);
		}
		$('#content > div').remove(); 
			
	} else {
		$('#content > div')
			.fadeOut('fast',function(){
				if ($('body').hasClass('StartPage')) {
					cpbe.bigView.setContentSize(false);
				}
				$(this).remove(); 
			});
	}	
};

/* ........................ initialize ........................ */

cpbe.bigView.init = function(){
	cpbe.bigView.prepareStage();
	cpbe.bigView.addContent();
	
	$.historyInit(cpbe.history);
		
	$('#bigView_next').click(function(){
		//cpbe.log('Kan ja klicka? ' + cpbe.bigView.navigating);
		if (cpbe.bigView.navigating === false) {
			cpbe.bigView.navigating = true;
			cpbe.history.dontrun = true;
			cpbe.bigView.previousHash = window.location.hash;
						
			var nextHash = $(window.location.hash).next('.bigView_item').attr('id');
			
			if (nextHash == undefined) {
				nextHash = $('.bigView_item').eq(0).attr('id');
			}
			
			/* * *
			*	Temporary fix for IE
			* * * * * * * * * * * * * * */
			/* if(cpbe.browser.ie)
			{
				var url = window.location.href;
				url = url.split("#")[0]+'#'+nextHash;
				window.location.href = url;
				window.location.reload();
				return false;
			}
			*/
			
			$.historyLoad(nextHash);
			cpbe.bigView.next();
		}
		return false;
	});
	
	$('#bigView_prev').click(function(){
		//cpbe.log('Kan ja klicka? ' + cpbe.bigView.navigating);
		if (cpbe.bigView.navigating === false) {
			cpbe.bigView.navigating = true;
			cpbe.history.dontrun = true;
			cpbe.bigView.previousHash = window.location.hash;
			
			var nextHash = $(window.location.hash).prev().attr('id');
			
			if (nextHash == undefined) {
				nextHash = $('.bigView_item:last').attr('id');
			}
			
			/* * *
			*	Temporary fix for IE
			* * * * * * * * * * * * * * */
			/* if(cpbe.browser.ie)
			{
				var url = window.location.href;
				url = url.split("#")[0]+'#'+nextHash;
				window.location.href = url;
				window.location.reload();
				return false;
			} */
			
			$.historyLoad(nextHash);
			cpbe.bigView.prev();
		}
		return false;
	});

	$(document.body).keyup(function(e){
		
		if (e.keyCode == 37) { // arrow left
			//cpbe.log('ARROW LEFT');
			$('#bigView_prev').click();
		} else if (e.keyCode == 39) { // arrow right
			//cpbe.log('ARROW RIGHT');
			$('#bigView_next').click();
		}
	});
};


/* ------------------------ Products ------------------------ */

cpbe.product = {};

cpbe.product.flashLoaded = false;

/* ........................ Display item ........................ */

cpbe.product.show = function(prodItem){
	window.location.hash = '_'+prodItem.attr('id');
	cpbe.trackStats(window.location.href);
	
	$('.productListing').addClass('dimmed');
	
	if ($(document.body).hasClass('StockService')) {
		cpbe.product.showMaterial(prodItem);
	} else {
		cpbe.product.showGarment(prodItem);
	}
};

cpbe.product.showGarment = function(prodItem){
	
	$('.productSearch').css('visibility','hidden');
	
	var itemViewArea = $('#itemViewArea');
	itemViewArea
		//.addClass('active')
		.find('.itemInfoArea')
			.remove()
			.end()
		.fadeIn()
		.addClass('active');
				
	if (cpbe.browser.flash < 9) { // fallback
		itemViewArea.find('.itemImageArea img').attr('src',prodItem.find('.itemImageArea a').eq(0).attr('href'));
			
	} else { // show flash
		itemViewArea.find('.itemImageArea').find('img, object, embed').remove();
		itemViewArea.find('.itemImageArea').append('<div id="flash_productView"></div>');
		
		/*
		 * FLASHVARS
		 * 
		 * imgFront - Sökväg till bild på produktens framsida. 
		 * imgBack - Sökväg till bild på produktens baksida.
		 * hotspotsFront - Semikolon-separerad lista med hotspots
		 * hotspotsBack - Semikolon-separerad lista med hotspots
		 */

		var prodImg1Url = prodItem.find('.itemImageArea a').eq(0).attr('href');
			
		var prodImg2 = prodItem.find('.itemImageArea .prodImg2');
		var hotspotsFront = prodItem.find('.itemImageArea .hotspotsFront');
		var hotspotsBack = prodItem.find('.itemImageArea .hotspotsBack');
		
		var flashVars = {};
		flashVars.imgFront = prodItem.find('.itemImageArea a').eq(0).attr('href');
		
		if (prodImg2.length > 0) {
			flashVars.imgBack = prodImg2.attr('href');
		}
		if (hotspotsFront.length > 0) {
			flashVars.hotspotsFront = hotspotsFront.html();
		}
		if (hotspotsBack.length > 0) {
			flashVars.hotspotsBack = hotspotsBack.html();
		}
	
		swfobject.embedSWF("/Templates/Public/Swf/productViewer.swf", 
			"flash_productView", "305", "490", "9.0.0", false, 
			flashVars, {allowscriptaccess:'always',wmode:'opaque'}, false);
	}
	
	itemViewArea.find('h2').html(prodItem.find('h2').html());
	itemViewArea.find('h3').html(prodItem.find('h3').html());
	itemViewArea.append(prodItem.find('.itemInfoArea').clone());
	var suggestedThumb = itemViewArea.find('.accessoryImgUrl');
	suggestedThumb.replaceWith('<img src="'+suggestedThumb.html()+'" alt="" />');
		
	itemViewArea.data('productIndex',$('.product').index(prodItem));
}

cpbe.product.showMaterial = function(prodItem){
	
	$('.productSearch').css('visibility','hidden');
	
	var itemViewArea = $('#itemViewArea');
	itemViewArea
		//.addClass('active')
		.find('.itemInfoArea')
			.remove()
			.end()
		.fadeIn()
		.addClass('active');
				
	itemViewArea.find('.itemImageArea img').attr('src',prodItem.find('.itemImageArea a').eq(0).attr('href'));
	
	itemViewArea.find('.article span').html(prodItem.find('.article').html()); 
	itemViewArea.find('.colour span').html(prodItem.find('.colour').html());
			
	itemViewArea.find('h2').html(prodItem.find('h3').html());
	//itemViewArea.find('h3').html(prodItem.find('h3').html());
	itemViewArea.append(prodItem.find('.itemInfoArea').clone());
	var suggestedThumb = itemViewArea.find('.accessoryImgUrl');
	suggestedThumb.replaceWith('<img src="'+suggestedThumb.html()+'" alt="" />');
		
	itemViewArea.data('productIndex',$('.product').index(prodItem));
}

/* ........................ Control current view ........................ */

cpbe.product.close = function(){
	$('.productListing').removeClass('dimmed');
	
	$('#itemViewArea')
		.fadeOut()
		.removeClass('active');
		
	$('.productSearch').css('visibility','visible');
	
	window.location.hash = '';
}

cpbe.product.next = function(){
	var nextIndex = $('#itemViewArea').data('productIndex') + 1;
	if (nextIndex == $('.product').length) {
		nextIndex = 0;
	}
	cpbe.product.show($('.product').eq(nextIndex));
}

cpbe.product.prev = function(){
	var prevIndex = $('#itemViewArea').data('productIndex') - 1;
	if (prevIndex == -1) {
		prevIndex = $('.product').length - 1;
	}
	cpbe.product.show($('.product').eq(prevIndex));
}

/* ........................ Search ........................ */

cpbe.product.setSearchParam = function(param,displayText,displayIndex) {
	$('.searchParameters span').eq(displayIndex)
		.html(displayText)
		.data('searchParam',param);
		
	if (cpbe.browser.ie7 === true) {
		$('#searchOptions').trigger('recalc.fakeTable');
	}
	
	$('.productPagination').show();
	$('.textArea').hide();
	
	cpbe.product.searchByParam();
}

cpbe.product.clearParams = function() {
	$('.searchParameters span')
		.html('&ndash;')
		.data('searchParam','');
	
	if (cpbe.browser.ie7 === true) {
		$('#searchOptions').trigger('recalc.fakeTable');
	}
	
}

cpbe.product.searchByParam = function() {
	var postData = [];
	
	$('.searchParameters span').each(function(){
		var param = $(this).data('searchParam');
		if (param != undefined) {
			if (param != '') {
				postData.push($(this).parent().attr('class') + '=' + $(this).data('searchParam'));
			}
		}
	});
	
	if (cpbe.searchAjaxUrl.indexOf('?') == -1) {
		var queryPrefix = '?';
	} else {
		var queryPrefix = '&';
	}
	
	postData = queryPrefix + postData.join('&');
	
	$.ajax({
		type: 'GET',
		url: cpbe.searchAjaxUrl+postData,
		dataType: 'html',
		//data: postData,
		//complete: function(xhr,text){},
		success: function(data,text){
			$('.productListing')
				.find('.product')
					.remove()
					.end()
				.html(data);
				
			cpbe.product.paginationSet();

		},
		error: function(xhr,text,error){
			$('.productListing')
				.find('.product')
					.remove()
					.end()
				.html('<div class="errorMsg">There was an error when searching, please try later.</div>');
			cpbe.product.paginationSet();
		}
	});
}

/* ........................ Pagination ........................ */

cpbe.product.paginationSet = function() {
	$('.product:gt(8)').hide();
	$('.productListing_current_wrap').show();
	$('.productPagination a').removeClass('stop');
	
	
	var totalLength = $('.product').length;
	
	if (totalLength === 0) {
		$('.productListing_total').html('0');
		$('.productListing_current_wrap').hide();
		$('.productPagination a').addClass('stop');
	} else {
		if (totalLength < 9) {
			$('.productListing_current').html('all');
			$('.productPagination a').addClass('stop');
		} else {
			$('.productListing_current').html('1&ndash;9');
			$('.productPagination a.prev').addClass('stop');
		}
		
		$('.productListing_total').html($('.product').length);
	}
	
}

cpbe.product.pageNext = function() {
	var currentItems = $('.product:visible');
	var firstVisible = $('.product').index(currentItems);
	$('.productPagination a').removeClass('stop');
	
	if ($('.product').length >= (firstVisible + 10)) {
		firstVisible += 9;
		currentItems.hide();
		
		$('.product').slice(firstVisible,firstVisible+9).show();
	}
	
	if ($('.product').length - (firstVisible+1) < 9) {
		var endNum = $('.product').length;
		$('.productPagination a.next').addClass('stop');
	} else {
		var endNum = firstVisible+9;
	}
	
	$('.productListing_current').html((firstVisible+1) + '&ndash;' + endNum);
}

cpbe.product.pagePrev = function() {
	var currentItems = $('.product:visible');
	var firstVisible = $('.product').index(currentItems);
	$('.productPagination a').removeClass('stop');
	
	if (firstVisible > 8) {
		firstVisible -= 9;
		currentItems.hide();
		
		$('.product').slice(firstVisible,firstVisible+9).show();
	}
	
	if ($('.product').length < 9) {
		var endNum = $('.product').length;
	} else {
		var endNum = firstVisible+9;
	}
	
	if (firstVisible === 0) {
		$('.productPagination a.prev').addClass('stop');
	}
	
	$('.productListing_current').html((firstVisible+1) + '&ndash;' + endNum);
}


/* ........................ Initialization ........................ */

cpbe.product.init = function() {
	if ($('.textArea > div').children().length > 0) {
		$('.productPagination').hide();
	}
	
	$('.productThumbnail').live('click',function(){
		cpbe.product.show($(this).parent());
		return false;
	});
	
	$('#itemViewArea .close').click(function(){
		cpbe.product.close();
		return false;
	});
	
	$('#itemViewArea .next').click(function(){
		cpbe.product.next();
		return false;
	});
	
	$('#itemViewArea .prev').click(function(){
		cpbe.product.prev();
		return false;
	});
	
	
	if ($('.productPagination').length > 0) {
		cpbe.product.paginationSet();
		
		$('.productPagination .next').click(function(){
			if ($(this).hasClass('stop') === false) {
				cpbe.product.pageNext();
			}
			return false;
		});
		
		$('.productPagination .prev').click(function(){
			if ($(this).hasClass('stop') === false) {
				cpbe.product.pagePrev();
			}
			return false;
		});
	}


	if ($('#searchOptions').length > 0) {
		var folds = $('#searchOptions .searchFold');
		
		$('#searchOptions li').hover(function(){
			//$(this).addClass('hover');
			folds.hide();
			$(this).find('.searchFold').fadeIn();
		},function(){
			//$(this).removeClass('hover');
			$(this).find('.searchFold').fadeOut();
		});
		
		$('#searchOptions .searchFold div > a').click(function(){
			if (cpbe.searchAjaxUrl) {
				var param = $(this).attr('id');
				var displayText = $(this).find('.linktext').text();
				var displayIndex = $('.searchOptions li').index($(this).parents('li').eq(0));
						
				cpbe.product.setSearchParam(param, displayText, displayIndex);
				
				//$(this).parents('li').eq(0).removeClass('hover');
				$(this).parents('.searchFold').eq(0).fadeOut();
				
				return false;
			}
		}); 
		
		$('.reset a').click(function(){
			cpbe.product.clearParams();
			
			return false;
		});
		
		
		if (cpbe.browser.ie7 === true) {
			cpbe.fakeTable('#searchOptions','a:eq(0), span:first-child');
			$('#searchOptions').bind('recalc.fakeTable',function(){
				cpbe.fakeTable('#searchOptions','a:eq(0), span:first-child');
			});
		}
	}
	
	if (window.location.hash.indexOf('_') == 1) {
		var productId = window.location.hash.replace('_','');
		if ($(productId).length > 0 && $(productId).hasClass('product')) {
			$(productId).find('a').eq(0).click();
		}
	}
	
};

/* ------------------------ Store locator ------------------------ */

cpbe.storeLocator = {};

cpbe.storeLocator.tree = {};
cpbe.storeLocator.tree.regions = {};
cpbe.storeLocator.tree.countries = {};

cpbe.storeLocator.init = function() {
	$('a[href*=mailto]').each(function(){
		var content = $(this).html();
		$(this).html(cpbe.wordbreaker(content,['@','.']));
	});
	
	$('.store_selector_world .opts a').each(function(){
		var currentRegion = $(this).attr('rel');
		cpbe.storeLocator.tree.regions[currentRegion] = [];
		
		$('.'+$(this).attr('rel')).each(function(){// countries
			$(this).find('.opts a').each(function(){ 
				
				var currentCountry = $(this).attr('rel');
				cpbe.storeLocator.tree.countries[currentCountry] = [];
			
				$('.'+$(this).attr('rel')).each(function(){// cities
					$(this).find('.opts a').each(function(){ 
						cpbe.storeLocator.tree.regions[currentRegion].push($(this).attr('rel'));
						cpbe.storeLocator.tree.countries[currentCountry].push($(this).attr('rel'));
					});
				});
				
			});
		});

	});

	
	$('.store_selector_world').bind('setVal.inputSelect',function(){
		$('.store')
			.show()
			.removeClass('marked');
		
		$('.store_regions')
			.removeClass('noneChoosen')
			.find('.inputSelect')
				.hide()
				.end()
			.find('.'+$(this).data('value'))
				.removeClass('selected')
				.css('display','block');
				
		$('.store_countries')
			.addClass('noneChoosen')
			.find('.inputSelect')
				.removeClass('selected');
		
		$.each(cpbe.storeLocator.tree.regions[$(this).data('value')],function(){
			$('.'+this+' .store').addClass('marked');
		});
		
		$('.store').not('.marked').hide();
	});
	
	$('.store_regions .inputSelect').bind('setVal.inputSelect',function(){
		$('.store')
			.show()
			.removeClass('marked');
		
		$('.store_countries')
			.removeClass('noneChoosen')
			.find('.inputSelect')
				.hide()
				.end()
			.find('.'+$(this).data('value'))
				.css('display','block');	
				
		$.each(cpbe.storeLocator.tree.countries[$(this).data('value')],function(){
			$('.'+this+' .store').addClass('marked');
		});
		
		$('.store').not('.marked').hide();
	});
	
	$('.store_countries .inputSelect').bind('setVal.inputSelect',function(){
		$('.store')
			.show()
			.removeClass('marked');
		
		$('.textArea').hide();
		
		$('.store', $('.'+$(this).data('value'))).addClass('marked');
		$('.store').not('.marked').hide();
	});
	
	cpbe.customSelects.init();
	
	$('.store. a.details').click(function(){
		var currentStore = $(this).parent().clone();
		
		$('#store_back').show('normal');
		
		$('.storeHome').slideUp('normal',function(){
			$('.storeView')
				.find('.store, .storeImage, .brandStoreDescription')
					.remove()
					.end()
				.append(currentStore)
				.prepend('<img class="storeImage" src="'+$('.storeView a.storeImage').attr('href')+'" alt="" />');
			
			$('.storeView')
					.append($('.storeView .brandStoreDescription'));
			
			$('.storeView')
				.slideDown('slow');
		});
		return false;
	});
	
	$('#store_back a').click(function(){
		$(this).parent().hide();
		
		$('.storeView').slideUp('normal',function(){
			$('.storeHome').slideDown('normal');
		});
		
		return false;
	});
};


/* ------------------------ Contacts ------------------------ */

cpbe.contacts = {};

cpbe.contacts.init = function(){
	$('a[href*=mailto]').each(function(){
		var content = $(this).html();
		$(this).html(cpbe.wordbreaker(content,['@','.']));
	});
	
	
	$('.contact_selector_world').bind('setVal.inputSelect',function(){
		$('.contact_regions')
			.removeClass('noneChoosen')
			.find('.inputSelect')
				.hide()
				.end()
			.find('.'+$(this).data('value'))
				.removeClass('selected')
				.css('display','block');
				
		$('.contact_countries')
			.addClass('noneChoosen')
			.find('.inputSelect')
				.removeClass('selected');
	});
	
	$('.contact_regions .inputSelect').bind('setVal.inputSelect',function(){
		var contact_pr = $('.contact_pr');
		var contact_sr = $('.contact_sr');
		var currentCountry = $(this).data('value');
		var currentTitle = $(this).find('.val').html();
		
		contact_pr.find('.tail').hide();
		contact_sr.find('.tail').hide();
		
		contact_pr
			.removeClass('active')
			.find('.place')
				.html(currentTitle)
				.end()
			.find('.contactItem')
				.hide();
				
		contact_sr
			.removeClass('active')
			.find('.place')
				.html(currentTitle)
				.end()
			.find('.contactItem')
				.hide();
		
		if (contact_pr.find('.'+currentCountry).length > 0) {
			contact_pr
				.addClass('active')
				.find('.'+currentCountry)
					.css('display','inline-block');
					
			if (cpbe.browser.ie7) {
				contact_pr.find('.'+currentCountry).css('display','inline');
			}
		}

		if (contact_sr.find('.'+currentCountry).length > 0) {
			contact_sr
				.addClass('active')
				.find('.'+currentCountry)
					.css('display','inline-block');
					
			if (cpbe.browser.ie7) {
				contact_sr.find('.'+currentCountry).css('display','inline');
			}
		}
		
		
	});
	
	cpbe.customSelects.init();
	
};

/* ======================== Other ======================== */

/* ------------------------ Micro-templating ------------------------ */

cpbe.parseMicroTemplate = function(templateId,parseObj) {
	var tmpl = $(templateId).html();
	tmpl = tmpl.replace('<![CDATA[','').replace(']]>','');
	$.each(parseObj,function(i,val){
		var key = new RegExp(this,'g');
		tmpl.replace(key,val);
	});
}

/* ======================== Page Load Event handlers ======================== */

$(document).ready(function(){
	cpbe.browser.init();
	
	var page = $('body');
	if (page.hasClass('StartPage')) {
		cpbe.bigView.init();
		
		var navItems = $('#nav2 .navItem');
		navItems.eq(navItems.length - 1).addClass('selected');
		
	} else if (page.hasClass('EditorialPage')) {
		cpbe.bigView.init();
		
	} else if (page.hasClass('News')) {
		
		
	} else if (page.hasClass('StoreLocator')) {
		cpbe.storeLocator.init();
		
	} else if (page.hasClass('StoreLocatorStore')) {
		
		
	} else if (page.hasClass('FileLibrary')) {
		
		
	} else if (page.hasClass('Collections')) {
		cpbe.product.init();
		
	} else if (page.hasClass('Product')) {
		
		
	} else if (page.hasClass('StockService')) {
		cpbe.product.init();

	} else if (page.hasClass('Contact')) {
		cpbe.contacts.init();

	}



	
	if ($('#bigView').length == 0) { // TEMP - knapparna skall ej vara med live på icke bigView-sidor
		$('#bigView_next, #bigView_prev').hide();
	}
	
	cpbe.footerNavInit();

	cpbe.mainNavInit();
	
	if (page.hasClass('EditorialPage') || page.hasClass('StartPage')) {
		$('#bigView_prev').each(function(){
			this.focus();
		});
	}
	
});

