//file URL's for inserted content
var searchHouseHTML_url	= 'App_Themes/AT1/js/searchhouse.htm' + '?_=' + (new Date()).getTime();
var searchHouseJS_url	= 'App_Themes/AT1/js/searchhouse.js' + '?_=' + (new Date()).getTime();
var housemapJSON_url	= 'App_Themes/AT1/js/housemap.txt' + '?_=' + (new Date()).getTime();
var downloadsJSON_url	= 'App_Themes/AT1/js/downloads.txt' + '?_=' + (new Date()).getTime();

//download page specifics
var downloads_catID		= 181
var downloads_secondaryTitle = 'Säkerhetsdatablad, produktblad, broschyrer'
var downloads_jsonData = []

//brand name specifics
var brandnames = ['Osmo', 'Timberex', 'Welin & Co'];	//the brand names that are recognized in the category names
var brandname_dummyImage = ['dummy-osmo_808.jpg', 'dummy-timberex_809.jpg', 'dummy-welin_810.jpg'];
var brandnamesRE = [];
var brandCategories = [];
var otherBrandCategories = [];
for(var i = 0; i < brandnames.length; i++) {	//make an array for each brandname
	brandnamesRE[i] = RegExp('' + brandnames[i] + '(.*)', 'i');
}

//the house specifics
var housemap = [];
var categoryIDmap = {}

//facebook specifics
var facebook_iframe = '<iframe src="//www.facebook.com/plugins/like.php?app_id=276515685693960&amp;href=http%3A%2F%2Fwww.welinoco.com%2F&amp;send=false&amp;layout=button_count&amp;width=450&amp;show_faces=true&amp;action=like&amp;colorscheme=light&amp;font=lucida+grande&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:21px;" allowTransparency="true"></iframe>';


//patch if the console is not defined
//this keeps MSIE from breaking when a debug log statements is left in the sources
if (typeof console == "undefined") {
    window.console = {
        log: function () {}
    };
}

//path to server
var devPath = 'http://welin/';
var prodPath = 'http://www.welinoco.com/';
var hostPath = prodPath;
var href = document.location.href;

//check if it's a local (dev) or public (production) site
//if the hostname is a fully qualified domain name, then it's considered the productions site
if(/https?:\/\/([a-zA-Z_\-0-9\.]+)/.exec(href)[1].split('.').length == 1) {
	hostPath = devPath;
};

//globally available variables
var pageType, pageId, viewId, productId
var infoPageParts = /.*-i-([0-9]+)\.aspx/.exec(href);
var manufacturerPageParts = /.*-m-([0-9]+)\.aspx/.exec(href);
var productPageParts = /.*-p-([0-9]+)-c-([0-9]+)\.aspx/.exec(href);
var categoryPageParts = /.*-c-([0-9]+)(?:-([0-9]))?\.aspx/.exec(href);

//figure out what type of page this is
if(infoPageParts != null) {					//info page: /<whatever>-i-<id>.aspx
	pageType = 'info';
	pageId = infoPageParts[1];
}
else if(manufacturerPageParts != null) {	//manufacturer page: /<whatever>-m-<id>.aspx
	pageType = 'manufacturer';
	pageId = manufacturerPageParts[1];	
}
else if(productPageParts != null) {			//product page: /<whatever>-p-<page-id>-c-<category-id>.aspx
//	console.log(productPageParts);
	pageType = 'product';
	productId = productPageParts[1];
	pageId = productPageParts[2];
}
else if(categoryPageParts != null) {		//category page: /<whatever>-c-<id>-<view>.aspx
	pageType = 'category';
	pageId = categoryPageParts[1];
}
else {
	pageType = 'start';
	pageId = ''
}


