
$(document).ready(function() {

	Session.load();

	/* CSS3 stuff (sadly we have to do this by js) */

	$('UL LI:first-child').addClass('first-child');
	$('UL LI:last-child').addClass('last-child');

	/* For IE6 */
	$('.sidebar .section:first-child').addClass('section-first-child');
	$('.hotspottable .hotspot').hover(function() {
		$(this).addClass('hotspot-hover');
	}, function() {
		$(this).removeClass('hotspot-hover');	
	});

	$('.content .one_third_column:nth-child(3n+2)').css('margin', '0 34px');

	$('.content .tuotteet LI:nth-child(2n)').css('borderRight', '0');
	var last = $('.content .tuotteet LI:last-child').css('borderBottom', '0');
	if (last.length && last.prev().length && last.offset().top == last.prev().offset().top)
		// no bottom border for items in last row
		last.prev().css('borderBottom', '0');


	$('.sidebar UL.navi').each(function() {
		if ($('LI', this).length == 0)
			$(this).hide();
	});

	/* Don't submit empty fields, keep GET query shorter */
	$('FORM.skip_empty_fields').submit(function() {
		$(':input', this).each(function() {
			if ($(this).val() == '')
				$(this).attr('disabled', true);
		});
		return true;
	});
	
	/* Don't submit 'display: none' fields, they are unrelevant */
	$('FORM.skip_invisible_fields').submit(function() {
		$(':input', this).each(function() {
			if ($(this).css('display') == 'none')
				$(this).attr('disabled', true);
		});
		return true;
	});
	
	$('FORM.validate').submit(validate_form);

	$('SELECT.empty_option').each(function() {
		$(this).prepend($(document.createElement('option')).attr('value', '').text('Valitse'));
	});

	$('A.email').each(function() {
		// remove .com postfix and reverse
		var t = $(this).text();
		var decrypted = t.substring(0, t.length - 4).split("").reverse().join("");
		$(this).text(decrypted);
		$(this).attr('href', 'mailto:' + decrypted);
	});
	
	/* Select an OPTION according to value from SELECT.preselect_from_get_VALUE */
	$('SELECT.preselect').each(function() {
		var param_match = this.className.match(/preselect_from_get_([^ ]+)/);
		if (param_match && param_match.length > 1) {
			var param = param_match[1];
			var href_match = document.location.href.match(new RegExp('[\?\&]' + param + '=([^\&]+)'));
			if (href_match && href_match.length > 1) {
				$('OPTION[value=' + decodeURIComponent(href_match[1]) + ']').attr('selected', true);
			}
		}
	});

	$('SELECT.visibility-controller').change(function() {
		$('SELECT.visibility-controlled', this.parentNode).not(this).hide().attr('disabled', true);
		$('.show-' + this.options[this.selectedIndex].value.toLowerCase().replace(/[^a-z0-9]/, ''),
			this.parentNode).show().attr('disabled', false);
	}).trigger('change');
	
	$('SELECT.sorted').sortOptions(true, 1);

	/* Show logout link for professionals */
	if ($('BODY.pro').length > 0) {
		var li = $(document.createElement('li'));
		var a = $(document.createElement('a'))
			.attr('href', '/kirjaudu_ulos?ngform_on=1&q0=' + $.cookie('pro_sid'))
			.text('Kirjaudu ulos')
			.appendTo(li);
		$('.header .shortcuts').append(li);
	}
	
	$('.latis-colorcode').each(function() {
		var colors = {
			APR: 'Aprikoosin värinen',
			BEI: 'Beige',
			COT: 'Coton värinen',
			HAR: 'Harmaa',
			KEL: 'Keltainen',
			LIL: 'Liila',
			MET: 'Metalli',
			MUS: 'Musta',
			ORA: 'Oranssi',
			PER: 'Persikan värinen',
			PUN: 'Punainen',
			RUS: 'Ruskea',
			SIN: 'Sininen',
			VAL: 'Valkoinen',
			VIH: 'Vihreä'
		}
		$(this).text(colors[$(this).text().substring(0, 3).toUpperCase()]).css('visibility', 'visible');
	});

	$('.latis-sizecode').each(function() {
		var code = $(this).text();
		var r = /([0-9]+)X([0-9]+)/;
		var match = r.exec(code);
		if (match && match.length == 3) {
			if (this.tagName.toLowerCase() == 'option') {
				$(this).val(match[1] + 'X' + match[2]);
			}
			$(this).text('Kokoluokka: ' + match[1] + ' x ' + match[2] + ' cm');
		} else {
			$(this).remove();
		}
	});
	
	$('SELECT.remove-duplicates').each(function() {
		var uniques = {};
		$('OPTION', this).each(function() {
			if (uniques[$(this).val()])
				$(this).addClass('to-be-removed');
			else
				uniques[$(this).val()] = true;
		});
		$('OPTION.to-be-removed', this).remove();
	});

	$('A.popup').click(function(e) {
		e.preventDefault();
		img_popup($(this).attr('href'));
	}).attr('title', 'Klikkaa suurempi kuva');

	$('INPUT[type=text].value-as-label').blur(function() {
		$(this).val($(this).attr('title'));
		$(this).addClass('low-contrast');
	});

	$('INPUT[type=text].value-as-label').focus(function() {
		$(this).val('');
		$(this).removeClass('low-contrast');
	});

	$('INPUT[type=text].value-as-label').trigger('blur');

	$('FORM.auto-submit SELECT').change(function() { this.form.submit() });
	
	$('FORM.ajax').submit(function() {
		var form = this;
		var params = {};
		$(':input', form).each(function() { params[$(this).attr('name')] = $(this).val() });
		jQuery.get($(form).attr('action'), params, function(response) {
			if (response.indexOf('OK') != -1) {
				$('.msg-ok', form).show();
				$('.msg-error', form).hide();
				$(':input', form).attr('disabled', true);
			} else {
				$('.msg-ok', form).hide();
				$('.msg-error', form).show();
			}
		});
		return false;
	});

	if ($(document).height() > 1200) $('#scroll-top').show();  // keep this last

});

