﻿/**
 * jQuery Templates
 *
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Written by: Stan Lemon <stanlemon@mac.com>
 *
 */
(function($){
	$.template = function(html, options) {
		return new $.template.instance(html, options);
	};
	
	$.template.instance = function(html, options) {
        if ( options && options['regx'] ) options.regx = this.regx[ options.regx ];

		this.options = $.extend({
			compile: 		false,
			regx:           this.regx.standard
		}, options || {});

		this.html = html;

		if (this.options.compile) {
			this.compile();   
		}
		this.isTemplate = true;
	};

	$.template.regx = $.template.instance.prototype.regx = {
	    jsp:        /\$\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
        ext:        /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
        jtemplates: /\{\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}\}/g
	};
	
	$.template.regx.standard = $.template.regx.jsp;
	
	$.template.helpers = $.template.instance.prototype.helpers = {
		substr : function(value, start, length){
			return String(value).substr(start, length);
		}
	};

	$.extend( $.template.instance.prototype, {
		apply: function(values) {
			if (this.options.compile) {
				return this.compiled(values);
			} else {
				var tpl = this;
				var fm = this.helpers;

				var fn = function(m, name, format, args) {
					if (format) {
						if (format.substr(0, 5) == "this."){
							return tpl.call(format.substr(5), values[name], values);
						} else {
							if (args) {
								var re = /^\s*['"](.*)["']\s*$/;
								args = args.split(',');

								for(var i = 0, len = args.length; i < len; i++) {
									args[i] = args[i].replace(re, "$1");
								}
								args = [values[name]].concat(args);
							} else {
								args = [values[name]];
							}

							return fm[format].apply(fm, args);
						}
					} else {
						return values[name] !== undefined ? values[name] : "";
					}
				};

				return this.html.replace(this.options.regx, fn);
			}
		},

		compile: function() {
			var sep = $.browser.mozilla ? "+" : ",";
			var fm = this.helpers;

			var fn = function(m, name, format, args){
				if (format) {
					args = args ? ',' + args : "";

					if (format.substr(0, 5) != "this.") {
						format = "fm." + format + '(';
					} else {
						format = 'this.call("'+ format.substr(5) + '", ';
						args = ", values";
					}
				} else {
					args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
				}
				return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
			};

			var body;

			if ($.browser.mozilla) {
				body = "this.compiled = function(values){ return '" +
					   this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.options.regx, fn) +
						"';};";
			} else {
				body = ["this.compiled = function(values){ return ['"];
				body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.options.regx, fn));
				body.push("'].join('');};");
				body = body.join('');
			}
			eval(body);
			return this;
		}
	});

	var $_old = {
	    domManip: $.fn.domManip,
	    text: $.fn.text,
	    html: $.fn.html
	};

	$.fn.domManip = function( args, table, reverse, callback ) {
		if (args[0].isTemplate) {
			args[0] = args[0].apply( args[1] );
			delete args[1];
		}

		// Call the original method
		var r = $_old.domManip.apply(this, arguments);

		return r;
	};

	$.fn.html = function( value , o ) {
	    if (value && value.isTemplate) var value = value.apply( o );

		var r = $_old.html.apply(this, [value]);

		return r;
	};
	
	$.fn.text = function( value , o ) {
	    if (value && value.isTemplate) var value = value.apply( o );

		var r = $_old.text.apply(this, [value]);

		return r;
	};

})(jQuery);


/*! Copyright (c) 2008 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * Version: 3.0.1-pre
 * 
 * Requires: 1.2.2+
 */

