// this script is linked in ePages: Ulkoasu -> Muokkaa navigaatio elementtejä -> Ylätunniste -> javascript ulkoasu säädöt
// for some reason ePages call's this element twice, this prevents this code to be executed in both times
if (typeof(count) == 'undefined')
{
	var count = 0;
}
var basket_id = '';
var selected_type = 1;
var selected_manufacturer = 0;
var selected_model = 0;

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

if (!count)
{
	jQuery.ready(function($)
	{
		// initialize cover page's manufacturer list
		$('#manufacturer-list').html(manufacturers);
		
		product_selector();
		
		if (document.location.href.indexOf('recommendation_send') > 0)
		{
			$('body').prepend('<div id="recommend-link"><span>Viesti lähetetty!</span><a href="#">Suosittele kaverille</a></div>');
		}
		else
		{
			$('body').prepend('<div id="recommend-link"><a href="#">Suosittele kaverille</a></div>');
		}
		
		$('#empty-basket a').bind("click", function(e){
			empty_basket();
			return false;
		});
		
		if ($('.NavBarLeft .NavBarElement0 .ContextBoxBody').html().indexOf('korisi on tyhj') > 0)
		{
			$('#empty-basket').hide();
		}
		
		// hide cover info if there is products in basket
		if ($('.MiniBasket').is(':visible'))
		{
		  $('#cover-selector').show();
			$('#cover-info').hide();
    }
    
		// catch cover info links
		$('#show-polypussi').bind("click", function(e) {
			$('#cover-selector').show();
			$('#cover-info').hide();
			return false;
		});
		
		$('#show-motor').bind("click", function(e) {
		  $('#other-motor').click();
			$('#cover-selector').show();
			$('#cover-info').hide();
		  return false;
		});
    
    $('#show-active').bind("click", function(e) {
      $('#other-active').click();
			$('#cover-selector').show();
			$('#cover-info').hide();
      return false;
		});
    
    $('#show-micro').bind("click", function(e) {
      $('#other-micro').click();
			$('#cover-selector').show();
			$('#cover-info').hide();
      return false;
		});
    
		$('#show-kotisuodatin').bind("click", function(e) {
		  find_home_filters($('#search-home-filter'), true);
			$('#cover-selector').show();
			$('#cover-info').hide();
			return false;
		});
		
    $('#show-window').bind("click", function(e) {
      find_home_filters($('#search-home-filter'), true);
      $('#other-window').click();
			$('#cover-selector').show();
			$('#cover-info').hide();
			return false;
		});
		
    $('#show-crass').bind("click", function(e) {
      find_home_filters($('#search-home-filter'), true);
      $('#other-crass').click();
			$('#cover-selector').show();
			$('#cover-info').hide();
			return false;
		});
		
    $('#show-hood').bind("click", function(e) {
      find_home_filters($('#search-home-filter'), true);
      $('#other-hood').click();
			$('#cover-selector').show();
			$('#cover-info').hide();
			return false;
		});
		
		
		// catch cover main selector links
		$('#search-dust-bag').bind("click", function(e) {
			find_dust_bags(this, true);
			return false;
		});
		
		$('#search-home-filter').bind("click", function(e) {
			find_home_filters(this, true);
			return false;
		});
		
		// catch recommend link
		$('#recommend-link a').bind("click", function(e) {
			send_recommendation();
			return false;
		});
		
		// catch basket id for product search hiding
		$('.BasketLink').bind("click", function(e) {
			link_parts = $(this).attr('href').split('=');
			createCookie('basket_id', link_parts[1]);
		});
		
		if (document.location.href.indexOf('Shops') > 1)
		{
			createCookie('basket_id', null);
		}
		
		//product_image_carousel();
		update_external_database();
		search_by_product_number();
		fix_texts();
		
		if (document.location.href.indexOf('selected_product') > 0)
		{
			var pos1 						= document.location.href.indexOf('selected_type') + 14;
			var pos2						= document.location.href.indexOf('&selected_man');
			var type 						= document.location.href.substr(pos1, pos2 - pos1);

			var pos1 						= document.location.href.indexOf('selected_man') + 13;
			var pos2						= document.location.href.indexOf('&selected_model');
			var manufacturer_id = document.location.href.substr(pos1, pos2 - pos1);
			
			pos1								= document.location.href.indexOf('selected_model') + 15;
			pos2								= document.location.href.indexOf('&selected_product');
			var model_id 				= document.location.href.substr(pos1, pos2 - pos1);
			
			pos1 = document.location.href.indexOf('selected_product') + 17;
			var product_id 			= document.location.href.substr(pos1);
			select_product(type, manufacturer_id, model_id, product_id);
		}
		
	});
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// simulate selector clicks after product is added to basket and page is refressed

function select_product(type, manufacturer_id, model_id, product_id)
{ 
	if (type == 1) // dust bags
	{
		// simulate find dust bag click
		jQuery('#search-dust-bag').each(function(idx, item) {
			find_dust_bags(this, false);	
		});
		// print selector
		product_selector();
	}
	else // home filters
	{
		// simulate find home filters click
		jQuery('#search-home-filter').each(function(idx, item) {
			find_home_filters(jQuery(item), false);	
		});
		// print selector
		product_selector();
		
	} 
	if (manufacturer_id < 0) // simulate other filter click
	{
		jQuery('#other-list a').each(function(idx, item) { 
			var id = jQuery(item).attr('id');

			// vacuum filters
			if (id == 'other-vacuum' && manufacturer_id == -1)
			{ 
				jQuery(item).addClass('cover-list-selected');
				jQuery(item).click();
			}
			
			// window filters
			if (id == 'other-window' && manufacturer_id == -2)
			{
				jQuery(item).addClass('cover-list-selected');
				jQuery(item).click();
			}
			
			// hood filters
			if (id == 'other-hood' && manufacturer_id == -3)
			{
				jQuery(item).addClass('cover-list-selected');
				jQuery(item).click();
			}
		});
	}
	else // simulate dust bag or air condition filter click
	{
		jQuery('#manufacturer-list a').each(function(idx, item) {
			var id = jQuery(item).attr('id').replace('manufacturer-', '');
			
			if (id == manufacturer_id)
			{
				jQuery(item).addClass('cover-list-selected');
				jQuery(item).click();
			}
		});
	}
	
	// simulate model click
	jQuery('#model-list a').each(function(idx, item) {
		var id = jQuery(item).attr('class');
		if (id == model_id.replace(' hovered', '').replace(' focused', ''))
		{
			jQuery(item).addClass('cover-list-selected');
			jQuery(item).click();
		}
	});
	if (type == 2) 
	{
		jQuery('#manufacturer-list').css('height', '100px');
		jQuery('#other-list').css('height', '100px');
	}
	jQuery('#model-list').css('height', '231px');
	//jQuery('#model-list').html(jQuery('#model-list').html());
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// print product selector to cover page

function product_selector()
{
	// bind click of manufacturer
	jQuery('#manufacturer-list a').bind("click", function(e) {
		jQuery('#manufacturer-list a').removeClass('cover-list-selected');
		jQuery('#other-list a').removeClass('cover-list-selected');
		jQuery(this).addClass('cover-list-selected');
		
		if (jQuery('#search-dust-bag').hasClass('active'))
		{
		  jQuery('#cover-selector-model h2').html('Pölynimurin malli');
		}
		else
		{
		  jQuery('#cover-selector-model h2').html('Ilmanvaihtokoneen malli');
		}
		
		// get manufacturer id
		selected_manufacturer = jQuery(this).attr('id').replace('manufacturer-', ''); // form: manufacturer-xx
		print_model_table(selected_manufacturer);
		
		// bind click of model
		jQuery('#model-list a').bind("click", function(e) {
			
			jQuery('#model-list a').removeClass('cover-list-selected');
			jQuery(this).addClass('cover-list-selected');
			
			// get product id
			selected_model = jQuery(this).attr('class').replace(' cover-list-selected', '');
			var product_id = jQuery(this).attr('id').replace('product-', ''); // form: product-xx
			print_product_table(product_id);
			
			jQuery("#effect").effect('highlight', { color: 'green' });
		});
	});

//		var links = '<a id="product-74" class="-1">Moottorisuodatin - yleismalli</a>';
//		links += '<a id="product-73" class="-2">Mikrokuitusuodatin - yleismalli</a>';
//		links += '<a id="product-75" class="-3">Aktiivihiilisuodatin - yleismalli</a>';

	
	jQuery('#other-motor').bind('click', function(e) {
		selected_manufacturer = -1;
		
		var links = '<a id="product-74" class="-1">Yleismalli</a>';

		other_filter_selector(this, 'Moottorisuodatin', links);
	});

	jQuery('#other-active').bind('click', function(e) {
		selected_manufacturer = -1;
		
		var links = '<a id="product-75" class="-3">Yleismalli</a>';

		other_filter_selector(this, 'Aktiivihiilisuodatin', links);
	});

	jQuery('#other-micro').bind('click', function(e) {
		selected_manufacturer = -1;
		
		var links = '<a id="product-73" class="-2">Yleismalli</a>';

		other_filter_selector(this, 'Mikrokuitusuodatin', links);
	});
	
	jQuery('#other-window').bind('click', function(e) {
		selected_manufacturer = -2;
		
		var links = '<a id="product-76" class="-1">Yleismalli</a>';

		other_filter_selector(this, 'Ikkunan malli', links);
	});

	jQuery('#other-hood').bind('click', function(e) {
		selected_manufacturer = -3;
		
		var links = '<a id="product-77" class="-1">Yleismalli</a>';
		
		other_filter_selector(this, 'Liesituulettimen malli', links);
	});
	
	jQuery('#other-crass').bind('click', function(e) {
		selected_manufacturer = -3;
		
		var links = '<a id="product-70" class="-1">Yleismalli (410 x 419 mm)</a>';
		links += '<a id="product-71" class="-1">Yleismalli (420 x 520 mm)</a>';
		
		other_filter_selector(this, 'Karkeasuodattimen malli', links);
	});
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// print and bind other filter links

function other_filter_selector(obj, title, links)
{
	jQuery('#manufacturer-list a').removeClass('cover-list-selected');
	jQuery('#other-list a').removeClass('cover-list-selected');
	jQuery(obj).addClass('cover-list-selected');
	
	jQuery('#cover-selector-model h2').html(title);
	
	jQuery('#model-list').html(links);
	
	jQuery('#model-list a').bind('click', function(e) {
		selected_model = jQuery(this).attr('class').replace(' cover-list-selected', '');
		jQuery('#model-list a').removeClass('cover-list-selected');
		jQuery(this).addClass('cover-list-selected');
		print_product_table(jQuery(this).attr('id').replace('product-', ''));
	});
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// find dust bags is click handler

function find_dust_bags(obj, run_selector)
{
	jQuery(obj).addClass('active');
	jQuery('#search-home-filter').removeClass('active');

	jQuery('#manufacturer-list').html(manufacturers);
	selected_type = 1;
	
  jQuery('#other-to-vacuum').show();
  jQuery('#other-to-home').hide();


	if (run_selector)
	{
		product_selector();
	}
	
	jQuery('#cover-selector-manufacturer h2:first').html('Pölynimurin merkki');
	jQuery('#cover-selector-model h2').html('Pölynimurin malli');
	jQuery('#cover-selector-product h2').html('Valitsemaasi pölynimuriin sopivat tuotteet');
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// find home filters click handler

function find_home_filters(obj, run_selector)
{
	jQuery(obj).addClass('active');
	jQuery('#search-dust-bag').removeClass('active');

	jQuery('#manufacturer-list').html(manufacturers2);
	selected_type = 2;

  jQuery('#other-to-vacuum').hide();
  jQuery('#other-to-home').show();
    
	if (run_selector)
	{
		product_selector();
	}
	
	jQuery('#cover-selector-manufacturer h2:first').html('Ilmanvaihtokoneen valmistaja');
	jQuery('#cover-selector-model h2').html('Ilmanvaihtokoneen malli');
	jQuery('#cover-selector-product h2').html('Valitsemaasi ilmanvaihtokoneeseen sopivat tuotteet');
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// manufacturer click handler, populates model list

function print_model_table(manufacturer_id)
{
	var links = '';
	
	// generate model links
	for (model_id in model_manufacturers)
	{
		if (model_manufacturers[model_id] == manufacturer_id)
		{
			links += '<a id="product-' + model_products[model_id] + '" class="' + model_id + '">' + model_names[model_id] + '</a>';
		}
	}
	
	// print model links to screen
	jQuery('#model-list').html(links);
	jQuery('#model-list').css('height', '241px');
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// model click handler, populates product list

function print_product_table(product_id)
{
	if (product_id == 73)
	{
		// poistoilman suodatin
		var product = '<table cellspacing="0"><tr><th>Sini-<br/>tuotenumero</th><th>Tuotenimike<br/>&nbsp;</th><th>Pakkauskoko<br/>&nbsp;</th><th>Hinta /<br/>pakkaus</th><th>&nbsp;<br/>&nbsp;<th></tr>';
		product += '<tr><td id="effect">9500</td><td><a class="product-info" id="info-link-73">Pölynimurin poistoilman mikrosuodatin</a></td><td>1 kpl</td><td>5 €</td><td>';
		product += '<a class="product-basket" id="basket-link-73">Lisää ostoskoriin</a></td></tr></table>';
	}
	else if (product_id == 74)
	{
		// moottori suodatin
		var product = '<table cellspacing="0"><tr><th>Sini-<br/>tuotenumero</th><th>Tuotenimike<br/>&nbsp;</th><th>Pakkauskoko<br/>&nbsp;</th><th>Hinta /<br/>pakkaus</th><th>&nbsp;<br/>&nbsp;<th></tr>';
		product += '<tr><td id="effect">9600</td><td><a class="product-info" id="info-link-74">Pölynimurin moottorisuodatin</a></td><td>1 kpl</td><td>5 €</td><td>';
		product += '<a class="product-basket" id="basket-link-74">Lisää ostoskoriin</a></td></tr></table>';
	}
	else if (product_id == 75)
	{
		// hajunpoistaja
		var product = '<table cellspacing="0"><tr><th>Sini-<br/>tuotenumero</th><th>Tuotenimike<br/>&nbsp;</th><th>Pakkauskoko<br/>&nbsp;</th><th>Hinta /<br/>pakkaus</th><th>&nbsp;<br/>&nbsp;<th></tr>';
		product += '<tr><td id="effect">9800</td><td><a class="product-info" id="info-link-75">Pölynimurin hajunpoistaja. Aktiivihiilisuodatin</a></td><td>1 kpl</td><td>5 €</td><td>';
		product += '<a class="product-basket" id="basket-link-75">Lisää ostoskoriin</a></td></tr></table>';
	}
	else if (product_id == 76)
	{
		// ikkunasuodatin
		var product = '<table cellspacing="0"><tr><th>Sini-<br/>tuotenumero</th><th>Tuotenimike<br/>&nbsp;</th><th>Pakkauskoko<br/>&nbsp;</th><th>Hinta /<br/>pakkaus</th><th>&nbsp;<br/>&nbsp;<th></tr>';
		product += '<tr><td id="effect">9900</td><td><a class="product-info" id="info-link-76">Ikkunasuodatin</a></td><td>1 kpl</td><td>10 €</td><td>';
		product += '<a class="product-basket" id="basket-link-76">Lisää ostoskoriin</a></td></tr></table>';
	}
	else if (product_id == 77)
	{
		// liesituulettimensuodatin
		var product = '<table cellspacing="0"><tr><th>Sini-<br/>tuotenumero</th><th>Tuotenimike<br/>&nbsp;</th><th>Pakkauskoko<br/>&nbsp;</th><th>Hinta /<br/>pakkaus</th><th>&nbsp;<br/>&nbsp;<th></tr>';
		product += '<tr><td id="effect">9700</td><td><a class="product-info" id="info-link-77">Liesituulettimensuodatin</a></td><td>1 kpl</td><td>5 €</td><td>';
		product += '<a class="product-basket" id="basket-link-77">Lisää ostoskoriin</a></td></tr></table>';
	}
	else if (product_id == 70)
	{
		// karkeasuodatin
		var product = '<table cellspacing="0"><tr><th>Sini-<br/>tuotenumero</th><th>Tuotenimike<br/>&nbsp;</th><th>Pakkauskoko<br/>&nbsp;</th><th>Hinta /<br/>pakkaus</th><th>&nbsp;<br/>&nbsp;<th></tr>';
		product += '<tr><td id="effect">9410</td><td><a class="product-info" id="info-link-70">Karkeasuodatin leikattava yleismalli (410 x 419 mm)</a></td><td>1 kpl</td><td>10 €</td><td>';
		product += '<a class="product-basket" id="basket-link-70">Lisää ostoskoriin</a></td></tr></table>';
	}
	else if (product_id == 71)
	{
		// karkeasuodatin
		var product = '<table cellspacing="0"><tr><th>Sini-<br/>tuotenumero</th><th>Tuotenimike<br/>&nbsp;</th><th>Pakkauskoko<br/>&nbsp;</th><th>Hinta /<br/>pakkaus</th><th>&nbsp;<br/>&nbsp;<th></tr>';
		product += '<tr><td id="effect">9420</td><td><a class="product-info" id="info-link-71">Karkeasuodatin leikattava yleismalli (420 x 520 mm)</a></td><td>1 kpl</td><td>10 €</td><td>';
		product += '<a class="product-basket" id="basket-link-71">Lisää ostoskoriin</a></td></tr></table>';
	}
	else if (product_types[product_id] == 1)
	{
		count = '4 pussia';
		
		if (product_id == 72 || product_id == 9 || product_id == 10 || product_id == 37)
			count = '1 pussi';
			
		// generate product table
		var product = '<table cellspacing="0"><tr><th>Sini-<br/>tuotenumero</th><th>Tuotenimike<br/>&nbsp;</th><th>Pakkauskoko<br/>&nbsp;</th><th>Hinta /<br/>pakkaus</th><th>&nbsp;<br/>&nbsp;<th></tr>';
		product += '<tr><td id="effect">' + product_codes[product_id] + '</td><td><a class="product-info" id="info-link-' + product_id + '">Imurin pölypussi</a></td><td>' + count + '</td><td>10 €</td><td>';
		// add to basket link
		product += '<a class="product-basket" id="basket-link-' + product_id + '">Lisää ostoskoriin</a>';
	
		// poistoilman suodatin
		product += '</td></tr><tr><td>9500</td><td><a class="product-info" id="info-link-73">Pölynimurin poistoilman mikrosuodatin</a></td><td>1 kpl</td><td>5 €</td><td>';
		product += '<a class="product-basket" id="basket-link-73">Lisää ostoskoriin</a>';
	
		// moottorisuodatin
		product += '</td></tr><tr><td>9600</td><td><a class="product-info" id="info-link-74">Pölynimurin moottorisuodatin</a></td><td>1 kpl</td><td>5 €</td><td>';
		product += '<a class="product-basket" id="basket-link-74">Lisää ostoskoriin</a>';
	
		// moottorisuodatin
		product += '</td></tr><tr><td>9800</td><td><a class="product-info" id="info-link-75">Pölynimurin hajunpoistaja. Aktiivihiilisuodatin</a></td><td>1 kpl</td><td>5 €</td><td>';
		product += '<a class="product-basket" id="basket-link-75">Lisää ostoskoriin</a>';
	
		product += "</td></tr></table>";
	}
	else if (product_types[product_id] == 2)
	{
		// generate product table
		var product = '<table cellspacing="0"><tr><th>Sini-<br/>tuotenumero</th><th>Tuotenimike<br/>&nbsp;</th><th>Pakkauskoko<br/>&nbsp;</th><th>Hinta /<br/>pakkaus</th><th>&nbsp;<br/>&nbsp;<th></tr>';
		product += '<tr><td id="effect">' + product_codes[product_id] + '</td><td><a class="product-info" id="info-link-' + product_id + '">Kotisuodatin</a></td><td>1 kpl</td><td>' + product_price(product_id) + ' €</td><td>';
		// add to basket link
		product += '<a class="product-basket" id="basket-link-' + product_id + '">Lisää ostoskoriin</a>';
	
		// ikkuna suodatin
		//product += '</td></tr><tr><td>9900</td><td><a class="product-info" id="info-link-76">Ikkunasuodatin</a></td><td>1 kpl</td><td>10 €</td><td>';
		//product += '<a class="product-basket" id="basket-link-76">Lisää ostoskoriin</a>';
	
		// Liesituulettimensuodatin
		//product += '</td></tr><tr><td>9700</td><td><a class="product-info" id="info-link-77">Liesituulettimensuodatin</a></td><td>1 kpl</td><td>5 €</td><td>';
		//product += '<a class="product-basket" id="basket-link-77">Lisää ostoskoriin</a>';
	
		// Karkeasuodatin 1
		/*product += '</td></tr><tr><td>9410</td><td>Karkeasuodatin leikattava yleismalli (410 x 419 mm)</td><td>1 kpl</td><td>10 €</td><td>';
		product += '<a class="product-info" id="info-link-70">Katso tiedot</a> | ';
		product += '<a class="product-basket" id="basket-link-70">Lisää koriin</a>';*/
		
		// Karkeasuodatin 2
		product += '</td></tr><tr><td>9420</td><td><a class="product-info" id="info-link-71">Karkeasuodatin leikattava yleismalli (420 x 520 mm)</a></td><td>1 kpl</td><td>10 €</td><td>';
		product += '<a class="product-basket" id="basket-link-71">Lisää ostoskoriin</a>';
		
		product += "</td></tr></table>";
	}
	
	if (jQuery.trim(jQuery('.NavBarLeft .NavBarElement0 .ContextBoxBody').html()) != 'Ostoskorisi on tyhjä')
	{
		product += '<div id="continue-button"><a href="' + jQuery('.BasketLink').attr('href') + '">Jatka &raquo;</a></div>';
	}
	
	// print product table
	jQuery('#product-list').html(product);

	// bind product info click, opens modal dialog
	jQuery('.product-info').bind("click", function(e) { open_product_info(jQuery(this).attr('id').replace('info-link-', '')) });
	
	// bind add to basket click
	jQuery('.product-basket').bind("click", function(e) { add_product_to_basket(jQuery(this).attr('id').replace('basket-link-', '')) });
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// get procut price from product info page, AJAX

function product_price(product_id)
{
  var url = get_url() + '?ObjectPath=/Shops/19022009-129214/Products/' + product_codes[product_id];
	var price = '';
	
	// get product info page and parse dialog data
	jQuery.ajax({
					url: url,
					async: false,
					success: function(data) {
	
						// convert data to jQuery object for parsing
						var jQueryresponse = jQuery(data);
						
						price = jQueryresponse.find('.Price').html();
					}
	});
	return price.replace(',00 €', '');
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// opens modal product info dialog

function open_product_info(product_id)
{
	if (!product_id)
	{
		return;
	}
	
	// open dialog
	open_dialog(get_product_info(product_id), 'Tuotetiedot', 2, product_id);
	product_image_carousel();
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// empties basket

function empty_basket()
{ 
	var obj_id = jQuery('a.BasketLink').attr('href');
	
	/*jQuery.ajax({
					url: 'http://hermes.gagar.fi/epages/GPL.sf' + obj_id,
					async: false,
					success: function(data) {
						var jQueryresponse = jQuery(data);
						jQueryresponse.find('table.Basket a').each(function(idx, item) {
							if (jQuery(item).attr('href').indexOf('ChangeAction=Delete') > 0)
							{
							  
							  jQuery.ajax({
                  url: 'http://hermes.gagar.fi/epages/GPL.sf'+jQuery(item).attr('href'),
                  async: false
                 });
							}
						});
					}
	});*/
	alert('Siirryt ostoskoriin, jossa voit poistaa tuotteita tuoterivin päässä olevalla roskakori-kuvakkeella');
	
	document.location.href = get_url() + obj_id;
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// get product info from product page

function get_product_info(product_id)
{
	// make product info page's url
	var url = get_url() + '?ObjectPath=/Shops/19022009-129214/Products/' + product_codes[product_id];
	var html = '';
	
	// get product info page and parse dialog data
	jQuery.ajax({
					url: url,
					async: false,
					success: function(data) {
	
						// convert data to jQuery object for parsing
						var jQueryresponse = jQuery(data);
	
						// get title
						if (product_types[product_id] == 1)
						{
							html += '<div id="avainlippu"><img src="http://sinituote.redicom.fi/images/avainlippu.jpg"/></div>';
						}
						html += '<h1>' + jQueryresponse.find('.InfoArea .FullSize h1').html() + '</h1>';
						
						html += '<p>Paketin hinta: ' + jQueryresponse.find('.Price').html() + '</p>';
	
						// get body text
						html += '<p>' + jQueryresponse.find('.InfoArea .FullSize div:eq(1)').html();
						
						if (product_types[product_id] == 1)
							html += '<br/><a href="http://sinituote.redicom.fi/kaytto-ohje.html" target="_blank">Pölypussin käyttöohje</a>.</p>';
	
						// get image urls from external database value
						
						if (product_images[product_id])
						{
							var image_urls = product_images[product_id].split(';');

							var big_image = '';
							var small_images = '';
							
							for (var i = 0; i < image_urls.length; i++)
							{ 
								if (image_urls[i].indexOf('pussi') > 0 || image_urls.length == 1)
								{
									big_image = '<div class="dialog-big-image"><img onclick="open_product_image(this);" src="' + image_urls[i] + '"/></div>';
								}
								else
								{
									small_images += '<div class="dialog-small-image" id="dialog-small-img-' + i + '"><img src="' + image_urls[i] + '"/></div>';
								}
							}
							html += big_image;
							html += small_images;
						}
					}
	});
	
	return html;
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// opens big image from modal product info dialog to new window

function open_product_image(obj)
{
	window.open(jQuery(obj).attr('src'),
								'big_image',
								'width=780,height=800,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// print image carousel to modal procuct info dialog

function product_image_carousel()
{
	// product info dialogs image carousel
	// if small image is clicked, change it with big image and roll small images one step forward or backward
	jQuery('.dialog-small-image').bind("click", function(e) {
		
		var count = jQuery('.dialog-small-image').size();

		var src_big = jQuery('.dialog-big-image img').attr('src');

		/*if (jQuery(this).attr('id') == 'dialog-small-img-1')
		{
			var src_small = jQuery('#dialog-small-img-2 img').attr('src');
			jQuery('#dialog-small-img-2 img').attr('src', src_big);
		}
		else
		{
			var src_small = jQuery('#dialog-small-img-1 img').attr('src');
			jQuery('#dialog-small-img-1 img').attr('src', src_big);
		}*/
		
		jQuery('.dialog-big-image img').attr('src', jQuery(this).children().attr('src'));
		jQuery(this).children().attr('src', src_big);
	});
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// add product to basket

function add_product_to_basket(product_id)
{
	if (product_id == 10000)
	{
		code = '3348113';
	}
	else
	{
		code = epages_codes[product_id];
	}

	jQuery.ajax({type: "POST", url: "http://www.sininetkauppa.fi/epages/GPL.sf/?ObjectPath=/Shops/19022009-129214", data: "ChangeObjectID=" + code + "&ChangeAction=AddToBasket", async: false });
	
	if (product_id == 78 || product_id == 79)
	{
	  document.location.reload();
  }
  else
  {
	  document.location.href = 'http://www.sininetkauppa.fi/epages/GPL.sf/fi_FI/?ObjectPath=/Shops/19022009-129214&selected_type=' + selected_type + '&selected_man=' + selected_manufacturer + '&selected_model=' + selected_model + '&selected_product=' + product_id;
  }
   
	/*var url = get_url() + '?ChangeObjectID=' + code;
	url += '&ChangeAction=AddToBasket&LastViewObjectID=1581432&ViewAction=View
	
	document.location.href = url;
	/*jQuery.ajax({
						url: url,
						async: false,
						success: function(data) {
							refresh_basket();
						}
	});*/
	// add product to basket and replace current basket with updated one
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// refresh basket

function refresh_basket()
{
  
	jQuery.get(get_url() + '?ObjectPath=/Shops/19022009-129214', function(data) {
		var response = jQuery(data);
		
		response.find('.MiniBasket a').each(function(idx, item) {

			if (jQuery.trim(jQuery(item).html()) == 'Mikrokuit...')
			{
				var tmp = jQuery(item).attr('title').split(' ');
				var product_code = tmp[2];

				jQuery(item).html('mikrokuitupölypussia ' + product_code + '');
			}
		});
		
		jQuery('#empty-basket').show();
			
	  jQuery('.NavBarLeft .NavBarElement0').html(response.find('.NavBarLeft .NavBarElement0').html());
		jQuery('.BasketLink').bind("click", function(e) {
			link_parts = jQuery(this).attr('href').split('=');
			createCookie('basket_id', link_parts[1]);
		});
	});
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// search product by sini code

function search_by_product_number()
{
	// product search
	var product_parts = '';
	var options = '<option value="0">-- valitse --</option>';

	for (var i = 0; i < product_code_for_search.length; i++)
	{
		options += '<option value="' + product_id_for_search[i] + '">' + product_code_for_search[i] + '</option>';
	}

	jQuery("#product-search").html(options);

	// search box product info
	jQuery('#product-search').bind("change", function(e) { open_product_info(jQuery('#product-search').val()); });

	// search box help
	jQuery('#product-search-help a').bind("click", function(e) {
		
		var html = '<h1>Mistä löydän Sini-tuotenumeron</h1><p>Sini-tuotenumeron löydät pölypussipaketin mukana olevasta tuotekortista:</p>';
		html += '<img src="http://sinituote.redicom.fi/images/tuotekoodi-ohje.jpg">';
		
		// open dialog
		open_dialog(html, 'Sini-tuotenumero', 1, 0);
	});
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// send recommendation form

function send_recommendation()
{
	var html = "<h1>Suosittele Sinituotteen verkkokauppaa kaverille</h1><p>Tähän tekstiä</p><p>Kaikki kentät ovat pakollisia</p>";
	html += '<form id="recommendation-form" action="http://sinituote.redicom.fi/send_recommendation.php" method="get"><div class="form-column">';
	html += '<label for="receiver-name">Vastaanottajan nimi: *</label><br/><input type="text" size="30" name="receiver_name" id="receiver-name"/>';
	html += '<br/><label for="receiver-email">Vastaanottajan sähköposti: *</label><br/><input type="text" size="30" name="receiver_email" id="receiver-email"/>';
	html += '<br/><label for="sender-name">Oma nimi: *</label><br/><input type="text" size="30" name="sender_name" id="sender-name"/>';
	html += '<br/><label for="sender-email">Oma sähköposti: *</label><br/><input type="text" size="30" name="sender_email" id="sender-email"/></div>';
	html += '<div class="form-column"><label for="message">Viesti vastaanottajalle: *</label><br/><textarea name="message" id="recommend-message" cols="40" rows="15"></textarea></div></form>';

  open_dialog(html, 'Lähetä suositus', 3, 0);
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// send recommendation form submit

function submit_recommendation()
{
  if (jQuery('#receiver-name').val().length && jQuery('#receiver-email').val().length && jQuery('#sender-name').val().length && jQuery('#sender-email').val().length && jQuery('#recommend-message').val().length)
	{
		jQuery("#recommendation-form").submit();
	}
	else
	{
		alert('Kaikki kentät ovat pakollisia');
	}
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// text fixes, mostly payment steps

function fix_texts()
{
	// fix login box text
	jQuery('div.LoginBox div.InputLabelling:first').html('<p>Tilaaminen ei edellytä rekisteröitymistä</p><p>Käyttäjätunnus</p>');
	jQuery('div.LoginBox div.InputLabelling:eq(1)').html('<p style="padding-top: 8px">Salasana</p>');

	// registration header text
	jQuery('div.NewCustomer h3').replaceWith('<h1>Rekisteröityminen</h1><p>Rekisteröidy asiakkaaksemme verkkokauppaan. Yhteystietosi tallentuvat järjestelmään ja tulevat automaattisesti tilaajatietoihin. Saat halutessasi tietoa SINI-uutuuksista ja verkkokaupan tarjouksista.</p>');

	// fix some buttons to face to background better
	jQuery('.SearchMask form input').attr('src', '/WebRoot/GPL/SF/Icon/SimpleSymbols/ico_s_search.gif');
	
	// basket
	base = jQuery('#BasketForm .AlignCenter img').length * 6

	if (base)
	{	  
		for (var i = 0, j = 0; i < jQuery('#BasketForm .AlignCenter img').length; i++, j += 3)
		{
			jQuery('.SeparateColumn.Money:eq(' + (j) + ')').html('');
		}
	
		jQuery('.ContentArea #BasketForm .SeparateColumn').each(function(idx, item) {
			
			if (jQuery(item).html() == 'Maksutapa')
				jQuery(item).html('Verkkopankki');
			else if (jQuery.trim(jQuery(item).html()) == 'sis. ALV: Yleinen  (22 %)')
			 jQuery(item).html('Arvonlisäveron osuus hinnasta');
			else if (jQuery(item).html() == 'Yhteensä (ilman ALV)')
			 jQuery(item).parent().hide();	
			
			jQuery(item).children().each(function(idc, children) {
				if (jQuery(children).attr('href') && jQuery(children).attr('href').indexOf('/Products/'))
				jQuery(item).html(jQuery(children).html());
			});
		}); 
	}

  // piilota verkkopankki kuvake korin ensimmäisestä vaiheesta
  if (jQuery('li.ActiveItem .ItemLabel').html() == '1. Ostoskori')
  {
    jQuery('ul.OrderProcess li:eq(3) img').hide();
    jQuery('ul.OrderProcess li:eq(3) .ExplainItem').html('Verkkomaksu');
  }
  
   // Korosta verkkopankista palaamista maksun vaiheessa 4
  if (jQuery('li.ActiveItem .ItemLabel').html() == '4. Maksu')
  {
    jQuery('.BasketDetails div:eq(1)').html('Siirry verkkopankkiin. Maksu tapahtuu suojatun yhteyden avulla suoraan pankkiin, pelkästään maksutieto välittyy kauppiaalle.<p><b>Suoritettuasi maksun, muista painaa painiketta: "Palaa myyjän palveluun", jotta tilauksesi kirjautuu.</b></p>');
  }
  
	jQuery('.SeparateColumn.Money').each(function(idx, item) {
		if (jQuery(item).html() == '2,50 €')
			jQuery(item).html('');
	});
	
	var keep_all_delivery_methods = false;
	var hide_letter_delivery = false;
	var product_name = '';
	var show_coupon = false;
	var filter_no = '';
	
	jQuery("tr.ProductItem").each(function(idx, item) {
	  
		//product_name = jQuery(item).parent().parent().children().eq(1).html();
		product_name = jQuery(item).find('a').text();
		
		if (product_name.indexOf('ikrokuitupölypussi') == -1 && product_name.indexOf('kkunasuodatin') == -1
		    && product_name.indexOf('iesituulettimensuodatin') == -1 && product_name.indexOf('moottorisuodatin') == -1 
		    && product_name.indexOf('mikrosuodatin') == -1 && product_name.indexOf('Aktiivihiilisuodatin') == -1)
		{
			keep_all_delivery_methods = true;
		}
		/*if (product_name.indexOf('otisuodatin') > 0 || product_name.indexOf('kkunasuodatin') > 0 
				|| product_name.indexOf('iesituulettimensuodatin') > 0 || product_name.indexOf('arkeasuodatin') > 0)*/
		if (product_name.indexOf('otisuodatin') > 0 || product_name.indexOf('arkeasuodatin') > 0)
		{
			hide_letter_delivery = true;
		}
		
		if (product_name.indexOf('otisuodatin') > 0)
		{
		  show_coupon = true;
		  var link = jQuery(item).find('a').attr('href');
		  filter_no = link.substr(link.length - 4);
		}
		
		if (product_name.indexOf('kampanja') > 0)
		{
		  jQuery(item).replaceWith('1');
		  show_coupon = false;
		}
	});
	
	// coupong code handling
	if (show_coupon)
	{
    jQuery('#CouponCode').after('<input type="button" value="Lunasta" id="use-coupong"');
    
    if (filter_no == '9221' || filter_no == '9224' || filter_no == '9220')
    {
      jQuery('#use-coupong').bind("click", function(e) 
      {
        if (jQuery('#CouponCode').val() == 'suodatin')
        {
          add_product_to_basket(79); // 9410 karkea suodatin
        }
        else
        {
          alert('Väärä koodi!');
        }
      });
    }
    else
    {
      jQuery('#use-coupong').bind("click", function(e) 
      {
        if (jQuery('#CouponCode').val() == 'suodatin')
        {
          add_product_to_basket(78); // 9420 karkea suodatin
        }
        else
        {
          alert('Väärä koodi!');
        }
      });
    }
  }
  else
  {
    jQuery('#CouponCode').parent().prev().html('');
    jQuery('#CouponCode').hide();
  }
  
	if (!keep_all_delivery_methods)
	{
		jQuery("select[name='ShippingMethod'] :eq(1)").remove();
		jQuery("select[name='ShippingMethod'] :eq(1)").remove();
	}

	if (hide_letter_delivery)
	{
		jQuery("select[name='ShippingMethod'] option:first").remove();
		
		jQuery("select[name='ShippingMethod']").parent().parent().siblings('.Money').html('4,50 €');
		
		var total = parseFloat(jQuery('td.Total').html().replace(' €', ''));
		var vat = (total - (total / 1.23)).toFixed(2).replace('.', ',');
    var totalWoVat = (total / 1.23).toFixed(2).replace('.', ',');
    
		total += 4.50;

		var newVat = (total - (total / 1.23)).toFixed(2).replace('.', ',');
    var newTotalWoVat = (total / 1.23).toFixed(2).replace('.', ',');

		jQuery('td.Total').html(total.toFixed(2).replace('.', ',') + ' €');

		jQuery('td.Money').each(function(idx, item) {
			if (jQuery.trim(jQuery(item).html()) == totalWoVat + ' €')
				jQuery(item).html(newTotalWoVat + ' €');
		  if (jQuery.trim(jQuery(item).html()) == vat + ' €')
				jQuery(item).html(newVat + ' €');
		});	
	}
	
	// add products link
	jQuery('ul.OrderProcess').after('<p align="center"><a href="' + get_url() + '?ObjectPath=/Shops/19022009-129214">&laquo; Lisää tuotteita ostoskoriin</a></p>');

	if (jQuery.trim(jQuery('.TableHead:eq(3) div').html()) == 'Haluatko määrittää tilin samalla kertaa?')
	{
		jQuery('.TableHead:eq(3)').hide();
	}

  if (jQuery.trim(jQuery('.SizeContainer:eq(5) div').html()) == 'Rekisteröityneen asiakkaan edut:')
	{
		jQuery('.SizeContainer:eq(5) div:first').hide();
	}

	jQuery('.MiniBasket a').each(function(idx, item) {
		
		if (jQuery.trim(jQuery(item).html()) == 'Mikrokuit...')
		{
			var tmp = jQuery(item).attr('href').split('/');
			var product_code = tmp[4];
			
			jQuery(item).replaceWith('mikrokuitupölypussia ' + product_code + '');
		}
		if (jQuery.trim(jQuery(item).html()) == 'Kotisuoda...')
		{
			var tmp = jQuery(item).attr('href').split('/');
			var product_code = tmp[4];
			
			jQuery(item).replaceWith('kotisuodatin ' + product_code + '');
		}
		if (jQuery.trim(jQuery(item).html()) == 'Ikkunasuo...')
		{
			jQuery(item).replaceWith('ikkunasuodatin');
		}
		if (jQuery.trim(jQuery(item).html()) == 'Liesituul...')
		{
			jQuery(item).replaceWith('liesit. suodatin');
		}
		if (jQuery.trim(jQuery(item).html()) == 'Karkeasuo...')
		{
			jQuery(item).replaceWith('karkeasuodatin');
		}
		if (jQuery(item).attr('title').indexOf('Pölynimurin moottorisuodatin') != -1)
		{
			jQuery(item).replaceWith('moottorisuodatin');
		}
		if (jQuery(item).attr('title').indexOf('Pölynimurin poistoilman mikrosuodatin') != -1)
		{
			jQuery(item).replaceWith('mikrosuodatin');
		}
		if (jQuery(item).attr('title').indexOf('Pölynimurin hajunpoistaja') != -1)
		{
			jQuery(item).replaceWith('hajunpoistaja');
		}
	});
	
	jQuery('.NavBarLeft .NavBarElement4 .ContextBoxHead span').html('Kirjautuminen - <a href="#" id="show-login">Näytä</a>');
	jQuery('.NavBarLeft .NavBarElement4 .ContextBoxBody').hide();
	jQuery('#show-login').bind("click", function(e) {
		jQuery('.NavBarLeft .NavBarElement4 .ContextBoxBody').toggle();
		return false;
	});
	
	jQuery('.BasketAddressForm label').each(function(idx, item) {
		if (jQuery(item).attr('for') == 'EnableShippingAddress')
		{
			jQuery(item).html('Haluatko toimituksen muuhun kuin tilaajan osoitteeseen');
		}
	});
	
  jQuery('div.InputLabelling:eq(19)').html('<div id="direct-marketing">Minulle saa  lähettää  puolen vuoden välein muistutuksen ostamistani tuotteista</div>')
	jQuery('div.InputLabelling:eq(19)').css('display', 'inline');
	jQuery('div.InputLabelling:eq(19)').css('width', '600px');
	
	jQuery('#sahkopostilupa_on').parent().css('clear', 'both');
	jQuery('#sahkopostilupa_on').parent().css('margin-top', '1em');
	
	jQuery('a.BasketLink:eq(1)').hide();
	
	if (jQuery.trim(jQuery('.NavBarLeft .NavBarElement0 .ContextBoxBody').html()) == 'Ostoskorisi on tyhjä')
	{
	  jQuery('.NavBarLeft .NavBarElement0').hide();
	  jQuery('.NavBarLeft .NavBarElement1').css('margin-top', '-15px');
	}
	
	jQuery('.TableHead div').each(function(idx, item) {
	  if (jQuery.trim(jQuery(item).html()) == 'Oletko jo rekisteröitynyt?')
    {
      jQuery(item).html('Oletko jo rekisteröitynyt? (ei pakollinen)');
    }
  });
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// update product to external database

function update_external_database()
{ 
	// add or update products to external database
	if (jQuery('.UserAttributes').is(':visible') && location.href.indexOf('product_updated') == -1)
	{

		var images = '';
	
		jQuery('div.SlideShowPreview a').each(function(idx, item) {
			if (images.length)
				images += ';';
			
			images += jQuery(item).attr('href');
		});
	
		var sini_code = jQuery.trim(jQuery('.AttributeContent').html());

		if (sini_code)
		{
			var form = '<form id="add-product-form" action="http://sinituote.redicom.fi/product_viewer/add_product.php" method="post">';
			form += '<input type="hidden" name="sini_code" value="' + sini_code + '"/>';
			form += '<input type="hidden" name="images" value="' + images + '"/>';
			form += '<input type="hidden" name="epages_code" value="' + epages.vars.ObjectID + '"/>';
			form += '<input type="hidden" name="href" value="' + location.href + '"/>';
			form += '</form>';
		
			jQuery('.AttributeContent').html(form);
			jQuery('#add-product-form').submit();
		}
		else
		{
			alert('Lisäkentät kohdasta puuttuu Sini-tuotenumero!');
		}
	}
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// open dialog

function open_dialog(html, title, buttons, product_id)
{
  switch(buttons)
  {
    case 1:
      var buttons = '<a onclick="close_dialog();">Sulje</a>';
      break;
    case 2:
      var buttons = '<a onclick="close_dialog();">Sulje</a><a onclick="add_product_to_basket(' + product_id + ');">Lisää ostoskoriin</a>';
      break;
    case 3:
      var buttons = '<a onclick="close_dialog();">Sulje</a><a onclick="submit_recommendation()">Lähetä suositus</a>';
      break;
  }
  jQuery("#dialog").html('<div id="inner-dialog">' + html + '</div><div id="dialog-buttons">' + buttons + '</div>');
  jQuery("#dialog").show();
	jQuery('#product-search').hide();
	jQuery('.flash-element').hide();
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// close dialog

function close_dialog()
{
  jQuery("#dialog").hide();
  jQuery('#product-search').show(); 
  jQuery('.flash-element').show(); 
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// get url

function get_url()
{
  //var url_parts = document.location.href.split('?');
  var url_parts = jQuery('.NavBarElement2 a').attr('href').split('?');
  //alert(jQuery('.NavBarElement2 a').attr('href'));
  if (url_parts.length == 0)
  {
    return 'http://www.sininetkauppa.fi/epages/GPL.sf/';
  }
  else
  {
    return url_parts[0];
  }
}

count++;
