jQuery.noConflict();

Cufon.replace('#content h1, #sidebar h3, .four-columns h2');
Cufon.replace('.carousel .nav a');

/* Replace PNG images by VML objects for IE6 */
if (window.DD_belatedPNG) {
	DD_belatedPNG.fix('#logo, #content, #toolbar, #toolbar .tool, \
		#menu, #menu li, #menu .handle, #menu .nav, #menu-shadow-1, #menu-shadow-2, \
		dl.faq .toggle, .tooltip, .save, #front-news li, #footer, #salkku-content td button');
}

(function($) {

$(function() {

	if (window.DD_belatedPNG) {
		setTimeout(function() { $('#menu-shadow-2').height($('#menu').height() - 75); }, 10);  // don't ask...
	}
	

	$('#bg-left, #bg-right').height($(document).height());


	/* Parse & reformat tabbed gallery from tinymce generated code */
	
	window.hookGallery = function() {
		$('.tabbed-gallery').each(function() {
			var tabs = [];
			var tab = [null, null, null];
			var gallery = $(this);
			gallery.find('br').remove();
			gallery.children().each(function(i) {
				if ($(this).children().length == 0 && $(this).text() == '') return true;
				if (this.tagName.toLowerCase().match(/^h[1-6]/)) {
					// found title
					tab[0] = $(this).text();
				} else if (this.tagName.toLowerCase() == 'img') {
					// found image
					tab[1] = this;
				} else if ($(this).find('img').length > 0) {
					// found image
					tab[1] = $(this).find('img');
				} else if ($(this).text() != '' && tab[0] && tab[1]) {
					// found legend
					tab[2] = $(this).text();
					tabs.push(tab);
					tab = [null, null, null];				
				}
			});
			gallery.empty();
			var head = $('<div />').addClass('head salkku-skip').appendTo(gallery);
			$.each(tabs, function() {
				head.append($('<h3 />').text(this[0]).click(function() {
					$(this).addClass('current').siblings().removeClass('current');
					var idx = $(this).prevAll().length;
					$('.tab', gallery).eq(idx).show().siblings('.tab').hide();
				}));
				gallery.append(
					$('<div />').addClass('tab')
						.append($('<h3 />').text(this[0]))
						.append(this[1])
						.append($('<p />').addClass('legend').text(this[2]))
				);
			});
			$(':first', head).click();
			gallery.css('visibility', 'visible');
		});
	};
	
	hookGallery();
	
	/* Text input default text functionality */
	
	$('.autoclear').focus(function() {
		if ($(this).val() == $(this).attr('title'))
			$(this).val('').removeClass('autoclear-default');
	}).blur(function() {
		if ($(this).val() == '' || $(this).val() == $(this).attr('title'))
			$(this).val($(this).attr('title')).addClass('autoclear-default');
	}).each(function() {
		$(this).blur();
	});
	
	
	/* Navigation menu sliding */
	
	$('#menu .handle').click(function(e) {
		e.preventDefault();
		var menu = $(this.parentNode);
		var closed = ! menu.hasClass('open');
		menu.animate({ marginLeft: (closed ? 0 : 129) }).toggleClass('open');
		$.cookie('menu', closed ? 1 : 0, { path: '/', expire: 180 });  // closed inverted intentionally
	});
	
	
	/* Toggle faq answers, scroll to question if anchor found in url */
	
	$('ul.faq').each(function() {
		$('.toggle', this).click(function() {
			var li = $(this).parents('li:first');
			li.find('.full').show();
			li.find('.short').hide();
		});
		var m = window.location.href.match(/#avaa-([0-9]+)/);
		if (m && m[1]) {
			$('a[href$=' + m[1] + ']').click();
			$.scrollTo('#kysymys-' + m[1], 1000);
		}
	});
		
	
	/* Bind dictionary toggle, save/restore status from cookie */

	$('#toolbar .dictionary').click(function(e) {
		e.preventDefault();
		$('body').toggleClass('dict-enabled');
		$.cookie('putkiremontti-dictionary', $('body').hasClass('dict-enabled') ? 1 : 0, { path: '/' });
	}).each(function() {
		$('body').toggleClass('dict-enabled', $.cookie('putkiremontti-dictionary') !== '0');
	});
	

	/* Replace dictionary words */

	$('#content').nonLinkTextNodes().each(function() {
		var original = this.data;
		var replaced = original;
		var dict = window.dictionary || [];
		for (var i = 0; i < dict.length; i++) {
			var re = dict[i][0];
			var desc = dict[i][1];
			replaced = replaced.replace(re, '<span class="dict" title="' + desc + '">$1</span>');
		}
		if (original != replaced) $(this).replaceWith($('<span />').html(replaced));
	});

	
	/* Show bubble for dictionary words */
	
	$('span.dict').hover(function() {
		if (! $('body').hasClass('dict-enabled')) return;
		var word = $(this);
		var bubble = $('.bubble', this);
		word.addClass('hover');
		setTimeout(function() {
			if (word.hasClass('hover')) bubble.show().parent().css('zIndex', 100000);
		}, 250);
	}, function() {
		$(this).removeClass('hover').find('.bubble').hide().parent().css('zIndex', 1);
	}).each(function() {
		var inner = $('<span/>').addClass('inner').text($(this).attr('title'));
		var bubble = $('<span/>').addClass('bubble').append(inner).appendTo(this);
		$(this).attr('title', '');
	});
	if (window.DD_belatedPNG) DD_belatedPNG.fix('.bubble, .bubble div');
	
	
	/* Save fontsize into cookie */

	$('#textsize li').click(function() {
		var li = $(this);
		var m = this.className.match(/textsize\-[^ ]+/);
		if (m) {
			li.addClass('current').siblings().removeClass('current');
			$.cookie('textsize', m[0], { path: '/', expires: 180 });
			document.body.className = document.body.className.replace(/textsize\-[^ ]+/g, '');
			$('body').addClass(m[0]);
			Cufon.refresh();
		}
	});
	

	/* Rate page usefulness */
	
	$('#rate').submit(function() {
		var form = $(this);
		var ta = $('textarea.autoclear');
		if (ta.val() == ta.attr('title')) ta.attr('disabled', 'disabled');
		$('<input type="hidden" name="ngform_on" value="1" />').prependTo(form);
		$('fieldset', form).hide();
		$('.sending', form).show();
		$.post(form.attr('action'), form.serialize(), function(data, status) {
			setTimeout(function() {
				$('.sending', form).hide();
				$('.thanks', form).show();
			}, 1000);
		});
		return false;
	}).each(function() {
		$('button.no', this).click(function() {
			$('#rate .useful').val(0);
			$('#rate .extra').show();
			$('#rate .extra textarea');
		});
		$('button.yes', this).click(function() {
			$('#rate .useful').val(1);
		});
	});


	/* Image carousel */
	
	$('.carousel').each(function() {
		var ms_interval = $(this).class_attr('interval') | 4000;
		var ms_fade = $(this).class_attr('fade') | 1000;
		var viewport = $('.viewport', this);
		var frames = $('.frame', viewport);
		var nav = $('.nav', this);
		if (frames.length > 1) {
			var pause = false;
			var show = function(frame_next) {
				var frame_curr = $('.frame:last', viewport);
				try { frame_curr.before(frame_next); } catch (e) {};
				$('a[href$=#' + frame_next.attr('id') + ']', nav)
					.addClass('current').siblings().removeClass('current');
				frame_curr.fadeOut(ms_fade, function() {
					$(this).prependTo(viewport).show();
				});		
			}
			frames.each(function(i) {
				var id = $(this).attr('id');
				$('<a />').text(frames.length - i).attr('href', '#' + id).click(function(e) {
					e.preventDefault();
					pause = true;
					show($('#' + id));
					setTimeout(function() { pause = false }, 10000);
				}).addClass(i == frames.length - 1 ? 'current' : '').appendTo(nav);
			});
			Cufon.replace('.carousel .nav a');
			setInterval(function() {
				var a = $('a:first', nav).hasClass('current') ? $('a:last', nav) : $('a.current', nav).prev();
				if (! pause) show($('#' + a.attr('href').split('#')[1]));
			}, ms_interval);
		}
	});
	
	
	/* Replace title-attribute by fancy tooltip */
	
	$('.tooltipped').each(function() {
		var tooltip = $('<div />').addClass('tooltip').append($('<div />').addClass('inner').text($(this).attr('title')));
		$(this).attr('title', '').append(tooltip);
	}).hover(function() {
		$('.tooltip', this).show();
	}, function() {
		$('.tooltip', this).hide();
	});
	

	/* Apply some styling for tinymce elements */
	
	$('#sidebar p a, .editable p a').each(function() {
		if ($(this).text() == $(this).parent().text()) $(this).addClass('read-more');
	});
	

	/* Validate & submit ajax forms */

	$('form.ajax').submit(function() {
		var f = $(this);
		$('.required', f).each(function() { $(this).toggleClass('invalid', $(this).val() == '') });
		var invalid = $('.invalid', f);
		if (invalid.length > 0) {
			alert('Ole hyvä ja täytä tähdellä merkityt kentät');
			invalid.eq(0).focus();
		} else {
			$('.busy', f).show();
			if (f.hasClass('mail')) f.append($('<input type="hidden" name="mail_sendnow" value="1" />'));
			$.post(f.attr('action'), f.serialize(), function() {
				f.hide().find('.busy').hide();
				var thanks = $('#' + f.attr('id').replace(/form/, 'thanks'));
				thanks.show();
				if (thanks.hasClass('autofade')) setTimeout(function() { thanks.fadeOut(1000); }, 3000);
			});
		}
		return false;
	});
	

	/* Bind save-to-tietosalkku links */

	var update_salkku_counter = function() {
		salkku.count(function(count) {
			$('#toolbar .portfolio .count').css('visibility', 'visible').find('.value').text(count);					
		});
	}
	
	var salkku_item_anim = function(item, cb) {
		var target = $('#toolbar .portfolio');
		$('<div />').addClass('salkku-anim')
			.css('width', item.width())
			.css('height', item.height())
			.css('left', item.position().left)
			.css('top', item.position().top)
			.appendTo($('#document'))
			.animate({ width: 1, height: 1, top: target.position().top, left: target.position().left + (target.width() / 2) }, 500, cb);
	}
	
	$('.save-page').each(function() {
		var link = $(this);
		var item = $('#content .salkku-item:first');
		salkku.has_item(item, function(has) {
			link.addClass(has ? 'saved' : 'unsaved');
		});
		link.click(function(e) {
			e.preventDefault();
			item.attr('title', $('h1', item).text()).attr('href', window.location.href);
			salkku.add_item(item, function() {
				salkku_item_anim(item, function() {
					$(this).hide();
					link.addClass('saved').removeClass('unsaved');
					update_salkku_counter();
				});
			});
		});
	});

	$('.save-faq').each(function() {
		var link = $(this);
		var item = $(this).parents('.salkku-item:first');
		salkku.has_item(item, function(has) {
			link.addClass(has ? 'saved' : 'unsaved');
		});
		link.click(function(e) {
			e.preventDefault();
			item.attr('title', $('h2', item).text()).attr('href', window.location.href);
			salkku.add_item(item, function() {
				salkku_item_anim(item, function() {
					$(this).hide();
					link.addClass('saved').removeClass('unsaved');
					update_salkku_counter();
				});
			});
		});
	});
	
	update_salkku_counter();
});




/*************************/
/*   jQuery extensions   */
/*************************/


/* Parse pseudo-attribute from element's class.
   If class="name1-value1 name2-value2", then .class_attr('name1') returns 'value1'. */
jQuery.fn.class_attr = function(attr) {
	if (this[0]) {
		var m = this[0].className.match(new RegExp(attr + '-([^ ]+)'));
		if (m && m[1]) return m[1];
	}
	return false;
}


/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);


/**
 * 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(a,b,c){if(typeof b!='undefined'){c=c||{};if(b===null){b='';c.expires=-1}var d='';if(c.expires&&(typeof c.expires=='number'||c.expires.toUTCString)){var e;if(typeof c.expires=='number'){e=new Date();e.setTime(e.getTime()+(c.expires*24*60*60*1000))}else{e=c.expires}d='; expires='+e.toUTCString()}var f=c.path?'; path='+(c.path):'';var g=c.domain?'; domain='+(c.domain):'';var h=c.secure?'; secure':'';document.cookie=[a,'=',encodeURIComponent(b),d,f,g,h].join('')}else{var j=null;if(document.cookie&&document.cookie!=''){var k=document.cookie.split(';');for(var i=0;i<k.length;i++){var l=jQuery.trim(k[i]);if(l.substring(0,a.length+1)==(a+'=')){j=decodeURIComponent(l.substring(a.length+1));break}}}return j}};


/**
 * All descendent text nodes within a node
 */
$.fn.nonLinkTextNodes = function() {
	var ret = [];
	this.contents().each( function() {
		if (this.nodeName == 'A' ||
		    this.nodeName == 'H1' ||
		    this.nodeName == 'H2' ||
		    this.nodeName == 'H3' ||
		    this.nodeName == 'H4') return true;
		var fn = arguments.callee;
		if (this.nodeType == 3) 
			ret.push( this );
		else $(this).contents().each(fn);
	});
	return $(ret);
}


/*************************/
/*      Tietosalkku      */
/*************************/

var Tietosalkku = function() {
	if (CM_TEMPLATELANG == "sv_SE")
	{
        	this.URL_LOAD = '/rorbyte/informationsmapp/ajax-map-load';
        	this.URL_UPDATE = '/rorbyte/informationsmapp/ajax-map-update';
        	this.URL_CREATE = '/rorbyte/informationsmapp/ajax-map-create';
        }
	else
	{
		this.URL_LOAD = '/kerrostalon_putkiremontti/tietosalkku/ajax-salkku-load';
		this.URL_UPDATE = '/kerrostalon_putkiremontti/tietosalkku/ajax-salkku-update';
		this.URL_CREATE = '/kerrostalon_putkiremontti/tietosalkku/ajax-salkku-create';
	}
	this.COOKIE = 'tietosalkku';
	this.items = null;
	this.id = $.cookie(this.COOKIE);
	this.queue = [];
	this.loaded = false;
}

Tietosalkku.prototype.save = function(cb) {
	var salkku = this;
	if (! this.id) this.create(function() { salkku.update(cb) });
	else this.update(cb);
}

Tietosalkku.prototype.create = function(cb) {
	var salkku = this;
	var cb = cb || function() {};
	$.post(this.URL_CREATE, { ngf_okparams: 'id=%{ngf_uniq}', ngform_on: 1, q0: '' }, function(data, status) {
		salkku.id = $.trim(data);
		$.cookie(salkku.COOKIE, salkku.id, { path: '/', expires: 180 });
		cb.call(salkku);
		salkku.ready();
	});
}

Tietosalkku.prototype.update = function(cb) {
	$.post(this.URL_UPDATE, { id: this.id, cmf_0_1: this.items.html() }, cb);
}

Tietosalkku.prototype.load = function(cb) {
	var cb = cb || function() {};
	if (! this.items) {
		this.items = $('<div />');
		var salkku = this;
		if (this.id) this.items.load(this.URL_LOAD, { random: new Date().getTime() }, function() {
			salkku.call(cb);
			salkku.ready();
		});
		else { this.call(cb); salkku.ready(); }
	} else this.call(cb);
}

Tietosalkku.prototype.call = function(cb) {
	if (this.loaded) cb.call(this);
	else this.queue.push(cb);
}

Tietosalkku.prototype.ready = function() {
	this.loaded = true;
	var cb;
	while (cb = this.queue.shift()) cb.call(this);
}

Tietosalkku.prototype.has_item = function(item, cb) {
	var salkku = this;
	this.load(function() {
		var has = salkku.items && $('#' + item.attr('id'), salkku.items).length > 0;
		if (cb) cb.call(salkku, has);
	});
}

Tietosalkku.prototype.remove_item = function(item, cb) {
	var salkku = this;
	this.load(function() {
		salkku.has_item(item, function() {
			$('#' + item.attr('id'), salkku.items).remove();
			salkku.save(cb);
		});
	});
}

Tietosalkku.prototype.add_item = function(item, cb) {
	var salkku = this;
	this.load(function() {
		salkku.has_item(item, function(has) {
			if (has) return;
			var clone = item.clone();
			$('.salkku-skip', clone).remove();
			$('.cufon-vml-canvas', clone).remove();
			$('canvas', clone).remove();
			$('.bubble', clone).remove();
			salkku.items.append(clone);
			salkku.save(cb);
		});
	});
}

Tietosalkku.prototype.item_up = function(item, cb) {
	var salkku = this;
	this.load(function() {
		var itemx = (salkku.items).find('#' + item.attr('id'));
		var prev = itemx.prev('.salkku-item');
		if (prev.length > 0) prev.before(itemx);
		salkku.save(cb);
	});
}

Tietosalkku.prototype.item_down = function(item, cb) {
	var salkku = this;
	this.load(function() {
		var itemx = (salkku.items).find('#' + item.attr('id'));
		var next = itemx.next('.salkku-item');
		if (next.length > 0) next.after(itemx);
		salkku.save(cb);
	});
}

Tietosalkku.prototype.discard = function() {
	$.cookie(this.COOKIE, null, { path: '/' });
	this.id = null;
	this.render();
}

Tietosalkku.prototype.count = function(cb) {
	var salkku = this;
	this.load(function() {
		var count = salkku.items ? salkku.items.children('.salkku-item').length : 0;
		if (cb) cb.call(salkku, count);
	});
}

Tietosalkku.prototype.render = function(container) {
	container = container || this.container;
	this.container = container;
	var salkku = this;
	if (CM_TEMPLATELANG == "sv_SE")
	{
		var back_link = 'Gå tillbaka';
	}
	else
	{
	        var back_link = 'Palaa sivulle';		
	}
	this.load(function() {
		var table = $('table', salkku.container);
		var tbody = $('<tbody />');
		salkku.items.children('.salkku-item').each(function(i) {
			var row = $('<tr />').attr('id', $(this).attr('id')).addClass(i % 2 == 0 ? 'even' : 'odd');
			row.append($('<td />').addClass('move').append(
				$('<button />').addClass('list-edit move-up').click(function() {
					salkku.item_up(row, function() { salkku.render() });
				})
			).append(
				$('<button />').addClass('list-edit move-down').click(function() {
					salkku.item_down(row, function() { salkku.render() });
				})			
			));
			row.append($('<td />').addClass('title').text($(this).attr('title')));
			row.append($('<td />').append(
				$('<a />').attr('href', $(this).attr('href') || '')
					.text(back_link)
					.addClass('read-more')
			));
			row.append($('<td />').addClass('last-child').append(
				$('<button />').addClass('list-edit remove').click(function() {
					salkku.remove_item(row, function() { salkku.render() });
				})
			));
			tbody.append(row);
		});
		$('tbody', table).remove();
		table.append(tbody);
		salkku.count(function(count) {
			salkku.container.toggle(count > 0);
			$('.no-salkku-items').toggle(count == 0);
		});
	});
}

window.salkku = new Tietosalkku();

})(jQuery);