(function($) {
	$.event.special.mousewheel = {
		setup: function() {
			var handler = $.event.special.mousewheel.handler;
			
			if ( $.browser.mozilla )
				$(this).bind('mousemove.mousewheel', function(event) {
					$.data(this, 'mwcursorposdata', {
						pageX: event.pageX,
						pageY: event.pageY,
						clientX: event.clientX,
						clientY: event.clientY
					});
				});
		
			if ( this.addEventListener )
				this.addEventListener( ($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
			else
				this.onmousewheel = handler;
		},
		
		teardown: function() {
			var handler = $.event.special.mousewheel.handler;
			
			$(this).unbind('mousemove.mousewheel');
			
			if ( this.removeEventListener )
				this.removeEventListener( ($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
			else
				this.onmousewheel = function(){};
			
			$.removeData(this, 'mwcursorposdata');
		},
		
		handler: function(event) {
			var args = Array.prototype.slice.call( arguments, 1 );
			
			event = $.event.fix(event || window.event);
			$.extend( event, $.data(this, 'mwcursorposdata') || {} );
			var delta = 0, returnValue = true;
			
			if ( event.wheelDelta ) delta = event.wheelDelta/120;
			if ( event.detail     ) delta = -event.detail/3;
			if ( $.browser.opera  ) delta = -event.wheelDelta;
			
			event.data  = event.data || {};
			event.type  = "mousewheel";
			
			args.unshift(delta);
			args.unshift(event);

			return $.event.handle.apply(this, args);
		}
	};

	$.fn.extend({
		mousewheel: function(fn) {
			return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
		},
		
		unmousewheel: function(fn) {
			return this.unbind("mousewheel", fn);
		}
	});

})(jQuery);

// form label
(function($) {
	$.fn.label = function(options) {
		var default_settings = {
			clearLabels : true
		};
		var settings = $.extend(default_settings, options);
		
		return this.each(function(){
			var elm = $(this);
			if($(this).val().length > 0) {
				$.data(elm, 'default', $(this).val());
				elm.focus(function(){
					if($(this).val() == $.data(elm, 'default')) {
						$(this).val('');
					}
				}).blur(function(){
					if($(this).val() == '') {
						$(this).val($.data(elm, 'default'));
					}
				});

				if(settings.clearLabels) {
					$(this.form).submit(function(){
						if($(this).val() == $.data(elm, 'default')) {
							$(this).val('');
						}
					});
				}
			}
		});
	}
})(jQuery);

(function($) {
	$.PhosSwoosh = function(obj, o) {
		this.o = o;
		
		this.itemxml = null;
		this.pageIndex = 1;
		this.totalPages = 0;
		this.totalItemCount = 0;
		this.wrapperWidth = 0;
		this.isPageing = false;
		
		this.wrapper = $(obj);
		this.prevBtn = $(o.prevBtn);
		this.nextBtn = $(o.nextBtn);
		this.contentPanes = null;
		
		this.buildListItem = o.buildItem || this.buildItem;
		
		this.init();
	}

	$.PhosSwoosh.prototype.extend = jQuery.extend;

	$.PhosSwoosh.prototype.extend({
		init: function() {
			var self = this;
			$.ajax({
				type: "GET",
				url: '/index.php?mact=CGFeedMaker,cntnt01,default,0&cntnt01feed='+self.o.category+'&cntnt01showtemplate=false',
				async: false,
				dataType: "xml",
				success: function(data, textStatus) { self.itemxml = data; }
			});
			this.totalItemCount = $('item', this.itemxml).length;
			this.totalPages = parseInt( this.totalItemCount / this.o.items );
			if ( this.totalItemCount % this.o.items > 0 ) this.totalPages++;
			
			//GUI setup
			this.wrapperWidth = this.wrapper.width();
			this.wrapper.css({position: 'relative', height: this.wrapper.height(), width: '100%'});
			
			this.contentPanes = $([]).add( this.wrapper.wrapInner( $('<div>') ).find('>div') ).add( $('<div>').hide().appendTo( this.wrapper ) );
			this.contentPanes.css({ position: 'absolute', top: 0 }).addClass('pane');
			
			this.prevBtn.click(function() {
				if ( !self.isPageing ) self.goToPage( self.pageIndex-1 );
				return false;
			});
			this.nextBtn.click(function() {
				if ( !self.isPageing ) self.goToPage( self.pageIndex+1 );
				return false;
			});
			
			this.wrapper.mousewheel(function(event, delta) {
				if ( delta > -1 ) {
					if ( self.pageIndex > 1 )
						if ( !self.isPageing ) self.goToPage( self.pageIndex-1 );
				} else {
					if ( self.pageIndex < self.totalPages )
						if ( !self.isPageing ) self.goToPage( self.pageIndex+1 );
				}
				return false;
			});
		},
		
		goToPage: function( index ) {
			var self = this;
			
			self.isPageing = true;
			
			if ( index == 1 ) { this.prevBtn.fadeOut(); } else { this.prevBtn.fadeIn(); }
			if ( index == this.totalPages ) { this.nextBtn.fadeOut(); } else { this.nextBtn.fadeIn(); }
			
			var startIndex = (index-1) * this.o.items;
			var endIndex = startIndex + this.o.items;
			var visContentPane = this.contentPanes.filter(':visible');
			var hidContentPane = this.contentPanes.filter(':hidden');
			hidContentPane.empty();
			$('item', this.itemxml).slice( startIndex, endIndex ).each( function() {
				hidContentPane.append( self.buildListItem.apply( self, [this] ) );
			});
			
			//visContentPane.fadeOut('fast', function() { hidContentPane.fadeIn('fast'); }); //pre design-tratt
			
			//after design-tratt
			var hidInitLeft, visLeftTo, hidLeftTo;
			if ( index > this.pageIndex ) {
				hidInitLeft = (this.wrapperWidth/2);
				visLeftTo = -(this.wrapperWidth/3)
			} else {
				hidInitLeft = -(this.wrapperWidth/2);
				visLeftTo = (this.wrapperWidth/3)
			}
			
			hidContentPane.show().css({"left": hidInitLeft, opacity: 0 });
			
			visContentPane.animate( { left: visLeftTo, opacity: 0 }, { queue: false, duration: 250, complete: function() {
				visContentPane.hide();
			} } );
			hidContentPane.animate( { left: 0, opacity: 1 }, { queue: false, duration: 250, complete: function() {
				self.pageIndex = index;
				self.isPageing = false;
				hidContentPane.css("filter", "");
				addthis.button('.addthis_button');
			} } );
		},
		
		buildItem: function( node ) {
			var item = $('<div>');
			item.addClass('item clearfix');
			item.append($('<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;pub=xa-4b0e9fd920fa4186"><img src="http://s7.addthis.com/static/btn/v2/lg-share-sv.gif" width="125" height="16" border="0" alt="Share" /></a>'));
			item.append( $('<div>').addClass('frame2 lstimg').append( $('image', node).text() ) );
			item.append( $('<div>').addClass('content').append( $('description', node).text() ) );
			
			return item;
		}
	});

	$.fn.PhosSwoosh = function(o) {
		return this.each(function() {
			new $.PhosSwoosh(this, o);
		});
	}
})(jQuery);


var GUI = (function() {
	function initGUI() {
		var page = $('body').attr('class');
		if ( page ) {
			if ( sections[page] ) sections[page].apply(this, []);
		}
	}
	
	var sections = {
		news: function() {
			$('#centerCol.newslist').PhosSwoosh({
				category: 'news',
				items: 4,
				prevBtn: '#navPrev',
				nextBtn: '#navNext',
				buildItem: function( node ) {
					var template = $.template( $('#newsItemTemplate').html().replace( /&lt;/g, '<').replace( /&gt;/g, '>') );
					return template.apply( {
						image: $('image', node).text(),
						date: $('pubDate', node).text(),
						title: $('title', node).text(),
						description: $('description', node).text()
					});
				}
			});
		},
		"case": function() {
			$('#centerCol.caselist').PhosSwoosh({
				category: 'cases',
				items: 3,
				prevBtn: '#navPrev',
				nextBtn: '#navNext',
				buildItem: function( node ) {
					var template = $.template( $('#caseItemTemplate').html().replace( /&lt;/g, '<').replace( /&gt;/g, '>') );
					return template.apply( {
						image: $('image', node).text(),
						description: $('description', node).text()
					});
				}
			});
		},
		contact: function() {
			var contact = $('#contactWrapper');
			var contactField = $('#contactForm #to');
			$('p>a', contact).click( function() {
				contactField.val( $(this).next('i').text().replace(/-\|p\|-/g, '.').replace(/\|_kb_\|/g, '@') );
				return false;
			});
			
			var form = $('form', contact);
			form.submit( function() {
				var errorno = false;
				var error = 'Du behöver fylla i:';

				if($('#name', form).val() == '' || $('#name', form).val() == 'Your name') {
					error = error + '\nDitt namn.';
					errorno = true;
				} if($('#subject', form).val() == '' || $('#subject', form).val() == 'Subject') {
					error = error + '\nÄmnesraden.';
					errorno = true;
				}
				if($('#email', form).val() == '' || $('#email', form).val() == 'E-mail') {
					error = error + '\nDin e-post.';
					errorno = true;
				}
				if($('#message', form).val() == '' || $('#message', form).val() == 'Message') {
					error = error + '\nMeddelandet.';
					errorno = true;
				}
				if(errorno) alert(error);
				return !errorno;
			});
			$('input:not(#to),textarea', form).label();
		}
	}
	
	return {
		init: initGUI
	}
})();
$( document ).ready( function() {
	GUI.init();
});