var Session = {
	
	params: {},
	cookie_name: 'session',
	
	load: function() {
		var cookie = $.cookie(this.cookie_name);
		if (cookie) {
			var pairs = cookie.split('&');
			$.each(pairs, function() {
				var p = this.split('=');
				Session.params[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
			});
		}
	},
	
	store: function() {
		var pairs = [];
		for (key in this.params)
			pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(this.params[key]));
		if (pairs.length > 0)
			$.cookie(this.cookie_name, pairs.join('&'), { expires: 30, path: '/' });
	},
	
	save: function(key, val) {
		this.params[key] = val;
		this.store();
	},
	
	get: function(key, default_value) {
		return this.params[key] != undefined ? this.params[key] : default_value;
	}
}

function img_popup(src) {

	var popup = new Popup();

	var img = $(document.createElement('img'))
		.attr('src', src)
		.addClass('picture');
		
	popup.append(img);

	if ($('A.popup').length > 1) {

		var navi = $(document.createElement('div'))
			.addClass('navi');

		popup.append(navi);
			
		$('A.popup').each(function(index) {
			var a = $(document.createElement('a'))
				.attr('href', $(this).attr('href'))
				.addClass($(this).attr('href') == src ? 'current' : '')
				.appendTo(navi)
				.text(index + 1)
				.click(function(e) {
					e.preventDefault();
					$(this).parents('.popup').find('.picture').attr('src', $(this).attr('href'));
					$('a', this.parentNode).removeClass('current');
					$(this).addClass('current');
				});
		});
		
		var next = $(document.createElement('img'))
			.attr('src', '/files/laattapiste/img/arrow_right.png')
			.addClass('clickable next')
			.css('height', '10px')
			.appendTo(navi)
			.click(function() { $('.current', navi).next('a').click(); });
	
		var prev = $(document.createElement('img'))
			.attr('src', '/files/laattapiste/img/arrow_left.png')
			.addClass('clickable prev')
			.css('height', '10px')
			.prependTo(navi)
			.click(function() { $('.current', navi).prev('a').click(); });

		$(document).keydown(function(e) {
			// next on right arrow or space
			if (e.which == 39 || e.which == 8) $(next).click();		

			// prev on left arrow or backspace
			else if (e.which == 37 || e.which == 13) $(prev).click();
		});

	}
	
	popup.show();
}