$(function() {
//if this is a product page or the downloads page
if(pageType == 'product' || pageType == 'category' && pageId == downloads_catID) {
		$.get(hostPath + downloadsJSON_url, function(data) {
			downloads_jsonData = $.parseJSON(data);
			var downloadGroup = []
			for(var n = 0; n < brandnames.length; n++) {
				downloadGroup[n] = ''
			}
				
			if(pageType == 'category' && pageId == downloads_catID) {	//the downloads page, prep the table
				var downloadsTableRows = ''
				var downloadsTR = ''
				for(var i = 0; i < downloads_jsonData.length; i++) {
					downloadsTR = ''
					if(downloads_jsonData[i].SDB != undefined || downloads_jsonData[i].Datasheet != undefined) {
						downloadsTR += '<tr><td>' + downloads_jsonData[i].Description + '</td><td class="pdf">'
						if(downloads_jsonData[i].SDB != undefined)
							downloadsTR += '<a class="pdf" href="pub_docs/files/Säkerhetsdatablad/' + downloads_jsonData[i].SDB + '">Ladda ner</a>'
						downloadsTR += '</td><td class="pdf">'
						if(downloads_jsonData[i].Datasheet != undefined)
							downloadsTR += '<a class="pdf" href="pub_docs/files/Produktdatablad/' + downloads_jsonData[i].Datasheet + '">Ladda ner</a>'
						downloadsTR += '</td>'
						
						for(var n = 0; n < brandnamesRE.length; n++) {
							var res = brandnamesRE[n].exec(downloads_jsonData[i].Description);
							if(res != null && res.length > 0) {
								//generate a brand element
								downloadGroup[n] += downloadsTR
								break;
							}
						}
					}
				}

				$downloadList = '<div id="downloads">'
				for(var n = 0; n < brandnames.length; n++) {
					if(downloadGroup[n] != '')
						$downloadList += '<table><thead><tr><th colspan="3" class="brandname">' + brandnames[n] + '</th></tr><tr><th>Produkt</th><th>Säkerhetsdatablad</th><th>Broschyr</th></tr></thead><tbody>' + downloadGroup[n] + '</tbody></table>'
				}
				$downloadList += '</div>'
				$.template('categoryPageTextTemplate', $('div.CategoryPageText').html());	//get the text of the category page, use it as a template source
				$('div.CategoryPageText').html($.tmpl('categoryPageTextTemplate', {'downloadList': $downloadList}));
				$('#downloads tbody tr:even').addClass('even');
				
			}
		})
		
	}
	//insert search house functionality
	$.get(hostPath + searchHouseHTML_url, function(data) {
		$('div.MainArea').prepend(data);
		$.getScript(hostPath + searchHouseJS_url)
//			.error(function(xhrObj, textStatus, errorTrown) {alert('error! ' + textStatus)});
	});
	
	//remove extraneous header columns from search results
	$('table.search-result-table tr').first().find('td:gt(2)').remove()
	
	//remove jetshop logo
	$('.infoTextLogo').empty();

	//move the brandnames from the InfoTextWrapper to the RightArea
	$('div.RightArea').append($('.brandnames').detach());
	
	//set css derivative classes for the slideshow sizes
	$('.bildspel-original').addClass('bildspel');
	$('.bildspel-stor').addClass('bildspel');
	$('.bildspel-mellan').addClass('bildspel');
	$('.bildspel-liten').addClass('bildspel');

	
	//adjust the source image location to match the css style
	var adjustImageSize = function() {
		var $this = $(this);
		$this.attr('src', $this.attr('src').replace(new RegExp("/small|medium|large/original"), '/' + size + '/'));
	}
	
	$('.bildspel-original').each(function() {
		size = 'original';
		$(this).find('img').each(adjustImageSize);
	});
	$('.bildspel-stor').each(function() {
		size = 'large';
		$(this).find('img').each(adjustImageSize);
	});
	$('.bildspel-mellan').each(function() {
		size = 'medium';
		$(this).find('img').each(adjustImageSize);
	});
	$('.bildspel-liten').each(function() {
		size = 'small';
		$(this).find('img').each(adjustImageSize);
	});
	
	//activate the slide show
	$('ul.bildspel').jshowoff({speed:15000, links:false, effect: 'slideLeft', controls: true}).closest('div').css('float', 'right').find('.jshowoff-controls')	//.hide();
	$('ul.bildspel').click(function() {
		var $jshowoff = $(this).closest('div');
		$jshowoff.find('.jshowoff-controls').toggle()
	});
	$('ul.bildspel a.jshowoff-play').click(function() {
		alert('hello!');
	});
	
	//adjust jshowoff objects
	$('.bildspel').each(function() {
		var width = $(this).width();
		var height = $(this).height();
		$(this).parents('.jshowoff').width(width).height(height);
		$(this).parents('.jshowoff div').width(width).height(height);
	});
	

	//insert facebook like iframe
	$('div.ProductMenuFooter').append(facebook_iframe);

	//get the house mapping json file	
	$.get(hostPath + housemapJSON_url, function(data) {
		housemap = $.parseJSON(data);
		for(var i = 0; i < housemap.length; i++) {
			categoryIDmap[housemap[i].CategoryID] = housemap[i];
		}
		
		//adjust category images
		$('img.catimage').each(function() {
			var $this = $(this);
			var image = categoryIDmap[$this.attr('data-categoryid')];
			
			if(typeof image == 'undefined' || image.Image == '') {
//				image = 'dummy_452.jpg';
			}
			else {
				image = image.Image;
				$this.attr('src', prodPath + 'pub_images/small/' + image);
			}
		})
		
		//insert secondary titles for the categories in level 1
		$('.ProductCategoryLevel1 .ProductCategoryNameWrapper a').each(function() {
			var $this = $(this);
			var re = /.*-c-([0-9]+)-(?:[0-9]+)\.aspx/i;
			var res = re.exec($this.attr('href'));
			var catID = '0';
			var info;
			if(res != null) {
				catID = res[1];
				if(catID == downloads_catID) {	//handle the download category secondary title
					$this.find('.ProductCategoryNameRight').text(downloads_secondaryTitle);
				}
				else {
					var map = categoryIDmap[catID];
					if(map != null)
						$this.find('.ProductCategoryNameRight').text(map.Info);
				}
			}
		});
		
	})
	
		
	//handle category content for category level 1
	$.template('categoryPageTextTemplate', $('div.CategoryPageText').html());	//get the text of the category page, use it as a template source
	
	//create a compiled template for displaying a category item
	$.template('categoryTmpl', '<li><div><a href="${url}"><img src="/pub_images/small/${image}" class="catimage" data-categoryid="${CategoryID}" alt="${imageDescription}"></a><a class="text" href="${url}">${categoryName}</a></div></li>');
	
	//create a compiled template for displaying a supplier
	$.template('supplierTmpl', '<div class="underkategori-wrap"><h2>${supplierName}</h2><ul class="underkategorier">{{html categoryList}}</ul></div>');
	
	for(var i = 0; i < brandnames.length; i++) {	//make an array for each brandname
		brandCategories[i] = $('<ul></ul>');
	}
	
	//get the categories from the generated menu
	var categoryRawList = $('.ProductCategoryLevel2 .ProductCategoryNameWrapper');
	$('.ProductTreeLevelWrapper2').css('display', 'none');
	var url, catname, $cat;
	var $supplier = $('<ul></ul>');
	for(var i = 0; i < categoryRawList.length; i++) {
		$cat = $(categoryRawList[i]);
		url = $cat.find('a').attr('href');
		catname = $cat.find('span.ProductCategoryName').text();
		var re = /.*-c-([0-9]+)-(?:[0-9]+)\.aspx/i;
		var res = re.exec(url);
		var catID = '0';
		var image;
		if(res != null) {
			catID = res[1];
			image = categoryIDmap[catID];
		}
		
		for(var n = 0; n < brandnamesRE.length; n++) {
			var res = brandnamesRE[n].exec(catname);
			if(res != null && res.length > 0) {
				//generate a subcategory element
				brandCategories[n].append($.tmpl('categoryTmpl', {image: brandname_dummyImage[n], CategoryID: catID, imageDescription: 'my description', categoryName: res[1], url: url + '?pagesize=1000'}));
				break;
			}
		}		
	}
	
	var suppliersHtml = '';
	for(var i = 0; i < brandnames.length; i++) {	//make an array for each brandname
		if(brandCategories[i].children().length > 0) {
			suppliersHtml += ($('<div></div>').append($.tmpl('supplierTmpl', {supplierName: brandnames[i], categoryList: brandCategories[i].html()}))).html()
		}
	}
	
	if(!(pageType == 'category' && pageId == downloads_catID)) {
		$('div.CategoryPageText').html($.tmpl('categoryPageTextTemplate', {'kategorilista': suppliersHtml}));
	}
	
	
	//set css derivative classes for columns
	$('.spalt-hoger').addClass('spalt');
	$('.spalt-vanster').addClass('spalt');
	
	$('.spalt h2 a').each(function() {
		var href = $(this).attr('href');
		$(this).closest('h2').css('cursor', 'pointer');
		$(this).closest('h2').click(function() {
			window.location = href;
		})
	});
})