function validate_form() {
	$('INPUT.required, TEXTAREA.required', this).each(function() {
		if ($(this).val() == '') {
			$(this).addClass('error');
		} else {
			$(this).removeClass('error');	
		}
	});
	if ($(this).find('.error').length > 0) {
		window.alert('Ole hyvä ja täytä vaaditut kentät.');
		$(this).find('.error').shake().get(0).focus();
		return false;
	}
	return true;
}

function sort_select(select) {
	var options = {};
	var names = [];
	$('OPTION', select).each(function() {
		var name = $(this).text();
		options[name] = this;
		names.push(name);
	});
	var sorted = names.sort();
	
}


/* Popup object */

Popup = function(element) {
	this.create();
	this.append(element);
}

Popup.prototype.close = function() {
	this.popup.hide();
	this.shadow.hide();
}

Popup.prototype.create = function() {

	var shadow = $(document.createElement('div'))
		.addClass('shadow')
		.height($(document).height())
		.text('&nbsp;')
		.appendTo(document.body);

	var popup = $(document.createElement('div'))
		.addClass('popup')
		//.appendTo('.content');
		.appendTo('BODY');

	popup.css('left', $('BODY').width()/2 - popup.width()/2);
	
	var _this = this;

	var close = $(document.createElement('img'))
		.attr('src', '/files/laattapiste/img/image_popup_close.png')
		.addClass('close clickable')
		.click(function() { _this.close() })
		.appendTo(popup);
		
	$(document).keydown(function(e) {
		if (e.which == 27) _this.close();  // close by esc
	});
	
	this.popup = popup;
	this.shadow = shadow;
}

Popup.prototype.show = function() {
	this.popup.show();
	this.shadow.show();
}

Popup.prototype.append = function(elements) {
	this.popup.append(elements);
}


/* jQuery extensions */

jQuery.fn.shake = function(speed, offset) {
	speed = speed || 100;
	offset = offset || 5;
	var fx = [ offset, offset * -1, 0 ];
	return this.each(function() {
		var orig = parseInt($(this).css('marginLeft')) || 0;
		for (var i = 0; i < fx.length; i++) {
			$(this).animate({ marginLeft: orig + fx[i] + 'px' }, speed, 'swing');
		}
	});
};


/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1}var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000))}else{date=options.expires}expires='; expires='+date.toUTCString()}var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('')}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break}}}return cookieValue}};


/*
 * Copyright (c) 2006 Sam Collett (http://www.texotela.co.uk)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * Addepted to select an option by Mathias Bank (http://www.mathias-bank.de)
 */

jQuery.fn.sortOptions = function(ascending, skip)
{
	var start_from = skip || 0;
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return;
			ascending = typeof ascending == "undefined" ? true : ascending;
			var optionsLength = this.options.length;
			var sortArray = [];
			for(var i = start_from; i<optionsLength; i++)
			{
				sortArray.push(
				{
					value: this.options[i].value,
					text: this.options[i].text
				});
			}
			sortArray.sort(
				function(option1, option2)
				{
					option1text = option1.text.toLowerCase();
					option2text = option2.text.toLowerCase();
					if(option1text == option2text) return 0;
					if(ascending)
					{
						return option1text < option2text ? -1 : 1;
					}
					else
					{
						return option1text > option2text ? -1 : 1;
					}
				}
			);
			for(var i = start_from; i<optionsLength; i++)
			{
				this.options[i].text = sortArray[i - start_from].text;
				this.options[i].value = sortArray[i - start_from].value;
			}
		}
	)
	return this;
}

